问:
What is the best way to restore nuget packages?
I have a solution that uses custom nuget package sources. For now I specify them in Nuget.config file that is located near my solution file(so that it is checked out from source control):

```<code>|- MySoulution.sln
|- MyProjFolder
|- .nuget
   |- Nuget.exe
   |- Nuget.config
   |- Nuget.targets
</code>```

This works well when building solution from VisualStudio. It manages to read this nuget.config file and successfully restore all packages.

Now I'm configuring my solution to be built from TeamCity. So I've added project configuration and a build step to build it. But TeamCity doesn't restore nuget packages by default. So I've added a separate Nuget installer build step that runs nuget(of specific version) restore for my solution. But the problem is that it doesn't seem to see my custom nuget package sources from Nuget.config file in .nuget folder next to solution file.

I see two possible ways to overcome this:

Configure my custom package sources inside Nuget installer build step.

Configure my custom package sources in Nuget.config in AppData folder on build machine.

I don't like neither of this approaches because they don't provide me single poing of configuration for building both from TeamCity and VisualStudio.

To sum up, the question is: how do I configure my custom package sources so that they would be visible both from TeamCity and VisualStudio without requiring me to configure them several times in different places?

答:
how do I configure my custom package sources so that they would be visible both from TeamCity and VisualStudio without requiring me to configure them several times in different places?

As you know, if you do not want to configure custom nuget sources several times in different places, you can set the custom nuget sources in the NuGet.config and add it to source control. So the key to your problem is why NuGet doesn't respect the your custom nuget package sources from Nuget.config file in .nuget folder next to solution file.

Just as my comment, if you're using NuGet 2.7 or later and have a solution that is still configured for MSBuild-integrated restore, you may have an older version of nuget.exe in the solution's .nuget folder. This will cause builds to fail with an error stating that you have not given consent to restore packages.
To avoid this issue, it's recommended to migrate any project using MSBuild-integrated restore to use the automatic restore capabilities of NuGet 2.7 and above, you can follow the process as below:

Close Visual Studio to avoid file potential file locks and conflicts.

If using TFS:
Remove nuget.exe and NuGet.targets from the solution's .nuget folder and remove those files from the solution workspace.
Retain Nuget.Config with the disableSourceControlIntegration setting as explained in Omitting packages with Team Foundation Version Control.

If not using TFS:
Remove the .nuget folder from the solution and the solution workspace.

Edit each project file in the solution, remove the  element, and remove any references to the NuGet.targets file. Those settings generally appear as follows:

After that put NuGet.config next to the solution file with custom NuGet source:

```<code><?xml version="1.0" encoding="utf-8"?>
   <configuration>
     <solution>
       <add key="disableSourceControlIntegration" value="true" />
     </solution>

    <packageSources>
      <add key="CustomSource" value="http://CustomSource/nuget" />
    </packageSources>

    <packageRestore>
      <add key="enabled" value="True" />
    </packageRestore>

  </configuration>
</code>```

Now, in the NuGet Installer step, there is now a "Package Sources" field that you can fill in to have team city use a custom feed:

You can refer to this document NuGet Package Restore with TeamCity for more detail.

Besides, we can also specify custom feed in the NuGet.targets file in the .nuget folder(I did not verify it yet):

```<code><ItemGroup Condition=" '$(PackageSources)' == '' ">
    <PackageSource Include="https://nuget.org/api/v2/" />
    <PackageSource Include="\\MyShare" />
    <PackageSource Include="http://MyServer/" />
</ItemGroup>
</code>```

Body:
I have a solution that uses custom nuget package sources. For now I specify them in Nuget.config file that is located near my solution file(so that it is checked out from source control):

|- MySoulution.sln
|- MyProjFolder
|- .nuget
   |- Nuget.exe
   |- Nuget.config
   |- Nuget.targets

This works well when building solution from VisualStudio. It manages to read this nuget.config file and successfully restore all packages.

Now I'm configuring my solution to be built from TeamCity. So I've added project configuration and a build step to build it. But TeamCity doesn't restore nuget packages by default. So I've added a separate Nuget installer build step that runs nuget(of specific version) restore for my solution. But the problem is that it doesn't seem to see my custom nuget package sources from Nuget.config file in .nuget folder next to solution file.

I see two possible ways to overcome this:

Configure my custom package sources inside Nuget installer build step.

Configure my custom package sources in Nuget.config in AppData folder on build machine.

I don't like neither of this approaches because they don't provide me single poing of configuration for building both from TeamCity and VisualStudio.

To sum up, the question is: how do I configure my custom package sources so that they would be visible both from TeamCity and VisualStudio without requiring me to configure them several times in different places?

Body:
how do I configure my custom package sources so that they would be visible both from TeamCity and VisualStudio without requiring me to configure them several times in different places?

As you know, if you do not want to configure custom nuget sources several times in different places, you can set the custom nuget sources in the NuGet.config and add it to source control. So the key to your problem is why NuGet doesn't respect the your custom nuget package sources from Nuget.config file in .nuget folder next to solution file.

Just as my comment, if you're using NuGet 2.7 or later and have a solution that is still configured for MSBuild-integrated restore, you may have an older version of nuget.exe in the solution's .nuget folder. This will cause builds to fail with an error stating that you have not given consent to restore packages.
To avoid this issue, it's recommended to migrate any project using MSBuild-integrated restore to use the automatic restore capabilities of NuGet 2.7 and above, you can follow the process as below:

Close Visual Studio to avoid file potential file locks and conflicts.

If using TFS:
Remove nuget.exe and NuGet.targets from the solution's .nuget folder and remove those files from the solution workspace.
Retain Nuget.Config with the disableSourceControlIntegration setting as explained in Omitting packages with Team Foundation Version Control.

If not using TFS:
Remove the .nuget folder from the solution and the solution workspace.

Edit each project file in the solution, remove the  element, and remove any references to the NuGet.targets file. Those settings generally appear as follows:

After that put NuGet.config next to the solution file with custom NuGet source:

<?xml version="1.0" encoding="utf-8"?>
   <configuration>
     <solution>
       <add key="disableSourceControlIntegration" value="true" />
     </solution>

    <packageSources>
      <add key="CustomSource" value="http://CustomSource/nuget" />
    </packageSources>

    <packageRestore>
      <add key="enabled" value="True" />
    </packageRestore>

  </configuration>

Now, in the NuGet Installer step, there is now a "Package Sources" field that you can fill in to have team city use a custom feed:

You can refer to this document NuGet Package Restore with TeamCity for more detail.

Besides, we can also specify custom feed in the NuGet.targets file in the .nuget folder(I did not verify it yet):

<ItemGroup Condition=" '$(PackageSources)' == '' ">
    <PackageSource Include="https://nuget.org/api/v2/" />
    <PackageSource Include="\\MyShare" />
    <PackageSource Include="http://MyServer/" />
</ItemGroup>


来源: stackexchange

问:
Xamarin.Forms Content Page title color change
This is the result I want to see on all my devices.

But it looks like this on the device with android 5.1 installed.

My third title dont see. I had to use the following definitions in my 3rd page (Yukle Page) .cs file. I am getting such a result, probably because I changed the color setting.

How can I make the title color of my 3rd page (Yukle Page) in .cs "white" in Xamarin.Forms? Thank you!

答:
You have apply theme in Toolbar.axml in your Android Project.

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeToolbar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</code>```

Define ThemeToolbar style in styles.xml

```<code> <style name="ThemeToolbar" parent="Theme.AppCompat.Light">

    <!-- navigation icon color -->
    <item name="colorControlNormal">@color/accent</item>

    <!-- color of the menu overflow icon -->
    <item name="android:textColorSecondary">"define your color code here"</item>
    <item name="android:textColorPrimary">"define color hex code here."</item>
    <item name="colorPrimary">@color/lightGray</item>
  </style>
</code>```

For More info use following link:

https://blog.xamarin.com/material-design-for-your-xamarin-forms-android-apps/

ContentLicense: CC BY-SA 3.0

Body:
You have apply theme in Toolbar.axml in your Android Project.

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeToolbar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Define ThemeToolbar style in styles.xml

 <style name="ThemeToolbar" parent="Theme.AppCompat.Light">

    <!-- navigation icon color -->
    <item name="colorControlNormal">@color/accent</item>

    <!-- color of the menu overflow icon -->
    <item name="android:textColorSecondary">"define your color code here"</item>
    <item name="android:textColorPrimary">"define color hex code here."</item>
    <item name="colorPrimary">@color/lightGray</item>
  </style>

For More info use following link:

https://blog.xamarin.com/material-design-for-your-xamarin-forms-android-apps/


问:
RegEx to match Json format
I have regEx \{\s*"lat"\s*:\s*(.+?)\s*,\s*"lng":\s*(.+?)\s*} to match following JSON value {"lat": 0.788,"lng":0.878798}, but i want in such a way that it will only match if the "lat" and "lng" values are either integer or decimal

答:
To do that, you want to match [0-9]*\.?[0-9]+ instead of .*

Although you probably want to parse that json to an object, since it is less error-prone (e.g., what if the order of long and lat is reversed?)

What language / framework are you using?

Title: RegEx to match Json format


问:
Ember-simple-auth cant get currentUser after reload
I have a simple Ember app (repo) with authentication using ember-simple-auth (i followed this article https://medium.com/@benhansen/token-based-authentication-with-jwt-ember-and-rails-af54b03fe237). After logging in I have access to currentUser in my routes, controllers and templates. However, if I navigate to any route besides my ApplicationRoute and reload the browser, I can no longer access currentUser in that route, but it's available in the template. If I navigate back to application route and navigate to different one again, then I can access the currentUser. How can I fix this, i.e. I want to be able to access currentUser in any route even after reload?

ApplicationRoute:

```<code>import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  sessionAccount: Ember.inject.service(),
  beforeModel() {
    this.get('sessionAccount').loadCurrentUser();
  }
});
</code>```

SessionAccount service:

```<code>import Ember from 'ember';

const { inject: { service }, RSVP } = Ember;

export default Ember.Service.extend({
  session: service('session'),
  store: service(),

  loadCurrentUser() {
    if (this.get('session.isAuthenticated')) {
      this.get('store')
      .queryRecord('user', { me: true })
      .then((user) => {
        this.set('currentUser', user);
      });
    } else {
      return RSVP.resolve();
    }
  }
});
</code>```

Bookings route - the 'other' route:

```<code>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  sessionAccount: Ember.inject.service(),

  model() {
    const currentUser = this.get('sessionAccount.currentUser');

    return this.get('store').query('booking', {
      filter: {
        'user_id': currentUser.id
      },
      include: 'rental,rental.rental-ratings'
    });
  }
});
</code>```

答:
Ended just following the tutorial form Ember simple auth github repo. Who would have thought this would work:) Had to change code in app/routes/application.js, also changed the name of my service from 'sessionAccount' to 'currentUser':</p>

```<code>// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

const { service } = Ember.inject;

export default Ember.Route.extend(ApplicationRouteMixin, {
  currentUser: service(),

  beforeModel() {
    return this._loadCurrentUser();
  },

  sessionAuthenticated() {
    this._super(...arguments);
    this._loadCurrentUser();
  },

  _loadCurrentUser() {
    return this.get('currentUser').load().catch(() => this.get('session').invalidate());
  }
});
</code>```

Body:
I have a simple Ember app (repo) with authentication using ember-simple-auth (i followed this article https://medium.com/@benhansen/token-based-authentication-with-jwt-ember-and-rails-af54b03fe237). After logging in I have access to currentUser in my routes, controllers and templates. However, if I navigate to any route besides my ApplicationRoute and reload the browser, I can no longer access currentUser in that route, but it's available in the template. If I navigate back to application route and navigate to different one again, then I can access the currentUser. How can I fix this, i.e. I want to be able to access currentUser in any route even after reload?

ApplicationRoute:

import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Ember.Route.extend(ApplicationRouteMixin, {
  sessionAccount: Ember.inject.service(),
  beforeModel() {
    this.get('sessionAccount').loadCurrentUser();
  }
});

SessionAccount service:

import Ember from 'ember';

const { inject: { service }, RSVP } = Ember;

export default Ember.Service.extend({
  session: service('session'),
  store: service(),

  loadCurrentUser() {
    if (this.get('session.isAuthenticated')) {
      this.get('store')
      .queryRecord('user', { me: true })
      .then((user) => {
        this.set('currentUser', user);
      });
    } else {
      return RSVP.resolve();
    }
  }
});

Bookings route - the 'other' route:

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  sessionAccount: Ember.inject.service(),

  model() {
    const currentUser = this.get('sessionAccount.currentUser');

    return this.get('store').query('booking', {
      filter: {
        'user_id': currentUser.id
      },
      include: 'rental,rental.rental-ratings'
    });
  }
});

Body:
Ended just following the tutorial form Ember simple auth github repo. Who would have thought this would work:) Had to change code in app/routes/application.js, also changed the name of my service from 'sessionAccount' to 'currentUser':

// app/routes/application.js
import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

const { service } = Ember.inject;

export default Ember.Route.extend(ApplicationRouteMixin, {
  currentUser: service(),

  beforeModel() {
    return this._loadCurrentUser();
  },

  sessionAuthenticated() {
    this._super(...arguments);
    this._loadCurrentUser();
  },

  _loadCurrentUser() {
    return this.get('currentUser').load().catch(() => this.get('session').invalidate());
  }
});


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答:
ASP.NET MVC is a pretty tough framework to start out on. It assumes you are already versed in ASP.NET, and ideally you even have a little bit of Ruby on Rails or similar experience too (ASP.NET MVC was really influenced by rails). On top of all of that good knowledge of C# is also very helpful.

I guess it depends on what your needs are. Are you going to create a mission critical webapp that your business depends on? In that case, yeah really learn ASP.NET and C# well. If this is just for a hobby and/or learning, then I say just go for it and learn C# as you go.

ContentLicense: CC BY-SA 2.5


问:
jQuery autocomplete is showing empty results
I have this PHP script to get all patient name from my database:

```<code><?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];

$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>
</code>```

And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.

Here is my jQuery script:

```<code>  $(document).ready(function()
  {
    $( "#searchTxt" ).autocomplete({
      source: "../php/autoComplete.php"
    });
  })
</code>```

I can see that if a type a name at the network tab I can see a returned array:

But at the text box I see that the autocomplete are empty like in the following image:

And it is showing 2 white boxes instead of one that of the returned array

答: This is nice plugin for that kind of results: https://twitter.github.io/typeahead.js/</p>

Body:
I have this PHP script to get all patient name from my database:

<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];

$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>

And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.

Here is my jQuery script:

  $(document).ready(function()
  {
    $( "#searchTxt" ).autocomplete({
      source: "../php/autoComplete.php"
    });
  })

I can see that if a type a name at the network tab I can see a returned array:

But at the text box I see that the autocomplete are empty like in the following image:

And it is showing 2 white boxes instead of one that of the returned array


问:
How to build this query in postgresql

Supposing I have this data. How to query this in such a way that will result to this in an efficient way. It will sum the qty of all OUT less the IN per item.

答:
Try this query:

```<code>select
    "Desc",
    sum(case when Type = 'out' then Qty else 0 end) -
    sum(case when Type = 'in'  then Qty else 0 end)
from yourTable
group by "Desc"
    Desc
</code>```

Note that DESC is a reserved keyword and you should not be naming your databases, tables, or columns using it.  I think you would have to escape it in double quotes to get the query to run.

Title: How to build this query in postgresql

Body:
Try this query:

select
    "Desc",
    sum(case when Type = 'out' then Qty else 0 end) -
    sum(case when Type = 'in'  then Qty else 0 end)
from yourTable
group by "Desc"
    Desc

Note that DESC is a reserved keyword and you should not be naming your databases, tables, or columns using it.  I think you would have to escape it in double quotes to get the query to run.


问:
Create stored procedure in DocumentDB Emulator
Update:  I downloaded the emulator again and did a repair and the options show up again.  Resolved.

can anyone please tell me if it is possible to create stored procedures in DocumentDB emulator?  I know I can do it in the real DocumentDB on Azure.  However, I can't seem to be able to find the script panel anywhere in the emulator.  I google around and I can't find any answer either. According to the website, I should be able to create stored procs using the emulator.  Very strange.

答:
We can create stored procedure using the Azure Cosmos DB Emulator, the following code works fine on my side.

Register stored procedure

```<code>DocumentClient client = new DocumentClient(
    new Uri("https://localhost:8081"),
    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
var TestSproc = new StoredProcedure
{
    Id = "SayHello",
    Body = @"function SayHello() {
    var response = getContext().getResponse();
    response.setBody('hello');}"
};
StoredProcedure createdStoredProcedure = await client.CreateStoredProcedureAsync(UriFactory.CreateDocumentCollectionUri("testdb", "testcoll"), TestSproc);
</code>```

Execute stored procedure

```<code>StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
    UriFactory.CreateStoredProcedureUri("testdb", "testcoll", "SayHello"));

result.Response.ToString();
</code>```

Result

Body:
We can create stored procedure using the Azure Cosmos DB Emulator, the following code works fine on my side.

Register stored procedure

DocumentClient client = new DocumentClient(
    new Uri("https://localhost:8081"),
    "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==");
var TestSproc = new StoredProcedure
{
    Id = "SayHello",
    Body = @"function SayHello() {
    var response = getContext().getResponse();
    response.setBody('hello');}"
};
StoredProcedure createdStoredProcedure = await client.CreateStoredProcedureAsync(UriFactory.CreateDocumentCollectionUri("testdb", "testcoll"), TestSproc);

Execute stored procedure

StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
    UriFactory.CreateStoredProcedureUri("testdb", "testcoll", "SayHello"));

result.Response.ToString();

Result


问:
Accessing SQL Server in parallel
I'm trying to use the Task-Parallel-Library to offload expensive ADO.NET database access from the UI thread (formerly the program I'm re-writing would simply freeze, occasionally updating a VB6 text box with its progress, until the data in the database was fully loaded).  I have an complex dependency structure (26 individual tasks), and I'm trying to figure out how much of it is worth parallelizing.

I'd like to know whether or not IO access like this can be parallelized at all with performance bonuses.  If not I'll just sequentially load the data and update the UI whenever enough information is loaded to perform that task, but It'd be nice to get an extra boost by loading maybe two things at a  time instead of just one (even if I don't get double speedup).

答:
It's possible that parallelizing this will increase performance, but not guaranteed. It all depends on where your bottleneck is.

For example, if a request is expensive because it loads lots of data, then it probably consumes much of your clients network bandwith. Parallelizing in this case wouldn't help much, if at all.

If, on the other hand, the bottleneck is the SQL processing and your SQL request leaves the SQL Server with spare capacity in its own bottleneck, then you can profit from SQL Servers (very good) parallelizing capabilities.

It is also possible that parallelizing slows you down. If for example the SQl Server has not much RAM and access only to a single disk, forcing it to do multiple queries in parallel may lead to more seek activity on the harddisk, which can dramatically slow down the overall read rate.

So, as it often is, the answer isn't a simple yes or no, but "it depends".

Title: Accessing SQL Server in parallel


问:
MNIST: x is just a placeholder , How is data from MNIST going into the placeholder x?
This is the code from sentdex tutorials:
How is the data from MNIST set being transfered into the placeholder x.

Please help me , considering i am just a beginner into tensorflow, if it has something to do with the placeholder then please explain.

Thanks in advance!

```<code>"""
os.environ removes the warning
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
"""
tensorflow starts below
"""

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)

# 10 classes , 0-9

"""
nodes for the hidden layers
"""
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10 # 0-9

batch_size = 100

"""
placeholders
"""

x = tf.placeholder('float',[None,784]) # 784 is 28*28 ,i.e., the size of mnist images
y = tf.placeholder('float')

# y is the label of data

def neural_network_model(data):

    # biases are added so that the some neurons get fired even when input_data is 0

    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784,n_nodes_hl1])),'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),
    'biases':tf.Variable(tf.random_normal([n_classes]))}

    # (input_data * weights) + biases

    l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']) , hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1) # activation func

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']) , hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2) # activation func

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']) , hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3) # activation func

    output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']

    return output

# we now have modeled a neural network

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
    # softmax_cross_entropy_with_logits ==> for changing weights
    # we wanna minimize the difference

    # AdamOptimizer optionally has a learning_reate : 0.0001
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 5 # cycles of feed forward + back

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer()) # replace it with global_variable_initializer

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x,epoch_y = mnist.train.next_batch(batch_size)
                _,c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
                epoch_loss += c
            print('Epoch',epoch,'completed out of',hm_epochs,' loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float')) # cast changes the data type of a tensor
        print('Accuracy: ',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))

if __name__ == "__main__":
    train_neural_network(x)
</code>```

答:
To see where the MNIST data is transferred into the tf.placeholder() tensors x and y, focus on these lines:

```<code>for _ in range(int(mnist.train.num_examples/batch_size)):
    epoch_x, epoch_y = mnist.train.next_batch(batch_size)
    _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
</code>```

The arrays epoch_x and epoch_y are a pair of (somewhat confusingly named) NumPy arrays that contain a batch of batch_size images and labels respectively from the MNIST training data set. They will contain a different batch in each iteration of the for loop.

The feed_dict argument to sess.run() tells TensorFlow to substitute  the value of epoch_x for placeholder x, and the value of epoch_y for placeholder y. Thus TensorFlow will use those values to run a step of the optimization algorithm (Adam, in this case).

Note that the MNIST data is also used on this line:

```<code>print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
</code>```

...except here the program is using the entire test data set to evaluate the accuracy of the model.

Body:
This is the code from sentdex tutorials:
How is the data from MNIST set being transfered into the placeholder x.

Please help me , considering i am just a beginner into tensorflow, if it has something to do with the placeholder then please explain.

Thanks in advance!

"""
os.environ removes the warning
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
"""
tensorflow starts below
"""

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/",one_hot=True)

# 10 classes , 0-9

"""
nodes for the hidden layers
"""
n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10 # 0-9

batch_size = 100

"""
placeholders
"""

x = tf.placeholder('float',[None,784]) # 784 is 28*28 ,i.e., the size of mnist images
y = tf.placeholder('float')

# y is the label of data

def neural_network_model(data):

    # biases are added so that the some neurons get fired even when input_data is 0

    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784,n_nodes_hl1])),'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),
    'biases':tf.Variable(tf.random_normal([n_classes]))}

    # (input_data * weights) + biases

    l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']) , hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1) # activation func

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']) , hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2) # activation func

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']) , hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3) # activation func

    output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']

    return output

# we now have modeled a neural network

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))
    # softmax_cross_entropy_with_logits ==> for changing weights
    # we wanna minimize the difference

    # AdamOptimizer optionally has a learning_reate : 0.0001
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 5 # cycles of feed forward + back

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer()) # replace it with global_variable_initializer

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x,epoch_y = mnist.train.next_batch(batch_size)
                _,c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})
                epoch_loss += c
            print('Epoch',epoch,'completed out of',hm_epochs,' loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct,'float')) # cast changes the data type of a tensor
        print('Accuracy: ',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))

if __name__ == "__main__":
    train_neural_network(x)

Body:
To see where the MNIST data is transferred into the tf.placeholder() tensors x and y, focus on these lines:

for _ in range(int(mnist.train.num_examples/batch_size)):
    epoch_x, epoch_y = mnist.train.next_batch(batch_size)
    _, c = sess.run([optimizer, cost], feed_dict = {x: epoch_x, y: epoch_y})

The arrays epoch_x and epoch_y are a pair of (somewhat confusingly named) NumPy arrays that contain a batch of batch_size images and labels respectively from the MNIST training data set. They will contain a different batch in each iteration of the for loop.

The feed_dict argument to sess.run() tells TensorFlow to substitute  the value of epoch_x for placeholder x, and the value of epoch_y for placeholder y. Thus TensorFlow will use those values to run a step of the optimization algorithm (Adam, in this case).

Note that the MNIST data is also used on this line:

print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

...except here the program is using the entire test data set to evaluate the accuracy of the model.


答:
I think its because the data you have passed, it seems there are multiple columns, you need to specify label and value or it should be simple array (as per your code it should be this kind of data)like

```<code>var availableTags = [
  "ActionScript",
  "COBOL",
  "ColdFusion",

];
</code>```

You can check more about custom field passing

Title: jQuery autocomplete is showing empty results

Body:
I think its because the data you have passed, it seems there are multiple columns, you need to specify label and value or it should be simple array (as per your code it should be this kind of data)like

var availableTags = [
  "ActionScript",
  "COBOL",
  "ColdFusion",

];

You can check more about custom field passing


问:
Recieving wrong values from JSON API
I have the following code:

```<code>var urlKraken1 = "https://api.kraken.com/0/public/OHLC?pair=XBTUSD&interval=1";
request({
    url: urlKraken1,
    json: true
}, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        var valuesArray = [];
        var cur = body.result.XXBTZUSD.length -1;
        var time = body.result.XXBTZUSD[cur][0];
        var high = body.result.XXBTZUSD[cur][2];
        var low = body.result.XXBTZUSD[cur][3];
        var open = body.result.XXBTZUSD[cur][1];
        var close = body.result.XXBTZUSD[cur][4];
        var volume = body.result.XXBTZUSD[cur][6];
        var Currency1 = "BTC";
        var Currency2 = "USD";
        valuesArray.push([time, "kraken.com", Currency1, Currency2, high, low, open, close, volume]);
        writeMultiRows("kraken.com", Currency1, valuesArray);
}
</code>```

But in my database I'm getting values which are not correct with the ones from the API.
Data I receive for example:

```<code>time = 1499280240
high = 2609.001
low = 2608.666
open = 2609.001
close = 2608.666
volume= 12.42484963
</code>```

But I should receive:

```<code>time = 1499280240
high = 2610.000
low = 2605.022
open = 2609.001
close = 2610.000
volume= 15.42483298
</code>```

Thanks in advance for every kind of tips and help!

答:
The data which your assigning is wrong.
press f12 and open network tab and check the network response to see the exact data...
Assign the  array accordingly...</p>

Title: Recieving wrong values from JSON API

Body:
I have the following code:

var urlKraken1 = "https://api.kraken.com/0/public/OHLC?pair=XBTUSD&interval=1";
request({
    url: urlKraken1,
    json: true
}, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        var valuesArray = [];
        var cur = body.result.XXBTZUSD.length -1;
        var time = body.result.XXBTZUSD[cur][0];
        var high = body.result.XXBTZUSD[cur][2];
        var low = body.result.XXBTZUSD[cur][3];
        var open = body.result.XXBTZUSD[cur][1];
        var close = body.result.XXBTZUSD[cur][4];
        var volume = body.result.XXBTZUSD[cur][6];
        var Currency1 = "BTC";
        var Currency2 = "USD";
        valuesArray.push([time, "kraken.com", Currency1, Currency2, high, low, open, close, volume]);
        writeMultiRows("kraken.com", Currency1, valuesArray);
}

But in my database I'm getting values which are not correct with the ones from the API.
Data I receive for example:

time = 1499280240
high = 2609.001
low = 2608.666
open = 2609.001
close = 2608.666
volume= 12.42484963

But I should receive:

time = 1499280240
high = 2610.000
low = 2605.022
open = 2609.001
close = 2610.000
volume= 15.42483298

Thanks in advance for every kind of tips and help!


问:
Xcode 9 expand/collapse braces/brackets {} side bar missing
Can't find one under

Xcode ▶ Preferences/Text Editing ▶ "Code Folding Ribbon" box.

答:
I have the same question and I found this at forums.developer.apple.com

...isn't implemented in the new editor yet.
@https://forums.developer.apple.com/thread/78912


问:
jQuery add attribute to span and alert when added
I have html table like below:

```<code><table id="list" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr class='thread selected'>
    <td class='subject'>Jill</td>
    <td>Smith</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    <span class='flag'></span>
    </span>
    </td>
  </tr>
  <tr class='thread'>
    <td class='subject'>Eve</td>
    <td>Jackson</td>
    <td class='flags'>
    <span class='attach'></span>
    <span class='flag'>
    </span>
  </td>
  </tr>
</table>
</code>```

If a user select a row I want to add dynamically title='With flag'in last span like

```<code><span class='flag' title='With flag'></span>
</span>
</code>```

and want to alert('title added'); using if statement.

How can I achive this using jQuery

答:
Try this:  </p>

```<code>$(".thread").click(function() {
   $(this).find(".flag").attr("title","With flag");
   alert("title added");
});
</code>```

Body:
I have html table like below:

    Firstname
    Lastname
    Age

    Jill
    Smith

    Eve
    Jackson

If a user select a row I want to add dynamically title='With flag'in last span like

and want to alert('title added'); using if statement.

How can I achive this using jQuery

Body:
Try this:

$(".thread").click(function() {
   $(this).find(".flag").attr("title","With flag");
   alert("title added");
});


问:
SDL_SetWindowSize gives a new window, that can't be written to
In the program below, SDL_SetWindowSize does make the window itself bigger... but it doesn't let SDL_RenderClear (or other functions) display anything in that new area.

The platform is CentOS running on VMWare.  I don't get this problem in my Visual Studio version, FWIW.

In this screenshot, the window with the grey top bar is the new window created by the resize; it's cleared to red, but only in the area delimited by the old size.

I know I could create the window the right size from the beginning, but I really do need the ability to resize later.

```<code>#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>

SDL_Window*   sdlWindow;
SDL_Renderer* sdlRenderer;

class myException {};

void initialize ()
{
  if (SDL_Init (SDL_INIT_EVERYTHING) < 0)
    throw myException ();

  sdlWindow = SDL_CreateWindow ("",
                 SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                 640, 480,
                 0);
  if (! sdlWindow) throw myException ();

  int rendererIndex = -1, rendererFlags =  0;
  sdlRenderer = SDL_CreateRenderer (sdlWindow, rendererIndex, rendererFlags);

  if (! sdlRenderer) throw myException ();

  SDL_ClearError ();
}

int main (int argc, char** argv)
{
  initialize ();

  SDL_SetWindowSize (sdlWindow, 800, 400);

  SDL_SetRenderDrawColor (sdlRenderer, 255, 0, 0, 255); //now we'll clear to red

  SDL_RenderClear   (sdlRenderer);
  SDL_RenderPresent (sdlRenderer); //update screen now

  SDL_Delay (2000);                 //Delay, then quit
  SDL_Quit ();

  return 0;
}
</code>```

答:
The rendering surface is invalidated on windows resize, quote from SDL wiki on SDL_GetWindowSurface:

This surface will be invalidated if the window is resized. After resizing a window this function must be called again to return a valid surface.

So you must get window surface again after resizing window, in general.

Body:
In the program below, SDL_SetWindowSize does make the window itself bigger... but it doesn't let SDL_RenderClear (or other functions) display anything in that new area.

The platform is CentOS running on VMWare.  I don't get this problem in my Visual Studio version, FWIW.

In this screenshot, the window with the grey top bar is the new window created by the resize; it's cleared to red, but only in the area delimited by the old size.

I know I could create the window the right size from the beginning, but I really do need the ability to resize later.

#include <SDL.h>
#include <SDL_ttf.h>
#include <SDL_image.h>

SDL_Window*   sdlWindow;
SDL_Renderer* sdlRenderer;

class myException {};

void initialize ()
{
  if (SDL_Init (SDL_INIT_EVERYTHING) < 0)
    throw myException ();

  sdlWindow = SDL_CreateWindow ("",
                 SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                 640, 480,
                 0);
  if (! sdlWindow) throw myException ();

  int rendererIndex = -1, rendererFlags =  0;
  sdlRenderer = SDL_CreateRenderer (sdlWindow, rendererIndex, rendererFlags);

  if (! sdlRenderer) throw myException ();

  SDL_ClearError ();
}

int main (int argc, char** argv)
{
  initialize ();

  SDL_SetWindowSize (sdlWindow, 800, 400);

  SDL_SetRenderDrawColor (sdlRenderer, 255, 0, 0, 255); //now we'll clear to red

  SDL_RenderClear   (sdlRenderer);
  SDL_RenderPresent (sdlRenderer); //update screen now

  SDL_Delay (2000);                 //Delay, then quit
  SDL_Quit ();

  return 0;
}


问:
Javascript - returning concatenates instead of sum of variables from input
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

```<code><input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
</code>```

JavaScript

```<code>var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});
</code>```

JSFiddle Demo

答:
If your purpose is this according to your code then it will always sum up with first box value.

```<code>  var value = parseInt($(this).val());
    if(value)
    totalvalue = totalvalue + value;
});
</code>```

Otherwise you should elaborate your question so that proper answer could be provided.

Body:
I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

HTML

<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>

JavaScript

var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
    $(".value").each(function() {
        totalvalue = parseInt(totalvalue + $(this).val());
    });
    $("#totalvalue").val(totalvalue);
});

JSFiddle Demo

Body:
If your purpose is this according to your code then it will always sum up with first box value.

  var value = parseInt($(this).val());
    if(value)
    totalvalue = totalvalue + value;
});

Otherwise you should elaborate your question so that proper answer could be provided.


问:
Spring Boot ModelAndView - cannot update value to Model
I am trying to create a form with 3 fields within the class LoginForm: usuario, senha, msgLogin.
I receive the fields usuário and senha from the input boxes and then I try to redirect to the same page with the same fields plus the field MsgLogin. But I've not been able to update the msgLogin field and I don't understand why.
These are the code:

HTML:

```<code><form id="frmLogin" class="form col-md-12" action="#" th:action="@{/login}" th:object="${loginForm}" method="post">
        <div class="form-group">
            <label for="usuario" class="col-md-1">Usuário: </label>
            <input type="text" id="usuario" placeholder="Email" th:field="*{usuario}"/>
        </div>

        <div class="form-group">
            <label for="senha" class="col-md-1">Senha: </label>
            <input type="password" id="senha" placeholder="senha" th:field="*{senha}"/>
        </div>

        <div class="row">
            <button id="entrar">Entrar</button>
        </div>

    <div class="row">
        <div id="msgLogin"></div>
        <p th:text="${loginForm.msgLogin}" />
    </div>
</form>
</code>```

The Controller:

```<code>@RequestMapping("/")
public String init(@ModelAttribute LoginForm loginForm) {
    Logger.getAnonymousLogger().info("Tela Inicial.");
    return "home";
}

@PostMapping("/login")
public ModelAndView entrar(LoginForm loginForm) throws IOException {
    Logger.getAnonymousLogger().info("Entrando no Internet Banking.");

    service.login(usuario, senha);

    ModelMap model = new ModelMap();
    loginForm.setMsgLogin("I want to update that value!");
    model.addAttribute("loginForm", loginForm);
    return new ModelAndView("redirect:/", model);
}
</code>```

Class using Lombok:

```<code>@Getter
@Setter
public class LoginForm {

    private String usuario;

    private String senha;

    private String msgLogin;

}
</code>```

答: A redirect send a 302 HTTP status back to the browser to resubmit using a new url, so it resubmits the same two fields to the new url. There's no expectation of payload data in the 302 response.</p>

Body:
I am trying to create a form with 3 fields within the class LoginForm: usuario, senha, msgLogin.
I receive the fields usuário and senha from the input boxes and then I try to redirect to the same page with the same fields plus the field MsgLogin. But I've not been able to update the msgLogin field and I don't understand why.
These are the code:

HTML:

<form id="frmLogin" class="form col-md-12" action="#" th:action="@{/login}" th:object="${loginForm}" method="post">

            Usuário:
            <input type="text" id="usuario" placeholder="Email" th:field="*{usuario}"/>

            Senha:
            <input type="password" id="senha" placeholder="senha" th:field="*{senha}"/>

            <button id="entrar">Entrar</button>

</form>

The Controller:

@RequestMapping("/")
public String init(@ModelAttribute LoginForm loginForm) {
    Logger.getAnonymousLogger().info("Tela Inicial.");
    return "home";
}

@PostMapping("/login")
public ModelAndView entrar(LoginForm loginForm) throws IOException {
    Logger.getAnonymousLogger().info("Entrando no Internet Banking.");

    service.login(usuario, senha);

    ModelMap model = new ModelMap();
    loginForm.setMsgLogin("I want to update that value!");
    model.addAttribute("loginForm", loginForm);
    return new ModelAndView("redirect:/", model);
}

Class using Lombok:

@Getter
@Setter
public class LoginForm {

    private String usuario;

    private String senha;

    private String msgLogin;

}


问:
how to fulfill two conditions inside a defined function in python?
I was wondering if there is a way to fulfill two if statements simultaneously. I have the following code:

```<code>def crossingTime(self, level, channel_data, times):
    ndata = len(channel_data)
    for i in range(ndata-1):
        thisADC = channel_data[i]
        nextADC = channel_data[i+1]
        if thisADC >= level and nextADC < level:
            return times[i]
</code>```

The code is fully functional, but I want to implement a second condition, which should be fulfilled simultaneously after if statement:

```<code>if thisADC <= level and nextADC > level:
   return times[i]
</code>```

However, I'm not completely sure how to go about that. Any help will be truly appreciated.

答:
If you want to return times[i] if either of your conditions is true, why not just doing:

```<code>if thisADC >= level and nextADC < level or thisADC <= level and nextADC > level:
    return times[i]
</code>```

Body:
I was wondering if there is a way to fulfill two if statements simultaneously. I have the following code:

def crossingTime(self, level, channel_data, times):
    ndata = len(channel_data)
    for i in range(ndata-1):
        thisADC = channel_data[i]
        nextADC = channel_data[i+1]
        if thisADC >= level and nextADC < level:
            return times[i]

The code is fully functional, but I want to implement a second condition, which should be fulfilled simultaneously after if statement:

if thisADC <= level and nextADC > level:
   return times[i]

However, I'm not completely sure how to go about that. Any help will be truly appreciated.

Body:
If you want to return times[i] if either of your conditions is true, why not just doing:

if thisADC >= level and nextADC < level or thisADC <= level and nextADC > level:
    return times[i]


问:
Simon Game how to proceed?
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

```<code>var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]
</code>```

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

```<code>Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.
</code>```

So that's what I did:

```<code>var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }
</code>```

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

```<code>for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }
</code>```

But it doesn't work. Can anyone help me out?

答:
I myself am trying to build the Simon game(I am just starting in front end development). Here are some of the pointers that I made before starting out.

I need to start with one coloring tile to bleep once and followed by two coloring tiles to bleep once each and so on for number of levels you decide. So, my approach is to have 4 colored tiles already defined say 1 for red,2 for yellow,3 for blue,4 for green tiles. Now for each level I can generate random numbers(1 through 4) via a function. So, if I am using a loop that runs equal to number of times what level the game is on, I'll have one random number generated for level 1, 2 random numbers generated for level 2 and so on.

For each random number, you could bleep the respective colored tile.

Now for the time gap between the bleeps of colored tiles, you could make use of setInterval function to run after certain amount of milliseconds, which is only cleared only when required number of tiles have bleeped. E.g. On level 4, the setInterval should run for 4 times with a time gap of 1000 ms.

Now, as advancing through levels you could decrease the time gap to make the game faster and more challenging.

Also, note down how you're going to let user know, that it's their turn to play now and also, once user is done with their level, how do you tell the application it should not wait for more user input and analyse the result of this level and proceed or not for the next level.

I know, this is all words, but believe me, if you have all this planned, your effort will be less and more fruitful.

Title: Simon Game how to proceed?

Body:
So I am trying to build a Simon Game.
First of all I created a random array with 20 values that varies between 1 and 4 (That would identify each color of the game).
So 1 would be red, 2 would be blue, 3 would be green and 4 would be yellow.
So I got the array which is something like this:

var arrayRandomColors = [1, 3, 1, 2, 4, 3, 2, 1, 3, 2, 1, 2, 4, 1, 2, 3, 4, 1, 3, 2]

Now this is de order of sounds and colors of my Simon Game. However, I now need to go over there array like this:

Level 1 - [1] -> Level 2 - [1, 3] -> Level 3 - [1, 3, 1] ->  Level 4 - [1, 3, 1, 2]... etc. And then each time it loops over these arrays it plays a sequence o sounds that corresponds to the current level.

So that's what I did:

var j=2;
    var arrayPlay = [];
    for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        console.log(arrayPlay); //[1] -> [1,3] -> [1,3,1]...etc
        arrayPlay = [];
    }

So far, I managed to get all the arrays I want. However, I got stuck about how to proceed, because I need to go over this numbers slowly, showing the colors being selected and playing a sound while it loops, and the for loop is just too fast. I thought about doing something like this:

for (var j=2; j<22; j++){
        for(var i=1; i<j; i++){
            arrayPlay.push(arrayRandomColors[i-1]);
        }
        //console.log(arrayPlay);
        for (var k=0; k<arrayPlay.length; k++){
            var id = setInterval(function(){
                console.log("entrou");
            if (arrayPlay[k] == 1){
                $red.css("background-color", "#ffc1c1");
                $red.delay(500);
                $red.css("background-color", "red");
            }
            else if (arrayPlay[k] == 2){
                $blue.css("background-color", "#a5b0f7");
                $blue.delay(500);
                $blue.css("background-color", "blue");
            }
            else if (arrayPlay[k] == 3){
                $green.css("background-color", "#aff7a5");
                $green.delay(500)
                $green.css("background-color", "green");
            }
            else if (arrayPlay[k] == 4){
                $yellow.css("background-color", "#fffb91");
                $yellow.delay(500);
                $yellow.css("background-color", "yellow");
            }

            }, 500);
        }
        arrayPlay = [];
        console.log("\n");
    }

But it doesn't work. Can anyone help me out?


问:
c# - Checking if a specific material tab page is active
I'm trying to check if a specific tab page is active in my tab control, in order to change some of the colors in my form.
I have checked this question! but the problem I'm facing now is that I'm using materialskin framework, and looks like the tab selectors of this framework have no SelectedTab property, so I couldn't use

if(materialTabSelector1.Controls[5] == materialTabSelector1.SelectedTab)
    MessageBox.Show("Tab 5 Is Selected");

or any other similar codes provided in the answers of that post.
maybe I can handle the mouse left button click on each of the tabs, but the selector does not have a click event for each of it's pages.

any other suggestions for doing that?

答: The TabSelector is just for Displaying the what Tab is Active, but it does not contain any Controls or logic behind it. But it has a BaseTabControl, which is pretty much a normal TabControl. In there you could apply your logic.</p>


问:
Lisp Format Procedure Applied to Arrays
I need some help with the format function and arrays.

My objective is to print a 2 dimensional array of N·N integer values as N integers per line. For example:

```<code>#2A((1 2 3)
    (4 5 6)
    (7 8 9))
</code>```

should be printed as

```<code>1 2 3
4 5 6
7 8 9
</code>```

I couldn't find any documentation on how to use format to print arrays. Can it actually be done, or should I convert my array into a list and use something like:

```<code>(format t "~{~%~{~A~^ ~}~}"  list)
</code>```

答:
```<code>(defun show-board (board)
  (loop for i below (car (array-dimensions board)) do
        (loop for j below (cadr (array-dimensions board)) do
          (let ((cell (aref board i j)))
            (format t "~a " cell)))
        (format t "~%")))
</code>```

Title: Lisp Format Procedure Applied to Arrays

Body:
I need some help with the format function and arrays.

My objective is to print a 2 dimensional array of N·N integer values as N integers per line. For example:

#2A((1 2 3)
    (4 5 6)
    (7 8 9))

should be printed as

1 2 3
4 5 6
7 8 9

I couldn't find any documentation on how to use format to print arrays. Can it actually be done, or should I convert my array into a list and use something like:

(format t "~{~%~{~A~^ ~}~}"  list)


问:
Default permissions class for DRF
Django rest framework currently has IsAdminUseras a permissions class is there also a corresponding IsOwnerOrAdminUser?  Something to that affect? It seems like there should be something that only allows an object to have CRUD functionality if the current user is the one that created it.  I'm using DRF with djangorestframework-jwt

答:
You can find full list of rest-framework permissions in docs. There is DjangoModelPermissionsOrAnonReadOnly which allows no-safe methods only for users with add, change and delete permissions on models.
If it's not fit your requrements you can implement your own permission class something like this:

```<code>class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user or request.user.is_superuser
</code>```

This method is documented here.

Title: Default permissions class for DRF

Body:
You can find full list of rest-framework permissions in docs. There is DjangoModelPermissionsOrAnonReadOnly which allows no-safe methods only for users with add, change and delete permissions on models.
If it's not fit your requrements you can implement your own permission class something like this:

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user or request.user.is_superuser

This method is documented here.


问:
Need java code in importing a text file comparing a set of strings
I have a set strings (string1,string2,string3,string4) and i want to search this in a text file (input.txt) using java coding, i have tried using below command but it is not working, please help.</p>

```<code>package string;
import java.io.File; //Required for input file
import java.io.FileNotFoundException; //Required for exceptioenter code heren throw
import java.util.Scanner; //required for scanner

public class strng {

public static void main(String[] args) throws FileNotFoundException // throws clause added
{

//ask the the for the string to be searched
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter part of the string: ");
    String searchString = keyboard.next().toLowerCase();

 // open the data file
    File file = new File("APPD_01_15_16_01.txt");
 // create a scanner from the file
    Scanner inputFile = new Scanner (file);

    // While there is another line to read.
    while(inputFile.hasNext())
    {
        // read the lines
         //Read string

        //Check if user input is a match and if true print out info.

        if(searchString.contains("samplemachine")
        {
            System.out.println("Yup!");
        }
        else
        {
            System.out.println("Fail!");
        }
    }

    // be polite and close the file
    inputFile.close();

}

}
</code>```

答:
Based on your code, your not reading the contents of your inputFile. You should read the contents of your inputFile line by line inside your loop. After you read the line, you can now check if the line contains what your looking for.</p>

```<code>// While there is another line to read.
while(inputFile.hasNextLine())
{
    // read the next line from the input file
    String line = inputFile.nextLine();

    //Check if user input is a match and if true print out info.
    if(line.contains(searchString)
    {
        System.out.println(line);
    }
}
</code>```

Body:
I have a set strings (string1,string2,string3,string4) and i want to search this in a text file (input.txt) using java coding, i have tried using below command but it is not working, please help.

package string;
import java.io.File; //Required for input file
import java.io.FileNotFoundException; //Required for exceptioenter code heren throw
import java.util.Scanner; //required for scanner

public class strng {

public static void main(String[] args) throws FileNotFoundException // throws clause added
{

//ask the the for the string to be searched
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter part of the string: ");
    String searchString = keyboard.next().toLowerCase();

 // open the data file
    File file = new File("APPD_01_15_16_01.txt");
 // create a scanner from the file
    Scanner inputFile = new Scanner (file);

    // While there is another line to read.
    while(inputFile.hasNext())
    {
        // read the lines
         //Read string

        //Check if user input is a match and if true print out info.

        if(searchString.contains("samplemachine")
        {
            System.out.println("Yup!");
        }
        else
        {
            System.out.println("Fail!");
        }
    }

    // be polite and close the file
    inputFile.close();

}

}

Body:
Based on your code, your not reading the contents of your inputFile. You should read the contents of your inputFile line by line inside your loop. After you read the line, you can now check if the line contains what your looking for.

// While there is another line to read.
while(inputFile.hasNextLine())
{
    // read the next line from the input file
    String line = inputFile.nextLine();

    //Check if user input is a match and if true print out info.
    if(line.contains(searchString)
    {
        System.out.println(line);
    }
}


问:
Positioning images with FloatLayout
This is driving me insane.  I'm trying to position an image to the top of the main window with FloatLayout.  Below is a simplified example.

It seems that a button is fine, but an image defaults to a 100x100 square (yes, I think I've read that somewhere) and the top bounding box of the image is at the top of the screen, not the image.

How can I force the image (top of the rectangle) to the top of the window like the button is?

Screen_showing example_button_and_image

```<code>import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
from kivy.config import Config

Config.set('graphics', 'width', '480')
Config.set('graphics', 'height', '800')

class MyApp(App):

    def setOrientation(self, orient):
        """"""
        self.orient = orient

    def build(self):
        return FloatLayout()

if __name__ == "__main__":
    app = MyApp()
    app.setOrientation(orient="vertical")
    app.run()

<FloatLayout>:
    Image:
        source: 'image_400x90.png'
        pos_hint: {'left':1, 'top':1}
        size_hint: None, None
        allow_stretch: False
        keep_ratio: True

    Button:
        font_size: 30
        color: 0,1,0,1
        size_hint: 0.3, 0.1
        text: "TopRight"
        pos_hint: {'right':1, 'top':1}
</code>```

答:
That happend because the Image is a Widget and "the real image" (the picture) is a texture of that Widget, and by default, the image is centered and fits inside the widget bounding box. If you don’t want that, you can set allow_stretch to True and keep_ratio to False. (docs)

For understand that you can add a canvas with a rectangle in the Image Widget like this:

```<code>Image:
        canvas:
            Color:
                rgba: 1, 1, 1, 0.5
            Rectangle:
                pos: self.pos
                size: self.size
        source: 'dog.jpg'
        pos_hint: {'left':1, 'top':1}
        size_hint: None, None
        allow_stretch: True
        keep_ratio: False
</code>```

And then you can see why the image doesn't do what you want

another pic (the image(texture) is centered and fits inside the widget):

One thing you can do is set allow_stretch: True and keep_ratio: False
This is the result: (set the size with size_hint)

Title: Positioning images with FloatLayout

Body:
This is driving me insane.  I'm trying to position an image to the top of the main window with FloatLayout.  Below is a simplified example.

It seems that a button is fine, but an image defaults to a 100x100 square (yes, I think I've read that somewhere) and the top bounding box of the image is at the top of the screen, not the image.

How can I force the image (top of the rectangle) to the top of the window like the button is?

Screen_showing example_button_and_image

import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.floatlayout import FloatLayout
from kivy.config import Config

Config.set('graphics', 'width', '480')
Config.set('graphics', 'height', '800')

class MyApp(App):

    def setOrientation(self, orient):
        """"""
        self.orient = orient

    def build(self):
        return FloatLayout()

if __name__ == "__main__":
    app = MyApp()
    app.setOrientation(orient="vertical")
    app.run()

<FloatLayout>:
    Image:
        source: 'image_400x90.png'
        pos_hint: {'left':1, 'top':1}
        size_hint: None, None
        allow_stretch: False
        keep_ratio: True

    Button:
        font_size: 30
        color: 0,1,0,1
        size_hint: 0.3, 0.1
        text: "TopRight"
        pos_hint: {'right':1, 'top':1}

Body:
That happend because the Image is a Widget and "the real image" (the picture) is a texture of that Widget, and by default, the image is centered and fits inside the widget bounding box. If you don’t want that, you can set allow_stretch to True and keep_ratio to False. (docs)

For understand that you can add a canvas with a rectangle in the Image Widget like this:

Image:
        canvas:
            Color:
                rgba: 1, 1, 1, 0.5
            Rectangle:
                pos: self.pos
                size: self.size
        source: 'dog.jpg'
        pos_hint: {'left':1, 'top':1}
        size_hint: None, None
        allow_stretch: True
        keep_ratio: False

And then you can see why the image doesn't do what you want

another pic (the image(texture) is centered and fits inside the widget):

One thing you can do is set allow_stretch: True and keep_ratio: False
This is the result: (set the size with size_hint)


问:
How do I add a context menu to an app

I would like to know how to implement this "context menu" with action buttons like the one that appears on whatsapp and other apps when you click message.

Thank you very much.

答:
That is UIMenuController. I am not good with swift. For Swift please check this link. Objective C code is as follows:

```<code>- (void)showMenu
{
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = @[
       [[UIMenuItem alloc] initWithTitle:@"Title1" action:@selector(MyAction1)],
       [[UIMenuItem alloc] initWithTitle:@"Title2" action:@selector(MyAction2)],
       [[UIMenuItem alloc] initWithTitle:@"Title3" action:@selector(MyAction)]];
    [menu setTargetRect:self.bounds inView:self];
    [menu setMenuVisible:YES animated:YES];
}
</code>```

Title: How do I add a context menu to an app

Body:
That is UIMenuController. I am not good with swift. For Swift please check this link. Objective C code is as follows:

- (void)showMenu
{
    UIMenuController *menu = [UIMenuController sharedMenuController];
    menu.menuItems = @[
       [[UIMenuItem alloc] initWithTitle:@"Title1" action:@selector(MyAction1)],
       [[UIMenuItem alloc] initWithTitle:@"Title2" action:@selector(MyAction2)],
       [[UIMenuItem alloc] initWithTitle:@"Title3" action:@selector(MyAction)]];
    [menu setTargetRect:self.bounds inView:self];
    [menu setMenuVisible:YES animated:YES];
}


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答:
I jumped into Rails and Django without learning Ruby or Python first.

You learn what you need to know pretty quickly and everything you do learn is always guaranteed to be practical and immediately useful.

If you already understand MVC you already know which piece of code does what.


问:
Adding Data to an Object
```<code>targetList: any = [];
public datavalue = [
  {
    value: ""
  }
]

this.httpService.service("Fields").subscribe(
  (
    targetList => {
      this.targetList = targetList;
      console.log(this.targetList);
      for (var i = 0; i < this.targetList.length; i++) {
        if (this.targetList[i].results.multiple == true) {
         this.targetList[i].results.data = this.datavalue;
        }
      }
    }
  ),
  error => { alert(`Can't get Fields.`); }
);

addvalue(i): void {
   var dataObj = {
    value: ""
   };
   this.targetList[i].results.data.push(dataObj);
 }

 removevalue(i, index) {
   this.targetList[i].results.data.splice(index, 1);
  }
</code>```

The data i get In my Service is as following

```<code>[
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":false
     }
  }
]
</code>```

In This Result if multiple = true then how to add this data .

```<code>[
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true,
       "data" :[
                  {
                     value : ""
                  }
                ]
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
       "data" :[
                  {
                     value : ""
                  }
                ]
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":false
     }
  }
]
</code>```

Help in the Adding this format , as the fields are dynamic . I am rendering this into the Html page.

```<code>                <div *ngIf="targetList.length>0">
                <!-- Index i for List of Elements-->
                <div *ngFor="let target of targetList; let i = index">
                  <fieldset>
                    <section>
                      <label class="label">{{target.results.field1}}</label>
                      <div *ngIf="target.results.multiple else singletext" class="table-responsive">
                        <table class="table table-bordered">
                          <tbody>
                            <!-- Index j for Multiple Data within an Element-->
                            <tr *ngFor="let data of target.results.data; let j = index">
                              <td>
                                <label class="input">
                                    <input type="text" name={{target.results.field1+i+j}} ngModel class="input-sm">
                                </label>
                              </td>
                              <td>
                                <label class="input">
                                    <a class="btn btn-danger btn-sm" (click)="removevalue(i,j)"><i class=" fa fa-remove"></i></a></label>
                              </td>
                            </tr>
                            <tr>
                              <td colspan="2"><a class="btn btn-success btn-sm" (click)="addvalue(i)">Add Value</a></td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                      <ng-template #singletext>
                        <label class="input">
                            <input type="text" name={{target.results.feild1+i}} ngModel  class="input-sm">
                        </label>
                      </ng-template>
                      <label class="label">{{ target.results.desc }}</label>
                    </section>
                  </fieldset>
                </div>
              </div>
</code>```

In this one , if i use the above code , it is adding datalist to the second object as well, while i need to add it only for the first object.

答:
loop through the your entire json object and look for the <code>'multiple'</code> attribute in each of the objects contained within an array   </p>

```<code> targetList: any = [];

    this.httpService.service("Fields").subscribe(
      (
        targetList => {
          this.targetList = targetList.json();
          console.log(this.targetList);

          for(let i=0 ; i<this.targetList.length ; i++ ){
              if(this.targetList[i].results.multiple){
                 // assuming you have data ready in 'dataValue' object
                 this.targetList[i].results['data'] = Object.assign({}, dataValue); // clone the object before setting it
              }
          }
        }
      ),
      error => { alert(`Can't get Fields.`); }
    );
</code>```

Title: Adding Data to an Object

Body:
targetList: any = [];
public datavalue = [
  {
    value: ""
  }
]

this.httpService.service("Fields").subscribe(
  (
    targetList => {
      this.targetList = targetList;
      console.log(this.targetList);
      for (var i = 0; i < this.targetList.length; i++) {
        if (this.targetList[i].results.multiple == true) {
         this.targetList[i].results.data = this.datavalue;
        }
      }
    }
  ),
  error => { alert(`Can't get Fields.`); }
);

addvalue(i): void {
   var dataObj = {
    value: ""
   };
   this.targetList[i].results.data.push(dataObj);
 }

 removevalue(i, index) {
   this.targetList[i].results.data.splice(index, 1);
  }

The data i get In my Service is as following

[
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":false
     }
  }
]

In This Result if multiple = true then how to add this data .

[
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true,
       "data" :[
                  {
                     value : ""
                  }
                ]
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":true
       "data" :[
                  {
                     value : ""
                  }
                ]
     }
  },
  {
     "results":{
       "field1":false,
       "field2":0,
       "multiple":false
     }
  }
]

Help in the Adding this format , as the fields are dynamic . I am rendering this into the Html page.

0">

                  <fieldset>

                      {{target.results.field1}}

                                    <input type="text" name={{target.results.field1+i+j}} ngModel class="input-sm">

                              Add Value

                      <ng-template #singletext>

                            <input type="text" name={{target.results.feild1+i}} ngModel  class="input-sm">

                      </ng-template>
                      {{ target.results.desc }}

                  </fieldset>

In this one , if i use the above code , it is adding datalist to the second object as well, while i need to add it only for the first object.

Body:
loop through the your entire json object and look for the 'multiple' attribute in each of the objects contained within an array

 targetList: any = [];

    this.httpService.service("Fields").subscribe(
      (
        targetList => {
          this.targetList = targetList.json();
          console.log(this.targetList);

          for(let i=0 ; i<this.targetList.length ; i++ ){
              if(this.targetList[i].results.multiple){
                 // assuming you have data ready in 'dataValue' object
                 this.targetList[i].results['data'] = Object.assign({}, dataValue); // clone the object before setting it
              }
          }
        }
      ),
      error => { alert(`Can't get Fields.`); }
    );


问:
Python- positional argument follows keyword argument
I have a function which accepts variable length of arguments as described below. I am passing the kwargs as a dictionary. However I don't understand why I am getting the error.

```<code>class PanSearch(object):
    otp_wait = 30

    def __init__(self, surname, dob, mobile_no, otp_host, **kwargs):
        kwargs.setdefault('browser', 'chromium')
        self.surname = surname
        self.dob = dob
        self.mobile_no = mobile_no
        self.otp_host = otp_host
        self.middle_name = kwargs.get('middle_name', None)
        self.first_name = kwargs.get('first_name', None)
        self.status = kwargs.get('status')
        self.gender = 'M' if kwargs.get('status') == 'P' else None

# instantiating the object
otp_host = 'abc.xyz.in'
input_kwargs = {'status': 'P', 'gender': 'M', 'browser': 'chromium'}
driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)

File "pan_no.py", line 87
    driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)
                                                                                ^
SyntaxError: positional argument follows keyword argument
</code>```

答:
you need to change

```<code>driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)
</code>```

to

```<code>driver = PanSearch('kulkarni', '13/10/1981', '9769172006', otp_host, **input_kwargs)
</code>```

Body:
I have a function which accepts variable length of arguments as described below. I am passing the kwargs as a dictionary. However I don't understand why I am getting the error.

class PanSearch(object):
    otp_wait = 30

    def __init__(self, surname, dob, mobile_no, otp_host, **kwargs):
        kwargs.setdefault('browser', 'chromium')
        self.surname = surname
        self.dob = dob
        self.mobile_no = mobile_no
        self.otp_host = otp_host
        self.middle_name = kwargs.get('middle_name', None)
        self.first_name = kwargs.get('first_name', None)
        self.status = kwargs.get('status')
        self.gender = 'M' if kwargs.get('status') == 'P' else None

# instantiating the object
otp_host = 'abc.xyz.in'
input_kwargs = {'status': 'P', 'gender': 'M', 'browser': 'chromium'}
driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)

File "pan_no.py", line 87
    driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)
                                                                                ^
SyntaxError: positional argument follows keyword argument

Body:
you need to change

driver = PanSearch(surname='kulkarni', dob='13/10/1981', mobile_no='9769172006', otp_host, **input_kwargs)

to

driver = PanSearch('kulkarni', '13/10/1981', '9769172006', otp_host, **input_kwargs)


问:
compare column of two rows of same table in mysql
I have a table name player_history containing history of player. in this table having column player_id, Final_position,meeting_code,race_no and beaten_time. If a player stood a first or second position the time will be same there are meeting code one day and in each meeting code there are maximum 10 races.

I want to select those records where 1st and second position beaten time are not same.

```<code>player_id Meeting_Code race_no final_position beaten_time
  1         0001          1         1             2
  2         0001          1         2             2
  1         0001          2         1             5
  2         0001          2         2             6
... so on
</code>```

Output should be:

```<code>player_id Meeting_Code race_no final_position beaten_time
  1         0001          2         1             5
  2         0001          2         2             6
</code>```

Also if it is not correct I want to update records of first position only.

答:
Check this it will work</p>

```<code>SELECT *
FROM   table_name
GROUP BY player_id
HAVING count(beaten_time) = 1;
</code>```

Body:
I have a table name player_history containing history of player. in this table having column player_id, Final_position,meeting_code,race_no and beaten_time. If a player stood a first or second position the time will be same there are meeting code one day and in each meeting code there are maximum 10 races.

I want to select those records where 1st and second position beaten time are not same.

player_id Meeting_Code race_no final_position beaten_time
  1         0001          1         1             2
  2         0001          1         2             2
  1         0001          2         1             5
  2         0001          2         2             6
... so on

Output should be:

player_id Meeting_Code race_no final_position beaten_time
  1         0001          2         1             5
  2         0001          2         2             6

Also if it is not correct I want to update records of first position only.

Body:
Check this it will work

SELECT *
FROM   table_name
GROUP BY player_id
HAVING count(beaten_time) = 1;


问:
How to build this query in postgresql

Supposing I have this data. How to query this in such a way that will result to this in an efficient way. It will sum the qty of all OUT less the IN per item.

答:
Or

```<code>SELECT Description, SUM(Case WHEN rowtype = 'in' then 1 else -1 end * Qty) as rowqty FROM yourtable GROUP BY description
</code>```

Note that it is not a good idea to use reserved words as column names.  DESC and TYPE are asking for trouble!

Title: How to build this query in postgresql

Body:
Or

SELECT Description, SUM(Case WHEN rowtype = 'in' then 1 else -1 end * Qty) as rowqty FROM yourtable GROUP BY description

Note that it is not a good idea to use reserved words as column names.  DESC and TYPE are asking for trouble!


问:
How to read image as FileInputStream from source folder?
I have been trying to upload image to database. So I made a browse button to go through directories and get the image.  Suppose if no image is selected, a default image will be uploaded to the database. The image is stored in a folder named 'resources' under source folder.In the image, helper is the folder containting .java files and below is the resources folder I am uploading the image as FileInputStream and the code is

```<code>File pic=new File(imgloc);
FileInputStream fis=new FileInputStream(pic);
</code>```

If the image is not selected to upload a default image my code is

```<code>File pic=new File(this.getClass().getResource("/resources/profile1.png").getFile());
FileInputStream fis=new FileInputStream(pic);
</code>```

And my query to database is

```<code>    ps.setBinaryStream(1,fis ,(int) pic.length()); //While substituing for '?' in query
</code>```

After build to jar it produce FileNotFoundException when trying to add default image. May be the question is asked several times I didn't find solution in that.  I want read the image as file..Thanks in advance.

答:
to help illustrate I create a project with a source directory

```<code>src
</code>```

below source I had a package starthere with a class Main

I create another source directory xxx and put in a file a.txt

I also created under xxx a directory called text and put in a file named b.txt

Also I created under src a directory called other and put in a file called c.txt

My code is

```<code>    URL url = Main.class.getResource("/a.txt");
    System.out.println(url);
    URL url2 = Main.class.getResource("/text/b.txt");
    System.out.println(url2);
    URL url3 = Main.class.getResource("/other/c.txt");
    System.out.println(url3);
</code>```

and my output is

D:\temp>java -cp ab.jar starthere.Main

jar:file:/D:/temp/ab.jar!/a.txt

jar:file:/D:/temp/ab.jar!/text/b.txt

jar:file:/D:/temp/ab.jar!/other/c.txt

edit

As you are not wanting to use a File, but simply the InputStream, you can use

```<code>InputStream fis = Main.class.getResourceAsStream("/a.txt");
</code>```

and then set using ps.setBinaryStream(1, fis);

Body:
I have been trying to upload image to database. So I made a browse button to go through directories and get the image.  Suppose if no image is selected, a default image will be uploaded to the database. The image is stored in a folder named 'resources' under source folder.In the image, helper is the folder containting .java files and below is the resources folder I am uploading the image as FileInputStream and the code is

File pic=new File(imgloc);
FileInputStream fis=new FileInputStream(pic);

If the image is not selected to upload a default image my code is

File pic=new File(this.getClass().getResource("/resources/profile1.png").getFile());
FileInputStream fis=new FileInputStream(pic);

And my query to database is

    ps.setBinaryStream(1,fis ,(int) pic.length()); //While substituing for '?' in query

After build to jar it produce FileNotFoundException when trying to add default image. May be the question is asked several times I didn't find solution in that.  I want read the image as file..Thanks in advance.

Body:
to help illustrate I create a project with a source directory

src

below source I had a package starthere with a class Main

I create another source directory xxx and put in a file a.txt

I also created under xxx a directory called text and put in a file named b.txt

Also I created under src a directory called other and put in a file called c.txt

My code is

    URL url = Main.class.getResource("/a.txt");
    System.out.println(url);
    URL url2 = Main.class.getResource("/text/b.txt");
    System.out.println(url2);
    URL url3 = Main.class.getResource("/other/c.txt");
    System.out.println(url3);

and my output is

D:\temp>java -cp ab.jar starthere.Main

jar:file:/D:/temp/ab.jar!/a.txt

jar:file:/D:/temp/ab.jar!/text/b.txt

jar:file:/D:/temp/ab.jar!/other/c.txt

edit

As you are not wanting to use a File, but simply the InputStream, you can use

InputStream fis = Main.class.getResourceAsStream("/a.txt");

and then set using ps.setBinaryStream(1, fis);


问:
Iterate over all elements in template in Angular2
I have following template. How can I get access to all the elements inside the template? I tried using ViewChildren but it gives reference to only one element (I guess because no two elements are same and I am not using same directive/component inside the template)

```<code>template: `

 <div>Name: <input type="text" name="name" /> </div>
 <div>Gender: <select  name="gender" >
    <option>Male(1)</option>
    <option>Female(2)</option>
  </select>
 </div>
 <div>About you: <textarea ></textarea></div>
 <div>Married: <input type="checkbox" /></div>
  <div>
  Children:
    <ng-container *ngFor = "let option of this.selectOptions">
    <input  type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"/> {{option}}
    </ng-container>
  </div>
  <p > Some para</p>
  <p >Para with span <span>Inside span</span></p>

`
</code>```

Question 1 -
How can I get a collection of all elements in the template?

Question 2 -
What would be the way to distinguish between the elements. I guess all the elements would be of type ElementRef.

答:
The idea with Angular is that you should never need to do this.

There are very few circumstances where manipulating the DOM directly
  is necessary.   Angular 2 provides a set of powerful, high-level APIs
  like queries that one can use instead.
  - http://angularjs.blogspot.com/2016/04/5-rookie-mistakes-to-avoid-with-angular.html

Body:
I have following template. How can I get access to all the elements inside the template? I tried using ViewChildren but it gives reference to only one element (I guess because no two elements are same and I am not using same directive/component inside the template)

template: `

Name: <input type="text" name="name" />

Gender: <select  name="gender" >
    <option>Male(1)</option>
    <option>Female(2)</option>
  </select>

About you: <textarea ></textarea>

Married: <input type="checkbox" />

  Children:
    <ng-container *ngFor = "let option of this.selectOptions">
    <input  type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"/> {{option}}
    </ng-container>

 Some para

Para with span Inside span

`

Question 1 -
How can I get a collection of all elements in the template?

Question 2 -
What would be the way to distinguish between the elements. I guess all the elements would be of type ElementRef.


问:
Parse string for unicode characters in C#
I have an input form where someone is allowed to type unicode characters. So it might be something like "Hey \uF32A what's up?". If I get this string it will have a substring of "\uF32A" how do i turn that to the character '\uF32A'?</p>

答:
Use Regular Expression to Unescape as shown below:</p>

```<code>var str = @"Hey \uF32A what's up?";
System.Text.RegularExpressions.Regex.Unescape(str);
</code>```

Body:
Use Regular Expression to Unescape as shown below:

var str = @"Hey \uF32A what's up?";
System.Text.RegularExpressions.Regex.Unescape(str);


问:
Unable to load Web Application project due to its configuration
I've a problem with loading Web Application project in VS2013. This project depends on IIS Express, but I wouldn't install IIS Express because I already installed IIS.

What I can edit in .csproj file to load this project? I've tried to set  to false, but it's wouldn't help me to solve problem.

Thank you for advice.

Upd.1: Also, I cannot create new web projects - VS tell me same things.

答:
If nothing works, try removing following two lines from .csproj file. (always worked for me)

```<code><ProjectGuid>{3AA499DF-4A65-43B7-8965-D08A4C811834}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
</code>```

Body:
If nothing works, try removing following two lines from .csproj file. (always worked for me)

<ProjectGuid>{3AA499DF-4A65-43B7-8965-D08A4C811834}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>