text:
Q: Java.lang.NullPointerExpception error in code I'm trying to get this code to run and make an image with a darkened figure. However i continue to get this Run-time error:
java.lang.NullPointerException
    at java.lang.String.<init>(Unknown Source)
    at SimplePicture.<init>(SimplePicture.java:96)
    at SimplePicture.explore(SimplePicture.java:364)
    at Prob04Runner.run(Prob04.java:50)
    at Prob04.main(Prob04.java:8)

My Null Values are necessary for the code.
I don't understand what I'm doing wrong, here is the code and thank you:
import java.awt.Color;
public class Prob04{
  public static void main(String[] args){
    Prob04Runner obj = new Prob04Runner();
    obj.run();
  }//end main
}//end class Prob04
//======================================================//

class Prob04Runner{

  public Prob04Runner(){//constructor
    System.out.println("Display your name here.");
  }//end constructor
  //----------------------------------------------------//

  public void run(){

    Picture skater = new Picture("Prob04a.bmp");
    skater.explore();
    skater = crop(skater,6,59,392,293);

    Picture hole = new Picture("Prob04b.bmp");
    hole.explore();
    hole = crop(hole,6,59,392,293);

    Picture snowScene = new Picture("Prob04c.jpg");
    snowScene.explore();
    snowScene = crop(snowScene,6,59,392,293);

    //Make all the pixels darker in the snow scene except
    // for those in the location of the hole. Make them
    // brighter.
    darkenBackground(hole,snowScene);

    //Apply a red tint to the skater
    redTint(skater);

    //Draw the skater on the snowScene.
    greenScreenDraw(skater,snowScene,0,0);

    //Display students name on the final output and
    // display it.
    snowScene.addMessage("Display your name here.",10,15);

    snowScene.explore();
    System.out.println(snowScene);

  }//end run method
  //----------------------------------------------------//

  //Assumes the source has a pure green background.
  // Applies a red tint to every pixel that is not pure
  // green.
  private void redTint(Picture pic){
    Pixel[] pixels = pic.getPixels();
    Color color = null;
    int red = 0;
    int green = 0;
    int blue = 0;
    for(int cnt = 0;cnt < pixels.length;cnt++){
      color = pixels[cnt].getColor();
      //Apply a red tint to all non-green pixels
      if(!(color.equals(Color.GREEN))){
        //Increase the value of the red component
        red = color.getRed();
        if(red*1.25 < 255){
          red = (int)(red * 1.25);
        }else{
          red = 255;
        }//end else
        //Decrease the value of blue and green
        green = (int)(color.getGreen()*0.8);
        blue = (int)(color.getBlue()*0.8);

        //Apply the new color to the pixel.
        pixels[cnt].setColor(new Color(red,green,blue));
      }//end if
    }//end for loop
  }//end redTint
  //----------------------------------------------------//

  //Assumes the pattern image has a pure green background.
  // Assumes that the pattern and the destination have the
  // same dimensions. Darkens every pixel in the
  // destination that is at the location of a green pixel
  // in the pattern. Applies a red tint to every pixel
  // in the destination that is at the location of a
  // non-green pixel in the pattern
  private void darkenBackground(
                           Picture pattern,
                           Picture dest){

    Pixel[] patternPixels = pattern.getPixels();
    Pixel[] destPixels = dest.getPixels();
    Color color = null;
    int red = 0;
    int green = 0;
    int blue = 0;

    for(int cnt = 0;cnt < patternPixels.length;cnt++){
      color = patternPixels[cnt].getColor();
      if(color.equals(Color.GREEN)){
        //Darken corresponding pixel in the destination.
        color = destPixels[cnt].getColor();
        destPixels[cnt].setColor(color.darker());
      }else{
        //Apply a red tint to the corresponding pixel in
        // the destination.
        color = destPixels[cnt].getColor();
        red = color.getRed();
        if(red*1.25 < 255){
          red = (int)(red * 1.25);
        }else{
          red = 255;
        }//end else
        green = (int)(color.getGreen() * 0.8);
        blue = (int)(color.getBlue() * 0.8);
        destPixels[cnt].setColor(new Color(red,green,blue));
      }//end else
    }//end for loop
  }//end darkenBackground

  private void greenScreenDraw(
                           Picture source,
                           Picture dest,
                           //Place the upper-left corner
                           // of the source image at the
                           // following location in the
                           // destination image.
                           int destX,
                           int destY){
    int width = source.getWidth();
    int height = source.getHeight();
    Pixel pixel = null;
    Color color = null;

    for(int row = 0;row < height;row++){
      for(int col = 0;col < width;col++){
        color = source.getPixel(col,row).getColor();
        if(!(color.equals(Color.GREEN))){
          pixel = dest.getPixel(destX + col,destY + row);
          pixel.setColor(color);
        }//end if
      }//end inner loop
    }//end outer loop

  }//end greenScreenDraw
  //----------------------------------------------------//

  //Crops a Picture object to the given width and height
  // with the upper-left corner located at startCol and
  // startRow.
  private Picture crop(Picture pic,int startCol,
                                   int startRow,
                                   int width,
                                   int height){
    Picture output = new Picture(width,height);

    int colOut = 0;
    int rowOut = 0;
    int col = 0;
    int row = 0;
    Pixel pixel = null;
    Color color = null;
    for(col = startCol;col < startCol+width;col++){
      for(row = startRow;row < startRow+height;row++){
        color = pic.getPixel(col,row).getColor();
        pixel = output.getPixel(colOut,rowOut);
        pixel.setColor(color);
        rowOut++;
      }//end inner loop
      rowOut = 0;
      colOut++;
    }//end outer loop
    return output;
  }//end crop

}//end class Prob04Runner

A: You are probably calling a constructor of String with an argument null which causes the NullPointerException
Usually it is not necessary to call a constructor of String. Just assign it like String x = y. String x = new String(y) is not necessary.
Of course, you have still to find out why your String is null.
edit: If your String needs to be null, don't call the constructor.
For more details, please add the source of the class SimplePicture.


text:
Q: DevicePixelRatio doesn't match expectations I have monitor with native resolution 3072 width and 1920 height of physical pixels. However I use scaled version (1792 x 1120). I have created a simple site containing div styled with height: 1120px;. Opening site in full screen mode without any browser's headers covers my screen in exactly 100%. As MDN states:

The devicePixelRatio of Window interface returns the ratio of the
resolution in physical pixels to the resolution in CSS pixels for the
current display device.

So I looked at devTools console and I see that for me window.devicePixelRatio = 2.
And now I wonder if my devicePixelRatio shouldn't be equal 1920/1120 instead of 2? If it really is 2 then my native height resolution should be 2240 physical pixels.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compilation fails for Generic class with Generic Interface To my understanding following code should run without any compilation error.
However, when I run this program I am getting following compilation error.

The member type B.D cannot be qualified with a parameterized type,
  since it is static. Remove arguments from qualifying type B

class B<X> {
    interface C {
    }

    interface D<Y> {
    }
}

class Test {
     // compilation fails here
    B<String>.D<String>[] arr = new B<String>.D<String>[10];
}

Please help me understand this behavior.

A: In a way similar to an inner static class, a nested interface does not have an association to an instance of its outer class, only to the class itself. All static members are shared among all instances of B, regardless of B's type parameter. Consider:
class B<T> {
    public static int shared = 0;
}

Variable shared is the same in B<String>, B<Integer>, B<Object> and so on. An attempt to access it on a parameterized B leads to a compile error:
int copy = B<String>.shared; // <<== Does not compile

Hence, type parameter of B has no effect on the declaration of arr, so Java wants you to remove it:
B.D<String>[] arr = new B.D[10];

A: First of all, you can not create arrays of concrete parametrized types. Example:
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal

does not work. See here for details.
But it looks like the compiler is giving you a different, less helpful error message here because it first stumbles over the fact that nested interfaces are similar to static inner classes.
So, the only thing that you can do is: ignore the generic type on the rhs of the assignment:
B.D<String>[] arr = new B.D[10];

which of course leads to type safety warnings - and makes the whole idea of having that inner interface being generic somehow obsolete.
So the real answer is probably: generics and arrays do not go well together in Java - avoid using them in the first place. And don't be surprised that making things more complicated by bringing in interface nesting results in even less of "nice user experience".

A: Inner interfaces are always static (unlike classes). So parameter String for B make no sense in definition new B<String>.D<String>.


text:
Q: Prologs returns in haskell I'm rewritting my Prolog program in Haskell and i have small problem, how can i do something like that
myFunc(Field, Acc, Acc) :-
    % some "ending" condition
    !.
myFunc(Field, Acc, Result) :-
    nextField(Field, Field2),
    test1(Field2,...),
    myFunc(Field2, Acc, Result).
myFunc(Field, Acc, Result) :-
    nextField(Field, Field2),
    test2(Ak, (X1, Y1)),
    myFunc(Field2, [Field2|Acc], Result).

in Haskell? Code above is checking some condition and recursivly calls itself so in the end i get list of specific fields. The whole point is that if some condition (test1 or test2) fails, it is returning to the last point it could make other choice and does it. How do i implement something like that in Haskell?

A: To model Prolog computations as expressively in Haskell, you need a backtracking monad. This is trivially done using the LogicT monad. Your example as it stands translates to the following:
import Control.Monad.Logic

myFunc :: Int -> [Int] -> Logic [Int]
myFunc field acc = ifte (exitCond field acc) (\_-> return acc) $
    (do f <- nextField field
        guard $ test1 f
        myFunc f acc)
    `mplus`
    (do f <- nextField field
        guard $ test2 f
        myFunc f (f:acc))

Assuming the following implementations for the functions and predicates:
nextField i = return (i+1)
test1 f = f < 10
test2 f = f < 20
exitCond f a = guard (f > 15)

You use mplus to combine to Logic computations so that if one fails it backtracks and tries the other one. ifte is just a soft cut (there's no hard cut in logict, although I believe it's trivial to implement since logict is based on continuations) to exit when the exiting condition is true. You run your computation as follows:
Main> runLogic (myFunc 1 []) (\a r -> a:r) []
[[16,15,14,13,12,11,10],[16,15,14,13,12,11,10,9],[16,15,14,13,12,11,10,8]...

runLogic takes the Logic computation, a continuation and an initial value for the output of the continuation. Here I just passed a continuation which will accumulate all results in a list. The above will backtrack and get all solutions, unlike the Prolog example, since we used a soft cut instead of a hard cut. To stop backtracking after getting the first solution you can use once:
Main> runLogic (once $ myFunc 1 []) (\a r -> a:r) []
[[16,15,14,13,12,11,10]]

you can also use observe to observe the first solution only, without having to pass a continuation:
Main> observe (myFunc 1 [])
[16,15,14,13,12,11,10]

or even obserMany and observeAll:
observeMany 5 (myFunc 1 []) --returns the first 5 solutions

observerAll (myFunc 1 [])   --returns a list of all solutions

Finally, you will need to install the logict package to get the above code to work. Use cabal install logict to install it.
Edit: Answering your question in the comments
Yes, you can do something similar without having to install logict. Although a dedicated backtracking monad makes things less complicated and makes clear what you are trying to do.
To model the logict example above you only need the [] monad
myFunc :: Int -> [Int] -> [[Int]]
myFunc field acc | exitCond field acc = return acc
myFunc field acc = do
     let m1 = do
           f <- nextField field
           guard $ test1 f
           myFunc f acc
         m2 = do
           f <- nextField field
           guard $ test2 f
           myFunc f (f:acc)
      in m1 `mplus` m2

nextField i = return $ i + 1
exitCond i a = i > 15
test1 i = i < 10
test2 i = i < 20

You can run it as follows:
Main> myFunc 1 []
[[16,15,14,13,12,11,10],[16,15,14,13,12,11,10,9],[16,15,14,13,12,11,10,8]...

You can also choose how many solutions you want as before:
Main> head $ myFunc 1 []
[16,15,14,13,12,11,10]
Main> take 3 $ myFunc 1 []
[[16,15,14,13,12,11,10],[16,15,14,13,12,11,10,9],[16,15,14,13,12,11,10,8]]

However, you will need the Cont monad, and thus the ListT monad, to implement a hard cut as in the Prolog example, which was not available in the logict example above:
import Control.Monad.Cont
import Control.Monad.Trans.List

myFunc :: Int -> ListT (Cont [[Int]]) [Int]
myFunc field = callCC $ \exit -> do
    let g field acc | exitCond field acc = exit acc
        g field acc =
          let m1 = do
                     f <- nextField field
                     guard $ test1 f
                     g f acc
              m2 = do
                     f <- nextField field
                     guard $ test2 f
                     g f (f:acc)
          in m1 `mplus` m2
    g field []

Like Prolog, this last example will not backtrack again after exitCond is satisfied:
*Main> runCont (runListT (myFunc 1)) id
[[16,15,14,13,12,11,10]]

A: You comment helped clarify some, but there is still some question in mind about what you are looking for so here is an example of using the list monad and guard.
import Control.Monad

myFunc lst = do
  e <- lst
  guard $ even e -- only allow even elements
  guard . not $ e `elem` [4,6,8] -- do not allow 4, 6, or 8
  return e -- accumulate results

used in ghci:
> myFunc [1..20]
[2,10,12,14,16,18,20]

A: I've never programmed in Haskell - then I would call for your help - but could hint about
that Prolog fragment - where I think you have a typo - should be myFunc(Field2, [(X1,Y1)|Acc], Result). could be compiled -by hand - in a continuation passing schema.
Let's google about it (haskell continuation passing prolog). I will peek first the Wikipedia page: near Haskell we find the continuation monad.
Now we can try to translate that Prolog in executable Haskell. Do this make sense ?

A: Textual translation of your code to Haskell is:
myFunc field acc = take 1 $              -- a cut
                     g field acc
  where
    g f a | ending_condition_holds = [a]
    g f a =
      ( nextField f       >>= (\f2 ->
        (if test1  ...                   -- test1 a predicate function
          then  [()]
          else  []  )     >>= (_ ->
        g f2 a         )))
      ++
      ( nextField f       >>= (\f2 ->
        test2  ...        >>= (\_ ->     -- test2 producing some results
        g f2 (f2:a)    )))


text:
Q: Caliburn.Micro - OnDeactivate Not triggering I'm having a strange issue, and im pretty much at my wits end trying to work it out.
I have a Conductor which activates and deactivates viewmodels used for editing data, these view models implements screen and use OnDeactivate to ensure that any changes are saved before closing.
However for some reason, OnDeactivate in one of my ViewModels is never called, even tho i can see it being passed to DeactivateItem of the conductor.
To do this have the following in my conductor:
    private void SwitchScreen(Screen viewModel)
    {
        DeactivateItem(ActiveItem, true);
        ActivateItem(viewModel);
        NotifyOfPropertyChange(() => ProjectActionRegion);
    }

    public override void DeactivateItem(IScreen item, bool close)
    {
        base.DeactivateItem(item, close);
        NotifyOfPropertyChange(() => ProjectActionRegion);
    }

This ensures that when TryClose is called the region is correctly updated. The SwitchScreen is called each time a selection is made on a datagrid, loading the viewmodel. I can see that Deactivate item is called when i change selection, and i can see its passing the correct viewmodel into that method.
However OnDeactivate is still never called, and i have no idea why :/
    protected override void OnDeactivate(bool close)
    {
        System.Windows.Forms.MessageBox.Show("SAVE ME!");
    }

Edited to remove incorrect code (the base. was a mistake, this is my actual code)
EDIT:
I've just realized what the difference between the working versions and the broken version is. I have a view/viewmodel that works as a conductor, this works fine. However inside that viewmodel i load a second view/viewmodel that also works as a conductor, this one fails to work, i wonder if it has to do with with being inside another conductor (but not actually handled by that conductor, just loaded into that viewmodel)

A: For screen life-cycle to function correctly, all of the view models in your view hierarchy must be conducted. You should make your child conductor an active screen of your parent conductor.
You can either do this by making it the active item of the parent conductor, or by using the ConductWith method on the child conductor, passing in a reference to the parent conductor.


text:
Q: Opening two ports I have 2 ip cameras, one is operating on port 8021 the other I would like to operate on 8022
I have successfully opened a port forwarding rule for port 8021 and can see my camera output from outside my network
I also have a rule set up for port 8022 but using port checker I see it is closed.
What could be stopping this port from opening?

A: Some possibilities -

*

*The camera does not have a default gateway ?

*The camera is operating on a different port, eg 8021 ?

*There is a firewall blocking port 8022 ?

*There is confusion due to NAT ?

If your router has the ability to dump packets, look at whats traversing which interface.   If not, try substituting a PC with a similar server on port 8021 and doing a traffic dump on that - this could help work out if its a device problem or routing issue.


text:
Q: Iterating over certain model attributes with RSpec I'm learning tests in Rails with RSpec and I'm trying to refactor some basic unit tests.
I have a model with :name, :protein and :calories. I would like to write a .each do loop that would loop only through some of the attributes (:protein and :calories), set a negative value to them and then test them.
Right now I'm writing duplicate code
  it "is not valid with negative values" do
    subject.calories = -1
    expect(subject).to_not be_valid
  end

  it "is not valid with negative values" do
    subject.protein = -1
    expect(subject).to_not be_valid
  end

As there are actually several attributes I would like to be able to write something like
nutritional_value = [:protein, :calories]
  nutritional_value.each do |nutr|
    subject.nutr = -1
    expect(subject).to_not be_valid
  end

Hope I've made myself clear, still learning

A: It is not best practices to write logic in spec file.
Install shoulda matchers gem (https://github.com/thoughtbot/shoulda-matchers)
And then you can write like this
it { is_expected.not_to allow_value(-1).for(:protein) }
it { is_expected.not_to allow_value(-1).for(:calories) }

A: I am not sure what your model attributes are (can you post them?) but if your model has the fields "protein" and "calories" and you validate these to be > -1 you probably want to:
  [:protein, :calories].each do |nutr|
    subject[nutr] = -1
    expect(subject).to_not be_valid
  end

Also if you have two different validations defined in your model, it's better practice to spec them in two separate examples if you absolutely want to do it by the book.


text:
Q: Clonar elementos html Como puedo clonar elementos de html y poder cambiarle sus propiedades independientemente?
Intenté con esto:

function clonar(){
  var c = document.getElementById("about0");
  var clon = c.cloneNode(true);
  clon.style.width = "1000px";
  document.body.appendChild(clon);
}
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color:gray;

}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Con "independiente" me refiero a que a los elementos clonados les pueda cambiar sus propiedades, osea de todas las propiedades que heredó, si quiero cambiarle el color, etc.

A: Segun la documentacion se puede utilizar Node#cloneNode:

El método Node.cloneNode () devuelve un duplicado del nodo en el que
  se llamó este método.

Y claramente lo estas utilizando lo que entiendo que el error que tienes es que no estas llamando la funcion clonar y estas utilizando el id equivocado, en vez de about0, deberia de ser about.
Aqui tu ejemplo editado

function clonar(){
  var c = document.getElementById("about");
  var clon = c.cloneNode(true);
  clon.style.width = "1000px";
  document.body.appendChild(clon);

}
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color:gray;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

A: No estas invocando la funcion clonar() y el id about0 no existe, deberia ser about

function clonar() {
  var c = document.getElementById("about");
  var clon = c.cloneNode("about");
  clon.style.width = "50px";
  clon.style.height = "50px";
  document.body.appendChild(clon);

}
clonar();
#about {
  width: 350px;
  height: 350px;
  border-radius: 175px;
  background-color: gray;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>


text:
Q: What does points score do in Hitman Absolution? I just play the game and was wondering what does point do in this game ? Are they just a number to compare to another player online or maybe you can buy or unlock any stuff in game ?

A: High scores obtained in main singleplayer campaign missions unlock "assasin techniques" which upgrade Agents 47's abilities (improving recovery time, reducing weapon recoil). You can find a list of all assasin techniques here.


text:
Q: How do I get the Category of an Android Preference? How do I get the PreferenceCategory of a Preference? PreferenceManager has a findPreference method but a Preference does not have a getCategory method.
Is there a way to get the PreferenceCategory of a Preference from it's key name?

A: There is no getCategory() method but you could use this following workaround: If you don't use dependency attribute for your Preference you could set your Preference as dependent from PreferenceCategory and then use getDependency() method. For example:
<PreferenceCategory
    android:title="MyPrefCat"
    android:key="category"
    android:selectable="false">
    <CheckBoxPreference
            android:key="chkbox"
            android:dependency="category" />
</PreferenceCategory>

In the PreferenceActivity you could use now:
CheckBoxPreference currentPref = (CheckBoxPreference) findPreference("chkbox");
String prefCatKey = currentPref.getDependency();
PreferenceCategory catPref = (PreferenceCategory) findPreference(prefCatKey);
// Access PreferenceCategory's attributes such as its title:
String prefCatTitle = catPref.getTitle().toString();

A: Are you trying to do this from within the PreferenceActivity or elsewhere? If from there, try this out. It should loop through your categories and find the right one. Just make sure you update the catKeys array to include the categories you want to search each time you change your xml.
String catKeys = {"catOne","catTwo","catThree","catFour"};

String getCategoryKey(String prefKey)
{
    PreferenceCategory curCat;
    Preference test;
    for(String catKey : catKeys)
    {
        curCat = (PreferenceCategory)findPreference(catKey);
        if(curCat == null)
            continue;
        test = curCat.findPreference(prefKey);
        if(test != null)
            return catKey;
    }
}

A: There is no built-in method in the SDK to get the parent (either category or screen) of the preference. You should manually find it in the hierarchy to be able to write something like:
Preference preference = findPreference(key);
getParent(preference).removePreference(preference);

Below are the methods which enables it. Note, that it should be written in your preference activity (derived from the PreferenceActivity class), which can provide the hierarchy root by calling getPreferenceScreen()
private PreferenceGroup getParent(Preference preference)
{
    return getParent(getPreferenceScreen(), preference);
}

private PreferenceGroup getParent(PreferenceGroup root, Preference preference)
{
    for (int i = 0; i < root.getPreferenceCount(); i++)
    {
        Preference p = root.getPreference(i);
        if (p == preference)
            return root;
        if (PreferenceGroup.class.isInstance(p))
        {
            PreferenceGroup parent = getParent((PreferenceGroup)p, preference);
            if (parent != null)
                return parent;
        }
    }
    return null;
}

A: I don't see a getCategory or getGroup neither in Preference.
But, you can use the methods of PreferenceCategory
inherited from http://developer.android.com/reference/android/preference/PreferenceGroup.html
getPreference(int index)

int getPreferenceCount()

That's a long way indeed for what you want to do, but it looks like you should rebuild the preference menu indeed.
Other alternative would be to saxp your xml prefrence file.
Regards,
 Stéphane

A: You can find the entire child-parent tree by traversing over all of the preferences and then check which is the parent of any preference you wish, even without using the id of the parent:
public static Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
    {
    final Map<Preference,PreferenceGroup> result=new HashMap<Preference,PreferenceGroup>();
    final Stack<PreferenceGroup> curParents=new Stack<PreferenceGroup>();
    curParents.add(activity.getPreferenceScreen());
    while(!curParents.isEmpty())
      {
      final PreferenceGroup parent=curParents.pop();
      final int childCount=parent.getPreferenceCount();
      for(int i=0;i<childCount;++i)
        {
        final Preference child=parent.getPreference(i);
        result.put(child,parent);
        if(child instanceof PreferenceGroup)
          curParents.push((PreferenceGroup)child);
        }
      }
    return result;
    }

usage:
  final Map<Preference,PreferenceGroup> preferenceParentTree=buildPreferenceParentTree(SettingsActivity.this);
  final PreferenceGroup preferenceParent=preferenceParentTree.get(preference);

EDIT: If you wish to just hide it, you can also use this:
https://developer.android.com/reference/androidx/preference/Preference#setVisible(boolean)
I'm not sure if currently it's available or not, though.


text:
Q: VMWare Win7 guest on Win7 host can't access internet I have a Win7 guest on VmWare Workstation 6.5 running on another Win7 that is on a notebook with wireless network. Seeking this same problem on web pages I do not found and answer for my problem not even a problem like mine.
I tried Bridge or Nat, changing windows network adapter confs on the two OS, and change settings on Virtual Network Editor too. But none worked.
My notebook ip is something like 192.168.1.170, gateway is 192.168.1.1. Even setup virtual adapters to this subnet and this configs on DHCP not worked. My great doubt is what type of connection to use on VM (Bridge, NAT, etc...) and what adapter to change (VMNet0, VMnet8) or create a new one.
I don't know how to combine those options to make it works.

A: I use Custom VMnet8(NAT) on the Virtual Machine.
In the Workstation "Virtual Network Editor" set
Tab NAT/ VMnet host = VMnet8.
Tab DHCP/ Virtual Network = VMnet8
Quit and restart Vmware after Workstation network setting changes; if not sometimes they do not work properly.


text:
Q: Rotate Bits Right operation in Ruby Is there a Rotate Bits Right in Ruby ?
Or how can I do that please.
Thanks

A: Some facts:

*

*Ruby has operators << and >> to shift, but no built-in rotate operator. You have to fake it.

*Ruby's Fixnum class automatically promotes to Bignum when the value exceeds the machine word size. This includes numbers that would fit in an unsigned word but not a signed word -- for example, 0xffffffff is a positive Bignum, not a negative Fixnum.

So if you want a rotate operation, you a) have to write it using the shift operators, b) either hardcode 32 or 64 bits or ask Fixnum for the word size, and c) accept that the result might end up being a Bignum.
That being said, this might work:
class Integer
  def ror count
    (self >> count) | (self << (32 - count)) & 0xFFFFFFFF
  end
end

>> printf "0x%x\n", (0x01234567.ror 4)
0x70123456

A: If you need higher performance, and don't mind adding a dependency, there is the bit-twiddle gem, which provides this operation implemented in native code:
require 'bit-twiddle/core_ext'
# rotate by 8 bits
0x08048586.rrot32(8).to_s(16) # => "86080485"

Disclosure: I'm the author of this gem.

A: ROR is rotate right.
Here's a C implementation that could be ported to Ruby.
Ruby does have the

*

*<<    Bitwise Shift Left and

*

Bitwise Shift Right

operators


text:
Q: objective c libraries on ubuntu I installed GNUStep on Ubuntu 12.10, and some tools for Objective-C development. I then tried to compile the following code.
#import <Foundation/Foundation.h>

int main(int *argc, const char *argv[]) {
  NSAutorelease *pool = [[NSAutorelease alloc] init];
  NSLog(@"hello world");
  [pool drain];
  return 0;
}

When I compile it with gcc -o hello hello.m -Wall -lobjc, I get the following error.

Foundation/Foundation.h: No such file or directory; compilation terminated.

I find the Foundation library and other libraries in /usr/include/GNUstep/Foundation. Why am I getting that error message?


text:
Q: copy files on EC2 slowing down very fast I'm running a simple test when i'm copying 6 GB of files from one directory to other.
I'm doing this test on R4.4xlarge instance of AWS.
The disk is 300 GIB and the IOPs are configured to 600 on the specific volume.
What i'm facing is very wierd, in the begining it start copying in rate of more than 600 MB/sec and after few seconds it slowing down dramatically to 20 MB /sec.
The volume type (file system type) is IO1, and the OS is windows
Any idea of what could cause this behaviour?

A: AWS storage topics is a beast.  In short, i suggest you go through the following material.
Slide share : Deep Dive: Maximizing EC2 and EBS Performance
Youtube :  Deep Dive: Maximizing EC2 and EBS Performance


text:
Q: Having issues while constructing a test vector text file for Logisim? First of all I want to mention that I am using Logisim -Evolution Version - 3.4.1 for all my logical circuits simulation. The link to this Logisim software is :
https://github.com/reds-heig/logisim-evolution
Now the issue I am facing is I had an assignment to construct an ALU using this software by using this
YouTube video as a reference whose link is :
https://youtu.be/lvYCchzQTyE
at time stamp - 20:30
he opens up his test vector , which basically is used to dry run some cases on your circuit.
Now i tried to recreate this truth table in a text file whose link is :
https://paste.sh/3-ovBHtY#fE_SwK99-tv_VQmtlJCALNHA
But when i am trying to load this .txt file as my test vector i am faced with this error message :
The error message image
It states that it's not able to parse multiple bit for a single column for eg .:
in columns A I have multi-bit values as '1011' e.t.c which it's unable to parse.
I wanted the exact same truth table that he got in his video at - 20:30
but there's that parsing error coming up and again.
Thanks for any help in advance.

A: The best way to solve this issue is to take a screenshot of the table from the youtube video itself.

A: I found this https://weinman.cs.grinnell.edu/courses/CSC211/2018F/assignments/combinational-logic/
If you have 4 bit pin A write in text A[4]


text:
Q: Progress to next loop iteration when using nullable/optional tokens I have to write parser to be used in java app which will accept:

*

*numbers (ex: 1 2 3)

*ranges of numbers (ex: 1-3)

*named ranges (ex: GROUP_1_MATCHED)

Each token is separated by either:
<WHITE : ([" ", "\t"])+ >
<COMMA : (",") >
<SEMICOLON : (";") >
<EOL : ("\r" | "\n" | "\r\n") >

Everything would be easy if range hadn't optional spaces like:
1-  2
2  -3
3  -    4
4-5

Test string is this:
"  1 2 3 4 5,6,7;8;9,,  10;11;;,  ;,;,,;\n\n   ;,,;  12,13-13,  14  -    14 15- 15 16 -16 \n17-17\n 18 - 18\n 19 - 19 \n GROUP_1_A;GROUP_1_A GROUP_1_A;GROUP_1_A,GROUP_1_A  ,;;\n\n   \"GROUP_1_A\"  ;;   20"
I have tried several ways of defining the white spaces around "-" but all in all ended either in infinite nested loop which process given simple string till the end and then start from the beginning or just can't go to next iteration. It would be easy if there was a way to check visit next token without consuming it.
SKIP: {
    < QUOTATION :  ( ["\""] ) > |
    < APOSTROPHE : ( ["'"] ) >
}

TOKEN: {
    < NAME :            ( ["a"-"z", "A"-"Z"])+ (["a"-"z", "A"-"Z", "_", "0"-"9"] )* > |
    < NUM :             ( ["0"-"9"] ){1,5} > |
    < WHITE :           ( [" ", "\t"] ) > |
    < EOL :             ( "\n" | "\r" | "\r\n" ) > |
    < COMMA :           ( [","] ) > |
    < SEMICOLON :       ( [";"] ) >
}

Map<String, List<String>> parse() : {
    Map<String, List<String>> result = new HashMap<String, List<String>>();
    List<String> single = new ArrayList<String>();
    List<String> range = new ArrayList<String>();
    List<String> named = new ArrayList<String>();
    result.put(SINGLE, single);
    result.put(RANGE, range);
    result.put(NAMED, named);
    Token name = null;
    Token first = null;
    Token last = null;
}
{
    (<WHITE>)*
    (
        (name = <NAME> |
            first = <NUM>
            (LOOKAHEAD(2) (<WHITE>)* "-" (<WHITE>)* last = <NUM>)?
        )
        ((LOOKAHEAD(2) <EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+ | <EOF>)

        {
            if (name != null) {
                named.add(name.image);
            } else if (first != null && last == null) {
                single.add(first.image);
            } else if (first != null && last != null) {
                String s = first.image + " - " + last.image;
                range.add(s);
            } else {
                System.err.println("Parser error found");
            }

            name = null;
            first = null;
            last = null;
        }
    )+
    {
        return result;
    }
}

And here is output from parsing:
Call:   parse
  Consumed token: <<WHITE>: " " at line 1 column 1>
  Consumed token: <<WHITE>: " " at line 1 column 2>
  Consumed token: <<NUM>: "1" at line 1 column 3>
  Visited token: <<WHITE>: " " at line 1 column 4>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "2" at line 1 column 5>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "2" at line 1 column 5>; Expected token: <"-">
  Visited token: <<WHITE>: " " at line 1 column 4>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 4>
  Consumed token: <<NUM>: "2" at line 1 column 5>
  Visited token: <<WHITE>: " " at line 1 column 6>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "3" at line 1 column 7>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "3" at line 1 column 7>; Expected token: <"-">
  Visited token: <<WHITE>: " " at line 1 column 6>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 6>
  Consumed token: <<NUM>: "3" at line 1 column 7>
  Visited token: <<WHITE>: " " at line 1 column 8>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "4" at line 1 column 9>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "4" at line 1 column 9>; Expected token: <"-">
  Visited token: <<WHITE>: " " at line 1 column 8>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 8>
  Consumed token: <<NUM>: "4" at line 1 column 9>
  Visited token: <<WHITE>: " " at line 1 column 10>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "5" at line 1 column 11>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "5" at line 1 column 11>; Expected token: <"-">
  Visited token: <<WHITE>: " " at line 1 column 10>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 10>
  Consumed token: <<NUM>: "5" at line 1 column 11>
  Visited token: <<COMMA>: "," at line 1 column 12>; Expected token: <<WHITE>>
  Visited token: <<COMMA>: "," at line 1 column 12>; Expected token: <"-">
  Visited token: <<COMMA>: "," at line 1 column 12>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 12>
  Consumed token: <<NUM>: "6" at line 1 column 13>
  Visited token: <<COMMA>: "," at line 1 column 14>; Expected token: <<WHITE>>
  Visited token: <<COMMA>: "," at line 1 column 14>; Expected token: <"-">
  Visited token: <<COMMA>: "," at line 1 column 14>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 14>
  Consumed token: <<NUM>: "7" at line 1 column 15>
  Visited token: <<SEMICOLON>: ";" at line 1 column 16>; Expected token: <<WHITE>>
  Visited token: <<SEMICOLON>: ";" at line 1 column 16>; Expected token: <"-">
  Visited token: <<SEMICOLON>: ";" at line 1 column 16>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 16>
  Consumed token: <<NUM>: "8" at line 1 column 17>
  Visited token: <<SEMICOLON>: ";" at line 1 column 18>; Expected token: <<WHITE>>
  Visited token: <<SEMICOLON>: ";" at line 1 column 18>; Expected token: <"-">
  Visited token: <<SEMICOLON>: ";" at line 1 column 18>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 18>
  Consumed token: <<NUM>: "9" at line 1 column 19>
  Visited token: <<COMMA>: "," at line 1 column 20>; Expected token: <<WHITE>>
  Visited token: <<COMMA>: "," at line 1 column 20>; Expected token: <"-">
  Visited token: <<COMMA>: "," at line 1 column 20>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 20>
  Visited token: <<COMMA>: "," at line 1 column 21>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 21>
  Visited token: <<WHITE>: " " at line 1 column 22>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 22>
  Visited token: <<WHITE>: " " at line 1 column 23>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 23>
  Consumed token: <<NUM>: "10" at line 1 column 24>
  Visited token: <<SEMICOLON>: ";" at line 1 column 26>; Expected token: <<WHITE>>
  Visited token: <<SEMICOLON>: ";" at line 1 column 26>; Expected token: <"-">
  Visited token: <<SEMICOLON>: ";" at line 1 column 26>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 26>
  Consumed token: <<NUM>: "11" at line 1 column 27>
  Visited token: <<SEMICOLON>: ";" at line 1 column 29>; Expected token: <<WHITE>>
  Visited token: <<SEMICOLON>: ";" at line 1 column 29>; Expected token: <"-">
  Visited token: <<SEMICOLON>: ";" at line 1 column 29>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 29>
  Visited token: <<SEMICOLON>: ";" at line 1 column 30>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 30>
  Visited token: <<COMMA>: "," at line 1 column 31>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 31>
  Visited token: <<WHITE>: " " at line 1 column 32>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 32>
  Visited token: <<WHITE>: " " at line 1 column 33>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 1 column 33>
  Visited token: <<SEMICOLON>: ";" at line 1 column 34>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 34>
  Visited token: <<COMMA>: "," at line 1 column 35>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 35>
  Visited token: <<SEMICOLON>: ";" at line 1 column 36>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 36>
  Visited token: <<COMMA>: "," at line 1 column 37>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 37>
  Visited token: <<COMMA>: "," at line 1 column 38>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 1 column 38>
  Visited token: <<SEMICOLON>: ";" at line 1 column 39>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 1 column 39>
  Visited token: <<EOL>: "\n" at line 1 column 40>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 1 column 40>
  Visited token: <<EOL>: "\n" at line 2 column 1>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 2 column 1>
  Visited token: <<WHITE>: " " at line 3 column 1>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 1>
  Visited token: <<WHITE>: " " at line 3 column 2>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 2>
  Visited token: <<WHITE>: " " at line 3 column 3>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 3>
  Visited token: <<SEMICOLON>: ";" at line 3 column 4>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 3 column 4>
  Visited token: <<COMMA>: "," at line 3 column 5>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 3 column 5>
  Visited token: <<COMMA>: "," at line 3 column 6>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 3 column 6>
  Visited token: <<SEMICOLON>: ";" at line 3 column 7>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 3 column 7>
  Visited token: <<WHITE>: " " at line 3 column 8>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 8>
  Visited token: <<WHITE>: " " at line 3 column 9>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 9>
  Consumed token: <<NUM>: "12" at line 3 column 10>
  Visited token: <<COMMA>: "," at line 3 column 12>; Expected token: <<WHITE>>
  Visited token: <<COMMA>: "," at line 3 column 12>; Expected token: <"-">
  Visited token: <<COMMA>: "," at line 3 column 12>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 3 column 12>
  Consumed token: <<NUM>: "13" at line 3 column 13>
  Visited token: <"-" at line 3 column 15>; Expected token: <<WHITE>>
  Visited token: <"-" at line 3 column 15>; Expected token: <"-">
  Visited token: <<NUM>: "13" at line 3 column 16>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "13" at line 3 column 16>; Expected token: <<NUM>>
  Consumed token: <"-" at line 3 column 15>
  Consumed token: <<NUM>: "13" at line 3 column 16>
  Visited token: <<COMMA>: "," at line 3 column 18>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 3 column 18>
  Visited token: <<WHITE>: " " at line 3 column 19>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 19>
  Visited token: <<WHITE>: " " at line 3 column 20>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 20>
  Consumed token: <<NUM>: "14" at line 3 column 21>
  Visited token: <<WHITE>: " " at line 3 column 23>; Expected token: <<WHITE>>
  Visited token: <<WHITE>: " " at line 3 column 24>; Expected token: <<WHITE>>
  Consumed token: <<WHITE>: " " at line 3 column 23>
  Consumed token: <<WHITE>: " " at line 3 column 24>
  Consumed token: <"-" at line 3 column 25>
  Consumed token: <<WHITE>: " " at line 3 column 26>
  Consumed token: <<WHITE>: " " at line 3 column 27>
  Consumed token: <<WHITE>: " " at line 3 column 28>
  Consumed token: <<WHITE>: " " at line 3 column 29>
  Consumed token: <<NUM>: "14" at line 3 column 30>
  Visited token: <<WHITE>: " " at line 3 column 32>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 32>
  Consumed token: <<NUM>: "15" at line 3 column 33>
  Visited token: <"-" at line 3 column 35>; Expected token: <<WHITE>>
  Visited token: <"-" at line 3 column 35>; Expected token: <"-">
  Visited token: <<WHITE>: " " at line 3 column 36>; Expected token: <<WHITE>>
  Consumed token: <"-" at line 3 column 35>
  Consumed token: <<WHITE>: " " at line 3 column 36>
  Consumed token: <<NUM>: "15" at line 3 column 37>
  Visited token: <<WHITE>: " " at line 3 column 39>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 39>
  Consumed token: <<NUM>: "16" at line 3 column 40>
  Visited token: <<WHITE>: " " at line 3 column 42>; Expected token: <<WHITE>>
  Visited token: <"-" at line 3 column 43>; Expected token: <<WHITE>>
  Visited token: <"-" at line 3 column 43>; Expected token: <"-">
  Consumed token: <<WHITE>: " " at line 3 column 42>
  Consumed token: <"-" at line 3 column 43>
  Consumed token: <<NUM>: "16" at line 3 column 44>
  Visited token: <<WHITE>: " " at line 3 column 46>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 3 column 46>
  Visited token: <<EOL>: "\n" at line 3 column 47>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 3 column 47>
  Consumed token: <<NUM>: "17" at line 4 column 1>
  Visited token: <"-" at line 4 column 3>; Expected token: <<WHITE>>
  Visited token: <"-" at line 4 column 3>; Expected token: <"-">
  Visited token: <<NUM>: "17" at line 4 column 4>; Expected token: <<WHITE>>
  Visited token: <<NUM>: "17" at line 4 column 4>; Expected token: <<NUM>>
  Consumed token: <"-" at line 4 column 3>
  Consumed token: <<NUM>: "17" at line 4 column 4>
  Visited token: <<EOL>: "\n" at line 4 column 6>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 4 column 6>
  Visited token: <<WHITE>: " " at line 5 column 1>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 5 column 1>
  Consumed token: <<NUM>: "18" at line 5 column 2>
  Visited token: <<WHITE>: " " at line 5 column 4>; Expected token: <<WHITE>>
  Visited token: <"-" at line 5 column 5>; Expected token: <<WHITE>>
  Visited token: <"-" at line 5 column 5>; Expected token: <"-">
  Consumed token: <<WHITE>: " " at line 5 column 4>
  Consumed token: <"-" at line 5 column 5>
  Consumed token: <<WHITE>: " " at line 5 column 6>
  Consumed token: <<NUM>: "18" at line 5 column 7>
  Visited token: <<EOL>: "\n" at line 5 column 9>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 5 column 9>
  Visited token: <<WHITE>: " " at line 6 column 1>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 6 column 1>
  Consumed token: <<NUM>: "19" at line 6 column 2>
  Visited token: <<WHITE>: " " at line 6 column 4>; Expected token: <<WHITE>>
  Visited token: <"-" at line 6 column 5>; Expected token: <<WHITE>>
  Visited token: <"-" at line 6 column 5>; Expected token: <"-">
  Consumed token: <<WHITE>: " " at line 6 column 4>
  Consumed token: <"-" at line 6 column 5>
  Consumed token: <<WHITE>: " " at line 6 column 6>
  Consumed token: <<NUM>: "19" at line 6 column 7>
  Visited token: <<WHITE>: " " at line 6 column 9>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 6 column 9>
  Visited token: <<EOL>: "\n" at line 6 column 10>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 6 column 10>
  Visited token: <<WHITE>: " " at line 7 column 1>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 7 column 1>
  Consumed token: <<NAME>: "GROUP_1_A" at line 7 column 2>
  Visited token: <<SEMICOLON>: ";" at line 7 column 20>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 7 column 20>
  Consumed token: <<NAME>: "GROUP_1_A" at line 7 column 21>
  Visited token: <<WHITE>: " " at line 7 column 39>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 7 column 39>
  Consumed token: <<NAME>: "GROUP_1_A" at line 7 column 40>
  Visited token: <<SEMICOLON>: ";" at line 7 column 58>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 7 column 58>
  Consumed token: <<NAME>: "GROUP_1_A" at line 7 column 59>
  Visited token: <<COMMA>: "," at line 7 column 77>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 7 column 77>
  Consumed token: <<NAME>: "GROUP_1_A" at line 7 column 78>
  Visited token: <<WHITE>: " " at line 7 column 96>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 7 column 96>
  Visited token: <<WHITE>: " " at line 7 column 97>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 7 column 97>
  Visited token: <<COMMA>: "," at line 7 column 98>; Expected token: <<EOL>>
  Consumed token: <<COMMA>: "," at line 7 column 98>
  Visited token: <<SEMICOLON>: ";" at line 7 column 99>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 7 column 99>
  Visited token: <<SEMICOLON>: ";" at line 7 column 100>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 7 column 100>
  Visited token: <<EOL>: "\n" at line 7 column 101>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 7 column 101>
  Visited token: <<EOL>: "\n" at line 8 column 1>; Expected token: <<EOL>>
  Consumed token: <<EOL>: "\n" at line 8 column 1>
  Visited token: <<WHITE>: " " at line 9 column 1>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 1>
  Visited token: <<WHITE>: " " at line 9 column 2>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 2>
  Visited token: <<WHITE>: " " at line 9 column 3>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 3>
  Consumed token: <<NAME>: "GROUP_1_A" at line 9 column 5>
  Visited token: <<WHITE>: " " at line 9 column 24>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 24>
  Visited token: <<WHITE>: " " at line 9 column 25>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 25>
  Visited token: <<SEMICOLON>: ";" at line 9 column 26>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 9 column 26>
  Visited token: <<SEMICOLON>: ";" at line 9 column 27>; Expected token: <<EOL>>
  Consumed token: <<SEMICOLON>: ";" at line 9 column 27>
  Visited token: <<WHITE>: " " at line 9 column 28>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 28>
  Visited token: <<WHITE>: " " at line 9 column 29>; Expected token: <<EOL>>
  Consumed token: <<WHITE>: " " at line 9 column 29>
  Consumed token: <<NUM>: "20" at line 9 column 30>
  Visited token: <<WHITE>: " " at line 9 column 32>; Expected token: <<WHITE>>
  Visited token: <<WHITE>: " " at line 9 column 33>; Expected token: <<WHITE>>
  Consumed token: <<WHITE>: " " at line 9 column 32>
  Consumed token: <<WHITE>: " " at line 9 column 33>
Return: parse

parsers.excel.ParseException: Encountered " <NUM> "1 "" at line 9, column 34.
Was expecting one of:
    <WHITE> ...
    "-" ...

Parser should produce similar output:
single = [1,2,3,4,5,6,7,8,9,10,11,12,20]
range = [13 - 13,14 - 14,15 - 15,16 - 16,17 - 17,18 - 18,19 - 19]
named = [GROUP_1_A,GROUP_1_A,GROUP_1_A,GROUP_1_A,GROUP_1_A,GROUP_1_A]

Problem occur when parser doesn't know if space come from space before dash or space which is separator of the whole number.
If you know of any way to modify the JavaCC to accomplish parsing provided string correctly it would be greatly appreciated.

A: Let's step back a bit from JavaCC and see what your grammar actually is.
parse --> ows ( body )+
body --> part sep
part --> <NAME>
part --> <NUM>
part --> <NUM> ows "-" ows <NUM>
sep --> (<EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+
sep -->  EOF
ows --> (<WHITE>)*

You should check that over to make sure that (a) I haven't made any mistakes and (b) this really is the language you intended.
I don't like the way you are dealing with EOF.  It's not really a separator. I'd suggest using the following grammar which is practically identical
parse --> ows body
body --> part ( sep body | <EOF> )
part --> <NAME>
part --> <NUM>
part --> <NUM> ows "-" ows <NUM>
sep --> (<EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+
ows --> (<WHITE>)*

First solution:  Syntactic lookahead
The OP said It would be easy if there was a way to check [the] next token without consuming it.  There is.  It's called syntactic lookahead.
The only place we need lookahead is to distinguish the second and third productions for part.
Let's combine them.
part --> <NAME>
part --> <NUM> ( ows "-" ows <NUM> )?

No fixed length lookahead determine whether or not to take the optional path in the second production. So we use syntactic lookahead like this:
part --> <NAME>
part --> <NUM> ( LOOKAHEAD( ows "-" ) ows "-" ows <NUM> )?

Now, we're done. Let's put the production back into JavaCC
void parse() : { }
{
    ows() body }
}

void body() : { }
{
    part() ( sep() body()  | <EOF> )
}

void part() : { }
{
   <NAME>
|
   <NUM>
   ( LOOKAHEAD( ows() "-")
     ows() "-" ows() <NUM>
   )?
}

void sep() : {}
{
    (<EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+
}

void ows() : {}
{
    (<WHITE>)*
}

Second solution:  LL(1)
Could we solve it with an LL(1) grammar?  Yes.  Let's go back to the original grammar, or rather the grammar that takes the EOF out of the loop.
parse --> ows body
body --> part (sep body | <EOF>)
part --> <NAME>
part --> <NUM> ( ows "-" ows <NUM> )?
sep --> (<EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+
ows --> (<WHITE>)*

Inline part and introduce nonterminal afternum
parse --> ows body
body --> <NAME> (sep body | <EOF>)
body --> <NUM> afternum
afternum --> ( ows "-" ows <NUM> )? (sep body | <EOF>)
sep --> (<EOL> | <COMMA> | <SEMICOLON> | <WHITE>)+
ows --> (<WHITE>)*

Now the problem is in afternum.
When we start to parse afternum there are 5 possibilities to consider. (i) The next token is a "-". (ii) The next token is an EOL, COMMA, or SEMICOLON. (iii) The next token is a white space. (iv) The next token is an EOF. (v) In any other case, we have an error.
In case (ii) this can't be the last part.  In case (iii), the WHITE we just saw could have been the first character of a sep or it might be leading to a hyphen. We make a new nonterminal to deal with both possibilities.
afternum --> "-" ows <NUM> (sep body | <EOF>)
afternum --> nonwssep (sep)? body
afternum --> <WHITE> moreafternum
afternum --> EOF

moreafternum --> ows "-" ows <NUM> (sep body | EOF)
               | sep? body

nonwssep --> <EOL> | <COMMA> | <SEMICOLON>

Now the problem is in moreafternum, since, if the next token is WHITE, either choice is viable.
Let's manipulate moreafternum a bit. The goal is to expose that WHITE token so we can factor it out.
    moreafternum
= By definition
    ows "-" ows <NUM> (sep body | EOF) | sep? body
= Expand the ?
      ows "-" ows <NUM> (sep body | EOF)
    | body
    | sep body
= Expand first `ows` and split white from other cases
      "-" ows <NUM> (sep body | EOF)
    | WHITE ows "-" ows <NUM> (sep body | EOF)
    | body
    | sep body
= Expand the `sep` in the fourth case
      "-" ows <NUM> (sep body | EOF)
    | WHITE ows "-" ows <NUM> (sep body | EOF)
    | body
    | (WHITE | nonwesep) sep? body
= Split the fourth case
      "-" ows <NUM> (sep body | EOF)
    | WHITE ows "-" ows <NUM> (sep body | EOF)
    | body
    | WHITE sep? body
    | nonwssep sep? body
= Duplicate the fourth choice
      "-" ows <NUM> (sep body | EOF)
    | WHITE ows "-" ows <NUM> (sep body | EOF)
    | WHITE sep? body
    | body
    | WHITE sep? body
    | nonwssep sep?
= Combine the second and third choices.
      "-" ows <NUM> (sep body | EOF)
    | WHITE ( ows "-" ows <NUM> (sep body | EOF) | sep? body )
    | body
    | WHITE sep? body
    | nonwssep sep? body
= combine the third, fourth, and fifth choices
      "-" ows <NUM> (sep body | EOF)
    | WHITE ( ows "-" ows <NUM> (sep body | EOF) | sep? body)
    | sep? body
= Definition of moreafternum
      "-" ows <NUM> (sep body | EOF)
    | WHITE moreafternum
    | sep? body

Now we can redefine moreafternum with this recursive version
moreafternum --> "-" ows <NUM> (sep body | EOF)
               | <WHITE> moreafternum
               | sep? body

If we code this production in JavaCC, there will still be a choice conflict between the second and third choices when the next token is WHITE.  JavaCC will prefer then second over the third, which is what we want.  If you don't like the warning you can supress it with a LOOKAHEAD.  Note that this LOOKAHEAD will not change the Java code produced, it simply suppresses the warning.
void moreafternum() : {} {
       "-" ows() <NUM> (sep() body() | <EOF>)
|
       // LOOKAHEAD( <WHITE> ) // Optional lookahead to suppresss the warning
       <WHITE> moreafternum()
|
       ( sep() )? body() }

We can go all the way to LL(1) by taking another look at moreafternum.
     moreafternum
=  From above
      "-" ows <NUM> (sep body | EOF)
    | WHITE ( ows "-" ows <NUM> (sep body | EOF) | sep? body)
    | body
    | WHITE sep? body
    | nonwssep sep? body
= Fourth choice is subsumed by the second.
      "-" ows <NUM> (sep body | EOF)
    | WHITE ( ows "-" ows <NUM> (sep body | EOF) | sep? body)
    | body
    | nonwssep sep? body
= Combine last two choices
      "-" ows <NUM> (sep body | EOF)
    | WHITE ( ows "-" ows <NUM> (sep body | EOF) | sep? body)
    | (nonwssep sep?)? body
= Original definition of moreaftersep
      "-" ows <NUM> (sep body | EOF)
    | WHITE moreaftersep
    | (nonwssep sep?)? body

Putting it altogether we get
parse --> ows body

body --> <NAME> (sep body | <EOF>)
body --> <NUM> afternum

afternum --> "-" ows <NUM> (sep body | <EOF>)
afternum --> <WHITE> moreafternum
afternum --> nonwssep (sep)? body
afternum --> EOF

moreafternum --> "-" ows <NUM> (sep body | EOF)
moreafternum --> <WHITE> moreafternum
moreafternum --> ( nonwssep (sep)? )? body

nonwssep --> <EOL> | <COMMA> | <SEMICOLON>

sep --> (nonwssep | <WHITE>)+

ows --> (<WHITE>)*

This is LL(1), so you can translate it to JavaCC with no lookahead.


text:
Q: inserting values from multipe selected checkboxes into database So the whole scenario is as follows:
I have a form on my website which has multiple values of checkboxes. For example, "price" has four checkboxes. The user can select anywhere from none to all four checkboxes.
I am unable to insert the "SELECTED" checkbox value into the table of the database. I have tried all the methods that I could find on Google and Stackoverflow.
I am relatively new into PHP, so I know very little about it. But to get this problem right, I have gone through various documentations, many in fact.
Anyways, here is what I am doing right now, and it works. But it's a bad method and I know there would be a much more efficient way of doing that.

     <input type="checkbox" name="price1" value="Less than 10,000, "> Less than 10,000
     <input type="checkbox" name="price2" value="10,001 to 15000, "> 10,001 - 15000
     <input type="checkbox" name="price3" value="15,001 to 25000, "> 15,001 - 25000
     <input type="checkbox" name="price4" value="25,001 to 35000, "> 25,001 - 35000
     <input type="checkbox" name="price5" value="35,001 and more, "> 35,001 and more

So basically each of the individual checkboxes for the price has its own independent name.
The corresponding PHP is as follows
            <?php
        session_start();

        $_SESSION["f1"]=$_REQUEST["price1"];
        $_SESSION["f2"]=$_REQUEST["price2"];
        $_SESSION["f3"]=$_REQUEST["price3"];
        $_SESSION["f4"]=$_REQUEST["price4"];
        $_SESSION["f5"]=$_REQUEST["price5"];
        $_SESSION["f"]=$_SESSION["f1"].$_SESSION["f2"].$_SESSION["f3"].$_SESSION["f4"].$_SESSION["f5"];

        $z6=$_SESSION["f"];

        require_once('ConnectDB.php');
        $conn=mysql_connect(SERVER,USER,PASSWORD);
        mysql_select_db(DATABASE,$conn);

        query="insert into mobile_frm values('".$z6."')";
        mysql_query($query) or die(mysql_error());

        echo"Thanks for using us";
        header('Location: gadget.html');
        mysql_close($conn);

        ?>

This is the PHP script that writes the form value in the Database. I have only included a part of it to keep it plain and simple.
Here I am just taking all the individual values and making one string out of them.
Please give me some direction into it.

A: You can send an array of form elements, just change your markup to:
<input type="checkbox" name="prices[]" value="Less than 10,000, ">
<input type="checkbox" name="prices[]" value="10,001 to 15000, ">
// etc...

Then, PHP side:
$prices = $_POST['prices'];   // this is now an array, work on it

A: First of all you are using the deprecated library mysql. Should switch to Mysqli or better PDO.
Then you have a typo here:
query="insert into mobile_frm values('".$z6."')";

This should be:
$query="insert into mobile_frm values('$z6')";

assuming that your table has only one column.
Then, as other said before each checkbox should have the same name prices[] (that is the array notation). In the prices array you will have only the checked checkboxes.
SIDENOTE: you are using $_REQUEST array but you should use $_POST or $_GET depending on what method you define in your form. I also assume that you need to use $_SESSION to store the posted values (to use them elsewhere). In any other cases your code should be revised not to use $_SESSION just to assign the stored value to a variable.

A: use square bracket([]) after name of the checkbox.
<input type="checkbox" name="price1[]" value="Less than 10,000, "> Less than 10,000

In PHP you can use
$price1 = $_POST['price1'];

A: Below is the code showing that how to use multiple checkbox fields in PHP.
First change the checkbox name to price[].

     <input type="checkbox" name="price[]" value="Less than 10,000, "> Less than 10,000
     <input type="checkbox" name="price[]" value="10,001 to 15000, "> 10,001 - 15000
     <input type="checkbox" name="price[]" value="15,001 to 25000, "> 15,001 - 25000
     <input type="checkbox" name="price[]" value="25,001 to 35000, "> 25,001 - 35000
     <input type="checkbox" name="price[]" value="35,001 and more, "> 35,001 and more

How to take value in PHP?
Ans: You can directly take value: $prices = $_POST['prices']; In this case you can get your value as an array. If you want delimiter then use $price = implode(', ', $_POST['price']);.

A:

     <input type="checkbox" name="price[]" value="Less than 10,000, "> Less than 10,000
     <input type="checkbox" name="price[]" value="10,001 to 15000, "> 10,001 - 15000
     <input type="checkbox" name="price[]" value="15,001 to 25000, "> 15,001 - 25000
     <input type="checkbox" name="price[]" value="25,001 to 35000, "> 25,001 - 35000
     <input type="checkbox" name="price[]" value="35,001 and more, "> 35,001 and more

<?php
$price = $_REQUEST['price'];
//for single cell value separte by ,
$p = implode(',',$price);
// for each value
for($i = 0;count($price)<$i;$i++){

    // put insert query and value of selected price
    $p = $price[$i];
}
?>


text:
Q: Creating Multiple Rectangle Objects at Once (Java) First off,  thanks for just clicking this :) I'm an amateur student coder, and I'm creating a (horrible) version of Pacman. I'm trying to create rectangles for each of my dots on my 1000x650 applet screen, so I can create an if statement when  Packages hit box touches them, they disappear.
My problem is, I want to create a class so I can create the rectangles easily and have only 1 if statement,  and not one for each dot rectangle (trying to learn to be efficient :P)
If I didn't elaborate enough, I'll be wary to bring edits based on your responses,  and thanks!!!
(Edit 1: Fixed a run on sentence xD)

A: You can use a for statement which repeadly loops untill a condition is met.
This is the general structure:
for (counterInitialization; terminatingCondition; incrementLoopsCount) {
    statement(s);
}

And this is an example in which the loop continue for as long as the counter i<n):
int n = 50;
for(int i = 0;i<n;i++){
//code for creating a rectangle
...
}

I suggest you give this a read.

A: If you need to fill rectangles on both X and Y (Matrix), you most probably need nested loops.
Let's consider you want to a 5 * 5 rectangle every 100 pixels in the width with a 50 pixels spacing in the height:
for(int x = 0;x<1000;x+= 100)
{
     for(int y=0;y<650; y+= 50)
     {
          drawRectangle(x, y, 5, 5); // Considering drawRectangle(x, y, width, height)
     }
}

A: Try this code, it will return true when it collides with the dot.
Object pacman = new Object();
pacman.xcoord = null;
pacman.ycoord = null;

final int dotsInStage = 50;
// add other properties

int xcoords[] = new int[dotsInStage];
int ycoords[] = new int[dotsInStage];

Call this Boolean:
public boolean dotCollison (int xcoords[], int ycoords[], Object pacman) {
       loop = 0;
       while (loop <= dotsInStage) {
            if (pacman.xcoord = xcoords[loop] && pacman.ycoord = ycoords[loop]) {
                return true;
                break;
            }
        }
}

To add the rectangles, try:
int loop = 0;
while (loop <= dotsInStage) {
   Graphics.drawRectangle (xcoord[loop] , ycoord[loop] , xcoord[loop] + 10 , ycoord[loop] + 10);
}

Hope it works and happy coding!

A: I'm not totally comprehending your question. But
Couldn't you just create a 2 d array use a nested for loop
For( int I = 0; I<array.length;i++){
For (int j = 0; j <array[0].length;I++){
//fill w/ rectangles
array[I][j]= ;
}}


text:
Q: Setting a page link in the footer? What is the proper process for setting a page up with a link to it in the footer?
Currently, all my pages are in Appearance -> Menu...and of course displayed in the main menu.
However I want a batch of them to be in the footer.
I have decent HTML,CSS, PHP skills but new to WP.

A: What may be easier (if you don't necessarily want all the same menu items to appear in the footer) is to:

*

*Create a new menu, "Footer Menu" for example

*Add-in whatever links (pages) are needed there

*Add a widget (called Custom Menu) to a footer widget position (if your current theme supports it).

Let me know if that helps. Thanks!


text:
Q: Spark : DB connection per Spark RDD partition and do mapPartition I want to do a mapPartitions on my spark rdd,
    val newRd = myRdd.mapPartitions(
      partition => {

        val connection = new DbConnection /*creates a db connection per partition*/

        val newPartition = partition.map(
           record => {
             readMatchingFromDB(record, connection)
         })
        connection.close()
        newPartition
      })

But, this gives me a connection already closed exception, as expected because before the control reaches the .map() my connection is closed. I want to create a connection per RDD partition, and close it properly. How can I achieve this?
Thanks!

A: As mentioned in the discussion here - the issue stems from the laziness of map operation on the iterator partition. This  laziness means that for each partition, a connection is created and closed, and only later (when RDD is acted upon), readMatchingFromDB is called.
To resolve this, you should force an eager traversal of the iterator before closing the connection, e.g. by converting it into a list (and then back):
val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB

  connection.close()
  newPartition.iterator // create a new iterator
})

A: rdd.foreachPartitionAsync(iterator->{

// this object will be cached inside each executor JVM. For the first time, the //connection will be created and hence forward, it will be reused.
// Very useful for streaming apps
DBConn conn=DBConn.getConnection()
while(iterator.hasNext()) {
  conn.read();
}

});

public class DBConn{
private static dbObj=null;

//Create a singleton method that returns only one instance of this object
}

}


text:
Q: Setup react.js with Node.js using Typescript I am new here and I need help!
I'm not able to find a WORKING guide for setting up a Typescript project using React.ja and Node.js. I spent hours on searching online tutorials but I've only lost time,as the stuff I foud was not clear at all, or I just have some errors in my machine.
Anybody can give me some clarifications?
Any help would be appreciated :)

A: Use the official Create React App utility with Typescript template. Check This Link
EDIT
You can use some well-built starter boilerplates, with Yeoman.
It will save you a lot of time.


text:
Q: Copy custom list from one server to anothe server programatically sharepoint 2007 We are using sharepoint 2007,We have two site, both sites are on different server.
According to requirement we need to copy custom list from one server to another on daily/weekly basis.
We want to automate this process.
Is there any way by which we can do this programatically.
Thanks in advance,
Rushikesh

A: *

*For scheduling you can use SharePoint Timer Jobs.

*For the second part, copying list, I am assuming you want to copy the List Items. You can use SharePoint List Web Service for submitting items to a remote server.


text:
Q: Display a field associated with user logged in? Basically i have a simple table (mbs_users) containing:
    Field   Type    Collation   Attributes  Null    Default Extra   Action
id  int(5)          No  None    AUTO_INCREMENT
username    varchar(7)  utf8_general_ci     No  None
password    varchar(7)  utf8_general_ci     No  None
status  varchar(65) utf8_general_ci     No  None

The user logs in from the page main_login .php

<form name="form1" method="post" action="checklogin.php">

Member Login

Username
:
<input name="myusername" type="text" id="myusername">

Password
:
<input name="mypassword" type="text" id="mypassword">

<input type="submit" name="Submit" value="Login">

</form>

Check login file
<?php
$host="mysql.mywebsite.co.uk"; // Host name
$username="myusernamexx/ Mysql username
$password="password"; // Mysql password
$db_name="mbs_orderstatus"; // Database name
$tbl_name="mbs_users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

and then redirects to login_success.php
// Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>

Login Successful

How do i get the field 'status' associated with the user that just logged in to show on this page?

A: You already have that information at the login page. At the login page you also set data into the session. Why not set the data you need in the session? That way you can use it at the other pages.
So in login file:
$sql = "SELECT * FROM $tbl_name WHERE username = '$myusername' and password = '$mypassword'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
$_SESSION['username'] = $data['username']
$_SESSION['status'] = $data['status']

And in login_success:
echo $_SESSION['status'];


text:
Q: Pointer reference possible memory leak detected? Do I have a memory leak?
I am building a game engine and I have some code that I think is right but my code analysis tools ( cppcheck ) says I have memory leak, it maybe a false positive.
I have a ( this is a bare bones use case )
class Mesh
{
D3DMATERIAL9* mpMaterials;
LPDIRECT3DTEXTURE9* mpTextures;

D3DMATERIAL9*& GetMaterials() { return mpMaterials; }
LPDIRECT3DTEXTURE9*& GetTexures() {return mpTextures; }
};

in my mesh class I have some directx pointers
When I load the mesh I send a shared_ptr to a function in my graphics manager class to be loaded.
In that function I do
void Renderer::LoadMesh( shared_ptr<Mesh> myMesh)
{
// other code
D3DMATERIAL9*& pMaterials= myMesh->GetMaterials();
LPDIRECT3DTEXTURE9*& pTextures= myMesh->GetTextures();
// other code

// and then instantiate them

pMaterials = new D3DMATERIAL9[matCount];
pTextures = new LPDIRECT3DTEXTURE9[texCount];

// And then i do some stuff with those objects.
}

Now at the end of this function is when cpp check says pMaterials and pTextures leaked their memory. It is my understanding that pMaterials and pTextures are references to the pointers within myMesh and that the memory I instantiated lives there because the pointers in the Mesh class point to that instantiated memory, and that as long as I destroy the Mesh object properly sometime later ( and call delete[] mpMaterials; delete[] mpTextures; in the Mesh destructor ) I have not leaked memory right?

A: I wrote the memory leaks check in cppcheck. and I agree that is a false positive. I will fix it.
feel free to report it in the cppcheck issue tracker.

A: It might be possible that you are not leaking memory in case you call that loading function only once. Anyway, your class design looks quite fragile as there is no proper data encapsulation for those pointers. It would be better if you had setters for the data that gets loaded in the loading function. This would allow the class owning the data to delete old data in case setters are called more than once.

A: As long as you destroy your Mesh object at some point you won't be leaking your two arrays.
It is not uncommon for static analysis tools to have false positives, especially when checking for run-time issues such as memory leaks.  Try using a run-time analysis tool such as Valgrind if you're interested in memory leaks.

A: No, it seems that your code is ok.
Valgrind says "invalid delete/free/realloc", but the cause of it is probably that you (seem to) free ther pointer that you have never allocated.
Since you are doing some funny things with the pointers here, you probably have a false positive.


text:
Q: When I wrote text to a File, why don't I see the Text when I open the file? I wrote an android app that just outputs a text and date to a file on the SD card.
public class MyWastedTimeActivity extends Activity {
    /** Called when the activity is first created. */
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText ujET=(EditText)findViewById(R.id.input);
        Button gomb=(Button)findViewById(R.id.button1);
        final String ujString=ujET.getText().toString();
        gomb.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                try {
                    commitToFile(ujString);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }

private void commitToFile(String mit) throws IOException {
    String aktIdo = DateFormat.getDateInstance().format(new Date());
     String kiIr =aktIdo+" "+mit+"\n";

     FileOutputStream fos = null;
     ObjectOutputStream out = null;

      File root = Environment.getExternalStorageDirectory();

       fos = new FileOutputStream(  root + "/" +"idom.txt" ,true);

       out = new ObjectOutputStream( fos );
       out.writeObject( kiIr );
       out.close();

     }
}

The problem is when i open the "idom.txt"-file on my pc it gives me :Ԁt䴎牡ㄠⰸ㈠㄰′갊í琅฀慍⁲㠱〲㈱ਠ when its really not what i wrote ...Any suggestion?

A: You have used ObjectOutputStream Class. The method writeObject is used to write an object to the stream. Look at this Reference Document. It is going to write in binary format which is not human readble form.
I Suggest you to use PrintWriter Class. PrintWriter is one of the character-based classes.
Here is a nice example.


text:
Q: how to create dart project and accepts inputs in VScode How can I create and run a Dart console application Using VS Code? I tried to accept via vscode. I kept getting "global evaluation requires a thread to have been loaded vscode"

A: Just run with the following command:
cd <PROJECT_FOLDER>
dart run bin/<NAME_OF_YOUR_DART_FILE>.dart


text:
Q: How to pass date from AngularJS Datepicker to Java Servlet? I am trying to add a date filter to my code. I want to pass the date chosen in the AngularJS Date-Picker to the Java Servlet and then call the stored procedure through the Persistence code as shown.
How do I format the dates correctly in the JavaScript and then in the Java code?
Datepicker code
<datepicker date-format="yyyyMMdd" button-prev=''
    button-next=''>

    <input ng-model="filters.dateFrom" type="text" placeholder="Select a starting date">

</datepicker>

<datepicker date-format="yyyyMMdd" button-prev=''
    button-next=''>

    <input ng-model="filters.dateTo" type="text" placeholder="Select an end date">

</datepicker>

AngularJS code
app.factory('graphService', function ($http, Restangular) {

        var exports = {};

        exports.getRestangular = function () {
            // return Restangular.setBaseUrl("/api");
            return Restangular.setBaseUrl("/apm/graph");
        };

        exports.getGraphDataDC = function (dcName, from, to) {
            return exports.getRestangular().one("graphData/DC/" + dcName + "/" + from + "/" + to).get();
        };

Java Servlet
                    List <SummaryDelaysDataCenter80Perc> dcData;

                    String dcname = pathInfo[pathInfo.length-3];
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

                    try {
                        from = new java.util.Date(simpleDateFormat.parse(pathInfo[pathInfo.length - 2]).getTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    try {
                        to = new java.util.Date(simpleDateFormat.parse(pathInfo[pathInfo.length - 1]).getTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    try
                    {
                        dcData = persistance.getSummaryDelaysDC80Perc(from, to, dcname);
                    } catch(RuntimeException e) {
                        LOGGER.error("Could not load data form database, reason: {}", e);
                        throw new ServletException(e);
                    }
                    // parse to json
                    json = ThreadsafeUtils.getGsonInstance(pretty).toJson(dcData);
                    LOGGER.debug(dcData.size() + " summary entries were read");

                    out.write(json);
                    break;

Persistence
    public List<SummaryDelaysSystem80Perc> getSummaryDelaysSystem80Perc(Date from, Date to, String systemName) throws RuntimeException {
        List<SummaryDelaysSystem80Perc> result = new ArrayList<>();
        Calendar c = Calendar.getInstance(Locale.GERMANY);
        java.sql.Date minDate;
        java.sql.Date maxDate;
        String call;
        if (from != null)
            minDate = new java.sql.Date(from.getTime());
        else
            minDate = Utils.getDBMinDate();

        if (to != null) {
            maxDate = new java.sql.Date(to.getTime());
        } else {
            maxDate = Utils.getDBMaxDate();
        }
        call = "CALL " + summaryDelaysSystemProcedureName + "(?, ?, ?, ?)";

//      sdelten80.setName(systemName);
        try {
            //prepare statement
            java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
            java.sql.CallableStatement cst = connection.prepareCall(call);
            //set parameters
            cst.setDate(1, minDate, c);
            cst.setDate(2, maxDate, c);
//          cst.setString(2, to.toString());
            cst.setString(3, systemName);
            // execute statement and retrieve result
            cst.execute();
            ResultSet rs = cst.getResultSet();
            while (rs.next()) {
                SummaryDelaysSystem80Perc sdelsys80 = new SummaryDelaysSystem80Perc();
                DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.GERMANY);
                String strDate = dateFormat.format(rs.getTimestamp(1));
                sdelsys80.setName(rs.getString(2));
                sdelsys80.setDate(strDate);
                sdelsys80.setPerc80serverdelay(Double.toString(rs.getDouble(3)));
                sdelsys80.setPerc80networkdelay(Double.toString(rs.getDouble(4)));
                sdelsys80.setPerc80clientdelay(Double.toString(rs.getDouble(5)));
                sdelsys80.setPerc80roundtrips(Long.toString(rs.getLong(6)));
                result.add(sdelsys80);
            }
        } catch (java.sql.SQLException e) {
            throw new RuntimeException("StoredProcedureCall was not successful", e);
        }
        return result;
    }

A: Your datepicker needs to be in a form that posts the data. Then using the input field name, you can access the posted value.
See here as well: How to transfer data from JSP to servlet when submitting HTML form
If you don't want to use a form and have the automated browser post, you can have the $http.post in your ng-click function so something like this:
<input ng-model="filters.dateFrom" type="text" placeholder="Select a starting date">
<button ng-click="BtnClick();">Post to server</button>

in angular controller
$scope.BtnClick = function() { /* Post the values using $http.post and you can access to the input values using filters.dateFrom and filters.dateTo */


text:
Q: WCF not accessible in Azure I have a WCF service hosted in a webrole in Azure.
When I test it in dev fabric it works ok from my web page (other web role).
But when I deploy it in the Cloud it doesn't seems to be running, although the webrole is ready.
When I use Fiddler to do a GET on one of the public methods of my WCF service, I get:

[Fiddler] Connection to
  xxxxxxxxxxxxxx.cloudapp.net failed.
  Exception Text: A connection attempt
  failed because the connected party did
  not properly respond after a period of
  time, or established connection failed
  because connected host has failed to
  respond yyyyyyyyyyyyyy

This is the service configuration:
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="GovGuard" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
  <WebRole name="GovGuard.Services">
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="GuardServiceEndpointBinding" endpointName="GuardServiceEndpoint" />
        </Bindings>
      </Site>
    </Sites>
    <ConfigurationSettings>
      <Setting name="DevelopmentConnectionString" />
      <Setting name="GovGuardStorageConnectionString" />
    </ConfigurationSettings>
    <Endpoints>
      <InputEndpoint name="GuardServiceEndpoint" protocol="http" port="81" />
    </Endpoints>
    <Imports>
      <Import moduleName="Diagnostics" />
    </Imports>
    <LocalResources>
      <LocalStorage name="MyCompany.GovGuard.Services.svclog" sizeInMB="1000" cleanOnRoleRecycle="false" />
    </LocalResources>
  </WebRole>
  <WebRole name="GovGuard.Web">
    <Sites>
      <Site name="Web">
        <Bindings>
          <Binding name="GuardWebEndpointBinding" endpointName="GuardWebEndpoint" />
        </Bindings>
      </Site>
    </Sites>
    <ConfigurationSettings>
      <Setting name="GuardServiceUrl" />
      <Setting name="DevelopmentConnectionString" />
      <Setting name="GovGuardStorageConnectionString" />
    </ConfigurationSettings>
    <Endpoints>
      <InputEndpoint name="GuardWebEndpoint" protocol="http" port="80" />
    </Endpoints>
    <Imports>
      <Import moduleName="Diagnostics" />
    </Imports>
    <LocalResources>
      <LocalStorage name="MyCompany.GovGuard.Web.svclog" cleanOnRoleRecycle="false" sizeInMB="1000" />
    </LocalResources>
  </WebRole>
</ServiceDefinition>

(edit)
In my investigation of the problem it may be this: I use the Microsoft.SqlServer.Types assembly as file reference in the WCF project. I use copy-local = true to copy the assembly to the bin folder and it is packaged in the .csx file. But.... the Microsoft.SqlServer.Types also needs the SqlServerSpatial.dll library (not assembly). I created a postbuild script to copy that dll to the bin also, but I didn't succeed....
Maybe someone can help me how to package a dll (not an assembly) to the .csx file....
(edit)
Found it here: http://msdn.microsoft.com/en-us/gg271395

A: WCF does not play nicely if you are trying to do a self hosted service.
Because of the way that the HTTP.sys registration happens it does it on the local machine name and does not allow you to do a wildcard registration accepting the load balanced name. The option you have is to use a internal endpoint and try to connect from your web host the IP of the worker role.
What I ended up doing was just converting my WCF service to a MVC endpoint and making my worker role be a web application. It's not the most elegant, but it worked.

A: Finally the solution that works: I develop on a 32 bit Win7 machine and I copied the SqlServerSpatial.dll from my machine to the WCF project (with Copy to Output Directory and BuildAction Content). That caused a weird error message in the Cloud, because that library was 32 bit! I renewed the library with a 64 bit version and now after deploy in the Cloud everything works!


text:
Q: Laravel 5.2 validator: Validate Array request parameter, at least one value must be selected I am having a form where i am having title, body, answers[][answer] and options[][option].
I want atleast one answer must be selected for the given question,  for example:
i have ABC question and having 5 options for that question,now atleast one answer must be checked or all for given question.
Efforts
protected $rules = [
            'title' => 'required|unique:contents|max:255',
            'body' => 'required|min:10',
            'type' => 'required',
            'belongsto' => 'sometimes|required',
            'options.*.option' => 'required|max:100',
            'answers.*.answer' => 'required',
        ];

But this is not working. i want atleast one answer must be selected.
Please help me.

A: The problem is that on $_POST an array filled with empty strings will be passed if no answer is selected.
$answers[0][0] = ''
$answers[0][1] = ''
$answers[0][2] = ''

Hence the following will not work since array count will be greater than zero due to the empty strings:
 $validator = Validator::make($request->all(), [
    'answers.*'   => 'required'
  ]);

The easiest way to solve this is to create a custom Validator rule by using Laravel's Validator::extend function.
  Validator::extendImplicit('arrayRequireMin', function($attribute, $values, $parameters)
  {
      $countFilled = count(array_filter($values));
      return ($countFilled >= $parameters[0]);
  });

And then call it in your Validation request:
  $validator = Validator::make($request->all(), [
    'answers.*'   => 'arrayRequireMin:1'
  ]);

The magic happens in array_filter() which removes all empty attributes from the array. Now you can set any minimum number of answers required.
Validator::extendImplicit() vs Validator::extend()

For a rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create such an "implicit" extension, use the Validator::extendImplicit() method:

Laravel's validation docs

A: Try this,
    'answer.0' => 'required'

it will help you. I think.


text:
Q: How to fix row value in a table passed from controller using ajax? I have to pass table value from controller to view using ajax. I am succeeded to pass table value but all the data comes in a same column. I want to show data in row.
I have tried possible cases. Since, this is the first time i am getting this problem, so i request to guide me.
//this is my table code in view:

    Module ID
    Module Name
    Module Status

//this is my ajax:
 $(function () {
        $(".report").click(function () {
            var title = $(this).data('title');

            var id=$(this).data('id');
            $("#project-title").val(title);

             $('#project-id').val(id);

                $.ajax({

                    url: "{{url('tms/projects/',[null])}}/"+id,
                       method: 'GET',

                       success:function(response){
                     // console.log(response);
                       $('#values').html(response);
                 }
          });
        });

    });

//this is my controller:
    public function showajax($id){
       $modules= modules::where('project_id',$id)->get();

    foreach($modules as $row)
    {
        $html[]=
              '' . $row->id . '	' .
                 '' . $row->title . '	' .
                 '' . $row->status. '	'.
                 '
';
    }

     return Response::json($html);

}

A: Your ajax call function,
$(function () {
        $(".report").click(function () {
            var title = $(this).data('title');

            var id=$(this).data('id');
            $("#project-title").val(title);

             $('#project-id').val(id);

                $.ajax({

                    url: "{{url('tms/projects/',[null])}}/"+id,
                    //type instead of method
                    type: 'GET',

                       success:function(response){
                     // console.log(response);
                       // append instead of html
                       $('#values').append(response.html);
                 }
          });
        });

    });

Your Controller,
 public function showajax($id){
       $modules= modules::where('project_id',$id)->get();

    foreach($modules as $row)
    {
        $html[]=
              '' . $row->id . '	' .
                 '' . $row->title . '	' .
                 '' . $row->status. '	'.
                 '
';
    }

     return Response::json(['success' => true, 'html'=>$html]);

}

A: According to your response, Adding a class in the row doesn't solve your problem. You have to use insertAfter()
var $tableRow = $('.report tr');

$.ajax({
    url: "{{url('tms/projects/',[null])}}/"+id,
    method: 'GET',
    success:function(response){
        $(response).insertAfter( $tableRow );
    }
});


text:
Q: How to change app navbar color when app is in drawer in Ionic 3 I need to change the color of the apps navbar when app is in the drawer.
I tried status bar plugin but it only chnage the color of the status bar when app is open on screen.
this.statusBar.overlaysWebView(false);
this.statusBar.backgroundColorByHexString('#e13c31');

and
<preference name="StatusBarBackgroundColor" value="red" />
<preference name="StatusBarOverlaysWebView" value="true" />

I want to change Hrythm apps navbar color to red like message app has its own color which is blue.

A: 1.****ionic 3
.toolbar-background {
  background-color: blue;
}

2.****older version
<ion-navbar *navbar primary></ion-navbar>
<ion-navbar *navbar secondary></ion-navbar>
<ion-navbar *navbar danger></ion-navbar>

3. In variable.scss I added the property as navbarColor: #009688
$colors: (
  primary:     #387ef5,
  secondary:   #32db64,
  danger:      #f53d3d,
  light:       #f4f4f4,
  dark:        #222,
  favorite:    #69BB7B,
  navbarColor: #009688
);

And added in my home.html at the ion-navbar element.
<ion-navbar color='navbarColor'></ion-navbar>

4. With Ionic 2 rc2 we have the following variables we can use to change the toolbar appearance:
$toolbar-background
$toolbar-border-color
$toolbar-text-color
$toolbar-active-color
$toolbar-inactive-color

5.
<ion-navbar no-border-bottom [color]="isAndroid ? 'primary' : 'light'">

6.
<ion-navbar color="primary">
    <ion-title>Not Delivered Details</ion-title>
    <ion-buttons end>
    </ion-buttons>
</ion-navbar>

A: After spending lots of time searching for this issue, I finally found the solution.
I used the "Header Color" plugin to change the color of the header when the app is in the drawer.
https://ionicframework.com/docs/v3/native/header-color/


text:
Q: getElementById no funciona ¿Alguien ve el error?
En el index.html:
    <!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

Introduce los valores:

    <input  type="text" name="arrayInput" id="arrayInput">
    Enviar

Y en mi js:
console.log('ok!');

const button = document.getElementById('butt');

eventListeners();

function eventListeners() {
    if (button) {
        button.addEventListener('click', recogerInput);
    } else {
      console.log('No lo encuentro');
    }
  }

Me devuelve el else...
Necesito algo tan simple como que me añada el click al botón, pero no entiendo por qué no lo encuentra ni con getElementById ni con querySelectorAll...

A: A mi me funciona perfectamente, el unico error que me daba es que la funcion recogerInput no existia, la agregue y aqui esta el ejemplo. Te recomiendo ponerlo antes del  para que al momento que cargue tu archivo .js el DOM este completamente cargado.

console.log('ok!');

const button = document.getElementById('butt');

eventListeners();

function eventListeners() {
    if (button) {
        button.addEventListener('click', recogerInput);
    } else {
      console.log('No lo encuentro');
    }
  }
  function recogerInput(){
  console.log("Hey")
  }

    <meta charset="utf-8">
    <title></title>

Introduce los valores:

    <input  type="text" name="arrayInput" id="arrayInput">
    Enviar

A: El problema, como ya se ha dicho, era que no estaba creado el handler (recogerInput) que estabas asignando al evento.
Visto eso, te recomendaría que implementes buenas prácticas en tu código:

*

*Deberías comprobar que el DOM está cargado antes de referirte a cualquier parte de él. Puedes hacerlo agregando un listener  a DOMContentLoaded, tal y como explica MDN.

*No tiene sentido marear tanto el código, usando dos funciones para agregar un listener. Lo correcto sería simplemente asignar el listener  una vez que el DOM se haya cargado, porque es lo que certifica que el elemento se encontrará sí o sí. Si se trata de elementos dinámicos, entonces puedes asignarles una clase, y luego usar querySelectorAll u otro para asignar el listener a los elementos de esa clase.

Hay que optar por la simplicidad en el código, o puedes encontrarte tarde o temprano en medio de un plato de spaghetti.

/*TODO manipulación de elementos del DOM debería ir dentro de este bloque*/
document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
  /*
    Crea una referencia sólo ni necesitas
    referirte a este elemento más adelante
    sino puedes hacer una asignación directa con:
    document.getElementById('butt')..addEventListener('click', recogerInput);
  */
  const button = document.getElementById('butt');
  button.addEventListener('click', recogerInput);
});

function recogerInput(e) {
  console.log("ocurrió click en "+e.target.text);
}

Introduce los valores:

  <input type="text" name="arrayInput" id="arrayInput">
  Enviar


text:
Q: two cells from other table in one current cell I have a table which holds truck info . I have another table which holds driver info  (name and truck id there two of them in each trip) . I make a daily report  from the first table regarding it's current status and I want to have a cell which holds the two current drivers. When I do join on the tables I get two rows from each truck and the only difference is the name of the driver.
Is there a way to produce a single row (either PHP or SQL query) ?
to get an idea  my current result is this :
Truck:DRIVER1:Date:Destination:Cargo:Remarks
Truck:DRIVER2:Date:Destination:Cargo:Remarks

And I want to get something like this :
Truck:DRIVER1 DRIVER2:Date:Destination:Cargo:Remarks

is that even possible ? I'm fairly new to this

A: Say for example you have stored first fetched string in $str1 and second in the second variable $str2.
You can now just use ltrim() and rtrim() functions as
<?php
$str1 = 'Truck:DRIVER1:Date:Destination:Cargo:Remarks';
$str2 = 'Truck:DRIVER2:Date:Destination:Cargo:Remarks';
$result = ltrim($str2,'Truck:');
$result = rtrim($result,':Date:Destination:Cargo:Remarks');
?>

After this you get the value of $result as DRIVER2
And then you can just concatenate the result into string one as
$str1 = 'Truck:DRIVER1 '.$result.':Date:Destination:Cargo:Remarks';

And when you echo the $str you will get the desired output
Output
Truck:DRIVER1 DRIVER2:Date:Destination:Cargo:Remarks