问:
MDB onMessage() holds the connection in case of redelivering message
I need to redeliver a message if it can't be processed, for example because of some external endpoint failure. So I'm using following MDB configuration (it worth to mention that I'm using openMQ (Glassfish 4.1)):

```<code>@MessageDriven(mappedName = "MyQueue",  name = "MyQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "endpointExceptionRedeliveryAttempts", propertyValue = "10"),
@ActivationConfigProperty(propertyName = "endpointExceptionRedeliveryInterval", propertyValue = "30000")})
</code>```

Here's onMessage() method:

```<code>  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void onMessage (Message message)
  {
    try
    {
      //some processing here
    }
    catch (JMSException jmsException)
    {
      logger.log (Level.SEVERE, "Exception processing notification message", jmsException);
    }
    catch (BackingStoreException e)
    {
      // because of throwing RuntimeException, the message is going to be redelivered according to mdb configuration params(interval and attempts count)
      throw new RuntimeException ();
    }
  }
</code>```

In order to redeliver a message it's also possible to rollback a transaction, however openMQ lacks the property for redelivery interval, so it doesn't suites me:

https://github.com/javaee/openmq/issues/220

https://github.com/javaee/openmq/issues/23

https://github.com/javaee/openmq/issues/134

All in all, redelivery works fine, besides one moment: if message is going to be redelivered, mdb doesn't release the connection and holds it for endpointExceptionRedeliveryInterval * endpointExceptionRedeliveryAttempts, in my case 5 minutes. So, cause the default values for maxPoolSize is 32, 32 "bad" messages are enough to block the mdb.

Is there are way to release the connection in case of message redelivering?

答:
This is the expected behavior as per JMS specification and I do not think that there could be some way to release the connection object while some sort of message processing is under progress. Read JMS specs here and below is relevant except from "4.3.5 Closing a Connection":

If one or more of the connection’s session’s message listeners is
  processing a message at the point connection close is invoked, all the
  facilities of the connection and it’s sessions must remain available
  to those listeners until they return control to the JMS provider.

When connection close is invoked it should not return until message
  processing has been orderly shut down. This means that all message
  listeners that may have been running have returned and that all
  pending receives have returned.

I am not sure why you want to use such high numbers for retry mechanism, 10 attempts are too big to go for, maximum I have seen till now is 3 times, I think you can try to adjust your retry mechanism numbers, or may be having another connection which is dedicated to re-delivery.

Body:
I need to redeliver a message if it can't be processed, for example because of some external endpoint failure. So I'm using following MDB configuration (it worth to mention that I'm using openMQ (Glassfish 4.1)):

@MessageDriven(mappedName = "MyQueue",  name = "MyQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "endpointExceptionRedeliveryAttempts", propertyValue = "10"),
@ActivationConfigProperty(propertyName = "endpointExceptionRedeliveryInterval", propertyValue = "30000")})

Here's onMessage() method:

  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  public void onMessage (Message message)
  {
    try
    {
      //some processing here
    }
    catch (JMSException jmsException)
    {
      logger.log (Level.SEVERE, "Exception processing notification message", jmsException);
    }
    catch (BackingStoreException e)
    {
      // because of throwing RuntimeException, the message is going to be redelivered according to mdb configuration params(interval and attempts count)
      throw new RuntimeException ();
    }
  }

In order to redeliver a message it's also possible to rollback a transaction, however openMQ lacks the property for redelivery interval, so it doesn't suites me:

https://github.com/javaee/openmq/issues/220

https://github.com/javaee/openmq/issues/23

https://github.com/javaee/openmq/issues/134

All in all, redelivery works fine, besides one moment: if message is going to be redelivered, mdb doesn't release the connection and holds it for endpointExceptionRedeliveryInterval * endpointExceptionRedeliveryAttempts, in my case 5 minutes. So, cause the default values for maxPoolSize is 32, 32 "bad" messages are enough to block the mdb.

Is there are way to release the connection in case of message redelivering?


来源: stackexchange

问:
Change Add to Cart button in WooCommerce based on item Category
I am wanting to change the Add to Cart WooCommerce button when in the single item page based on the category of the item.

In my scenario, if it is a 'team-gear' category item I want the Add to Cart button to be replaced with a button that says "Order Request" and has a URL to my order request form. If it is any other category I would like the Add to Cart to remain the same.

I am completely unsure of the code to do this, though I keep reading it may take place in the functions.php file.

Any help would be greatly appreciated.

Thank you!

答:
simple and direct way:

1) copy the template file simple.php located in woocommerce/templates/single-product/add-to-cart/simple.php into your theme folder under /woocommerce/single-product/add-to-cart

2) change the code in simple.php by adding your conditions after make a query like $category = get_queried_object();
$category_ID = $category->term_id;
and the put insert your customized code for your cart

ContentLicense: CC BY-SA 3.0


问:
how could I use array in push operator on aggregation function, I got exception: aggregating group operators are unary ($push) error
I want to find all the patients who has got cough and headache in his/her all medical records

Every medical record contains two fields to record symptom, "SYMPTOM_1, SYMPTOM_2"

I queried by the follwoing query , but I got this error.

exception: aggregating group operators are unary ($push)

I expect to find the patients got cough and headache in his medical records history

And the expected results should be Mary and Jack

codes for cough : cough_codes = ["477  ","4770 "]
codes for headache : headache_codes = ["147  ","1470 "]

Here my query

```<code>cur= db_conn.medical_records.aggregate(
        [
            {"$match":{
                 "$and":[
                   {
                    "$or":[
                        {'SYMPTOM_1': '477  '},
                        {'SYMPTOM_2': '4770 '}
                      ]
                   },
                   {
                    "$or":[
                        {'SYMPTOM_1': '147  '},
                        {'SYMPTOM_2': '1470 '}
                      ]
                   },
                 ]
               }
            },
            { "$sort": { "APPL_DATE": 1}},
            { "$group":
                  {
                      "_id": "$ID",
                      "dis": { "$push": ["$SYMPTOM_1","$SYMPTOM_2"] }
                  }
            }
        ]
    ) # end of aggregate query
</code>```

Medical records

```<code>{
    "id": 1,
    "name": "Mary",
    "SYMPTOM_1": "4770  ",
    "SYMPTOM_2": "477  ",
    "datetime": "2011-04-02"
},

{
    "id": 2,
    "name": "Jack",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "4770  ",
    "datetime": "2011-04-02"
},

{
    "id": 3,
    "name": "Mark",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "4770  ",
    "datetime": "2010-01-02"
},

....

{
    "id": 4,
    "name": "Jack",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "1470  ",
    "datetime": "2015-04-09"
},

{
    "id": 5,
    "name": "Mary",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "147  ",
    "datetime": "2010-09-02"
}
</code>```

答:
You could use Accumulators:</p>

```<code>    Accumulators.push("dis",
                    new BasicDBObject("SYMPTOM_1", "$SYMPTOM_1")
                        .append("SYMPTOM_2", "$SYMPTOM_2"))
</code>```

Body:
I want to find all the patients who has got cough and headache in his/her all medical records

Every medical record contains two fields to record symptom, "SYMPTOM_1, SYMPTOM_2"

I queried by the follwoing query , but I got this error.

exception: aggregating group operators are unary ($push)

I expect to find the patients got cough and headache in his medical records history

And the expected results should be Mary and Jack

codes for cough : cough_codes = ["477  ","4770 "]
codes for headache : headache_codes = ["147  ","1470 "]

Here my query

cur= db_conn.medical_records.aggregate(
        [
            {"$match":{
                 "$and":[
                   {
                    "$or":[
                        {'SYMPTOM_1': '477  '},
                        {'SYMPTOM_2': '4770 '}
                      ]
                   },
                   {
                    "$or":[
                        {'SYMPTOM_1': '147  '},
                        {'SYMPTOM_2': '1470 '}
                      ]
                   },
                 ]
               }
            },
            { "$sort": { "APPL_DATE": 1}},
            { "$group":
                  {
                      "_id": "$ID",
                      "dis": { "$push": ["$SYMPTOM_1","$SYMPTOM_2"] }
                  }
            }
        ]
    ) # end of aggregate query

Medical records

{
    "id": 1,
    "name": "Mary",
    "SYMPTOM_1": "4770  ",
    "SYMPTOM_2": "477  ",
    "datetime": "2011-04-02"
},

{
    "id": 2,
    "name": "Jack",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "4770  ",
    "datetime": "2011-04-02"
},

{
    "id": 3,
    "name": "Mark",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "4770  ",
    "datetime": "2010-01-02"
},

....

{
    "id": 4,
    "name": "Jack",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "1470  ",
    "datetime": "2015-04-09"
},

{
    "id": 5,
    "name": "Mary",
    "SYMPTOM_1": "477  ",
    "SYMPTOM_2": "147  ",
    "datetime": "2010-09-02"
}

Body:
You could use Accumulators:

    Accumulators.push("dis",
                    new BasicDBObject("SYMPTOM_1", "$SYMPTOM_1")
                        .append("SYMPTOM_2", "$SYMPTOM_2"))


问:
Ruby on Rails: Many-to-Many Instance
New to rails. I'm creating a project with several database tables all in relation to each other. I would like to know how to add a foreign key reference to an instance after it has been created. Code below:

In schema:

```<code>    class Blog < ActiveRecord::Base
      has_many :posts
      has_many :owners
      has_many :users, through: :owners
    end

    class Owner < ActiveRecord::Base
      belongs_to :user
      belongs_to :blog
    end

    class User < ActiveRecord::Base
       has_many :messages
       has_many :posts
       has_many :owners
       has_many :blogs, through: :owners
    end
</code>```

Models:

```<code>class User < ActiveRecord::Base
   has_many :messages
   has_many :posts
   has_many :owners
   has_many :blogs, through: :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :owners
  has_many :users, through: :owners
end
</code>```

In rails console:

```<code>blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>
</code>```

答:
If you're trying to make it so that user1 becomes the owner of the blog, you could try

```<code>blog1 = Blog.first
user1 = User.first
Owner.create(user: user1, blog: blog1)
</code>```

or

```<code>Owner.create(user: User.first, blog:Blog.first)
</code>```

Hope I answered your question!

Title: Ruby on Rails: Many-to-Many Instance

Body:
New to rails. I'm creating a project with several database tables all in relation to each other. I would like to know how to add a foreign key reference to an instance after it has been created. Code below:

In schema:

    class Blog < ActiveRecord::Base
      has_many :posts
      has_many :owners
      has_many :users, through: :owners
    end

    class Owner < ActiveRecord::Base
      belongs_to :user
      belongs_to :blog
    end

    class User < ActiveRecord::Base
       has_many :messages
       has_many :posts
       has_many :owners
       has_many :blogs, through: :owners
    end

Models:

class User < ActiveRecord::Base
   has_many :messages
   has_many :posts
   has_many :owners
   has_many :blogs, through: :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :owners
  has_many :users, through: :owners
end

In rails console:

blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>

Body:
If you're trying to make it so that user1 becomes the owner of the blog, you could try

blog1 = Blog.first
user1 = User.first
Owner.create(user: user1, blog: blog1)

or

Owner.create(user: User.first, blog:Blog.first)

Hope I answered your question!


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
As several people have probably already answered, interfaces can be used to enforce certain behaviors between classes that will not implement those behaviors the same way.  So by implementing an interface you are saying that your class has the behavior of the interface.  The IAnimal interface would not be a typical interface because Dog, Cat, Bird, etc. classes are types of animals, and should probably extend it, which is a case of inheritance.  Instead, an interface would be more like animal behavior in this case, such as IRunnable, IFlyable, ITrainable, etc.

Interfaces are good for many things, one of the key things is pluggability.  For example, declaring a method that has a List parameter will allow for anything that implements the List interface to be passed in, allowing the developer to remove and plug in a different list at a later time without having to rewrite a ton of code.

It is possible you'll never use interfaces, but if you're designing a project from scratch, especially a framework of some sort, you'll probably want to get familiar with them.

I would recommend reading the chapter on interfaces in Java Design by Coad, Mayfield, and Kern.  They explain it a little better than the average introductory text.  If you don't use Java, you can just read the beginning of the chapter, which is just mainly concepts.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek

OwnerDisplayName: Ryan Thames

LastEditorDisplayName: Ryan Thames


问:
HapiJS start longer background process
How should I implement a PHP exec like call to a system function with HapiJS? The user submits a processing job that needs to run in the background for some time.

I somehow need to return a job id / session id to the user, run the job asynchronously, allow the user to check back for completion and reroute when completed...

I bet there are existing solutions for that, yet I'd highly welcome a pointer into the right direction.

答:
Check out node's child process documentation: here

To do what you are describing I would spawn a process without a callback and then use a little trick: trying to kill a process that isn't running causes an error see here

```<code>const exec = require('child_process').exec;

//Launch the process
const child = exec('ls');
const pid = child.pid;

//later in another scope when you are looking to see if it is running
try {
    process.kill(pid, 0);
}
catch (e) {
    console.log("it's finished");
}
</code>```

Title: HapiJS start longer background process

Body:
Check out node's child process documentation: here

To do what you are describing I would spawn a process without a callback and then use a little trick: trying to kill a process that isn't running causes an error see here

const exec = require('child_process').exec;

//Launch the process
const child = exec('ls');
const pid = child.pid;

//later in another scope when you are looking to see if it is running
try {
    process.kill(pid, 0);
}
catch (e) {
    console.log("it's finished");
}


问:
Why does std::vector not have an append method?
The recommendation for appending one vector to another (according to Concatenating two std::vectors) is to use:

```<code>vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
</code>```

Why does vector not have a method along the lines of:

```<code>vector1.append(vector2);
</code>```

The only reason that comes to mind is that it may be unclear exactly what append does.

答:
That's a pretty good reason. In fact, as an apt example, I think you've got the meaning of "append" wrong. I'd expect it to be equivalent to push_back (which exists), whereas you're looking for something more like "concatenate".

Why isn't there a concatenate function? Well, there could have been. But the standard doesn't like to give you things you don't really need, and (as you've shown) this operation is pretty easy to implement yourself.

Body:
The recommendation for appending one vector to another (according to Concatenating two std::vectors) is to use:

vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

Why does vector not have a method along the lines of:

vector1.append(vector2);

The only reason that comes to mind is that it may be unclear exactly what append does.


问:
Place imageview with fixed footer android
I want to place image approx full height and a fixed footer.
I tried this code.
Image is dynamically update using from gallery

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.aaaa.com.EditView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp"
        android:layout_alignParentBottom="true"
        android:id="@+id/footerEdit"
        android:weightSum="2">

        <Button
            android:id="@+id/addBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/icon_content" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/takePhoto"
            android:background="@drawable/icon_camera"/>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/imgview"/>
    </RelativeLayout>
</code>```

I want to scale image entire screen but leave footer area
Please guide

答:
When you are working with relative layouts, you still can manage Header and Footer (this last for you) indicating and order between the layouts.
For your main content area add:

```<code>android:layout_above="@id/lytFooter"
</code>```

to be set stacked over your footer
and

```<code>android:layout_below="@id/lytHeader"
</code>```

to be set stacked below your header.

For your main content area set height to match_parent.

Hope it helps.

Body:
I want to place image approx full height and a fixed footer.
I tried this code.
Image is dynamically update using from gallery

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.aaaa.com.EditView">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp"
        android:layout_alignParentBottom="true"
        android:id="@+id/footerEdit"
        android:weightSum="2">

        <Button
            android:id="@+id/addBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/icon_content" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/takePhoto"
            android:background="@drawable/icon_camera"/>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/imgview"/>
    </RelativeLayout>

I want to scale image entire screen but leave footer area
Please guide

Body:
When you are working with relative layouts, you still can manage Header and Footer (this last for you) indicating and order between the layouts.
For your main content area add:

android:layout_above="@id/lytFooter"

to be set stacked over your footer
and

android:layout_below="@id/lytHeader"

to be set stacked below your header.

For your main content area set height to match_parent.

Hope it helps.


问:
How to create user-accessible file on Android phone?
I am trying to save data from my app to a file, and than save this file on my PC. I've read many tutorials about file creation on external storage. Following this guides, i created the code below. The phone has no SD card, the external storage is on the internal memory. So there is my problem: the file exsist after using the "writeFunc", but it is empty. No any exception is thrown.
I tryed this part with all of the existing flags, sadly with no result:

FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);

The setReadable and setWritable functions return with "false", but no exception.

What should i do otherwise?

```<code>package com.track.fos;
//imports are okay

public class MainActivity extends AppCompatActivity {

public TextView textBox;
private File fileStruct;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textBox = (TextView) findViewById(R.id.textView);
    textBox.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString());

    fileStruct = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "lufiTestFile.txt" );
}

public void writeFunc(View view) {

    textBox.append("\nFilestruct to string: " + fileStruct.toString());
    Log.d("External storage state", Environment.getExternalStorageState(fileStruct));

    try {
        boolean stateInfo = fileStruct.exists();
        textBox.append("\nexist: " + stateInfo);

        if( !stateInfo ){
            //stateInfo = fileStruct.mkdirs();
            //textBox.append("\nmake dirs: " + stateInfo);
            stateInfo = fileStruct.createNewFile();
            textBox.append("\ncreateNewFile: " + stateInfo);
        }

        stateInfo = fileStruct.setReadable( true , false);
        textBox.append("\nsetReadable: " + stateInfo);
        stateInfo = fileStruct.setWritable( true, false );
        textBox.append("\nsetWritable: " + stateInfo);

        FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);
        fOut.write("Test text hopefuly inside the file.".getBytes());
        fOut.flush();
        fOut.close();
        textBox.append("\nFile written");
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("File write throws",e.getCause().toString());
        textBox.append("\nFile write failed");
    }
}

public void readFunc(View view) {

    try {
        FileInputStream fin = openFileInput( fileStruct.getName() );
        int c;
        String temp = "";
        while ((c = fin.read()) != -1) {
            temp = temp + Character.toString((char) c);
        }
        textBox.append("\n" + temp);
    } catch (Exception e) {
        e.printStackTrace();
        textBox.append("\nFile read failed");
    }
}
}
</code>```

答:
```<code>FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);
</code>```

That will not open a FileOutputStream for a file on external storage. openFileOutput() writes to internal storage.

Replace that with:

```<code>FileOutputStream fOut = new FileOutputStream(fileStruct);
</code>```

You will also need to ensure that the file gets indexed, so other apps and desktop OSes can see it.

Body:
I am trying to save data from my app to a file, and than save this file on my PC. I've read many tutorials about file creation on external storage. Following this guides, i created the code below. The phone has no SD card, the external storage is on the internal memory. So there is my problem: the file exsist after using the "writeFunc", but it is empty. No any exception is thrown.
I tryed this part with all of the existing flags, sadly with no result:

FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);

The setReadable and setWritable functions return with "false", but no exception.

What should i do otherwise?

package com.track.fos;
//imports are okay

public class MainActivity extends AppCompatActivity {

public TextView textBox;
private File fileStruct;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textBox = (TextView) findViewById(R.id.textView);
    textBox.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString());

    fileStruct = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "lufiTestFile.txt" );
}

public void writeFunc(View view) {

    textBox.append("\nFilestruct to string: " + fileStruct.toString());
    Log.d("External storage state", Environment.getExternalStorageState(fileStruct));

    try {
        boolean stateInfo = fileStruct.exists();
        textBox.append("\nexist: " + stateInfo);

        if( !stateInfo ){
            //stateInfo = fileStruct.mkdirs();
            //textBox.append("\nmake dirs: " + stateInfo);
            stateInfo = fileStruct.createNewFile();
            textBox.append("\ncreateNewFile: " + stateInfo);
        }

        stateInfo = fileStruct.setReadable( true , false);
        textBox.append("\nsetReadable: " + stateInfo);
        stateInfo = fileStruct.setWritable( true, false );
        textBox.append("\nsetWritable: " + stateInfo);

        FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);
        fOut.write("Test text hopefuly inside the file.".getBytes());
        fOut.flush();
        fOut.close();
        textBox.append("\nFile written");
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("File write throws",e.getCause().toString());
        textBox.append("\nFile write failed");
    }
}

public void readFunc(View view) {

    try {
        FileInputStream fin = openFileInput( fileStruct.getName() );
        int c;
        String temp = "";
        while ((c = fin.read()) != -1) {
            temp = temp + Character.toString((char) c);
        }
        textBox.append("\n" + temp);
    } catch (Exception e) {
        e.printStackTrace();
        textBox.append("\nFile read failed");
    }
}
}

Body:
FileOutputStream fOut = openFileOutput( fileStruct.getName(), MODE_WORLD_READABLE);

That will not open a FileOutputStream for a file on external storage. openFileOutput() writes to internal storage.

Replace that with:

FileOutputStream fOut = new FileOutputStream(fileStruct);

You will also need to ensure that the file gets indexed, so other apps and desktop OSes can see it.


问:
Accessing gradient values of keras model outputs with respect to inputs
I made a pretty simple NN model to do some non-linear regressions for me in Keras, as an introduction exercise. I uploaded my jupyter notebookit as a gist here (renders properly on github), which is pretty short and to the point.

It just fits the 1D function y = (x - 5)^2 / 25.

I know that Theano and Tensorflow are, at their core, graph based derivative (gradient) passing frameworks. And utilizing the gradients of loss functions with respect to weights for gradient step-based optimization are the main purpose of that.

But what I'm trying to get sense of is if I have access to something that, given a trained model, can approximate derivatives of inputs with respect to the output layer for me (not the weights or loss function). So for this case, I would want y' = 2(x-5)/25.0 estimated via the network's derivative graph for me for an indicated value of the input x, in the network's currently trained state.

Do I have any options in either the Keras or Theano/TF backend APIs to do this, or do I need to do my own chain ruling somehow with the weights (or maybe adding my own non-trainable "identity" layers or something)? In my notebook, you can see me trying a few approaches based what I was able to find so far, but without a ton of success.

To make it concrete, I have a working keras model with the structure:

```<code>model = Sequential()
# 1d input
model.add(Dense(64, input_dim=1, activation='relu'))
model.add(Activation("linear"))
model.add(Dense(32, activation='relu'))
model.add(Activation("linear"))
model.add(Dense(32, activation='relu'))
# 1d output
model.add(Dense(1))

model.compile(loss='mse', optimizer='adam', metrics=["accuracy"])
model.fit(x, y,
      batch_size=10,
      epochs=25,
      verbose=0,
      validation_data=(x_test, y_test))
</code>```

I would like to estimate the derivative of output y with respect to input x at, say, x = 0.5.

All of my attempts to extract gradient values based on searching for past answers have led to syntax errors. From a high level point of view, is this a supported feature of Keras, or is any solution going to be backend-specific?

答:
As you mention, Theano and TF are symbolic, so doing a derivative should be quite easy:

```<code>import theano
import theano.tensor as T
import keras.backend as K
J = T.grad(model.output[0, 0], model.input)
jacobian = K.function([model.input, K.learning_phase()], [J])
</code>```

First you compute the symbolic gradient (T.grad) of the output given the input, then you build a function that you can call and does the computation. Note that sometimes this is not that trivial due to shape problems, as you get one derivative for each element in the input.

Body:
I made a pretty simple NN model to do some non-linear regressions for me in Keras, as an introduction exercise. I uploaded my jupyter notebookit as a gist here (renders properly on github), which is pretty short and to the point.

It just fits the 1D function y = (x - 5)^2 / 25.

I know that Theano and Tensorflow are, at their core, graph based derivative (gradient) passing frameworks. And utilizing the gradients of loss functions with respect to weights for gradient step-based optimization are the main purpose of that.

But what I'm trying to get sense of is if I have access to something that, given a trained model, can approximate derivatives of inputs with respect to the output layer for me (not the weights or loss function). So for this case, I would want y' = 2(x-5)/25.0 estimated via the network's derivative graph for me for an indicated value of the input x, in the network's currently trained state.

Do I have any options in either the Keras or Theano/TF backend APIs to do this, or do I need to do my own chain ruling somehow with the weights (or maybe adding my own non-trainable "identity" layers or something)? In my notebook, you can see me trying a few approaches based what I was able to find so far, but without a ton of success.

To make it concrete, I have a working keras model with the structure:

model = Sequential()
# 1d input
model.add(Dense(64, input_dim=1, activation='relu'))
model.add(Activation("linear"))
model.add(Dense(32, activation='relu'))
model.add(Activation("linear"))
model.add(Dense(32, activation='relu'))
# 1d output
model.add(Dense(1))

model.compile(loss='mse', optimizer='adam', metrics=["accuracy"])
model.fit(x, y,
      batch_size=10,
      epochs=25,
      verbose=0,
      validation_data=(x_test, y_test))

I would like to estimate the derivative of output y with respect to input x at, say, x = 0.5.

All of my attempts to extract gradient values based on searching for past answers have led to syntax errors. From a high level point of view, is this a supported feature of Keras, or is any solution going to be backend-specific?

Body:
As you mention, Theano and TF are symbolic, so doing a derivative should be quite easy:

import theano
import theano.tensor as T
import keras.backend as K
J = T.grad(model.output[0, 0], model.input)
jacobian = K.function([model.input, K.learning_phase()], [J])

First you compute the symbolic gradient (T.grad) of the output given the input, then you build a function that you can call and does the computation. Note that sometimes this is not that trivial due to shape problems, as you get one derivative for each element in the input.


问:
Replace backward slashes with forwards slashes or double backward slashes in C++
So I have a string:

```<code>string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
</code>```

I want to replace all backward slashes in it with forward ones so it looks like:

```<code>C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug
</code>```

This does not work:

```<code>string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");
</code>```

Obviously, \ is an escape character so that is probably causing the problem.

答:
If you have something like this:

```<code>string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
</code>```

it every character proceded by '\' is special character. The correct way is

```<code>string path = "C:\\Users\\Richard\\Documents\\Visual Studio 2010\\Projects\\Client\\Debug";
</code>```

Use std::replace like Fred said.

Body:
So I have a string:

string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

I want to replace all backward slashes in it with forward ones so it looks like:

C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug

This does not work:

string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");

Obviously, \ is an escape character so that is probably causing the problem.

Body:
If you have something like this:

string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";

it every character proceded by '\' is special character. The correct way is

string path = "C:\\Users\\Richard\\Documents\\Visual Studio 2010\\Projects\\Client\\Debug";

Use std::replace like Fred said.


问:
Break s into next line starting from the left (rtl language)
I have some spans. They form a sentence:

```<code><span dir="rtl"> word4 </span>
<span dir="rtl"> word3 </span>
<span dir="rtl"> word2 </span>
<span dir="rtl"> word1 </span>
</code>```

It's written in a language which goes from right to left. So the last span contains the very first word. Now everything is displayed correctly as long as the sentence is displayed in one single line.

HOWEVER: When the sentence breaks, it will break the usual way, which means that what is the first word of the sentence, is now in the next line.

How can I make my spans break down on the left, so that the first span moves down into the next line first?

答:
What you probably want is the following:</p>

```<code><div dir="rtl">
  <span> word4 </span>
  <span> word3 </span>
  <span> word2 </span>
  <span> word1 </span>
</div>
</code>```

Title: Break <span>s into next line starting from the left (rtl language)

Body:
I have some spans. They form a sentence:

 word4
 word3
 word2
 word1

It's written in a language which goes from right to left. So the last span contains the very first word. Now everything is displayed correctly as long as the sentence is displayed in one single line.

HOWEVER: When the sentence breaks, it will break the usual way, which means that what is the first word of the sentence, is now in the next line.

How can I make my spans break down on the left, so that the first span moves down into the next line first?

Body:
What you probably want is the following:

<div dir="rtl">
  <span> word4 </span>
  <span> word3 </span>
  <span> word2 </span>
  <span> word1 </span>
</div>


问:
Xamarin Forms oncreate bundle null reference error
I have a simple Xamarin Forms app, but it says bundle is null oncreate.

At line:
global::Xamarin.Forms.Forms.Init(this, bundle);

The full error:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

```<code>    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());

        EMDKResults results = EMDKManager.GetEMDKManager(Android.App.Application.Context, this);

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

    }
</code>```

It worked a few hours ago. I don't see any changes that can cause this. How should I find the problem?

答:
I can't believe it!

Somehow I checked "Linking" to SDK Assemblies Only from None. This was the error. I checked it to None and it works again!

Body:
I have a simple Xamarin Forms app, but it says bundle is null oncreate.

At line:
global::Xamarin.Forms.Forms.Init(this, bundle);

The full error:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

    protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(bundle);

        global::Xamarin.Forms.Forms.Init(this, bundle);
        LoadApplication(new App());

        EMDKResults results = EMDKManager.GetEMDKManager(Android.App.Application.Context, this);

        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

    }

It worked a few hours ago. I don't see any changes that can cause this. How should I find the problem?


问:
Get path geometry from image
If i have a logo, let's say done as a jpg or even a png. Any suggestion for how I can use that to define a path geometry?  It would be really good if any suggestions could be provided for how i can do it in blend.
Thanks</p>

答:
I have a good idea but you're png, bmp, jpg or other non vector file is must be very simple because we need best scan results and only use inkscape.

Step: Drag and drop your file workspace on Inkscape, download free.

Tip: If your image is color white, Top menu item File->Document Properties-> heck Checkerboard Background and if you want uncheck Page border show.

Step: Top menu item Path-> Trace Bitmap-> Mode check what you want property, i usually use color property and if your file is png check Remove Background then click OK, then wait again Ok button is Enable and close window.

Step: Now you have a two layer, top layer vektor file and bottom layer your file. Select vector file and top menu item Edit-> XML Editor-> select svg path and look side column, d name propery in your data path value.

But this method may not always work or may not give the desired results and draw your own shapes with the scape so you can get the path data from the XML editor.

Example, my first tests this like:

and after working on it some more:

Title: Get path geometry from image

ContentLicense: CC BY-SA 4.0


问:
Wrong FS on loading json with spark from s3
I'm trying to load geojson file with spark and magellan library
My code for loading is:

```<code>val polygons = spark.read.format("magellan").option("type", "geojson").load(inJson)
</code>```

Where inJson is path to my json on s3:
s3n://bucket-name/geojsons/file.json

Error with stack trace:

0.3 in stage 0.0 (TID 3, ip-172-31-19-102.eu-west-1.compute.internal, executor 1): java.lang.IllegalArgumentException: Wrong FS:
  s3n://bucket-name/geojsons/file.json, expected:
  hdfs://ip-172-31-27-182.eu-west-1.compute.internal:8020   at
  org.apache.hadoop.fs.FileSystem.checkPath(FileSystem.java:653)    at
  org.apache.hadoop.hdfs.DistributedFileSystem.getPathName(DistributedFileSystem.java:194)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem.access$000(DistributedFileSystem.java:106)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem$3.doCall(DistributedFileSystem.java:304)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem$3.doCall(DistributedFileSystem.java:299)
    at
  org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:312)
    at org.apache.hadoop.fs.FileSystem.open(FileSystem.java:773)    at
  magellan.mapreduce.WholeFileReader.nextKeyValue(WholeFileReader.scala:45)
    at
  org.apache.spark.rdd.NewHadoopRDD$$anon$1.hasNext(NewHadoopRDD.scala:199)
    at
  org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:39)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)   at
  scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)    at
  scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)    at
  scala.collection.Iterator$class.foreach(Iterator.scala:893)   at
  scala.collection.AbstractIterator.foreach(Iterator.scala:1336)    at
  scala.collection.TraversableOnce$class.foldLeft(TraversableOnce.scala:157)
    at scala.collection.AbstractIterator.foldLeft(Iterator.scala:1336)
    at
  scala.collection.TraversableOnce$class.fold(TraversableOnce.scala:212)
    at scala.collection.AbstractIterator.fold(Iterator.scala:1336)  at
  org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$20.apply(RDD.scala:1086)
    at
  org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$20.apply(RDD.scala:1086)
    at
  org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1980)
    at
  org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1980)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)   at
  org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

The problem occurs only when I run it on more than one machine, so it works fine on EMR cluster with master and 1 instance in core group, but fails like that with 10 instances in core group

答: If you are running on EMR, you can just use "s3://bucket/path" instead of "s3n://...."</p>

Body:
I'm trying to load geojson file with spark and magellan library
My code for loading is:

val polygons = spark.read.format("magellan").option("type", "geojson").load(inJson)

Where inJson is path to my json on s3:
s3n://bucket-name/geojsons/file.json

Error with stack trace:

0.3 in stage 0.0 (TID 3, ip-172-31-19-102.eu-west-1.compute.internal, executor 1): java.lang.IllegalArgumentException: Wrong FS:
  s3n://bucket-name/geojsons/file.json, expected:
  hdfs://ip-172-31-27-182.eu-west-1.compute.internal:8020   at
  org.apache.hadoop.fs.FileSystem.checkPath(FileSystem.java:653)    at
  org.apache.hadoop.hdfs.DistributedFileSystem.getPathName(DistributedFileSystem.java:194)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem.access$000(DistributedFileSystem.java:106)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem$3.doCall(DistributedFileSystem.java:304)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem$3.doCall(DistributedFileSystem.java:299)
    at
  org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at
  org.apache.hadoop.hdfs.DistributedFileSystem.open(DistributedFileSystem.java:312)
    at org.apache.hadoop.fs.FileSystem.open(FileSystem.java:773)    at
  magellan.mapreduce.WholeFileReader.nextKeyValue(WholeFileReader.scala:45)
    at
  org.apache.spark.rdd.NewHadoopRDD$$anon$1.hasNext(NewHadoopRDD.scala:199)
    at
  org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:39)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)   at
  scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)    at
  scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)    at
  scala.collection.Iterator$class.foreach(Iterator.scala:893)   at
  scala.collection.AbstractIterator.foreach(Iterator.scala:1336)    at
  scala.collection.TraversableOnce$class.foldLeft(TraversableOnce.scala:157)
    at scala.collection.AbstractIterator.foldLeft(Iterator.scala:1336)
    at
  scala.collection.TraversableOnce$class.fold(TraversableOnce.scala:212)
    at scala.collection.AbstractIterator.fold(Iterator.scala:1336)  at
  org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$20.apply(RDD.scala:1086)
    at
  org.apache.spark.rdd.RDD$$anonfun$fold$1$$anonfun$20.apply(RDD.scala:1086)
    at
  org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1980)
    at
  org.apache.spark.SparkContext$$anonfun$33.apply(SparkContext.scala:1980)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)   at
  org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

The problem occurs only when I run it on more than one machine, so it works fine on EMR cluster with master and 1 instance in core group, but fails like that with 10 instances in core group


问:
How can I redirect the output of cppcheck into a file?
I would like to redirect the output of cppcheck to a text file. It prints a lot of information to stdout but if I run cppcheck --enable=all --verbose . > /srv/samba/share/tmp/cppcheck.out, I do not get all the information in the file. Why not? How can I get the results in a file?

答:
The latest dev version of cppcheck contains a new option:

```<code>--output-file=<file name>
</code>```

Add this option to direct the output into a specific file.

Usage example:

By default cppcheck prints its results to stdout:

```<code>$ cppcheck --enable=all test.cpp
  Checking test.cpp ...
  [test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
  (information) Cppcheck cannot find all the include files (use --check-config for details)
</code>```

You can use the option --output-file as follows to store the result in report.txt:

```<code>$ cppcheck --enable=all --output-file=report.txt test.cpp
Checking test.cpp ...
</code>```

Now the result is stored in report.txt:

```<code>$ more report.txt
[test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
(information) Cppcheck cannot find all the include files (use --check-config for details)
</code>```

As an alternative you could redirect the output to a file:

```<code>$ cppcheck --enable=all test.cpp 2> report.txt
Checking test.cpp ...
</code>```

Now the result is stored in report.txt:

```<code>$ more report.txt
[test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
(information) Cppcheck cannot find all the include files (use --check-config for details)
</code>```

Body:
The latest dev version of cppcheck contains a new option:

--output-file=<file name>

Add this option to direct the output into a specific file.

Usage example:

By default cppcheck prints its results to stdout:

$ cppcheck --enable=all test.cpp
  Checking test.cpp ...
  [test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
  (information) Cppcheck cannot find all the include files (use --check-config for details)

You can use the option --output-file as follows to store the result in report.txt:

$ cppcheck --enable=all --output-file=report.txt test.cpp
Checking test.cpp ...

Now the result is stored in report.txt:

$ more report.txt
[test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
(information) Cppcheck cannot find all the include files (use --check-config for details)

As an alternative you could redirect the output to a file:

$ cppcheck --enable=all test.cpp 2> report.txt
Checking test.cpp ...

Now the result is stored in report.txt:

$ more report.txt
[test.cpp:54]: (style) The scope of the variable 'middle' can be reduced.
(information) Cppcheck cannot find all the include files (use --check-config for details)


问:
OneNote ClassNotebook data from REST API has wrong students list
I'm running OneNote add-in that use OneNote REST APIs.

While investigating an issue from one of our user, I found the class notebook data from REST API only have one student in students field but the user said that there are more in OneNote app.

So, here is data from REST API. And I asked their class notebook manage screen and there is only one - But they see lists in OneNote app.

Is this something different type of notebook?

答:
The response indicates that single student entry is a group (see 'principalType'), while the teachers are of type 'Person'. It looks like the students were added as a group, which is why you only see that group in the API response and in the Add/Remove students screen. That group was expanded into its individual students when the notebook was created. The teacher will see the students in the OneNote client, but only the group in the Class Notebook Creator app.

You can use the Azure AD APIs to get the list of students who are part of that group.

By the way, the API response and screenshots you included contain some personal information that you may want to remove :)


问:
Conditional join in SQL depending on a column value
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

```<code>proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;
</code>```

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

答:
I would use two joins and a coalesce statement:

```<code>proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * coalesce(B1.perc_ress,B2.perc_ress) as variable1,
A.P_RVNE    * coalesce(B1.perc_ress,B2.perc_ress) as variable2
from      tableA    as A
left join tableB    as B1
    on A.cod_cia = 1 and A.cod_cia=B1.cod_cia and A.cod_agrup_produto=B1.cod_agrup_produto
left join tableB    as B2
    on  A.cod_cia=B2.cod_cia and A.projeto=B2.projeto;
</code>```

you could add A.cod_cia ne 1 in the second join, but it's not necessary unless.

Body:
I'm trying to do a join on a SAS table using PROC-SQL. Depending on the value of one variable in table A I need to join using a column, otherwise I need to use another column.

proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * B.perc_ress as variable1,
A.P_RVNE    * B.perc_ress as variable2
from      tableA    as A
left join tableB    as B
on case when A.cod_cia = 1 then A.cod_cia=B.cod_cia and A.cod_agrup_produto=B.cod_agrup_produto
                           else A.cod_cia=B.cod_cia and A.projeto=B.projeto;

I need to join just to create variable1 and variable2. I don't want to select any variable from table B.

My cod doesn't run. SAS gives me an error message saying that it is expecting an `end.

Does anyone know how to conditional join depending on columns?

Body:
I would use two joins and a coalesce statement:

proc sql;
create table test
as select
A.*,
A.PPNG_RVNE * coalesce(B1.perc_ress,B2.perc_ress) as variable1,
A.P_RVNE    * coalesce(B1.perc_ress,B2.perc_ress) as variable2
from      tableA    as A
left join tableB    as B1
    on A.cod_cia = 1 and A.cod_cia=B1.cod_cia and A.cod_agrup_produto=B1.cod_agrup_produto
left join tableB    as B2
    on  A.cod_cia=B2.cod_cia and A.projeto=B2.projeto;

you could add A.cod_cia ne 1 in the second join, but it's not necessary unless.


问:
Extract rows from a pandas dataframe between two rows
This is a sample of the data that I have.

```<code>T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0
</code>```

Is it possible to extract rows with 'A' in the first column between two rows with 'T' in first column and put into a new dataframe?

For example in this case
dataframe 1 would have

```<code>A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0
</code>```

and dataframe 2 would have

```<code>A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0
</code>```

thank you !

答:
A very natural way to split into separate dataframes is to use groupby.  I find where the first column is 'T' and use boolean indexing and cumsum to identify the groups.

```<code>m = df.iloc[:, 0].eq('T')
cumgrp = m.cumsum()[~m]
grps = df[~m].groupby(cumgrp)
</code>```

We can see the groups and print them by iterating through them.

```<code>for n, g in grps:
    print(n)
    print()
    print(g)
    print()

1

   0     1  2  3  4  5
1  A  1.42  1  1  0  0
2  A  1.42  1  2  0  0

2

   0     1  2  3  4  5
4  A  1.42  1  1  0  0
5  A  1.42  1  3  0  0
6  A  1.42  1  4  0  0
</code>```

You can get a list of these with

```<code>list_of_groups = [g for n, g in grps]
</code>```

Body:
This is a sample of the data that I have.

T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0
A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0
T| 1.42 | Test1 |   1|   0 |   0

Is it possible to extract rows with 'A' in the first column between two rows with 'T' in first column and put into a new dataframe?

For example in this case
dataframe 1 would have

A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   2|   0 |   0

and dataframe 2 would have

A| 1.42 |     1 |   1|   0 |   0
A| 1.42 |     1 |   3|   0 |   0
A| 1.42 |     1 |   4|   0 |   0

thank you !

Body:
A very natural way to split into separate dataframes is to use groupby.  I find where the first column is 'T' and use boolean indexing and cumsum to identify the groups.

m = df.iloc[:, 0].eq('T')
cumgrp = m.cumsum()[~m]
grps = df[~m].groupby(cumgrp)

We can see the groups and print them by iterating through them.

for n, g in grps:
    print(n)
    print()
    print(g)
    print()

1

   0     1  2  3  4  5
1  A  1.42  1  1  0  0
2  A  1.42  1  2  0  0

2

   0     1  2  3  4  5
4  A  1.42  1  1  0  0
5  A  1.42  1  3  0  0
6  A  1.42  1  4  0  0

You can get a list of these with

list_of_groups = [g for n, g in grps]


问:
How to hide blinking cursor in Angular 2?
I was working on search bar where user input the keyword. When the user hit the enter key, results are displayed. I want to implement in this way -

Whenever, user hits enter to search results for a keyword, you can see there is no blinking cursor at the end of keyword. This don't happen when you go to google.com and click on input box. At that time, we see a blinking cursor.

The problem I'm facing is that, when a user hits enter key, results are displayed but cursor remains blinking in search bar. What should I do to solve this problem so that clicking on input box should display a blinking cursor but on hitting enter key, it hides blinking cursor ?

NOTE - Since I don't know, how this problem is being generated I haven't provided the code. I just wanted to have some rough idea with code how should I proceed. :)

答:
This is done by taking the focus away from the input field, which requires a tiny bit of javascript.

I don't know how your code works as you aren't providing the code but form submit would be I imagine, how you would trigger the action on enter?

So I'll do a quick example...

We have a form which is populated with an input field.

var form = document.querySelector('#form');
var input = document.querySelector('#text');

form.onsubmit = function(e) {
  e.preventDefault();
  text.blur();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
  <input type="text" id="text">
</form></code>```

Using .blur takes the focus away from the input.

I miss read your question and saw that you were doing this with Angular, however I will leave the original answer there for anyone else that may stumble upon this answer.

To do it in Angular, it has a lovely attribute of ng-enter.

We can then add this to the input by doing <input type="text" ng-enter="$scope.blur()" />

Then we can create this action by doing

```<code>$scope.blur = function($event) {
    var input = $event.target;

    input.blur();
}
</code>```

Body:
This is done by taking the focus away from the input field, which requires a tiny bit of javascript.

I don't know how your code works as you aren't providing the code but form submit would be I imagine, how you would trigger the action on enter?

So I'll do a quick example...

We have a form which is populated with an input field.

var form = document.querySelector('#form');
var input = document.querySelector('#text');

form.onsubmit = function(e) {
  e.preventDefault();
  text.blur();
}

<form id="form">
  <input type="text" id="text">
</form>

Using .blur takes the focus away from the input.

I miss read your question and saw that you were doing this with Angular, however I will leave the original answer there for anyone else that may stumble upon this answer.

To do it in Angular, it has a lovely attribute of ng-enter.

We can then add this to the input by doing <input type="text" ng-enter="$scope.blur()" />

Then we can create this action by doing

$scope.blur = function($event) {
    var input = $event.target;

    input.blur();
}


问:
How to debug this WCF error?
When trying to run or reference the service project I get this error:

The type 'MyCompany.MyNameSpace.MyType', provided as  the Service attribute value in the ServiceHost directive could not be found.

Where to look to fix this?

Edit:
This is while running under the buit in vs 2008 cassini.

答:
Check your svc html file for the tag: <%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>

If explicitly setup in IIS make sure the virtual folder is a web application

You can enable WCF tracing by allowing me to link you to my blog post because I am evil and want to generate more traffic to my website to be all important :)
http://jtstroup.net/post/Wcf-Tracing.aspx

Title: How to debug this WCF error?


问:
jqPlot : $.jqPlot is not a function error
I need to create charts on a website.

In my HTML code i have created a div with an ID.

This is my HTML code :

```<code><script src="/js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/jquery.jqplot.min.css" />
<script language="javascript" type="text/javascript" src="/js/jquery.jqplot.js"></script>
<script language="javascript" type="text/javascript" src="/js/graph.js"></script>

<body>
    <div id="graph" style="height:400px;width:300px;></div> //i want to have my chart here
</body>
</code>```

In the js code i have only wrote an exemple from the official website of jqPlot :

```<code>$(document).ready(function() {
    var chart_data = [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]];
    var chart_opt = {
        title:'Graph',
        axes:{yaxis:{min:-10, max:240}},
        series:[{color:'#5FAB78'}]
    };
    $.jqplot('graph', chart_data, chart_opt);
});
</code>```

So my problem is that i have an error on the browser's console : $.jqplot is not a function

Any idea ?

答:
You are getting this error because you have the jqplot inside the $(document).ready(function(). Try something like this.

```<code> $(document).ready(function(){
   GetChart();
});

function GetChart(){
    var chart_data = [[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]];

    $('#graph').jqplot([chart_data], {
        title:'Default Bar Chart',
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer
            }
        }
    });
    }
</code>```

Here is a working example - https://jsfiddle.net/xrnfqax3/

For this example to work, you will need to add the following references to your project-

```<code>jquery.min.js
jquery.jqplot.js
jquery.jqplot.css
jqplot.barRenderer.js
jqplot.barRenderer.min.js
jqplot.categoryAxisRenderer.js
jqplot.categoryAxisRenderer.min.js
</code>```

Body:
I need to create charts on a website.

In my HTML code i have created a div with an ID.

This is my HTML code :

<link rel="stylesheet" type="text/css" href="/styles/jquery.jqplot.min.css" />

 //i want to have my chart here

In the js code i have only wrote an exemple from the official website of jqPlot :

$(document).ready(function() {
    var chart_data = [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]];
    var chart_opt = {
        title:'Graph',
        axes:{yaxis:{min:-10, max:240}},
        series:[{color:'#5FAB78'}]
    };
    $.jqplot('graph', chart_data, chart_opt);
});

So my problem is that i have an error on the browser's console : $.jqplot is not a function

Any idea ?

Body:
You are getting this error because you have the jqplot inside the $(document).ready(function(). Try something like this.

 $(document).ready(function(){
   GetChart();
});

function GetChart(){
    var chart_data = [[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]];

    $('#graph').jqplot([chart_data], {
        title:'Default Bar Chart',
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer
            }
        }
    });
    }

Here is a working example - https://jsfiddle.net/xrnfqax3/

For this example to work, you will need to add the following references to your project-

jquery.min.js
jquery.jqplot.js
jquery.jqplot.css
jqplot.barRenderer.js
jqplot.barRenderer.min.js
jqplot.categoryAxisRenderer.js
jqplot.categoryAxisRenderer.min.js


问:
C++ How to bind and invoke a templated type method
I'm trying to understand the syntax to bind to a templated type's method. This seemed similar to my question, but didn't seem to give an example of binding and calling a templated type method.

Here's my code sample:

```<code>#include <functional>
#include <iostream>

using namespace std;

void DidSomething(int x)
{
    cout << "Did something x = " << x << endl;
}

template <typename T>
class Outer
{
public:
    void StartSomething()
    {
        Inner inner;

        // below lines cause
        // error C2893 Failed to specialize function template
        //'unknown-type std::invoke(_Callable &&,_Types &&...)'

        auto fnGlobal = std::bind(&::DidSomething);
        inner.DoOneThing(fnGlobal);

        auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
        inner.DoOneThing(fnMethod);
    }

    void DidSomething(int x)
    {
        cout << "Did something x = " << x << endl;
    }

    // example typedef, the actual callback has a lot of args (5 args)
    typedef std::function<void(int)> DidSomethingCallback;

private:

    class Inner
    {
    public:
        void DoOneThing(DidSomethingCallback fnDidSomething)
        {
            fnDidSomething(3);
        }
    };

    T t;
};

int main()
{
    Outer<bool> outer;
    outer.StartSomething();

    return 0;
}
</code>```

答:
You are using std::bind the wrong way. You need to pass the corresponding number of arguments to be bound or placeholders as it may be when you create a std::bind object. Change:

```<code>    auto fnGlobal = std::bind(&::DidSomething);
    inner.DoOneThing(fnGlobal);

    auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
    inner.DoOneThing(fnMethod);
</code>```

to:

```<code>    auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);
    inner.DoOneThing(fnGlobal);

    auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);
    inner.DoOneThing(fnMethod);
</code>```

That should work

Body:
I'm trying to understand the syntax to bind to a templated type's method. This seemed similar to my question, but didn't seem to give an example of binding and calling a templated type method.

Here's my code sample:

#include <functional>
#include <iostream>

using namespace std;

void DidSomething(int x)
{
    cout << "Did something x = " << x << endl;
}

template <typename T>
class Outer
{
public:
    void StartSomething()
    {
        Inner inner;

        // below lines cause
        // error C2893 Failed to specialize function template
        //'unknown-type std::invoke(_Callable &&,_Types &&...)'

        auto fnGlobal = std::bind(&::DidSomething);
        inner.DoOneThing(fnGlobal);

        auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
        inner.DoOneThing(fnMethod);
    }

    void DidSomething(int x)
    {
        cout << "Did something x = " << x << endl;
    }

    // example typedef, the actual callback has a lot of args (5 args)
    typedef std::function<void(int)> DidSomethingCallback;

private:

    class Inner
    {
    public:
        void DoOneThing(DidSomethingCallback fnDidSomething)
        {
            fnDidSomething(3);
        }
    };

    T t;
};

int main()
{
    Outer<bool> outer;
    outer.StartSomething();

    return 0;
}

Body:
You are using std::bind the wrong way. You need to pass the corresponding number of arguments to be bound or placeholders as it may be when you create a std::bind object. Change:

    auto fnGlobal = std::bind(&::DidSomething);
    inner.DoOneThing(fnGlobal);

    auto fnMethod = std::bind(&Outer<T>::DidSomething, this);
    inner.DoOneThing(fnMethod);

to:

    auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);
    inner.DoOneThing(fnGlobal);

    auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);
    inner.DoOneThing(fnMethod);

That should work


问:
Adding jQuery to wordpress page to display Time/Date Picker
I found a Time picker here:
Time Picker.
It is the second one on the list with the grey square and 4 arrows. I need to know how to add this time picker to a WordPress page. When I downloaded all the JS files and the CSS files it included an HTML page. But, if I use the HTML code (below) the arrows are missing so selecting the time doesn't work like the original page. The download provides me with the js and css files needed I just don't know how to use them.

```<code><!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="jquery.timeentry.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jquery.plugin.js"></script>
<script src="jquery.timeentry.js"></script>
<script>
$(function () {
    $('#defaultEntry').timeEntry();
});
</script>
</head>
<body>
<h1>jQuery Time Entry Basics</h1>
<p>This page demonstrates the very basics of the
    <a href="http://keith-wood.name/timeEntry.html">jQuery Time Entry plugin</a>.
    It contains the minimum requirements for using the plugin and
    can be used as the basis for your own experimentation.</p>
<p>For more detail see the <a href="http://keith-wood.name/timeEntryRef.html">documentation reference</a> page.</p>
<p>Enter your time: <input type="text" id="defaultEntry" size="10"></p>
</body>
</html>
</code>```

These are the first two steps needed in the USAGE: section of the source page.

Include the jQuery library (1.7+) in the head section of your page.

Download and include the jQuery Time Entry CSS and JavaScript in the
  head section of your page.

I tried to add this code to my wordpress page on the text tab but I don't get the results I need:

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="/wp-content/jquery.timeentry.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="/wp-content/jquery.plugin.js"></script>
<script type="text/javascript" src="/wp-content/jquery.timeentry.js"></script>
<script type="text/javascript">
<!--
$('#spinnerOrange').timeEntry({spinnerImage: 'wp-content/spinnerOrange.png'});
//--></script>
</head>
<body>
<h1>jQuery Time Entry Basics</h1>
<p>This page demonstrates the very basics of the
    <a href="http://keith-wood.name/timeEntry.html">jQuery Time Entry plugin</a>.
    It contains the minimum requirements for using the plugin and
    can be used as the basis for your own experimentation.</p>
<p>For more detail see the <a href="http://keith-wood.name/timeEntryRef.html">documentation reference</a> page.</p>
<p>Enter your time: <input type="text" id="spinnerOrange" size="10"></p>
</body>
</html>
</code>```

I am not sure if I referenced the script right or the stylesheet. Any help would be greatly appreciated.

Thanks,
Matt

答:
jQuery is already included in Wordpress by default.
In order to add scripts, the right way to do it in Wordpress is using wp_enqueue_script

Here the doc: https://developer.wordpress.org/reference/functions/wp_enqueue_script/

Here a sample:
https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

Body:
I found a Time picker here:
Time Picker.
It is the second one on the list with the grey square and 4 arrows. I need to know how to add this time picker to a WordPress page. When I downloaded all the JS files and the CSS files it included an HTML page. But, if I use the HTML code (below) the arrows are missing so selecting the time doesn't work like the original page. The download provides me with the js and css files needed I just don't know how to use them.

<!doctype html>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="jquery.timeentry.css" rel="stylesheet">

jQuery Time Entry Basics

This page demonstrates the very basics of the
    jQuery Time Entry plugin.
    It contains the minimum requirements for using the plugin and
    can be used as the basis for your own experimentation.

For more detail see the documentation reference page.

Enter your time: <input type="text" id="defaultEntry" size="10">

These are the first two steps needed in the USAGE: section of the source page.

Include the jQuery library (1.7+) in the head section of your page.

Download and include the jQuery Time Entry CSS and JavaScript in the
  head section of your page.

I tried to add this code to my wordpress page on the text tab but I don't get the results I need:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="/wp-content/jquery.timeentry.css" rel="stylesheet">

jQuery Time Entry Basics

This page demonstrates the very basics of the
    jQuery Time Entry plugin.
    It contains the minimum requirements for using the plugin and
    can be used as the basis for your own experimentation.

For more detail see the documentation reference page.

Enter your time: <input type="text" id="spinnerOrange" size="10">

I am not sure if I referenced the script right or the stylesheet. Any help would be greatly appreciated.

Thanks,
Matt


问:
Firewall-rules, cannot specify ports and protocols
When I try to create a new firewall rule I suddenly can't specify any ports or protocols it just jumps back to allow all. Does anyone know how to solve this and why I can't specify ports and protocols?</p>

答:
I went to the the google cloud console on my phone and tried to create the firewal rule again, somehow on my phone I could specify the ports. I then tried it on my computer with a different browser and it worked. I deleted my browser history and now it works fine in both browsers. Not quite sure what the error was.

UPDATE: When using Google Chrome, everything seems to be working fine.


问:
Angular: How to filter out by style?
I am new to Angular, so this might seem easy. This is the HTML code:

```<code><div>
    Has Time: <input type="checkbox" ng-model="people_filter">
</div>
<ul style="list-style: none;">
    <li ng-repeat="human in people | orderBy:'name' | filter:people_filter ">
        <a href="#!/" ng-style="set_availability(human)">
            {{human.name}}
        </a>
    </li>
</ul>
</code>```

JS code:

```<code>$scope.set_availability = function(human) {
        if (the human has time) {
            return {
                    color: 'blue'
            };
        }

        return {
            color: 'red'
        };
    };
</code>```

When I inspect element:

```<code><a href="#!/" ng-style="set_availability(human)" class="ng-binding" style="color: blue;">
    John Lennon
</a>
</code>```

I have a checkbox with ng-model="people_filter".

If checked, I want it to filter out people who are available.

  If unchecked, I want to list all of the people.

The availability is reflected in ng-style="blue" (if yes) or ng-style="red" (if no). And it is working, I am able to see style="color:blue;" or style="color:red;".

Is there a quick fix for this?

答:
I think you want to change the color of the style based on the output of the function call. Please check this out.</p>

```<code>$availableHuman = [];
$scope.set_availability = function(human) {
            if (human.time) {
                availableHuman.push(human);
                return {
             "color:"+blue+";
                };
            }

            return {
                 "color:"+red+";
            };
        };

 <div class="list" ng-repeat="human in availableHuman">
  {{ human }}
</div>
</code>```

Title: Angular: How to filter out by style?

Body:
I am new to Angular, so this might seem easy. This is the HTML code:

    Has Time: <input type="checkbox" ng-model="people_filter">

            {{human.name}}

JS code:

$scope.set_availability = function(human) {
        if (the human has time) {
            return {
                    color: 'blue'
            };
        }

        return {
            color: 'red'
        };
    };

When I inspect element:

    John Lennon

I have a checkbox with ng-model="people_filter".

If checked, I want it to filter out people who are available.

  If unchecked, I want to list all of the people.

The availability is reflected in ng-style="blue" (if yes) or ng-style="red" (if no). And it is working, I am able to see style="color:blue;" or style="color:red;".

Is there a quick fix for this?

Body:
I think you want to change the color of the style based on the output of the function call. Please check this out.

$availableHuman = [];
$scope.set_availability = function(human) {
            if (human.time) {
                availableHuman.push(human);
                return {
             "color:"+blue+";
                };
            }

            return {
                 "color:"+red+";
            };
        };

 <div class="list" ng-repeat="human in availableHuman">
  {{ human }}
</div>


问:
Importing Dates into Access 2013
What types of date values will access recognize when you are importing? I have a csv file that has a date field that Excel recognizes but Access does not (data conversion error).</p>

答: When you are importing dates, the import form has a section which lets you define what format your dates are in. There is a chance your regional settings are also in play, so make sure the form matches your data. Remember that UK uses dd/mm/yyyy by default and the USA uses mm/dd/yyyy format.</p>

Title: Importing Dates into Access 2013


问:
Distinct command doesn't work
This is the command:

```<code>SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;
</code>```

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries

答: THE DISTINCT keyword operates on ALL select-list items that follow it, not just the next immediate column.  So, in your case, it IS (or would be) removing duplicates when ALL columns are considered.  The results you show all look individual over all the columns.</p>

Title: Distinct command doesn't work

Body:
This is the command:

SELECT DISTINCT T.TRIP_ID, T.TRIP_NAME, T.STATE, T.TYPE, S.TRIP_ID, S.TRIP_NAME

FROM TRIP T, TRIP S

WHERE T.STATE = 'NH'

AND T.TYPE = 'Hiking'

AND T.TRIP_ID < S.TRIP_ID

ORDER BY T.TRIP_NAME;

I should only getting about 6 results but somehow I get 298 repeated results. What's the problem with this code?

Correct result (6 entries)

My result (first few entries) which totals to 298 entries


答:
This is an option:

```<code>SELECT ids.id
  FROM ( SELECT @i
              , substring(@string, @start, @end-@start) id
            FROM <BigTable>
               , ( SELECT @string := <YourStringOfIds>
                        , @start:=0
                        , @end:=0
                        , @i:=0
                        , @len:=length(@string)
                        , @n:=@len-length(replace(@string,',',''))+1
                 ) t
            WHERE (@i := @i+1) <= @n
              AND (@start := @end+1)
              AND (@loc := locate(',',@string,@start))
              AND @end := if(@loc!=0,@loc,@len+1)
       ) ids
    LEFT JOIN <BigTable> u
      ON u.id = ids.id
  WHERE u.id is null
</code>```

BigTable can be any table whose number of rows >= number of ids in your string.

Title: Check which IDs from a set do not exists in a table

Body:
I have a list of user IDs, like this:

757392,733602,749955,744304,746852,753904,755117,636163,564931,740787,751450,743799,643918,
749903,571888,30207,705953,749120,749001,749192,749978,750840,544228,702121,746246,383667,
558790,585628,592771,745818,749375,241209,749235,746860,748318,748016,748951,747321,748684,
748225,565375,748673,747869,748522,748335,744775,672229,578056,713127,740234,632608,711135,
746528,362131,742223,746567,745224,332989,439837,745418,673582,269584,742606,745135,746950,
476134,740830,742949,276934

I have a MySQL table users with the id field.

How do I check - using a query - which IDs of the ones I have do not exists in the users table?

This sounds like a simple problem to me, yet I couldn't find any example on StackOverflow which would address a fixed set of ID values.

Body:
This is an option:

SELECT ids.id
  FROM ( SELECT @i
              , substring(@string, @start, @end-@start) id
            FROM <BigTable>
               , ( SELECT @string := <YourStringOfIds>
                        , @start:=0
                        , @end:=0
                        , @i:=0
                        , @len:=length(@string)
                        , @n:=@len-length(replace(@string,',',''))+1
                 ) t
            WHERE (@i := @i+1) <= @n
              AND (@start := @end+1)
              AND (@loc := locate(',',@string,@start))
              AND @end := if(@loc!=0,@loc,@len+1)
       ) ids
    LEFT JOIN <BigTable> u
      ON u.id = ids.id
  WHERE u.id is null

BigTable can be any table whose number of rows >= number of ids in your string.


问:
SQLException: No suitable driver found for jdbc:derby://localhost:1527
I get this error in Netbeans:

```<code>java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/
</code>```

How is this caused and how can I solve it?

答:
I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing:
In case you are using maven, likely you'll state the dependencies i.e:

```<code><groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>
</code>```

Please be careful with the version. It must be compatible with the server instance you are running.

I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.

So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.

Body:
I get this error in Netbeans:

java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/

How is this caused and how can I solve it?

Body:
I just bumped into this problem, tried all above suggestions but still failed. Without repeat what have been suggested above, here are the things I (you) may be missing:
In case you are using maven, likely you'll state the dependencies i.e:

<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.1.1</version>

Please be careful with the version. It must be compatible with the server instance you are running.

I solved my case by giving up on what maven dependencies provided and manually adding external jar from "%JAVA_HOME%\db\lib", the same source of my running server. In this case I'm testing using my Local.

So if you're testing with remote server instance, look for the derbyclient.jar that come with server package.


答:
std::bind requires you to specify placeholders for unbound arguments so that the return type will know how many arguments to expect and where to pass them to. Hence you must write:

```<code>auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);
</code>```

to tell it that fnGlobal takes one argument and should call ::DidSomething with that one argument. Otherwise, fnGlobal will take no arguments. Likewise

```<code>auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);
</code>```

will make fnMethod take one argument, call it x, then call this->DidSomething(x). Without the placeholder, fnMethod will take no arguments.

The clunkiness of std::bind makes it desirable to avoid using it in many cases. In the first case, it suffices to write

```<code>// the & is optional
auto fnGlobal = ::DidSomething;
</code>```

to make fnGlobal a normal function pointer. In the second case, a lambda can be used:

```<code>auto fnMethod = [this](int x) { DidSomething(x); };
</code>```

Title: C++ How to bind and invoke a templated type method

Body:
std::bind requires you to specify placeholders for unbound arguments so that the return type will know how many arguments to expect and where to pass them to. Hence you must write:

auto fnGlobal = std::bind(&::DidSomething, std::placeholders::_1);

to tell it that fnGlobal takes one argument and should call ::DidSomething with that one argument. Otherwise, fnGlobal will take no arguments. Likewise

auto fnMethod = std::bind(&Outer<T>::DidSomething, this, std::placeholders::_1);

will make fnMethod take one argument, call it x, then call this->DidSomething(x). Without the placeholder, fnMethod will take no arguments.

The clunkiness of std::bind makes it desirable to avoid using it in many cases. In the first case, it suffices to write

// the & is optional
auto fnGlobal = ::DidSomething;

to make fnGlobal a normal function pointer. In the second case, a lambda can be used:

auto fnMethod = [this](int x) { DidSomething(x); };


问:
How do I set a blank value for an f.select form field
I am using the following to allow my users to select their sex in their profile.

```<code><%= f.select (:sex, %w{ Male Female }) %>
</code>```

How would I create a blank value that the list would default to if nothing has been passed to the user.sex column? I am simply passing male or female as a string.

The purpose is I want a blank value so a validation can make sure they are aware they have to select it.

答:
There are two possibilities, depending on what you're after:

include_blank

```<code><%= f.select (:sex, %w{ Male Female }, :include_blank => true) %>
</code>```

This will always include a blank option in the select, which will allow people to set the value back to the blank value if they're seeing this on an edit form.

prompt

```<code><%= f.select (:sex, %w{ Male Female }, :prompt => "Gender...") %>
</code>```

This will include the specified prompt value, so long as the field hasn't already been set. If it has (on an edit form for example), there's no need to remind the user that they need to select a value so the prompt doesn't appear

Body:
I am using the following to allow my users to select their sex in their profile.

<%= f.select (:sex, %w{ Male Female }) %>

How would I create a blank value that the list would default to if nothing has been passed to the user.sex column? I am simply passing male or female as a string.

The purpose is I want a blank value so a validation can make sure they are aware they have to select it.

Body:
There are two possibilities, depending on what you're after:

include_blank

<%= f.select (:sex, %w{ Male Female }, :include_blank => true) %>

This will always include a blank option in the select, which will allow people to set the value back to the blank value if they're seeing this on an edit form.

prompt

<%= f.select (:sex, %w{ Male Female }, :prompt => "Gender...") %>

This will include the specified prompt value, so long as the field hasn't already been set. If it has (on an edit form for example), there's no need to remind the user that they need to select a value so the prompt doesn't appear


问:
sshtunnel not working in when used in a function
I am trying to create a sshtunnel to access my database. I am using the sshtunnel package together with SQLalchemy and pandas.

Example 1

```<code># run in terminal
ssh -L 5433:127.0.0.1:5432 [ssh_config]

# run in iPython
pd.read_sql_query(query, conn)
</code>```

When I create an ssh tunnel on my terminal and then run the query with pandas (see example above), it works fine and the DataFrame is returned.

Example 2

When I create the tunnel and then generate a connection in that context, it does not work.

```<code>with SSHTunnelForwarder(
    os.environ['SSH_ADDRESS'],
    ssh_username=os.environ['SSH_USER'],
    ssh_pkey=os.environ['SSH_PKEY'],
    remote_bind_address=('127.0.0.1', 5432),
    local_bind_address=('0.0.0.0', 5433)
) as sshserver:
    conn = self.engine.connect()
    pd.read_sql_query(query, conn)
    conn.close()
    sshserver.stop()
</code>```

The error message is:

```<code>OperationalError: (psycopg2.OperationalError) SSL SYSCALL error: EOF detected
[SQL: '\nselect \nid\n\nfrom \nclean.accounts \n\nlimit 10\n']
</code>```

The really curious thing is that this problem 'alternates'. What I mean by this is that running it once will cause the error message to occur. But if I run the function again, it returns the Dataframe. And if I try running it a third time, the error message appears again. This goes on indefinitely each time I run the command.

Does anyone have any idea what the problem is?

答:
I guess removing sshserver.stop() from last line will work for you.
When we are using with function to handle files or server connections; it itself take care of opening & closing the file or connection resp. There is no need to explicitly close the connection.

More description here

Body:
I am trying to create a sshtunnel to access my database. I am using the sshtunnel package together with SQLalchemy and pandas.

Example 1

# run in terminal
ssh -L 5433:127.0.0.1:5432 [ssh_config]

# run in iPython
pd.read_sql_query(query, conn)

When I create an ssh tunnel on my terminal and then run the query with pandas (see example above), it works fine and the DataFrame is returned.

Example 2

When I create the tunnel and then generate a connection in that context, it does not work.

with SSHTunnelForwarder(
    os.environ['SSH_ADDRESS'],
    ssh_username=os.environ['SSH_USER'],
    ssh_pkey=os.environ['SSH_PKEY'],
    remote_bind_address=('127.0.0.1', 5432),
    local_bind_address=('0.0.0.0', 5433)
) as sshserver:
    conn = self.engine.connect()
    pd.read_sql_query(query, conn)
    conn.close()
    sshserver.stop()

The error message is:

OperationalError: (psycopg2.OperationalError) SSL SYSCALL error: EOF detected
[SQL: '\nselect \nid\n\nfrom \nclean.accounts \n\nlimit 10\n']

The really curious thing is that this problem 'alternates'. What I mean by this is that running it once will cause the error message to occur. But if I run the function again, it returns the Dataframe. And if I try running it a third time, the error message appears again. This goes on indefinitely each time I run the command.

Does anyone have any idea what the problem is?


问:
cond fails when I add a puts function
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

```<code>   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end
</code>```

Is this the correct syntax for cond ? Why this error seems so random ?

答:
cond returns the value of the last expression in each body. The code fails because you end up returning :ok (the return value of IO.puts instead of the table); you need to return the updated table from the first clause (lo == vi):

```<code>cond do
  lo == vi ->
    table = put_in(table, [team], table[team] + 1)
    table = put_in(table, [vteam], table[vteam] + 1)
    IO.puts("TEST")
    table
  lo > vi ->
    put_in(table, [team], table[team] + 3)
  lo < vi ->
    put_in(table, [vteam], table[vteam] + 3)
end
</code>```

Title: cond fails when I add a puts function

Body:
I have a function that inside it's Enum.reduce tries to update a Map. Now I'm not sure you can do this but when the line IO.puts("TEST") is on, the code fails in the next iteration after printing TEST. If I remove that line, the code works.

   def to_table({team, matches}, table) do
    Enum.reduce matches, table, fn({vteam, result}, table) ->
      %{f: lo, a: vi} = result
      cond do
        lo == vi ->
          put_in(table, [team], table[team] + 1)
          put_in(table, [vteam], table[vteam] + 1)
          IO.puts("TEST")
        lo > vi ->
          put_in(table, [team], table[team] + 3)
        lo < vi ->
          put_in(table, [vteam], table[vteam] + 3)
      end
    end
  end

Is this the correct syntax for cond ? Why this error seems so random ?

Body:
cond returns the value of the last expression in each body. The code fails because you end up returning :ok (the return value of IO.puts instead of the table); you need to return the updated table from the first clause (lo == vi):

cond do
  lo == vi ->
    table = put_in(table, [team], table[team] + 1)
    table = put_in(table, [vteam], table[vteam] + 1)
    IO.puts("TEST")
    table
  lo > vi ->
    put_in(table, [team], table[team] + 3)
  lo < vi ->
    put_in(table, [vteam], table[vteam] + 3)
end