text:
Q: Forming JSON with Key and Value if Key Exists I have a JSON Structure something like:
    [
   {
      "name":"angelinas"
   },
   {
      "name":"besuto"
   },
   {
      "name":"catch",
      "cuisine":"Japanese"
   },
   {
      "name":"center cut"
   },
   {
      "name":"fedora"
   },
   {
      "name":"Habanero",
      "cuisine":"Mexican"
   },
   {
      "name":"Indies"
   },
   {
      "name":"new"
   },
   {
      "name":"RazINN"
   },
   {
      "name":"restaurantTestVenue779"
   },
   {
      "name":"restaurantTestVenue9703"
   },
   {
      "name":"Salsa ",
      "cuisine":"Mexican"
   },
   {
      "name":"Sushi Place",
      "cuisine":"Japanese"
   },
   {
      "name":"The Ashoka"
   },
   {
      "name":"The Poboys"
   },
   {
      "name":"the shogun"
   },
   {
      "name":"vinyard view"
   }
]

Using the JSON above i want to identify whether a cuisine is assosiated to restaurant. If yes, I want to build a JSON Structure something like:
[
   {
      "Mexican":{
         "venueNames":[
            "Habanero",
            "Salsa"
         ]
      }
   },
   {
      "Japanese":{
         "venueNames":[
            "Sushi Place",
            "catch"
         ]
      }
   }
]

Have tried to build the JSON using a for loop and .hasProperty but not much of a success.

A: Here is what you can do!
First iterate through the data and use the method "hasOwnProperty" to check if the cuisine exists and if it does then check if your cuisines object has that cuisine and if does then add it to it.
const data = [{
        "name": "angelinas"
    },
    {
        "name": "besuto"
    },
    {
        "name": "catch",
        "cuisine": "Japanese"
    },
    {
        "name": "center cut"
    },
    {
        "name": "fedora"
    },
    {
        "name": "Habanero",
        "cuisine": "Mexican"
    },
    {
        "name": "Indies"
    },
    {
        "name": "new"
    },
    {
        "name": "RazINN"
    },
    {
        "name": "restaurantTestVenue779"
    },
    {
        "name": "restaurantTestVenue9703"
    },
    {
        "name": "Salsa ",
        "cuisine": "Mexican"
    },
    {
        "name": "Sushi Place",
        "cuisine": "Japanese"
    },
    {
        "name": "The Ashoka"
    },
    {
        "name": "The Poboys"
    },
    {
        "name": "the shogun"
    },
    {
        "name": "vinyard view"
    }
]

let cuisines = {};

for (const resturant of data) {
    if (resturant.hasOwnProperty('cuisine')) {

        if (cuisines.hasOwnProperty(resturant.cuisine)) {
            cuisines[resturant.cuisine].venueNames.push(resturant.name);
        } else {
            cuisines[resturant.cuisine] = {
                venueNames: [resturant.name]
            };
        }
    }
}

A: It's a simple reduction of the array. If the restaurant has a defined cuisine, check if the result already has this cuisine defined. If not, create an object for it where you can push the restaurant name to.

const restaurants = [
   {
    "name":"angelinas"
   },
   {
    "name":"besuto"
   },
   {
    "name":"catch",
    "cuisine":"Japanese"
   },
   {
    "name":"center cut"
   },
   {
    "name":"fedora"
   },
   {
    "name":"Habanero",
    "cuisine":"Mexican"
   },
   {
    "name":"Indies"
   },
   {
    "name":"new"
   },
   {
    "name":"RazINN"
   },
   {
    "name":"restaurantTestVenue779"
   },
   {
    "name":"restaurantTestVenue9703"
   },
   {
    "name":"Salsa ",
    "cuisine":"Mexican"
   },
   {
    "name":"Sushi Place",
    "cuisine":"Japanese"
   },
   {
    "name":"The Ashoka"
   },
   {
    "name":"The Poboys"
   },
   {
    "name":"the shogun"
   },
   {
    "name":"vinyard view"
   }
];
const cuisines = restaurants.reduce((result, restaurant ) => {
  if ( restaurant.hasOwnProperty( 'cuisine' )) {
    const { cuisine } = restaurant;
    if ( !result.hasOwnProperty( cuisine )) {
      result[ cuisine ] = {
        venueNames: []
      };
    }
    result[ cuisine ].venueNames.push( restaurant.name );
  }
  return result;
}, {});
console.log( cuisines );

In my personal opinion, I would use a slightly different structure though. If we represent collections with objects that are always the same, we can simplify most transformations. This is less efficient that doing everything in one loop, but the code used to create the transformation is almost readable english:

const restaurants = [
   { "name": "angelinas", "cuisine": null },
   { "name": "besuto", "cuisine": null },
   { "name": "catch", "cuisine": "japanese" },
   { "name": "center cut", "cuisine": null },
   { "name": "fedora", "cuisine": null },
   { "name": "habanero", "cuisine": "mexican" },
   { "name": "Indies", "cuisine": null },
   { "name": "new", "cuisine": null },
   { "name": "RazINN", "cuisine": null },
   { "name": "restaurantTestVenue779", "cuisine": null },
   { "name": "restaurantTestVenue9703", "cuisine": null },
   { "name": "Salsa ", "cuisine": "mexican" },
   { "name": "Sushi Place", "cuisine": "japanese" },
   { "name": "The Ashoka", "cuisine": null },
   { "name": "The Poboys", "cuisine": null },
   { "name": "the shogun", "cuisine": null },
   { "name": "vinyard view", "cuisine": null }
];
const create_cuisine = name => ({ name, "venues": [] });
const unique = () => {
  const seen = {};
  return item => {
    const json = JSON.stringify( item );
    return seen.hasOwnProperty( json )
      ? false
      : ( seen[ json ] = true );
  };
};
// Filter away all the restaurants without a cuisine value.
const restaurants_with_cuisine = restaurants.filter( restaurant => restaurant.cuisine );
const cuisines = restaurants_with_cuisine
  // Extract the cuisine anmes from the restaurants.
  .map( restaurant => restaurant.cuisine )
  // Filter aways all the duplicates.
  .filter( unique() )
  // Create a new cuisine object.
  .map( cuisine_name => create_cuisine( cuisine_name ));
// Finally add all the restaurant names to the right cuisine.
restaurants_with_cuisine.forEach( restaurant => cuisines.find( cuisine => cuisine.name === restaurant.cuisine ).venues.push( restaurant.name ));

console.log( cuisines );

A: You can use in one loop below.
data.forEach(function(item) {
    // if item has cuisine and cuisine not exist in new array
    if(item["cuisine"] != null && typeof newArr.find(v => v[item.cuisine] != null) == 'undefined') {
    // create new object with structure
    let obj = {};
    obj[item.cuisine] = {
         "venueNames":[item.name]
      };

    newArr.push(obj);
  }
  else {
    // else find existing cuisine and add new venue
    let obj = newArr.find(v => v.hasOwnProperty(item.cuisine));
    if(typeof obj != 'undefined') {
        obj[item.cuisine].venueNames.push(item.name);
    }
  }
});

JSFIDDLE

A: Using a few es6 features, we can generate this list with Set, map and filter.
We will first map a list of cuisines, and remove invalid ones such as undefined. With that we will use a Set to create a unique list of cuisines.
Next we will take that list and map it again to return the final object, by filtering the original object where the cuisine matches the current iteration. Finally we map the filtered results to return just the name to the venueNames object.
Our result will look like this:

function getItems(places) {
  // Get a unique list of cuisines
  return [...new Set(places.map(p => p.cuisine).filter(c => c))]
    // Build the result
    .map(c => {
      return {
        [c]: {
          // Get a list of cuisines that match the current cuisine
          venueNames: places.filter(p => p.cuisine == c).map(c => c.name)
        }
      }
    })
}

const places = [
  {"name": "angelinas"},
  {"name": "besuto"},
  {"name": "catch","cuisine": "Japanese"},
  {"name": "center cut"},
  {"name": "fedora"},
  {"name": "Habanero","cuisine": "Mexican"},
  {"name": "Indies"},
  {"name": "new"},
  {"name": "RazINN"},
  {"name": "restaurantTestVenue779"},
  {"name": "restaurantTestVenue9703"},
  {"name": "Salsa ","cuisine": "Mexican"},
  {"name": "Sushi Place","cuisine": "Japanese"},
  {"name": "The Ashoka"},
  {"name": "The Poboys"},
  {"name": "the shogun"},
  {"name": "vinyard view"}
]

console.log(getItems(places))


text:
Q: Change the color of SpriteRenderer in Unity3d I have this method that picks a random color from a preset array of colors.
 public Color GetRandomColor()
 {
     return colors[rand.Next(0, colors.Length)];
 }

Then I use it in this method in another class
public void RandomizeColors()
{
    for(int i = 0; i< spriteRenderers.Length; i++)
    {
        spriteRenderers[i].color = rColors.GetRandomColor();
    }
}

The problem is that the colors of the sprite renderers all get set to some strange values. The RGB gets set to something in the thousands.
if I use spriteRenderers[i].color = Color.black for example it works fine.
I have checked the return values of GetRandomColor() and they are all correct. Where am I doing this wrong ?
Edit:
The array of colors. This is part of a constructor:
colors = new Color[7];
colors[0] = new Color(87f,72f,161f) ;
colors[1] = new Color(39f,145f,221f);
colors[2] = new Color(233f,191f,57f);
colors[3] = new Color(238f,133f,57f);
colors[4] = new Color(238f,71f,46f);
colors[5] = new Color(193f,57f,235f);
colors[6] = new Color(104f,176f,58f);

A: Unity Documentation says you need to have the r, g and b arguments in the range of 0f to 1f. So you can basically divide your r, g and b by 256.

A: Directly extracted from the Unity Scripting API:

Color
struct in UnityEngine
Description
Representation of RGBA colors.
This structure is used throughout Unity to pass colors around. Each color component is a floating point value with a range from 0 to 1.

Here is the Link to the Documentation:
Unity Scripting API

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple dex files define-volley error when build apk....
[enter image description here][1]
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/android/volley/VolleyError;

my gradle :

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.morten.gpibwal.desakayuambon"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    dexOptions {

    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.github.bumptech.glide:volley-integration:1.4.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:design:25.3.1'
    testCompile 'junit:junit:4.12'
}

A: The solution is
 delete "compile 'com.github.bumptech.glide:volley-integration:1.4.0'

A: add  multiDexEnabled true in gradle file also use same version for compile dependencies check below code
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.morten.gpibwal.desakayuambon"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }
    }
    dexOptions {

    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support:cardview-v7:25.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'
    compile 'com.github.bumptech.glide:volley-integration:1.4.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:support-v4:25.0.0'
    compile 'com.android.support:design:25.0.0'
    testCompile 'junit:junit:4.12'
}

remove unnecessary empty
  dexOptions {

        }

A:
com.android.dex.DexException: Multiple dex files define
  Lcom/android/volley/VolleyError;

You should delete
compile 'com.github.bumptech.glide:volley-integration:1.4.0'

Then Clean-Rebuild-Run.


text:
Q: Can UTF8 encoded data missread as Latin-1 produce ASCII artifacts? UTF-8 single byte characters map perfectly to Latin-1 (ISO 8859-1) characters (those below the character code of 128); basicly the default ASCII characters.
If I have a UTF-8 encoded string and pass it to a function, that expects a Latin-1 string is there any possibility that the Latin-1 function misinterprets parts of UTF-8 mutlibyte characters as ASCII characters?
I imagine something like this could happen:
(imagniray) UTF-8 multibyte character: 0xA330
(mis-)interpreted by Latin-1 function as two Latin-1 characters: 0xA3 0x30
The first of those characters does not lie within the ASCII set, but the second is the ASCII code for the 0 character. Is it possible that an multibyte UTF-8 character produces an artifact that looks like a single-byte UTF-8 / ASCII character like in the example above?
From my understanding of UTF-8 only single-byte characters contain any bytes with the most significant bit unset, so basicly multibyte characters never contain a byte that could be misinterpreted by a Latin-1 function as a valid ASCII character (because all those characters have the most significant bit unset). But I want to make sure this is true and I don't screw up on this, because this may have security implications when dealing with data sanitization - which I am apparently currently doing.

A: You are correct in your understanding that only single byte characters contain any bytes with the most significant bit unset. There is a nice table showing this at: http://en.wikipedia.org/wiki/UTF-8#Description


text:
Q: Rails Error Messages I encountered an issue today I haven't seen before - I have a custom validation to check if a discount code has already been used in my Order model:
validate :valid_discount_code

def valid_discount_code
  is_valid = false
  code = nil

  if discount_code.present?

    if discount_code.try(:downcase) == 'xyz'
      code = 'xyz'
      is_valid = true
    else
      code = Coupon.find_by_coupon_code(discount_code)
      is_valid = code.present?
    end

    if code.nil?
      is_valid = false
      errors.add(:discount_code, "is not a valid referral code")
    elsif ( code.present? && Coupon.where(email: email, coupon_code: code).present? )
      is_valid = false
      errors.add(:discount_code, "has already been used.")
    end

    puts "------------"
    puts errors.full_messages   ## successfully 'puts' the correct error message into my console.
    puts "------------"

    if is_valid
     .... do stuff.....
    end

  end

end

In my controller:
   if current_order.update_attributes(discount_code: params[:coupon_code].downcase, another_attribute: other_stuff)

      ....
      session[:order_id] = nil
      render json: { charged: 'true' }.as_json

    else

      puts "==============="
      puts current_order.id     # shows the correct current order ID
      puts current_order.errors.full_messages    # shows that there are no errors present
      puts "==============="

      render json: { charged: 'false', errors: current_order.errors.full_messages }.as_json

    end

So it looks like at update_attributes, it runs the validation, fails the validation, creates the error message, and then once it's back at my controller the error message is gone. I'm stumped as to what can be causing that issue.
EDIT:
Here is what current_order is:
In ApplicationController.rb:
def current_order
  session[:order_id].present? ? Order.find(session[:order_id]) : Order.new
end

A: Looks like every time you call current_order it reruns the find method.  You can confirm this in the logs, but try not to call that, or at least memoize it.  In an instance variable, the same order will be used everytime.
def current_order
  @current_order ||= (Order.find_by_id(session[:order_id]) || Order.new)
end


text:
Q: How to Convert unicode sequence to utf8 in php which received from json android? I have receive json data in php from android an just get sequence of unicode chracaters:
\u0628\u0647\u0645\u0646

How can I convert it to utf8 by the way characters are arabic character.

A: Just use json_decode()
$json = '{
    "Arabic": "\u0628\u0647\u0645\u0646"
}';

$json_decode = json_decode($json, true);
print_r($json_decode);

Output:
Array
(
    [Arabic] => بهمن
)


text:
Q: Form keydown in C# I use these codes to inform users when they press a button and show them in a message box that you have pressed a button. In the winform I have a button, so these codes won't working until I change button1 tabstop to false. and when I click on the button after that it won't tell users that they're pressing a button.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyCode == Keys.A)
   {
      MessageBox.Show("You have pressed A");
   }
}

These codes won't working until I change tabstop of the button to false. Help to how can I do that and let the users know when they pressed a button in any time.
Any help will be appreciated

A: Set the KeyPreview property of form to true from designer. It will work


text:
Q: Error when compiling aeson-pretty for elm server I am trying to install elm-server on a x86_64 linux box which fails because of errors with aeson-pretty compilation. I will appreciate help with fixing this error. Googling for the error didn't help much. So, I am reaching out here.
Cabal dry-run output first for what I am trying to do - it shows what dependencies will change:
$ cabal install elm-server --max-backjumps 1000 -v --dry-run
Reading available packages...
Choosing modular solver.
Resolving dependencies...
In order, the following would be installed:
aeson-0.7.0.2 (reinstall)
aeson-pretty-0.7.1 (reinstall) changes: aeson-0.7.0.1 -> 0.7.0.2,
attoparsec-0.10.4.0 added, cmdargs-0.10.3 added
pandoc-types-1.12.3.2 (reinstall)
texmath-0.6.6 (reinstall)
yaml-0.8.8.1 (reinstall)
pandoc-1.12.3.3 (reinstall) changes: old-time-1.1.0.1 added
Elm-0.12 (reinstall) changes: aeson-0.7.0.1 -> 0.7.0.2, aeson-pretty-0.7.1
added, pandoc-1.12.3.3 added
elm-server-0.11 (new package)

Error when aeson-pretty is compiled during actual run - I will appreciate pointers on how to resolve this (I have removed absolute file system path from the log below to remove some identifying information of work server):
ghc/7.6.1/bin/ghc --make -no-link -fbuilding-cabal-package -O -static -outputdir dist/build/aeson-pretty/aeson-pretty-tmp -odir dist/build/aeson-pretty/aeson-pretty-tmp -hidir dist/build/aeson-pretty/aeson-pretty-tmp -stubdir dist/build/aeson-pretty/aeson-pretty-tmp -i -idist/build/aeson-pretty/aeson-pretty-tmp -icli-tool -idist/build/autogen -Idist/build/autogen -Idist/build/aeson-pretty/aeson-pretty-tmp -optP-include -optPdist/build/autogen/cabal_macros.h -hide-all-packages -package-db dist/package.conf.inplace -package-id aeson-0.7.0.2-f4ad04aa4d2e7f65b938bd54f014afc0 -package-id attoparsec-0.10.4.0-a54b3de99ba828be808aba7bf3812cbc -package-id base-4.6.0.0-26b6c2181978d0c24c3b2f1a3f0f4de0 -package-id bytestring-0.10.0.0-bd919bc93a32f3db2328df9effbade89 -package-id cmdargs-0.10.3-e485ed32e993ef88a56151ce766e3511 -package-id aeson-pretty-0.7.1-inplace -XHaskell98 cli-tool/Main.hs -Wall
<command line>: cannot satisfy -package-id aeson-0.7.0.2-f4ad04aa4d2e7f65b938bd54f014afc0:
    aeson-0.7.0.2-f4ad04aa4d2e7f65b938bd54f014afc0 is unusable due to missing or recursive dependencies:
      template-haskell-2.8.0.0-3c3595becd07418f521cf03c08f6ee4e
    (use -v for more information)
Failed to install aeson-pretty-0.7.1

Running ghc-pkg on template-haskell, I get this:
$ ghc-pkg list template-haskell
WARNING: there are broken packages.  Run 'ghc-pkg check' for more details.
ghc/7.6.1/lib/ghc-7.6.1/package.conf.d
   template-haskell-2.8.0.0
.ghc/x86_64-linux-7.6.1/package.conf.d
   template-haskell-2.8.0.0

Running ghc-pkg check, I get this (just to verify it is not template-haskell that is broken) - makes sense that Elm is broken since it needs to be re-installed with elm-server:
The following packages are broken, either because they have a problem
listed above, or because they depend on a broken package.
Elm-0.12

So, it looks like I need to do my own modification of cabal package for elm-server to fix some dependencies on template-haskell. To do that, I need help with figuring out how to debug the error above in terms of cabal configuration.
In case any one is wondering about sandbox, I don't want to use cabal sandbox because of disk quota limit on work server. I am ok with breaking existing packages if I can get elm and elm-server to install.

A: template-haskell is tied to your GHC version, so it shouldn't be in your user package database.  Unregister template-haskell then reinstall any broken packages.


text:
Q: Spring Boot with JSF; Could not find backup for factory javax.faces.context.FacesContextFactory I'm having some problems with Spring Boot and JSF. The servlet appears to start up correctly, but when I attempt to access a resource I get the following exception
java.lang.IllegalStateException: Could not find backup for factory javax.faces.context.FacesContextFactory.
    at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:1011)
    at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:343)
    at javax.faces.webapp.FacesServlet.init(FacesServlet.java:302)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:884)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1720)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:724)

My Application class is as follows
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Bean
    public FacesServlet facesServlet() {
        return new FacesServlet();
    }

    @Bean
    public ServletRegistrationBean facesServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
            facesServlet(), "*.xhtml");
        registration.setName("Christmas");
        return registration;
    }

    @Bean
    public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
        return new ServletListenerRegistrationBean<ConfigureListener>(
            new ConfigureListener());
    }
}

I have no web.xml or faces-config.xml, and my pom.xml is as follows
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.x.y.z</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.5.RELEASE</version>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0</version>
        </dependency>

        <!-- JSF 2 -->
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.11</version>
        </dependency>

        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.11</version>
        </dependency>
    </dependencies>

</project>

I have a suspicion that there are some conflicts in the dependencies relating to the jsf api, but I can't seem to figure out where. Any help on fixing this issue would be greatly appreciated.

A: To get JSF working on Spring Boot without a web.xml or faces-config.xml you need to force it to load its configuration files via an init parameter on the ServletContext. An easy way to do that is to implement ServletContextAware:
public class Application implements ServletContextAware {

    // ...

    @Override
    public void setServletContext(ServletContext servletContext) {
        servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
    }
}

JSF's ConfigureListener also has a dependency on JSP, so you'll need to add a dependency on Jasper to your pom:
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

It's not directly related to your problem, but you don't need to declare FacesServlet as a bean. The ServletRegistrationBean is sufficient.
This leaves Application.java looking as follows:
import javax.faces.webapp.FacesServlet;
import javax.servlet.ServletContext;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.ServletListenerRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.ServletContextAware;

import com.sun.faces.config.ConfigureListener;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application implements ServletContextAware {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

    @Bean
    public ServletRegistrationBean facesServletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(
            new FacesServlet(), "*.xhtml");
        registration.setLoadOnStartup(1);
        return registration;
    }

    @Bean
    public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
        return new ServletListenerRegistrationBean<ConfigureListener>(
            new ConfigureListener());
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
    }
}

A: probably you forget add listener com.sun.faces.config.ConfigureListener.class :
  @Bean
    public ServletContextInitializer servletContextInitializer() {

        return sc -> {
            ***sc.addListener(com.sun.faces.config.ConfigureListener.class);***
            sc.setInitParameter("com.sun.faces.expressionFactory", "com.sun.el.ExpressionFactoryImpl");
            sc.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
            sc.setInitParameter("facelets.DEVELOPMENT", Boolean.TRUE.toString());
            sc.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
            sc.setInitParameter("javax.faces.FACELETS_LIBRARIES", "springsecurity.taglib.xml");
            sc.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1");
            sc.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", Boolean.TRUE.toString());
            sc.setInitParameter("javax.faces.PARTIAL_STATE_SAVING_METHOD", Boolean.TRUE.toString());
            sc.setInitParameter("javax.faces.PROJECT_STAGE", "Development");
            sc.setInitParameter("javax.faces.STATE_SAVING_METHOD", "server");
            sc.setInitParameter("primefaces.CLIENT_SIDE_VALIDATION", Boolean.TRUE.toString());
            sc.setInitParameter("primefaces.FONT_AWESOME", Boolean.TRUE.toString());
            sc.setInitParameter("primefaces.THEME", "Omega");
        };
    }


text:
Q: Django Rest + React + Flutter: how to restrict domain origin of requests I am currently building a web + mobile application.
My front end is developed using React and Axios (for API call requests). It is served directly by vercel on mydomain.com
My Mobile App is developed using the Flutter
My back end is developed using Django and Django Rest. It is served with apache2 on api.mydomain.com. It only serves API endpoints.
So the front-end, Mobile app, and back-end are separated.
I would like only my front-end (mydomain.com) and flutter app to be able to make API requests to my Django Rest backend.
I would like to prevent any other domains, any clients such as postman, insomnia, curl, or any script to make API requests to my backend.
I have already set CORS in Django Rest. However, I can still make requests to the backend using curl or any other client.
Do you have any idea of what I could do to achieve this?
Thanks a lot in advance for your answers.

A: CORS is enforced only by web browsers to prevent leaking information to unrelated pages that might request it. You need some kind of access control, either by authenticating the caller or limiting access to the endpoint.
Checking the Host header with get_host() may offer sufficient protection, depending on your server setup.
get_host() will tell you the value of the Host header in the request, which is data provided by the client so could be manipulated in any way. The Host header is an integral part of HTTP 1.1 in allowing multiple domains to be hosted at a single address so you might be able to depend on your server rejecting requests that aren't actually arriving from localhost with a matching header, but it's difficult to be certain.
It would likely be more reliable to check the client's network address and reject requests from all clients except those that are specifically allowed.
Check this question too.


text:
Q: Visual Studio Code Snippets do not work with K&R style braces I am running the latest version of Visual Studio 2019. I have changed my C++ code to use K&R style braces by going to Tools > Options > Text Editor > C/C++ > Code Style > Formatting > New Lines and changing all the options to Keep on same line, but add a space before. The issue is that when I do this code snippets no longer work correctly, for example:
Normally when using Allman style braces the if code snippet would look like this:
if (true)
{

}

What I expected it to look like when using K&R style braces was this:
if (true) {

}

But what it actually looked like was this:
if (true)   {

}

This is very annoying as whenever I use a code snippet to complete an if statement, for loop or anything else I have to waste time removing the extra characters it inserts. Any help would be appreciated :)


text:
Q: MongoDB query returns 3 dots instead of answer I am following an online course on a website and when I am trying to submit a query on my local MongoDB, it returns ... instead of the answer.
The query I submit is
db.scores.find( { "type" : "essay", "score" : 50 }, { student : true, _id : false ).pretty()

A: When I had this same error, its was the result of a string value being terminated prematurely due to a ' or " in the string. Look for any extraneous quotation marks or apostrophes in the values you're adding which may interfere with the declaration.

A: The "..." that I get as an "answer" from the local MongoDB server indicates that the server is expecting from me to provide it with more input.
I clearly have a syntax error on my query, I forgot to close a curly bracket.
The correct query db.scores.find( { "type" : "essay", "score" : 50 }, { student : true, _id : false } ).pretty() does not return "..."
HINT: In case the forgotten input is not in the end of the query, but somewhere in the middle (as happened in this query) you can escape the "..." mode by hitting the "enter" two times and then try to type in the new query again.

A: Just as addition: watch out the password string. Be aware it not to contain quotation mark which interfers with quotation mark of declaration of it, like in my case. I got ... too.


text:
Q: fastest u_int64_t[8] array compare in C/C++ What is the fastest method, to compare two u_int64[8] arrays in C/C++ ?
Array 1 is inside a std::vector (~10k elements) array 2 is inside a dynamic allocated struct. (is memcmp() here false positive free?)
My (pseudo C) implementation :
typedef struct {
    u_int64_t array[8];
}work_t;

/* alloc and fill array work_t* work = new (std::nothrow) work_t etc... */

for(u_int32_t i=0; i < some_std_vector.size(); i++) {

                if((some_std_vector[i]->array[0] == work->array[0]) &&
                   (some_std_vector[i]->array[1] == work->array[1]) &&
                   (some_std_vector[i]->array[2] == work->array[2]) &&
                   (some_std_vector[i]->array[3] == work->array[3]) &&
                   (some_std_vector[i]->array[4] == work->array[4]) &&
                   (some_std_vector[i]->array[5] == work->array[5]) &&
                   (some_std_vector[i]->array[6] == work->array[6]) &&
                   (some_std_vector[i]->array[7] == work->array[7])) {
                    //...do some stuff...
                }
}

The target platform is Linux x86_64 gcc 4.9.2, the loop is inside a pthread, tcmalloc is used, and the code is compiled with -O2

A: I would imagine the only way to truly answer this question would be to write two routines, one using the loop you provided, and the other using memcmp.  Then, analyze and look at the diassembly to see which looks to be the most efficient.   (You could also be obsessive and use a profiler.)
One might also write a custom routine in assembly to compare them directly (i.e., a custom version of memcmp that works specifically for comparing exactly what you're looking at) and compare it alongside the other two as well.
Either way, I agree with the others that everything is probably going to be pretty close (with a modern compiler); however, if you really wanted to be retentive about it, you'd have to test it with a profiler and/or have the skills to look at the assembly created and know which one would be faster by sight.

A: Here are some suggestions to improve the speed.
Use Local Variables if possible
Instead of using pointers, e.g. -> operator, use local variables or pass the variables as references.  The compiler may generate extra code for loading a pointer into a register then dereferencing the the register to get the value.
Use Processor's Data Cache
Most modern processors have a data cache.  If you can load several variables with the data, then compare, you may invoke the processor's data cache.
Also, design your data to fit efficiently into a data cache line.  This means that data members (arrays included) should be next to each other or very close.
Block Compare
At the lowest level you are comparing many consecutive bytes.  As other's have mentioned, you may get better performance by using a memory compare function.
Another suggestion is to help the compiler by loading the values into separate variables, the comparing the values:
for (/*...*/)
{
//...
    uint64_t a1 = some_std_vector[i]->array[0];
    uint64_t a2 = some_std_vector[i]->array[1];
    uint64_t a3 = some_std_vector[i]->array[2];
    uint64_t a4 = some_std_vector[i]->array[3];

    uint64_t b1 = work->array[0];
    uint64_t b2 = work->array[1];
    uint64_t b3 = work->array[2];
    uint64_t b4 = work->array[3];

    if ((a1 == b1) && (a2 == b2) && (a3 == b3) && (a4 == b4))
    {
       //...
    }
}

The concept here is to load the variables first into multiple registers and then compare the registers.
Review Assembly Language & Profile
With all of the techniques presented in the answers, the best method is to code one up, review the assembly language and profile.  Remember to set the optimization levels to high for speed.
If your process has special instructions that can make this faster, you want to verify that the compiler is using them or there is justification for not using them.

A: Depending on the device you are using and compiler you are using, you can try some "specific" issues. E.g. in some compilers there are techniques that allow to perform wide load from memory and, in result of that, fastest multiple comparisons. Also there are ways to manually unroll the loop, so they are executed faster. But it depends on compiler.
You can always try some ways and check assembler code to see which way is the fastest.

A: I did some tests and looked at gcc memcmp, glibc memcmp and my code above. glibc-2.20 memcmp is the fastes way, because it uses platform specific optimisations (in my case).
gcc memcmp is much slower. (bug43052, compile with -fno-builtin-memcmp)


text:
Q: is it possible to check the authentication status of an HTTP post request before getting the response? I'm using java.net.HttpURLConnection.
I first write the body of the post request to the OutputStream associated with the URLConnection object.
After I have done that, I close the OutputStream and then call getInputStream() or getResponseCode() or getHeaderFields(). That's when I find out if the provided credentials were considered valid or not valid.
This is problematic, because I don't want to make the same post request again (and have to re-upload its contents, which could include large files) in the event that the user credentials were rejected for some reason.
Since an exception is thrown if there is an attempt to call getOutputStream() after getResponseCode() or getHeaderFields() have been called, how can I ensure that the user credentials were accepted before attempting to upload the data?
Is there a way around this or is it just the way the server is configured?

A: The short answer is: You can't do that.
Basic auth is stateless. When you're doing a POST/PUT the user credentials are sent as headers for that HTTP request. They are not processed until the entire operation is complete (i.e. after you've sent the data payload).
In order to do what you're talking about you'd need to write a web service that managed login and file/data uploading separately through session management, allowing you to first authenticate (returning a session token of some sort) then send the data via a separate HTTP request.
Edit to add: In reality, you could hack your way around this by simply doing a GET to something that also requires auth. If it succeeds, you know the POST will also succeed baring the credentials being invalidated server side between the two requests. I would not advise this, but it would work.


text:
Q: Wrap operator in RxJS so it can be applied on materialized stream I'm looking for a way to trace value 'route' among stream operators. I have a materialized stream with additional metadata on Notification object (ex. valueId property). It's definition will look something like this:
const x = stream.pipe(
  materialize(),
  map(x => Object.assign(x, {valueId: randomInt()}))
);

Now I need to wrap operators that are applied to x. Let's say I need to use map(x => x * 2), but I cannot do it like this:
x.pipe(dematerialize(), map(x => x * 2))

Because I will lose my metadata. How do I make a wrap function, that will apply to any operator and will still preserve my additional metadata?
x.pipe(wrap(map(x => x * 2)))

I thought about something like this:
function wrap<T, R>(
  operator: OperatorFunction<T, R>
): (source: Observable<TaggedValue<T>>) => Observable<TaggedValue<R>> {
  return source =>
    source.pipe(
      switchMap(x =>
        of(x).pipe(
          dematerialize(),
          operator,
          materialize(),
          map(z => Object.assign(z, { valueId: x.valueId }))
        )
      )
    );
}

But it generates fake complete messages from of().
Sample: https://stackblitz.com/edit/rxjs-fhv54p

A: The issue in your approach using of is that the complete notifications of of are materialized and passed as value to the observer of source.
Try this:
function wrap<T, R>(op: OperatorFunction<T, R>):
  (source: Observable<any>) => Observable<any> {
  return source => {
    return source.pipe(
      switchMap(x => of(x)
        .pipe(
          dematerialize(),
          op,
          map(y => ({value: y, uuid: x.uuid}))
        )
      ),
      materialize(),
      map((x: any) => Object.assign(x, {
        value: x.value ? x.value.value : undefined,
        uuid: x.value ? x.value.uuid: undefined
      })),
    )
  }
}

Demo: https://stackblitz.com/edit/rxjs-gxj7zl

A: You can do something like this
const stream$ = stream$.pipe(map((data=> ({...data, x: data.x + 1}))))

Or move it to a wrap function
const mapProp = (propName, fn) => stream$.pipe(map((data=> ({...data, [propName]: fn(data[propName])}))))

//then
const stream$ = stream$.pipe(mapProp('x', x => x+1 ))

if you want to use it for something else but map
const mapProp = (propName, fn) => stream$.pipe(
    mergeMap(data =>
      of(data[propName])
        .pipe(
           fn,
           map(newPropValue => ({ ...data, propName: newPropValue })
        )
    )
)

//Usage
const stream$ = stream$.pipe(mapProp('x', map(x => x+1)))

A: For now I've came up with an idea that "preserves" data using wrap function state. I don't really like it's 'side effect' nature, although it's safest implementation I've found so far.
export function wrap<T, R>(
  operator: OperatorFunction<T, R>,
) => (source: Observable<TaggedValue<T>>) => Observable<TaggedValue<R>> {
  return source => {
    let metadata: { stepId: number; streamId: number; valueId: number };

    return source.pipe(
      tap(
        ({ valueId, stepId, streamId }) =>
          (metadata = { valueId, streamId, stepId: stepId + 1 }),
      ),
      dematerialize(),
      operator,
      materialize(),
      map(x => Object.assign(x, metadata, { timestamp: Date.now() })),
    );
  };
}

But it's not working, because metadata is getting overridden randomly.


text:
Q: Left join retornando somente determinados campos Tenho as seguintes tabelas:
tb_agenda
id_agendaid_medicodatahora
tb_paciente
id_pacientenome_paciente
tb_medico
id_mediconome_medico
tb_agendamento
id_agendamentoid_agendaid_paciente
Faco a seguinte consulta
select * from tb_agenda as a left join tb_agendamento as b on (a.id_agenda=b.id_agenda)

Eu gostaria que me retornassem os seguintes campos: id_agendamento, hora, nome_medico, nome_ paciente

A: Seria algo mais ou menos assim:
SELECT id_agendamento, hora, nome_medico, nome_paciente FROM tb_agenda AS agenda
INNER JOIN tb_agendamento AS agendamento ON agenda.id_agenda = agendamento.id_agenda
INNER JOIN tb_paciente AS paciente ON paciente.id_paciente = agendamento.id_paciente
INNER JOIN tb_medico AS medico ON medico.id_medico = agenda.id_medico

Veja mais sobre como fazer relacionamento aqui
Existem ainda alguns adendos sobre a estrutura das suas tabelas.
Depende de qual regra de negocio pretende implementar, mas desse jeito na maioria dos casos ficaria melhor:
tb_agenda
id_agenda:int
data:timestamp
hora:time
tb_paciente
id_paciente:int
nome_paciente:string
tb_medico
id_medico:int
nome_medico:string
tb_agendamento
id_agendamento:int
fk_agenda:int
fk_medico:int
fk_paciente:int


text:
Q: Input string was not in correct format while converting string to double I saw many posts related to this problem but non of the solutions worked for me.
string d = "";
d =reader.ReadLine();
filearr1[i, j] = Convert.ToDouble(d);

in the above code I am reading lines from a file and converting them to double but it gives me this exception

"input string was not in correct format".

Data inside the file is like this: one double value per line
0.0457707
0.0297815
-0.00791904
-0.0368762
-0.0171717
0.0367319
0.0148877
0.0464597

what can be the possible problem here? and the solution ?

A: Try using the following instead of Convert.ToDouble(d)
Double.Parse(d, NumberStyles.Float, CultureInfo.InvariantCulture)

A: You need to do
Convert.ToDouble(d, System.Globalization.CultureInfo.InvariantCulture);

A: Your code shows you using variable i & j, but not how you are incrementing these.
I have used the following code to read doubles from a file and into an array.
var fileArray = File.ReadAllLines(@"c:\inputs.txt");

var doubleArray = new double[fileArray.Length];

for (var i = 0; i < fileArray.Length; i++)
{
    doubleArray[i] = Convert.ToDouble(fileArray[i]);
}


text:
Q: Direct formula for 1, -1, 2, -2, 3, -3, 4, -4,... Is it possible to create a function which takes on the values $$1, -1, 2, -2, 3, -3, 4, -4, 5, -5...$$ for the inputs
$$1, 2, 3, 4, 5, 6, 7, 8, 9, 10...$$
?
It would be nice to have a direct formula instead of a generating function, which wolfram alpha allready gave me.

A: Yes. $f(x) = (-1)^{x+1} \left\lceil\frac{x}{2} \right\rceil$ should work.

A: If you sum two consecutive terms you find alternatively $0$ or $1$; so if you sum two consecutive terms and subtract the following two, you get $0$.
Thus the sequence satisfies the recurrence
$$
a_n+a_{n+1}-a_{n+2}-a_{n+3}=0
$$
This leads to the characteristic polynomial
$$
x^3+x^2-x-1
$$
that has roots $1$ and $-1$ (double), so the general solution is of the form
$$
a_n=p+q(-1)^n+r(-1)^nn
$$
and inserting the initial conditions $a_1=1$, $a_2=-1$ and $a_3=2$ we obtain
\begin{cases}
p-q-r=1 \\[4px]
p+q+2r=-1 \\[4px]
p-q-3r=2
\end{cases}
so $p=1/4$, $q=-1/4$ and $r=-1/2$:
$$
a_n=\frac{1}{4}-\frac{(-1)^n}{4}-\frac{(-1)^nn}{2}
$$
Note that $n=0$ gives also the expected $a_0=0$.


text:
Q: Why Can I Not Create A Micro Instance Of My Newly Created AMI? I started with a 64 bit version of Ubuntu 9.10 Karmic server edition. (using a micro instance on Amazon EC2, costing less than $0.01 per hour)
I added GNOME desktop to it and NX server.
I re-bundled the instance into a new AMI.
Now upon trying to start another instance of my freshly created AMI. I am unable to select a "micro"/cheap server format.
What have I done wrong? What triggered this limitation?
Is Amazon really smart enough to know which AMIs will work on which Servers? I had it running fine on a micro server while I re-bundled it..?

A: Micro instances must be EBS backed, they cannot be AMI backed.  You will convert it.

Micro Instance 613 MB of memory, Up to
  2 EC2 Compute Units (for short
  periodic bursts), EBS storage
  only, 32-bit or 64-bit platform"

http://aws.amazon.com/ec2/faqs/#What_kind_of_hardware_will_my_application_stack_run_on

A: I'm not sure why you wouldn't be able to launch your AMI in a new micro instance but I think there's a bit of confusion here.  Just to be clear, AMI and EBS are not two different options for backing instances.  EBS and S3 are the two options for backing AMIs (from documentation located here under Using Amazon EC2 -> Using AMIs -> AMI Basics).  Your AMI is very likely still backed by EBS and, therefore, acceptable for use with a micro instance.  Something else must be going on.

All AMIs are categorized as either
  backed by Amazon EBS or backed by
  Amazon S3. The former means that the
  root device is an Amazon EBS snapshot
  and appears as an Amazon EBS volume
  when an instance is launched from the
  AMI. The latter means that the root
  device is stored in Amazon S3 and
  appears as local storage when an
  instance is launched from the AMI.


text:
Q: SQL Command Result to Dictionary C# .NET 2.0 I have a simple SQL query (using SqlCommand, SqlTransaction) in .NET 2.0 that returns a table of integer-string pairs (ID, Name).  I want to get this data into a dictionary like Dictionary<int, string>.
I can get the result into a DataTable, but even iterating over it, I'm not sure how to do the typing and all that stuff.  I feel like this must be a common problem but I haven't found any good solutions.
Thanks in advance.

A: You could try an approach similar to this, adjusted to however you're currently looping over your results:
Dictionary<int, string> dictionary = new Dictionary<int, string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                dictionary.Add(reader.GetInt32(0), reader.GetString(1));
            }
        }
    }
}

// do something with dictionary

The SqlDataReader.GetInt32 method and SqlDataReader.GetString method would represent the ID and Name column indices, respectively.

A: You can return it as a DataReader, and construct the dictionary using linq:
Dictionary<int, string> dictionary;
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader()) {
    dictionary = reader.Cast<DbDataRecord>()
                       .ToDictionary(row => (int)row["id"], row => (string)row["name"]);
}

A: You can do like this.
// Define your Dictionary
IDictionary<int,string> dictionary = new Dictionary<int,string>();

// Read your dataTable
foreach(DataRow row in dataTable.Rows) {
       // Add Id and Name respectively
       dictionary.Add(int.parse(row[0].ToString()),row[1].ToString())
}

A:     IDictionary<int, string> dict = new Dictionary<int, string>();
    DataTable mydata = new DataTable("hey");

    foreach (DataRow item in mydata.Rows)
{
    dict.Add(item["id"], item["name"]);
}

A: i did not type this in visual studio so you might need to make minor changes to make it run...
Dictionary(int key,string value) dictionary = new Dictionary<int key,string value>();

foreach(DataRow row in DataTable.Rows)
{
   //null check??
   dictionary.add(Convert.toInt(row[0]),row[1].toString());
}

try that ... see if that helps.


text:
Q: We cannot send a text message to this phone number because its operator is not supported twitter I'm trying to create twitter developer account, so adding phone no at two factor auth page. but getting We cannot send a text message to this phone number because its operator is not supported.. I've a jio connection & I'm from India. what is the solution?

A: Confirm that the phone number "40404" is not blocked on your phone.  This is one of the most commons causes of this error.


text:
Q: Spring boot run Angular2 I have an app with REST as Spring Boot Application and client as Angular2.
Earlier, I started apps separately - Spring Boot by starting SpringBootApplication main method (it started to listen on port 8080), Angular2 - running from command line npm start (it usually started on 3000 port).
Now I want Maven to run both apps with one command.

*

*Angular 4.0.0

*Spring Boot 1.5.4.RELEASE

I've been trying to apply answer and this tutorial.
But in first case starts only Angular app, is second - only REST.
My package.json:
"scripts": {
    "build": "tsc -p src/",
    "build:watch": "tsc -p src/ -w",
    "serve": "lite-server -c=bs-config.json",
    "prestart": "npm run build",
    "start": "concurrently \"npm run build:watch\" \"npm run serve --proxy-config proxy-config.json\" ",
    "lint": "tslint ./src/**/*.ts -t verbose"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/forms": "~4.0.0",
    "@angular/http": "~4.0.0",
    "@angular/material": "^2.0.0-beta.7",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",
    "@angular/router": "~4.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.26",
    "angular-in-memory-web-api": "~0.3.0",
    "angular2-modal": "^3.0.1",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "jsplumb": "^2.4.3",
    "ng2-bs3-modal": "^0.10.4",
    "ng2-popup": "^0.4.0",
    "rxjs": "5.0.1",
    "systemjs": "0.19.40",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.1.0",
    "canonical-path": "0.0.2",
    "tslint": "^3.15.1",
    "rimraf": "^2.5.4",
    "@types/node": "^6.0.46"
  },
  "repository": {}

A: I agree with sinedsem that for dev I would keep the two apps separate. As for managing a production build, I would do things slightly differently. I don't like the idea of having any manual steps involved in the build such as copying the build files from angular to the source of the spring boot app.
Instead, I would manage the whole build under maven with the angular UI and spring boot app built as separate modules. The build would be managed completely by maven, delegating the angular UI build to npm/gulp etc using frontend-maven-plugin. This can either be added as a dependency to the spring boot app of the output of the build can be copied to the target directory of the spring boot module.
Parent POM
Create a new Parent POM
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example.angularboot</groupId>
<artifactId>boot-ui-parent</artifactId>
<version>0.1</version>
<packaging>pom</packaging>

<modules>
    <module>spring-boot-app</module>
    <module>angular-ui-resources</module>
</modules>

Angular UI Module
Build the Angular UI Module using frontend-maven-plugin to execute any npm/bower/gulp etc build steps. Either set the output of your build to target/classes/static or copy the built angular resources to target/classes/static
e.g. The below plugin  installs node/npm and runs the required npm bower and gulp steps to build the Angular app.
<plugin>
                    <groupId>com.github.eirslett</groupId>
                    <artifactId>frontend-maven-plugin</artifactId>
                    <version>1.3</version>
                    <executions>
                        <execution>
                            <id>install node and npm</id>
                            <goals>
                                <goal>install-node-and-npm</goal>
                            </goals>
                            <phase>generate-resources</phase>
                            <configuration>
                                <nodeVersion>v6.10.3</nodeVersion>
                                <npmVersion>4.6.1</npmVersion>
                            </configuration>
                        </execution>
                        <execution>
                            <id>npm install</id>
                            <goals>
                                <goal>npm</goal>
                            </goals>
                            <phase>generate-resources</phase>
                        </execution>
                        <execution>
                            <id>bower install</id>
                            <goals>
                                <goal>bower</goal>
                            </goals>
                            <configuration>
                                <arguments>install --allow-root</arguments>
                            </configuration>
                        </execution>
                        <execution>
                            <id>gulp build</id>
                            <goals>
                                <goal>gulp</goal>
                            </goals>
                            <phase>generate-resources</phase>
                        </execution>
                    </executions>
                </plugin>

Spring Boop App module
This should be the same as the current spring boot module with the addition of the new parent and the dependency for the angular-ui module.
As the built version of the angular UI was packaged under target/classes/static and the angular-ui jar is on the classpath of spring boot, the angular-ui gets packaged into the spring boot application.
Alternatively, you can run the copy resources maven plugin to copy the resources from the build directory of the angular-ui module to the build directory of the spring-boot module. though I don't really like copying resource files from one module to another
e.g.
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.1</version>
<executions>
    <execution>
        <id>copy-angular-components</id>
        <phase>process-classes</phase>
        <goals>
            <goal>copy-resources</goal>
        </goals>
        <configuration>
            <outputDirectory>${project.build.outputDirectory}/static</outputDirectory>
            <resources>
                <resource>
                    <directory>${basedir}/../angular-ui/target/classes/static</directory>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </configuration>
    </execution>
</executions>

A: Your package.json is used by npm, which is not the essential tool here.
I recommend you:

*

*For development keep running two apps separately.

*For production:

*

*Pack your angular application in bundle. For example, using webpack.

*Put your bundle to to spring boot project under /src/main/resources/static.

*Run Spring Boot application, which will serve your Angular app from static resources.

A: The solution proposed by tprebs makes sense but the two maven modules are strongly coupled (because the angular module deposits files in the spring-boot module, which is not a good practice).
Keep things simple stupid, if it's a single team that develops the front end and the back end, a single maven module is enough. For example :
Single maven module approach (KISS)
Assuming that spring boot source code is in src/main/java folder and angular code is in src/main/js folder.
src/main/js/angular-cli.json file :
Serve Angular app as spring boot static resources.
{
  [...]
  "apps": [
    {
      "root": "src",
      "outDir": "../resources/static",
      [...]
    },
   [...]
  ]
}

pom.xml :
Build Angular part from maven using npm
<plugin>
    <!-- build UI angular -->
    <groupId>com.github.eirslett</groupId>
    <artifactId>frontend-maven-plugin</artifactId>
    <version>1.0</version>
    <executions>
        <execution>
            <id>install node and npm</id>
            <goals>
                <goal>install-node-and-npm</goal>
            </goals>
            <configuration>
                <workingDirectory>src/main/js</workingDirectory>
                <nodeVersion>v6.9.2</nodeVersion>
                <npmVersion>4.1.1</npmVersion>
            </configuration>
        </execution>

        <execution>
            <id>npm install</id>
            <goals>
                <goal>npm</goal>
            </goals>
            <!-- Optional configuration which provides for running any npm command -->
            <configuration>
                <workingDirectory>src/main/js</workingDirectory>
                <arguments>install</arguments>
            </configuration>
        </execution>

        <execution>
            <id>npm build</id>
            <goals>
                <goal>npm</goal>
            </goals>
            <!-- Optional configuration which provides for running any npm command -->
            <configuration>
                <workingDirectory>src/main/js</workingDirectory>
                <arguments>run-script build</arguments>
            </configuration>
        </execution>
    </executions>
</plugin>

On the other hand, if the teams are distinct I would indeed choose two separated maven modules but, in order to limit the coupling between the two modules, I will publish the angular part as webjar (See https://spring.io/guides/gs/spring-boot-cli-and-js).


text:
Q: ssh: Identical rsa key generation steps work for one user, but no another I just went through generating rsa keys so that a windows 10 laptop running cygwin can log onto a CentOS machine without a password. It works fine. The same process however didn't work for setting up password-less login for another remote user. I am still asked for the password.
The steps for the first remote user were as follows
On the Windows10 client (Cygwin):
ssh-keygen -t dsa
chmod 600 /home/John/.ssh/id_dsa
scp /home/John/.ssh/id_dsa.pub UserA@my-server.com:

On the CentOS server (logged in as UserA, from the /home/UserA/ directory):
cat id_dsa.pub >> .ssh/authorized_keys
chmod 700 .ssh
chmod 600 .ssh/authorized_keys

Those steps worked fine, but the same steps for a different remote user did not for some reason. ssh UserB@my_server.com still asks for a password after doing
the same steps for another remote user:
On the Windows10 client (Cygwin):
ssh-keygen -t dsa
chmod 600 /home/John/.ssh/user_b_dsa
scp /home/John/.ssh/user_b_dsa.pub UserB@my-server.com:

On the CentOS server (logged in as UserB, from the /home/UserB/ directory):
cat user_b_dsa.pub >> .ssh/authorized_keys
chmod 700 .ssh
chmod 600 .ssh/authorized_keys

Any idea why the same steps would cause different results like this? I verified chmod commands worked and verified that authorized_key was correctly updated

A: So the solution seems to have been that the /home/UserB folder permissions were set to 770 and needed to be 700. Also, like I had originally tried, you don't need a different id_dsa key for the other user. Simply copying the original id_dsa.pub to the /home/UserB file and continuing with the same steps works fine. If you do try to use a different dsa file, that won't work either unless you explicitly tell ssh to use it with ssh -i /home/user/.ssh/my_dsa user@server.com Apparently ssh is really picky about what permissions things are and doesn't even spit out an error message to tell you what the issue is. You have to happen to magically know that ssh logs exist somewhere to get any insight into the issue..


text:
Q: Fundamental group of a wedge sum, in general (e.g. when van Kampen does not apply) What is the fundamental group of a wedge sum in general? e.g. including the times when van Kampen cannot help us.

The Wikipedia article on wedge sums mentions that

Van Kampen's theorem gives certain conditions (which are usually fulfilled for well-behaved spaces, such as CW complexes) under which the fundamental group of the wedge sum of two spaces $X$ and $Y$ is the free product of the fundamental groups of $X$ and $Y$.

This seems strangely worded. The conditions on the space for van Kampen are that it is

*

*the union of path-connected open sets $A_\alpha$,

*each contains the basepoint,

*each intersection $A_\alpha\cap A_\beta$ is path-connected,

*each intersection $A_\alpha\cap A_\beta\cap A_\gamma$ is path-connected;

then it follows that the the kernel of $\Phi$ is the normal subgroup $N$ generated by all elements of the form $i_{\alpha\beta}(\omega)i_{\beta\alpha}(\omega)^{-1}$
for $\omega\in\pi_1(A_\alpha\cap A_\beta)$, and hence $\Phi$ induces an isomorphism $\pi_1(X)\cong \ast_\alpha\pi_1(A_\alpha)/N$.
(I fix a basepoint for the rest of this question, all wedge sums are identified at this basepoint.)
Back to wedge sums. If we are looking at the wedge sum $\bigvee_\alpha A_\alpha$ where each $A_\alpha$ is path connected, then these conditions are obviously true. And since the intersection of any $A_\alpha$ is trivial, the fundamental group of the wedge sum is the free product of the groups.
The only problem that I can see arising is when $A_\alpha$ is not path connected. The fundamental group of a disconnected space $X\cup Y$ is $\pi_1(X)$ where the basepoint falls in $X$ (correct me if I am wrong, maybe I have over-simplified this). What is the fundamental group of this wedge sum, then? I would guess that it is $$\ast_\alpha\pi_1(A_\alpha^\prime),$$
where $A_\alpha^\prime$ is the component of $A_\alpha$ containing the basepoint.  If so, then surely $\pi_1(A_\alpha)=\pi_1(A_\alpha^\prime)$, and there is no problem after all, the fundamental group is just the free product of each fundamental group. Is this correct (the fundamental group is always $\pi_1(\bigvee A_\alpha)=\ast\pi_1(A_\alpha)$)?
The simple example I scrawled on my piece of paper is below. I figure the fundamental group is
$$\pi_1(\mathsf{Green}\vee\mathsf{Blue}\vee\mathsf{Red})=\Bbb{Z}\ast\Bbb{Z}\ast C_1=\Bbb{Z}\ast\Bbb{Z},$$
which makes sense, no loop at the basepoint can be in the leftmost or rightmost components, they must be (homotopic to a loop) in the figure eight graph.

P.S. a side question, why do we use \vee for the wedge sum rather than \wedge?
Thanks in advance :-)

A: Under certain conditions they do actually mean the existence of neighborhoods, containing the common point $x_0$ of the wedge, which do retract on $x_0$.
With this condition we are able to choose suitable open path-connected sets $A_i$ to compute the desired fundamental group.
For instance if you take the $n$ wedge of circles $S^1$ at $x_0$ you can compute its fundamental group via Van-Kampen. What is important here is that we have open neighborhoods $N_i$ containing $x_0$ for each circle $S^1$ of the wedge (just imagine a little open arc on $S^1$ which contains the center $x_0$ of the wedge) which do actually retract on $x_0$ (just shrink from both sides until you reach the center $x_0$ of the wedge).
Now you can indeed define $A_i$ to be the wedge of all $N_j$ for $j \neq i$ and wedge $S^1$ i.e. $$A_i=\left(\bigvee_{i \neq j}N_j\right) \vee S^1.$$
If you now take two different $A_i$'s, i.e. $A_i$ and $A_j$ and look at the intersection $A_i \cap A_j$ you'll see that it's simply the wedge of all $n$ neighboorhoods $N_i$ of $x_0$ and since all of them retract to $x_0$ we get $$\pi_1\left( \bigvee_{i=1}^nN_i\right) \cong \pi_1(\{x_0\})=0.$$
By a similiar argument using your retracts you can compute
$$\pi_1(A_i) \cong \pi_1(S^1) \cong \mathbb Z.$$
Now by applying Van Kampen you get that the fundamental group of your wedge sum is free abelian of rank $n$.

A: Suppose $X=A_0\cup A_1$ and we have $x_0\in A_0\cap A_1$.  Now the Siefert-VanKampen Theorem states
$$\pi_1(X,x_0)\cong\pi_1(A_0,x_0)\ast_{\pi_1(A_0,x_0)\cap\pi_1(A_1,x_0)}\pi_1(A_1,x_0)$$
is an amalgam provided several assumptions are satisfied:
1) We must have that $A_0$ and $A_1$ are open in $X$.
2) We must have that $A_0$ and $A_1$ and $A_0\cap A_1$ are path connected.
Notice that this specializes to something like the following:
Suppose $X=A_0\cup A_1$ where $x_0\in A_0\cap A_1$ and $A_0$, $A_1$, and $A_0\cap A_1$ are open, path-connected subspaces of $X$.  If $A_0\cap A_1$ is simply connected, then $\pi_1(X,x_0)\cong\pi_1(A_0,x_0)\ast\pi_1(A_1,x_0)$.
Now condition (1) explains why we need to be careful about wedge products; the subspaces $A_0$ and $A_1$ must be open in $X$.  Thus your desired result about fundamental groups of wedge products has the following formulation for a sufficient condition:
Let $X=\bigvee_{\alpha}A_\alpha$ be a finite wedge product of spaces $A_\alpha$ at $x_0$.  If $x_0$ has a simply connected open neighborhood $U$ such that $U\cup A_\alpha$ is open for all $\alpha$ and $A_\alpha\cap U$ is path connected, simply connected and open for all $\alpha$, then $$\pi_1(\bigvee_\alpha A_\alpha,x_0)\cong\ast_\alpha\pi_1(A_\alpha,x_0)$$
This can be proved using induction and the stated version of the SVK Theorem above.
As for wedge-versus-vee, that seems to be an unfortunate product of historical stuff...


text:
Q: Creating an update script from Oracle using TOAD In Oracle, using TOAD, we are able to create an insert script from a table.
However, I need to create an UPDATE script based on the values of each row
where the CLIENTID is 'blah blah'

Originally, what I did was create an Excel spreadsheet with all the necessary data and for each row, I pasted a
UPDATE TABLE BLAH BLAH SET COLUMN1 = "xxx", COLUMN2 = '' where CLIENT_ID = "123'

..but I ran into some difficulties with exporting the spreadsheet into a text based DOS file and converting it to a .sql as so to edit but it was messy and unpredictable.
Has anyone have a better idea I can implement?

A: I haven't seen any feature in Toad that helps write update queries in this fashion. But loading data directly is something that Toad makes very easy.
May be you could do this.
create table tmp_excel_data
( column1 varchar2(100),
  column2 varchar2(100),
  client_id varchar2(100)
);

Use toad to directly load data into this table. The update is simple from this point.
update CLIENT_DATA tgt
  tgt.column1 = (select column1
                  from tmp_excel_data src
                  where tgt.client_id = src.client_id);

--dont forget to commit.

This will also let you cleanse your data (removing dups..for example) if needed.

A: I usually do something like this:
SELECT 'UPDATE <TABLE_NAME> SET status =''' || status || '''  WHERE id =' || ID ||';'
FROM <TABLE_NAME>
WHERE <condition>

A: Use the button. Its ugly but it works.


text:
Q: AJAX form submitting the wrong row from dynamically generated rows of data I am currently reading data from a database and displaying the returned data in a table. One column contains the ID of each row, which I pass to a modal like this:
<a href=".user_id<?php echo $row['id']; ?>" data-toggle="modal" title="View and Edit User"> Edit

The modal gets data from another php file I included, using:
require('user_info.php');

The right data for each row is displayed on the modal, as I 'GET' the id passed into the modal, and query the database and display the returned info on a form on the modal. I have been careful to use classes in identifying the form elements, as I intend to submit the form using AJAX. Part of the form is:
<form method="POST" action="">

    User ID

        <input name="userid" type="text" class="form-control userid" value="<?php echo $prow['id'];?>">

        Name
        <input name="name" type="text" class="form-control" value="<?php echo $prow['fullname'];?>">

        Folder
        <input name="folder" type="text" class="form-control" value="<?php echo $prow['folder'];?>">

    <input type="submit" class="btn form-control modify_user_info" value="Submit Modification">

The problem now is, no matter which row on the original table I edit and submit through a modal, it is the first row of the table that attempts to get edited. The modals display the right information based on the row selected, but submitting the form on the modal always returns the data on the first row to the php file handling the form submission.
Here's my javascript:


text:
Q: How long will it take me to find the starting weapons I don't choose? Before your first mission after the opening mission, I'm given the choice of four weapons:

*

*Stun Gun

*Tranquilizer Rifle

*Combat Rifle

*Revolver

One factor I'm considering is how long it will take my to find the weapons I do not choose, since ideally I would like to get my hands on them all at some point.
How long into the game am I able to retrieve each of these weapons?

A: *

*Stungun - You can find one after completing the first mission. It's in a storage locker locked in an alleyway near Jensen's apartment. A hacking level of two is required to open it.

*Tranq - There are a couple of storage lockers in Detroit, also see the arms dealers.

*Combat Rifle - Soldiers and better armed gang members. Also look in your apartment for a few.

*Revolver - Some soldiers at the Milwaukee Junction factory may have them. I know they are found in Highland Park for sure though. (thanks @ArdaXi).

A: The combat rifle is probably the easiest to get to. Almost every soldier, even at the start, will carry one.
A revolver is also carried by some soldiers, but less frequently, so I would put that on number two. It still won't take too long into the game though.
The first I've seen a stun gun was also somewhere in the early game, when I started for pacifist.
Seeing as I've had a tranquillizer rifle from the start, I've never bothered to look for one, but they are also present quite a bit in the first few missions.
To sum up, I don't think you'll have to wait long for any of the weapons, but the ones for up close are going to take a bit longer than the ones with distance.


text:
Q: Fade in effect for new created elements I know that there is a JQuery function name fadeIn() and have search some information how to used that. On W3Schools I've read this:

The jQuery fadeIn() method is used to fade in a hidden element.

But I'll use that function for elements that I've just created to fade in, it's not hidden! Is there a way to make the same effect for new created elements? Here is some code to play whit it:
$("#resultaatArtisten").append(
    '
' +
        '<input type="hidden" value="' + var1 + '"/>' +
        '
' +
            '' +
        '
'+
        '
' + name + '
' +
    '
'
);

A: In the first div tag you could add style="display:none", or you can add display:none; to your .option-item in your CSS file.
Edit
It is recommended that you add the display property into your CSS file.
.option-item{display:none;}

A: Try this:
$("#resultaatArtisten").hide().append(
    '
' +
        '<input type="hidden" value="' + var1 + '"/>' +
        '
' +
            '' +
        '
'+
        '
' + name + '
' +
    '
'
).fadeIn();


text:
Q: Implementing flowchart type workflows in java We have a service that processes requests, it receives. Workflow for processing each request contains many steps, branches depending on some conditions(intermediate variable etc, result from some service call). Basically whole workflow can be written as a big flowchart.
Currently, my implementation contains lots of big If-else blocks. In each block, there are again many if-else sub blocks and so on. This code is very hard to manage and develop on. For instance if some new step/branches gets added in flow chart, Making corresponding code changes and testing those changes very painful.
Do there exist some libraries, that can be used in such situation? I have heard of Amazon Simple Work Flow, but can that be used here?

A: I know that drools flow, http://www.jboss.org/drools/drools-flow allows modelling work-flows as flow graphs and it is Java based and has an eclipse plugin for graphical flow modelling.
Drools flow has been merged into jBPM5 http://www.jboss.org/jbpm/ which is a similar project.


text:
Q: Ring of differentials Is this true that if $A$ and $B$ are $R$-algebras, where $R$ is a commutative ring, then
$$\Omega^1_{A \otimes_R B/ R} \simeq A \otimes_R \Omega^1_{B/R} \oplus B \otimes_R \Omega^1_{A/R}.$$
If it is true I struggle to prove it.


text:
Q: OxyPlot MajorStep is always start 0? this is my sample code.
var linearAxisX = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                MajorStep = 0.3,
                StringFormat = "F1",
                IsZoomEnabled = false,
                IsPanEnabled = false,
                MinorTickSize = 0,
                MajorGridlineStyle = LineStyle.None,
                MajorGridlineColor = OxyColor.FromArgb(40, 0, 0, 139),
                MinorGridlineStyle = LineStyle.None,
                FontSize = 10,
                MaximumPadding = 0.1,
                MinimumPadding = 0.1
            };

I thought it would be possible to apply Maximum, Minimum to 3.5, 4.4.
but start from 3.3.
I think MajorStep always starts at zero.
data is
(3.5, 10)
(3.8, 10)
(4.1, 10)
This is the chart I want.
Is this impossible?
thanks.


text:
Q: Using `void_t` to check if a class has a method with a specific signature At the moment, I'm using this method to check if a class has a method with a specific signature.
After attending Walter E. Brown's metaprogramming CppCon2014 talk, I started wondering if void_t could be used in this particular situation to make the code cleaner and more readable.
However I'm having trouble thinking in terms of  void_t - so far I understand that void_t can help me determine at compile-time whether or not an expression is valid.
Example:
template< class, class = void >
struct has_type_data_member : false_type { };

template< class T >
struct has_type_data_member<T, void_t<decltype(T::data)>> : true_type { };

If decltype(T::type) is a valid expression, has_type_data_member<T> will be a true compile-time constant. Therefore, we are sure that T has a member field called data.
I want to use the same approach to check if a type T has a method with a particular name and a particular signature.
Let's say I want to check if T has a method called getCount() that returns int. This is what I expected to work ((Ideone.com link)):
template< class, class = void >
struct hasGetCount : false_type { };

template< class T >
struct hasGetCount<T, VoidT<decltype(T::getCount)>>
: std::is_same<decltype(std::declval<T>().getCount()), int>::type { };

Unfortunately, the static_assert tests do not pass.
What am I doing wrong? Is it possible to use void_t in this situation?
Bonus questions:

*

*How can I also check if the method signature is equal to a signature the user passes as in the original implementation?

*I can use macros to define these kind of helper structs like this:
 DEFINE_METHOD_CHECKER(hasGetCount, getCount);
 // ...
 static_assert(hasGetCount<ClassWithGetCount>::value == true, "");

Is it possible to avoid having to define a struct first then check the struct's value?         I mean, is it possible to use a macro to write something like this? Example:
 static_assert(CHECK_METHOD(ClassWithGetCount, getCount)::value == true, "");

A: First, an id-expression naming a nonstatic member function can't be used as an unevaluated operand (such as the operand of decltype). Moreover, you should check for whether the entire function call expression is well formed, not just whether there is a member called getCount:
template< class, class = void >
struct hasGetCount : false_type { };

template< class T >
struct hasGetCount<T, VoidT<decltype(std::declval<T>().getCount())>>
: std::is_same<decltype(std::declval<T>().getCount()), int>::type { };

(Use declval<T&> if you want to check that getCount() can be called on an lvalue.)
If you just check for the existence of a getCount member, then you get a hard error if a member with that name exists but isn't callable (e.g., a data member).
Although at this point you might as well consider just using something like
template< class T >
struct hasGetCount<T, std::enable_if_t<std::is_same<decltype(std::declval<T>().getCount()), int>::value>> : std::true_type { };

instead of writing the decltype twice.

A: You could use void_t to easily verify that the return type of getCount is convertible to int:
template< class, class = void >
struct hasGetCount : false_type { };

template< class T >
struct hasGetCount<T,
  VoidT<
    decltype(std::declval<int&>() = std::declval<T>().getCount())
  >> : std::true_type {};

(Ideone live code)
Hopefully, by the time C++17 comes out, we'll be able to do this more easily with Concepts Lite:
template <typename T>
concept bool hasGetCount = requires (T t) {
  { t.getCount() } -> int;
};

A: If you also want to check for the parameters to the function and its return type, similar to what Casey suggested
template<typename... > struct Voider { using Type = void; };
template<typename... TArgs> using void_t = typename Voider<TArgs...>::Type;

template<class, typename, class = void>
struct hasGetCount : false_type { };

template< class T,  typename Ret, typename... Args>
struct hasGetCount<T, Ret(Args...),
    void_t<decltype(std::declval<Ret&>()
        = std::declval<T>().getCount(std::declval<Args>()...))
          >> : std::is_same<
               decltype(std::declval<T().getCount(std::declval<Args>()...)),
               Ret>::type {};

Usage:
class A {
public:
    int member;
    int getCount() {return 0;}
};
static_assert( hasGetCount<A, int(void)>::value , "A" );


text:
Q: Macbook Air screen fading randomly between off and full brightness My Macbook Air (2015 model, High Sierra) screen is dead most of the time but randomly fades in and out. Sometimes it fades rapidly in and out non-stop for a prolonged period, before fading out entirely. The backlight is not dead - it works but is impossible to control.
Please see this video for a demo of the issue.
Does anyone know the cause, or solution?

A: Could be hardware, overheating or simply a stuck function key. I would try cleaning it (especially between the screen and the base where the vent is) and making sure keys are not gummed up. Then test the hardware using
https://support.apple.com/en-us/HT201257 pre June 2013 version or
https://support.apple.com/en-us/HT202731 post June 2013
Jonah

A: This is a physical issue.
It could be something as simple as the LVDS connector with corrosion on it that needs cleaning or it's a possible there's cold solder joint or a failing component (possibly both).  Only guessing (since I don't have the unit in front of me to test), I would say that it's the 12V power rail that supplies the display that's the source of the problem.
To further diagnose the problem, hook it up to an external monitor.  If the problem doesn't manifest on the monitor, the issue has to do with the display and not the GPU.
You will need to take this in for service.  If you have Apple Care, this should be covered.  If not, you may have some luck with the Apple folks who may service it out of warranty.


text:
Q: Remove class, but slowly? So I am using jQuery to remove a class from an element, but it does it immediately. What I'd like is to have the class fade out smoothly, not so harsh.
This is the code I tried, which is not fading out at all:
    $(function() {
$( "a.engine" ).click(function() {
  $( "img.bg" ).removeClass( "intro_effects", 1000 );
  });
});

Any hints as to how to make this fade out?
Thanks much!
* HERE IS THE SITE
http://dev.mediaslave.ca/illustraflex/
Thanks again!

A: You'll need to use .animate to change the css properties, and then use .removeClass when the animation is complete.

A: $("a.engine").click(function() {
    $("img.bg").fadeOut( "slow", function() {
        // Animation complete
    });
});

A: jQuery UI lets you do that with its removeClass: http://jqueryui.com/removeClass/

A: Rather than using removeClass, try using fadeOut instead. Something like this should work for you:
$(function() {
  $( "a.engine" ).click(function() {
    $( "img.bg" ).fadeOut();
  });
});

A: Classes are not properties with transitions. They are either on, or they are off. So if you want something to fade out AND remove the class, you simply need two different commands... like so:
$(function() {
    $("a.engine").click(function(){
        $("img.bg").fadeOut(1000, function(){$(this).removeClass("intro_effects", 1000)});
    });
});

See it in action here:
http://jsfiddle.net/Y92qu/1/

A: This CSS should animate the properties when you change the class, and you can control it with the transition duration property.
img.bg {
    transition-property: all;
    transition-duration: 1s;
}


text:
Q: How does one sample a random walk on a circle with a Gaussian step size in R or Python? I am trying to obtain samples of a random walk on a circle that takes steps according to N(0, \sigma). To do this for a discrete random walk one calculates the cumulative sum of {+1,-1} coin tosses and then does mod the number of states on the circle at each step to obtain the current position. My question is: how to modify this for the continuous case?
Thanks in advance if anyone can help!

A: If the N(0,sigma) step distribution refers to the distribution of arc lengths around the circle, then
 cumsum(rnorm(n,0,sigma)) %% (2*pi)

should give a sample of the steps on the circle (in radians), starting from zero.


text:
Q: Flow Error Occured "The flow failed to access the value for" I am getting this flow error,while updating field in process builder:
This error occurred when the flow tried to update records: The flow failed to access the value for myVariable_current.RecordType.Name because it hasn't been set or assigned..

A: I'm assuming the right-hand-side of this image would show that you're assigning the reference to the Record Type Name of that SymphonyIPM__ record. This issue will occur when that object's Record Type is null, because in trying to reach the record type's name you're actually traversing a join:
(my object)->RecordType via RecordTypeId->Name

When RecordTypeId is null, this results in an exception.
This isn't actually the right way to assign an object's record type in Process Builder, however. Instead of assigning the Record Type Name, simply assign the RecordTypeId directly. That will work even if your source record has a null record type.


text:
Q: Spock rightShift (mocking) operator apparently not working Here is my Spock unit test:
def "when favorite color is red then doSomething produces empty list of things"() {
    given:
    FizzBuzz fizzBuzz = Mock(FizzBuzz)
    fizzBuzz.name >> 'Dark Helmet'
    fizzBuzz.attributes >> [:]
    fizzBuzz.attributes["favcolor"] >> 'red'
    fizzBuzz.attributes["age"] >> '36'

    Something something = new Something(fizzBuzz)

    when:
    Whoah whoah = something.doSomething()

    then:
    !whoah.things
}

And here is the FizzBuzz mock:
public interface FizzBuzz extends Serializable {
    Map<String, Object> getAttributes();
}

When I run this I get:
java.lang.NullPointerException: Cannot invoke method rightShift() on null object

at com.commercehub.houston.SomethingSpec.when favorite color is red then doSomething produces empty list of things fail(SomethingSpec.groovy:18)

Process finished with exit code 255

The 'null object' its referring to on Line 18 is either fizzBuzz or its attributes map. Why?

A: You're attempting to use multiple levels of indirection, and the >> is getting applied to the result of .attributes["favcolor"], which is null (since .attributes is an empty map). Instead, just initialize the map:
fizzBuzz.attributes >> [favcolor: 'red', age: 36]

(Also, did you really mean age to be a string?)

A: In my case, I realized I was accidentally declaring the result of the when block.
when:
Whoah whoah = something.doSomething() >> expectedResult


text:
Q: Is there a way to reverse engineer a stored procedure and retrieve table and column names without executing the code? I have a stored procedure in my SQL Server database, and I need to collect the table and column names used in it without actually executing the code.  Is there an easier way to reverse engineer the stored procedure and retrieve the table and column names without executing the code?
I appreciate any help or suggestions on this matter. Thank you.
I know that I can use sp_depends to get the dependent objects of the stored procedure, but it only returns the names of the tables and not the column names.

A: If the stored procedure is encrypted or internally not implemented in sql (e.g. .NET C#) there is no chance for reverse engeneering. If this is not the case the system stored procedure sp_helptext is your friend.
exec sp_helptext procname        -- procedure resides in standard schema, normally dbo
exec sp_helptext 'test.procname' -- procedure resides in schema test

In SSMS you could also navigate to  -> Programmability -> Stored Procedures. Here you have to localize the procedure you are interested in and press right-mouse-button for the context menu. Here you have to choose 'Script Stored Procedure as'. But internally the sp_helptext is used too.


text:
Q: Javascript event on form add fields I've got a rails app using bootstrap with a form page that has the option to add additional form fields. The tutorial from this Railscast episode heavily influenced this form page add fields feature. I have a need to watch the add fields so that I can hide a warning panel in the new well created. Here is the code that will not work(in coffeescript):
  $('#classifications_forms').on 'change', (event) ->
     container = $('.classifications_form').last()
     $('#premium-divide', container).hide()

Here is the code in jquery:
$('#classifications_forms').on('change', function(event) {
  var container;
  container = $('.classifications_form').last();
  return $('#premium-divide', container).hide();
});

I have tried an on click event for the add fields button, but it's late in the event watching as it will not hide the panel. If I hit the button a second time, it will hide the panel on the previously created well, so I know the code was working to hide the panel. My thinking is to hide the panel on the last well created, and I thought that a change on #classifications_forms would give me the event needed to hide the last well, but I guess its missing something on the event. What is missing above?
Here is a jsfiddle demonstrating the problem.

A: Because I was using bootstrap, I found a class to apply to the panel which took care of my problem:
.hidden


text:
Q: TextInput with typing digits from right to left and adding zeroes automatically for money input I'm trying to implement TextInput with typing digits from right to left and adding zeroes automatically while user is typing. Any ideas how to implement this correctly?
The expected behavior should look like this.

What I have right now:
 constructor(props) {
    super(props);
    this.state = {
      payrate: '',
    };
  }

  handleTextChange = (text) => {
    const newAmount = parseFloat(text/100);
     this.setState({
       payrate: newAmount,
     })

 <TextInput
         autoFocus
         style={[styles.textInput]}
         value={payrate}
         placeholder="0.00"
         maxLength={9}
         keyboardType="numeric"
         placeholderTextColor="#adecf5"
         onChangeText={this.handleTextChange}
         underlineColorAndroid='rgba(0,0,0,0)'
         autoCapitalize="none"
         selection={{start: cursor, end: cursor}}
         />

A: We use react-native-masked-text for that, works decently. https://github.com/benhurott/react-native-masked-text/blob/master/README.md


text:
Q: My Visual Studio 2010 IDE keeps opening when closed, why? I'm having problems with the IDE since it keeps opening when I tried to closed it. Do you have the same problem and solution for that?
Edit
I recently install hotfixes:

*

*[crashes on shutdown] VS10-KB2275326-x86

*[insufficient memory bug when copy-paste] VS10-KB2251084-x86

*[search box increased size bug] VS10-KB2268081-x86

*[unnescessarily scrolling in context menus] VS10-KB2345133-x86

A: Try to use this hotfix KB2275326 – The Visual Studio 2010 development environment crashes on shutdown

A: There's a checkbox in visual studio 2010 that asks if it should restart automatically when it crashes. So if its crashing then this is the expected behavior but if its opening after you click the exit button i have no idea about its cause.


text:
Q: Minimax and Connect 4? Principal Variation Searches are commonly implemented in chess AI algorithms. Can this algorithm be used when using Minimax to place Connect 4?
If so, how? I thought about this for a while, but could't figure out how the PVS could be applied to Connect 4.
Thanks.

A: There is nothing special about connect 4. PVS is a very simple modification of alpha-beta algorithm which can be applied to any game (turn-based, full information etc. but connect4 fullfills all the assumptions).
So the answer is "it can be usde, in the exact same form as always".
For more details, including pseudocode and long discussion you can look it up here

A: A really nice Tutorial about Connect 4 and how to implement a PERFECT connect 4 AI with Minimax/Negamax: http://blog.gamesolver.org/
.
EDIT: as Blastfurnace mentions. I forgot to mainly answer the question.
So Yes Minimax can be used for connect for i personally would use NegaMax but it's only a small optimization.
And HOW you could implement Minimax is described in the link above.


text:
Q: Zebra RW420 CPCL font issue I've designed a label with Label Vista (free Zebra software) and I went  watching at the generated CPCL code, I noticed:
_TTF -23 0 0 400 0 0 0 0 2 34 [Arial] 117 16 Test TTF string
T Ari06pt.cpf 0 118 45 Test Uploaded font string

I've uploaded to the printer the Ari06pt.cpf generated font.
Then I've tried to print from Label Vista and all went OK! IT WORKS!
After that I've passed the code to my android application (JAVA with Zebra SDK) and I've tried to print, but in this case only the
"T Ari06pt.cpf 0 118 45 Test Uploaded font string\r\n"

works right.... the first line (_TTF) is NOT WORKING anymore (white line was printed)...
Some solution?

A: According to CPCL manual:
_TTF -23 0 0 400 0 0 0 0 2 34 [Arial] 117 16 Test TTF string

is not a CPCL command. However, LabelVista creates for some reason (??) this command using resident TrueType fonts of your desktop OS and converts it silently in printing time to a CPCL "T" command like that:
T Ari06pt.cpf 0 117 16 Test TTF string

So I think that you should check LabelVista output if it contains commands other than CPCL. You can also try ZebraDesigner editor.
I have worked with Zebra MZ320 and QL420+ and they accept only prescaled fonts (*.cpf files) in their memory. So try to convert a TrueType font to a prescaled font. You can convert it using LabelVista or Zebra Font Downloader and then upload it to your printer. You can follow this Zebra font convertion guide.


text:
Q: При формировании формы ajax, на самбмите нет переменной Есть некая форма. В ней 3 зависимых селекта. При выборе последнего, формируется формируется массив текстовых инпутов feature[*]. (

<input type="text" name="feature[]" value=""

)
При сабмите формы, во входящем посте переменной feature нет.
Есть ли нюанс какой нибудь в ХТМЛ, что пришедшая часть формы аяксом потом не будет видна между тегами <form></form?>
Пришедший из ajax html вывожу на страницу $('#features_list').html(data);
UPD. Прописал для формы id="item-edit" и для каждого возвращаемого инпута form="item-edit" и заработало.
A:
При сабмите формы, во входящем посте переменной feature нет.

Для начала надо проверить есть ли небходимые данные данные на посте на клиенте, если да то они просто не биндятся на сервере

Есть ли нюанс какой нибудь в ХТМЛ, что пришедшая часть формы аяксом потом не будет видна между тегами <form></form?>

кажись таких ограничений нету, и постится будет все что имеет атрбут name внутри формы


text:
Q: Cannot connect to API: Should I use websocket or something else? I have this API: http://developers.xstore.pro/documentation/2.2 which says:
Communication with the xStation API
There are two IPs, that can be used interchangeably:

*

*xapia.x-station.eu

*xapib.x-station.eu

Here are the addresses of DEMO and REAL servers:

*

*DEMO: main port: 5124, streaming port: 5125

*REAL: main port: 5112, streaming port: 5113.

Both servers use SSL connection.
I'd like to login to my account but I just don't know how to connect to this API. I figured, the right way might be to use websocket which I've never used before...
websocket = new WebSocket("ws://xapia.x-station.eu:5124");

...but didn't even connect to server.
Could anyone provide me with some simple example or at least point me to right direction? This is completely new to me and don't know where to start.

A: I'll make this into an answer since it looks like it answers your question.
The API you refer to looks like it uses a plain SSL TCP connection (not a webSocket) and you must send requests as properly formatted JSON. If you were connecting to this API, you would use a plain socket as described in the nodejs Net module.

Cannot connect to API: Should I use websocket or something else?

You should be using a plain TCP socket, not a webSocket.  A webSocket is a higher level protocol that runs on top of a TCP socket.  It can only connect to a webSocket server.


text:
Q: NDSolve w/ vector-valued function doesn't work with addition of outside function? I'm trying to use Mathematica to solve a problem of orbits, specifically solving for the trajectory of a spacecraft moving near the Earth and Moon. I assume that the Earth is fixed at the center of the system and the Moon revolves around it, then model the motion of the spacecraft using a vector {x,y,z}. Unfortunately, NDSolve throws an error when I try to account for the gravity caused by the Moon. If I only include the terms for the Earth's gravity, it works perfectly, but it fails otherwise. Below is the code I used:
M[t_] = {rm Cos[((2 Pi)/pm) t], rm Sin[((2 Pi)/pm) t], 0.}
orbit = NDSolve[
   {l''[t] == (G me (-l[t]))/(Norm[
          l[t]]^3) + (G mm (M[t] - l[t]))/(Norm[M[t] - l[t]]^3),
    l[0] == p0,
    l'[0] == v0}
   , l[t], {t, 0, tmax}, MaxSteps -> 1000000,
   Method -> "StiffnessSwitching"];

All of the constants here (rm, pm, G, me, mm, tmax) were defined before running this cell. I'm new to Mathematica and don't quite understand what's going wrong. This is the relevant error:
NDSolve::ndfdmc: Computed derivatives do not have dimensionality consistent with the initial conditions.