问:
How to get nested class instance drools
I am newbie to drool usage and i have small query.
I have map as below for which i have created pojo using schemaJson2Pojo java api :

```<code>{
"svo": [
      {
        "clause": "Sunanda Pushkar died of poisoning",
        "svoMetadata": {
          "person": "sunanda pushkar",
          "subjectType": "person_coref"
        },
        "objectPOS": "IN VBG;",
        "isRelatedKeySVO": false,
        "subjectPOS": " NNP NNP",
        "subject": "Sunanda Pushkar",
        "confidence": 0.9266232318014763,
        "verb": "died",
        "verbPOS": "VBN",
        "source": "OpenIE",
        "isKeySVO": true,
        "object": "of poisoning;"
      }]
}
</code>```

Note : svo.svoMetadata has person name

So, on using schemaJson2Pojo api , following classes are generated :

```<code>class RootDoc
{
 private List<Svo> svo = new ArrayList<Svo>();

 public List<Svo> getSvo() {
        return svo;
    }

    public void setSvo(List<Svo> svo) {
        this.svo = svo;
    }
}

class Svo
{
  private SvoMetadata svoMetadata;

public SvoMetadata getSvoMetadata() {
        return svoMetadata;
    }

    public void setSvoMetadata(SvoMetadata svoMetadata) {
        this.svoMetadata = svoMetadata;
    }
}

class SvoMetadata
{
     private String person;

    public void setPerson(String person) {
        this.person = person;
    }

    public SvoMetadata withPerson(String person) {
        this.person = person;
        return this;
    }

}
</code>```

i forward RootDoc to drl and i am trying get an instance of "svoMetadata" as below as wish to update person in drl RHS :

rule in drl is as below:

```<code>when
        $mastermap : EsRootDoc($svolist:svo)
    $svo : Svo($svoMetadata2 : svoMetadata) from $svolist
         // $svoMetadata: SvoMetadata($t: $svo.getSvoMetadata())  // this gives me error
then
       $svoMetadata.setPerson("taranTaran");  // how do i get SvoMetadata instance to perform setPerson method????
</code>```

how do i get SvoMetadata instance to perform setPerson method????

答:
For others ,who could be looking for drl syntax for above NPE issue.

```<code>    $mastermap : EsRootDoc($svolist:svo)
    $svo : Svo($svoMetadata2 : svoMetadata!=null,svoMetadata.person!=null) from $svolist
</code>```

checking svoMetadata!=null solved the problem.

Title: How to get nested class instance drools

Body:
I am newbie to drool usage and i have small query.
I have map as below for which i have created pojo using schemaJson2Pojo java api :

{
"svo": [
      {
        "clause": "Sunanda Pushkar died of poisoning",
        "svoMetadata": {
          "person": "sunanda pushkar",
          "subjectType": "person_coref"
        },
        "objectPOS": "IN VBG;",
        "isRelatedKeySVO": false,
        "subjectPOS": " NNP NNP",
        "subject": "Sunanda Pushkar",
        "confidence": 0.9266232318014763,
        "verb": "died",
        "verbPOS": "VBN",
        "source": "OpenIE",
        "isKeySVO": true,
        "object": "of poisoning;"
      }]
}

Note : svo.svoMetadata has person name

So, on using schemaJson2Pojo api , following classes are generated :

class RootDoc
{
 private List<Svo> svo = new ArrayList<Svo>();

 public List<Svo> getSvo() {
        return svo;
    }

    public void setSvo(List<Svo> svo) {
        this.svo = svo;
    }
}

class Svo
{
  private SvoMetadata svoMetadata;

public SvoMetadata getSvoMetadata() {
        return svoMetadata;
    }

    public void setSvoMetadata(SvoMetadata svoMetadata) {
        this.svoMetadata = svoMetadata;
    }
}

class SvoMetadata
{
     private String person;

    public void setPerson(String person) {
        this.person = person;
    }

    public SvoMetadata withPerson(String person) {
        this.person = person;
        return this;
    }

}

i forward RootDoc to drl and i am trying get an instance of "svoMetadata" as below as wish to update person in drl RHS :

rule in drl is as below:

when
        $mastermap : EsRootDoc($svolist:svo)
    $svo : Svo($svoMetadata2 : svoMetadata) from $svolist
         // $svoMetadata: SvoMetadata($t: $svo.getSvoMetadata())  // this gives me error
then
       $svoMetadata.setPerson("taranTaran");  // how do i get SvoMetadata instance to perform setPerson method????

how do i get SvoMetadata instance to perform setPerson method????

Body:
For others ,who could be looking for drl syntax for above NPE issue.

    $mastermap : EsRootDoc($svolist:svo)
    $svo : Svo($svoMetadata2 : svoMetadata!=null,svoMetadata.person!=null) from $svolist

checking svoMetadata!=null solved the problem.


来源: stackexchange

问:
Addressing instance name string in __init__(self) in Python
I am doing something like this:

```<code>class Class(object):
    def __init__(self):
        self.var=#new instance name string#
</code>```

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

```<code>c=Class()
</code>```

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

答:
Python doesn't have variables, it has objects and names. When you do

```<code>c = Class()
</code>```

you're doing two things:

Creating a new object of type Class

Binding the object to the name c in the current scope.

The object you created doesn't have any concept of a "variable name" -- If later you do

```<code>a = c
</code>```

then the same object is accessible in exactly the same way using the names a and c. You can delete the name a, and the object would still exist.

If the objects you create need to have a name, the best way is to pass it to them explicitly,

```<code>class Class(object):
    def __init__(self, name):
        self.name = name

var = Class('var')
</code>```

OwnerDisplayName: xktybot

ContentLicense: CC BY-SA 3.0

Body:
I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

LastEditorDisplayName: xktybot

Body:
Python doesn't have variables, it has objects and names. When you do

c = Class()

you're doing two things:

Creating a new object of type Class

Binding the object to the name c in the current scope.

The object you created doesn't have any concept of a "variable name" -- If later you do

a = c

then the same object is accessible in exactly the same way using the names a and c. You can delete the name a, and the object would still exist.

If the objects you create need to have a name, the best way is to pass it to them explicitly,

class Class(object):
    def __init__(self, name):
        self.name = name

var = Class('var')

OwnerDisplayName: dF

ContentLicense: CC BY-SA 2.5


问:
How to download and play the song(.mp3,.m4a) if we know the url in android
I need to download a .mp3 or .m4a file from the server by using an URL, and then play that song.

Any ideas?

答:
There are plenty of questions of how to download a file in android. Just search.

On the other hand, you can use android's MediaPlayer to play the file from the internet without downloading it.


问:
Programmatically bill PayPal for a recurring payment
How to programmatically (not manually with our PayPal dashboard) bill (every month) a PayPal subscriber of our service for a non-fixed-amount Automatic Billing?

答:
The Classic APIs aren't going away for a long time.  They have way too many solutions currently integrated with it, and the newer REST APIs do not currently support all the features that Classic does.  For example, reference transactions are not currently supported in the REST API, so you'll have to use Classic for what you want as of today anyway.  They have said they'll be adding reference transactions to REST sometime this year, but I've heard that about other things before and it generally takes longer than planned.

I am personally sticking with Classic for most of my applications as of today.


问:
Tensorflow always predict the same output
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

```<code>df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)
</code>```

out:

(20, 1)
(20, 1)

in:

```<code># Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')
</code>```

out:

```<code>Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]
</code>```

in:

```<code>sess.run(y, feed_dict={x: inputX })
</code>```

out:

```<code>array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)
</code>```

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.

答:
first of all I have to admit that I never used tensorflow. But I think you have a modelling problem here.

You are using the simplest network architecture possible (a 1-dimensional  perceptron). You have two variables (w and b) which you want to learn and your decision rule for the output looks like

if you subtract the b and divide by w you get

So you are basically looking for a threshold to seperate odd and even numbers. No matter how you choose w and b you will always misclassify half of the numbers.

Although decinding if a number is odd or even seems to be a super trivial task for us humans it is not for a single perceptron.

Body:
So, I'm trying to learn tensorflow and, for that, I try to create a classifier for something that, I think, is not so hard.
I'd like to predict if a number is odd or even.
The problem is that Tensorflow always predict the same output, I searched answers the last days but nothing helped me...
I saw the following answers : -Tensorflow predicts always the same result

-TensorFlow always converging to same output for all items after training

-TensorFlow always return same result

Here's my code:

in:

df
    nb  y1
0   1   0
1   2   1
2   3   0
3   4   1
4   5   0
...
19  20  1

inputX = df.loc[:, ['nb']].as_matrix()
inputY = df.loc[:, ['y1']].as_matrix()
print(inputX.shape)
print(inputY.shape)

out:

(20, 1)
(20, 1)

in:

# Parameters
learning_rate = 0.00000001
training_epochs = 2000
display_step = 50
n_samples = inputY.size

x = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([1, 1]))
b = tf.Variable(tf.zeros([1]))
y_values = tf.add(tf.matmul(x, W), b)
y = tf.nn.relu(y_values)
y_ = tf.placeholder(tf.float32, [None,1])

# Cost function: Mean squared error
cost = tf.reduce_sum(tf.pow(y_ - y, 2))/(2*n_samples)
# Gradient descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initialize variabls and tensorflow session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(training_epochs):
    sess.run(optimizer, feed_dict={x: inputX, y_: inputY}) # Take a gradient descent step using our inputs and labels

    # Display logs per epoch step
    if (i) % display_step == 0:
        cc = sess.run(cost, feed_dict={x: inputX, y_:inputY})
        print("Training step:", '%04d' % (i), "cost=", "{:.9f}".format(cc)) #, \"W=", sess.run(W), "b=", sess.run(b)

print ("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={x: inputX, y_: inputY})
print ("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

out:

Training step: 0000 cost= 0.250000000
Training step: 0050 cost= 0.250000000
Training step: 0100 cost= 0.250000000
...
Training step: 1800 cost= 0.250000000
Training step: 1850 cost= 0.250000000
Training step: 1900 cost= 0.250000000
Training step: 1950 cost= 0.250000000
Optimization Finished!
Training cost= 0.25 W= [[ 0.]] b= [ 0.]

in:

sess.run(y, feed_dict={x: inputX })

out:

array([[ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.],
       [ 0.]], dtype=float32)

I tried to play with my Hyper parameters like, the learning rate or the number of training epochs.
I changed the activation function from softmax to relu.
I changed my dataframe to have more examples but nothing happened.
I also tried to add random for my Weights, but nothing changed, the cost was just starting to a higher value.


问:
How to access session variable in asp.net mvc using a javascript variable as a key?
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

```<code>success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }
</code>```

Any help would be appreciated.

Thanks.

答:
From your query, it seems that you need server side values on your client.
Since Javascript is run by your browser you won't be able to access "Session" object of the server.

Hence try the following alternates:
1. Make an ajax call to your server and get your Session value in response.
2. During login store your values in sessionStorage service provided by the browser.

Thanks

Body:
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }

Any help would be appreciated.

Thanks.


问:
Azure - http request takes a long time
I have small ASP.NET application and everything was ok, but a day ago I noticed:  http request takes a long time (~13-15seconds).

I tried to add simple method to controller:

```<code>    [HttpGet]
    [Route("~/api/[controller]/test")]
    public string Test()
    {
        return "Hello. I'm ok.";
    }
</code>```

But request takes ~13 seconds.

What I tried and what info I have:

On local machines (2 different) everething is ok - I don't see any delays.

Application was deployed on AZURE one week ago, but delays started a day ago.

Restart doesn't help.

Redeploing on Azure doesn't help.

Redeploing on Azure as other service doesn't help.

Connecting to Azure's DB from locale machne is fast.

My AZURE's quota is OK.

List item

Response time and CPU:

Monitor:

答:
Websites effectively go to sleep if not hit so the startup time of the first request can be slow.

Try hitting your url, time it. Then hit it again.

If the second one is fast, its just because nothing is hitting your application and its going into sleep mode.

Title: Azure - http request takes a long time

Body:
I have small ASP.NET application and everything was ok, but a day ago I noticed:  http request takes a long time (~13-15seconds).

I tried to add simple method to controller:

    [HttpGet]
    [Route("~/api/[controller]/test")]
    public string Test()
    {
        return "Hello. I'm ok.";
    }

But request takes ~13 seconds.

What I tried and what info I have:

On local machines (2 different) everething is ok - I don't see any delays.

Application was deployed on AZURE one week ago, but delays started a day ago.

Restart doesn't help.

Redeploing on Azure doesn't help.

Redeploing on Azure as other service doesn't help.

Connecting to Azure's DB from locale machne is fast.

My AZURE's quota is OK.

List item

Response time and CPU:

Monitor:


问:
UDAF merge rows where are first orderdby in a Spark DataSet/Dataframe
Let's say we have a dataset/dataframe in Spark where has 3 columns
ID, Word, Timestamp

I want to write a UDAF function where I can do something like this

```<code>df.show()

ID | Word | Timestamp
1  | I    | "2017-1-1 00:01"
1  | am   | "2017-1-1 00:02"
1  | Chris | "2017-1-1 00:03"
2  | I    | "2017-1-1 00:01"
2  | am   | "2017-1-1 00:02"
2  | Jessica | "2017-1-1 00:03"

val df_merged = df.groupBy("ID")
  .sort("ID", "Timestamp")
  .agg(custom_agg("ID", "Word", "Timestamp")

df_merged.show

ID | Words         | StartTime        |      EndTime     |
1  | "I am Chris"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
1  | "I am Jessica"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
</code>```

The question is how can ensure that the column Words will be merged in the right order inside my UDAF?

Body:
Let's say we have a dataset/dataframe in Spark where has 3 columns
ID, Word, Timestamp

I want to write a UDAF function where I can do something like this

df.show()

ID | Word | Timestamp
1  | I    | "2017-1-1 00:01"
1  | am   | "2017-1-1 00:02"
1  | Chris | "2017-1-1 00:03"
2  | I    | "2017-1-1 00:01"
2  | am   | "2017-1-1 00:02"
2  | Jessica | "2017-1-1 00:03"

val df_merged = df.groupBy("ID")
  .sort("ID", "Timestamp")
  .agg(custom_agg("ID", "Word", "Timestamp")

df_merged.show

ID | Words         | StartTime        |      EndTime     |
1  | "I am Chris"  | "2017-1-1 00:01" | "2017-1-1 00:03" |
1  | "I am Jessica"  | "2017-1-1 00:01" | "2017-1-1 00:03" |

The question is how can ensure that the column Words will be merged in the right order inside my UDAF?

Body:
Sorry I dont use Scala and hope you could read it.

Window function can do what you want:

df = df.withColumn('Words', f.collect_list(df['Word']).over(
    Window().partitionBy(df['ID']).orderBy('Timestamp').rowsBetween(start=Window.unboundedPreceding,
                                                                    end=Window.unboundedFollowing)))

Output:

+---+-------+-----------------+----------------+
| ID|   Word|        Timestamp|           Words|
+---+-------+-----------------+----------------+
|  1|      I|2017-1-1 00:01:00|  [I, am, Chris]|
|  1|     am|2017-1-1 00:02:00|  [I, am, Chris]|
|  1|  Chris|2017-1-1 00:03:00|  [I, am, Chris]|
|  2|      I|2017-1-1 00:01:00|[I, am, Jessica]|
|  2|     am|2017-1-1 00:02:00|[I, am, Jessica]|
|  2|Jessica|2017-1-1 00:03:00|[I, am, Jessica]|
+---+-------+-----------------+----------------+

Then groupBy above data:

df = df.groupBy(df['ID'], df['Words']).agg(
    f.min(df['Timestamp']).alias('StartTime'), f.max(df['Timestamp']).alias('EndTime'))
df = df.withColumn('Words', f.concat_ws(' ', df['Words']))

Output:

+---+------------+-----------------+-----------------+
| ID|       Words|        StartTime|          EndTime|
+---+------------+-----------------+-----------------+
|  1|  I am Chris|2017-1-1 00:01:00|2017-1-1 00:03:00|
|  2|I am Jessica|2017-1-1 00:01:00|2017-1-1 00:03:00|
+---+------------+-----------------+-----------------+


问:
Issue executing python script in Docker
I'm starting with Docker. I have started with a Hello World script in Python 3. This is my Dockerfile:

```<code>FROM ubuntu:latest

RUN apt-get update
RUN apt-get install python3

COPY . hello.py

CMD python3 hello.py
</code>```

In the same directory, I have this python script:

```<code>if __name__ == "__main__":
    print("Hello World!");
</code>```

I have built the image with this command:

```<code>docker build -t home/ubuntu-python-hello .
</code>```

So far, so good. But when I try to run the script with this command:

```<code>docker run home/ubuntu-python-hello
</code>```

I get this error:

```<code>/usr/bin/python3: can't find '__main__' module in 'hello.py'
</code>```

What am I doing wrong? Any advice or suggestion is accepted, I'm just a newbie.

Thanks.

答:
Thanks to Gerrat, I solved it this way:

```<code>COPY hello.py hello.py
</code>```

instead of

```<code>COPY . hello.py
</code>```

Title: Issue executing python script in Docker

Body:
I'm starting with Docker. I have started with a Hello World script in Python 3. This is my Dockerfile:

FROM ubuntu:latest

RUN apt-get update
RUN apt-get install python3

COPY . hello.py

CMD python3 hello.py

In the same directory, I have this python script:

if __name__ == "__main__":
    print("Hello World!");

I have built the image with this command:

docker build -t home/ubuntu-python-hello .

So far, so good. But when I try to run the script with this command:

docker run home/ubuntu-python-hello

I get this error:

/usr/bin/python3: can't find '__main__' module in 'hello.py'

What am I doing wrong? Any advice or suggestion is accepted, I'm just a newbie.

Thanks.

Body:
Thanks to Gerrat, I solved it this way:

COPY hello.py hello.py

instead of

COPY . hello.py


问:
Unable to import in CoreNFC in swift project Xcode 9 beta
I am unable to import CoreNFC in a swift project. Getting this error No such module CoreNFC.

I also added the framework to Linked Frameworks and Libraries.

答:
According to a post on the Apple Developer forums, you can only build for a real device or the Generic iOS device as there is no x86 version of CoreNFC.

Once you switch to one of these, you do not need to add CoreNFC to Linked Frameworks and Libraries, just @import it:

```<code>@import CoreNFC;
</code>```

Body:
According to a post on the Apple Developer forums, you can only build for a real device or the Generic iOS device as there is no x86 version of CoreNFC.

Once you switch to one of these, you do not need to add CoreNFC to Linked Frameworks and Libraries, just @import it:

@import CoreNFC;


问:
Use of def, val, and var in scala
```<code>class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)
</code>```

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

```<code>def age = 30
age = 45
</code>```

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

答:
As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:

```<code>val person = new Person("Kumar",12)
</code>```

Another possibility would be:

```<code>def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)
</code>```

However, person.age=20 in your code is allowed, as you get back a Person instance from the person method, and on this instance you are allowed to change the value of a var. The problem is, that after that line you have no more reference to that instance (as every call to person will produce a new instance).

This is nothing special, you would have exactly the same behavior in Java:

```<code>class Person{
   public int age;
   private String name;
   public Person(String name; int age) {
      this.name = name;
      this.age = age;
   }
   public String name(){ return name; }
}

public Person person() {
  return new Person("Kumar", 12);
}

person().age = 20;
System.out.println(person().age); //--> 12
</code>```

Title: Use of def, val, and var in scala

Body:
class Person(val name:String,var age:Int )
def person = new Person("Kumar",12)
person.age = 20
println(person.age)

These lines of code outputs 12, even though person.age=20 was successfully executed. I found that this happens because I used def in def person = new Person("Kumar",12). If I use var or val the output is 20. I understand the default is val in scala. This:

def age = 30
age = 45

...gives a compilation error because it is a val by default. Why do the first set of lines above not work properly, and yet also don't error?

Body:
As Kintaro already says, person is a method (because of def) and always returns a new Person instance. As you found out it would work if you change the method to a var or val:

val person = new Person("Kumar",12)

Another possibility would be:

def person = new Person("Kumar",12)
val p = person
p.age=20
println(p.age)

However, person.age=20 in your code is allowed, as you get back a Person instance from the person method, and on this instance you are allowed to change the value of a var. The problem is, that after that line you have no more reference to that instance (as every call to person will produce a new instance).

This is nothing special, you would have exactly the same behavior in Java:

class Person{
   public int age;
   private String name;
   public Person(String name; int age) {
      this.name = name;
      this.age = age;
   }
   public String name(){ return name; }
}

public Person person() {
  return new Person("Kumar", 12);
}

person().age = 20;
System.out.println(person().age); //--> 12


问:
How to replace black background with white on image resizing using Thumbnailator?
I use Thumbnailator to convert images from png to jpg and then resize them:

```<code>Thumbnails.of(new File("C:/279.png"))
                .outputFormat("JPG")
                .size(100, 100)
                .outputQuality(1.0)
                .toFile(new File("C:/279.jpg"));
</code>```

Original image has transparent background, but output image has black background. How to set white background on output image?

Thank you.

答:
Solution:

Use .addFilter(new Canvas(100, 100, Positions.CENTER, Color.WHITE))

Example:

```<code>Thumbnails.of(new File("C:/279.png"))
            .outputFormat("JPG")
            .size(100, 100)
            .addFilter(new Canvas(100, 100, Positions.CENTER, Color.WHITE))
            .outputQuality(1.0)
            .toFile(new File("C:/279.jpg"));
</code>```

Body:
I use Thumbnailator to convert images from png to jpg and then resize them:

Thumbnails.of(new File("C:/279.png"))
                .outputFormat("JPG")
                .size(100, 100)
                .outputQuality(1.0)
                .toFile(new File("C:/279.jpg"));

Original image has transparent background, but output image has black background. How to set white background on output image?

Thank you.

Body:
Solution:

Use .addFilter(new Canvas(100, 100, Positions.CENTER, Color.WHITE))

Example:

Thumbnails.of(new File("C:/279.png"))
            .outputFormat("JPG")
            .size(100, 100)
            .addFilter(new Canvas(100, 100, Positions.CENTER, Color.WHITE))
            .outputQuality(1.0)
            .toFile(new File("C:/279.jpg"));

ContentLicense: CC BY-SA 4.0


问:
Assign sorted dictionary to the new dictionary
I would like to sort dictionary and save it into the same one, but there is type conflict :

Cannot assign value of type [(Int) : (Double)] to the type [Int : Double].

```<code>dictionary = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })
</code>```

I know that after sorting it wont be any more a dictionary.

```<code>let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })
</code>```

I've made a simple for loop to loop thought sortet "dictionary" to assign values once more to the dictionary but it does not copy them as a sorted ;/

```<code>var test = [Int : Double]()

                    for (key, value) in sorted {
                        test[key] = value
                    }
</code>```

How could I assign the sorted dictionary back to the dictionary in the orded I've sorted it ?

EDID

For each annotation I have to get a deistance from dropped pin. I've made a dictionary which a key is annotation ID and value is a distance between annotation and dropped point. I need a dictionary to recognize in view for cell - table view data source; which annotation match which distance. So I have a dictionary with [Int : Double] and in table view data source :

```<code>let annotation = mapAnnotations[indexPath.row]
var distance = dictionary[annotation.ID]
</code>```

Reasuming, shell I sort mapAnnotations which is an array of Object via values inside dictionary with distances which are makred by annotationId ?

It would be sorting array of object.ID by keys from sorted

Thanks in advance!

答:
I've solved my problem.

First :

Had to sort values in dictionary by using :

```<code> let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })
</code>```

Then after that I've created an array which is going to have sorted annotations via sorted keys.

```<code>                    for (key, _) in sorted {
                        for ann in mapAnnotations {
                            if ann.ID == key {
                                sortedArray.append(ann)
                            }
                        }
                    }
</code>```

Body:
I would like to sort dictionary and save it into the same one, but there is type conflict :

Cannot assign value of type [(Int) : (Double)] to the type [Int : Double].

dictionary = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })

I know that after sorting it wont be any more a dictionary.

let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })

I've made a simple for loop to loop thought sortet "dictionary" to assign values once more to the dictionary but it does not copy them as a sorted ;/

var test = [Int : Double]()

                    for (key, value) in sorted {
                        test[key] = value
                    }

How could I assign the sorted dictionary back to the dictionary in the orded I've sorted it ?

EDID

For each annotation I have to get a deistance from dropped pin. I've made a dictionary which a key is annotation ID and value is a distance between annotation and dropped point. I need a dictionary to recognize in view for cell - table view data source; which annotation match which distance. So I have a dictionary with [Int : Double] and in table view data source :

let annotation = mapAnnotations[indexPath.row]
var distance = dictionary[annotation.ID]

Reasuming, shell I sort mapAnnotations which is an array of Object via values inside dictionary with distances which are makred by annotationId ?

It would be sorting array of object.ID by keys from sorted

Thanks in advance!

Body:
I've solved my problem.

First :

Had to sort values in dictionary by using :

 let sorted = dictionary.sorted(by: { (elem1: (key: Int, value: Double), elem2: (key: Int, value: Double)) -> Bool in
                        if elem1.value < elem2.value {
                            return true
                        } else {
                            return false
                        }
                    })

Then after that I've created an array which is going to have sorted annotations via sorted keys.

                    for (key, _) in sorted {
                        for ann in mapAnnotations {
                            if ann.ID == key {
                                sortedArray.append(ann)
                            }
                        }
                    }


问:
Capturing array of vectors in lambda makes elements const
```<code>#include <vector>

void main() {
  std::vector<int> test[2];
  auto funct = [test](){ test[0].push_back(1); };
  funct();
}
</code>```

As a result I get

main.cc:5:45: error: passing ‘const std::vector’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]’ discards qualifiers [-fpermissive]
     auto funct = test{ test[0].push_back(1); };

How can I capture test pointer without making its values const? Is there any other way other than making it a vector<vector<int>>? Why is it even becoming a const?

答:
```<code>#include <vector>

int main() {
  std::vector<int> test[2];
  auto funct = [test]() mutable { test[0].push_back(1); };
  funct();
}
</code>```

Body:
#include <vector>

void main() {
  std::vector<int> test[2];
  auto funct = [test](){ test[0].push_back(1); };
  funct();
}

As a result I get

main.cc:5:45: error: passing ‘const std::vector’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]’ discards qualifiers [-fpermissive]
     auto funct = test{ test[0].push_back(1); };

How can I capture test pointer without making its values const? Is there any other way other than making it a vector<vector<int>>? Why is it even becoming a const?


问:
Nuxt Js asyncData returning value acting strange.
I am working on a nuxt js/vue js project. In it I have to call multiple REST API. In the page component I am calling the asyncData() nuxt js API to call the REST api.

```<code>import { getCategories } from '~/api'
import { getProducts } from '~/api'

export default {

data() {
  return {

  }
},`

asyncData ({ req, params }) {
 //-----------------PART 1-----------------------------
    // var res1 = getCategories()
    // var res2 = getProducts()

    // return {
    //   res1,
    //   res2
    // }
//-----------------PART 2-----------------------------
    // return getCategories()
    // return getProducts()

//----------------------------------------------
      },

created() {

    if(typeof(Storage) !== "undefined"){

      if(!localStorage.getItem("cityName")){
        this.$router.push('/')
      }

    } else{
      console.log('This browser does not support local storage')
    }

    this.$store.dispatch('initFilters')

    this.$store.dispatch('initCategories', this.categories)

   //NOTICE HERE
   // console.log(this.allProducts) //This one works on single return
   // console.log(this.res1.allProducts) //This doesnot work on object return

  },

}
</code>```

When I try to return getCategories() or return getProducts() (PART 2 in the code)it works and return my desired object result.

But as I need both object, I tried to put them in an object and return them (PART 1) then calling by console.log(this.res1.allProducts) I am not getting the desired object.

Here is the API code

```<code>import axios from 'axios'
const API_ROOT = 'http://deligram.mg/rest/'
const API_VERSION = 'V1'
const MAGENTO_STORE = 'default'
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/'

const apiUrl = (path) => {
  return API_BASE + path
}

const apiGet = (path) => {
  return axios.get(apiUrl(path))
}

export function getCategories () {
  return apiGet('categories')
  .then((res) => {
    return { categories: res.data }
  })
}

export function getProducts () {
  return apiGet('products?searchCriteria%5BcurrentPage%5D=10')
  .then((res) => {
    return { allProducts: res.data }
  })
}
</code>```

Can anyone tell me what am I doing wrong? Or can anyone propose an alternative approach to get both object in the single return?

答:
I assume your API methods return a Promise. You should use Promise.all to wait until both promises are resolved, then return one object containing all the data that nuxt should set:

```<code>var res1 = getCategories()
var res2 = getProducts()
return Promise.all(re1, res2).then(function ([data1, data2]) {
 return Object.assign({}, data1, data2)
})
</code>```

the resulting object will look like this:

```<code>{
  categories: [ /* data from getCategories() */]
  allProducts: [ /* data from getProducts () */ ]
}
</code>```

Body:
I am working on a nuxt js/vue js project. In it I have to call multiple REST API. In the page component I am calling the asyncData() nuxt js API to call the REST api.

import { getCategories } from '~/api'
import { getProducts } from '~/api'

export default {

data() {
  return {

  }
},`

asyncData ({ req, params }) {
 //-----------------PART 1-----------------------------
    // var res1 = getCategories()
    // var res2 = getProducts()

    // return {
    //   res1,
    //   res2
    // }
//-----------------PART 2-----------------------------
    // return getCategories()
    // return getProducts()

//----------------------------------------------
      },

created() {

    if(typeof(Storage) !== "undefined"){

      if(!localStorage.getItem("cityName")){
        this.$router.push('/')
      }

    } else{
      console.log('This browser does not support local storage')
    }

    this.$store.dispatch('initFilters')

    this.$store.dispatch('initCategories', this.categories)

   //NOTICE HERE
   // console.log(this.allProducts) //This one works on single return
   // console.log(this.res1.allProducts) //This doesnot work on object return

  },

}

When I try to return getCategories() or return getProducts() (PART 2 in the code)it works and return my desired object result.

But as I need both object, I tried to put them in an object and return them (PART 1) then calling by console.log(this.res1.allProducts) I am not getting the desired object.

Here is the API code

import axios from 'axios'
const API_ROOT = 'http://deligram.mg/rest/'
const API_VERSION = 'V1'
const MAGENTO_STORE = 'default'
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/'

const apiUrl = (path) => {
  return API_BASE + path
}

const apiGet = (path) => {
  return axios.get(apiUrl(path))
}

export function getCategories () {
  return apiGet('categories')
  .then((res) => {
    return { categories: res.data }
  })
}

export function getProducts () {
  return apiGet('products?searchCriteria%5BcurrentPage%5D=10')
  .then((res) => {
    return { allProducts: res.data }
  })
}

Can anyone tell me what am I doing wrong? Or can anyone propose an alternative approach to get both object in the single return?

Body:
I assume your API methods return a Promise. You should use Promise.all to wait until both promises are resolved, then return one object containing all the data that nuxt should set:

var res1 = getCategories()
var res2 = getProducts()
return Promise.all(re1, res2).then(function ([data1, data2]) {
 return Object.assign({}, data1, data2)
})

the resulting object will look like this:

{
  categories: [ /* data from getCategories() */]
  allProducts: [ /* data from getProducts () */ ]
}


问:
How do I get the object if it exists, or None if it does not exist in Django?
When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.

```<code>go = Content.objects.get(name="baby")
</code>```

Instead of DoesNotExist, how can I have go be None instead?

答:
I think it isn't bad idea to use get_object_or_404()

```<code>from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)
</code>```

This example is equivalent to:

```<code>from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")
</code>```

You can read more about get_object_or_404() in django online documentation.

Body:
When I ask the model manager to get an object, it raises DoesNotExist when there is no matching object.

go = Content.objects.get(name="baby")

Instead of DoesNotExist, how can I have go be None instead?

Body:
I think it isn't bad idea to use get_object_or_404()

from django.shortcuts import get_object_or_404

def my_view(request):
    my_object = get_object_or_404(MyModel, pk=1)

This example is equivalent to:

from django.http import Http404

def my_view(request):
    try:
        my_object = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")

You can read more about get_object_or_404() in django online documentation.


问:
How to show only date from DataGridView to label
I am working on C# and sql server. I saved date using DateTimePicker to sql. Now I am using DataGridView to show record then by selecting a row that data is shown on labels. Problem is I want to show only date but through the following method time is also coming along.

```<code> private void datagridpatient_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        lblgridpbirthday.Text = row.Cells["Birthday"].Value.ToString();
    }
</code>```

How to show only date?

答:
Try this:</p>

```<code> var birthday =  Convert.ToDateTime(row.Cells["Birthday"].Value);
 lblgridpbirthday.Text = birthday.Date.ToString();
</code>```

Body:
I am working on C# and sql server. I saved date using DateTimePicker to sql. Now I am using DataGridView to show record then by selecting a row that data is shown on labels. Problem is I want to show only date but through the following method time is also coming along.

 private void datagridpatient_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        lblgridpbirthday.Text = row.Cells["Birthday"].Value.ToString();
    }

How to show only date?

Body:
Try this:

 var birthday =  Convert.ToDateTime(row.Cells["Birthday"].Value);
 lblgridpbirthday.Text = birthday.Date.ToString();


问:
Matplotlib: Times New Roman appears bold
For some reason when using Times New Roman in my mpl plots it appears bold. Other fonts are OK.

Here is a minimal example, and the result (inside a Word document, for comparison with what I expect Times New Roman to look like).

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt

with plt.style.context('word'):
  fig = plt.figure(1, figsize=(3.4, 2.1))
  ax1 = plt.subplot(111)
  ax1.plot([1,2,3,4,5], '+--')
  ax1.text(0.5, 3.5, r"Brown $\alpha + 12 \sum_ix$")
  ax1.text(0.5, 3, r"1.0 2.0")
  ax1.set_xlabel('normal 1.0 and math $1.0$')
  ax1.set_ylabel('Times New Roman')
  plt.tight_layout()
  fig.savefig('word.pdf')
</code>```

with the word stylesheet containing

```<code>backend: PS
text.usetex: False
font.family: serif
font.serif: Times New Roman
font.size: 11
axes.titlesize: 11
axes.labelsize: 11
</code>```

The plot is included in the document with its actual size (3.4'' by 2.1'').

The font is correctly found and it is also working in math-mode (see the alpha in the plot). It just seems that this is bold...

答:
I know the question is very old, but it still is a problem, at least for me on my mac. I found a very easy solution to this problem, posted by azag0 on github

```<code>del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()
</code>```

https://github.com/matplotlib/matplotlib/issues/5574

Body:
For some reason when using Times New Roman in my mpl plots it appears bold. Other fonts are OK.

Here is a minimal example, and the result (inside a Word document, for comparison with what I expect Times New Roman to look like).

import matplotlib as mpl
import matplotlib.pyplot as plt

with plt.style.context('word'):
  fig = plt.figure(1, figsize=(3.4, 2.1))
  ax1 = plt.subplot(111)
  ax1.plot([1,2,3,4,5], '+--')
  ax1.text(0.5, 3.5, r"Brown $\alpha + 12 \sum_ix$")
  ax1.text(0.5, 3, r"1.0 2.0")
  ax1.set_xlabel('normal 1.0 and math $1.0$')
  ax1.set_ylabel('Times New Roman')
  plt.tight_layout()
  fig.savefig('word.pdf')

with the word stylesheet containing

backend: PS
text.usetex: False
font.family: serif
font.serif: Times New Roman
font.size: 11
axes.titlesize: 11
axes.labelsize: 11

The plot is included in the document with its actual size (3.4'' by 2.1'').

The font is correctly found and it is also working in math-mode (see the alpha in the plot). It just seems that this is bold...

Body:
I know the question is very old, but it still is a problem, at least for me on my mac. I found a very easy solution to this problem, posted by azag0 on github

del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()

https://github.com/matplotlib/matplotlib/issues/5574


问:
HTML Responsiveness
This is the structure of my HTML and CSS:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
    <!-- LEFT SIDE -->
    <div id="video-container" class="col-xs-8 col-sm-8">
        <div class="row">
            <div id="video" class="col-xs-12 col-sm-12">
                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>
            </div>
        </div>
        <div class="row">
            <div id="banner" class="col-xs-12 col-sm-12 text-center">SAMPLE BANNER</div>
        </div>
        <div class="row">
            <div id="ctrl1" class="col-xs-6 col-sm-6"></div>
            <div id="ctrl2" class="col-xs-6 col-sm-6"></div>
        </div>
    </div>

    <!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-4 col-sm-4">
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 1
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 2
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 3
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 4
            </div>
        </div>
    </div>
</div></code>```

Now my problem is, How would i position the DIV updates-container (the one with the red background) to the bottom when the browser screen is small ..

答:
change

```<code><!-- LEFT SIDE -->
<div id="video-container" class="col-xs-8 col-sm-8">
</code>```

to

```<code><!-- LEFT SIDE -->
<div id="video-container" class="col-xs-12 col-sm-8">
</code>```

and :

```<code><!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-4 col-sm-4">
</code>```

to

```<code><!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-12 col-sm-4">
</code>```

Also,

```<code>html, body {
    margin: 0;
    height: 100%;
    overflow: hidden
}
</code>```

overflow: hidden might be a problem on smaller screens, you can use media queries to fix this

Title: HTML Responsiveness

Body:
This is the structure of my HTML and CSS:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>

SAMPLE BANNER

                SAMPLE UPDATE 1

                SAMPLE UPDATE 2

                SAMPLE UPDATE 3

                SAMPLE UPDATE 4

Now my problem is, How would i position the DIV updates-container (the one with the red background) to the bottom when the browser screen is small ..

Body:
change

<!-- LEFT SIDE -->
<div id="video-container" class="col-xs-8 col-sm-8">

to

<!-- LEFT SIDE -->
<div id="video-container" class="col-xs-12 col-sm-8">

and :

<!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-4 col-sm-4">

to

<!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-12 col-sm-4">

Also,

html, body {
    margin: 0;
    height: 100%;
    overflow: hidden
}

overflow: hidden might be a problem on smaller screens, you can use media queries to fix this


问:
MVC 6 View Components vs. Partial Views: What is the difference? When should each be used?
MVC 6 Introduced View components and said it is much stronger and flexible than partial views. Are view components meant to replace partial views? What is the difference and what kinds of situations call for each implementation?</p>

答: ViewComponents are also used when you need a partial view, that requires a model to be called in _Layout. To avoid writing C# code to create the model in the Layout, it's best to use a ViewComponent that can make use of the Services configured for the application, same as controllers, through dependency injection.


问:
Random number for dice (help)
```<code>import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18
</code>```

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value

答:
++a[1+dice.nextInt(6)]

dice.nextInt(6)= return an integer between 0 and 5

then you add 1 to that value, after that you get the element at that index in the array a  and you increase that using the ++ operation

Title: Random number for dice (help)

Body:
import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value


问:
UnitTests - Moq - How to Return() object from Moq that matches Parameter in Setup()
I am confused in Moq and I'm not sure what is wrong here.

I would like to test LeadService that depend on ILeadStorageService, and I want to configure Moq in that way - Return the object that matches the GUID passed in Setup.

The problem is in the Moq Setup/Returns line, because when I substitute dependent object to its real instantiation - Test passes, but it is totally wrong. I don't want to test just LeadService, not a dependent storage.

```<code>    public LeadService( IConfigurationDbContext configurationDbContext,
                        ILeadStorageService leadStorageService,
                        ILeadDeliveryService deliveryService)
    {
        this.configurationDbContext = configurationDbContext;
        this.leadStorageService = leadStorageService;
        this.deliveryService = deliveryService;

    }
</code>```

Tested method

```<code>        public TestLeadResponse ProcessTestLead(TestLeadRequest request)
        {
        var response = new TestLeadResponse()
        {
            Status = TestLeadStatus.Ok
        };

        try
        {
            var lead = leadStorageService.Get(request.LeadId);
            if (lead == null)
            {
                throw new LeadNotFoundException(request.LeadId);
            }

            var buyerContract =
                configurationDbContext.BuyerContracts.SingleOrDefault(bc => bc.Id == request.BuyerContractId);
            if (buyerContract == null)
            {
                throw new BuyerContractNotFoundException(request.BuyerContractId);
            }

            response.DeliveryEntry = deliveryService.DeliverLead(lead, buyerContract);
        }
        catch (LeadNotFoundException e)
        {
            response.Status = TestLeadStatus.LeadNotFound;
            response.StatusDescription = e.Message;
        }
        catch (BuyerContractNotFoundException e)
        {
            response.Status = TestLeadStatus.BuyerContractNotFound;
            response.StatusDescription = e.Message;
        }

        return response;
    }
</code>```

then in test preparation:

```<code>    [TestInitialize]
    public void Initialize()
    {
        _leadIdStr = "2c3ac0c0-f0c2-4eb0-a55e-600ae3ada221";

        _dbcontext = new ConfigurationDbContext();
        _lead = PrepareLeadObject();
        _buyerContract = PrepareBuyerContractObject(Id : 1, BuyerContractId :  1, BuyerTag: "GAME");
        _leadDeliveryMock = new Mock<ILeadDeliveryService>();
        _leadStorageMock = new Mock<ILeadStorageService>();
        _leadStorageService = new LeadStorageService("LeadGeneration_Dev");

    }

    private Lead PrepareLeadObject()
    {
        var lead = new Lead() {CountryId = 1, Country = "NL", Id = Guid.Parse(_leadIdStr)};
        return lead;

    }
</code>```

and the test itself:

```<code>    [TestMethod]
    public void LeadServiceTest_ProcessTestLeadWithWrongBuyerContractIDThrowsBuyerContractNotFoundException()
    {
        _leadDeliveryMock
            .Setup(methodCall => methodCall.DeliverLead(_lead, _buyerContract))
            .Returns<LeadDeliveryEntry>((r) => PrepareLeadDeliveryEntry());

        // here is the problem!!!!
        _leadStorageMock.Setup(mc => mc.Get(_leadId)).Returns((Lead l) => PrepareLeadObject());

        //if i change to real object - test passes
        //_service = new LeadService(_dbcontext, _leadStorageService, _leadDeliveryMock.Object);
        _service = new LeadService(_dbcontext, _leadStorageMock.Object, _leadDeliveryMock.Object);

        var response = _service.ProcessTestLead(new TestLeadRequest() { BuyerContractId = int.MaxValue, LeadId = _leadId });

        Assert.IsNotNull(response);
        Assert.AreEqual(response.Status, TestLeadStatus.BuyerContractNotFound);

    }
</code>```

Instead of expected Return - I got an exception:

What I am missing in _leadStorageMock.Setup().Returns() ?

答:
The Returns extension method accepts a delegate with same parameters as the method which you are mocking. And those arguments will be passed to delegate during invocation of mocked method. So instead of Lead object, you will get the argument which is passed to mc.Get method - the lead id:

```<code>_leadStorageMock.Setup(mc => mc.Get(_leadId))
      .Returns((Guid leadId) => PrepareLeadObject());
</code>```

Check QuickStart section related to accessing invocation arguments when returning a value.

Note that there is a bunch of Returns extension methods which accept a value function as an argument:

```<code>Returns<T>(Func<T, TResult> valueFunction);
Returns<T1, T2>(Func<T1, T2, TResult> valueFunction);
Returns<T1, T2, T3>(Func<T1, T2, T3, TResult> valueFunction);
// etc
</code>```

As you can see those value functions calculate the value to return from mocked method, but they all receive a different number of arguments (up to 16). Those arguments will exactly match arguments of the method you are mocking and they will be passed to the valueFunction during invocation of the mocked method. So if you are mocking some function with two arguments, then corresponding extension should be used:

```<code>mock.Setup(m => m.Activate(It.IsAny<int>(), It.IsAny<bool>())
    .Returns((int i, bool b) => b ? i : 0); // Func<T1, T2, TResult>
</code>```

Body:
I am confused in Moq and I'm not sure what is wrong here.

I would like to test LeadService that depend on ILeadStorageService, and I want to configure Moq in that way - Return the object that matches the GUID passed in Setup.

The problem is in the Moq Setup/Returns line, because when I substitute dependent object to its real instantiation - Test passes, but it is totally wrong. I don't want to test just LeadService, not a dependent storage.

    public LeadService( IConfigurationDbContext configurationDbContext,
                        ILeadStorageService leadStorageService,
                        ILeadDeliveryService deliveryService)
    {
        this.configurationDbContext = configurationDbContext;
        this.leadStorageService = leadStorageService;
        this.deliveryService = deliveryService;

    }

Tested method

        public TestLeadResponse ProcessTestLead(TestLeadRequest request)
        {
        var response = new TestLeadResponse()
        {
            Status = TestLeadStatus.Ok
        };

        try
        {
            var lead = leadStorageService.Get(request.LeadId);
            if (lead == null)
            {
                throw new LeadNotFoundException(request.LeadId);
            }

            var buyerContract =
                configurationDbContext.BuyerContracts.SingleOrDefault(bc => bc.Id == request.BuyerContractId);
            if (buyerContract == null)
            {
                throw new BuyerContractNotFoundException(request.BuyerContractId);
            }

            response.DeliveryEntry = deliveryService.DeliverLead(lead, buyerContract);
        }
        catch (LeadNotFoundException e)
        {
            response.Status = TestLeadStatus.LeadNotFound;
            response.StatusDescription = e.Message;
        }
        catch (BuyerContractNotFoundException e)
        {
            response.Status = TestLeadStatus.BuyerContractNotFound;
            response.StatusDescription = e.Message;
        }

        return response;
    }

then in test preparation:

    [TestInitialize]
    public void Initialize()
    {
        _leadIdStr = "2c3ac0c0-f0c2-4eb0-a55e-600ae3ada221";

        _dbcontext = new ConfigurationDbContext();
        _lead = PrepareLeadObject();
        _buyerContract = PrepareBuyerContractObject(Id : 1, BuyerContractId :  1, BuyerTag: "GAME");
        _leadDeliveryMock = new Mock<ILeadDeliveryService>();
        _leadStorageMock = new Mock<ILeadStorageService>();
        _leadStorageService = new LeadStorageService("LeadGeneration_Dev");

    }

    private Lead PrepareLeadObject()
    {
        var lead = new Lead() {CountryId = 1, Country = "NL", Id = Guid.Parse(_leadIdStr)};
        return lead;

    }

and the test itself:

    [TestMethod]
    public void LeadServiceTest_ProcessTestLeadWithWrongBuyerContractIDThrowsBuyerContractNotFoundException()
    {
        _leadDeliveryMock
            .Setup(methodCall => methodCall.DeliverLead(_lead, _buyerContract))
            .Returns<LeadDeliveryEntry>((r) => PrepareLeadDeliveryEntry());

        // here is the problem!!!!
        _leadStorageMock.Setup(mc => mc.Get(_leadId)).Returns((Lead l) => PrepareLeadObject());

        //if i change to real object - test passes
        //_service = new LeadService(_dbcontext, _leadStorageService, _leadDeliveryMock.Object);
        _service = new LeadService(_dbcontext, _leadStorageMock.Object, _leadDeliveryMock.Object);

        var response = _service.ProcessTestLead(new TestLeadRequest() { BuyerContractId = int.MaxValue, LeadId = _leadId });

        Assert.IsNotNull(response);
        Assert.AreEqual(response.Status, TestLeadStatus.BuyerContractNotFound);

    }

Instead of expected Return - I got an exception:

What I am missing in _leadStorageMock.Setup().Returns() ?

Body:
The Returns extension method accepts a delegate with same parameters as the method which you are mocking. And those arguments will be passed to delegate during invocation of mocked method. So instead of Lead object, you will get the argument which is passed to mc.Get method - the lead id:

_leadStorageMock.Setup(mc => mc.Get(_leadId))
      .Returns((Guid leadId) => PrepareLeadObject());

Check QuickStart section related to accessing invocation arguments when returning a value.

Note that there is a bunch of Returns extension methods which accept a value function as an argument:

Returns<T>(Func<T, TResult> valueFunction);
Returns<T1, T2>(Func<T1, T2, TResult> valueFunction);
Returns<T1, T2, T3>(Func<T1, T2, T3, TResult> valueFunction);
// etc

As you can see those value functions calculate the value to return from mocked method, but they all receive a different number of arguments (up to 16). Those arguments will exactly match arguments of the method you are mocking and they will be passed to the valueFunction during invocation of the mocked method. So if you are mocking some function with two arguments, then corresponding extension should be used:

mock.Setup(m => m.Activate(It.IsAny<int>(), It.IsAny<bool>())
    .Returns((int i, bool b) => b ? i : 0); // Func<T1, T2, TResult>


问:
Google fonts loading optimisation and caching
Google's page speed test shows only one problem:

Eliminate render-blocking JavaScript and CSS in above-the-fold content
  Your page has 1 blocking CSS resources. This causes a delay in rendering your page.

  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

  Optimize CSS Delivery of the following:

  https://fonts.googleapis.com/css?family=Roboto:300,400

The fonts being loaded as fonts.google.com recommends:

```<code><link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">
</code>```

Within  tag.

As far as i know, there is no way to control google's fonts caching and also, this url's output depends on user agent, so it doesn't make sense to distribute the fonts locally. So, the question is: what do i suppose to do with that? How do i satisfy google's speed test?

答:
data:font with fallback needed, load on footer. That will give result like mine :

This is example CSS for fallback, else may fail on some device :

```<code>@font-face {
 font-family: 'Arial'; /* Do Proper Naming */
 src: url('Arial.eot'); /* For IE 5-8 */
 src: local('?'), /* It is called smile hack to promote CSS to UTF-16 */
 url(data:font/truetype;charset=utf-8;base64,) format('truetype'), /*base64 encoded font IE9, Safari 3.1+ FF 3.5+ Chrome 4.0+*/
 url('Arial.svg#123XYZ') format('svg'); /* iPad, iPhone with OS less than or equal to 4.1 */
 font-weight: normal;
 font-style: normal;
}
</code>```

I wrote that -- https://thecustomizewindows.com/2013/10/base64-encoding-and-font-css/ That CSS is from an expert developer whom I paid, font developer. Read my guide, test that website's source code, use in the same way.

Body:
Google's page speed test shows only one problem:

Eliminate render-blocking JavaScript and CSS in above-the-fold content
  Your page has 1 blocking CSS resources. This causes a delay in rendering your page.

  None of the above-the-fold content on your page could be rendered without waiting for the following resources to load. Try to defer or asynchronously load blocking resources, or inline the critical portions of those resources directly in the HTML.

  Optimize CSS Delivery of the following:

  https://fonts.googleapis.com/css?family=Roboto:300,400

The fonts being loaded as fonts.google.com recommends:

<link href="https://fonts.googleapis.com/css?family=Roboto:300,400" rel="stylesheet">

Within  tag.

As far as i know, there is no way to control google's fonts caching and also, this url's output depends on user agent, so it doesn't make sense to distribute the fonts locally. So, the question is: what do i suppose to do with that? How do i satisfy google's speed test?

Body:
data:font with fallback needed, load on footer. That will give result like mine :

This is example CSS for fallback, else may fail on some device :

@font-face {
 font-family: 'Arial'; /* Do Proper Naming */
 src: url('Arial.eot'); /* For IE 5-8 */
 src: local('?'), /* It is called smile hack to promote CSS to UTF-16 */
 url(data:font/truetype;charset=utf-8;base64,) format('truetype'), /*base64 encoded font IE9, Safari 3.1+ FF 3.5+ Chrome 4.0+*/
 url('Arial.svg#123XYZ') format('svg'); /* iPad, iPhone with OS less than or equal to 4.1 */
 font-weight: normal;
 font-style: normal;
}

I wrote that -- https://thecustomizewindows.com/2013/10/base64-encoding-and-font-css/ That CSS is from an expert developer whom I paid, font developer. Read my guide, test that website's source code, use in the same way.


问:
Represent Flowchart-specified Algorithms in Haskell
I'm confronted with the task of implementing algorithms (mostly business logic style) expressed as flowcharts. I'm aware that flowcharts are not the best algorithm representation due to its spaghetti-code property (would this be a use-case for CPS?), but I'm stuck with the specification expressed as flowcharts.

Although I could transform the flowcharts into more appropriate equivalent representations before implementing them, that could make it harder to "recognize" the orginal flow-chart in the resulting implementation, so I was hoping there is some way to directly represent flowchart-algorithms as (maybe monadic) EDSLs in Haskell, so that the semblance to the original flowchart-specification would be (more) obvious.

答:
One possible representation of flowcharts is by using a group of mutually tail-recursive functions, by translating "go to step X" into "evaluate function X with state S". For improved readability, you can combine into a single function both the action (an external function that changes the state) and the chain of if/else or pattern matching that helps determine what step to take next.

This is assuming, of course, that your flowcharts are to be hardcoded (as opposed to loaded at runtime from an external source).


问:
How write join with Entity Framework
Here is my select in SQL:

```<code>select *
from FactorItems fi
inner join tblparts p on p.PartsID = fi.PartRef
</code>```

So as I use * to get all columns from my join.

But with this code:

```<code>var FactorItem = (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select FI);
</code>```

I just get data which is in FI. I want to get all data - so what code do I need for that?

答:
you are returning only one entity,  FI. You need to return both the entities .. FI and P , like :

```<code>// your rest of query
select new { FI, P}
</code>```

This way it should get you all the concerned data

Title: How write join with Entity Framework

Body:
Here is my select in SQL:

select *
from FactorItems fi
inner join tblparts p on p.PartsID = fi.PartRef

So as I use * to get all columns from my join.

But with this code:

var FactorItem = (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select FI);

I just get data which is in FI. I want to get all data - so what code do I need for that?

Body:
you are returning only one entity,  FI. You need to return both the entities .. FI and P , like :

// your rest of query
select new { FI, P}

This way it should get you all the concerned data


问:
Understanding how label works when elements hidden
I am trying to understand, how a can label work in conjunction with elements states like input[type="type=""]:checked or input[type=""]:unchecked.I got a very basic example which I am trying to work out, but I cannot make the label a circle or square that can have a check mark or unchecked when clicked. What makes the label have that outlook and showing checked and unchecked state? Does the label need to have a width and height? If so do I need to make it a block level element.

```<code>input[type="checkbox"]{
  width:0;
  heigh:0;
/*   or display:none? */
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  content: '\f096'; /
   //Can be some good example
}
label:after{
  content: '\f00c';
  //Can be some good example
}
input[type="checkbox"]:checked{
  content:"check"
  //Can be some good example
}
input[type="checkbox"]:unchecked{
  content:"x"
  //Can be some good example
}
</code>```

Something achievable like this but without text next to labels as I want checkbox based on styling.

答:
you need to make a relationship ( css wise ) between your checkbox and the clicked label and change it's content . use css selectors for that. for example + or ~

in the example below i used :before and :after . :after will appear only when the checkbox is :checked. i think this is what you want.

IMPORTANT ! : you set the same id to all checkboxes this is bad because

duplicate ID's are not a good practice when writing HTML

you link all labels to the same checkbox ( all are linked to the checkbox with id checkbox . in the below example all have different ids and so every label is linked with it's corresponding checkbox

see code below

.img-holder{
   position:relative
}
.checkbox-holder{
  position:absolute;
  background: #fcfff4;
  margin-top:5px;
  margin-left:10px;
  width:50px;
}
input[type="checkbox"]{
  width:0;
  height:0;
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  border:2px solid red;
  content:"";
  height:20px;
  width:20px;
   border-radius:100%;
  display:inline-block;

}

label:after {
  content:'';
  position:absolute;
  width:10px;
  height:10px;
  border-radius:100%;
  background:green;
  top:-2px;
  left:7px;
  opacity:0;
}
input[type="checkbox"]:checked + label:after {
  opacity:1;
}
input[type="checkbox"]:checked + label:before {
  border-color:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox">
        <label for="checkbox">
      </div>
        <img src="https://placeimg.com/300/480/any/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
          <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox2">
        <label for="checkbox2">
      </div>
        <img src="https://placeimg.com/300/480/any/sephia" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
                <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox3">
        <label for="checkbox3">
      </div>
        <img src="https://placeimg.com/300/480/nature/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
                      <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox4">
        <label for="checkbox4">
      </div>
        <img src="https://placeimg.com/300/480/arch/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
   </div>
</div></code>```

Body:
I am trying to understand, how a can label work in conjunction with elements states like input[type="type=""]:checked or input[type=""]:unchecked.I got a very basic example which I am trying to work out, but I cannot make the label a circle or square that can have a check mark or unchecked when clicked. What makes the label have that outlook and showing checked and unchecked state? Does the label need to have a width and height? If so do I need to make it a block level element.

input[type="checkbox"]{
  width:0;
  heigh:0;
/*   or display:none? */
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  content: '\f096'; /
   //Can be some good example
}
label:after{
  content: '\f00c';
  //Can be some good example
}
input[type="checkbox"]:checked{
  content:"check"
  //Can be some good example
}
input[type="checkbox"]:unchecked{
  content:"x"
  //Can be some good example
}

Something achievable like this but without text next to labels as I want checkbox based on styling.

Body:
you need to make a relationship ( css wise ) between your checkbox and the clicked label and change it's content . use css selectors for that. for example + or ~

in the example below i used :before and :after . :after will appear only when the checkbox is :checked. i think this is what you want.

IMPORTANT ! : you set the same id to all checkboxes this is bad because

duplicate ID's are not a good practice when writing HTML

you link all labels to the same checkbox ( all are linked to the checkbox with id checkbox . in the below example all have different ids and so every label is linked with it's corresponding checkbox

see code below

.img-holder{
   position:relative
}
.checkbox-holder{
  position:absolute;
  background: #fcfff4;
  margin-top:5px;
  margin-left:10px;
  width:50px;
}
input[type="checkbox"]{
  width:0;
  height:0;
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  border:2px solid red;
  content:"";
  height:20px;
  width:20px;
   border-radius:100%;
  display:inline-block;

}

label:after {
  content:'';
  position:absolute;
  width:10px;
  height:10px;
  border-radius:100%;
  background:green;
  top:-2px;
  left:7px;
  opacity:0;
}
input[type="checkbox"]:checked + label:after {
  opacity:1;
}
input[type="checkbox"]:checked + label:before {
  border-color:green;
}

<div class="container">
  <div class="row">
    <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox">
        <label for="checkbox">
      </div>
        <img src="https://placeimg.com/300/480/any/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
          <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox2">
        <label for="checkbox2">
      </div>
        <img src="https://placeimg.com/300/480/any/sephia" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
                <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox3">
        <label for="checkbox3">
      </div>
        <img src="https://placeimg.com/300/480/nature/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
                      <div class="col-3 img-holder">
      <div class="checkbox-holder">
        <input type="checkbox" id="checkbox4">
        <label for="checkbox4">
      </div>
        <img src="https://placeimg.com/300/480/arch/grayscale" alt="">
<!--                 <div class="flex-column justify-content-center">
               <h4 class="add">Added</h4>
               <h4 class="remove">Removed</h4>
          </div> -->
        </div>
   </div>
</div>


问:
.NET core custom service based on request on Startup
I am following this example of .NET core based on request dependency injection:

https://dotnetliberty.com/index.php/2016/04/11/asp-net-core-custom-service-based-on-request/

I have different implementations of a service based on some http headers and I want to load a specific service depending on request.

In startup.cs I have the following code:

```<code> services.AddDbContext<MyContext>(options => options.UseMysql);

services.AddTransient<IMyService>(serviceProvider =>
            {
                var context = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                var header = context.Request.Headers["mycustomheader"];
                if (header == "first") return new MyFirstService();
                else return new SecondService();
            });
</code>```

This is working fine. On every request I get the header and use different implementations of IMyService.

The problem is that I also need to inject the DbContext which I have defined previously and I have no idea how to do it, or if its even possible.

I mean I need to do:

```<code>new FirstService(DbContext); instead of new FirstService();
and new SecondService(DbContext); instead of new SecondService();
</code>```

Is this possible in .NET core?

答:
You need to use DI for that:

```<code>var context = serviceProvider.GetRequiredService<MyContext>();
</code>```

This is the same as what you already do for getting IHttpContextAccessor.

Body:
I am following this example of .NET core based on request dependency injection:

https://dotnetliberty.com/index.php/2016/04/11/asp-net-core-custom-service-based-on-request/

I have different implementations of a service based on some http headers and I want to load a specific service depending on request.

In startup.cs I have the following code:

 services.AddDbContext<MyContext>(options => options.UseMysql);

services.AddTransient<IMyService>(serviceProvider =>
            {
                var context = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                var header = context.Request.Headers["mycustomheader"];
                if (header == "first") return new MyFirstService();
                else return new SecondService();
            });

This is working fine. On every request I get the header and use different implementations of IMyService.

The problem is that I also need to inject the DbContext which I have defined previously and I have no idea how to do it, or if its even possible.

I mean I need to do:

new FirstService(DbContext); instead of new FirstService();
and new SecondService(DbContext); instead of new SecondService();

Is this possible in .NET core?

Body:
You need to use DI for that:

var context = serviceProvider.GetRequiredService<MyContext>();

This is the same as what you already do for getting IHttpContextAccessor.


问:
How to display Select all option at last using bootstrap multiselect?
In multi select dropdown Select all option should be displayed at last after displaying all other options...

```<code>Ex : Select All
     Black
     Red
</code>```

What i want is

```<code>Ex : Black
     Red
     Select All
</code>```

i am referring below link
https://github.com/davidstutz/bootstrap-multiselect

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
        <meta name='viewport' content='width=device-width'>
    <link href="<?php echo base_url();?>assets/css/fonts.css" rel="stylesheet" type="text/css" />

    <script src="<?php echo base_url();?>assets/js/anglr/library/jquery-1.10.2.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="<?php echo base_url();?>assets/css/bootstrap.min.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="<?php echo base_url();?>assets/css/bootstrap-multiselect.css"
        rel="stylesheet" type="text/css" />

    <script src="<?php echo base_url();?>assets/js/anglr/controller/bootstrap_multiselect.js"
        type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('#lstFruits').multiselect({
                includeSelectAllOption: true,
                selectedBottom:true
            });
        });
    </script>
    <script type="text/javascript">
     var web_link2="<?php echo base_url();?>";
     $(function () {
        $('#btnSelected2').click(function () {
        var selected = $("#lstFruits option:selected");

        var message = "";
        selected.each(function () {
            message += $(this).val() + "\n";
        });
        var array_split=message.split(',');
        var document_array = document.getElementById('selectedtoken').value;
        window.location.href = web_link2+"campaign/confirm_unsubscribe/"+document_array+'-'+message;
    });
  });
</script>
</head>
<body>
    <div class="subscribe-Container">
    <header class="subscribe-Header">
            <a class="link"><img src="<?php echo base_url();?>assets/images/opend-logo.png" class="logo-img" alt="Opend" title="Opend"></a>
    </header>
    <div class="subscribe-Content">
      <h1>admin@opend.com</h1>
      <?php if(!isset($msg)||$msg=='')
        {
          ?>
            <p>Please Confirm your unsubscribe request Opend by Clicking on "Unsubscribe" button below to remove your email address</p>
            <select id="lstFruits" multiple>
    <option value="v"><?php echo $vertical_name?></option>
    <option value="c">Contact List</option>

</select>
<input type="hidden" id="selectedtoken" value="<?php echo $mail_token_var?>"/>
<!--<button class="" id="btnSelected2" value="Unsubscribe"></button>-->
          <a class="unsub_button"  id="btnSelected2" >Unsubscribe</a>
        <?php } else echo $msg; ?>
    </div>

  </div>
  </body>
</html>
</code>```

I tried using the below mentioned code

答:
use this script for select all functionality for your multiselect dropdown

html

```<code><select id="lstFruits" multiple>
     <option value="v"><?php echo $vertical_name?></option>
     <option value="c">Contact List</option>
     <option id="select_all">Select All<option>
</select>
</code>```

JS

```<code>$('#select_all').click(function() {
    $('#lstFruits option').prop('selected', true);
});
</code>```

Body:
In multi select dropdown Select all option should be displayed at last after displaying all other options...

Ex : Select All
     Black
     Red

What i want is

Ex : Black
     Red
     Select All

i am referring below link
https://github.com/davidstutz/bootstrap-multiselect

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
        <meta name='viewport' content='width=device-width'>
    <link href="<?php echo base_url();?>assets/css/fonts.css" rel="stylesheet" type="text/css" />

    <link href="<?php echo base_url();?>assets/css/bootstrap.min.css"
        rel="stylesheet" type="text/css" />

    <link href="<?php echo base_url();?>assets/css/bootstrap-multiselect.css"
        rel="stylesheet" type="text/css" />

            <img src="<?php echo base_url();?>assets/images/opend-logo.png" class="logo-img" alt="Opend" title="Opend">

admin@opend.com

      <?php if(!isset($msg)||$msg=='')
        {
          ?>

Please Confirm your unsubscribe request Opend by Clicking on "Unsubscribe" button below to remove your email address

            <select id="lstFruits" multiple>
    <option value="v"><?php echo $vertical_name?></option>
    <option value="c">Contact List</option>

</select>
<input type="hidden" id="selectedtoken" value="<?php echo $mail_token_var?>"/>

          Unsubscribe
        <?php } else echo $msg; ?>

I tried using the below mentioned code

Body:
use this script for select all functionality for your multiselect dropdown

html

<select id="lstFruits" multiple>
     <option value="v"><?php echo $vertical_name?></option>
     <option value="c">Contact List</option>
     <option id="select_all">Select All<option>
</select>

JS

$('#select_all').click(function() {
    $('#lstFruits option').prop('selected', true);
});


问:
How to set different colors for each word(dynamic words getting from server) in label?
I have multiple words in an array:

```<code>NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];
</code>```

I need to set these words into UILabel with different colors.

答:
@Hari can you try below code</p>

```<code> NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];

NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
        NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
        [attStr appendAttributedString:textstr];
 }

UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];

-(UIColor *) getRandomColor
{
    CGFloat redcolor = arc4random() % 255 / 255.0;
    CGFloat greencolor = arc4random() % 255 / 255.0;
    CGFloat bluencolor = arc4random() % 255 / 255.0;
    return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}
</code>```

Body:
I have multiple words in an array:

NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];

I need to set these words into UILabel with different colors.

Body:
@Hari can you try below code

 NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];

NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
        NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
        [attStr appendAttributedString:textstr];
 }

UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];

-(UIColor *) getRandomColor
{
    CGFloat redcolor = arc4random() % 255 / 255.0;
    CGFloat greencolor = arc4random() % 255 / 255.0;
    CGFloat bluencolor = arc4random() % 255 / 255.0;
    return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}


问:
django-tables2 exclude not working SingleTableMixin
Using SingleTableMixin, nothing but the model is being passed to the rendered table. I commented out every line until it broke and **model = Stat is the only thing required for it to work.

I saw similar questions but nothing particular to my case since the table is rendering, just without any of the class Meta info except model

```<code>tables.py

class StatTable(tables.Table):

class Meta:
    model = Stat
    data = Stat.objects.all()
    exclude = ('id',)
    attrs = {'class': 'table table-hover table-condensed'}

views.py

class StatTableMixin(SingleTableMixin):
    table_class = StatTable
    context_table_name = 'stat_table'

class AircraftList(ListView, StatTableMixin):
    model = Aircraft
    template_name = "aircraft/aircraft_list.html"

def get_context_data(self, **kwargs):
    context = super(AircraftList, self).get_context_data(**kwargs)
    context['title'] = "D-> | Aircraft"
    context['stat_table'] = Stat.objects.all()
    return context
</code>```

答:
You are using a custom context_table_name, and assign a QuerySet (Stat.objects.all()) to that name in get_context_data(). This will make django-tables2 render the default view for a queryset, not the custom one you want (StatTable).

You can fix this by not assigning the queryset to context['stat_table'] and using ListView.get_queryset() to prepare the correct queryset to populate the table with data.

Body:
Using SingleTableMixin, nothing but the model is being passed to the rendered table. I commented out every line until it broke and **model = Stat is the only thing required for it to work.

I saw similar questions but nothing particular to my case since the table is rendering, just without any of the class Meta info except model

tables.py

class StatTable(tables.Table):

class Meta:
    model = Stat
    data = Stat.objects.all()
    exclude = ('id',)
    attrs = {'class': 'table table-hover table-condensed'}

views.py

class StatTableMixin(SingleTableMixin):
    table_class = StatTable
    context_table_name = 'stat_table'

class AircraftList(ListView, StatTableMixin):
    model = Aircraft
    template_name = "aircraft/aircraft_list.html"

def get_context_data(self, **kwargs):
    context = super(AircraftList, self).get_context_data(**kwargs)
    context['title'] = "D-> | Aircraft"
    context['stat_table'] = Stat.objects.all()
    return context


答:
Mostly, that's just hard to read code. It would be at least slightly simpler to read (IMO) as

```<code>a[dice.nextInt(6) + 1]++;
</code>```

... but it's easier still to understand it if you split things up:

```<code>int roll = dice.nextInt(6) + 1;
a[roll]++;
</code>```

Note that there's no difference between ++foo and foo++ when that's the whole of a statement - using the post-increment form (foo++) is generally easier to read, IMO: work out what you're going to increment, then increment it.

Random.nextInt(6) will return a value between 0 and 5 inclusive - so adding 1 to that result gets you a value between 1 and 6 inclusive.

Title: Random number for dice (help)

Body:
Mostly, that's just hard to read code. It would be at least slightly simpler to read (IMO) as

a[dice.nextInt(6) + 1]++;

... but it's easier still to understand it if you split things up:

int roll = dice.nextInt(6) + 1;
a[roll]++;

Note that there's no difference between ++foo and foo++ when that's the whole of a statement - using the post-increment form (foo++) is generally easier to read, IMO: work out what you're going to increment, then increment it.

Random.nextInt(6) will return a value between 0 and 5 inclusive - so adding 1 to that result gets you a value between 1 and 6 inclusive.


问:
Passing data to from one controller to another view controller
I want to pass value and display from ViewController1 to ViewController2, when I go to ViewController2. The data did not display on the view. But I check po data.odrNum it has the value in it.

ViewController1

```<code>ViewController2 *data = [[ViewController2 alloc] init];
data.odrNum = [respondData valueForKey:@"orderCode"];
</code>```

ViewController2.h

@property (strong, nonatomic) NSString *odrNum;

ViewController2.m

```<code>self.orderConNum.text = self.odrNum;
</code>```

And this is the way I present my ViewController2

```<code> UIStoryboard * storyboard = self.storyboard;
    OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];
    [self.navigationController pushViewController:detail animated:YES];
</code>```

答:
Have you considered using a sharedSingleton:

In the dropbox file is the sharedSingleton files I use.

In the Changables.h file you can add the variables you want to use and you can import it on the UIViewControllers you want to use.

To set this you only have to use:

```<code>[Changables sharedSingleton].yourVariable = @"my variable data"
</code>```

and to get the data back you can just use

```<code>[Changables sharedSingleton].yourVariable.
</code>```

I have used this to use custom Objects as well.

Body:
I want to pass value and display from ViewController1 to ViewController2, when I go to ViewController2. The data did not display on the view. But I check po data.odrNum it has the value in it.

ViewController1

ViewController2 *data = [[ViewController2 alloc] init];
data.odrNum = [respondData valueForKey:@"orderCode"];

ViewController2.h

@property (strong, nonatomic) NSString *odrNum;

ViewController2.m

self.orderConNum.text = self.odrNum;

And this is the way I present my ViewController2

 UIStoryboard * storyboard = self.storyboard;
    OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];
    [self.navigationController pushViewController:detail animated:YES];

Body:
Have you considered using a sharedSingleton:

In the dropbox file is the sharedSingleton files I use.

In the Changables.h file you can add the variables you want to use and you can import it on the UIViewControllers you want to use.

To set this you only have to use:

[Changables sharedSingleton].yourVariable = @"my variable data"

and to get the data back you can just use

[Changables sharedSingleton].yourVariable.

I have used this to use custom Objects as well.


问:
iOS – Run/Debug/Install builds over Wi-Fi
We have iPad and iPhone devices, but short of wires. Is there any way that we can install/debug the builds over Wi-Fi in iOS?

I know the way in Android, but not of iOS.

答: Using Xcode 9 you can debug over wifi(same network).</p>