问:
Dilemma with Toast message
I'm developing a simple app, the user will have to fill in their name, email, rate the app, and describe their experience(optional). If their is an empty field(name and email), an error message will pop up. I'm having trouble with Toast.LENGTH_LONG() at the end of the code. It keep saying 'method call expected'.

MainActivity.java

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

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //Create an array adapter
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.rate_array, android.R.layout.simple_spinner_dropdown_item);

    //Specify the layout for the drop down menu
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    final EditText name = (EditText) findViewById(R.id.Name);
    final EditText e_mail = (EditText) findViewById(R.id.email);
    final Button submit = (Button) findViewById(R.id.submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(name.getText().length() == 0){
                name.setError("Please fill in your name");
            }
            else{
                if(e_mail.getText().length() == 0){
                    e_mail.setError("Please fill in your email");
                }
                else{
                    Toast.makeText(this, "Validation successful",
                    Toast.LENGTH_LONG()).show();
                }
            }
        }
    });

 }
}
</code>```

activity_main.xml

```<code><LinearLayout 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.example.infinite_space.myapplication.MainActivity"
android:orientation="vertical"
android:weightSum="1">

<TextView
    android:id="@+id/textView"
    android:layout_width="292dp"
    android:layout_height="37dp"
    android:text="Enter Feedback details to b sent to the developers"
    android:visibility="visible"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_weight="0.18" />

<EditText
    android:id="@+id/Name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your Name"
    android:inputType="textPersonName"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="67dp" />

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="35dp"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"
    tools:layout_editor_absoluteY="176dp"
    tools:layout_editor_absoluteX="16dp"
    android:prompt="@string/rate_level"
    android:entries="@array/rate_array" />

<EditText
    android:id="@+id/email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your email"
    android:inputType="textEmailAddress"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="122dp" />

<EditText
    android:id="@+id/details"
    android:layout_width="fill_parent"
    android:layout_height="103dp"
    android:ems="10"
    android:hint="Details..."
    android:inputType="text"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="227dp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Would you like an email respond ?"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="343dp" />

<Button
    android:id="@+id/submit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Feedback"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="385dp" />
</LinearLayout>
</code>```

答:
Try this :</p>

```<code> Toast.makeText(this, "Validation successful",Toast.LENGTH_LONG).show();
</code>```

Title: Dilemma with Toast message

Body:
I'm developing a simple app, the user will have to fill in their name, email, rate the app, and describe their experience(optional). If their is an empty field(name and email), an error message will pop up. I'm having trouble with Toast.LENGTH_LONG() at the end of the code. It keep saying 'method call expected'.

MainActivity.java

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

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //Create an array adapter
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.rate_array, android.R.layout.simple_spinner_dropdown_item);

    //Specify the layout for the drop down menu
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    final EditText name = (EditText) findViewById(R.id.Name);
    final EditText e_mail = (EditText) findViewById(R.id.email);
    final Button submit = (Button) findViewById(R.id.submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(name.getText().length() == 0){
                name.setError("Please fill in your name");
            }
            else{
                if(e_mail.getText().length() == 0){
                    e_mail.setError("Please fill in your email");
                }
                else{
                    Toast.makeText(this, "Validation successful",
                    Toast.LENGTH_LONG()).show();
                }
            }
        }
    });

 }
}

activity_main.xml

<LinearLayout 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.example.infinite_space.myapplication.MainActivity"
android:orientation="vertical"
android:weightSum="1">

<TextView
    android:id="@+id/textView"
    android:layout_width="292dp"
    android:layout_height="37dp"
    android:text="Enter Feedback details to b sent to the developers"
    android:visibility="visible"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_weight="0.18" />

<EditText
    android:id="@+id/Name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your Name"
    android:inputType="textPersonName"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="67dp" />

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="35dp"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"
    tools:layout_editor_absoluteY="176dp"
    tools:layout_editor_absoluteX="16dp"
    android:prompt="@string/rate_level"
    android:entries="@array/rate_array" />

<EditText
    android:id="@+id/email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your email"
    android:inputType="textEmailAddress"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="122dp" />

<EditText
    android:id="@+id/details"
    android:layout_width="fill_parent"
    android:layout_height="103dp"
    android:ems="10"
    android:hint="Details..."
    android:inputType="text"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="227dp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Would you like an email respond ?"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="343dp" />

<Button
    android:id="@+id/submit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Feedback"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="385dp" />
</LinearLayout>

Body:
Try this :

 Toast.makeText(this, "Validation successful",Toast.LENGTH_LONG).show();


来源: stackexchange

问:
which api's are available to find movie shows information?
I want to find shows of movie,show booking,price of shows, I am searching for api for that can any one tell me which api's are there for that.</p>

答:
It's not really related to the iPhone tag...

Anyway, you could check

The TV DataBase API for TV Shows

The Movie DataBase API for movies

ContentLicense: CC BY-SA 2.5


问:
How tetrieve in python
when I enter a value as a date in my interface how to retrieve it in python</p>

```<code>class Attachement(models.Model):
date_atta   =   fields.Date(string='Date Attachement')
</code>```

答:
for example if you need to retreive it from a method in the same class:

```<code>def your_method(self):
   yourfield = self.date_atta
</code>```

And you can use yourfield as you wish. I hope this help you.

ContentLicense: CC BY-SA 3.0

Title: How tetrieve in python

Body:
when I enter a value as a date in my interface how to retrieve it in python

class Attachement(models.Model):
date_atta   =   fields.Date(string='Date Attachement')

Body:
for example if you need to retreive it from a method in the same class:

def your_method(self):
   yourfield = self.date_atta

And you can use yourfield as you wish. I hope this help you.


问:
How do I get Gnuplot to "fill" out of range matrix-points with color of boundary?
I have a rather specific problem. I want to plot a electronic difference density using splot. The gridfile contains values from around -5 to up to 25. However, I am only interested in small values to find nodelines. So I would like to set palette such, that everything that is smaller/larger than the lower/upper boundary has the boundary color.
Here is what I use:

```<code>set key off
set view map
set palette defined (-0.01 'blue', 0 'white', 0.01 'red')
splot [][][-0.01:0.01] 'gridfile.dat' matrix with points pointtype 5 palette
</code>```

That gives me almost what I want - but instead of coloring the out of range points with the colors of the boundaries gnuplot just does nothing (so I get the color of the background there).

I tried fiddling around with cbrange, because according to the manual, that should do what I need:

Cbrange

The set cbrange command sets the range of values which are colored using the current palette by styles with pm3d, with image and with palette. Values outside of the color range use color of the nearest extreme.

However, that has not worked so far and I am running out of ideas (and out of possible google-searches).

Does anybody know how I could solve this?

答:
set cbrange is indeed what you are looking for, but not what the third bracket pair [-0.01:0.01] for splot does: that is the zrange. Use

```<code>set key off
set view map
set palette defined (-0.01 'blue', 0 'white', 0.01 'red')
set cbrange [-0.01:0.01]
splot 'gridfile.dat' matrix with points pointtype 5 palette
</code>```

Body:
I have a rather specific problem. I want to plot a electronic difference density using splot. The gridfile contains values from around -5 to up to 25. However, I am only interested in small values to find nodelines. So I would like to set palette such, that everything that is smaller/larger than the lower/upper boundary has the boundary color.
Here is what I use:

set key off
set view map
set palette defined (-0.01 'blue', 0 'white', 0.01 'red')
splot [][][-0.01:0.01] 'gridfile.dat' matrix with points pointtype 5 palette

That gives me almost what I want - but instead of coloring the out of range points with the colors of the boundaries gnuplot just does nothing (so I get the color of the background there).

I tried fiddling around with cbrange, because according to the manual, that should do what I need:

Cbrange

The set cbrange command sets the range of values which are colored using the current palette by styles with pm3d, with image and with palette. Values outside of the color range use color of the nearest extreme.

However, that has not worked so far and I am running out of ideas (and out of possible google-searches).

Does anybody know how I could solve this?

Body:
set cbrange is indeed what you are looking for, but not what the third bracket pair [-0.01:0.01] for splot does: that is the zrange. Use

set key off
set view map
set palette defined (-0.01 'blue', 0 'white', 0.01 'red')
set cbrange [-0.01:0.01]
splot 'gridfile.dat' matrix with points pointtype 5 palette


问:
XML Relationship
I am unable to define a relationship between paper and author. Is it possible to define one?</p>

```<code><xsd:complextype name="Researcher'>
</xsd:complextype>
<xsd:complexType name = "Paper" >
      <xsd:extension base = " Researcher " >
      </xsd:extension>
  </xsd:complexType>
<xsd:complexType name = "Author">
      <xsd:extension base = " Researcher ">
      </xsd:extension>
</xsd:complexType>
</code>```

答:
I assume you want a 'paper' to have an 'author'.  The way I do this in my schemas is to have a list of authors and a list of papers.  Something like this:

```<code><papers>

<authorlist>
    <author>Bob Barr</author>
    <author>Ron Paul</author>
    <author>Ralph Nader</author>
</authorlist>

<paperlist>
    <paper>
       <title>How to Revert Your Economy to the Gold Standard</title>
       <author>Ron Paul</author>
    </paper>
    <paper>
        <title>Unsafe at any Speed</title>
        <author>Ralph Nader</author>
    </paper>
     <paper>
         <title>How to be a Viable 3rd Party Candidate</title>
         <author>Bob Barr</author>
     </paper>
 </paperlist>
 </papers>
</code>```

The tabbing is messed up, but in my example every paper/author has to refer to an authorlist/author.  I would use schema code similar to this to achieve the desired effect:

```<code><xsd:element name="paper" type="Papers_Type">
    <xsd:unique name="Author_Key">
        <xsd:selector xpath="authorlist/author">
        <xsd:field xpath="text()"/>
    </xsd:key>
    <xsd:keyref name="Paper_Author_AuthorRef" refer="AuthorKey">
         <xsd:selector xpath="paperlist/paper/author"/>
         <xsd:field xpath="text()"/>
    </xsd:keyref>
</xsd:element>

<xsd:complextype name="Papers_Type">
    <!--Enter element definitions to your liking here-->
</xsd:complextype>
</code>```

So papers/paperlist/paper/author has to correspond to papers/authorlist/author otherwise validation will throw an error.  Good luck!

LastEditorDisplayName: Eddie

Title: XML Relationship

Body:
I am unable to define a relationship between paper and author. Is it possible to define one?

<xsd:complextype name="Researcher'>
</xsd:complextype>
<xsd:complexType name = "Paper" >
      <xsd:extension base = " Researcher " >
      </xsd:extension>
  </xsd:complexType>
<xsd:complexType name = "Author">
      <xsd:extension base = " Researcher ">
      </xsd:extension>
</xsd:complexType>

Body:
I assume you want a 'paper' to have an 'author'.  The way I do this in my schemas is to have a list of authors and a list of papers.  Something like this:

<papers>

<authorlist>
    <author>Bob Barr</author>
    <author>Ron Paul</author>
    <author>Ralph Nader</author>
</authorlist>

<paperlist>
    <paper>
       <title>How to Revert Your Economy to the Gold Standard</title>
       <author>Ron Paul</author>
    </paper>
    <paper>
        <title>Unsafe at any Speed</title>
        <author>Ralph Nader</author>
    </paper>
     <paper>
         <title>How to be a Viable 3rd Party Candidate</title>
         <author>Bob Barr</author>
     </paper>
 </paperlist>
 </papers>

The tabbing is messed up, but in my example every paper/author has to refer to an authorlist/author.  I would use schema code similar to this to achieve the desired effect:

<xsd:element name="paper" type="Papers_Type">
    <xsd:unique name="Author_Key">
        <xsd:selector xpath="authorlist/author">
        <xsd:field xpath="text()"/>
    </xsd:key>
    <xsd:keyref name="Paper_Author_AuthorRef" refer="AuthorKey">
         <xsd:selector xpath="paperlist/paper/author"/>
         <xsd:field xpath="text()"/>
    </xsd:keyref>
</xsd:element>

<xsd:complextype name="Papers_Type">
    <!--Enter element definitions to your liking here-->
</xsd:complextype>

So papers/paperlist/paper/author has to correspond to papers/authorlist/author otherwise validation will throw an error.  Good luck!

OwnerDisplayName: Stephen Friederichs


问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答: I think, from a maintenance point of view, as shallow an inheritance hierarchy as you can manage is the way to go.  Tracing bugs down through multiple hierarchical levels, and then having to figure out at which level they should then be fixed can be a tricky one.</p>

Title: How many levels of inheritance


问:
AngularJS- How to filter by property/ attribute of an object- forEach is not a function
I have an AngularJS application, and on one of the pages, there are a number of widgets displayed. One of the widgets displays a table containing information about a system that is being monitored by the application. This table currently contain two columns: a 'Type' column, displaying the type of information shown in that row; and a 'Data' column, displaying the value of the variable that holds that information.

It is possible to customise the information displayed on the widget using a dialog that is opened when the 'Settings' button is clicked on the widget toolbar. There are 'Columns' and 'Rows' text input fields on that dialog which are used to set the columns headings and rows to be displayed in the table. Currently, when the user starts typing into the 'Rows' text input field, a drop down list is displayed showing the user the variables that are available to be displayed in the table, and that match what the user has typed (i.e. as they continue to type, the list of options available will get more specific).

The function used to display this drop down to the user while they type in the text input field is:

```<code>$scope.autocompleteVarsFilter = function(query) {
    if(!query && lastVarQryKw) {
        query = lastVarQryKw;
    }
    var result = Object.keys(fxVar.getVars()).filter(function(name) {
        return name.indexOf(query.toLowerCase()) !== -1;
    });

    if(result.length > 0) {
        lastVarQryKw = query;
    }
    return result;
};
</code>```

I am currently trying to add a third column to that table, to display a link to a given page that the user will choose. I decided that a 'link' would be denoted by a string starting with the character : (i.e. if the user types in :index, that would be a link to the home page of the site).

As soon as the user types :, the full list of available pages should be displayed in a 'drop-down', and as the user continues to type, this list should be filtered based on what they are typing (as it is with variable names)

I have updated my function as follows:

```<code>$scope.autocompleteVarsFilter = function(query) {
    if(query.startWith(":") {
        var buttonsQuery = query.substring(1);
        if(!buttonsQuery && lastVarQryKw) {
            buttonsQuery = lastVarQryKw;
        }

        var userPages = pagesPresets; //This is getting the full list of available pages from a service called 'pagesPresets'
        console.log("Value of userPages: ", userPages);

        var page;
        for(page in userPages) {
            console.log("for loop started");
            if(page.key.startWith(buttonsQuery)) {
                console.log("Matching page found: ", page);
            }
        }

        if(result.length > 0) {
            lastVarQryKw = query;
        }
        return result;

    } else {
        if(!query && lastVarQryKw) {
            query = lastVarQryKw;
        }
        var result = Object.keys(fxVar.getVars()).filter(function(name) {
            return name.indexOf(query.toLowerCase()) !== -1;
        });

        if(result.length > 0) {
            lastVarQryKw = query;
        }

        return result;
    }
};
</code>```

The else clause of the if statement is doing what the function was originally doing (i.e. displaying the available variables), and currently still works as intended. However, when testing this feature, if I now type : followed by any string into the text input field, the if clause runs, but the available pages are not displayed in a drop down, and I see the following output displayed in the console by my console.log() statements:

Value of userPages:

0: {_id: "...", _rev: 1, _url: "...", key: "pages/auth", {...}, ...}

1: {_id: "...", _rev: 13, _url: "...", key: "pages/userpage2", value: {...}, ...}

2: {_id: "...", _rev:13, _url: "...", key: "pages/", value: "/pages/userpage1", ...}

for loop started

TypeError: Cannot read property 'startsWith' of undefined

The issue seems to be that I can't reference the key attribute/ property of the userpage objects to match their value to the value that the user is typing into the text box.

Given that I can see that the page objects I'm using have an attribute key that holds the value I want to filter by, how do I actually get hold of this key attribute to use it?

I tried changing that for loop to:

```<code>var page;
var key;
for(page in userPages) {
    console.log("for loop started");
    key = page.getAttribute("key");
    if(key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page);
    }
}
</code>```

but this just gives the output:

for loop started

TypeError: page.getAttribute is not a function

Anyone have any suggestions?

Edit

I tried doing what @Alex K suggested in their answer, and updated the for loop in my function to:

```<code>var page;
var pageKey;
var key;
var result;

console.log("Iterating using foreach");
for(page in userPages) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
};
</code>```

I also tried updating it to:

```<code>userPages.forEach(function(page) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
});
</code>```

and:

```<code>userPages.forEach(function(page) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
});
</code>```

But these all gave the same output in the console, which was:

Iterating using foreach

ctrl.js:483 Matching page found:  pages/userpage2

ctrl.js:483 Matching page found:  pages/userpage1

ctrl.js:483 Matching page found:  pages/

ctrl.js:483 Matching page found:  pages/pagetitle

ctrl.js:483 Matching page found:  pages/auth

```<code>angular.js:10160 TypeError: a.forEach is not a function
at Object.b.makeObjectArray (ng-tags-input.min.js:1)
at ng-tags-input.min.js:1
at wrappedCallback (angular.js:11735)
at wrappedCallback (angular.js:11735)
at angular.js:11821
at Scope.$eval (angular.js:12864)
at Scope.$digest (angular.js:12676)
at Scope.$apply (angular.js:12968)
at angular.js:14494
at completeOutstandingRequest (angular.js:4413)
</code>```

So clearly the line from inside the if statement was being run, because I was getting all of those print statements in the console, and yet for some reason, it thinks that forEach is not a function...

Anyone have any suggestions for how to fix this?

答:
A for...in loop iterates over the enumerable property names of an object. You then need to access the object using that property name to get the value. Here's an example:

console.log('Using for...in on an object:');

var myObj = {
  'prop1': 'Hello world!',
  'prop2': 12345,
  'some crazy property': null
};

for (var propName in myObj) {

  console.log('propName is ' + propName);

  //Now we can lookup the value using that property name.
  var propValue = myObj[propName];

  console.log('myObj[' + propName + '] is ' + propValue);

}```
</div>
</div>
</p>

<p>In contrast, a <code>forEach</code> loop iterates directly over the <strong>values</strong> of an <strong>array</strong>. Your callback function is provided the value directly, so you don't need to access the array to retrieve it. Example: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log('Using forEach on an array:');

var myArray = [
  {key: 'this is object 1!'},
  {key: 'this is object 2!'}
];

myArray.forEach(function (obj) {

  console.log('in ForEach loop...');

  console.log('obj is ' + JSON.stringify(obj));

  //We can directly access the object's properties as needed
  console.log('obj.key is ' + obj.key);

});</code>```

So, here's how you can update your code using for...in or using forEach:

var buttonsQuery = 'pages/userpage2';

var userPages = [{
    _id: "...",
    _rev: 1,
    _url: "...",
    key: "pages/auth"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/userpage2"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/",
    value: "/pages/userpage1"
  }
]

console.log('Iterating using for...in');
for (var prop in userPages) {

  console.log('prop is ' + prop);

  //Access the page object using the property name
  var page = userPages[prop];

  console.log('page is ' + JSON.stringify(page));

  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
}

//Better way to iterate if userPages is an array:
console.log('iterating using forEach');
userPages.forEach(function(page) {

  //page is already the object we're interested in.
  //No need to access the array again.
  console.log('page is ' + JSON.stringify(page));

  //Access the object's properties as needed
  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
});```

You can also use a for...of loop to iterate, but that's not supported in IE.

Body:
I have an AngularJS application, and on one of the pages, there are a number of widgets displayed. One of the widgets displays a table containing information about a system that is being monitored by the application. This table currently contain two columns: a 'Type' column, displaying the type of information shown in that row; and a 'Data' column, displaying the value of the variable that holds that information.

It is possible to customise the information displayed on the widget using a dialog that is opened when the 'Settings' button is clicked on the widget toolbar. There are 'Columns' and 'Rows' text input fields on that dialog which are used to set the columns headings and rows to be displayed in the table. Currently, when the user starts typing into the 'Rows' text input field, a drop down list is displayed showing the user the variables that are available to be displayed in the table, and that match what the user has typed (i.e. as they continue to type, the list of options available will get more specific).

The function used to display this drop down to the user while they type in the text input field is:

$scope.autocompleteVarsFilter = function(query) {
    if(!query && lastVarQryKw) {
        query = lastVarQryKw;
    }
    var result = Object.keys(fxVar.getVars()).filter(function(name) {
        return name.indexOf(query.toLowerCase()) !== -1;
    });

    if(result.length > 0) {
        lastVarQryKw = query;
    }
    return result;
};

I am currently trying to add a third column to that table, to display a link to a given page that the user will choose. I decided that a 'link' would be denoted by a string starting with the character : (i.e. if the user types in :index, that would be a link to the home page of the site).

As soon as the user types :, the full list of available pages should be displayed in a 'drop-down', and as the user continues to type, this list should be filtered based on what they are typing (as it is with variable names)

I have updated my function as follows:

$scope.autocompleteVarsFilter = function(query) {
    if(query.startWith(":") {
        var buttonsQuery = query.substring(1);
        if(!buttonsQuery && lastVarQryKw) {
            buttonsQuery = lastVarQryKw;
        }

        var userPages = pagesPresets; //This is getting the full list of available pages from a service called 'pagesPresets'
        console.log("Value of userPages: ", userPages);

        var page;
        for(page in userPages) {
            console.log("for loop started");
            if(page.key.startWith(buttonsQuery)) {
                console.log("Matching page found: ", page);
            }
        }

        if(result.length > 0) {
            lastVarQryKw = query;
        }
        return result;

    } else {
        if(!query && lastVarQryKw) {
            query = lastVarQryKw;
        }
        var result = Object.keys(fxVar.getVars()).filter(function(name) {
            return name.indexOf(query.toLowerCase()) !== -1;
        });

        if(result.length > 0) {
            lastVarQryKw = query;
        }

        return result;
    }
};

The else clause of the if statement is doing what the function was originally doing (i.e. displaying the available variables), and currently still works as intended. However, when testing this feature, if I now type : followed by any string into the text input field, the if clause runs, but the available pages are not displayed in a drop down, and I see the following output displayed in the console by my console.log() statements:

Value of userPages:

0: {_id: "...", _rev: 1, _url: "...", key: "pages/auth", {...}, ...}

1: {_id: "...", _rev: 13, _url: "...", key: "pages/userpage2", value: {...}, ...}

2: {_id: "...", _rev:13, _url: "...", key: "pages/", value: "/pages/userpage1", ...}

for loop started

TypeError: Cannot read property 'startsWith' of undefined

The issue seems to be that I can't reference the key attribute/ property of the userpage objects to match their value to the value that the user is typing into the text box.

Given that I can see that the page objects I'm using have an attribute key that holds the value I want to filter by, how do I actually get hold of this key attribute to use it?

I tried changing that for loop to:

var page;
var key;
for(page in userPages) {
    console.log("for loop started");
    key = page.getAttribute("key");
    if(key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page);
    }
}

but this just gives the output:

for loop started

TypeError: page.getAttribute is not a function

Anyone have any suggestions?

Edit

I tried doing what @Alex K suggested in their answer, and updated the for loop in my function to:

var page;
var pageKey;
var key;
var result;

console.log("Iterating using foreach");
for(page in userPages) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
};

I also tried updating it to:

userPages.forEach(function(page) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
});

and:

userPages.forEach(function(page) {
    page = userPages[page];
    if(page.key.startsWith(buttonsQuery)) {
        console.log("Matching page found: ", page.key);
        pageKey = page.key;
        result = pageKey;
    }
});

But these all gave the same output in the console, which was:

Iterating using foreach

ctrl.js:483 Matching page found:  pages/userpage2

ctrl.js:483 Matching page found:  pages/userpage1

ctrl.js:483 Matching page found:  pages/

ctrl.js:483 Matching page found:  pages/pagetitle

ctrl.js:483 Matching page found:  pages/auth

angular.js:10160 TypeError: a.forEach is not a function
at Object.b.makeObjectArray (ng-tags-input.min.js:1)
at ng-tags-input.min.js:1
at wrappedCallback (angular.js:11735)
at wrappedCallback (angular.js:11735)
at angular.js:11821
at Scope.$eval (angular.js:12864)
at Scope.$digest (angular.js:12676)
at Scope.$apply (angular.js:12968)
at angular.js:14494
at completeOutstandingRequest (angular.js:4413)

So clearly the line from inside the if statement was being run, because I was getting all of those print statements in the console, and yet for some reason, it thinks that forEach is not a function...

Anyone have any suggestions for how to fix this?

Body:
A for...in loop iterates over the enumerable property names of an object. You then need to access the object using that property name to get the value. Here's an example:

console.log('Using for...in on an object:');

var myObj = {
  'prop1': 'Hello world!',
  'prop2': 12345,
  'some crazy property': null
};

for (var propName in myObj) {

  console.log('propName is ' + propName);

  //Now we can lookup the value using that property name.
  var propValue = myObj[propName];

  console.log('myObj[' + propName + '] is ' + propValue);

}

In contrast, a forEach loop iterates directly over the values of an array. Your callback function is provided the value directly, so you don't need to access the array to retrieve it. Example:

console.log('Using forEach on an array:');

var myArray = [
  {key: 'this is object 1!'},
  {key: 'this is object 2!'}
];

myArray.forEach(function (obj) {

  console.log('in ForEach loop...');

  console.log('obj is ' + JSON.stringify(obj));

  //We can directly access the object's properties as needed
  console.log('obj.key is ' + obj.key);

});

So, here's how you can update your code using for...in or using forEach:

var buttonsQuery = 'pages/userpage2';

var userPages = [{
    _id: "...",
    _rev: 1,
    _url: "...",
    key: "pages/auth"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/userpage2"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/",
    value: "/pages/userpage1"
  }
]

console.log('Iterating using for...in');
for (var prop in userPages) {

  console.log('prop is ' + prop);

  //Access the page object using the property name
  var page = userPages[prop];

  console.log('page is ' + JSON.stringify(page));

  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
}

//Better way to iterate if userPages is an array:
console.log('iterating using forEach');
userPages.forEach(function(page) {

  //page is already the object we're interested in.
  //No need to access the array again.
  console.log('page is ' + JSON.stringify(page));

  //Access the object's properties as needed
  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
});

You can also use a for...of loop to iterate, but that's not supported in IE.


问:
send event to specific kafka topic partition and read it by flume hive sink
I am using Kafka 0.10 and Flume 1.8. I am trying to get information on below (but could not get it). So can any body please help me.

Is there any way to send events to particular kafka topic partition

And if so, then can we read such events (coming to specific partition) with flume using hive sink

答:
I'm not sure I understand your motive... I'm pretty sure you can create a kafka topic with a single partition if you wish to.

By doing this, you would know which partition and topic you were reading from. It is also possible to have multiple sources in flume, so if you wish for a single service to read from multiple topics but for each topic to only have a single partition, you can easily do this.

Apologies, I would have written this as a comment as it should really be a comment but I don't yet have that privilege in stackoverflow. Anyway, I hope this helps.


问:
Elm "implies" function
I'm looking for an Elm function that does the following:

```<code>if e then
  Just a
else
  Nothing
</code>```

For example, I am looking for an operator (=>) : Bool -> a -> Maybe a (binary function is fine also) that can be used like this

```<code>(x == 42) => "yes"
</code>```

and will return Just "yes" if x == 42 and Nothing otherwise.

Clearly, I can use the if-then-else to accomplish the same thing, but I curious if such a function already exists.

答:
The Elm Fancy Search tool is great for this kind of search. You can type in a function signature or name and see where it is used across all packages listed on package.elm-lang.org.

At the current time, that function signature exists in two packages under the function name when:

krisajenkins/elm-exts/27.4.0: Exts.Maybe.when: When test returns true, return Just value, otherwise return Nothing.

Gizra/elm-essentials/1.2.0: Gizra.Maybe.when: Create a Just a if condition is True, otherwise Nothing

Title: Elm "implies" function

Body:
I'm looking for an Elm function that does the following:

if e then
  Just a
else
  Nothing

For example, I am looking for an operator (=>) : Bool -> a -> Maybe a (binary function is fine also) that can be used like this

(x == 42) => "yes"

and will return Just "yes" if x == 42 and Nothing otherwise.

Clearly, I can use the if-then-else to accomplish the same thing, but I curious if such a function already exists.


问:
Deploy docker image as standalone executable
Are there any tools to install/deploy a docker image as a standalone/portable installation.
So that you don't have to install docker manually beforehand, just one installation, and it will run and deploy your docker image. And perhaps autostart it as well on boot.

Mainly interested for Win&OSX, but for linux would be nice too.

答: You can get a standalone Docker image automatically with preconfigured scaling options using the already packaged Docker engine. The details of this solution and its installation are described in the instruction.</p>


问:
Change variable inside js string
I would like to change the following line:

$("

"+displayName + ""+"
"+description+"

".appendTo(".results")

into the next string:

$("

 {1}" + ""+"
"+description+"

",{0:url, 1:displayName}.appendTo(".results").

however, instead of displayName i get 1.
please help to fix this
As you can see i've tried to write it like in c#

答:
Using ES6 string interpolation, it would look like this:

$(`

       ${displayName}

${description}

`).appendTo(".results");```

Notice the back-ticks instead of double-quotes.

Title: Change variable inside js string

Body:
Using ES6 string interpolation, it would look like this:

$(`
  <ul>
    <li>
      <a href=${url}> ${displayName}</a>
      <br>${description}</br>
    </li>
  </ul>
`).appendTo(".results");

Notice the back-ticks instead of double-quotes.


问:
using DictVectorizer to convert strings
```<code>satisfaction_level  last_evaluation number_project  average_montly_hours    time_spend_company  Work_accident   left    promotion_last_5years   dept    salary
0.38    0.53    2   157 3   0   1   0   TECHNICAL   low
0.8 0.86    5   262 6   0   1   0   HR  medium
0.11    0.88    7   272 4   0   1   0   HR  medium
0.72    0.87    5   223 5   0   1   0   FINANCE low
0.37    0.52    2   159 3   0   1   0   MARKETING   low
0.41    0.5 2   153 3   0   1   0   TECHNICAL   low
0.1 0.77    6   247 4   0   1   0   HR  low
0.92    0.85    5   259 5   0   1   0   FINANCE low
0.89    1   5   224 5   0   1   0   HR  low
</code>```

I used the above data and tried to convert C using DictVectorizer. Code is given below

```<code>import pandas as pd
from sklearn.feature_extraction import DictVectorizer

dv=DictVectorizer()
hr_data=pd.read_csv(r"C:\Users\IBM_ADMIN\Desktop\data\HR_comma_sep.csv")
dv.fit_transform(X=hr_data.dept)
</code>```

But it threw error:

'str' object has no attribute 'items'

答:
Or we may using category

```<code>df.dept.astype('category').cat.codes
Out[925]:
0    3
1    1
2    1
3    0
4    2
5    3
6    1
7    0
8    1
dtype: int8

df.dept.astype('category').cat.categories
Out[926]: Index(['FINANCE', 'HR', 'MARKETING', 'TECHNICAL'], dtype='object')
</code>```

Title: using DictVectorizer to convert strings

Body:
satisfaction_level  last_evaluation number_project  average_montly_hours    time_spend_company  Work_accident   left    promotion_last_5years   dept    salary
0.38    0.53    2   157 3   0   1   0   TECHNICAL   low
0.8 0.86    5   262 6   0   1   0   HR  medium
0.11    0.88    7   272 4   0   1   0   HR  medium
0.72    0.87    5   223 5   0   1   0   FINANCE low
0.37    0.52    2   159 3   0   1   0   MARKETING   low
0.41    0.5 2   153 3   0   1   0   TECHNICAL   low
0.1 0.77    6   247 4   0   1   0   HR  low
0.92    0.85    5   259 5   0   1   0   FINANCE low
0.89    1   5   224 5   0   1   0   HR  low

I used the above data and tried to convert C using DictVectorizer. Code is given below

import pandas as pd
from sklearn.feature_extraction import DictVectorizer

dv=DictVectorizer()
hr_data=pd.read_csv(r"C:\Users\IBM_ADMIN\Desktop\data\HR_comma_sep.csv")
dv.fit_transform(X=hr_data.dept)

But it threw error:

'str' object has no attribute 'items'

Body:
Or we may using category

df.dept.astype('category').cat.codes
Out[925]:
0    3
1    1
2    1
3    0
4    2
5    3
6    1
7    0
8    1
dtype: int8

df.dept.astype('category').cat.categories
Out[926]: Index(['FINANCE', 'HR', 'MARKETING', 'TECHNICAL'], dtype='object')


问:
SQL formatting standards
In my last job, we worked on a very database-heavy application, and I developed some formatting standards so that we would all write SQL with a common layout. We also developed coding standards, but these are more platform-specific so I'll not go into them here.

I'm interested to know what other people use for SQL formatting standards. Unlike most other coding environments, I haven't found much of a consensus online for them.

To cover the main query types:

```<code>select
    ST.ColumnName1,
    JT.ColumnName2,
    SJT.ColumnName3
from
    SourceTable ST
inner join JoinTable JT
    on JT.SourceTableID = ST.SourceTableID
inner join SecondJoinTable SJT
    on ST.SourceTableID = SJT.SourceTableID
    and JT.Column3 = SJT.Column4
where
    ST.SourceTableID = X
    and JT.ColumnName3 = Y
</code>```

There was some disagreement about line feeds after select, from and where. The intention on the select line is to allow other operators such as "top X" without altering the layout. Following on from that, simply keeping a consistent line feed after the key query elements seemed to result in a good level of readability.

Dropping the linefeed after the from and where would be an understandable revision. However, in queries such as the update below, we see that the line feed after the where gives us good column alignment. Similarly, a linefeed after group by or order by keeps our column layouts clear and easy to read.

```<code>update
    TargetTable
set
    ColumnName1 = @value,
    ColumnName2 = @value2
where
    Condition1 = @test
</code>```

Finally, an insert:

```<code>insert into TargetTable (
    ColumnName1,
    ColumnName2,
    ColumnName3
) values (
    @value1,
    @value2,
    @value3
)
</code>```

For the most part, these don't deviate that far from the way MS SQL Server Managements Studio / query analyser write out SQL, however they do differ.

I look forward to seeing whether there is any consensus in the Stack Overflow community on this topic. I'm constantly amazed how many developers can follow standard formatting for other languages and suddenly go so random when hitting SQL.

答:
A hundred answers here already, but after much toing and froing over the years, this is what I've settled on:

```<code>SELECT      ST.ColumnName1
          , JT.ColumnName2
          , SJT.ColumnName3

FROM        SourceTable       ST
JOIN        JoinTable         JT  ON  JT.SourceTableID  =  ST.SourceTableID
JOIN        SecondJoinTable  SJT  ON  ST.SourceTableID  =  SJT.SourceTableID
                                  AND JT.Column3        =  SJT.Column4

WHERE       ST.SourceTableID  =  X
AND         JT.ColumnName3    =  Y
</code>```

I know this can make for messy diffs as one extra table could cause me to re-indent many lines of code, but for my ease of reading I like it.

OwnerDisplayName: Timbo

ContentLicense: CC BY-SA 4.0

Title: SQL formatting standards

Body:
In my last job, we worked on a very database-heavy application, and I developed some formatting standards so that we would all write SQL with a common layout. We also developed coding standards, but these are more platform-specific so I'll not go into them here.

I'm interested to know what other people use for SQL formatting standards. Unlike most other coding environments, I haven't found much of a consensus online for them.

To cover the main query types:

select
    ST.ColumnName1,
    JT.ColumnName2,
    SJT.ColumnName3
from
    SourceTable ST
inner join JoinTable JT
    on JT.SourceTableID = ST.SourceTableID
inner join SecondJoinTable SJT
    on ST.SourceTableID = SJT.SourceTableID
    and JT.Column3 = SJT.Column4
where
    ST.SourceTableID = X
    and JT.ColumnName3 = Y

There was some disagreement about line feeds after select, from and where. The intention on the select line is to allow other operators such as "top X" without altering the layout. Following on from that, simply keeping a consistent line feed after the key query elements seemed to result in a good level of readability.

Dropping the linefeed after the from and where would be an understandable revision. However, in queries such as the update below, we see that the line feed after the where gives us good column alignment. Similarly, a linefeed after group by or order by keeps our column layouts clear and easy to read.

update
    TargetTable
set
    ColumnName1 = @value,
    ColumnName2 = @value2
where
    Condition1 = @test

Finally, an insert:

insert into TargetTable (
    ColumnName1,
    ColumnName2,
    ColumnName3
) values (
    @value1,
    @value2,
    @value3
)

For the most part, these don't deviate that far from the way MS SQL Server Managements Studio / query analyser write out SQL, however they do differ.

I look forward to seeing whether there is any consensus in the Stack Overflow community on this topic. I'm constantly amazed how many developers can follow standard formatting for other languages and suddenly go so random when hitting SQL.

Body:
A hundred answers here already, but after much toing and froing over the years, this is what I've settled on:

SELECT      ST.ColumnName1
          , JT.ColumnName2
          , SJT.ColumnName3

FROM        SourceTable       ST
JOIN        JoinTable         JT  ON  JT.SourceTableID  =  ST.SourceTableID
JOIN        SecondJoinTable  SJT  ON  ST.SourceTableID  =  SJT.SourceTableID
                                  AND JT.Column3        =  SJT.Column4

WHERE       ST.SourceTableID  =  X
AND         JT.ColumnName3    =  Y

I know this can make for messy diffs as one extra table could cause me to re-indent many lines of code, but for my ease of reading I like it.


问:
Storing passwords in Chef?
What is the best practice for storing password and API keys with Chef?  It's really tempting to store database passwords, AWS api keys, and other sensitive credentials as Chef Server Attributes for use in recipes -- but what about security considerations?  What's the best practice for this?</p>

答:
From the #chef IRC channel, many people store this kind of data in a data bag on the chef server.

For example, a data bag might be 'aws', with an item 'main', referring to the primary AWS account. Separate keys in the item would be for each particular value. E.g.:

```<code>{
  "id": "main",
  "aws_secret_key": "The secret access key",
  "aws_access_key": "The access key"
}
</code>```

You may also be interested in encrypted data bags. I wrote about them in more detail for managing postfix SASL authentication.

Update: I've written blog posts about Chef Vault on my blog and sysadvent.

Title: Storing passwords in Chef?

Body:
From the #chef IRC channel, many people store this kind of data in a data bag on the chef server.

For example, a data bag might be 'aws', with an item 'main', referring to the primary AWS account. Separate keys in the item would be for each particular value. E.g.:

{
  "id": "main",
  "aws_secret_key": "The secret access key",
  "aws_access_key": "The access key"
}

You may also be interested in encrypted data bags. I wrote about them in more detail for managing postfix SASL authentication.

Update: I've written blog posts about Chef Vault on my blog and sysadvent.


问:
how to separating a nested list python
I am trying to create a new list build from the items inside the list
for example list = [[math,chemistery],biology]

I would like to create the new list

```<code>new_list = [math, chemistery, biology]
</code>```

thanks for the help

答:
The following code works when items that are nested are really list or subclass of list, and there are no further nesting.

```<code>new_list = []
for item in old_list:
    if isinstance(item, list):
        new_list.extend(item)        # expand nested items
    else:
        new_list.append(item)        # simply append one
</code>```

If you have other list-like types you may switch to

isinstance(item, (list, other_list_like_class))

Tips: Better not shadow class name 'list' by assigning values to it.

If further nesting exists, simply add an recursion as in

```<code>def expand_nested_list(old_list):
    new_list = []
    for item in old_list:
        if isinstance(item, list):
            new_list.extend(expand_nested_list(item))
        else:
            new_list.append(item)
    return new_list
</code>```

This will lead to

expand_nested_list([[[1], 2], 3])      # returns [1, 2, 3]

Title: how to separating a nested list python

Body:
I am trying to create a new list build from the items inside the list
for example list = [[math,chemistery],biology]

I would like to create the new list

new_list = [math, chemistery, biology]

thanks for the help

Body:
The following code works when items that are nested are really list or subclass of list, and there are no further nesting.

new_list = []
for item in old_list:
    if isinstance(item, list):
        new_list.extend(item)        # expand nested items
    else:
        new_list.append(item)        # simply append one

If you have other list-like types you may switch to

isinstance(item, (list, other_list_like_class))

Tips: Better not shadow class name 'list' by assigning values to it.

If further nesting exists, simply add an recursion as in

def expand_nested_list(old_list):
    new_list = []
    for item in old_list:
        if isinstance(item, list):
            new_list.extend(expand_nested_list(item))
        else:
            new_list.append(item)
    return new_list

This will lead to

expand_nested_list([[[1], 2], 3])      # returns [1, 2, 3]


问:
How to validate a HTML input for a phone number
Brief

Validate a UK Mobile Phone Number field in a HTML Form to take into account the following rules:

Phone Number must begin 07

Phone Number must not exceed 11 Digits

Spaces are allowed (ignored). I've found that Auto-Fill features sometimes save numbers like 0123456789 or 01234 456 789. I'd rather not cause the inconvenience to the user to reformat their auto-fill input.

Valid Input Examples

07234567890

07234 567 895

07 23 45 78 90

Where I am

So far, I've only been able to validate my second point using:

<input id="phonenum" type="tel" pattern="^\d{11}$" required >

答:
If you want to use regular expressions you can use the following</p>

```<code>^(0\W*7\W*(?:\d\W*){9})$
</code>```

Body:
If you want to use regular expressions you can use the following

^(0\W*7\W*(?:\d\W*){9})$


问:
Find string in array and get the value after an "tag"
iam not sure: is this the fastest way to check an array for an Value beginning with XXX ? And if yes, extract the value after XXX: ?</p>

```<code>foreach ($result['tag'] as $value) {

        $pos = strpos($value, 'xxx:');

        if ($pos !== false) {
            $split = explode('xxx:', $value);
            $r = $split[1];
        } else {
            $r = '';
        }
 }
</code>```

答:
need to check substr vs explode performance !

by replace 2 lines

```<code>$split = explode('xxx:', $value);
$r = $split[1];
</code>```

with

```<code>$r = substr($value,4);
</code>```

i think the second is more elegant

Body:
iam not sure: is this the fastest way to check an array for an Value beginning with XXX ? And if yes, extract the value after XXX: ?

foreach ($result['tag'] as $value) {

        $pos = strpos($value, 'xxx:');

        if ($pos !== false) {
            $split = explode('xxx:', $value);
            $r = $split[1];
        } else {
            $r = '';
        }
 }

Body:
need to check substr vs explode performance !

by replace 2 lines

$split = explode('xxx:', $value);
$r = $split[1];

with

$r = substr($value,4);

i think the second is more elegant


问:
Access SQL Avoid Cartesian Product using Instr = 0 or Not Like
I have two tables

```<code>T1        T2
list      remark
abc       this is my list
def       i have abc remark
ghi       other than I have def comment
jkl       ghi is also there
          and this one will
          and this one too
</code>```

I am attempting to write a query that will return all remarks in T2 that are not like the list in T1.

I have tried both Instr and Join with Not Like, but am stuck on the Cartesian Product issue.

Running a query where Instr = True returns the list I expect

```<code>SELECT DISTINCT t2.remark, InStr([t2].[remark],[t1].[list]) AS [Check]
FROM t2, t1
WHERE (((InStr([t2].[remark],[t1].[list]))=True));
</code>```

ghi is also there

  I have abc remark

  other than I have def comment

But running for False is where I get all results, due to Cartesian Product:

Same with using Not Like

```<code>SELECT DISTINCT t2.remark
FROM t2 LEFT JOIN t1 ON t2.Remark NOT LIKE "*" & t1.List & "*"
</code>```

I have also tried sub queries, but no luck. Any idea how I can solve this with Access SQL?

I suppose I could write the statement with TRUE then do another query where the remarks do not equal the result of my first query, but that seems a bit inefficient.

答:
@Andre beat me by a few minutes.

This also appears to work and returns 3 records

```<code>SELECT  remark
        , list
FROM    T1 LEFT JOIN T2 ON INSTR(T2.remark,T1.list)>0
</code>```

I have abc remark / abc

other than I have def comment / def

ghi is also there / ghi

Sorry... that returns the opposite.

Use:

```<code>SELECT  remark
        , list
FROM    T2 LEFT JOIN T1 ON INSTR(T2.remark,T1.list)>0
WHERE   list IS NULL
</code>```

this is my list / NULL

and this one will / NULL

and this one too / NULL

Body:
I have two tables

T1        T2
list      remark
abc       this is my list
def       i have abc remark
ghi       other than I have def comment
jkl       ghi is also there
          and this one will
          and this one too

I am attempting to write a query that will return all remarks in T2 that are not like the list in T1.

I have tried both Instr and Join with Not Like, but am stuck on the Cartesian Product issue.

Running a query where Instr = True returns the list I expect

SELECT DISTINCT t2.remark, InStr([t2].[remark],[t1].[list]) AS [Check]
FROM t2, t1
WHERE (((InStr([t2].[remark],[t1].[list]))=True));

ghi is also there

  I have abc remark

  other than I have def comment

But running for False is where I get all results, due to Cartesian Product:

Same with using Not Like

SELECT DISTINCT t2.remark
FROM t2 LEFT JOIN t1 ON t2.Remark NOT LIKE "*" & t1.List & "*"

I have also tried sub queries, but no luck. Any idea how I can solve this with Access SQL?

I suppose I could write the statement with TRUE then do another query where the remarks do not equal the result of my first query, but that seems a bit inefficient.

Body:
@Andre beat me by a few minutes.

This also appears to work and returns 3 records

SELECT  remark
        , list
FROM    T1 LEFT JOIN T2 ON INSTR(T2.remark,T1.list)>0

I have abc remark / abc

other than I have def comment / def

ghi is also there / ghi

Sorry... that returns the opposite.

Use:

SELECT  remark
        , list
FROM    T2 LEFT JOIN T1 ON INSTR(T2.remark,T1.list)>0
WHERE   list IS NULL

this is my list / NULL

and this one will / NULL

and this one too / NULL


问:
Django Static JS Files Not Loading
I have a django project I am working on, and I am pretty new to Django and Python in general. I have a simple template made, with all of my css and js files being called in the base.html file, while i am using {% content block %} to fill in the templates.

All of the css files are being called, as well as all the js files. I can view them by typing in /http://myurl://static/jsfile.js. The CSS files are working in my html document as well. The only thing that isn't working is any of the javascript, not even embedded javascript.

Here is my settings.py

```<code># URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/djsite/djsite/static/',
'C:/djsite/djsite/templates/static/',
)
</code>```

Here is my urls.py

# Site URLS

```<code>from django.conf.urls.defaults import *
from djsite.views import *
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
 # Main Pages
url(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'main/home.html'}),
(r'^about', 'django.views.generic.simple.direct_to_template', {'template': 'main/about.html'}),
(r'^profile', 'django.views.generic.simple.direct_to_template', {'template': 'network/user-home.html'}),
(r'^privacy', 'django.views.generic.simple.direct_to_template', {'template':     'main/privacy.html'}),
(r'^contact/$', 'djsite.views.contact'),

# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
</code>```

And here is my here is my base.html (It's a little longer, I cut off as much as I could)

```<code><head>
<title>{% block title %}{% endblock %}</title>

<script type="text/javascript">

    //initialize tabs
$(document).ready(function() {
    $('#tabs').tabs();
});

//initialize slider
$(document).ready(function(){
    $('#showcase').bxSlider({
        hideControlOnEnd: true,
        infiniteLoop: false,
    });
});

//for portfolio captions
$(window).load(function capTions(){
    $("a.caption").each(function(){
        $(this)
            .css({
                "height" : $(this).children("img").height() + "px",
                "width" : $(this).children("img").width() + "px"
            })
            .children("span").css(
                "width", $(this).width() - 10 + "px")
            .find("big").after('<div class="clear"></div>');
            $("a.caption").hover(function(){
                $(this).children("img").stop().fadeTo(500, .6);
                $(this).children("span").stop().fadeTo(500, 1);
            }, function(){
                    $(this).children("span").stop().delay(0).fadeOut(200);
                $(this).children("img").stop().delay(0).fadeTo(500, 1);
            });
    // End $(this)
    });
});

$(document).ready(function () {
    $("[rel=tooltip]").tooltip({
        placement: 'bottom',
    });
    $("[rel=popover]").popover();
 });
</script>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Tyler Bailey">
<meta name="description" content="" />
<meta name="keywords" content="" />

<link rel="shortcut icon" href="/favicon.ico" />
{% load staticfiles %}
{% block addl_styles %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/network.style.css" />
{% endblock %}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}libs/jquery.bxSlider.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}libs/jquery-ui-1.8.22.custom.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}libs/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/hirestarts.script.js"></script>

</head>

<body>
<div id="wrapper">
    <header>
        {% include 'includes/nav.html' %}
    </header>
<div class="contentContainer">
{% block content %}

{% endblock %}
</code>```

It's mainly the jquery-ui that I am worried about as of right now, but I don't understand why the CSS would load, and I can view all files in the /static/ folder but the JS won't work?

答:
I had the same kind of problem with a Django project. Seems that Chrome just won't fetch the files when you refresh the page, it loads them from cache instead.

If you open debug in Chrome and look up the static file you miss - for me - it was actually there, but with an earlier version of code inside. If you right-click on it to open in new tab it shows its up-to-date content.

So, for me, a Cmd + Shift + R in Chrome did the magic.

Title: Django Static JS Files Not Loading

Body:
I have a django project I am working on, and I am pretty new to Django and Python in general. I have a simple template made, with all of my css and js files being called in the base.html file, while i am using {% content block %} to fill in the templates.

All of the css files are being called, as well as all the js files. I can view them by typing in /http://myurl://static/jsfile.js. The CSS files are working in my html document as well. The only thing that isn't working is any of the javascript, not even embedded javascript.

Here is my settings.py

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/djsite/djsite/static/',
'C:/djsite/djsite/templates/static/',
)

Here is my urls.py

# Site URLS

from django.conf.urls.defaults import *
from djsite.views import *
from django.conf import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
 # Main Pages
url(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'main/home.html'}),
(r'^about', 'django.views.generic.simple.direct_to_template', {'template': 'main/about.html'}),
(r'^profile', 'django.views.generic.simple.direct_to_template', {'template': 'network/user-home.html'}),
(r'^privacy', 'django.views.generic.simple.direct_to_template', {'template':     'main/privacy.html'}),
(r'^contact/$', 'djsite.views.contact'),

# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)

And here is my here is my base.html (It's a little longer, I cut off as much as I could)

<title>{% block title %}{% endblock %}</title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Tyler Bailey">
<meta name="description" content="" />
<meta name="keywords" content="" />

<link rel="shortcut icon" href="/favicon.ico" />
{% load staticfiles %}
{% block addl_styles %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/network.style.css" />
{% endblock %}

        {% include 'includes/nav.html' %}

{% block content %}

{% endblock %}

It's mainly the jquery-ui that I am worried about as of right now, but I don't understand why the CSS would load, and I can view all files in the /static/ folder but the JS won't work?


问:
A forward slash from https:// is being removed when sending a /oauth/authorize request to a Rails app from a chrome extension?
I am making a launchWebAuthFlow authorization code request from a Chrome extension to a Rails app hosted on Heroku.  Doorkeeper is an OAuth wrapper for Rails, and that is what is processing my request.  More specifically Doorkeeper::AuthorizationsController#new is processing the request as HTML (why HTML?).

The forward slash (/) is missing from both the URL encoded redirect_uri and the redirect_uri shown in the rails params. The url is correct on the chrome extension side of things (unless the launchWebAuthFlow built in function is doing something to it), so I think something is happening on the server.

It works in development so I don't think anything is wrong on the extension.  The app is hosted on Heroku.

Any idea of what could be going wrong here?

答:
Based from this link, Apache denies all URLs with %2F in the path part, for security reasons: scripts can't normally (ie. without rewriting) tell the difference between %2F and / due to the PATH_INFO environment variable being automatically URL-decoded.

You can turn this feature off using the AllowEncodedSlashes directive, but note that other web servers will still disallow it (with no option to turn that off), and that other characters may also be taboo (eg. %5C), and that %00 in particular will always be blocked by both Apache and IIS. So if your application relied on being able to have %2F or other characters in a path part you'd be limiting your compatibility/deployment options.

You should use rawurlencode(), not urlencode() for escaping path parts. urlencode() is misnamed, it is actually for application/x-www-form-urlencoded data such as in the query string or the body of a POST request, and not for other parts of the URL.

The difference is that + doesn't mean space in path parts. rawurlencode() will correctly produce %20 instead, which will work both in form-encoded data and other parts of the URL.

Hope this helps!


Title: How to convert a png image created from a list of tuples back to that list of tuples?

Body:
tupledlist=[(71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 103), (71, 146, 95), (71, 146, 109), (71, 146, 109), (71, 146, 91), (71, 146, 97), (71, 146, 95), (71, 146, 26), (71, 146, 91), (71, 146, 104), (71, 146, 94), (71, 146, 26), (71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 102), (71, 146, 99), (71, 146, 109), (71, 146, 110)]

from PIL import Image
OUTPUT_IMAGE_SIZE = (1280, 720)
for frame_number, color in enumerate(tupledlist):
    image = Image.new('RGB', OUTPUT_IMAGE_SIZE, color=color)
    image.save("path.png")

This will create a png image. Now I want the list of tuples from the image back. How to achieve this? I tried image.getbands() but it's not working .

import PIL
from PIL import Image
image=Image.open("c:/users/ashub/desktop/encrypted.png")
image.getbands()

Body:
If I understand correctly, you want to achieve this:

from PIL import Image

tupledlist=[(71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26),
            (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 103), (71, 146, 95), (71, 146, 109), (71, 146, 109), (71, 146, 91), (71, 146, 97),
            (71, 146, 95), (71, 146, 26), (71, 146, 91), (71, 146, 104), (71, 146, 94), (71, 146, 26), (71, 146, 110), (71, 146, 98), (71, 146, 99), (71, 146, 109), (71, 146, 26),
            (71, 146, 99), (71, 146, 109), (71, 146, 26), (71, 146, 91), (71, 146, 26), (71, 146, 110), (71, 146, 95), (71, 146, 109), (71, 146, 110), (71, 146, 26), (71, 146, 102),
            (71, 146, 99), (71, 146, 109), (71, 146, 110)]

OUTPUT_IMAGE_SIZE = (1280, 720)
image = Image.new('RGB', OUTPUT_IMAGE_SIZE)
image.putdata(tupledlist)
image.save("path.png")
print("Saved image.")

image=Image.open("path.png")
print(list(image.getdata()))

The list with the RGB values will be stored in the image, but the rest of the pixels remaining will take RGB values (0,0,0). Printing them will show you all of the 921600 (1280x720) pixels.


问:
How to change output format of material 2 date-picker
I am using angular material 2 Date-Picker component

The only string input it understands is in ISO date format

Ex. "2017-11-13T10:39:28.300Z"

But i want to patch my form control with locale date value

Ex. "11/13/2017, 4:09:46 PM"

So that it output the later format and even expects this format.

How can i do this? Is there a way to not use ISO but custom formats?

Some Thoughts:

Should i write customDateAdaptor?

Update:

https://stackblitz.com/edit/angular-material-moment-adapter-example-bqvm2f

i have tried to implement custom dateAdaptor by extending nativeDateAdaptor

答:
Not sure, if you are already doing this but I found some information that might give you some idea on your implementation.

As of today the Angular Material Date Module supports two ways of providing a date value MatNativeDateModule and MatMomentDateModule. The MatNativeDateModule accepts ISO 8601 format by default. But since you don't want to use ISO format, I would suggest using MatMomentDateModule (Moment.js implementation).

When we use the MatMomentDateModule the date object is not anymore a JavaScript Date object but instead is a Moment.js instance(take advantage of methods available to a Moment js instance like format()). There are basic to intermediate examples available on Material Date Picker docs page using the Moment.js. Also, once your date is a Moment.js instance, you could overwrite the methods(format, parse.) from MomentDateAdapter instead of native date adapter.


问:
Template type derivation
I need to implement a class, say 'MyClass' using templates.

```<code>template<class T>
class MyClass
{
public:

          T var1;
          T1 var2;
        };
</code>```

There are two member variables var1 and var2. If the class template argument, 'T', is fundamental type (eg: float, double or long double), the types of both the variables var1 and var2 should be the same as the template argument. That is T1 = T in the above example.

But if the template argument is std::complex<T>, I would like to have

```<code>T var1;
std::complex<T> var2;
</code>```

How to implement it in C++11?

答:
A possible solution could be define a simple type traits to extract the correct type

```<code>template <typename T>
struct myTypeTraits
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>>
 { using type = T; };
</code>```

and MyClass become

```<code>template <typename T>
class MyClass
 {
   using T0 = typename myTypeTraits<T>::type;

   T0 var1;
   T  var2;
 };
</code>```

If you want to be sure that T is a fundamental type (or do you mean arithmetic?), is a little more complicated.

A possible way is define a type traits to say (true or false) if a type is a std::complex

```<code>template <typename>
struct isComplex : public std::false_type
 { };

template <typename T>
struct isComplex<std::complex<T>> : public std::true_type
 { };
</code>```

Next modify myTypeTraits with a declaration (no generic definition) and two default bool values

```<code>template <typename T, bool = std::is_fundamental<T>::value,
                      bool = isComplex<T>::value>
struct myTypeTraits;
</code>```

Next two specializations, the first one for fundamentals and the second one for complexes types

```<code>template <typename T>
struct myTypeTraits<T, true, false>
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>, false, true>
 { using type = T; };
</code>```

The MyClass class remain equals but now give an error if you try to instantiate it with (by example) a std::string.

The following is a full compiling example

```<code>#include <complex>
#include <type_traits>

template <typename>
struct isComplex : public std::false_type
 { };

template <typename T>
struct isComplex<std::complex<T>> : public std::true_type
 { };

template <typename T, bool = std::is_fundamental<T>::value,
                      bool = isComplex<T>::value>
struct myTypeTraits;

template <typename T>
struct myTypeTraits<T, true, false>
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>, false, true>
 { using type = T; };

template <typename T>
class MyClass
 {
   public:  // public to check with the static_assert()
      using T0 = typename myTypeTraits<T>::type;

   private:
      T0 var1;
      T  var2;
 };

int main ()
 {
   MyClass<int>                  mi; // compile
   MyClass<std::complex<float>>  mc; // compile
   // MyClass<std::string>          ms; // compilation error

   static_assert( std::is_same<int, decltype(mi)::T0>{}, "!" );
   static_assert( std::is_same<float, decltype(mc)::T0>{}, "!" );
 }
</code>```

Title: Template type derivation

Body:
I need to implement a class, say 'MyClass' using templates.

template<class T>
class MyClass
{
public:

          T var1;
          T1 var2;
        };

There are two member variables var1 and var2. If the class template argument, 'T', is fundamental type (eg: float, double or long double), the types of both the variables var1 and var2 should be the same as the template argument. That is T1 = T in the above example.

But if the template argument is std::complex<T>, I would like to have

T var1;
std::complex<T> var2;

How to implement it in C++11?

Body:
A possible solution could be define a simple type traits to extract the correct type

template <typename T>
struct myTypeTraits
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>>
 { using type = T; };

and MyClass become

template <typename T>
class MyClass
 {
   using T0 = typename myTypeTraits<T>::type;

   T0 var1;
   T  var2;
 };

If you want to be sure that T is a fundamental type (or do you mean arithmetic?), is a little more complicated.

A possible way is define a type traits to say (true or false) if a type is a std::complex

template <typename>
struct isComplex : public std::false_type
 { };

template <typename T>
struct isComplex<std::complex<T>> : public std::true_type
 { };

Next modify myTypeTraits with a declaration (no generic definition) and two default bool values

template <typename T, bool = std::is_fundamental<T>::value,
                      bool = isComplex<T>::value>
struct myTypeTraits;

Next two specializations, the first one for fundamentals and the second one for complexes types

template <typename T>
struct myTypeTraits<T, true, false>
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>, false, true>
 { using type = T; };

The MyClass class remain equals but now give an error if you try to instantiate it with (by example) a std::string.

The following is a full compiling example

#include <complex>
#include <type_traits>

template <typename>
struct isComplex : public std::false_type
 { };

template <typename T>
struct isComplex<std::complex<T>> : public std::true_type
 { };

template <typename T, bool = std::is_fundamental<T>::value,
                      bool = isComplex<T>::value>
struct myTypeTraits;

template <typename T>
struct myTypeTraits<T, true, false>
 { using type = T; };

template <typename T>
struct myTypeTraits<std::complex<T>, false, true>
 { using type = T; };

template <typename T>
class MyClass
 {
   public:  // public to check with the static_assert()
      using T0 = typename myTypeTraits<T>::type;

   private:
      T0 var1;
      T  var2;
 };

int main ()
 {
   MyClass<int>                  mi; // compile
   MyClass<std::complex<float>>  mc; // compile
   // MyClass<std::string>          ms; // compilation error

   static_assert( std::is_same<int, decltype(mi)::T0>{}, "!" );
   static_assert( std::is_same<float, decltype(mc)::T0>{}, "!" );
 }


问:
Why is a parameter pack allowed after default arguments?
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

```<code>#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}
</code>```

This produces

```<code>t.i = 1, t.str = huh??
</code>```

答: The why of it is simple. Effectively parameter packs always have a default: Parameter packs can be empty, so that won't contradict the concept that missing defaults must be the last arguments.</p>

Body:
Maybe I'm missing something obvious, but the following compiles and runs, and I'm not sure why. I am aware of this, but in the example below the position of the parameter pack and the default argument are reversed. Doesn't it violate the rule that default arguments have to appear last? The parameter pack cannot have a default value.

#include <iostream>
#include <string>
#include <tuple>

template<typename ... Ts>
struct Test
{
    int i;
    std::string str;

    Test(int _i = 0, Ts&& ... _ts)
        :
          i(_i),
          str(std::get<0>(std::forward_as_tuple(std::forward<Ts>(_ts)...)))
    {}
};

int main()
{
    Test<std::string> t(1, "huh??");
    std::cout << "t.i = " << t.i << ", t.str = " << t.str << "\n";

    return 0;
}

This produces

t.i = 1, t.str = huh??


问:
Avoiding SQL Injection in SQL query with Like Operator using parameters?
Taking over some code from my predecessor and I found a query that uses the Like operator:

```<code>SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';
</code>```

Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?

note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.

答:
In Entity Framework 6 it could be done like this by Native SQL:

```<code>List<Person> peopleList = contex.People.SqlQuery(
    @"SELECT * FROM [Person].[Person]
       WHERE [FirstName] LIKE N'%' + @p0 + '%' ", "ab").ToList();
</code>```

Or

```<code>List<Person> peopleList = contex.People.SqlQuery(
    @"SELECT * FROM [Person].[Person]
       WHERE [FirstName] LIKE N'%' + @name + '%' ",
    new SqlParameter("@name", "ab")).ToList();
</code>```

Also, you can just use LINQ to Entities directly:

```<code>List<Person> peopleList1 = contex.People.Where(s => s.FirstName.Contains("ab")).ToList();
</code>```

OwnerDisplayName: MikeJ

Body:
Taking over some code from my predecessor and I found a query that uses the Like operator:

SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';

Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?

note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.

LastEditorDisplayName: MikeJ

Body:
In Entity Framework 6 it could be done like this by Native SQL:

List<Person> peopleList = contex.People.SqlQuery(
    @"SELECT * FROM [Person].[Person]
       WHERE [FirstName] LIKE N'%' + @p0 + '%' ", "ab").ToList();

Or

List<Person> peopleList = contex.People.SqlQuery(
    @"SELECT * FROM [Person].[Person]
       WHERE [FirstName] LIKE N'%' + @name + '%' ",
    new SqlParameter("@name", "ab")).ToList();

Also, you can just use LINQ to Entities directly:

List<Person> peopleList1 = contex.People.Where(s => s.FirstName.Contains("ab")).ToList();


问:
Safest way to update game score from client to server database? Javascript
So I have this game that is completely run on the client. No server interaction what so ever apart from downloading the initial scripts to play the game. Anyway at the end of the game I would like for the client to send me back the scores which should be updated in the server database. Now I have come to accept the fact that there is no way on earth I can hide this from a hacker and send the scores unaltered. But I would like to know till what level can I modify the whole process that it virtually becomes pretty infeasible for the hacker manipulate the data which is being sent. For sure I would not like the score to be sent as plain text from client machine and I don't want my server to perform complex decryption algorithm. What is the best way hence to achieve considerable amount of security that every tom dick and harry doesn't hack the scores... I hope someone could provide a nice little way that I could work on... :) Thanks

So my ideal result should be -> have trusted result from a calculation (of score) made by an untrusted party (the player)!

-Edit-

Someone told me something about hiding the data in a picture get request. Like, I am implementing this game on canvas (html5). So he asked me at the end of the game to fetch a game over image from my server, and they request should contain the hashed score. I did not exactly understand the complete process but if you could explain it, would be really glad! :)

coda^   so you can mask the requests nicely

shouvik how do I do it!?

coda^   you can compose the checksum you want to submit. like 12312312a12313a232 is your md5 which contains the score. bring in an asset into the canvas like

coda^   server.com/images/md5_hash_of_score/congratulations.png

coda^   which you can rewrite server side via htaccess

答:
"Now I have come to accept the fact that there is no way on earth I can hide this from a hacker and send the scores unaltered."

Oh yes, there is!

You can use RSA or any other public key encryption method (also called assymetric cryptography).

Create a set of (public and private) keys for the server.
Have your client code include your server's public key.

At the end of the game, the client code, encrypts the score (with this key) and sends both (plain score and encrypted score) to server.

Server decrypts and checks if plain score and decrypted one are same.
If yes, accept score.
If not, reject (there's a hacker or network error in the middle).

-------UPDATE-----------CORRECTION--------------

As Ambrosia, pointed out, my approach fails completely with this kind of attack.

What you actually want is to have a trusted result from a calculation (of score) made by an untrusted party (the player). No easy way to achieve this.

See this: http://coltrane.wiwi.hu-berlin.de/~fis/texts/2003-profit-untrust.pdf

Also this one: http://www.cse.psu.edu/~snarayan/publications/securecomputation.pdf

And this (which needs a subscription to the ACM digital library): http://portal.acm.org/citation.cfm?id=643477.643479


问:
Vue.js - Detect Nested Property Value Changes
I'm dynamically binding to an Array of objects in a Vue.js 2.0 app. I want to respond to changes as values in that Array change. At this time, as shown in this Fiddle, I have the following:

html

```<code><div id="app">
  <table>
    <thead>
      <tr>
        <th v-for="(col, index) in cols">
          <input :placeholder="col.title" v-model="inputValues[col.prop]" />
        </th>
      </tr>
    </thead>

    <tbody>
      <tr v-for="(item, index) in items">
        <td>{{ item.name }}</td>
        <td>{{ item.age }}</td>
        <td>{{ item.birthday }}</td>
      </tr>
    </tbody>
  </table>

  <hr />
  <textarea>{{ inputValues }}</textarea>
</div>
</code>```

javascript

```<code>new Vue({
  el: '#app',
  data: {
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    inputValues: [],

    items: [
      { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
      { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
      { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
      { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
      { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
    ]
  },

  methods: {
    buttonClick: function() {
      alert(JSON.stringify(this.inputValues));
    }
  }
})
</code>```

I can't seem to find a way to bind to changes in any of the values entered into the header. How do I detect and react to property values changes in an Array?

答:
inputValues should be an object, not an array.

```<code>data: {
  cols: [
    { title: 'Name', prop:'name' },
    { title: 'Age', prop:'age' },
    { title: 'Birthday', prop:'birthday' },
  ],
  // inputValues should be an object.
  inputValues: {name: null, age: null, birthday: null },

  items: [
    { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
    { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
    { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
    { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
    { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
  ]
}
</code>```

Body:
I'm dynamically binding to an Array of objects in a Vue.js 2.0 app. I want to respond to changes as values in that Array change. At this time, as shown in this Fiddle, I have the following:

html

          <input :placeholder="col.title" v-model="inputValues[col.prop]" />

        {{ item.name }}
        {{ item.age }}
        {{ item.birthday }}

  <textarea>{{ inputValues }}</textarea>

javascript

new Vue({
  el: '#app',
  data: {
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    inputValues: [],

    items: [
      { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
      { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
      { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
      { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
      { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
    ]
  },

  methods: {
    buttonClick: function() {
      alert(JSON.stringify(this.inputValues));
    }
  }
})

I can't seem to find a way to bind to changes in any of the values entered into the header. How do I detect and react to property values changes in an Array?

Body:
inputValues should be an object, not an array.

data: {
  cols: [
    { title: 'Name', prop:'name' },
    { title: 'Age', prop:'age' },
    { title: 'Birthday', prop:'birthday' },
  ],
  // inputValues should be an object.
  inputValues: {name: null, age: null, birthday: null },

  items: [
    { id:1, name:'Andreas Winchell', age:47, birthday:'08-04-1970' },
    { id:2, name:'Victoria Hodges', age:80, birthday:'01-24-1937' },
    { id:2, name:'James Morris', age:59, birthday:'06-14-1958' },
    { id:2, name:'Larry Walker', age:68, birthday:'08-07-1949' },
    { id:2, name:'Lee Maynard', age:46, birthday:'04-17-1971' }
  ]
}


问:
Unsuccessful Updating table with PHP using Update table Set
I have a table buildtracker connected to a form. I am attempting to edit the data in a particular row and therefore Update the row.

The table consists of these columns:  ID key, EnteredBy, INI

```<code>$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");

$rowID = $conn->real_escape_string($_POST['ID']);
$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
$ini   = $conn->real_escape_string($_POST['ini']);

$query   = "UPDATE buildtracker SET
          EnteredBy = '$enteredBy', INI = '$ini'
          WHERE ID = '$rowID' ";

$success = $conn->query($query); //insertion above ^ is the column names

if (!$success) {
    die("Couldn't enter data: ".$conn->error);
    }
return $query;
</code>```

I'm receiving no new data or updates on the table. What can I do differently to improve upon this?

Thanks!

答:
As all errors that I create - this was a result of the declaration of my $rowID not pointing the correct html element.

original

```<code>$rowID   = $conn->real_escape_string($_POST['ID']); // ID is the COLUMN NAME
</code>```

Working

```<code>$rowID   = $conn->real_escape_string($_POST['rowID']); //rowID is the DOM element name
</code>```

Thank you for your comments and answers.

Going to look into implementing Hossam's safer version of preventing injections. I appreciate you all :)

Body:
I have a table buildtracker connected to a form. I am attempting to edit the data in a particular row and therefore Update the row.

The table consists of these columns:  ID key, EnteredBy, INI

$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");

$rowID = $conn->real_escape_string($_POST['ID']);
$enteredBy    = $conn->real_escape_string($_POST['enteredBy']);
$ini   = $conn->real_escape_string($_POST['ini']);

$query   = "UPDATE buildtracker SET
          EnteredBy = '$enteredBy', INI = '$ini'
          WHERE ID = '$rowID' ";

$success = $conn->query($query); //insertion above ^ is the column names

if (!$success) {
    die("Couldn't enter data: ".$conn->error);
    }
return $query;

I'm receiving no new data or updates on the table. What can I do differently to improve upon this?

Thanks!

Body:
As all errors that I create - this was a result of the declaration of my $rowID not pointing the correct html element.

original

$rowID   = $conn->real_escape_string($_POST['ID']); // ID is the COLUMN NAME

Working

$rowID   = $conn->real_escape_string($_POST['rowID']); //rowID is the DOM element name

Thank you for your comments and answers.

Going to look into implementing Hossam's safer version of preventing injections. I appreciate you all :)


问:
Using textvariable for a Tkinter (or ttk) LabelFrame
I want to update the label of a Tkinter LabelFrame widget.

For a Label widget, this can be done using the textvariable attribute, to which one can assign a StringVar.

I want to do the same thing, but for a LabelFrame

```<code>self.labelText = StringVar()
self.selectionFrame = ttk.LabelFrame(self, textvariable=self.labelText)

(...)

if A:
     self.labelText.set("LabelA")
elif B:
     self.labelText.set("LabelB")
</code>```

How can I achieve this?

答:
I just found some kind of a solution - using the labelwidget attribute to supply a separate Label object which uses the underlying StringVar:

```<code>self.labelText = StringVar()
self.labelWidget = Label(self, textvariable=self.labelText)
self.selectionFrame = ttk.LabelFrame(self, labelwidget=self.labelWidget)
</code>```

This way, I can update the labelText to change the label of the LabelFrame

```<code>self.labelText.set("New Label")
</code>```

Body:
I want to update the label of a Tkinter LabelFrame widget.

For a Label widget, this can be done using the textvariable attribute, to which one can assign a StringVar.

I want to do the same thing, but for a LabelFrame

self.labelText = StringVar()
self.selectionFrame = ttk.LabelFrame(self, textvariable=self.labelText)

(...)

if A:
     self.labelText.set("LabelA")
elif B:
     self.labelText.set("LabelB")

How can I achieve this?

Body:
I just found some kind of a solution - using the labelwidget attribute to supply a separate Label object which uses the underlying StringVar:

self.labelText = StringVar()
self.labelWidget = Label(self, textvariable=self.labelText)
self.selectionFrame = ttk.LabelFrame(self, labelwidget=self.labelWidget)

This way, I can update the labelText to change the label of the LabelFrame

self.labelText.set("New Label")


问:
Can't Delete HDFS Directory Via Web Interface Because I'm Dr. Who
I'm trying to delete the directory deepnlptest/models on a local HDFS system using the web interface at http://localhost:50070/explorer.html.
My username is wmcneill and permissions on the HDFS directory I am trying to delete and the enclosing one are drwxr-xr-x owned by wmcneill.

```<code>$ hdfs dfs -ls deepnlptest
17/11/16 09:36:11 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 5 items
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 17:09 deepnlptest/canonical-folders
drwxr-xr-x   - wmcneill supergroup          0 2017-11-08 14:35 deepnlptest/data
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 16:51 deepnlptest/embeddings
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 16:53 deepnlptest/models
drwxr-xr-x   - wmcneill supergroup          0 2017-11-09 10:28 deepnlptest/pretrained_embeddings
</code>```

I get the following error when I try to use the web interface to delete the directory.

Except for deleting, the web interface works fine for browsing HDFS. I am able to do everything on the HDFS system via the command line command hdfs dfs including deleting the directory.

```<code>$ hdfs dfs -rm -r deepnlptest/models
17/11/16 09:37:17 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Deleted deepnlptest/models
</code>```

I assume that "dr.who" is a default user and I need to add my username to some Hadoop configuration file, but I can't figure out which one.

I'm running Hadoop 2.8.2 on a Mac installed beneath /usr/local/Cellar/hadoop/2.8.2.

答:
When you access the Web UI, you are accessing the cluster as Dr.Who, not your user.

Dr. Who doesn't have permission to delete in your dir. It is a user to be used for browsing.

```<code>+------------------------------+-----------+----------------------------------------------------+
|                              |           | The user name to filter as,on static web filters   |
| hadoop.http.staticuser.user  |  dr.who   | while rendering content. An example use is the HDFS|
|                              |           | web UI (user to be used for browsing files).       |
+------------------------------+-----------+----------------------------------------------------+
</code>```

Refer: Who is Dr.Who?

Additional reference: core-default

Body:
I'm trying to delete the directory deepnlptest/models on a local HDFS system using the web interface at http://localhost:50070/explorer.html.
My username is wmcneill and permissions on the HDFS directory I am trying to delete and the enclosing one are drwxr-xr-x owned by wmcneill.

$ hdfs dfs -ls deepnlptest
17/11/16 09:36:11 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 5 items
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 17:09 deepnlptest/canonical-folders
drwxr-xr-x   - wmcneill supergroup          0 2017-11-08 14:35 deepnlptest/data
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 16:51 deepnlptest/embeddings
drwxr-xr-x   - wmcneill supergroup          0 2017-11-15 16:53 deepnlptest/models
drwxr-xr-x   - wmcneill supergroup          0 2017-11-09 10:28 deepnlptest/pretrained_embeddings

I get the following error when I try to use the web interface to delete the directory.

Except for deleting, the web interface works fine for browsing HDFS. I am able to do everything on the HDFS system via the command line command hdfs dfs including deleting the directory.

$ hdfs dfs -rm -r deepnlptest/models
17/11/16 09:37:17 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Deleted deepnlptest/models

I assume that "dr.who" is a default user and I need to add my username to some Hadoop configuration file, but I can't figure out which one.

I'm running Hadoop 2.8.2 on a Mac installed beneath /usr/local/Cellar/hadoop/2.8.2.

Body:
When you access the Web UI, you are accessing the cluster as Dr.Who, not your user.

Dr. Who doesn't have permission to delete in your dir. It is a user to be used for browsing.

+------------------------------+-----------+----------------------------------------------------+
|                              |           | The user name to filter as,on static web filters   |
| hadoop.http.staticuser.user  |  dr.who   | while rendering content. An example use is the HDFS|
|                              |           | web UI (user to be used for browsing files).       |
+------------------------------+-----------+----------------------------------------------------+

Refer: Who is Dr.Who?

Additional reference: core-default


问:
Get user's timezone for Gmail addon
How to get the user's timezone in the appscript for Gmail add-on. I don't want the script's timezone but user's.
I just need to display some history. So if I can convert UTC to user's timezone in client-side, it is also fine.

Session.getScriptTimeZone() gives the script's timezone, not the user's.

Is there a way to get the timezone of the user or show the time according to the user's computer timezone?

答:
Session.getScriptTimeZone(); gets the user's timezone that is set on their Gmail account. If the user wants to change their timezone, they have to change it through Google Calendar (how to change timezone).

If you want to get the timezone that reflects the user's computer's settings, here is a small script:

function getTimeZone(){
    var now = new Date().toString();
    var timeZone = now.replace(/.*[(](.*)[)].*/,'$1');//extracts timezone string
    return timeZone;
}```

Additionally, you can add Moment.js to your Apps Script project
and utilize the functions they already built: https://momentjs.com/

Title: Get user's timezone for Gmail addon

Body:
Session.getScriptTimeZone(); gets the user's timezone that is set on their Gmail account. If the user wants to change their timezone, they have to change it through Google Calendar (how to change timezone).

If you want to get the timezone that reflects the user's computer's settings, here is a small script:

function getTimeZone(){
    var now = new Date().toString();
    var timeZone = now.replace(/.*[(](.*)[)].*/,'$1');//extracts timezone string
    return timeZone;
}

Additionally, you can add Moment.js to your Apps Script project
and utilize the functions they already built: https://momentjs.com/