问:
Sample RDD element(s) according to weighted probability [Spark]
In PySpark I have an RDD composed by (key;value) pairs where keys are sequential integers and values are floating point numbers.

I'd like to sample exactly one element from this RDD with probability proportional to value.

In a naiive manner, this task can be accomplished as follows:

```<code>pairs = myRDD.collect()   #now pairs is a list of (key;value) tuples
K, V = zip(*pairs)        #separate keys and values
V = numpy.array(V)/sum(V) #normalise probabilities
extractedK = numpy.random.choice(K,size=1,replace=True, p=V)
</code>```

What concerns me is the collect() operation which, as you might know, loads the entire list of tuples in memory, which can be quite expensive. I'm aware of takeSample(), which is great when elements should be extracted uniformly, but what happens if elements should be extracted according to weighted probabilities?

Thanks!

答:
This is basically doable, but you should really consider whether it makes sense to use Spark for this. If you need to draw random values, then you presumeably need to do so many times over in a loop. Each iteration will require scanning through all the data (maybe more than once).

So fitting the data you need into memory and then drawing values from it randomly is almost certainly the right way to go. If your data is really too big to fit into memory, consider (a) only collecting the columns you need for this purpose and (b) whether your data can be binned in a way that makes sense.

Having said that, it is doable within Spark. Below is pysaprk code to demonstrate the idea.

```<code>import random
import pyspark.sql.functions as F
from pyspark.sql.window import Window
# read some sample data (shown below)
df = spark.read.csv("prb.csv",sep='\t',inferSchema=True,header=True)
# find the sum of the value column
ss = df.groupBy().agg( F.sum("vl").alias("sum") ).collect()
# add a column to store the normalized values
q = df.withColumn("nrm_vl", (df["vl"] / ss[0].sum) )
w = Window.partitionBy().orderBy("nrm_vl")\
          .rowsBetween(Window.unboundedPreceding, Window.currentRow)
q = q.select("*", F.sum("nrm_vl").over(w).alias("cum_vl"))
q.show()
+---+---+-------------------+-------------------+
| ky| vl|             nrm_vl|             cum_vl|
+---+---+-------------------+-------------------+
|  2|0.8|0.07079646017699115|0.07079646017699115|
|  3|1.1|0.09734513274336283|0.16814159292035397|
|  4|1.7|0.15044247787610618| 0.3185840707964601|
|  0|3.2| 0.2831858407079646| 0.6017699115044247|
|  1|4.5| 0.3982300884955752| 0.9999999999999999|
+---+---+-------------------+-------------------+

def getRandVl(q):
    # choose a random number and find the row that is
    # less than and nearest to the random number
    # (analog to `std::lower_bound` in C++)
    chvl = q.where( q["cum_vl"] > random.random() ).groupBy().agg(
        F.min(q["cum_vl"]).alias("cum_vl") )
    return q.join(chvl, on="cum_vl", how="inner")
# get 30 random samples.. this is already slow
# on a single machine.
for i in range(0,30):
    x = getRandVl(q)
    # add this row. there's no reason to do this (it's slow)
    # except that it's convenient to count how often each
    # key was chosen, to check if this method works
    cdf = cdf.select(cdf.columns).union(x.select(cdf.columns))

# count how often we picked each key
cdf.groupBy("ky","vl").agg( F.count("*").alias("count") ).show()
+---+---+-----+
| ky| vl|count|
+---+---+-----+
|  4|1.7|    4|
|  2|0.8|    1|
|  3|1.1|    3|
|  0|3.2|   11|
|  1|4.5|   12|
+---+---+-----+
</code>```

I think these counts are reasonable given the values. I'd rather test it with many more samples, but it's too slow.

Body:
In PySpark I have an RDD composed by (key;value) pairs where keys are sequential integers and values are floating point numbers.

I'd like to sample exactly one element from this RDD with probability proportional to value.

In a naiive manner, this task can be accomplished as follows:

pairs = myRDD.collect()   #now pairs is a list of (key;value) tuples
K, V = zip(*pairs)        #separate keys and values
V = numpy.array(V)/sum(V) #normalise probabilities
extractedK = numpy.random.choice(K,size=1,replace=True, p=V)

What concerns me is the collect() operation which, as you might know, loads the entire list of tuples in memory, which can be quite expensive. I'm aware of takeSample(), which is great when elements should be extracted uniformly, but what happens if elements should be extracted according to weighted probabilities?

Thanks!

Body:
This is basically doable, but you should really consider whether it makes sense to use Spark for this. If you need to draw random values, then you presumeably need to do so many times over in a loop. Each iteration will require scanning through all the data (maybe more than once).

So fitting the data you need into memory and then drawing values from it randomly is almost certainly the right way to go. If your data is really too big to fit into memory, consider (a) only collecting the columns you need for this purpose and (b) whether your data can be binned in a way that makes sense.

Having said that, it is doable within Spark. Below is pysaprk code to demonstrate the idea.

import random
import pyspark.sql.functions as F
from pyspark.sql.window import Window
# read some sample data (shown below)
df = spark.read.csv("prb.csv",sep='\t',inferSchema=True,header=True)
# find the sum of the value column
ss = df.groupBy().agg( F.sum("vl").alias("sum") ).collect()
# add a column to store the normalized values
q = df.withColumn("nrm_vl", (df["vl"] / ss[0].sum) )
w = Window.partitionBy().orderBy("nrm_vl")\
          .rowsBetween(Window.unboundedPreceding, Window.currentRow)
q = q.select("*", F.sum("nrm_vl").over(w).alias("cum_vl"))
q.show()
+---+---+-------------------+-------------------+
| ky| vl|             nrm_vl|             cum_vl|
+---+---+-------------------+-------------------+
|  2|0.8|0.07079646017699115|0.07079646017699115|
|  3|1.1|0.09734513274336283|0.16814159292035397|
|  4|1.7|0.15044247787610618| 0.3185840707964601|
|  0|3.2| 0.2831858407079646| 0.6017699115044247|
|  1|4.5| 0.3982300884955752| 0.9999999999999999|
+---+---+-------------------+-------------------+

def getRandVl(q):
    # choose a random number and find the row that is
    # less than and nearest to the random number
    # (analog to `std::lower_bound` in C++)
    chvl = q.where( q["cum_vl"] > random.random() ).groupBy().agg(
        F.min(q["cum_vl"]).alias("cum_vl") )
    return q.join(chvl, on="cum_vl", how="inner")
# get 30 random samples.. this is already slow
# on a single machine.
for i in range(0,30):
    x = getRandVl(q)
    # add this row. there's no reason to do this (it's slow)
    # except that it's convenient to count how often each
    # key was chosen, to check if this method works
    cdf = cdf.select(cdf.columns).union(x.select(cdf.columns))

# count how often we picked each key
cdf.groupBy("ky","vl").agg( F.count("*").alias("count") ).show()
+---+---+-----+
| ky| vl|count|
+---+---+-----+
|  4|1.7|    4|
|  2|0.8|    1|
|  3|1.1|    3|
|  0|3.2|   11|
|  1|4.5|   12|
+---+---+-----+

I think these counts are reasonable given the values. I'd rather test it with many more samples, but it's too slow.


来源: stackexchange

问:
How to preserve-3d using css - firefox issue
I want to be able to hide TEXT1, TEXT2, TEXT3 etc. when hovering with the mouse over either the image or text.
I have managed to do this in chrome by adding
    transform-style: preserve-3d;

The link i am sharing with you works in chrome but not in firefox.

Working Code Link (works in Chrome but not in Firefox)

```<code> #f1_card {
     width: 100%;
     height: 100%;
     transform-style: preserve-3d;
     -webkit-transform-style: preserve-3d;
     -moz-transform-style: preserve-3d;

     /** fixes non transitive 3d from parent  and child **/
     transform-style: preserve-3d;
     transition: all 0.5s linear;
     -webkit-border-radius: 200px;
     -moz-border-radius: 200px;
     border-radius: 200px;
 }
</code>```

Could you please help me out with this issue in Firefox?

答:
You should add the following style to your css:

```<code>.face.front {
  transform: rotateY(0deg);
}
</code>```

Seems like this is known issue. See here Backface-Visibility Not Working Properly in Firefox (Works in Safari)

Here is fix for your example:

https://jsfiddle.net/tx3uf7ch/9/

Here is minimal code to reproduce the issue:

https://jsfiddle.net/5obugjqa/4/

Here is fix for it:

https://jsfiddle.net/5obugjqa/3/

Please follow this guide when asking: How to create a Minimal, Complete, and Verifiable example. And you'll either manage to resolve the issue on your own or get the answer much faster.

ContentLicense: CC BY-SA 3.0

Body:
I want to be able to hide TEXT1, TEXT2, TEXT3 etc. when hovering with the mouse over either the image or text.
I have managed to do this in chrome by adding
    transform-style: preserve-3d;

The link i am sharing with you works in chrome but not in firefox.

Working Code Link (works in Chrome but not in Firefox)

 #f1_card {
     width: 100%;
     height: 100%;
     transform-style: preserve-3d;
     -webkit-transform-style: preserve-3d;
     -moz-transform-style: preserve-3d;

     /** fixes non transitive 3d from parent  and child **/
     transform-style: preserve-3d;
     transition: all 0.5s linear;
     -webkit-border-radius: 200px;
     -moz-border-radius: 200px;
     border-radius: 200px;
 }

Could you please help me out with this issue in Firefox?

Body:
You should add the following style to your css:

.face.front {
  transform: rotateY(0deg);
}

Seems like this is known issue. See here Backface-Visibility Not Working Properly in Firefox (Works in Safari)

Here is fix for your example:

https://jsfiddle.net/tx3uf7ch/9/

Here is minimal code to reproduce the issue:

https://jsfiddle.net/5obugjqa/4/

Here is fix for it:

https://jsfiddle.net/5obugjqa/3/

Please follow this guide when asking: How to create a Minimal, Complete, and Verifiable example. And you'll either manage to resolve the issue on your own or get the answer much faster.


问:
SQL: find space between 2 movies and lower the space
I am making a cinema booking aplication. I have to make a schedule that is efficient for the cinema. That means that time(space) between 2 movies should be 0.

What I have to do: I have to make a Functionality that can find the max space of 30 minutes between 2 movies and set it back to 0, so that the movies have a perfect overlap.

So for example:

Movie 1 : 11:00 - 13:00

Movie 2: 13:30 - 15:00

Movie 3: 15:30 - 16:00

With the functionality the result should be:

Movie 1 : 11:00 - 13:00

Movie 2: 13:00 - 15:00

Movie 3: 15:00 - 16:00

Here is my table:
ShowTable

答:
```<code>IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(Movie,Starttime,EndTime)
SELECT 'Movie 1','11:00','13:00' UNION ALL
SELECT 'Movie 2','13:30','15:00' UNION ALL
SELECT 'Movie 3','15:30','16:00'
UPDATE t SET t.Starttime=p.EndTime
FROM #t AS t
CROSS APPLY(SELECT MAX(tt.EndTime) AS EndTime FROM #t AS tt WHERE DATEDIFF(MINUTE,tt.EndTime,t.Starttime)>0) p
WHERE p.EndTime IS NOT NULL

SELECT * FROM #t
</code>```

```
Movie      Starttime        EndTime
---------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000
Movie 2    13:00:00.0000000 15:00:00.0000000
Movie 3    15:00:00.0000000 16:00:00.0000000
```

Which version are you using, If you are using 2012+
you also can you use LAG

```<code>SELECT *,LAG(EndTime)OVER(ORDER BY EndTime) AS NewStartTime FROM #t
</code>```

```
Movie      Starttime        EndTime          NewStartTime
---------- ---------------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000 NULL
Movie 2    13:30:00.0000000 15:00:00.0000000 13:00:00.0000000
Movie 3    15:30:00.0000000 16:00:00.0000000 15:00:00.0000000
```

I add roomid into sample data

```<code>IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(ShowID int,RoomID int, Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(ShowID,RoomId,Movie,Starttime,EndTime)
SELECT 1,1,'Movie 1','11:00','13:00' UNION ALL
SELECT 3,1,'Movie 2','13:30','15:00' UNION ALL
SELECT 4,1,'Movie 3','15:30','16:00' UNION ALL
SELECT 2,2,'Movie 3','12:30','14:30' UNION ALL
SELECT 5,2,'Movie 1','15:30','16:30'
SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t
UPDATE t SET t.Starttime=isnull(p.NewStartTime,t.Starttime)
FROM #t AS t
inner join(
  SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t
) as p on t.ShowId=p.ShowId

select *  FROM #t AS t
</code>```

Did the following result is you wanted?

```

    ShowID  RoomID  Movie   Starttime   EndTime
1   1   1   Movie 1 11:00:00    13:00:00
2   3   1   Movie 2 13:00:00    15:00:00
3   4   1   Movie 3 15:00:00    16:00:00
4   2   2   Movie 3 12:30:00    14:30:00
5   5   2   Movie 1 14:30:00    16:30:00
```

Body:
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(Movie,Starttime,EndTime)
SELECT 'Movie 1','11:00','13:00' UNION ALL
SELECT 'Movie 2','13:30','15:00' UNION ALL
SELECT 'Movie 3','15:30','16:00'
UPDATE t SET t.Starttime=p.EndTime
FROM #t AS t
CROSS APPLY(SELECT MAX(tt.EndTime) AS EndTime FROM #t AS tt WHERE DATEDIFF(MINUTE,tt.EndTime,t.Starttime)>0) p
WHERE p.EndTime IS NOT NULL

SELECT * FROM #t

Movie      Starttime        EndTime
---------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000
Movie 2    13:00:00.0000000 15:00:00.0000000
Movie 3    15:00:00.0000000 16:00:00.0000000

Which version are you using, If you are using 2012+
you also can you use LAG

SELECT *,LAG(EndTime)OVER(ORDER BY EndTime) AS NewStartTime FROM #t

Movie      Starttime        EndTime          NewStartTime
---------- ---------------- ---------------- ----------------
Movie 1    11:00:00.0000000 13:00:00.0000000 NULL
Movie 2    13:30:00.0000000 15:00:00.0000000 13:00:00.0000000
Movie 3    15:30:00.0000000 16:00:00.0000000 15:00:00.0000000

I add roomid into sample data

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(ShowID int,RoomID int, Movie varchar(10),Starttime TIME,EndTime time)
INSERT INTO #t(ShowID,RoomId,Movie,Starttime,EndTime)
SELECT 1,1,'Movie 1','11:00','13:00' UNION ALL
SELECT 3,1,'Movie 2','13:30','15:00' UNION ALL
SELECT 4,1,'Movie 3','15:30','16:00' UNION ALL
SELECT 2,2,'Movie 3','12:30','14:30' UNION ALL
SELECT 5,2,'Movie 1','15:30','16:30'
SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t
UPDATE t SET t.Starttime=isnull(p.NewStartTime,t.Starttime)
FROM #t AS t
inner join(
  SELECT *,LAG(EndTime)OVER(partition by RoomId ORDER BY EndTime) AS NewStartTime FROM #t
) as p on t.ShowId=p.ShowId

select *  FROM #t AS t

Did the following result is you wanted?

    ShowID  RoomID  Movie   Starttime   EndTime
1   1   1   Movie 1 11:00:00    13:00:00
2   3   1   Movie 2 13:00:00    15:00:00
3   4   1   Movie 3 15:00:00    16:00:00
4   2   2   Movie 3 12:30:00    14:30:00
5   5   2   Movie 1 14:30:00    16:30:00


问:
How to generate a set of random points within a given (x,y) coordinates in an x-y plane?
Suppose I want to take 4 clusters of points. Each cluster can be within a given set of x-y co ordinates. Each point within a cluster is a random generated point.

These clusters will be acting as input for my K-Means clustering problem.
How do I do it using Python?

答:
If you generate data using

```<code>min + (max - min) * random()
</code>```

Then they will be between min and max.

Do this for x and y, and for every cluster.

Body:
If you generate data using

min + (max - min) * random()

Then they will be between min and max.

Do this for x and y, and for every cluster.


问:
How to use Kubernetes SSL certificates
I am trying to build an HTTPs proxy server in front of another service in Kubernetes, using either an NginX proxy LoadBalancer server, or Ingress.  Either way, I need a certificate and key so that my external requests get authenticated.

I'm looking at how to manage tls in a cluster, and I've noticed that the certificate used to connect to the container cluster is the same one as is mounted at /var/run/secrets/kubernetes.io/serviceaccount/ca.crt on a running pod.

So I'm thinking that my node cluster already has a registered certificate, all I need is the key, throw it into a secret and mount that into my proxy server.  But I can't find how.

Is it this simple?  How would I do that?  Or do I need to create a new certificate, sign it etc etc?  Would I then need to replace the current certificate?

答:
If you want an external request to get into your K8s cluster then this is the job of an ingress controller, or configuring the service with a loadbalancer, if your cloud provider supports it.

The certificate discussed in your reference is really meant to be used for intra-cluster communications, as it says:

Every Kubernetes cluster has a cluster root Certificate Authority (CA). The CA is generally used by cluster components to validate the API server’s certificate, by the API server to validate kubelet client certificates, etc.

If you go for an ingress approach then here is the doc for tls. At the bottom a list of alternatives, such as the load balancer approach.

I guess you could use the internal certificate externally if you are able to get all your external clients to trust it. Personally I'd probably use kube-lego, which automates getting certificates from Let's Encrypt, since most browsers trust this CA now.

Hope this helps

Title: How to use Kubernetes SSL certificates


问:
MySQL Error Incorrect key file. myisamchk repair works but table corrupts again soon
my first question on stackoverflow so I hope I have followed all the guidelines.

I have a website with MySql db on a Digital Ocean droplet.

I found mysql had stopped running and after looking found corrupt tables. After repairing them with myisamchk -r I thought the problem was solved. However it kept occurring. I changed innodb_buffer_pool_size = 20M in my.cnf and a have created some free space on /dev/vda/ after reading this MySQL, Error 126: Incorrect key file for table

```<code>Filesystem     1K-blocks     Used Available Use% Mounted on
udev              239664        4    239660   1% /dev
tmpfs              50176      380     49796   1% /run
/dev/vda1       20511356 12346408   7099992  64% /
none                   4        0         4   0% /sys/fs/cgroup
none                5120        0      5120   0% /run/lock
none              250872        0    250872   0% /run/shm
</code>```

I have these errors in the mysql/error.log

```<code>[ERROR] /usr/sbin/mysqld: Incorrect key file for table './websitename/wp_options.MYI'; try to repair it
[ERROR] Got an error from thread_id=178, /build/mysql-5.5-heGK82/mysql-5.5-5.5.55/storage/myisam/mi_update.c:226
[ERROR] MySQL thread id 178, OS thread handle 0x7f4544010700, query id 69124 localhost th3489075 Updating
</code>```

When I run myisamchk db_name.MYI on the corrupt table I get

```<code>Checking MyISAM file: wp_options.MYI
Data records:     375   Deleted blocks:       0
myisamchk: warning: Table is marked as crashed
myisamchk: warning: 1 client is using or hasn't closed the table properly
- check file-size
myisamchk: error: Size of datafile is: 1059228           Should be: 1059276
- check record delete-chain
- check key delete-chain
- check index reference
- check data record references index: 1
- check data record references index: 2
- check record links
myisamchk: error: Keypointers and record positions doesn't match
myisamchk: warning: Found        375 key parts. Should be: 377
MyISAM-table 'wp_options.MYI' is corrupted
Fix it using switch "-r" or "-o"
</code>```

Repairing the table with myisamchk -r or -o options seems to work as running myisamchk *.MYI immediately after reports no problems but later on it returns the error above.

I have various backups of the db but am unsure how different they are from the current ones.

I understand the warning myisamchk: warning: 1 client is using or hasn't closed the table properly occurs if mysql is running.

When mysql is stopped myisamchk *.MYI reports all ok but mysql still crashes.

答:
Every time there is a power failure or other abrupt termination of mysqld, MyISAM tables may be corrupted.  This is a strong reason to switch to InnoDB, which does a better job of protecting itself and automatically repair upon restart.

Meanwhile, you could try OPTIMIZE TABLE as a way of forcing a rebuild of the table.  This may or may not lose the data that seems to be missing, but it will probably get rid of the error message until the next crash.

Body:
my first question on stackoverflow so I hope I have followed all the guidelines.

I have a website with MySql db on a Digital Ocean droplet.

I found mysql had stopped running and after looking found corrupt tables. After repairing them with myisamchk -r I thought the problem was solved. However it kept occurring. I changed innodb_buffer_pool_size = 20M in my.cnf and a have created some free space on /dev/vda/ after reading this MySQL, Error 126: Incorrect key file for table

Filesystem     1K-blocks     Used Available Use% Mounted on
udev              239664        4    239660   1% /dev
tmpfs              50176      380     49796   1% /run
/dev/vda1       20511356 12346408   7099992  64% /
none                   4        0         4   0% /sys/fs/cgroup
none                5120        0      5120   0% /run/lock
none              250872        0    250872   0% /run/shm

I have these errors in the mysql/error.log

[ERROR] /usr/sbin/mysqld: Incorrect key file for table './websitename/wp_options.MYI'; try to repair it
[ERROR] Got an error from thread_id=178, /build/mysql-5.5-heGK82/mysql-5.5-5.5.55/storage/myisam/mi_update.c:226
[ERROR] MySQL thread id 178, OS thread handle 0x7f4544010700, query id 69124 localhost th3489075 Updating

When I run myisamchk db_name.MYI on the corrupt table I get

Checking MyISAM file: wp_options.MYI
Data records:     375   Deleted blocks:       0
myisamchk: warning: Table is marked as crashed
myisamchk: warning: 1 client is using or hasn't closed the table properly
- check file-size
myisamchk: error: Size of datafile is: 1059228           Should be: 1059276
- check record delete-chain
- check key delete-chain
- check index reference
- check data record references index: 1
- check data record references index: 2
- check record links
myisamchk: error: Keypointers and record positions doesn't match
myisamchk: warning: Found        375 key parts. Should be: 377
MyISAM-table 'wp_options.MYI' is corrupted
Fix it using switch "-r" or "-o"

Repairing the table with myisamchk -r or -o options seems to work as running myisamchk *.MYI immediately after reports no problems but later on it returns the error above.

I have various backups of the db but am unsure how different they are from the current ones.

I understand the warning myisamchk: warning: 1 client is using or hasn't closed the table properly occurs if mysql is running.

When mysql is stopped myisamchk *.MYI reports all ok but mysql still crashes.


问:
Access all fields of an EntityType
I have a form (new Order) that contains a CollectionType field where the entry_type is another form (Product (Name and quantity) ) which contain a EntityType field (A dropdown select) with a IntegerType field.

I'm using Symfony prototype to allow multiple add of this form (add many product to an order ), but I want to access the price of each product displayed so I can calculate the final amount of this order.

OrderForm:

```<code> public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
       ->add('client', EntityType::class, array(
           'class' => 'AppBundle:Client',
           'query_builder' => function (EntityRepository $er) {
               return $er->createQueryBuilder('u')
                   ->orderBy('u.raison', 'ASC');
           },
           'choice_label' => 'raison',

       ))

        ->add('ligne', CollectionType::class, array(
            'entry_type' => BCitemsFormType::class,
            'allow_add'    => true,
            'allow_delete'    => true,
            'by_reference' => false,

        ))

    ;

}
</code>```

ProductLine:

```<code> public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('produit', EntityType::class, array(
            'class' => 'AppBundle:Produit',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->orderBy('u.libele', 'ASC');
            },
            'choice_label' => 'libele',

        ))

        ->add('quantity', IntegerType::class, [
            'attr' => ['min' => 1],
            'label' => 'Quantité',
        ])
        ;

}
</code>```

View where I'm displaying The ProductLine Form:

```<code><div class="form-group" id="form_ref">
     <label class="control-label col-md-3">Produits</label>
            <div class="col-md-9">
                <div class="input-icon right">
                  <i class="" data-original-title="" id="icone_ref"></i>

                   <ul class="tags" data-prototype="{{ form_widget(bcForm.ligne.vars.prototype)|e('html_attr') }}" >

                    </ul>

                 </div>
              </div>
</div>
</code>```

When I add a product Line, I get a list of my products with name field in the choice_label, I want to display the price also or any others fields of my entity Product.

答: Thank you for your answer , the problem is not only to display the price , i need to check wich value of my Product List is selected and get the right price , with prototype the code is generated automaticly so i cant know the name of the Select element . </p>

ContentLicense: CC BY-SA 4.0

Title: Access all fields of an EntityType

Body:
I have a form (new Order) that contains a CollectionType field where the entry_type is another form (Product (Name and quantity) ) which contain a EntityType field (A dropdown select) with a IntegerType field.

I'm using Symfony prototype to allow multiple add of this form (add many product to an order ), but I want to access the price of each product displayed so I can calculate the final amount of this order.

OrderForm:

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
       ->add('client', EntityType::class, array(
           'class' => 'AppBundle:Client',
           'query_builder' => function (EntityRepository $er) {
               return $er->createQueryBuilder('u')
                   ->orderBy('u.raison', 'ASC');
           },
           'choice_label' => 'raison',

       ))

        ->add('ligne', CollectionType::class, array(
            'entry_type' => BCitemsFormType::class,
            'allow_add'    => true,
            'allow_delete'    => true,
            'by_reference' => false,

        ))

    ;

}

ProductLine:

 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('produit', EntityType::class, array(
            'class' => 'AppBundle:Produit',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->orderBy('u.libele', 'ASC');
            },
            'choice_label' => 'libele',

        ))

        ->add('quantity', IntegerType::class, [
            'attr' => ['min' => 1],
            'label' => 'Quantité',
        ])
        ;

}

View where I'm displaying The ProductLine Form:

     Produits

When I add a product Line, I get a list of my products with name field in the choice_label, I want to display the price also or any others fields of my entity Product.


问:
Validation in PHP form and saving to a file
```<code>   if($_POST){

$errors = array();

//start validation
if(empty($_POST['email'])){
    $errors['email1'] = "Your Email Cannot be empty";
}

if (!filter_var(['email'], FILTER_VALIDATE_EMAIL)){
    $errors['email2'] = "Email not valid!";
}

if(empty($_POST['phone'])){
    $errors['phone1'] = "Your Number Cannot be empty";
}
if(strlen($_POST['phone']) < 8){
    $errors['phone2'] = "Your Phone Number must be at least 8 characters long";
}

if(strlen($_POST['phone']) > 8){
    $errors['phone3'] = "Your Phone Number must be not more than 8 characters long";
}

//check errors
if(count($errors) == 0)
{
    //redirect to home page
    header("Location: index.php");
    exit();
}
}
</code>```

This is my code which needs to be validated. The validation works ok but here is the problem.

```<code><div class="form-group">
            <label for="name">Email</label>
            <input type="email" class ="form-control" name="email" id="email" placeholder="Enter Email">
            <p><?php if(isset($errors['email1'])) echo $errors['email1'];?></p>
            <p><?php if(isset($errors['email2'])) echo $errors['email12'];?></p>
        </div>

        <div class="form-group">
            <label for="phone">Phone Number</label>
            <input type="text" class ="form-control" name="phone" id="phone" placeholder="Enter Phone Number">
            <p><?php if(isset($errors['phone1'])) echo $errors['phone1'];?></p>
            <p><?php if(isset($errors['phone2'])) echo $errors['phone2'];?></p>
            <p><?php if(isset($errors['phone3'])) echo $errors['phone3'];?></p>
        </div>
</code>```

I have the form set to save to a file. The inputs will be validated and the error messages will be displayed but the form that has wrong inputs will still be saved to a file. Any help would be appreciated thanks.

```<code><?php
    if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])){

        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $enquiry = $_POST['enquiry'];

        $file = "form.txt";

        $save = "Email: ".$email."\n".
                "Phone: ".$phone."\n".
                "Comment: ".$enquiry."\n";

        file_put_contents($file,$save, FILE_APPEND);
}
?>
</code>```

答:
Based off your comment, you want ONLY VALID data to go into the file.

But your PHP check is looking to see if ANY values are set, here:

```<code>if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])) {
</code>```

If you change that to check to make sure ONLY valid data is present, then you'd be good.  Adding a simple && count($errors) == 0 could do it (if I understand the structure of your files).

So just replace that line above with this:

```<code>if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry']) && count($errors) == 0) {
</code>```

So your file would look something like this:

```<code>    ....PHP code above here....

    //check errors
    if(count($errors) == 0)
    {
          if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])){

                $email = $_POST['email'];
                $phone = $_POST['phone'];
                $enquiry = $_POST['enquiry'];

                $file = "form.txt";

                $save = "Email: ".$email."\n".
                        "Phone: ".$phone."\n".
                        "Comment: ".$enquiry."\n";

                file_put_contents($file,$save, FILE_APPEND);
        }

        //redirect to home page
        header("Location: index.php");
        exit();
    } // end count($errors) == 0 check
} // end if($_POST) check
?>

<div class="form-group">
        <label for="name">Email</label>
        <input type="email" class ="form-control" name="email" id="email" placeholder="Enter Email">
        <p><?php if(isset($errors['email1'])) echo $errors['email1'];?></p>
        <p><?php if(isset($errors['email2'])) echo $errors['email12'];?></p>
    </div>

....HTML code continues here....
</code>```

Body:
   if($_POST){

$errors = array();

//start validation
if(empty($_POST['email'])){
    $errors['email1'] = "Your Email Cannot be empty";
}

if (!filter_var(['email'], FILTER_VALIDATE_EMAIL)){
    $errors['email2'] = "Email not valid!";
}

if(empty($_POST['phone'])){
    $errors['phone1'] = "Your Number Cannot be empty";
}
if(strlen($_POST['phone']) < 8){
    $errors['phone2'] = "Your Phone Number must be at least 8 characters long";
}

if(strlen($_POST['phone']) > 8){
    $errors['phone3'] = "Your Phone Number must be not more than 8 characters long";
}

//check errors
if(count($errors) == 0)
{
    //redirect to home page
    header("Location: index.php");
    exit();
}
}

This is my code which needs to be validated. The validation works ok but here is the problem.

            Email
            <input type="email" class ="form-control" name="email" id="email" placeholder="Enter Email">

<?php if(isset($errors['email1'])) echo $errors['email1'];?>

<?php if(isset($errors['email2'])) echo $errors['email12'];?>

            Phone Number
            <input type="text" class ="form-control" name="phone" id="phone" placeholder="Enter Phone Number">

<?php if(isset($errors['phone1'])) echo $errors['phone1'];?>

<?php if(isset($errors['phone2'])) echo $errors['phone2'];?>

<?php if(isset($errors['phone3'])) echo $errors['phone3'];?>

I have the form set to save to a file. The inputs will be validated and the error messages will be displayed but the form that has wrong inputs will still be saved to a file. Any help would be appreciated thanks.

<?php
    if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])){

        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $enquiry = $_POST['enquiry'];

        $file = "form.txt";

        $save = "Email: ".$email."\n".
                "Phone: ".$phone."\n".
                "Comment: ".$enquiry."\n";

        file_put_contents($file,$save, FILE_APPEND);
}
?>

Body:
Based off your comment, you want ONLY VALID data to go into the file.

But your PHP check is looking to see if ANY values are set, here:

if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])) {

If you change that to check to make sure ONLY valid data is present, then you'd be good.  Adding a simple && count($errors) == 0 could do it (if I understand the structure of your files).

So just replace that line above with this:

if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry']) && count($errors) == 0) {

So your file would look something like this:

    ....PHP code above here....

    //check errors
    if(count($errors) == 0)
    {
          if(isset($_POST['email'])  && isset($_POST['phone'])  && isset($_POST['enquiry'])){

                $email = $_POST['email'];
                $phone = $_POST['phone'];
                $enquiry = $_POST['enquiry'];

                $file = "form.txt";

                $save = "Email: ".$email."\n".
                        "Phone: ".$phone."\n".
                        "Comment: ".$enquiry."\n";

                file_put_contents($file,$save, FILE_APPEND);
        }

        //redirect to home page
        header("Location: index.php");
        exit();
    } // end count($errors) == 0 check
} // end if($_POST) check
?>

<div class="form-group">
        <label for="name">Email</label>
        <input type="email" class ="form-control" name="email" id="email" placeholder="Enter Email">
        <p><?php if(isset($errors['email1'])) echo $errors['email1'];?></p>
        <p><?php if(isset($errors['email2'])) echo $errors['email12'];?></p>
    </div>

....HTML code continues here....


问:
application failed (make Killed)
I have compiled my cpp file via a make file. I have run my file via this make file too.

This multi-thread application uses 99% of CPU as well. I am using Ubuntu 16.04.1 LTS as my OS.

After three days of running, I realized that the application has suddenly stopped and I see this unexpected error message on the terminal.

```<code>Makefile:: recipe for target 'myMain' failed
make: *** myMain Killed
</code>```

There is not other error message. This application failed with no exception error message. And I am highly confidant about the programs I write (about failing) despite no one is writing a full proof application.

I have never seen message of make: *** something Killed before too.

Unfortunately, this is a case which I cannot easily repeat again and again to see what is wrong.

I am wondering if make application or Ubuntu have any mechanism to kill any application if running for a long time and taking huge amount of resource?

Update

Thanks to user Basile Starynkevitch, this is the result I received from dmesg:

```<code>[351059.556308] Out of memory: Kill process 2794 (main) score 882 or sacrifice child
[351059.556318] Killed process 2794 (main) total-vm:30432908kB, anon-rss:13530324kB, file-rss:0kB
</code>```

答:
Out of memory: Kill process

Most likely you were compiling sources as a user and your environment were restricted by the resource limits listed with ulimit -a command (either memory or number of processes). Once the hard limit is hit, the process is killed by the Linux kernel.

If you've got enough memory, it's possible to increase these limits (ulimit -Sv), otherwise you need to increase memory of your machine or add some extra swap space.

For more details about this behaviour, see: Kernel - Out Of Memory Management.

When the machine is low on memory, old page frames will be reclaimed, but despite reclaiming pages is may find that it was unable to free enough pages to satisfy a request even when scanning at highest priority. If it does fail to free page frames, out_of_memory() is called to see if the system is out of memory and needs to kill a process.

Title: application failed (make Killed)

Body:
I have compiled my cpp file via a make file. I have run my file via this make file too.

This multi-thread application uses 99% of CPU as well. I am using Ubuntu 16.04.1 LTS as my OS.

After three days of running, I realized that the application has suddenly stopped and I see this unexpected error message on the terminal.

Makefile:: recipe for target 'myMain' failed
make: *** myMain Killed

There is not other error message. This application failed with no exception error message. And I am highly confidant about the programs I write (about failing) despite no one is writing a full proof application.

I have never seen message of make: *** something Killed before too.

Unfortunately, this is a case which I cannot easily repeat again and again to see what is wrong.

I am wondering if make application or Ubuntu have any mechanism to kill any application if running for a long time and taking huge amount of resource?

Update

Thanks to user Basile Starynkevitch, this is the result I received from dmesg:

[351059.556308] Out of memory: Kill process 2794 (main) score 882 or sacrifice child
[351059.556318] Killed process 2794 (main) total-vm:30432908kB, anon-rss:13530324kB, file-rss:0kB


问:
Design Pattern, Qt Model/View and multiple threads
I am creating an application which displays the market data and uses it in some other forms too. I store market data in a map say
std::map<tickerId, StockData>. Let me give one used case of how this map can be used.

network sends a data packet encapsulating the stock Data at time t. updatePrice(tickerId, latestPrice)

update the stock data in the map. Now, multiple threads can access/update the data. So the map has to be locked for thread-safe operations. Here is the first question, do I need to lock the underlying data too for updates?

There are multiple uses of the new stock data, say, there is a price update on IBM, then I need to update the value of IBM in my portfolio. As well as display the new data on a screen. And there can be several other simultaneous uses.updatePosition(tickerId, price) and updateStockScreen(tickerId, price). Also, separting Gui updates from position update is important as GUI is not the main strength of the application.

I am just troubled about how to implement this type of design. I read about Model/View Design in QT to display data but if View thread reads from the same map, it has to be locked. This leads to an slow/inefficient design. Every time view reads from the model, the model needs to be locked. Is this preffered in real-time GUIs?

To summarize, I have stored a lot of different objects as maps. And objects are updated in realtime. I need to update them and then use them at various locations. It would be great if someone can give me a small example on how to implement such designs.

Some references to useful books are appreciated too.

I am new and trying to achieve too much with my little knowledge so forgive me if I have asked stupid/ill-formed questions.

Thanks
Shiv

答:
I learned another potential problem today, the hard way, even if the model was read only. I use another thread to modify the data in the model (actually, my program is over 20 threads, and they all play nice), which then a Qt timer updates. This works very well, but there is a problem I fell into, which is:

You cannot lock between rowCount/columnCount and data().

Qt works sequentially, meaning that in human language, it'll ask "how big are you", and then ask "what data do you have at this position", and these are prone to break.

Consider:

```<code>int FilesQueue::rowCount(const QModelIndex &/*parent*/) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    return filesQueue.size();
}
QVariant FilesQueue::data(const QModelIndex &index, int role) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    if ( role == Qt::DisplayRole) {
        return filesQueue[index.row()]->getFilename();
    }
}
</code>```

Qt will do the calls like this:

```<code>//...
obj->rowCount();
obj->data(...);
//...
</code>```

And I had assertion failure all over the place because simply, between rowCount() and data(), there was a thread that was changing the size of the data! It broke the program. So this was happening:

```<code>//...
obj->rowCount();
//another thread: filesQueue.erase(...)
obj->data(...);
//...
</code>```

My solution to the problem is to verify the size, again, in the data() method:

```<code>QVariant FilesQueue::data(const QModelIndex &index, int role) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    //solution is here:
    if(static_cast<int>(filesQueue.size()) <= index.row())
        return QVariant();
    if ( role == Qt::DisplayRole) {
        return filesQueue[index.row()]->getFilename();
    }
}
</code>```

and there goes 3 hours of my life I'll never get back :-)

Body:
I learned another potential problem today, the hard way, even if the model was read only. I use another thread to modify the data in the model (actually, my program is over 20 threads, and they all play nice), which then a Qt timer updates. This works very well, but there is a problem I fell into, which is:

You cannot lock between rowCount/columnCount and data().

Qt works sequentially, meaning that in human language, it'll ask "how big are you", and then ask "what data do you have at this position", and these are prone to break.

Consider:

int FilesQueue::rowCount(const QModelIndex &/*parent*/) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    return filesQueue.size();
}
QVariant FilesQueue::data(const QModelIndex &index, int role) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    if ( role == Qt::DisplayRole) {
        return filesQueue[index.row()]->getFilename();
    }
}

Qt will do the calls like this:

//...
obj->rowCount();
obj->data(...);
//...

And I had assertion failure all over the place because simply, between rowCount() and data(), there was a thread that was changing the size of the data! It broke the program. So this was happening:

//...
obj->rowCount();
//another thread: filesQueue.erase(...)
obj->data(...);
//...

My solution to the problem is to verify the size, again, in the data() method:

QVariant FilesQueue::data(const QModelIndex &index, int role) const
{
    std::lock_guard<decltype(mainQueueMutex)> lg(mainQueueMutex);
    //solution is here:
    if(static_cast<int>(filesQueue.size()) <= index.row())
        return QVariant();
    if ( role == Qt::DisplayRole) {
        return filesQueue[index.row()]->getFilename();
    }
}

and there goes 3 hours of my life I'll never get back :-)


问:
How to remove previous swf when enter new swf (AS3)......?
I am creating double Quiz games with 3 swf files(main.swf,A.swf,B.swf),when i load from Main.swf into another swf example into(B.swf) and reload back to Main.swf again,it works perfectly without erros... but when this process keep on looping, its seems like spamming CPU memory usage...what coding i should used to solve it?
(**i guess because the previous swf file's memory not totally remove when enter another swf, new swf just replacing on top)
(I used .unload(),removeChild (),stop() so on seems doesn't solve this problem..i did try my best to solve but fail)
I think there must be some codes used solve this,i dunno what else.can give me little solutions?

Your all Kindness will be very appreciate:)
Thanks

答:
You don't need to reload each SWF in a loop! Assign a variable to the loaded SWF instead and use that variable to interact with the swf.

```<code>  private var swfA:MovieClip;

  private function onLoadComplete( event:Event ):void
  {
       //if you've loaded A.swf
       swfA = event.currentTarget.content;
  }
</code>```

From that point on, you can:

```<code>  //hide the swf
  swfA.visible = false;

  //remove it from stage
  removeChild( swfA );
</code>```

And if you had linked it to its own class , you could even call methods or set properties

```<code>  //for instance...
  swfA.answers = [ answer1 , answer2 .... , answern];
  swfA.showResult();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You don't need to reload each SWF in a loop! Assign a variable to the loaded SWF instead and use that variable to interact with the swf.

  private var swfA:MovieClip;

  private function onLoadComplete( event:Event ):void
  {
       //if you've loaded A.swf
       swfA = event.currentTarget.content;
  }

From that point on, you can:

  //hide the swf
  swfA.visible = false;

  //remove it from stage
  removeChild( swfA );

And if you had linked it to its own class , you could even call methods or set properties

  //for instance...
  swfA.answers = [ answer1 , answer2 .... , answern];
  swfA.showResult();


问:
ActiveModel::ForbiddenAttributesError in UrlsController#create
I have the following code:

```<code>class UrlsController < ApplicationController
def new
 @shortened_url = Url.new
end
def create
 @shortened_url = Url.new(params[:url])
 if @shortened_url.save
   flash[:shortened_id] = @shortened_url.id
   redirect_to new_url_url
 else
   render :action => "new"
  end
end

def show
     @shortened_url = Url.find(params[:id])
    redirect_to @shortened_url.url
     end

 end
</code>```

I'm getting the error I know is related to the required parameters and permit. Any one can tell me how the method need to be written?

this is the model:

```<code>class Url < ActiveRecord::Base
  validates :url, :presence => true
end
</code>```

the error is when submitting the form. I get
ActiveModel::ForbiddenAttributesError in UrlsController#create

答:
It needed the use of strong parameters</p>

```<code>class UrlsController < ApplicationController
def new
 @shortened_url = Url.new
 end
def create
 @shortened_url = Url.new(shortened_url)
 if @shortened_url.save
   flash[:shortened_id] = @shortened_url.id
   redirect_to new_url_url
 else
   render :action => "new"
 end
end

 def show
 @shortened_url = Url.find(params[:id])
 redirect_to @shortened_url.url
end

private

 def shortened_url
   params.require(:url).permit!
 end

end
</code>```

Body:
I have the following code:

class UrlsController < ApplicationController
def new
 @shortened_url = Url.new
end
def create
 @shortened_url = Url.new(params[:url])
 if @shortened_url.save
   flash[:shortened_id] = @shortened_url.id
   redirect_to new_url_url
 else
   render :action => "new"
  end
end

def show
     @shortened_url = Url.find(params[:id])
    redirect_to @shortened_url.url
     end

 end

I'm getting the error I know is related to the required parameters and permit. Any one can tell me how the method need to be written?

this is the model:

class Url < ActiveRecord::Base
  validates :url, :presence => true
end

the error is when submitting the form. I get
ActiveModel::ForbiddenAttributesError in UrlsController#create

Body:
It needed the use of strong parameters

class UrlsController < ApplicationController
def new
 @shortened_url = Url.new
 end
def create
 @shortened_url = Url.new(shortened_url)
 if @shortened_url.save
   flash[:shortened_id] = @shortened_url.id
   redirect_to new_url_url
 else
   render :action => "new"
 end
end

 def show
 @shortened_url = Url.find(params[:id])
 redirect_to @shortened_url.url
end

private

 def shortened_url
   params.require(:url).permit!
 end

end


问:
Cant get While loop to work
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.</p>

```<code>              using System;

class CalculatorProgram
{
    //varibale for do-while loop
    private static string endAnswer;
    public static void Main() // <----- The Entry point
    {
     //Variables
     string Choice1;
    string mathChoice;
    decimal Num1;
    decimal Num2;
    decimal Answer;
    bool userWrong = true;

    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    Choice1 = Console.ReadLine();

    while(userWrong)
    {
        if (Choice1 == "Yes")

        {
            do
            {
                Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
                mathChoice = Console.ReadLine();

                //User inputs the 2 numbers

                //Math Choices
                if (mathChoice == "Add")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());

                    Answer = Num1 + Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Subtract")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 - Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Multiply")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 * Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Divide")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 / Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
                }

                else
                {
                    Console.WriteLine("This is not an option! Shutting Down..");
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                //varibale for while loop to continue if selected Yes.
                Console.Write("Another Equation?: ");
                endAnswer = Console.ReadLine();

            } while (endAnswer == "Yes");

            //Goodbye Message
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
            userWrong = false;
        }
        //If someone selects no for wanting to use my program.
        else if (Choice1 == "No")
        {
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("That is not an option");
            Console.ReadLine();

        }

    }

    }
}
</code>```

答:
Probably your problem is that you don’t make a correct validation of the input.
Now, you read the input from console and compare with a static string so
“Add” is different from “add” and different from “Add(space)“.
I suggest you to make a more strong input validation:</p>

```<code>Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
mathChoice = mathChoice.ToUpper().Trim();
//User inputs the 2 numbers

//Math Choices
if (mathChoice == "ADD")
{
     Console.WriteLine("What 2 numbers would you like to use?");
     ....
}
</code>```

Title: Cant get While loop to work

Body:
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.

              using System;

class CalculatorProgram
{
    //varibale for do-while loop
    private static string endAnswer;
    public static void Main() // <----- The Entry point
    {
     //Variables
     string Choice1;
    string mathChoice;
    decimal Num1;
    decimal Num2;
    decimal Answer;
    bool userWrong = true;

    Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
    Choice1 = Console.ReadLine();

    while(userWrong)
    {
        if (Choice1 == "Yes")

        {
            do
            {
                Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
                mathChoice = Console.ReadLine();

                //User inputs the 2 numbers

                //Math Choices
                if (mathChoice == "Add")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());

                    Answer = Num1 + Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Subtract")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 - Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Multiply")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 * Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
                }

                else if (mathChoice == "Divide")
                {
                    Console.WriteLine("What 2 numbers would you like to use?");
                    Console.Write("Number 1 is: ");
                    Num1 = decimal.Parse(Console.ReadLine());

                    Console.Write("Number 2 is: ");
                    Num2 = decimal.Parse(Console.ReadLine());
                    Answer = Num1 / Num2;
                    Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
                }

                else
                {
                    Console.WriteLine("This is not an option! Shutting Down..");
                    Console.ReadKey();
                    Environment.Exit(0);
                }

                //varibale for while loop to continue if selected Yes.
                Console.Write("Another Equation?: ");
                endAnswer = Console.ReadLine();

            } while (endAnswer == "Yes");

            //Goodbye Message
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
            userWrong = false;
        }
        //If someone selects no for wanting to use my program.
        else if (Choice1 == "No")
        {
            Console.WriteLine("Thank you for using my program, goodbye ");
            Console.ReadKey();
            Environment.Exit(0);
        }
        else
        {
            Console.WriteLine("That is not an option");
            Console.ReadLine();

        }

    }

    }
}

Body:
Probably your problem is that you don’t make a correct validation of the input.
Now, you read the input from console and compare with a static string so
“Add” is different from “add” and different from “Add(space)“.
I suggest you to make a more strong input validation:

Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
mathChoice = mathChoice.ToUpper().Trim();
//User inputs the 2 numbers

//Math Choices
if (mathChoice == "ADD")
{
     Console.WriteLine("What 2 numbers would you like to use?");
     ....
}


问:
Learn Python the Hard Way ex4
I'm recently follow learn python the hard way to ex4 and a bit confused about it. I use python3.5.2
This is what I typed in my editor and it worked well:

but when I open the file through terminal, it turned out like this:

('There are', 100, 'cars available')
('There are only', 30, 'drivers available')
('There will be', 70, 'empty cars today.')
('we can transport', 90, 'to carpool today.')
('we need to put about', 3, 'in each car.')
```

<p>The result I expect is:</p>

<pre class="lang-none prettyprint-override"><code>There are 100 cars available without the symbols.
</code>```

答:
Your editor and your terminal are using different versions of Python.

In Python 3+, printing a tuple (what you're doing essentially) separates elements by a space.

In Python 2.7, it prints as if it would print a tuple.

This likely is happening because you have both versions installed, but 2.7 appears first in your PATH, so when you invoke Python through the command line, that's what's used. To fix it, just edit your PATH to move the 3+ version up.

This is achieved by the following on Windows 10:

Right click This PC > Properties

Click Advances system settings, on the right

Click Environment Variables...

Double click the PATH user variable

Locate the version of Python you want to be used by default (in your case 3.5.2 - should be in a folder named Python35)

Click that, and click the Move Up button until it's above other Python versions

Do the same for its Scripts folder

Title: Learn Python the Hard Way ex4

Body:
I'm recently follow learn python the hard way to ex4 and a bit confused about it. I use python3.5.2
This is what I typed in my editor and it worked well:

but when I open the file through terminal, it turned out like this:

('There are', 100, 'cars available')
('There are only', 30, 'drivers available')
('There will be', 70, 'empty cars today.')
('we can transport', 90, 'to carpool today.')
('we need to put about', 3, 'in each car.')

The result I expect is:

There are 100 cars available without the symbols.


问:
How to do insert with an exported file
I have the below code exported into a sql file.

```<code>        INSERT INTO `MyGuests` (`id`, `firstname`, `lastname`, `email`, `reg_date`) VALUES
('1', 'John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('2', 'Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('3', 'Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');
</code>```

I want to import it into another data base with same schema but i want it to autoincrement and put the next incremental id in place... can I do this as below just remove the id and sequential nr before importing.?

```<code>                INSERT INTO `HisGuests` (`firstname`, `lastname`, `email`, `reg_date`) VALUES
('John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');
</code>```

Or do i need something like this..

```<code>                INSERT INTO `HisGuests` (`id`, `firstname`, `lastname`, `email`, `reg_date`) VALUES
('', 'John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('', 'Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('', 'Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');
</code>```

I also changed the db name to indicate the new db plus the new db will already have some data so its important that it pickup the next id and continue from that point.. forward.

Thanks in advance..

答:
Use first variant:

```<code>INSERT INTO `HisGuests` (`firstname`, `lastname`, `email`, `reg_date`) VALUES
('John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');
</code>```

Without id field, MySQL will auto increment it.

Title: How to do insert with an exported file

Body:
I have the below code exported into a sql file.

        INSERT INTO `MyGuests` (`id`, `firstname`, `lastname`, `email`, `reg_date`) VALUES
('1', 'John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('2', 'Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('3', 'Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');

I want to import it into another data base with same schema but i want it to autoincrement and put the next incremental id in place... can I do this as below just remove the id and sequential nr before importing.?

                INSERT INTO `HisGuests` (`firstname`, `lastname`, `email`, `reg_date`) VALUES
('John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');

Or do i need something like this..

                INSERT INTO `HisGuests` (`id`, `firstname`, `lastname`, `email`, `reg_date`) VALUES
('', 'John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('', 'Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('', 'Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');

I also changed the db name to indicate the new db plus the new db will already have some data so its important that it pickup the next id and continue from that point.. forward.

Thanks in advance..

Body:
Use first variant:

INSERT INTO `HisGuests` (`firstname`, `lastname`, `email`, `reg_date`) VALUES
('John', 'Doe', 'john@example.com', '2017-06-04 18:39:29'),
('Bill', 'Doe', 'bill@example.com', '2017-06-04 18:42:31'),
('Jane', 'Doe', 'jane@example.com', '2017-06-04 18:42:31');

Without id field, MySQL will auto increment it.


问:
How can I copy the contents of one file to another using Ruby's file methods?
I want to copy the contents of one file to another using Ruby's file methods.

How can I do it using a simple Ruby program using file methods?

答:
You can also use File.binread and File.binwrite if you wish to hold onto the file contents for a bit. (Other answers use an instant copy_stream instead.)

If the contents are other than plain text files, such as images, using basic File.read and File.write won't work.

```<code>temp_image = Tempfile.new('image.jpg')
actual_img = IO.binread('image.jpg')
IO.binwrite(temp_image, actual_img)
</code>```

Source: binread,
binwrite.

Body:
You can also use File.binread and File.binwrite if you wish to hold onto the file contents for a bit. (Other answers use an instant copy_stream instead.)

If the contents are other than plain text files, such as images, using basic File.read and File.write won't work.

temp_image = Tempfile.new('image.jpg')
actual_img = IO.binread('image.jpg')
IO.binwrite(temp_image, actual_img)

Source: binread,
binwrite.


问:
How to select view in IndexedStack
I can't seem to figure out how to select the displayed view for the IndexedStack class. There is an index value but it is final and can't bet set.</p>

答:
You should be calling the IndexedStack constructor in the build() method of a State. Store the index you want in a mutable member variable of your State, e.g. _index, and use _index as the index constructor argument for the IndexedStack. To change the _index to a different value, e.g. newIndex, you can call setState(() { _index = newIndex }); anywhere in your State.

Your call to setState will notify Flutter that your State wants to rebuild itself. At the appropriate time, Flutter will call your build() method and the new value for _index will be used.

You can learn more about widgets and state in the Flutter Widget Tour.

Title: How to select view in IndexedStack


问:
Imported Old site to new url, pages looping on a redirect
I moved my old site to my new url http://www.polestardistribution.com with no problem. Imported the old files, imported the old database, everything was super smooth until I checked the sites pages and posts.

For some reason I have to use the default permalink settings, no other settings will work and throw me into a redirect loop to no where.

Any suggestions would be great, I'm willing to try anything.

I'm using Yahoo! hosting,not by my choice, if that helps.

答: try replacing any instances of your old domain name in your database and .htaccess file with the new domain name.</p>


问:
Installing npm packages in Webstorm 2017.1.3 / Ubuntu 16.04 LTS
When trying to create a new "Node.js Express App" in WebStorm 2017.1.3. / on Ubuntu 16.04 LTS. I get the following error: Please specify npm or yarn package.

So I installed the package globally using

```<code>$ sudo npm install -g express
</code>```

and restarted WebStorm but still no luck.

I then tried the suggestions made in this thread: WebStorm - error: Please specify npm package. Again no luck.

I went on and tried to install the package using WebStorm, but still get the same error message:

Any ideas how I can get this running?

答:
Starting with Express version 4, you should install express-generator.

```<code>npm install express-generator -g
</code>```

More information on using express-generator

Body:
When trying to create a new "Node.js Express App" in WebStorm 2017.1.3. / on Ubuntu 16.04 LTS. I get the following error: Please specify npm or yarn package.

So I installed the package globally using

$ sudo npm install -g express

and restarted WebStorm but still no luck.

I then tried the suggestions made in this thread: WebStorm - error: Please specify npm package. Again no luck.

I went on and tried to install the package using WebStorm, but still get the same error message:

Any ideas how I can get this running?

Body:
Starting with Express version 4, you should install express-generator.

npm install express-generator -g

More information on using express-generator


问:
How to set docker mongo data volume
I want to use Dockerizing MongoDB and store data in local volume.

But .. failed ...

It has mongo:latest images

```<code>kerydeMacBook-Pro:~ hu$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
mongo               latest              b11eedbc330f        2 weeks ago         317.4 MB
ubuntu              latest              6cc0fc2a5ee3        3 weeks ago         187.9 MB
</code>```

I want to store the mono data in ~/data. so ---

```<code>kerydeMacBook-Pro:~ hu$ docker run -p 27017:27017 -v ~/data:/data/db --name mongo -d mongo
f570073fa3104a54a54f39dbbd900a7c9f74938e2e0f3f731ec8a3140a418c43
</code>```

But ... it not work...

docker ps -- no daemon mongo

```<code>kerydeMacBook-Pro:~ hu$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
</code>```

try to run "mongo" --failed

```<code>kerydeMacBook-Pro:~ hu$ docker exec -it f57 bash
Error response from daemon: Container f57 is not running
</code>```

docker inspect mongo

```<code>kerydeMacBook-Pro:~ hu$ docker inspect mongo
[
{
    "Id": "f570073fa3104a54a54f39dbbd900a7c9f74938e2e0f3f731ec8a3140a418c43",
    "Created": "2016-02-15T02:19:01.617824401Z",
    "Path": "/entrypoint.sh",
    "Args": [
        "mongod"
    ],
    "State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 100,
        "Error": "",
        "StartedAt": "2016-02-15T02:19:01.74102535Z",
        "FinishedAt": "2016-02-15T02:19:01.806376434Z"
    },

"Mounts": [
        {
            "Source": "/Users/hushuming/data",
            "Destination": "/data/db",
            "Mode": "",
            "RW": true
        },
        {
            "Name": "365e687c4e42a510878179962bea3c7699b020c575812c6af5a1718eeaf7b57a",
            "Source": "/mnt/sda1/var/lib/docker/volumes/365e687c4e42a510878179962bea3c7699b020c575812c6af5a1718eeaf7b57a/_data",
            "Destination": "/data/configdb",
            "Driver": "local",
            "Mode": "",
            "RW": true
        }
    ],
</code>```

If I do not set data volume, mongo image can work!

But, when setting data volume, it can't. Who can help me?

答:
Via Docker Compose:

```<code>version: '2'
    services:
      mongodb:
        image: mongo:latest
        volumes:
          - ./<your-local-path>:/data/db
</code>```

/data/db is the location of the data saved on the container.

<your-local-path> is the location on your machine AKA the host machine where the actual database journal files will be saved.

Title: How to set docker mongo data volume

Body:
I want to use Dockerizing MongoDB and store data in local volume.

But .. failed ...

It has mongo:latest images

kerydeMacBook-Pro:~ hu$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
mongo               latest              b11eedbc330f        2 weeks ago         317.4 MB
ubuntu              latest              6cc0fc2a5ee3        3 weeks ago         187.9 MB

I want to store the mono data in ~/data. so ---

kerydeMacBook-Pro:~ hu$ docker run -p 27017:27017 -v ~/data:/data/db --name mongo -d mongo
f570073fa3104a54a54f39dbbd900a7c9f74938e2e0f3f731ec8a3140a418c43

But ... it not work...

docker ps -- no daemon mongo

kerydeMacBook-Pro:~ hu$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

try to run "mongo" --failed

kerydeMacBook-Pro:~ hu$ docker exec -it f57 bash
Error response from daemon: Container f57 is not running

docker inspect mongo

kerydeMacBook-Pro:~ hu$ docker inspect mongo
[
{
    "Id": "f570073fa3104a54a54f39dbbd900a7c9f74938e2e0f3f731ec8a3140a418c43",
    "Created": "2016-02-15T02:19:01.617824401Z",
    "Path": "/entrypoint.sh",
    "Args": [
        "mongod"
    ],
    "State": {
        "Status": "exited",
        "Running": false,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 0,
        "ExitCode": 100,
        "Error": "",
        "StartedAt": "2016-02-15T02:19:01.74102535Z",
        "FinishedAt": "2016-02-15T02:19:01.806376434Z"
    },

"Mounts": [
        {
            "Source": "/Users/hushuming/data",
            "Destination": "/data/db",
            "Mode": "",
            "RW": true
        },
        {
            "Name": "365e687c4e42a510878179962bea3c7699b020c575812c6af5a1718eeaf7b57a",
            "Source": "/mnt/sda1/var/lib/docker/volumes/365e687c4e42a510878179962bea3c7699b020c575812c6af5a1718eeaf7b57a/_data",
            "Destination": "/data/configdb",
            "Driver": "local",
            "Mode": "",
            "RW": true
        }
    ],

If I do not set data volume, mongo image can work!

But, when setting data volume, it can't. Who can help me?

Body:
Via Docker Compose:

version: '2'
    services:
      mongodb:
        image: mongo:latest
        volumes:
          - ./<your-local-path>:/data/db

/data/db is the location of the data saved on the container.

<your-local-path> is the location on your machine AKA the host machine where the actual database journal files will be saved.


问:
Bookshelf JS Relation - Getting Count
I'm trying to get users count belongs to specific company.

Here is my model;

```<code>var Company = Bookshelf.Model.extend({
    tableName: 'companies',
    users: function () {
        return this.hasMany(User.Model, "company_id");
    },
    users_count : function(){
        return new User.Model().query(function(qb){
            qb.where("company_id",9);
            qb.count();
        }).fetch();
    },
    organization: function () {
        return this.belongsTo(Organization.Model, "organization_id");
    }
});
</code>```

method "users" works very well, no problem.

method "users_count" query works well, but cant get value to "company" model.

in routes, i'm using bookshelf models like this;

```<code>new Company.Model({id:req.params.id})
            .fetch({withRelated:['users']})
            .then(function(model){
                res.send(model.toJSON())
            })
            .catch(function(error){
                res.send(error);
            });
</code>```

How should i use users_count method, i'm kinda confused (probably because of promises)

答:
Check out the bookshelf-eloquent extension. The withCount() function is probably what you are looking for. Your code would look something like this:</p>

```<code>let company = await Company.where('id', req.params.id)
    .withCount('users').first();
</code>```

Title: Bookshelf JS Relation - Getting Count

Body:
I'm trying to get users count belongs to specific company.

Here is my model;

var Company = Bookshelf.Model.extend({
    tableName: 'companies',
    users: function () {
        return this.hasMany(User.Model, "company_id");
    },
    users_count : function(){
        return new User.Model().query(function(qb){
            qb.where("company_id",9);
            qb.count();
        }).fetch();
    },
    organization: function () {
        return this.belongsTo(Organization.Model, "organization_id");
    }
});

method "users" works very well, no problem.

method "users_count" query works well, but cant get value to "company" model.

in routes, i'm using bookshelf models like this;

new Company.Model({id:req.params.id})
            .fetch({withRelated:['users']})
            .then(function(model){
                res.send(model.toJSON())
            })
            .catch(function(error){
                res.send(error);
            });

How should i use users_count method, i'm kinda confused (probably because of promises)

Body:
Check out the bookshelf-eloquent extension. The withCount() function is probably what you are looking for. Your code would look something like this:

let company = await Company.where('id', req.params.id)
    .withCount('users').first();


问:
fgets() doesn't function as expected
This is my code

```<code>int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");
   scanf("%d",&N);

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}
</code>```

Given inputs are:

```<code>N = 3
red 50,
50 green,
blue 50
</code>```

Here the problem is fgets inside for loop gets executed only twice if N is 3. This problem doesn't arise if I comment the scanf statement. Can somebody explain me what is causing this problem and how it can be solved?

答:
After a few hours of scratching my head, I realized the following:

Avoid using scanf. Managing buffer overflows is not easy.

Always try to use fgets to get user inputs.

Try this code here:

```<code>#include<stdio.h>
#include<stdlib.h>
int main(){
   int N,i,radius,diameter,count =0;
   char str[20];

   printf("Get the num : ");

   char buffer[64];
   fgets(buffer, 64, stdin);
   N = strtoul(buffer,NULL,10);
   char color[N][20];

   printf("%d\n",sizeof(color));

   printf("Enter the mesage\n");

   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
      if(color[i][strlen(color[i])-1]=='\n'){

     color[i][strlen(color[i])-1]='\0';
  }
  else{

     while((getchar())!='\n');//this is just to prevent an overflow for the size of char arrays
  }

   }
   for(i=0;i<N;i++){
      printf("%s\n",color[i]);
  }
  return 0;
}
</code>```

Notice that I first input a number inside a char array. Convert that into a number using strtoul(string to unsigned long). Now inside the for loop I again use fgets to take inputs. The problem was, if you enter a string greater than 19 chars, the remaining part will be left inside the input buffer and shall be assigned to the subsequent input. To manage that I used getchar inside a while loop, which consumes all the unnecessary characters and the newline character from the input stream. Avoid using fflush as it may result in undefined behavior as answered here

-fflush(stdin) function does not work

-http://www.geeksforgeeks.org/clearing-the-input-buffer-in-cc/

Also note that you are using Variable Length Arrays which may not always be a good choice. Older versions of c compiler prohibit them. You had declared color[N][20] first before initializing N. That was wrong.

I suggest you to read this too

-C - scanf() vs gets() vs fgets()

Title: fgets() doesn't function as expected

Body:
This is my code

int main(){
   int N,i,radius,diameter,count =0;
   char str[20];
   char color[N][20];
   printf("Get the num : ");
   scanf("%d",&N);

   printf("Enter the mesage\n");
   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
   }
   for(i=0;i<N;i++){
      printf("%s",color[i]);
  }
  return 0;
}

Given inputs are:

N = 3
red 50,
50 green,
blue 50

Here the problem is fgets inside for loop gets executed only twice if N is 3. This problem doesn't arise if I comment the scanf statement. Can somebody explain me what is causing this problem and how it can be solved?

Body:
After a few hours of scratching my head, I realized the following:

Avoid using scanf. Managing buffer overflows is not easy.

Always try to use fgets to get user inputs.

Try this code here:

#include<stdio.h>
#include<stdlib.h>
int main(){
   int N,i,radius,diameter,count =0;
   char str[20];

   printf("Get the num : ");

   char buffer[64];
   fgets(buffer, 64, stdin);
   N = strtoul(buffer,NULL,10);
   char color[N][20];

   printf("%d\n",sizeof(color));

   printf("Enter the mesage\n");

   for(i=0;i<N;i++){
      fgets(color[i],20,stdin);
      if(color[i][strlen(color[i])-1]=='\n'){

     color[i][strlen(color[i])-1]='\0';
  }
  else{

     while((getchar())!='\n');//this is just to prevent an overflow for the size of char arrays
  }

   }
   for(i=0;i<N;i++){
      printf("%s\n",color[i]);
  }
  return 0;
}

Notice that I first input a number inside a char array. Convert that into a number using strtoul(string to unsigned long). Now inside the for loop I again use fgets to take inputs. The problem was, if you enter a string greater than 19 chars, the remaining part will be left inside the input buffer and shall be assigned to the subsequent input. To manage that I used getchar inside a while loop, which consumes all the unnecessary characters and the newline character from the input stream. Avoid using fflush as it may result in undefined behavior as answered here

-fflush(stdin) function does not work

-http://www.geeksforgeeks.org/clearing-the-input-buffer-in-cc/

Also note that you are using Variable Length Arrays which may not always be a good choice. Older versions of c compiler prohibit them. You had declared color[N][20] first before initializing N. That was wrong.

I suggest you to read this too

-C - scanf() vs gets() vs fgets()


问:
Homebrew: list the packages installed from taps?
Over time, I've installed a number of packages with Homebrew, mostly from the default repo of formulae (homebrew-core), but some from other locations via brew tap.

Now I'm putting together some install scripts to make my dev environment more reproducible, and I'm trying to figure out which packages can be installed by a simple brew install and which require a brew tap beforehand.

The ability to query brew has proved useful for figuring out which options I used for each package, but not for this tap-related question. Is there a way to do this without manually going through each package and seeing where it's available?

答:
I found a couple ways that work.

```<code>brew list --full-name
</code>```

Slower, but a little more informative:

```<code>brew info $(brew list) | grep '^From:' | sort
</code>```

Body:
I found a couple ways that work.

brew list --full-name

Slower, but a little more informative:

brew info $(brew list) | grep '^From:' | sort


答:
Due to this reference:
https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
this will be correct:

```<code>int _tmain(int argc, _TCHAR* argv[])
{
    int N, i, radius, diameter, count = 0;
    char str[10];
    char color[20];
    printf("Get the num : ");
    scanf_s("%d", &N);

    printf("Enter the mesage\n");
    //for (i = 0; i<N; i++){
        fgets(color, 20, stdin);
    //}
    //for (i = 0; i<N; i++){
        printf("%s", color);
    //}
    return 0;
}
</code>```

I changed scanf to scanf_s for VC++.

Title: fgets() doesn't function as expected

Body:
Due to this reference:
https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
this will be correct:

int _tmain(int argc, _TCHAR* argv[])
{
    int N, i, radius, diameter, count = 0;
    char str[10];
    char color[20];
    printf("Get the num : ");
    scanf_s("%d", &N);

    printf("Enter the mesage\n");
    //for (i = 0; i<N; i++){
        fgets(color, 20, stdin);
    //}
    //for (i = 0; i<N; i++){
        printf("%s", color);
    //}
    return 0;
}

I changed scanf to scanf_s for VC++.


问:
Easy way to get daily pageviews (different to each url)?
I need to display daily pageviews in my wordpress site. The problem is I need it to be url aware I mean not count visits for the whole site but just count how many visits the current URL had. Is there an easy way to do so?</p>

答:
http://wordpress.org/extend/plugins/pixelstats/

Counts not only the pageviews but also the RSS viewed articles.


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

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

this is my foreach loop

@foreach($products as $product)

                {{ $product->product_description }}

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

                        @{{price*qty}}

            @endforeach

Problem:

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

Flow:

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

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

Thanks for the answer in advance guys...

I have updated this with my controller code in laravel

public function create()
      {

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

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

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

答:
Instead of using the foreach in blade use a ng-repeat directive. Get the data in the foreach in a json and iterate it in the template.

Before the render of the angular controller make a script:

```<code><script>
  var products = "{{ json_encode($products) }}";
</script>
</code>```

Then in the controller store it as:

```<code>$scope.products = products;
</code>```

Then iterate it:

```<code><p ng-repeat="product in products">
  @{{ product.product_description }}
  @{{ product.price*product.qty}}
</p>
</code>```

Title: AngularJS and Laravel Foreach

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

          Description
          Prices

          Action

        //foreach loop here

this is my foreach loop

@foreach($products as $product)

                {{ $product->product_description }}

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

                        @{{price*qty}}

            @endforeach

Problem:

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

Flow:

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

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

Thanks for the answer in advance guys...

I have updated this with my controller code in laravel

public function create()
      {

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

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

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

Body:
Instead of using the foreach in blade use a ng-repeat directive. Get the data in the foreach in a json and iterate it in the template.

Before the render of the angular controller make a script:

<script>
  var products = "{{ json_encode($products) }}";
</script>

Then in the controller store it as:

$scope.products = products;

Then iterate it:

<p ng-repeat="product in products">
  @{{ product.product_description }}
  @{{ product.price*product.qty}}
</p>


问:
Is it feasible to create a NullObject for every class? ( with a tool of course )
The NullObjectPattern is intended to be a "safe" ( neutral ) behavior.

The idea is create an object that don't do anything ( but doesn't throw NullPointerException either )

For instance the class defined as:

```<code>class Employee {
    private String name;
    private int age;
    public String getName(){ return name; }
    public int getAge()    { return age;  }
}
</code>```

Would cause a NullPointerException in this code:

```<code> class Other {
      Employee oscar;

      String theName = oscar.getName(); // NPE

 }
</code>```

What the NOP says, is you can have an object like this:

```<code> class NullEmployee extends Employee {
      public static final  Employee instance = new NullEmployee();
      public String getName(){ return ""; }
      public int getAge()    { return 0;  }
 }
</code>```

And then use it as the default value.

```<code> Employee oscar = NullEmployee.instance;
</code>```

The problem comes, when you need to repeat the code for every class you create, then a solution would be to have a tool to created it.

Would it be feasible/reasonable/useful  to create such a tool or to use it ( if existed  )?

Perhaps using AOP or DI the default value could be used automagically.

答:
What I'd like to see would be for a compiler to allow one to define the behavior of a null object with a statically-defined type.  For example, if 'Foo' is of class 'bar':

```Class Bar
  Dim Value as Integer
  Function Boz() As Integer
    Return Value
  End Sub
  Sub Nothing.Bar() As Integer
    Return -9
  End Sub
End Class```

attempting to evaluate Foo.Bar() would yield Foo.Value if Foo is non-null, or else -9.  One could achieve some such functionality using extension methods, but that seems a little icky.

Body:
The NullObjectPattern is intended to be a "safe" ( neutral ) behavior.

The idea is create an object that don't do anything ( but doesn't throw NullPointerException either )

For instance the class defined as:

class Employee {
    private String name;
    private int age;
    public String getName(){ return name; }
    public int getAge()    { return age;  }
}

Would cause a NullPointerException in this code:

 class Other {
      Employee oscar;

      String theName = oscar.getName(); // NPE

 }

What the NOP says, is you can have an object like this:

 class NullEmployee extends Employee {
      public static final  Employee instance = new NullEmployee();
      public String getName(){ return ""; }
      public int getAge()    { return 0;  }
 }

And then use it as the default value.

 Employee oscar = NullEmployee.instance;

The problem comes, when you need to repeat the code for every class you create, then a solution would be to have a tool to created it.

Would it be feasible/reasonable/useful  to create such a tool or to use it ( if existed  )?

Perhaps using AOP or DI the default value could be used automagically.

Body:
What I'd like to see would be for a compiler to allow one to define the behavior of a null object with a statically-defined type.  For example, if 'Foo' is of class 'bar':

Class Bar
  Dim Value as Integer
  Function Boz() As Integer
    Return Value
  End Sub
  Sub Nothing.Bar() As Integer
    Return -9
  End Sub
End Class

attempting to evaluate Foo.Bar() would yield Foo.Value if Foo is non-null, or else -9.  One could achieve some such functionality using extension methods, but that seems a little icky.


问:
What's the difference of two tensorflow variable names?
A new beginner of tensorflow and a simple question is:
I saw a code:

```<code>W1 = tf.Variable(tf.zero((2,2)),name="weights")
</code>```

What is the different with "W1" and "weights"?

答:
W1 is the name of the python variable. It is intended for a python interpreter you will use it to address this variable in your code. So if you will need to do some operations (add, multiply, conv, initialize), you will use this name. You can think about it as a pointer which knows where is the location of your tensor.

name='weights' is intended for a human. For a more detailed answer look here. When you will print the python variable you will see this name. It is also used to save/restore the variables and for visualization in tensorboard:

Body:
A new beginner of tensorflow and a simple question is:
I saw a code:

W1 = tf.Variable(tf.zero((2,2)),name="weights")

What is the different with "W1" and "weights"?


问:
NullPointerException despite specifying
I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:

```<code>public JOptionPane version = new JOptionPane();
public String modversion;

public Version()
{
    showVersion();
}

public static void main(String[] args)
{

}

public void showVersion()
{
    //input = version
    String vers = version.showInputDialog("Welche Version soll modifiziert werden?");

    if (vers.equals(null)) {
            return;
    } else {
        if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
        {

          //mod version is saved as String (title for the config list)

            modversion = vers;
            return;
        } else  {
           // with incompatible input the method will be repeated
            JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
            showVersion();
        }
    }
}
</code>```

If you just press "Ok", the input would equal "null":

```<code>if (vers.equals(null)) {
            return;
    }
</code>```

but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?

答:
You can't call .equals() on a null object.

To check if the vers variable is null, you should use vers == null

Title: NullPointerException despite specifying

Body:
I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:

public JOptionPane version = new JOptionPane();
public String modversion;

public Version()
{
    showVersion();
}

public static void main(String[] args)
{

}

public void showVersion()
{
    //input = version
    String vers = version.showInputDialog("Welche Version soll modifiziert werden?");

    if (vers.equals(null)) {
            return;
    } else {
        if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
        {

          //mod version is saved as String (title for the config list)

            modversion = vers;
            return;
        } else  {
           // with incompatible input the method will be repeated
            JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
            showVersion();
        }
    }
}

If you just press "Ok", the input would equal "null":

if (vers.equals(null)) {
            return;
    }

but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?