Programming Theory

Programming theory deals with the design, implementation, analysis, characterization, and classification of programming languages and their individual features, along with introductory programming concepts like program structure, variable declaration and conditional and looping constructs. Sub-disciplines include the formal semantics of programming languages, type theory, program analysis and transformation, comparative programming language analysis, metaprogramming, domain-specific languages, compiler construction and run-time systems.

Share tech news, updates, or what's on your mind.

Sign up to Post

import org.json.simple.JSONObject;

class JsonEncodeDemo {

   public static void main(String[] args){
      JSONObject obj = new JSONObject();

      obj.put("name", "foo");
      obj.put("num", new Integer(100));
      obj.put("balance", new Double(1000.21));
      obj.put("is_vip", new Boolean(true));

      System.out.print(obj);
   }
}
On compiling and executing the above program the following result will be generated −

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Open in new window


what above example doing
is it encoding jsonobject to java object?
i see output also seems like json to me?
Following is another example that shows a JSON object streaming using Java JSONObject −

import org.json.simple.JSONObject;

class JsonEncodeDemo {

   public static void main(String[] args){
	
      JSONObject obj = new JSONObject();

      obj.put("name","foo");
      obj.put("num",new Integer(100));
      obj.put("balance",new Double(1000.21));
      obj.put("is_vip",new Boolean(true));

      StringWriter out = new StringWriter();
      obj.writeJSONString(out);
      
      String jsonText = out.toString();
      System.out.print(jsonText);
   }
}
On compiling and executing the above program, the following result is generated −

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Open in new window


how above one is differen from first one?
0
New feature and membership benefit!
LVL 11
New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Consider algos/softwares that take keywords in one document and match them (possibly a kind of set intersection) with keywords in N other documents, possibly producing a match ranking.

a. Is there a specific name for this?
b. Are there implementations in Java and PHP?

Example use cases would be
  • patients submitting a list of symptoms and then software looking for matches against known conditions
  • applicants submitting skillsets and looking for potential job matches
  • dating websites
0
See this code:
$piece1 = $test;
$piece2 = "";
$piece3 = "";
$ln = strlen($test);
if ($ln > 84) {

	$arrayWords = explode(' ', $test);

// Max size of each line
	$maxLineLength = 84;

// Auxiliar counters, foreach will use them
	$currentLength = 0;
	$index = 0;

	foreach ($arrayWords as $word) {
    // +1 because the word will receive back the space in the end that it loses in explode()
		$wordLength = strlen($word) + 1;

		if (($currentLength + $wordLength) <= $maxLineLength) {
			$arrayOutput[$index] .= $word . ' ';

			$currentLength += $wordLength;
		} else {
			$index += 1;

			$currentLength = $wordLength;

			$arrayOutput[$index] = $word . ' ';
		}
	}
	$piece1 = $arrayOutput[0];
	$piece2 = $arrayOutput[1];
	$piece3 = $arrayOutput[2];
}	

Open in new window


This works perfectly, except I need a variation where I can limit the FIRST line ($arrayOutput[0]) to 84 & the subsequent lines to 94. See attached image for visual of this need. The text is printed using a pdf generator on an existing form image (with the word Remarks & the lines.)

How can I do this?

Thank you
Capture.JPG
0
hi,
I was writing below example
https://www.youtube.com/watch?v=ShO_Z64sGwI&list=PLZM-6wiKGRfGmXzuR8uX3UsE8g91K6Vp1&index=5

package com.gp.mockito;

import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import static org.mockito.Mockito.*;

public class CalculatorServiceTest {

	CalculatorService calService;
	
	@Before
	public void setup(){
		ICalculator cal_mock = mock(ICalculator.class);
		when(cal_mock.add(2, 4)).thenReturn(6);
		calService=new CalculatorService();
		//calService.setCal(cal_mock);
		
		
	}
	@Test
	public void testAddNumbers(){
		Assert.assertEquals(6, calService.addTwoNumbers(2,4));
	}
}

Open in new window

package com.gp.mockito;

public class CalculatorService {
ICalculator cal;
public ICalculator getCal() {
	return cal;
}
public void setCal(ICalculator cal) {
	this.cal = cal;
}
public int addTwoNumbers(int x, int y){
	return cal.add(x, y);
}
}

Open in new window

package com.gp.mockito;

public interface ICalculator {
public int add(int x,int y);
}

Open in new window

why we need setter for calservice implementation class.

why are they setting interface mock object to the calservice object

observerd one example here
https://www.youtube.com/watch?v=DyuWgBHfxNQ

i do not see any setter here though?
1
hi how to see post man response. i installed post man now instead of advance res client
postMan401.png
postMan200.png
0
Bloom Filter
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data definitely won't be found. Read on to find out more...
5
By mistake i removed the jre default from eclipse java project instead of updating jre with jdk as beow

Here is the complete sequence in Eclipse Luna:
Right click your project > properties.
Select “Java Build Path” on left, then “JRE System Library”, click Edit…
Select "Workspace Default JRE"
Click "Installed JREs"
If you see JRE you want in the list select it (selecting a JDK is OK too)

how to add jdk 1.8
please advise
0
hi,

i am importing existing project into eclipse as non maven project. Everytime i import new project i see bunch of errors. when i go to error and say fix project set up and give jdk 1.8 then issues resolves. why i have to do this everytime to every new project. can i teach eclipse some how to rememebr so that i do not have to give this again and agian. please advise
errorJDK.png
errorJDK2.png
0
hi,

If i do Control+Alt+H on eclipse java class method say methodA() it does show call hierarchy  of who is(lets say methodB()) calling that method (methodA())

If i do control Alt H on methodB() it shows methodC() which is calling methodC()

my question is how to find by selecting methodC() that methodB() is its parent method and methodA() its grand parent method.

i mean to debug upward as well not just downward using call hierarchy.
is there is a way i can do both ways?

please advise
0
Hello, I have the following code while practising for loop but what I don't understand is, why we have a loop inside a loop?? what's the deal here?

<?php

// Create a script to construct the following pattern, using a nested for loop

//* 
//* * 
//* * * 
//* * * * 
//* * * * * 
//* * * * * 
//* * * * 
//* * * 
//* * 
//* 

$n=5;
for($i=1; $i<=$n; $i++)
{
for($j=1; $j<=$i; $j++)
{
echo " * ";
}
echo "<br>";
}
for($i=$n; $i>=1; $i--)
{
for($j=1; $j<=$i; $j++)
{
echo " * ";
}
echo "<br>";
}

?>

Open in new window

0
Free Tool: ZipGrep
LVL 11
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Hello,

I am looking to create a web-based application that, at a later date, may have a supporting windows program and mobile app (but not for phase 1).

I was considering the language to write the code in and which one would be best and was looking for your advice. These were the high-level requirements.

Will utilize a back-end database.
Will need to create PDFs based on templates and information held in the database (i.e. like an order receipt).
Will need to create PowerPoint, Word and Excel documents based on templates and information held in the database (i.e. create a copy of the order in PowerPoint format).
Allow the user to view information in tables that can be edited directly in the table with a double click or similar.
Ability for the system to generate and send emails
The ability for the system to generate an email in Outlook and save in the user's draft folder.

It would be great to get your thoughts on this given the high-level requirements.
0
I love the notion that my REST web service could deliver a complete UI to the client, which that the client could then display complete functionality inside a window, on their own site. What's kind of client/server relationship is this?

Is this what Code-On-Demand does?

Does it return HTML/JavaScript/CSS?

What kind of control is needed on the client to receive this? An iframe?

What kind of problems might there be with this kind of interaction?
0
Hi,

I ran below example on tomcat 9

https://www.mkyong.com/webservices/jax-rs/jersey-hello-world-example/


how to run tomcat 7 as well.

can i keep same ports for tomcat 7 and tomcat 9.

can i start both servers from eclipse same time?


how to keep port nubet more common ones?
please advise
tomcat_11.png
0
I have supported various web services over many years but need to clearly what is meant by the term "web API."

Please give me a short description so I can judge if I have worked with this or not.

Thanks
0
What technologies are best suited for the highest performance web services to handle the heaviest loads? Thousands (even millions) of transactions per second?

I know that Node.js can handle thousand(s) sessions on a single thread. And I do not know of any other technology which handle more than one session per thread. Am I right about that? Are there others that can do this also?

What about real-time programming as it relates to web-services. Is there such a thing?

And how about a few general words about hardware deployment? Having a central API call which distributes calls to hundreds of more specialized web servers? What about Caching for successive related calls?

And what about Machine Learning? Can algorithms be optimized by existing Machine Learning algorithms that reduce the average response times of the most heavily load web service?

Thanks.
0
My WPF project has a MainWindow. The MainWindow has an "Open File" button on the toolbar. The "Open FIle" button when clicked sends an event to my VIewModel saying, "Hey, the user clicked the "Open File" button.

My ViewModel responds with "I need to display an Open File Dialog." It displays the Win32 Open File Dialog, and subscribes to that dialog's "OK" button click event.

User selects a file and clicks "OK".

My ViewModel responds to the "OK" click event, gets the file name from the Open File Dialog, and passes it to the Model, telling the Model, "Hey, the user wants to open this file."

Now I'm thinking of testability. I don't have Visual Studio Enterprise. I should be able to test my ViewModel without it actually displaying an Open File Dialog.

I had a situation where the ViewModel forgot to subscribe to the Open File Dialog's "OK" button click event. I now want to be able to test for this in my unit tests.

And I'm not sure how to do that.

(I'm also not sure if my View (MainWindow) should send a click event "User clicked the Open File icon", or if my View should send a Command "User wants to open a file." I'm thinking Command, since then the VIew can send the same Command when the user clicks the menu option for File Open. Otherwise I have my ViewModel handling the menu File Open click event separately. Are Commands preferable?)
0
http://codingbat.com/prob/p117630
public Map<String, Integer> wordCount(String[] strings) {
  Map<String, Integer> map=new HashMap<String, Integer>();
  for(String str: strings){
    int i=0;
    if(str.equals(str)){
      i++;
    }
    map.put(str,i);
  }
  return map;
}

Open in new window

Expected      Run            
wordCount(["a", "b", "a", "c", "b"]) → {"a": 2, "b": 2, "c": 1}      {"a": 1, "b": 1, "c": 1}      X      
wordCount(["c", "b", "a"]) → {"a": 1, "b": 1, "c": 1}      {"a": 1, "b": 1, "c": 1}      OK      
wordCount(["c", "c", "c", "c"]) → {"c": 4}      {"c": 1}      X      
wordCount([]) → {}      {}      OK      
wordCount(["this", "and", "this", ""]) → {"": 1, "and": 1, "this": 2}      {"": 1, "and": 1, "this": 1}      X      
wordCount(["x", "y", "x", "Y", "X"]) → {"x": 2, "X": 1, "y": 1, "Y": 1}      {"x": 1, "X": 1, "y": 1, "Y": 1}      X      
wordCount(["123", "0", "123", "1"]) → {"0": 1, "1": 1, "123": 2}      {"0": 1, "1": 1, "123": 1}      X      
wordCount(["d", "a", "e", "d", "a", "d", "b", "b", "z", "a", "a", "b", "z", "x", "b", "f", "x", "two", "b", "one", "two"]) → {"a": 4, "b": 5, "d": 3, "e": 1, "f": 1, "one": 1, "x": 2, "z": 2, "two": 2}      {"a": 1, "b": 1, "d": 1, "e": 1, "f": 1, "one": 1, "x": 1, "z": 1, "two": 1}      X      
wordCount(["apple", "banana", "apple", "apple", "tea", "coffee", "banana"]) → {"banana": 2, "apple": 3, "tea": 1, "coffee": 1}      {"banana": 1, "apple": 1, "tea": 1, "coffee": 1}      X      
other tests
X      

how to fix and improve my code for above challenge?
please advise
0
when i am trying below challenge
http://codingbat.com/prob/p115012

as below
public Map<String, String> mapAB3(Map<String, String> map) {
  if(map.get("a")!=null ){
    
    map.put("b",map.get("a"));
  }
  
   if(map.get("b")!=null){
     map.put("a",map.get("b"));
   }
   return map;
}

Open in new window


public Map<String, String> mapAB3(Map<String, String> map) {
  if(map.get("a")!=null ){
   
    map.put("b",map.get("a"));
  }
 
   if(map.get("b")!=null){
     map.put("a",map.get("b"));
   }
   return map;
}
I am failing one edge case. how to improve my code and fix it. please advise
0
Hi,

I like to see some .class files generated in EAR file. Is there any java free decompiler to do this within eclipse and outside eclipse as well. please advise
0
Vote for the Most Valuable Expert
LVL 7
Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Hi,


what is difference between below 3 lines




 map.put("ab", map.get("a").concat(map.get("b")));



map.put("ab", map.get("a")+ map.get("b"));

map.put("ab", "null" + map.get("b"));


I passed all tests
http://codingbat.com/prob/p107259
Looking for ways to improve my code and also avoid Null pointer exceptions


Expected	Run		
mapAB({"a": "Hi", "b": "There"}) → {"a": "Hi", "ab": "HiThere", "b": "There"}	{"a": "Hi", "ab": "HiThere", "b": "There"}	OK	
mapAB({"a": "Hi"}) → {"a": "Hi"}	{"a": "Hi"}	OK	
mapAB({"b": "There"}) → {"b": "There"}	{"b": "There"}	OK	
mapAB({"c": "meh"}) → {"c": "meh"}	{"c": "meh"}	OK	
mapAB({"a": "aaa", "ab": "nope", "b": "bbb", "c": "ccc"}) → {"a": "aaa", "ab": "aaabbb", "b": "bbb", "c": "ccc"}	{"a": "aaa", "ab": "aaabbb", "b": "bbb", "c": "ccc"}	OK	
mapAB({"ab": "nope", "b": "bbb", "c": "ccc"}) → {"ab": "nope", "b": "bbb", "c": "ccc"}	{"ab": "nope", "b": "bbb", "c": "ccc"}	OK

Open in new window


please advise
0
Hi,

public Map<String, String> topping2(Map<String, String> map) {
  if(map.get("ice cream")!=null){
    map.put("yogurt", map.get("ice cream"));
  }
  if(map.get("spinach")!=null){
    map.put("nuts", map.get("spinach"));
  }
  else{
    map=map;
  }
  return map;
}

Open in new window

how above code different from below code

public Map<String, String> topping2(Map<String, String> map) {
//public Map < String, String > topping1(Map < String, String > map) {
   // map.put("spinach", "nuts");
    if (map.containsKey("spinach")) {
        map.put("spinach", "nuts");
   }
      if (map.containsKey("ice cream")) {
        map.put("yogurt", map.get("ice cream"));
       // map.put("ice cream", map.get("ice cream"));

   }
    return map;
}

Open in new window


my above first code fails below test
http://codingbat.com/prob/p196458

Expected      Run            
topping2({"ice cream": "cherry"}) → {"yogurt": "cherry", "ice cream": "cherry"}      {"yogurt": "cherry", "ice cream": "cherry"}      OK      
topping2({"spinach": "dirt", "ice cream": "cherry"}) → {"yogurt": "cherry", "spinach": "nuts", "ice cream": "cherry"}      {"yogurt": "cherry", "spinach": "dirt", "ice cream": "cherry", "nuts": "dirt"}      X      
topping2({"yogurt": "salt"}) → {"yogurt": "salt"}      {"yogurt": "salt"}      OK      
topping2({"yogurt": "salt", "bread": "butter"}) → {"yogurt": "salt", "bread": "butter"}      {"yogurt": "salt", "bread": "butter"}      OK      
topping2({}) → {}      {}      OK      
topping2({"ice cream": "air", "salad": "oil"}) → {"yogurt": "air", "ice cream": "air", "salad": "oil"}      {"yogurt": "air", "ice cream": "air", "salad": "oil"}      OK      
0
Hi,

How below solution is different from

public Map<String, String> topping3(Map<String, String> map) {
 // Map<String, String> map=null;
  if(map.get("potato")!=null){
    map.put("fries",map.get("potato"));
  }
    if(map.get("salad")!=null){
    map.put("spinatch",map.get("salad"));
  }
  else
  map=map;
  return map;
  
}

Open in new window


below solution

public Map < String, String > topping3(Map < String, String > map) {
   // map.put("bread", "butter");
    if (map.containsKey("potato")) {
        map.put("fries", map.get("potato"));

    }
     if (map.containsKey("salad")) {
        map.put("spinach", map.get("salad"));

    }
    return map;
}

Open in new window



please advise.

First one does not pass all tests from
http://codingbat.com/prob/p128461
Expected      Run            
topping3({"potato": "ketchup"}) → {"potato": "ketchup", "fries": "ketchup"}      {"potato": "ketchup", "fries": "ketchup"}      OK      
topping3({"potato": "butter"}) → {"potato": "butter", "fries": "butter"}      {"potato": "butter", "fries": "butter"}      OK      
topping3({"salad": "oil", "potato": "ketchup"}) → {"spinach": "oil", "salad": "oil", "potato": "ketchup", "fries": "ketchup"}      {"salad": "oil", "spinatch": "oil", "potato": "ketchup", "fries": "ketchup"} missing: "spinach": "oil"      X      
topping3({"toast": "butter", "salad": "oil", "potato": "ketchup"}) → {"toast": "butter", "spinach": "oil", "salad": "oil", "potato": "ketchup", "fries": "ketchup"}      {"toast": "butter", "salad": "oil", "spinatch": "oil", "potato": "ketchup", "fries": "ketchup"} missing: "spinach": "oil"      X      
topping3({}) → {}      {}      OK      
topping3({"salad": "pepper", "fries": "salt"}) → {"spinach": "pepper", "salad": "pepper", "fries": "salt"}      {"salad": "pepper", "spinatch": "pepper", "fries": "salt"} missing: "spinach": "pepper"      X      
other tests
OK
0
I seek a list of 20 most important design patterns in computing today.

I am a C#.NET Full Stack developer, so that may bias which patters are the top 20 for me.

I want to make myself a faster programmer and able to code more on my feet under pressure. And having tried and true patterns on the top of your mind, will help.

Thanks.
0
import java.util.*;
import java.util.stream.*;
public class X {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("xxax", "xbxbx", "xxcx", "zzz");
		System.out.println(noX(list));
	}
	public static List<String> noX(List<String> strings) {
		return strings.stream().map(s -> s.replaceAll("x","")).collect(Collectors.toList());
    }	
}

Open in new window

in above program what are Collectors , stream, collect methods. And why map is used in this lamda functional examples
0
http://codingbat.com/prob/p128270
public int[] front11(int[] a, int[] b) {
 
  if (a.length==0) return new int[]{b[0]};
  if (b.length==0) return new int[]{a[0]};
   if ((a.length==0) && (b.length==0)) return new int[]{};
  return new int[]{a[0],b[0]};
}





public int[] front11(int[] a, int[] b) {
    if ((a.length==0) && (b.length==0)) return new int[]{};
  if (a.length==0) return new int[]{b[0]};
  if (b.length==0) return new int[]{a[0]};

  return new int[]{a[0],b[0]};
}




why first one fails below test with ArrayIndexOutOfBoundsException
Expected	Run		
front11([1, 2, 3], [7, 9, 8]) → [1, 7]	[1, 7]	OK	
front11([1], [2]) → [1, 2]	[1, 2]	OK	
front11([1, 7], []) → [1]	[1]	OK	
front11([], [2, 8]) → [2]	[2]	OK	
front11([], []) → []	ArrayIndexOutOfBoundsException: 0 (line:3)	X	
front11([3], [1, 4, 1, 9]) → [3, 1]	[3, 1]	OK	
front11([1, 4, 1, 9], []) → [1]	[1]	OK	
other tests
OK	
Correct for more than half the tests

Your progress graph for this problem

Open in new window


please advise
0

Programming Theory

Programming theory deals with the design, implementation, analysis, characterization, and classification of programming languages and their individual features, along with introductory programming concepts like program structure, variable declaration and conditional and looping constructs. Sub-disciplines include the formal semantics of programming languages, type theory, program analysis and transformation, comparative programming language analysis, metaprogramming, domain-specific languages, compiler construction and run-time systems.