问:
Converting a year from 4 digit to 2 digit and back again in C#
My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:

I put a DropDownList of the 4-digit year on the page.

I validate the expiration date in a DateTime field to be sure that the expiration date being passed to the CC processor isn't expired.

I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.

Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the DateTime object. Or should I just keep processing it as I am?

答:
The answer is already given. But here I want to add something.
Some person told that it did not work.

May be you are using

DateTime.Now.Year.ToString("yy");

that is why it is not working. I also made the same the mistake.

Change it to

DateTime.Now.ToString("yy");

OwnerDisplayName: Mike Wills

LastEditorDisplayName: Seb Nilsson


来源: stackexchange

问:
Default initialization vs. copy initialization from default-constructed value
Let thing be a default-constructible and move-constructible type. Consider the following two initializations:

```<code>thing t1;          // (1)
auto t2 = thing{}; // (2)
</code>```

(1) default-constructs t1.

(2) default-constructs a temporary of type thing and moves it into t2.

Under which circumstances will the move in (2) be elided?

In modern style C++ initializations, the type usually either doesn't appear at all or appears on the right. For example:

```<code>auto copy = vec;                              // Type doesn't appear

auto p_derived = std::make_unique<derived>(); // Type appears naturally on the right

// Putting the type on the right here makes it explicit that the upcast is intended
auto p_base = std::unique_ptr<base>{ std::make_unique<derived>() };
</code>```

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

Does that mean that (2) is preferable over (1) for the sake of consistency?

答:
Which is preferable is a matter of opinion.  I will not weigh in, that is not what SO is for.

Every modern compiler that supports C++11 will elide that move, unless you pass explicit compiler flags to never elide things.

In C++17 there is no move to elide; the thing{} is a prvalue, and prvalues are not objects in C++17 but rather instructions to create objects (which may instantiate an anonymous temporary object, but not in this case).

The auto x = prvalue ; statement causes the prvalue instructions to be used to construct x.

ContentLicense: CC BY-SA 3.0

Body:
Let thing be a default-constructible and move-constructible type. Consider the following two initializations:

thing t1;          // (1)
auto t2 = thing{}; // (2)

(1) default-constructs t1.

(2) default-constructs a temporary of type thing and moves it into t2.

Under which circumstances will the move in (2) be elided?

In modern style C++ initializations, the type usually either doesn't appear at all or appears on the right. For example:

auto copy = vec;                              // Type doesn't appear

auto p_derived = std::make_unique<derived>(); // Type appears naturally on the right

// Putting the type on the right here makes it explicit that the upcast is intended
auto p_base = std::unique_ptr<base>{ std::make_unique<derived>() };

Using (2) would be consistent with those styles, whereas using (1) wouldn't.

Also, when using (1) with a long typename, the variable name appears far on the right. When using (2), the variable name is equally appparent no matter how long the typename is.

Does that mean that (2) is preferable over (1) for the sake of consistency?


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答:
A lot of good advice has already been given.  Here's two more points to add:

1 - Never ever store a password in plain-text.  Salt it, hash it with a cryptographically secure hash, and store the salt/hash.

2 - Store date/time in UTC and convert to desired timezone at the presentation layer.  (I always store datetime as a unix timestamp, but that's just my preference.  Nothing wrong with the mysql DATETIME.)

I would recommend that you test your design before you fully commit to it, and write an entire application around it.  Push your design up to a real mysql database and and write a few quires to make sure you can add and retrieve all the info that you want.  Once you have your quires functioning write a script to load the database with lots(hundreds of thousandths to millions of records) and run your quires again.  This is the best way to test out your design. When you only have few hundred records, pretty much any query will be quick.  Once your database hits critical mass and no longer fits in ram you will you really be able to tell if your design and indexes are optimized for your intended use.

ContentLicense: CC BY-SA 2.5


问:
PROCEDURE does not work
```<code>create  or replace procedure pr_empleados is
cursor cur_empleados is
  SELECT RUT_EMPLEADO ,
      sum(monto_total),
      SUELDO_BASE,
      TO_CHAR(FECHA_FACTURA,'MM') "MES_PAGO",
      TO_CHAR(FECHA_FACTURA,'YYYY') "AÑO"
  FROM EMPLEADO FULL JOIN FACTURA USING (RUT_EMPLEADO)
    GROUP BY
      RUT_EMPLEADO,TO_CHAR(FECHA_FACTURA,'MM') ,
      TO_CHAR(FECHA_FACTURA,'YYYY'),
      SUELDO_BASE;
      V_BONIFICACION INT:= 0;
     V_SUMA NUMBER;
    V_COMISION NUMBER ;
    REG_EMPLEADOS CUR_EMPLEADOS%ROWTYPE;
 BEGIN
  FOR REG_EMPLEADOS IN CUR_EMPLEADOS
    LOOP
    select  sum(monto_total) into  V_SUMA
    from factura;
     IF  V_SUMA  > 100000  and  V_SUMA <= 300000 THEN
           V_COMISION := ROUND(V_SUMA * 0.1);
    ELSIF  V_SUMA  > 300000  and  V_SUMA  <= 500000 THEN
        V_COMISION := ROUND(V_SUMA  * 0.15);
    ELSIF  V_SUMA   > 500000  and  V_SUMA  <= 700000 THEN
        V_COMISION := ROUND(V_SUMA  * 0.2);
    ELSIF  V_SUMA > 700000 AND V_SUMA <= 1500000 THEN
        V_COMISION :=  ROUND(V_SUMA  * 0.25);
    END IF;

    V_BONIFICACION :=  ROUND((V_COMISION +  REG_EMPLEADOS.SUELDO_BASE)*0.085);
    INSERT INTO BONIFICACIONES VALUES(REG_EMPLEADOS.RUT_EMPLEADO,
                                      REG_EMPLEADOS."MES_PAGO",
                                      REG_EMPLEADOS."AÑO",
                                      V_COMISION,
                                      V_BONIFICACION);
     END LOOP ;
     END Pr_Empleados;

     exec pr_empleados;
</code>```

答:
PL/SQL does not automatically commit for DML statements
such as INSERT.

Where are you committing the transaction?

Title: PROCEDURE does not work


问:
How to compare two hash sets in java?
How can I compare two hash sets in java ? My first hash sets looks like below.

```<code>static Set<String> nounPhrases = new HashSet<>();
</code>```

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

```<code>static Set<String> nounPhrases2 = new HashSet<>();
</code>```

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

答:
This is a wheel already invented.

Set#equals() compares sets in the way you would expect:

```<code>set1.equals(set2)
</code>```

If you want two Set variables that are both null to be "equal", then use:

```<code>Objects.equals(set1, set2)
</code>```

Title: How to compare two hash sets in java?

Body:
How can I compare two hash sets in java ? My first hash sets looks like below.

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

Body:
This is a wheel already invented.

Set#equals() compares sets in the way you would expect:

set1.equals(set2)

If you want two Set variables that are both null to be "equal", then use:

Objects.equals(set1, set2)


问:
Spring Boot Constructor based Dependency Injection
I'm a beginner with Spring Boot and Dependency Injection and I can't get my head around Constructor based Dependency Injection in Spring Boot. I have class called ParameterDate that look like this:

```<code>public class ParameterDate {

    private Date parameterDateUnadjusted;
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}
</code>```

I have another class where I want to use ParameterDate. Normally I would do Field based Injection with

```<code>@Autowired
ParameterDate parameterDate;
</code>```

And where ever needed I just use parameterDate.

How would I do this with Constructor based Injection?

答:
```<code>public MyClazzRequiringParameterDate(ParameterDate parameterDate){
     this.parameterDate = parameterDate;
}
</code>```

Since Boot 1.4 @Autowired has been optional on constructors if you have one constructor Spring will try to autowire it. You can just tag the constructor with @Autowired if you want to be explicit about it.

Generally speaking you should favour Constructor > Setter > Field injection. Injecting directly to the field misses the point of DI, it also means your tests are reliant on Spring to inject dependencies into rather than just being able to pass mocks or stubs directly to it. Jurgan Holler has stated that he would remove field injection if at all possible.

Body:
I'm a beginner with Spring Boot and Dependency Injection and I can't get my head around Constructor based Dependency Injection in Spring Boot. I have class called ParameterDate that look like this:

public class ParameterDate {

    private Date parameterDateUnadjusted;
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;
}

I have another class where I want to use ParameterDate. Normally I would do Field based Injection with

@Autowired
ParameterDate parameterDate;

And where ever needed I just use parameterDate.

How would I do this with Constructor based Injection?

Body:
public MyClazzRequiringParameterDate(ParameterDate parameterDate){
     this.parameterDate = parameterDate;
}

Since Boot 1.4 @Autowired has been optional on constructors if you have one constructor Spring will try to autowire it. You can just tag the constructor with @Autowired if you want to be explicit about it.

Generally speaking you should favour Constructor > Setter > Field injection. Injecting directly to the field misses the point of DI, it also means your tests are reliant on Spring to inject dependencies into rather than just being able to pass mocks or stubs directly to it. Jurgan Holler has stated that he would remove field injection if at all possible.

ContentLicense: CC BY-SA 4.0


问:
How do I return a FactoryGirl definition in rails console?
I have a :quote factory defined in FactoryGirl and would like to view that object in Rails console.

```<code>FactoryGirl.find_definitions
</code>```

returns

```<code>FactoryGirl::DuplicateDefinitionError: Factory already registered: quote
from /User/.rvm/gems/ruby-2.3.0/gems/factory_girl-4.8.0/lib/factory_girl/decorator.rb:10:in `method_missing'
[8] pry(main)>
</code>```

Unsure of how to 'engage' with this object in console, can you advise please.

答:
For learning purposes just look at it!

Huh? It's in the code. Open corresponding file and look at it, to learn what it's doing. As for actual runtime ruby objects - under normal circumstances you never have to deal with factory instances directly.

But your curiosity will not go unsatisfied. Loaded factories go to FactoryGirl.factories. Inspect away. :)

Body:
I have a :quote factory defined in FactoryGirl and would like to view that object in Rails console.

FactoryGirl.find_definitions

returns

FactoryGirl::DuplicateDefinitionError: Factory already registered: quote
from /User/.rvm/gems/ruby-2.3.0/gems/factory_girl-4.8.0/lib/factory_girl/decorator.rb:10:in `method_missing'
[8] pry(main)>

Unsure of how to 'engage' with this object in console, can you advise please.


问:
How do I convert Twips to Pixels in .NET?
I'm working on a migration project in which a database actually stores display sizes in twips.
Since I can't use twips to assign sizes to WPF or Winforms controls, I was wondering if .NET has a conversion method usable at runtime?</p>

答:
For reference, another C# version, using the Win32 API instead of requiring a Graphics objects:

```<code>using System.Runtime.InteropServices;

static class SomeUtils {

  public static int ConvertTwipsToPixels(int twips, MeasureDirection direction) {
    return (int)(((double)twips)*((double)GetPixperinch(direction))/1440.0);
  }

  public static int ConvertPixelsToTwips(int pixels, MeasureDirection direction) {
    return (int)((((double)pixels)*1440.0)/((double)GetPixperinch(direction)));
  }

  public static int GetPPI(MeasureDirection direction) {
    int ppi;
    IntPtr dc = GetDC(IntPtr.Zero);

    if (direction == MeasureDirection.Horizontal)
      ppi = GetDeviceCaps(dc, 88); //DEVICECAP LOGPIXELSX
    else
      ppi = GetDeviceCaps(dc, 90); //DEVICECAP LOGPIXELSY

    ReleaseDC(IntPtr.Zero, dc);
    return ppi;
  }

  [DllImport("user32.dll")]
  static extern IntPtr GetDC(IntPtr hWnd);

  [DllImport("user32.dll")]
  static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);

  [DllImport("gdi32.dll")]
  static extern int GetDeviceCaps(IntPtr hdc, int devCap);
}

public enum MeasureDirection {
  Horizontal,
  Vertical
}
</code>```

The MeasureDirection is supposed to be specified as there is no guarantee that pixels are always square (according to the kb).

Reference: kb210590: ACC2000: How to Convert Twips to Pixels

Body:
For reference, another C# version, using the Win32 API instead of requiring a Graphics objects:

using System.Runtime.InteropServices;

static class SomeUtils {

  public static int ConvertTwipsToPixels(int twips, MeasureDirection direction) {
    return (int)(((double)twips)*((double)GetPixperinch(direction))/1440.0);
  }

  public static int ConvertPixelsToTwips(int pixels, MeasureDirection direction) {
    return (int)((((double)pixels)*1440.0)/((double)GetPixperinch(direction)));
  }

  public static int GetPPI(MeasureDirection direction) {
    int ppi;
    IntPtr dc = GetDC(IntPtr.Zero);

    if (direction == MeasureDirection.Horizontal)
      ppi = GetDeviceCaps(dc, 88); //DEVICECAP LOGPIXELSX
    else
      ppi = GetDeviceCaps(dc, 90); //DEVICECAP LOGPIXELSY

    ReleaseDC(IntPtr.Zero, dc);
    return ppi;
  }

  [DllImport("user32.dll")]
  static extern IntPtr GetDC(IntPtr hWnd);

  [DllImport("user32.dll")]
  static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);

  [DllImport("gdi32.dll")]
  static extern int GetDeviceCaps(IntPtr hdc, int devCap);
}

public enum MeasureDirection {
  Horizontal,
  Vertical
}

The MeasureDirection is supposed to be specified as there is no guarantee that pixels are always square (according to the kb).

Reference: kb210590: ACC2000: How to Convert Twips to Pixels


问:
C# DataContractSerializer exception when Deserializing 'The data at the root level is invalid'
[SOLVED]
There was an error deserializing the object of type 'Message'. The data at the root level is invalid

I have the following code for Serializing/Deserializing

```<code>    public static byte[] Serialize(object Object)
    {
        using (var memoryStream = new MemoryStream())
        {
            DataContractSerializer serializer = new DataContractSerializer(Object.GetType());
            serializer.WriteObject(memoryStream, Object);
            return memoryStream.ToArray();
        }
    }

    public static Type Deserialize<Type>(byte[] SerializedData)
    {
        using (var memoryStream = new MemoryStream(SerializedData))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(Type));
            return (Type)serializer.ReadObject(memoryStream);
        }
    }
</code>```

This is the class I'm serializing

```<code>[DataContractAttribute]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}
</code>```

Here is how it is used

```<code>

    void Send(string MessageType, string Data)
    {
        Message message = new Message();
        message.MessageType = MessageType;
        message.MessageData = Data;
        byte[] byteData = Serializer.Serialize(message); // SERIALIZE

        // Send the data
        stream.Write(byteData, 0, byteData.Length);
    }

    Message Receive()
    {
        stream.Read(bytes, 0, bytes.Length);
        Message message = Serializer.Deserialize(bytes); // DESERIALIZE
        return message;
    }

</code>```

I have tried several different things I have found on google from similar issues, but I cannot fix the issue.  Is there something wrong with the way I'm serializing?

答:
[SOLVED]

There were two issues. The first issue is [DataContractAttribute] need to be [Serializable]

```<code>[Serializable]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}
</code>```

Second is related to something not visible in the code above.
The 'bytes' array was initialized to a size greater than the data received, causing the Deserializer to not work properly.

I just created a new data array with the appropriate size to pass to the Deserializer

```<code>Message Receive()
{
    int messageLength = stream.Read(bytes, 0, bytes.Length);
    byte[] data = new byte[messageLength];
    Array.Copy(bytes, data, messageLength);

    Message message = Serializer.Deserialize(data); // DESERIALIZE
    return message;
}
</code>```

Body:
[SOLVED]
There was an error deserializing the object of type 'Message'. The data at the root level is invalid

I have the following code for Serializing/Deserializing

    public static byte[] Serialize(object Object)
    {
        using (var memoryStream = new MemoryStream())
        {
            DataContractSerializer serializer = new DataContractSerializer(Object.GetType());
            serializer.WriteObject(memoryStream, Object);
            return memoryStream.ToArray();
        }
    }

    public static Type Deserialize<Type>(byte[] SerializedData)
    {
        using (var memoryStream = new MemoryStream(SerializedData))
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(Type));
            return (Type)serializer.ReadObject(memoryStream);
        }
    }

This is the class I'm serializing

[DataContractAttribute]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}

Here is how it is used

    void Send(string MessageType, string Data)
    {
        Message message = new Message();
        message.MessageType = MessageType;
        message.MessageData = Data;
        byte[] byteData = Serializer.Serialize(message); // SERIALIZE

        // Send the data
        stream.Write(byteData, 0, byteData.Length);
    }

    Message Receive()
    {
        stream.Read(bytes, 0, bytes.Length);
        Message message = Serializer.Deserialize(bytes); // DESERIALIZE
        return message;
    }

I have tried several different things I have found on google from similar issues, but I cannot fix the issue.  Is there something wrong with the way I'm serializing?

Body:
[SOLVED]

There were two issues. The first issue is [DataContractAttribute] need to be [Serializable]

[Serializable]
public class Message
{
    public string MessageType = string.Empty;
    public string MessageData = string.Empty;
}

Second is related to something not visible in the code above.
The 'bytes' array was initialized to a size greater than the data received, causing the Deserializer to not work properly.

I just created a new data array with the appropriate size to pass to the Deserializer

Message Receive()
{
    int messageLength = stream.Read(bytes, 0, bytes.Length);
    byte[] data = new byte[messageLength];
    Array.Copy(bytes, data, messageLength);

    Message message = Serializer.Deserialize(data); // DESERIALIZE
    return message;
}


问:
Android Studio stuck on "Gradle: resolve dependencies '_debugCompile'" or 'detachedConfiguration1'
I have no idea what I changed in my project, but it suddenly cannot get past this step while building gradle scripts.

There is no problem building it with just 'gradle assemble'.

EDIT: the previous stuck point was resolve dependencies 'detachedConfiguration1'. (After the first failed attempt of _debugCompile, I'm back at detachedConfiguration1).
I guess it is too many dependency projects? Some sample projects I have are imported just fine in the Studio....
I reinstalled the Android Studio and removed all the settings and preferences as well.

I have to kill it every time it starts doing this.

Ring any bells?

```<code>import com.android.build.gradle.AppPlugin
import com.android.build.gradle.LibraryPlugin

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript {
repositories {
    mavenCentral()
}

dependencies {
    classpath 'com.android.tools.build:gradle:0.9.+'
}

apply plugin: 'android'

repositories {
    maven { url 'http://ksoap2-android.googlecode.com/svn/m2-repo' }

    mavenCentral()
}

dependencies {

    compile 'com.google.code.ksoap2-android:ksoap2-android:2.5.2'
    compile 'com.android.support:support-v4:18.0.+'
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':lib-projects:StickyListHeaders')
    compile project(':lib-projects:ActionBar-PullToRefresh')
    compile project(':lib-projects:facebook')
    compile project(':lib-projects:Mopub:mopub-sdk')
    compile project(':lib-projects:NineOldAndroids')
    compile project(':lib-projects:ActionBarSherlock:actionbarsherlock')
    compile project(':lib-projects:ActionBarSherlock:actionbarsherlock-i18n')
    compile project(':lib-projects:SmoothProgressBar')
    compile project(':lib-projects:android-viewflow-master:viewflow')
}

android {

    signingConfigs {

        debug {
            storeFile file('....')
        }
    }

    compileSdkVersion 19
    buildToolsVersion "19.0.3"
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        //instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...

        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')

    }
}
</code>```

答:
Just providing my experience in case others run into the following scenario.

The problem for me was one of my repositories was hosted on my companies network and not the public network.  After VPN'ing I was able to "resolve the dependency."

Body:
I have no idea what I changed in my project, but it suddenly cannot get past this step while building gradle scripts.

There is no problem building it with just 'gradle assemble'.

EDIT: the previous stuck point was resolve dependencies 'detachedConfiguration1'. (After the first failed attempt of _debugCompile, I'm back at detachedConfiguration1).
I guess it is too many dependency projects? Some sample projects I have are imported just fine in the Studio....
I reinstalled the Android Studio and removed all the settings and preferences as well.

I have to kill it every time it starts doing this.

Ring any bells?

import com.android.build.gradle.AppPlugin
import com.android.build.gradle.LibraryPlugin

// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript {
repositories {
    mavenCentral()
}

dependencies {
    classpath 'com.android.tools.build:gradle:0.9.+'
}

apply plugin: 'android'

repositories {
    maven { url 'http://ksoap2-android.googlecode.com/svn/m2-repo' }

    mavenCentral()
}

dependencies {

    compile 'com.google.code.ksoap2-android:ksoap2-android:2.5.2'
    compile 'com.android.support:support-v4:18.0.+'
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':lib-projects:StickyListHeaders')
    compile project(':lib-projects:ActionBar-PullToRefresh')
    compile project(':lib-projects:facebook')
    compile project(':lib-projects:Mopub:mopub-sdk')
    compile project(':lib-projects:NineOldAndroids')
    compile project(':lib-projects:ActionBarSherlock:actionbarsherlock')
    compile project(':lib-projects:ActionBarSherlock:actionbarsherlock-i18n')
    compile project(':lib-projects:SmoothProgressBar')
    compile project(':lib-projects:android-viewflow-master:viewflow')
}

android {

    signingConfigs {

        debug {
            storeFile file('....')
        }
    }

    compileSdkVersion 19
    buildToolsVersion "19.0.3"
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        //instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...

        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')

    }
}


问:
I am getting this error while installing blacklight project in ruby on rails for the bundle install in ubuntu 16.04
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

```<code>current directory: /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/gems/json-1.8.6/ext/json/ext/generator
</code>```

/usr/bin/ruby2.3 -r ./siteconf20170529-7305-1qu2mp6.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/gems/json-1.8.6 for inspection.
Results logged to /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out

答:
Thanks for asking!  Do you have the ruby-dev package installed?  You can get it with:</p>

```<code>sudo apt-get install ruby-dev
</code>```

Body:
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/gems/json-1.8.6/ext/json/ext/generator

/usr/bin/ruby2.3 -r ./siteconf20170529-7305-1qu2mp6.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/gems/json-1.8.6 for inspection.
Results logged to /tmp/bundler20170529-7305-1ybn2iijson-1.8.6/extensions/x86_64-linux/2.3.0/json-1.8.6/gem_make.out

Body:
Thanks for asking!  Do you have the ruby-dev package installed?  You can get it with:

sudo apt-get install ruby-dev


问:
Angular sub-component binding doesn't work
I'm trying to display message in sub-component using dependency injection.

Here is first.component.ts:

```<code>import { Component } from '@angular/core';
import { SecondComponent } from './second.component';

@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    this.secondComponent.Show('Test message');
  }
}
</code>```

Here is second.component.ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  template: '<p>{{ _message }}</p>'
})

export class SecondComponent {
  _message: string;

  Show(message: string) {
    this._message = message;
  }
}
</code>```

Console show no errors, but {{ _message }} in browser is not updated.

Where am I wrong?

答:
You can do this one of two ways; expose a public method in your SecondComponent or use @Input as yurzui mentioned

Public method in child component

Change your FirstComponent to

```<code>@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second #second></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  @ViewChild('second') second;
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    second.Show('Test message');
  }
}
</code>```

and mark the Show method in your SecondComponent as public

or Use @Input to pass data directly to your child component

```<code>@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second message="message"></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  public message: string;
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    this.message = 'Test message';
  }
}

import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  template: '<p>{{ _message }}</p>'
})

export class SecondComponent {
  @Input() _message: string;
}
</code>```

Body:
I'm trying to display message in sub-component using dependency injection.

Here is first.component.ts:

import { Component } from '@angular/core';
import { SecondComponent } from './second.component';

@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    this.secondComponent.Show('Test message');
  }
}

Here is second.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  template: '
{{ _message }}
'
})

export class SecondComponent {
  _message: string;

  Show(message: string) {
    this._message = message;
  }
}

Console show no errors, but {{ _message }} in browser is not updated.

Where am I wrong?

Body:
You can do this one of two ways; expose a public method in your SecondComponent or use @Input as yurzui mentioned

Public method in child component

Change your FirstComponent to

@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second #second></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  @ViewChild('second') second;
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    second.Show('Test message');
  }
}

and mark the Show method in your SecondComponent as public

or Use @Input to pass data directly to your child component

@Component({
  selector: 'app-first',
  template: `<button (click)="onClick()">Yes</button>
             <app-second message="message"></app-second>
             `,
  providers: [ SecondComponent ]
})

export class FirstComponent {
  public message: string;
  constructor(private secondComponent: SecondComponent) {}
  onClick() {
    this.message = 'Test message';
  }
}

import { Component } from '@angular/core';

@Component({
  selector: 'app-second',
  template: '<p>{{ _message }}</p>'
})

export class SecondComponent {
  @Input() _message: string;
}


问:
Scale rectangle object from middle – fabricjs
I have a rectangle object on fabricjs canvas. Now, when I try to scale the rectangle it always scales from a fixed corner and only expands to the direction where the mouse is. What I want is, when I scale it should scale from center and expand either side.  I tried setting originX and originY but that didn’t work. Can anyone help me on this? Thanks!</p>

```<code>var rect = new fabric.Rect({
 top: 150,
 left: 150,
 width: 100,
 height: 100,
 fill: 'black',
 originX: 'center',
 originY: 'center',
});
</code>```

答:
You need to set centeredScaling property to true for the rectangle object to make its' scale origin to center ...

var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
    top: 100,
    left: 100,
    width: 50,
    height: 50,
    fill: 'black',
    originX: 'center',
    originY: 'center',
    centeredScaling: true
});

canvas.add(rect).renderAll();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{border: 1px solid #ccc}</code>```

<canvas id="c" width="200" height="200"></canvas>```

Body:
I have a rectangle object on fabricjs canvas. Now, when I try to scale the rectangle it always scales from a fixed corner and only expands to the direction where the mouse is. What I want is, when I scale it should scale from center and expand either side.  I tried setting originX and originY but that didn’t work. Can anyone help me on this? Thanks!

var rect = new fabric.Rect({
 top: 150,
 left: 150,
 width: 100,
 height: 100,
 fill: 'black',
 originX: 'center',
 originY: 'center',
});

Body:
You need to set centeredScaling property to true for the rectangle object to make its' scale origin to center ...

var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
    top: 100,
    left: 100,
    width: 50,
    height: 50,
    fill: 'black',
    originX: 'center',
    originY: 'center',
    centeredScaling: true
});

canvas.add(rect).renderAll();

canvas{border: 1px solid #ccc}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>


问:
Tensorflow and openSUSE
I am interested in installing Tensorflow GPU-enabled in openSUSE but from Tensorflow's site the installation is provided only for Ubuntu. How can I do this?  </p>

答:
There's almost no different between installing on Ubuntu or OpenSUSE.

Follow the instructions here.

Note that in step 1, use your own package manager of OpenSUSE instead of apt-get which belongs to Ubuntu.

Title: Tensorflow and openSUSE


问:
Bucket a continuous variable into distinct boundary buckets
How to bucket continuous variables into fixed number of buckets such that the boundaries don't overlap?

Ex : Lets say I have 500 numbers with 302 1s, 120 2s and a bunch of other values that range from 3 - 40. How do I bucket these into 5 bins without looking at the distribution?

Percentile buckets would mean 1s present in 1,2 & 3 buckets while they are all effectively just one bin.

答: Use PROC RANK with GROUPS to specify the number of groups. You can also specify some methods, but they're all percentile based.   </p>


问:
VB.Net/C# - Split string on custom function
I'm working on a custom mathematical expression calculator, but I'm having problems at parsing nested conditional expression like this one:

```<code>IIF("M"="M",(IIF(100 < 50,(IIF(2 > 0.45,2,1)),(IIF(2 > 0.45,4,3)))),(IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))
</code>```

What I'd like to do is to split the IIF function by commas in order to get its parameters:

```<code>Dim condition = "M"="M"
Dim truePart = (IIF(100 < 50,(IIF([2 > 0.45,2,1)),(IIF(2 >0.45,4,3))))
Dim falsePart = (IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))
</code>```

At the moment I'm using Regex to parse single IIF function by getting what is inside the parentheses and the split it by commas:

```<code>\((.*?)\)
</code>```

Obviously that doesn't work with such expression since it will stop at the first closing parentheses, therefore I thought about using this to get all the other characters:

```<code>\((.*?)\).*
</code>```

But now I'm not sure how to split it, since using commas is not an option anymore.

答:
The answer from theory is that regular expressions are not capable to do what you requested because they "cannot count". However, you need to count.

The practise says that .NET regular expressions are no regular expressions but stack machines. With a group (?<Group>.*) you in fact add an entry to a stack of that group. With (?<-Group>), you can remove an entry from that stack. You can also test whether the stack is empty.

Out of curiosity, I gave it a try and I believe that

[\(,]([^\(\)]|(?<Par>\()|(?<-Par>\)))*(?(Par)---|[,\)])

should work, where --- is used as an escape sequence. If you understand that "regular expression" right away, then I think you are good to go. In all other cases, I would rather recommend you to write a parser manually. Otherwise, you are not going to understand your code 5min after you have tested it.

Body:
I'm working on a custom mathematical expression calculator, but I'm having problems at parsing nested conditional expression like this one:

IIF("M"="M",(IIF(100 < 50,(IIF(2 > 0.45,2,1)),(IIF(2 > 0.45,4,3)))),(IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))

What I'd like to do is to split the IIF function by commas in order to get its parameters:

Dim condition = "M"="M"
Dim truePart = (IIF(100 < 50,(IIF([2 > 0.45,2,1)),(IIF(2 >0.45,4,3))))
Dim falsePart = (IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))

At the moment I'm using Regex to parse single IIF function by getting what is inside the parentheses and the split it by commas:

\((.*?)\)

Obviously that doesn't work with such expression since it will stop at the first closing parentheses, therefore I thought about using this to get all the other characters:

\((.*?)\).*

But now I'm not sure how to split it, since using commas is not an option anymore.


问:
Writing to locals() works in contrast to documentation saying its not
I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython.
The confusion about locals(), vars() and globals() is real for me right now.
Especially because the output of this piece of code:

```<code>Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5
</code>```

According to the more than brief documentation this should not be possible in my understanding:

Note, the locals dictionary is only useful for reads since updates to
  the locals dictionary are ignored.

(which is for whatever reason stated in the description of the vars() function)

I hope someone can enlight me :)

答:
at module scope, locals() returns the global module dict which can be modified. locals in a function are different. Here, the variable is not changed. As mentioned elsewhere, this is all implementation dependent. You can't rely on locals() working as a writer.

```<code>>>> def foo():
...     x = 2
...     locals()['x'] = 3
...     print(x)
...
>>>
>>> foo()
2
</code>```

EDIT

In cpython, local variables are turned into slots on the frame object. By the time python runs the program, "x" is no longer "x", its an index into the slot.

```<code>>>> from dis import dis
>>> dis(foo)
  2           0 LOAD_CONST               1 (2)
              2 STORE_FAST               0 (x)

  3           4 LOAD_CONST               2 (3)
              6 LOAD_GLOBAL              0 (locals)
              8 CALL_FUNCTION            0
             10 LOAD_CONST               3 ('x')
             12 STORE_SUBSCR

  4          14 LOAD_GLOBAL              1 (print)
             16 LOAD_FAST                0 (x)
             18 CALL_FUNCTION            1
             20 POP_TOP
             22 LOAD_CONST               0 (None)
             24 RETURN_VALUE
</code>```

STORE_FAST               0 means to store the current value (it happens to be 2) into slot 0.

Body:
I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython.
The confusion about locals(), vars() and globals() is real for me right now.
Especially because the output of this piece of code:

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()["test"] = 5
>>> print(test)
5

According to the more than brief documentation this should not be possible in my understanding:

Note, the locals dictionary is only useful for reads since updates to
  the locals dictionary are ignored.

(which is for whatever reason stated in the description of the vars() function)

I hope someone can enlight me :)

Body:
at module scope, locals() returns the global module dict which can be modified. locals in a function are different. Here, the variable is not changed. As mentioned elsewhere, this is all implementation dependent. You can't rely on locals() working as a writer.

>>> def foo():
...     x = 2
...     locals()['x'] = 3
...     print(x)
...
>>>
>>> foo()
2

EDIT

In cpython, local variables are turned into slots on the frame object. By the time python runs the program, "x" is no longer "x", its an index into the slot.

>>> from dis import dis
>>> dis(foo)
  2           0 LOAD_CONST               1 (2)
              2 STORE_FAST               0 (x)

  3           4 LOAD_CONST               2 (3)
              6 LOAD_GLOBAL              0 (locals)
              8 CALL_FUNCTION            0
             10 LOAD_CONST               3 ('x')
             12 STORE_SUBSCR

  4          14 LOAD_GLOBAL              1 (print)
             16 LOAD_FAST                0 (x)
             18 CALL_FUNCTION            1
             20 POP_TOP
             22 LOAD_CONST               0 (None)
             24 RETURN_VALUE

STORE_FAST               0 means to store the current value (it happens to be 2) into slot 0.


问:
How to set progress of seekbar in listview with value mentioned in the database?
I am populating a listview with textviews and seekbars using simple cursor adapter.I could able to map the textviews with values from database, and I want to set the progress of seekbar with the database values. Can someone help me providing the approach with sample snippet?

I also want to get the progress of seekbars in the listview and save it back to database.

I used below code:

```<code>String[] strFieldName=new String[]{Database.NAME};
int[] Ids=new int[] {R.id.seekName1};
SimpleCursorAdapter planSCA=new SimpleCursorAdapter(
    getActivity(),
    R.layout.layout_seekitem,
    cursor,
    strFieldName,
    Ids
);
</code>```

答:
I think this should solve your query,

This is for using seekbar with listview

For accessing the DB to get value of progressbar in listview

Body:
I am populating a listview with textviews and seekbars using simple cursor adapter.I could able to map the textviews with values from database, and I want to set the progress of seekbar with the database values. Can someone help me providing the approach with sample snippet?

I also want to get the progress of seekbars in the listview and save it back to database.

I used below code:

String[] strFieldName=new String[]{Database.NAME};
int[] Ids=new int[] {R.id.seekName1};
SimpleCursorAdapter planSCA=new SimpleCursorAdapter(
    getActivity(),
    R.layout.layout_seekitem,
    cursor,
    strFieldName,
    Ids
);


问:
Add event on inner class by mouseovering on outer class in html using javascript
I have class post and another class postinr defined in post class. I want to attach event to class postinr while mouseovering on class post. But I am unable to do that. What is the solution. Here is simple structure of html and javascript...`

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{
post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "70px");
}
function animate2() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "123px");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3></h3>
  </div>
</div></code>```

答:
Within the animate functions, reference postinr. I added a border so you can see what is happening to the divs.

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{
post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
    var postInner=document.getElementsByClassName("postinr")[0];
 postInner.style.setProperty("-webkit-transition", "margin-top 2s");
 postInner.style.setProperty("margin-top", "70px");
}
function animate2() {
    var postInner=document.getElementsByClassName("postinr")[0];
 postInner.style.setProperty("-webkit-transition", "margin-top 2s");
 postInner.style.setProperty("margin-top", "123px");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
border:1px solid black;
}</code>```

```

Body:
Within the animate functions, reference postinr. I added a border so you can see what is happening to the divs.

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{
post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
    var postInner=document.getElementsByClassName("postinr")[0];
 postInner.style.setProperty("-webkit-transition", "margin-top 2s");
 postInner.style.setProperty("margin-top", "70px");
}
function animate2() {
    var postInner=document.getElementsByClassName("postinr")[0];
 postInner.style.setProperty("-webkit-transition", "margin-top 2s");
 postInner.style.setProperty("margin-top", "123px");
}

div{
border:1px solid black;
}

<div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3></h3>
  </div>
</div>


问:
attr new onclick function not working
I am replacing an onclick attr as so....

```<code>$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}
</code>```

My current html is

```<code><div id="divName" onclick="oldFunction()">
</code>```

and after i insert the new attr , inspecting element shows this

```<code><div id="divName" onclick="newFunction()">
</code>```

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

答:
You should use unobtrusive event handler and use .on() to attach event handler

```<code>var $elem = $('#divName');

//Remove previous event handler
$elem.prop('onclick',null);

//Bind new event handler
$elem.on('click', newFunction);
</code>```

function oldFunction() {
  console.log('old funnction.');

  var $elem = $('#divName');

  //Remove previous event handler
  $elem.prop('onclick', null);

  //Bind new event handler
  $elem.on('click', newFunction);

  console.log('New Event handler attached, click again');
}

function newFunction() {
  console.log('New Function Success');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divName" onclick="oldFunction()">click me</div></code>```

Title: attr new onclick function not working

Body:
I am replacing an onclick attr as so....

$('#divName').attr('onclick','newFunction()');

function newFunction(){
    alert('New Function Success');
}

My current html is

and after i insert the new attr , inspecting element shows this

but when i click , no alert msg is displayed, so new function is not being applied on click event , any ideas why ?

Body:
You should use unobtrusive event handler and use .on() to attach event handler

var $elem = $('#divName');

//Remove previous event handler
$elem.prop('onclick',null);

//Bind new event handler
$elem.on('click', newFunction);

function oldFunction() {
  console.log('old funnction.');

  var $elem = $('#divName');

  //Remove previous event handler
  $elem.prop('onclick', null);

  //Bind new event handler
  $elem.on('click', newFunction);

  console.log('New Event handler attached, click again');
}

function newFunction() {
  console.log('New Function Success');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divName" onclick="oldFunction()">click me</div>


问:
WebGL Depth Texture all white?
I'm using the WEBGL_depth_texture in chrome to render a scene to a framebuffer with a color and depth texture. When I display my color texture works fine, but my depthtexture is all white. Shouldn't it be like gray?

my draw texture function:

```<code>this.drawTexture = function() {

    //gl.viewport(0, 0, this.canvas.width, this.canvas.height);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer);
    gl.vertexAttribPointer(this.VertexPosition, 2, gl.FLOAT, false, 0, 0);

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertTexCoordBuffer);
    gl.vertexAttribPointer(this.VertexTexture, 2, gl.FLOAT, false, 0, 0);

    gl.bindTexture(gl.TEXTURE_2D, this.depthTexture);

    gl.drawArrays(gl.TRIANGLES, 0, 6);

    gl.bindTexture(gl.TEXTURE_2D, null);
</code>```

init:

```<code>           this.colorTexture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.colorTexture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

        this.depthTexture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.depthTexture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);

       // var framebuffer = gl.createFramebuffer();
        this.depthFramebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.depthFramebuffer);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.colorTexture, 0);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, this.depthTexture, 0);
</code>```

vertex shaders:

```<code>attribute vec2 VertexPosition;
attribute vec2 TextureCoord;

varying vec2 vTextureCoord;

    void main() {
      gl_Position = vec4(VertexPosition, 0, 1);
      vTextureCoord = TextureCoord;
}
</code>```

Fragment Shader

```<code>precision highp float;

uniform sampler2D uSampler;

varying vec2 vTextureCoord;

void main(void) {

    vec4 depth = texture2D(uSampler, vTextureCoord);
    gl_FragColor = depth;

}
</code>```

答:
I got the same problem and the solution was to linearize the depth value.

```<code>void main(void) {
    float n = 1.0;
    float f = 2000.0;
    float z = texture2D(uSampler0, vTextureCoord.st).x;
    float grey = (2.0 * n) / (f + n - z*(f-n));
    vec4 color = vec4(grey, grey, grey, 1.0);
    gl_FragColor = color;
}
</code>```

I tried at first to divided by 2 or 4 the depth value but I had always the same color for every pixels. So I thought the problem came from somewhere else. My point is, be careful.

Archived source: https://web.archive.org/web/20171127052549/http://blog.bongiovi.tw/webgl-depth-texture/

Title: WebGL Depth Texture all white?

Body:
I'm using the WEBGL_depth_texture in chrome to render a scene to a framebuffer with a color and depth texture. When I display my color texture works fine, but my depthtexture is all white. Shouldn't it be like gray?

my draw texture function:

this.drawTexture = function() {

    //gl.viewport(0, 0, this.canvas.width, this.canvas.height);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer);
    gl.vertexAttribPointer(this.VertexPosition, 2, gl.FLOAT, false, 0, 0);

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertTexCoordBuffer);
    gl.vertexAttribPointer(this.VertexTexture, 2, gl.FLOAT, false, 0, 0);

    gl.bindTexture(gl.TEXTURE_2D, this.depthTexture);

    gl.drawArrays(gl.TRIANGLES, 0, 6);

    gl.bindTexture(gl.TEXTURE_2D, null);

init:

           this.colorTexture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.colorTexture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

        this.depthTexture = gl.createTexture();
        gl.bindTexture(gl.TEXTURE_2D, this.depthTexture);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);

       // var framebuffer = gl.createFramebuffer();
        this.depthFramebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, this.depthFramebuffer);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.colorTexture, 0);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, this.depthTexture, 0);

vertex shaders:

attribute vec2 VertexPosition;
attribute vec2 TextureCoord;

varying vec2 vTextureCoord;

    void main() {
      gl_Position = vec4(VertexPosition, 0, 1);
      vTextureCoord = TextureCoord;
}

Fragment Shader

precision highp float;

uniform sampler2D uSampler;

varying vec2 vTextureCoord;

void main(void) {

    vec4 depth = texture2D(uSampler, vTextureCoord);
    gl_FragColor = depth;

}

Body:
I got the same problem and the solution was to linearize the depth value.

void main(void) {
    float n = 1.0;
    float f = 2000.0;
    float z = texture2D(uSampler0, vTextureCoord.st).x;
    float grey = (2.0 * n) / (f + n - z*(f-n));
    vec4 color = vec4(grey, grey, grey, 1.0);
    gl_FragColor = color;
}

I tried at first to divided by 2 or 4 the depth value but I had always the same color for every pixels. So I thought the problem came from somewhere else. My point is, be careful.

Archived source: https://web.archive.org/web/20171127052549/http://blog.bongiovi.tw/webgl-depth-texture/


问:
F# - Turn simple for loop into more functional construct
I have this simple "Investment" type with a "lifetime" property:

```<code>type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}
</code>```

I would like to iterate over the years of investment and perform some calculations for each year:

```<code>for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething
</code>```

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

答:
I quickly found an answer:</p>

```<code>[1..int CoffeMachine.Lifetime] |> List.iter (printf "%i")
</code>```

Body:
I have this simple "Investment" type with a "lifetime" property:

type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}

I would like to iterate over the years of investment and perform some calculations for each year:

for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

Body:
I quickly found an answer:

[1..int CoffeMachine.Lifetime] |> List.iter (printf "%i")


问:
List of most occurrences of element
I have a list let's say {1,1,2,2,3,3,3,4,4,4}. I want to find a List of the elements that occur the most often (it has to be a list as there can be a situation like here that 3 and 4 occur most and I need to get that information. How can I achieve this using LINQ?</p>

答:
A little complicated

```<code>var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
        var result = lst_input.Where(x => lst_input.Max(y => lst_input.Count(z => z == y)) == lst_input.Count(z => z == x)).Distinct().ToList();
</code>```

But the above code is not effective when dealing with a really big array, since finding max is re-run for each element, and we could distinct the list in the first place. Another more efficient way:

```<code>var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
var tmp = lst_input.Distinct();
var max_val = tmp.Max(y => lst_input.Count(z => z == y));
var result = tmp.Where(x => max_val == lst_input.Count(z => z == x)).ToList();
</code>```

Title: List of most occurrences of element

Body:
A little complicated

var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
        var result = lst_input.Where(x => lst_input.Max(y => lst_input.Count(z => z == y)) == lst_input.Count(z => z == x)).Distinct().ToList();

But the above code is not effective when dealing with a really big array, since finding max is re-run for each element, and we could distinct the list in the first place. Another more efficient way:

var lst_input = new List<int>(new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 4 });
var tmp = lst_input.Distinct();
var max_val = tmp.Max(y => lst_input.Count(z => z == y));
var result = tmp.Where(x => max_val == lst_input.Count(z => z == x)).ToList();


问:
Putting methods into an ArrayList Java
I would like to put these Methods into an ArrayList, but I can't figure out how to do that. I'm using NetBeans, and the program is going to be a GUI.

Here is my code:

```<code>public class canada150Tour extends javax.swing.JFrame {

    ArrayList <String> mcQuestions = new ArrayList(); //This is the array I want to put the below methods into.

    private void questionFredricton(){
        outputTextQuestion.append("Where is Fredricton located?");

        displayQuestions.append("New Brunswick");
    }
    private void questionRegina(){
        outputTextQuestion.setText("Where is Regina located?");

        displayQuestions.append("Saskatchewan");

    }
    private void questionOttawa(){
        outputTextQuestion.setText("Where is Ottawa located?");

        displayQuestions.append("Ontario");
    }
    private void questionHalifax(){
        outputTextQuestion.setText("Where is Halifax located?");

        displayQuestions.append("Nova Scotia");
    }
    private void questionQuebecCity(){
        outputTextQuestion.setText("Where is Quebec City located?");

        displayQuestions.append("Quebec");
    }
    private void questionEdmonton(){
        outputTextQuestion.setText("Where is Edmonton located?");

        displayQuestions.append("Alberta");
    }
    private void questionCharlottetown(){
        outputTextQuestion.setText("Where is Charlottetown located?");

        displayQuestions.append("Prince Edward Island");
    }
    private void questionVictoria(){
        outputTextQuestion.setText("Where is Victoria located?");

        displayQuestions.append("British Columbia");
    }
    private void questionIqaluit(){
        outputTextQuestion.setText("Where is Iqaluit located?");

        displayQuestions.append("Nunavut");
    }
    private void questionWhitehorse(){
        //outputTextQuestion.setText("Where is Whitehorse located?");

        displayQuestions.append("Yukon");
    }
    private void questionWinnipeg(){
        outputTextQuestion.setText("Where is Winnipeg located?");

        displayQuestions.append("Manitoba");
    }
</code>```

I've tried:

```<code>Collections.addAll(mcQuestions, questionFredricton(), questionRegina());
</code>```

And so on for all the methods, but obviously that isn't working.

I get a compiling error when I'm trying to add to the ArrayList (above):

'void' type not allowed here

I'm fairly new to Java, so still learning.

EDIT:
This will eventually be a multiple choice quiz.  I essentially want to the put the methods into an array so I can chose methods randomly.

Thanks in advance!

答:
Your method should return a String if you want to add a String in a ArrayList of String.

But in fact I don't think that you should do it because you needs both Question and Response. It seems better to have a List of QuestionAndResponse rather than two List of String.

A  QuestionAndResponse  could contain the text of the question but also the text of the expected response.

```<code>public class QuestionAndResponse{
     public QuestionAndResponse(String question, String response){
         this.question = question;
         this.response = response;
     }
     // getters for fields
}
</code>```

So you could declare the List :

```<code>List <QuestionAndResponse> mcQuestionsResponses = new ArrayList<>();
</code>```

And you could replace this :

```<code>private void questionFredricton(){
    outputTextQuestion.append("Where is Fredricton located?");
    displayQuestions.append("New Brunswick");
}
</code>```

by:

```<code>private QuestionAndResponse questionFredricton(){
    return new QuestionAndResponse("Where is Fredricton located?","New Brunswick");
}
</code>```

Now you can have a Canada150Tour (note the uppercase for the first letter to follow the naming conventions) constructor that uses them :

```<code>public class Canada150Tour extends JFrame {
    List <QuestionAndResponse> mcQuestionsResponses;
       ...
    public Canada150Tour(){
         mcQuestionsResponses = new ArrayList<>();
         mcQuestionsResponses.add(questionFredricton());
    }

     private QuestionAndResponse questionFredricton(){
        return new QuestionAndResponse("Where is Fredricton located?",
                                        "New Brunswick");
     }
}
</code>```

Title: Putting methods into an ArrayList Java

Body:
I would like to put these Methods into an ArrayList, but I can't figure out how to do that. I'm using NetBeans, and the program is going to be a GUI.

Here is my code:

public class canada150Tour extends javax.swing.JFrame {

    ArrayList <String> mcQuestions = new ArrayList(); //This is the array I want to put the below methods into.

    private void questionFredricton(){
        outputTextQuestion.append("Where is Fredricton located?");

        displayQuestions.append("New Brunswick");
    }
    private void questionRegina(){
        outputTextQuestion.setText("Where is Regina located?");

        displayQuestions.append("Saskatchewan");

    }
    private void questionOttawa(){
        outputTextQuestion.setText("Where is Ottawa located?");

        displayQuestions.append("Ontario");
    }
    private void questionHalifax(){
        outputTextQuestion.setText("Where is Halifax located?");

        displayQuestions.append("Nova Scotia");
    }
    private void questionQuebecCity(){
        outputTextQuestion.setText("Where is Quebec City located?");

        displayQuestions.append("Quebec");
    }
    private void questionEdmonton(){
        outputTextQuestion.setText("Where is Edmonton located?");

        displayQuestions.append("Alberta");
    }
    private void questionCharlottetown(){
        outputTextQuestion.setText("Where is Charlottetown located?");

        displayQuestions.append("Prince Edward Island");
    }
    private void questionVictoria(){
        outputTextQuestion.setText("Where is Victoria located?");

        displayQuestions.append("British Columbia");
    }
    private void questionIqaluit(){
        outputTextQuestion.setText("Where is Iqaluit located?");

        displayQuestions.append("Nunavut");
    }
    private void questionWhitehorse(){
        //outputTextQuestion.setText("Where is Whitehorse located?");

        displayQuestions.append("Yukon");
    }
    private void questionWinnipeg(){
        outputTextQuestion.setText("Where is Winnipeg located?");

        displayQuestions.append("Manitoba");
    }

I've tried:

Collections.addAll(mcQuestions, questionFredricton(), questionRegina());

And so on for all the methods, but obviously that isn't working.

I get a compiling error when I'm trying to add to the ArrayList (above):

'void' type not allowed here

I'm fairly new to Java, so still learning.

EDIT:
This will eventually be a multiple choice quiz.  I essentially want to the put the methods into an array so I can chose methods randomly.

Thanks in advance!

Body:
Your method should return a String if you want to add a String in a ArrayList of String.

But in fact I don't think that you should do it because you needs both Question and Response. It seems better to have a List of QuestionAndResponse rather than two List of String.

A  QuestionAndResponse  could contain the text of the question but also the text of the expected response.

public class QuestionAndResponse{
     public QuestionAndResponse(String question, String response){
         this.question = question;
         this.response = response;
     }
     // getters for fields
}

So you could declare the List :

List <QuestionAndResponse> mcQuestionsResponses = new ArrayList<>();

And you could replace this :

private void questionFredricton(){
    outputTextQuestion.append("Where is Fredricton located?");
    displayQuestions.append("New Brunswick");
}

by:

private QuestionAndResponse questionFredricton(){
    return new QuestionAndResponse("Where is Fredricton located?","New Brunswick");
}

Now you can have a Canada150Tour (note the uppercase for the first letter to follow the naming conventions) constructor that uses them :

public class Canada150Tour extends JFrame {
    List <QuestionAndResponse> mcQuestionsResponses;
       ...
    public Canada150Tour(){
         mcQuestionsResponses = new ArrayList<>();
         mcQuestionsResponses.add(questionFredricton());
    }

     private QuestionAndResponse questionFredricton(){
        return new QuestionAndResponse("Where is Fredricton located?",
                                        "New Brunswick");
     }
}


问:
MongoDb remove 2 data
I have a collection of technicians below. How to remove or pull data in both tasks and reservedDates in one command??</p>

```<code>db.technicians.find().pretty()
{
   "_id" : ObjectId("592acc916a32c48647427b2f"),
    "firstName" : "Pj",
    "lastName" : "Rizal",
    "tasks" : [
            ObjectId("593435177492fb214c3a8694"),
            ObjectId("5934389179439d2c20f07210"),
    ],
    "reservedDates" : [
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
    ]

}
</code>```

答:
According to MongoDB documentation

The $pull operator removes from an existing array all instances of a
  value or values that match a specified condition.

In above mentioned MongoDB document reservedDates field represents an embedded document .

To remove an entry from an embedded document belonging to a document matching specific condition update operation using $pull operator needs to be executed in MongoDB shell.

Title: MongoDb remove 2 data

Body:
I have a collection of technicians below. How to remove or pull data in both tasks and reservedDates in one command??

db.technicians.find().pretty()
{
   "_id" : ObjectId("592acc916a32c48647427b2f"),
    "firstName" : "Pj",
    "lastName" : "Rizal",
    "tasks" : [
            ObjectId("593435177492fb214c3a8694"),
            ObjectId("5934389179439d2c20f07210"),
    ],
    "reservedDates" : [
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
            {
                    "date" : "2017-06-29T16:00:00.000Z",
                    "time" : "2017-06-04T07:14:16.130Z",
            },
    ]

}


问:
Passing compiler options in CMake command line
I know how to pass compiler options using the cmake command:

```<code>set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")
</code>```

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

```<code>cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt
</code>```

or

```<code>cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt
</code>```

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

答:
Yes, you can append compiler and linker options. But there are two things you have to differentiate in CMake: the first call to generate the build environment and all consecutive calls for regenerating that build environment after changes to your CMakeLists.txt files or dependencies.

Here are some of the possibilities (excluding the more complex toolchain variants):

Append Compiler Flags

The initial content from the cached CMAKE_CXX_FLAGS variable is a combination of CMAKE_CXX_FLAGS_INIT set by CMake itself during OS/toolchain detection and whatever is set in the CXXFLAGS environment variable. So you can initially call:

```<code> cmake -E env CXXFLAGS="-Wall" cmake ..
</code>```

Later, CMake would expect that the user modifies the CMAKE_CXX_FLAGS cached variable directly to append things, e.g., by using an editor like ccmake commit with CMake.

You can easily introduce your own build type like ALL_WARNINGS. The build type specific parts are appended:

```<code>  cmake -DCMAKE_CXX_FLAGS_ALL_WARNINGS:STRING="-Wall" -DCMAKE_BUILD_TYPE=ALL_WARNINGS ..
</code>```

Append Linker Flags

The linker options are more or less equivalent to the compiler options. Just that CMake's variable names depend on the target type (EXE, SHARED or MODULE).

The CMAKE_EXE_LINKER_FLAGS_INIT, CMAKE_SHARED_LINKER_FLAGS_INIT or CMAKE_MODULE_LINKER_FLAGS_INIT do combine with the evironment variable LDFLAGS to CMAKE_EXE_LINKER_FLAGS, CMAKE_SHARED_LINKER_FLAGS and CMAKE_MODULE_LINKER_FLAGS.

So you can e.g call:

```<code> cmake -E env LDFLAGS="-rpath=/home/abcd/libs/" cmake ..
</code>```

See above.

Build type-specific parts are appended:

```<code> cmake -DCMAKE_SHARED_LINKER_FLAGS_MY_RPATH:STRING="-rpath=/home/abcd/libs/" -DCMAKE_BUILD_TYPE=MY_RPATH ..
</code>```

Alternatives

Just be aware that CMake does provide a special variable to set complier/linker flags in a platform independent way. So you don't need to know the specific compiler/linker option.

Here are some examples:

CMAKE_CXX_STANDARD

CMAKE_POSITION_INDEPENDENT_CODE

CMAKE_BUILD_RPATH

CMAKE_INSTALL_RPATH_USE_LINK_PATH

Unfortunately, there is none for the compiler's warning level (yet)

References

Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake

How to set warning level in CMake?

Body:
I know how to pass compiler options using the cmake command:

set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt

or

cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

Body:
Yes, you can append compiler and linker options. But there are two things you have to differentiate in CMake: the first call to generate the build environment and all consecutive calls for regenerating that build environment after changes to your CMakeLists.txt files or dependencies.

Here are some of the possibilities (excluding the more complex toolchain variants):

Append Compiler Flags

The initial content from the cached CMAKE_CXX_FLAGS variable is a combination of CMAKE_CXX_FLAGS_INIT set by CMake itself during OS/toolchain detection and whatever is set in the CXXFLAGS environment variable. So you can initially call:

 cmake -E env CXXFLAGS="-Wall" cmake ..

Later, CMake would expect that the user modifies the CMAKE_CXX_FLAGS cached variable directly to append things, e.g., by using an editor like ccmake commit with CMake.

You can easily introduce your own build type like ALL_WARNINGS. The build type specific parts are appended:

  cmake -DCMAKE_CXX_FLAGS_ALL_WARNINGS:STRING="-Wall" -DCMAKE_BUILD_TYPE=ALL_WARNINGS ..

Append Linker Flags

The linker options are more or less equivalent to the compiler options. Just that CMake's variable names depend on the target type (EXE, SHARED or MODULE).

The CMAKE_EXE_LINKER_FLAGS_INIT, CMAKE_SHARED_LINKER_FLAGS_INIT or CMAKE_MODULE_LINKER_FLAGS_INIT do combine with the evironment variable LDFLAGS to CMAKE_EXE_LINKER_FLAGS, CMAKE_SHARED_LINKER_FLAGS and CMAKE_MODULE_LINKER_FLAGS.

So you can e.g call:

 cmake -E env LDFLAGS="-rpath=/home/abcd/libs/" cmake ..

See above.

Build type-specific parts are appended:

 cmake -DCMAKE_SHARED_LINKER_FLAGS_MY_RPATH:STRING="-rpath=/home/abcd/libs/" -DCMAKE_BUILD_TYPE=MY_RPATH ..

Alternatives

Just be aware that CMake does provide a special variable to set complier/linker flags in a platform independent way. So you don't need to know the specific compiler/linker option.

Here are some examples:

CMAKE_CXX_STANDARD

CMAKE_POSITION_INDEPENDENT_CODE

CMAKE_BUILD_RPATH

CMAKE_INSTALL_RPATH_USE_LINK_PATH

Unfortunately, there is none for the compiler's warning level (yet)

References

Change default value of CMAKE_CXX_FLAGS_DEBUG and friends in CMake

How to set warning level in CMake?


问:
Autocomplete using Flask, Jquery , Javascript, MySQL
This is my html file where I'm trying to use the autocomplete function where I want to use the data which I get from MySQL query which is first_name and last_name. I'm passing this data using flask but I'm unable to use it for autocomplete function.

Data format:
    first_name: [["Steven"], ["Stephany"], ["Sonia"], ["Sambit"], ["Chowta"]]

 <title>Autocomplete</title>
 <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet">

<link rel="stylesheet" href="/static/style.css" type="text/css">

<form action="/login" method="POST">

Search

    <input id="firstname" type="text" class="login-field" value="" placeholder="FirstName" name="First Name">

    <input id="lastname" type="text" class="login-field" value="" placeholder="LastName" name="Last Name">

                <input type="submit" value="Search" class="btn btn-primary btn-large btn-block" >

</form>
```

答:
The data format of your:

```<code>first_name: [["Steven"], ["Stephany"], ["Sonia"], ["Sambit"], ["Chowta"]]
</code>```

is wrong. For details see option source.

If you cannot change the array on your server you can always flatten it on the client:

```<code>[].concat.apply([], first)
</code>```

var first =    [["Steven"], ["Stephany"], ["Sonia"], ["Sambit"], ["Chowta"]];
$(function() {
    $("#firstname").autocomplete({
        source: [].concat.apply([], first)
    });
    $("#lastname").autocomplete({
        source: [].concat.apply([], first)
    }).autocomplete("widget").addClass("fixed-height");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.fixed-height {
    padding: 1px;
    max-height: 200px;
    overflow: auto;
}</code>```

<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<form action="/login" method="POST">

Search

                    <input id="firstname" type="text" class="login-field" value="" placeholder="FirstName" name="First Name">

                    <input id="lastname" type="text" class="login-field" value="" placeholder="LastName" name="Last Name">

                <input type="submit" value="Search" class="btn btn-primary btn-large btn-block" >

</form>```

Body:
The data format of your:

first_name: [["Steven"], ["Stephany"], ["Sonia"], ["Sambit"], ["Chowta"]]

is wrong. For details see option source.

If you cannot change the array on your server you can always flatten it on the client:

[].concat.apply([], first)

var first =    [["Steven"], ["Stephany"], ["Sonia"], ["Sambit"], ["Chowta"]];
$(function() {
    $("#firstname").autocomplete({
        source: [].concat.apply([], first)
    });
    $("#lastname").autocomplete({
        source: [].concat.apply([], first)
    }).autocomplete("widget").addClass("fixed-height");
});

.fixed-height {
    padding: 1px;
    max-height: 200px;
    overflow: auto;
}

<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

<form action="/login" method="POST">
    <div class="login">
        <div class="login-screen">
            <div class="app-title">
                <h1>Search</h1>
            </div>
            <div class="login-form">
                <div class="control-group">
                    <input id="firstname" type="text" class="login-field" value="" placeholder="FirstName" name="First Name">
                    <label class="login-field-icon fui-user" for="firstname"></label>
                </div>
                <div class="control-group">
                    <input id="lastname" type="text" class="login-field" value="" placeholder="LastName" name="Last Name">
                    <label class="login-field-icon fui-lock" for="lastname"></label>
                </div>
                <input type="submit" value="Search" class="btn btn-primary btn-large btn-block" >
                <br>
            </div>
        </div>
    </div>
</form>


问:
AngularJS and Laravel Foreach
I do have a problem with using Angular with Laravel's foreach loop, i tried to be as detailed as possible :)

```<code><div style="padding:15px;" id="table-scroll" ng-app>
    <table class="table table-responsive tblProducts" id="tblProducts">
      <thead>
        <tr>
          <th>Description</th>
          <th>Prices</th>
          <th></th>
          <th></th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        //foreach loop here
      </tbody>
    </table>
</div>
</code>```

this is my foreach loop

@foreach($products as $product)

                {{ $product->product_description }}

                     product_price }}" ng-model="price">

                        @{{price*qty}}

            @endforeach

Problem:

-When I use "ng-model" the prices/quantity are not displayed, but when i use "ng-bind" the prices/quantity are displayed but the subtotal column displays NaN (i have no idea why).

Flow:

-Each row of that table displays a list of grocery items, when the checkbox is clicked, it means that the item is selected and transferred to another table for calculating the grandtotal.

Reference:
https://ibb.co/hCddLv (snap from list of grocery items)
https://ibb.co/e0jk0v (when that product is transferred, this happens)
*im using "ng-bind" to display the price and quantity...

Thanks for the answer in advance guys...

I have updated this with my controller code in laravel

public function create()
      {

          $rooms    = Room::where('status','=',0)->orderBy('room_length_of_stay')->get();

```<code>    $products = DB::table('classifications')
        ->join('products', 'classifications.id', '=', 'products.classification_id')
        ->select('classifications.*', 'products.*')
        ->get();

    //$scope.products = $products;
    return View::make('frontdesk.transactions.create', ['rooms' => $rooms, 'products'=>$products]);
}
</code>```

答: ng-model works by using a property on the scope to read/write a value as an input changes so you can't just assign it some value hence the problem.  Ideally I only use Angular for the front end and template handling and would do the looping with an ng-repeat over an array that is retrieved in JS from the backend (could be laravel based but would keep it just serving JSON data not doing anything with the view, lumen is good for this).  In the short term you can just set the value attribute on the input that would be the most direct way to put your data into the form that may not work with ng-model though (assuming you pointed that at some JS property) since it's expected the ng-model will be used for reading/writing the value.

Title: AngularJS and Laravel Foreach

Body:
I do have a problem with using Angular with Laravel's foreach loop, i tried to be as detailed as possible :)

          Description
          Prices

          Action

        //foreach loop here

this is my foreach loop

@foreach($products as $product)

                {{ $product->product_description }}

                     product_price }}" ng-model="price">

                        @{{price*qty}}

            @endforeach

Problem:

-When I use "ng-model" the prices/quantity are not displayed, but when i use "ng-bind" the prices/quantity are displayed but the subtotal column displays NaN (i have no idea why).

Flow:

-Each row of that table displays a list of grocery items, when the checkbox is clicked, it means that the item is selected and transferred to another table for calculating the grandtotal.

Reference:
https://ibb.co/hCddLv (snap from list of grocery items)
https://ibb.co/e0jk0v (when that product is transferred, this happens)
*im using "ng-bind" to display the price and quantity...

Thanks for the answer in advance guys...

I have updated this with my controller code in laravel

public function create()
      {

          $rooms    = Room::where('status','=',0)->orderBy('room_length_of_stay')->get();

    $products = DB::table('classifications')
        ->join('products', 'classifications.id', '=', 'products.classification_id')
        ->select('classifications.*', 'products.*')
        ->get();

    //$scope.products = $products;
    return View::make('frontdesk.transactions.create', ['rooms' => $rooms, 'products'=>$products]);
}


问:
How do I append one string to another in Python?
How do I efficiently append one string to another? Are there any faster alternatives to:

```<code>var1 = "foo"
var2 = "bar"
var3 = var1 + var2
</code>```

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.

答: it really depends on your application. If you're looping through hundreds of words and want to append them all into a list, .join() is better. But if you're putting together a long sentence, you're better off using +=.

Body:
How do I efficiently append one string to another? Are there any faster alternatives to:

var1 = "foo"
var2 = "bar"
var3 = var1 + var2

For handling multiple strings in a list, see How to concatenate (join) items in a list to a single string.

See How do I put a variable’s value inside a string (interpolate it into the string)? if some inputs are not strings, but the result should still be a string.


问:
jQuery not being imported
I'm trying to import jquery to work with semantic ui. The problem is, it's giving me a couple of errors:

```<code>Uncaught ReferenceError: jQuery is not defined
    at semantic.min.js:11
main.js:3 Uncaught ReferenceError: $ is not defined
    at main.js:3
</code>```

I know this is telling me jQuery is not being imported but I don't know why. This is my home page:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Ttitle</title>

  <link href="https://fonts.googleapis.com/css?family=Cabin" rel="stylesheet" />

  <link rel="stylesheet" href="res/css/frameworks/semantic-ui/semantic.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="res/css/main.css" />
</head>
<body>
  <?php require ROOT_DIR . "views/navs/main_nav.php"; ?>

  <?php
    if(!isset($_GET["section"])):
      require ROOT_DIR . "views/home.php";
    endif;
  ?>

  <!-- IMPORTING JQUERY FROM GOOGLE -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="res/css/frameworks/semantic-ui/semantic.min.js"></script>
  <script src="res/js/main.js"></script>
</body>
</html>
</code>```

Does anyone know why this is happening? Any help is appreciated!

UPDATE

I tried adding an empty script tag before my 3 main tags and somehow it is now being imported. It now looks like this:

```<code><!-- IMPORTING JQUERY FROM GOOGLE -->
<script></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="res/css/frameworks/semantic-ui/semantic.min.js"></script>
<script src="res/js/main.js"></script>
</code>```

Anyone know why this is happening?

答: Forgot to close a div tag inside my home.php file.

Title: jQuery not being imported

Body:
I'm trying to import jquery to work with semantic ui. The problem is, it's giving me a couple of errors:

Uncaught ReferenceError: jQuery is not defined
    at semantic.min.js:11
main.js:3 Uncaught ReferenceError: $ is not defined
    at main.js:3

I know this is telling me jQuery is not being imported but I don't know why. This is my home page:

<!DOCTYPE html>

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

  <link href="https://fonts.googleapis.com/css?family=Cabin" rel="stylesheet" />

  <link rel="stylesheet" href="res/css/frameworks/semantic-ui/semantic.min.css" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  <link rel="stylesheet" href="res/css/main.css" />

  <?php require ROOT_DIR . "views/navs/main_nav.php"; ?>

  <?php
    if(!isset($_GET["section"])):
      require ROOT_DIR . "views/home.php";
    endif;
  ?>

Does anyone know why this is happening? Any help is appreciated!

UPDATE

I tried adding an empty script tag before my 3 main tags and somehow it is now being imported. It now looks like this:

Anyone know why this is happening?


答:
If you want that hovering the parent div will affect the child div you can use same approach only use the "animate" on children.

I've put a sample if you have only 1 child, but you can do it in a loop for all children of class "postinr"

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{

post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
    var child = this.getElementsByClassName("postinr")[0];
 child.style.setProperty("-webkit-transition", "margin-top 2s");
 child.style.setProperty("margin-top", "70px");
}
function animate2() {
    var child = this.getElementsByClassName("postinr")[0];
 child.style.setProperty("-webkit-transition", "margin-top 2s");
 child.style.setProperty("margin-top", "123px");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.post {
border: 1px solid red;
height: 100px;
width: 100px;}

.postinr {
border: 1px solid blue;
}</code>```

123

```

Title: Add event on inner class by mouseovering on outer class in html using javascript

Body:
I have class post and another class postinr defined in post class. I want to attach event to class postinr while mouseovering on class post. But I am unable to do that. What is the solution. Here is simple structure of html and javascript...`

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{
post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "70px");
}
function animate2() {
 this.style.setProperty("-webkit-transition", "margin-top 2s");
 this.style.setProperty("margin-top", "123px");
}

Body:
If you want that hovering the parent div will affect the child div you can use same approach only use the "animate" on children.

I've put a sample if you have only 1 child, but you can do it in a loop for all children of class "postinr"

var post=document.getElementsByClassName("post");
var postInner=document.getElementsByClassName("postinr");
var i;
for(i=0; i<postInner.length; i++)
{

post[i].addEventListener("mouseover",animate,false);
post[i].addEventListener("mouseout",animate2,false);
}
function animate() {
    var child = this.getElementsByClassName("postinr")[0];
 child.style.setProperty("-webkit-transition", "margin-top 2s");
 child.style.setProperty("margin-top", "70px");
}
function animate2() {
    var child = this.getElementsByClassName("postinr")[0];
 child.style.setProperty("-webkit-transition", "margin-top 2s");
 child.style.setProperty("margin-top", "123px");
}

.post {
border: 1px solid red;
height: 100px;
width: 100px;}

.postinr {
border: 1px solid blue;
}

<div class="post">
  <img src="" alt="">
  <div class="postinr">
 <h3>123</h3>
  </div>
</div>


问:
How to create a fetch primary key of the updated table on which we create a trigger?
I have a Product table and a ProductPriceLog table to maintain price of a product.
Assume product table has 3 fields [ProductId, ProductName, ProductPrice] and price history just has 2 fields [ProductId(fk), productprice]

I am attempting to write a trigger which would add a log entry each time we update the price of the product.

```<code>CREATE TRIGGER price_change_trg
ON PRODUCT
AFTER INSERT OR UPDATE OF ProductPrice ON PRODUCT
BEGIN

     INSERT INTO ProductPriceLog ( @idd , ProductPrice)
END;
</code>```

Specifically, how to I fetch the productId from the Product table's row which was updated?

答: If i understood your question you must use inserted table that has data that just inserted in product tableselect @idd=productid from inserted

Body:
I have a Product table and a ProductPriceLog table to maintain price of a product.
Assume product table has 3 fields [ProductId, ProductName, ProductPrice] and price history just has 2 fields [ProductId(fk), productprice]

I am attempting to write a trigger which would add a log entry each time we update the price of the product.

CREATE TRIGGER price_change_trg
ON PRODUCT
AFTER INSERT OR UPDATE OF ProductPrice ON PRODUCT
BEGIN

     INSERT INTO ProductPriceLog ( @idd , ProductPrice)
END;

Specifically, how to I fetch the productId from the Product table's row which was updated?


问:
iOS Swift Realm Sync Issue
I used this configuration code for local storage.

```<code>var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey() as Data
</code>```

I used this configuration code for sync with server.

```<code>let syncServerURL = URL(string: serverUrl + objectName!)!
var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey() as Data     configuration.syncConfiguration = SyncConfiguration(user: SyncUser.current!, realmURL: syncServerURL)
</code>```

I create some data without sync, it is saved locally. However, if I turn on sync(different configuration), the previously created data(locally) is not synced to the server? How to sync already saved data?

答:
Realms are uniquely referenced by one of three mutually exclusive Realm.Configuration properties:

fileURL

inMemoryIdentifier

syncConfiguration

Realm configurations with any of these properties with different values will refer to separate Realms.

So your initial Realm has a fileURL value (with nil for the other two properties), whereas your second Realm has a syncConfiguration value (with nil for the other two properties) so they refer to separate Realms.

If you wish to copy data from the first (local) Realm to the second (synced) Realm, you may do so using Realm's APIs for reading objects & creating objects just like you would for any other data.

Title: iOS Swift Realm Sync Issue

Body:
I used this configuration code for local storage.

var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey() as Data

I used this configuration code for sync with server.

let syncServerURL = URL(string: serverUrl + objectName!)!
var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = getKey() as Data     configuration.syncConfiguration = SyncConfiguration(user: SyncUser.current!, realmURL: syncServerURL)

I create some data without sync, it is saved locally. However, if I turn on sync(different configuration), the previously created data(locally) is not synced to the server? How to sync already saved data?


答:
You can refer my solution. Hope to help, my friend.</p>

```<code>CREATE TRIGGER price_change_trg
ON PRODUCT
AFTER INSERT, UPDATE
AS
BEGIN
declare @productId int;
declare @ProductPrice decimal(10,2);
select @productId = i.ProductId from inserted i;
select @ProductPrice = i.ProductPrice from inserted i;
     INSERT INTO ProductPriceLog VALUES ( @productId  , @ProductPrice )
END;
</code>```

Title: How to create a fetch primary key of the updated table on which we create a trigger?

Body:
You can refer my solution. Hope to help, my friend.

CREATE TRIGGER price_change_trg
ON PRODUCT
AFTER INSERT, UPDATE
AS
BEGIN
declare @productId int;
declare @ProductPrice decimal(10,2);
select @productId = i.ProductId from inserted i;
select @ProductPrice = i.ProductPrice from inserted i;
     INSERT INTO ProductPriceLog VALUES ( @productId  , @ProductPrice )
END;