问:
Cost-sensitive learning in Tensorflow
I am trying to set up a cost-sensitive binary classification learning in TensorFlow, which would put different penalties on false positives and false negatives. Does anyone know how to create a loss function from a set of penalty weights $(w_1, w_2, w_3, w_4)$ for (true positive, false positive, false negative, true negative).

I went over the standard cost functions offered, but can't figure out how to combine them to get something similar to the above.

答:
cost_matrix:

```<code>[[0,1,100],
[1,0,1],
[1,20,0]]
</code>```

label:

```<code>[1,2]
</code>```

y*:

```<code>[[0,1,0],
[0,0,1]]
</code>```

y(prediction):

```<code>[[0.2,0.3,0.5],
[0.1,0.2,0.7]]
</code>```

label,cost_matrix-->cost_embedding:

```<code>[[1,0,1],
[1,20,0]]
</code>```

It obvious 0.3 in [0.2,0.3,0.5] refers to right lable probility of [0,1,0], so it should not contibute to loss.

0.7 in [0.1,0.2,0.7] is the same. In other words, the pos with value 1 in y* not contibute to loss.

So I have (1-y*):

```<code>[[1,0,1],
[1,1,0]]
</code>```

Then the entropy is target*log(predict) + (1-target) * log(1-predict),and value 0 in y*,should use (1-target)*log(1-predict), so I use (1-predict) said (1-y)

1-y:

```<code>[[0.8,*0.7*,0.5],
[0.9,0.8,*0.3*]]
</code>```

(italic num is useless)

the custom loss is

```<code>[[1,0,1], [1,20,0]]   *   log([[0.8,0.7,0.5],[0.9,0.8,0.3]])    *
[[1,0,1],[1,1,0]]
</code>```

and you can see the (1-y*) can be drop here

so the loss is -tf.reduce_mean(cost_embedding*log(1-y))
,to make it applicable , should be:

```<code>-tf.reduce_mean(cost_embedding*log(tf.clip((1-y),1e-10)))
</code>```

the demo is below

```<code>import tensorflow as tf
import numpy as np
hidden_units = 50
num_class = 3
class Model():
    def __init__(self,name_scope,is_custom):
        self.name_scope = name_scope
        self.is_custom = is_custom
        self.input_x = tf.placeholder(tf.float32,[None,hidden_units])
        self.input_y = tf.placeholder(tf.int32,[None])

        self.instantiate_weights()
        self.logits = self.inference()
        self.predictions = tf.argmax(self.logits,axis=1)
        self.losses,self.train_op = self.opitmizer()

    def instantiate_weights(self):
        with tf.variable_scope(self.name_scope + 'FC'):
            self.W = tf.get_variable('W',[hidden_units,num_class])
            self.b = tf.get_variable('b',[num_class])

            self.cost_matrix = tf.constant(
                np.array([[0,1,100],[1,0,100],[20,5,0]]),
                dtype = tf.float32
            )

    def inference(self):
        return tf.matmul(self.input_x,self.W) + self.b

    def opitmizer(self):
        if not self.is_custom:
            loss = tf.nn.sparse_softmax_cross_entropy_with_logits\
                (labels=self.input_y,logits=self.logits)
        else:
            batch_cost_matrix = tf.nn.embedding_lookup(
                self.cost_matrix,self.input_y
            )
            loss = - tf.log(1 - tf.nn.softmax(self.logits))\
                     * batch_cost_matrix

        train_op = tf.train.AdamOptimizer().minimize(loss)
        return loss,train_op

import random
batch_size = 128
norm_model = Model('norm',False)
custom_model = Model('cost',True)
split_point = int(0.9 * dataset_size)
train_set = datasets[:split_point]
test_set = datasets[split_point:]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        batch_index = random.sample(range(split_point),batch_size)
        train_batch = train_set[batch_index]
        train_labels = lables[batch_index]
        _,eval_predict,eval_loss = sess.run([norm_model.train_op,
                  norm_model.predictions,norm_model.losses],
                  feed_dict={
                      norm_model.input_x:train_batch,
                      norm_model.input_y:train_labels
        })
        _,eval_predict1,eval_loss1 = sess.run([custom_model.train_op,
                  custom_model.predictions,custom_model.losses],
                  feed_dict={
                      custom_model.input_x:train_batch,
                      custom_model.input_y:train_labels
        })
        # print '默认',eval_predict,'\n自定义',eval_predict1
        print np.sum(((eval_predict == train_labels)==True).astype(np.int)),\
            np.sum(((eval_predict1 == train_labels)==True).astype(np.int))
        if i%10 == 0:
            print  '默认测试',sess.run(norm_model.predictions,
                  feed_dict={
                      norm_model.input_x:test_set,
                      norm_model.input_y:lables[split_point:]
        })
            print  '自定义测试',sess.run(custom_model.predictions,
                  feed_dict={
                      custom_model.input_x:test_set,
                      custom_model.input_y:lables[split_point:]
        })
</code>```

Title: Cost-sensitive learning in Tensorflow

Body:
cost_matrix:

[[0,1,100],
[1,0,1],
[1,20,0]]

label:

[1,2]

y*:

[[0,1,0],
[0,0,1]]

y(prediction):

[[0.2,0.3,0.5],
[0.1,0.2,0.7]]

label,cost_matrix-->cost_embedding:

[[1,0,1],
[1,20,0]]

It obvious 0.3 in [0.2,0.3,0.5] refers to right lable probility of [0,1,0], so it should not contibute to loss.

0.7 in [0.1,0.2,0.7] is the same. In other words, the pos with value 1 in y* not contibute to loss.

So I have (1-y*):

[[1,0,1],
[1,1,0]]

Then the entropy is target*log(predict) + (1-target) * log(1-predict),and value 0 in y*,should use (1-target)*log(1-predict), so I use (1-predict) said (1-y)

1-y:

[[0.8,*0.7*,0.5],
[0.9,0.8,*0.3*]]

(italic num is useless)

the custom loss is

[[1,0,1], [1,20,0]]   *   log([[0.8,0.7,0.5],[0.9,0.8,0.3]])    *
[[1,0,1],[1,1,0]]

and you can see the (1-y*) can be drop here

so the loss is -tf.reduce_mean(cost_embedding*log(1-y))
,to make it applicable , should be:

-tf.reduce_mean(cost_embedding*log(tf.clip((1-y),1e-10)))

the demo is below

import tensorflow as tf
import numpy as np
hidden_units = 50
num_class = 3
class Model():
    def __init__(self,name_scope,is_custom):
        self.name_scope = name_scope
        self.is_custom = is_custom
        self.input_x = tf.placeholder(tf.float32,[None,hidden_units])
        self.input_y = tf.placeholder(tf.int32,[None])

        self.instantiate_weights()
        self.logits = self.inference()
        self.predictions = tf.argmax(self.logits,axis=1)
        self.losses,self.train_op = self.opitmizer()

    def instantiate_weights(self):
        with tf.variable_scope(self.name_scope + 'FC'):
            self.W = tf.get_variable('W',[hidden_units,num_class])
            self.b = tf.get_variable('b',[num_class])

            self.cost_matrix = tf.constant(
                np.array([[0,1,100],[1,0,100],[20,5,0]]),
                dtype = tf.float32
            )

    def inference(self):
        return tf.matmul(self.input_x,self.W) + self.b

    def opitmizer(self):
        if not self.is_custom:
            loss = tf.nn.sparse_softmax_cross_entropy_with_logits\
                (labels=self.input_y,logits=self.logits)
        else:
            batch_cost_matrix = tf.nn.embedding_lookup(
                self.cost_matrix,self.input_y
            )
            loss = - tf.log(1 - tf.nn.softmax(self.logits))\
                     * batch_cost_matrix

        train_op = tf.train.AdamOptimizer().minimize(loss)
        return loss,train_op

import random
batch_size = 128
norm_model = Model('norm',False)
custom_model = Model('cost',True)
split_point = int(0.9 * dataset_size)
train_set = datasets[:split_point]
test_set = datasets[split_point:]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        batch_index = random.sample(range(split_point),batch_size)
        train_batch = train_set[batch_index]
        train_labels = lables[batch_index]
        _,eval_predict,eval_loss = sess.run([norm_model.train_op,
                  norm_model.predictions,norm_model.losses],
                  feed_dict={
                      norm_model.input_x:train_batch,
                      norm_model.input_y:train_labels
        })
        _,eval_predict1,eval_loss1 = sess.run([custom_model.train_op,
                  custom_model.predictions,custom_model.losses],
                  feed_dict={
                      custom_model.input_x:train_batch,
                      custom_model.input_y:train_labels
        })
        # print '默认',eval_predict,'\n自定义',eval_predict1
        print np.sum(((eval_predict == train_labels)==True).astype(np.int)),\
            np.sum(((eval_predict1 == train_labels)==True).astype(np.int))
        if i%10 == 0:
            print  '默认测试',sess.run(norm_model.predictions,
                  feed_dict={
                      norm_model.input_x:test_set,
                      norm_model.input_y:lables[split_point:]
        })
            print  '自定义测试',sess.run(custom_model.predictions,
                  feed_dict={
                      custom_model.input_x:test_set,
                      custom_model.input_y:lables[split_point:]
        })


来源: stackexchange

问:
NOT BETWEEN in codeigniter not working
I want to ask why the query builder class does not included NOT BETWEEN. The hack i try was this
->where('"mytable.date" not between '." $min_date ".' AND '. "$max_date").

It built this query AND "mytable"."date" "not" between "2017-5-18" AND 2017-6-7.

How can i effectively used this with the codeigniter query builder class or active records.

I am using postgresql driver.

答:
I'm confused about your quotations may you try using this code below instead.

```<code>$this->db->where("mytable.date NOT BETWEEN '$min_date' AND '$max_date'");
</code>```

UPDATE

I tried NOT BETWEEN and really doesn't work. another alternative is

```<code>$this->db->where('mytable.date <=', $min_date);
$this->db->where('mytable.date >=', $max_date);
</code>```

ContentLicense: CC BY-SA 3.0

Title: NOT BETWEEN in codeigniter not working

Body:
I'm confused about your quotations may you try using this code below instead.

$this->db->where("mytable.date NOT BETWEEN '$min_date' AND '$max_date'");

UPDATE

I tried NOT BETWEEN and really doesn't work. another alternative is

$this->db->where('mytable.date <=', $min_date);
$this->db->where('mytable.date >=', $max_date);


问:
ERROR ITMS-90207 Apple Store Submisson
My app works perfectly when I'm running it on the simulator or device (for debug and release build configuration). But when I try to submit my app to the Apple Store I got the following error:

ERROR ITMS-90207: "Invalid Bundle. The bundle at 'APPNAME.app' does
  not contain a bundle executable."

I tried to upload the archive with Xcode and Application Loader, without success.

I have tried some of the solutions found in this topic (Xcode App Submisson ERROR ITMS-90207: "Invalid Bundle) but none of them work with my project:

CFBundleExecutable is declared in my plist file as $(EXECUTABLE_NAME)

I tried to disable Bitcode

I tried to remove all CFBundleExecutable form Pods plist files (keep only the one from my target's plist)

Maybe this error is related to Xcode version... My mac is running macOS Sierra Version 10.12.6 Beta (16G8c), Xcode Version 8.3.2 (8E2002) and Application Loader Version 3.0 (620).

Any help is welcome.

UDPATE:

I try with Xcode 8.2, I have the same error.

Here is my plist file for more detail:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleAllowMixedLocalizations</key>
    <true/>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>APPNAME</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb000000</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>639</string>
    <key>FacebookAppID</key>
    <string>000000</string>
    <key>FacebookDisplayName</key>
    <string>APPNAME</string>
    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSCameraUsageDescription</key>
    <string>Description...</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Description...</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Description...</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>location</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <false/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
</dict>
</plist>
</code>```

UDPATE 2:

I managed to publish the archive from another mac with Xcode 8.2.1.
I try with Xcode version 8.2 an 8.2.1 on my mac, but I still have the same error.
I have also tried Application Loader version 3.0 and 3.6, without success...
So it looks like, the problem comes from my mac. I have no idea what to do.

答:
Ridiculously enough, you also get this error if you try to submit a 9.0 deployment target app with XCode 9.1. Switchting the deployment target to 11.1 "fixed" it.

My hunch is that it is related to this:  https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html

"Deprecations: Apps with a deployment target of iOS 11 no longer build a 32-bit slice. To build and include a 32-bit slice, set the deployment target to an earlier version of iOS. (32163517)"

Title: ERROR ITMS-90207 Apple Store Submisson

Body:
My app works perfectly when I'm running it on the simulator or device (for debug and release build configuration). But when I try to submit my app to the Apple Store I got the following error:

ERROR ITMS-90207: "Invalid Bundle. The bundle at 'APPNAME.app' does
  not contain a bundle executable."

I tried to upload the archive with Xcode and Application Loader, without success.

I have tried some of the solutions found in this topic (Xcode App Submisson ERROR ITMS-90207: "Invalid Bundle) but none of them work with my project:

CFBundleExecutable is declared in my plist file as $(EXECUTABLE_NAME)

I tried to disable Bitcode

I tried to remove all CFBundleExecutable form Pods plist files (keep only the one from my target's plist)

Maybe this error is related to Xcode version... My mac is running macOS Sierra Version 10.12.6 Beta (16G8c), Xcode Version 8.3.2 (8E2002) and Application Loader Version 3.0 (620).

Any help is welcome.

UDPATE:

I try with Xcode 8.2, I have the same error.

Here is my plist file for more detail:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleAllowMixedLocalizations</key>
    <true/>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>APPNAME</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb000000</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>639</string>
    <key>FacebookAppID</key>
    <string>000000</string>
    <key>FacebookDisplayName</key>
    <string>APPNAME</string>
    <key>FirebaseAppDelegateProxyEnabled</key>
    <false/>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSCameraUsageDescription</key>
    <string>Description...</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Description...</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>Description...</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>location</string>
    </array>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <false/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
</dict>
</plist>

UDPATE 2:

I managed to publish the archive from another mac with Xcode 8.2.1.
I try with Xcode version 8.2 an 8.2.1 on my mac, but I still have the same error.
I have also tried Application Loader version 3.0 and 3.6, without success...
So it looks like, the problem comes from my mac. I have no idea what to do.


问:
Parse same JSON String Multiple Times in python
I need to parse the following json output, so I can take parse the Title entries

```<code>[{"Title":"000webhost","Name":"000webhost","Domain":"000webhost.com","BreachDate":"2015-03-01","AddedDate":"2015-10-26T23:35:45Z","ModifiedDate":"2015-10-26T23:35:45Z","PwnCount":13545468,"Description":"In approximately March 2015, the free web hosting provider <a href=\"http://www.troyhunt.com/2015/10/breaches-traders-plain-text-passwords.html\" target=\"_blank\" rel=\"noopener\">000webhost suffered a major data breach</a> that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.","DataClasses":["Email addresses","IP addresses","Names","Passwords"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"png"},{"Title":"Lifeboat","Name":"Lifeboat","Domain":"lbsg.net","BreachDate":"2016-01-01","AddedDate":"2016-04-25T21:51:50Z","ModifiedDate":"2016-04-25T21:51:50Z","PwnCount":7089395,"Description":"In January 2016, the Minecraft community known as Lifeboat <a href=\"https://motherboard.vice.com/read/another-day-another-hack-7-million-emails-and-hashed-passwords-for-minecraft\" target=\"_blank\" rel=\"noopener\">was hacked and more than 7 million accounts leaked</a>. Lifeboat knew of the incident for three months before the breach was made public but elected not to advise customers. The leaked data included usernames, email addresses and passwords stored as straight MD5 hashes.","DataClasses":["Email addresses","Passwords","Usernames"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"svg"}]
</code>```

To parse, this I use the following code :

```<code>cat $myfile | python -c "import sys, json; print json.load(sys.stdin)[0]['Title']"
</code>```

But this results in the output :

000webhost

whereas I need the output to be :

000webhost

Lifeboat

答:
If you want to display all the titles you need to loop over the items in the array. Currently you're asking for the first item [0].

You can do this as a one-liner using a comprehension to extract the titles:

```<code>[item['Title'] for item in json.load(sys.stdin)]
</code>```

And then a loop to print out each title on a separate line:

```<code>for title in [item['Title'] for item in json.load(sys.stdin)]: print title
</code>```

So the complete command line script would be:

```<code>cat $myfile | python -c "import sys, json; for title in [item['Title'] for item in json.load(sys.stdin)]: print title"
</code>```

Body:
I need to parse the following json output, so I can take parse the Title entries

[{"Title":"000webhost","Name":"000webhost","Domain":"000webhost.com","BreachDate":"2015-03-01","AddedDate":"2015-10-26T23:35:45Z","ModifiedDate":"2015-10-26T23:35:45Z","PwnCount":13545468,"Description":"In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.","DataClasses":["Email addresses","IP addresses","Names","Passwords"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"png"},{"Title":"Lifeboat","Name":"Lifeboat","Domain":"lbsg.net","BreachDate":"2016-01-01","AddedDate":"2016-04-25T21:51:50Z","ModifiedDate":"2016-04-25T21:51:50Z","PwnCount":7089395,"Description":"In January 2016, the Minecraft community known as Lifeboat was hacked and more than 7 million accounts leaked. Lifeboat knew of the incident for three months before the breach was made public but elected not to advise customers. The leaked data included usernames, email addresses and passwords stored as straight MD5 hashes.","DataClasses":["Email addresses","Passwords","Usernames"],"IsVerified":true,"IsFabricated":false,"IsSensitive":false,"IsActive":true,"IsRetired":false,"IsSpamList":false,"LogoType":"svg"}]

To parse, this I use the following code :

cat $myfile | python -c "import sys, json; print json.load(sys.stdin)[0]['Title']"

But this results in the output :

000webhost

whereas I need the output to be :

000webhost

Lifeboat

Body:
If you want to display all the titles you need to loop over the items in the array. Currently you're asking for the first item [0].

You can do this as a one-liner using a comprehension to extract the titles:

[item['Title'] for item in json.load(sys.stdin)]

And then a loop to print out each title on a separate line:

for title in [item['Title'] for item in json.load(sys.stdin)]: print title

So the complete command line script would be:

cat $myfile | python -c "import sys, json; for title in [item['Title'] for item in json.load(sys.stdin)]: print title"


问:
insert slected data as Foreign key and SQLSTATE[23000]: Integrity constraint violation: 1048
Thank you for being here!

i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key

I am getting this error :

In my localhost i can see the value it's suppose to return.
And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null

Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }

php file :

```<code> <?php
 header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();

     try{

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
        // Return data as JSON
            echo json_encode($data);
            var_dump($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

        $stmt    = $pdo->prepare($sql);

        $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
        $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
        $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
        $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
        $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
        $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
            $stmt->bindParam(':data', $acc_id, PDO::PARAM_STR);

        $stmt->execute();

         echo json_encode(array('message' => 'Congratulations the record was added to the database'));
   }

    catch(PDOException $e)
     {
        echo $e->getMessage();
     }
?>
</code>```

答:
It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:</p>

```<code><?php

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();

try {

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
    // You do not need to return response from here
    // echo json_encode($data);
    // var_dump($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

    $stmt    = $pdo->prepare($sql);

    // the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
    // notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
    // so, I just added some dummy data.
    $p_fname = 'Patient first name';
    $p_lname = 'Patient last name';
    $p_gender = 'm';
    $p_condition = 'condition';
    $p_birthdate = '1999-01-01';
    $p_emergencycontact = 'Contact';

    $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
    $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
    $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
    $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
    $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
    $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);

    // You do not have any $acc_id variable in your code. To get data from your fetch you need to do
    // like this:
    $stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR);

    $stmt->execute();

    header('Access-Control-Allow-Origin: *');

    // If you want to get the acc_id in your client side through the AJAX call, combine both
    // mesage and data in the same JSON object.
    echo json_encode(
        array(
            'message' => 'Congratulations the record was added to the database'
            'data' => $data
        )
   );
} catch(PDOException $e) {
    // make sure to send the proper status code
    http_response_code(500);
    // even error should be sent back as in json so that your javascript client can
    // easily parse it
    echo json_encode(
        array(
            'error' => $e->getMessage()
        )
    );
}
?>
</code>```

Body:
Thank you for being here!

i want to be able to select acc_id from account_info table and insert it in patient_info table as Foreign Key

I am getting this error :

In my localhost i can see the value it's suppose to return.
And this error which I suppose it occurs because i haven't inserted acc_id yet SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acc_id' cannot be null

Also var_dump($data) returns array(1) { [0]=> object(stdClass)#3 (1) { ["acc_id"]=> int(124) } }

php file :

 <?php
 header('Access-Control-Allow-Origin: *');

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();

     try{

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
        // Return data as JSON
            echo json_encode($data);
            var_dump($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:data, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

        $stmt    = $pdo->prepare($sql);

        $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
        $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
        $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
        $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
        $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
        $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);
            $stmt->bindParam(':data', $acc_id, PDO::PARAM_STR);

        $stmt->execute();

         echo json_encode(array('message' => 'Congratulations the record was added to the database'));
   }

    catch(PDOException $e)
     {
        echo $e->getMessage();
     }
?>

Body:
It seems there are multiple issues in your code or the way you are trying to do things. Please check the code below. It should work. I have added few inline comments. Please check them:

<?php

// Define database connection parameters
$hn      = 'localhost';
$un      = 'root';
$pwd     = '';
$db      = 'ringabell';
$cs      = 'utf8';

// Set up the PDO parameters
$dsn  = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt  = array(
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                   );
// Create a PDO instance (connect to the database)
$pdo  = new PDO($dsn, $un, $pwd, $opt);

// Retrieve specific parameter from supplied URL
$data = array();

try {

    $stmt = $pdo->query('SELECT acc_id FROM account_info ORDER BY acc_id DESC LIMIT 1');
    $data = $stmt->fetchAll(PDO::FETCH_OBJ);
    // You do not need to return response from here
    // echo json_encode($data);
    // var_dump($data);

    $sql= "INSERT INTO patient_info(acc_id, p_fname, p_lname, p_gender, p_condition, p_birthdate, p_emergencycontact)
                            VALUES(:acc_id, :p_fname, :p_lname, :p_gender, :p_condition, :p_birthdate, :p_emergencycontact)";

    $stmt    = $pdo->prepare($sql);

    // the $p_fname, $p_lname, $p_gender etc variables in your code were never initiated. You would get
    // notice for this if you had all error_reporting on. I am not sure from where you intend to get this info;
    // so, I just added some dummy data.
    $p_fname = 'Patient first name';
    $p_lname = 'Patient last name';
    $p_gender = 'm';
    $p_condition = 'condition';
    $p_birthdate = '1999-01-01';
    $p_emergencycontact = 'Contact';

    $stmt->bindParam(':p_fname', $p_fname, PDO::PARAM_STR);
    $stmt->bindParam(':p_lname', $p_lname, PDO::PARAM_STR);
    $stmt->bindParam(':p_gender', $p_gender, PDO::PARAM_STR);
    $stmt->bindParam(':p_condition', $p_condition, PDO::PARAM_STR);
    $stmt->bindParam(':p_birthdate', $p_birthdate, PDO::PARAM_STR);
    $stmt->bindParam(':p_emergencycontact', $p_emergencycontact, PDO::PARAM_STR);

    // You do not have any $acc_id variable in your code. To get data from your fetch you need to do
    // like this:
    $stmt->bindParam(':acc_id', $data[0]->acc_id, PDO::PARAM_STR);

    $stmt->execute();

    header('Access-Control-Allow-Origin: *');

    // If you want to get the acc_id in your client side through the AJAX call, combine both
    // mesage and data in the same JSON object.
    echo json_encode(
        array(
            'message' => 'Congratulations the record was added to the database'
            'data' => $data
        )
   );
} catch(PDOException $e) {
    // make sure to send the proper status code
    http_response_code(500);
    // even error should be sent back as in json so that your javascript client can
    // easily parse it
    echo json_encode(
        array(
            'error' => $e->getMessage()
        )
    );
}
?>


问:
perl from user input of a number, add each digit

I am very new to perl and I am learning this is not like c++. So The user will enter a number of any length, and I want to add each digit and print the sum.

```<code>#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

my @array = $num;
my $sum=0;
for my $arr (@array){

    $sum += $arr;

print $sum;
}
</code>```

 For example the user enters 1234, the sum: 10

the actual result I get is 1234.

答:
You Just need to add two lines

```<code>use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

#You missed out to remove the entermark at the end
chomp($num); my $newnum = "0";

$newnum += $_  for split//, $num;

print $newnum;
</code>```

Note: I didn't override or not considering the method what you have followed however I just did what I know in perl.

Further More details

Body:
I am very new to perl and I am learning this is not like c++. So The user will enter a number of any length, and I want to add each digit and print the sum.

#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

my @array = $num;
my $sum=0;
for my $arr (@array){

    $sum += $arr;

print $sum;
}

 For example the user enters 1234, the sum: 10

the actual result I get is 1234.

Body:
You Just need to add two lines

use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

#You missed out to remove the entermark at the end
chomp($num); my $newnum = "0";

$newnum += $_  for split//, $num;

print $newnum;

Note: I didn't override or not considering the method what you have followed however I just did what I know in perl.

Further More details


问:
is there any way to execute code before the observable emits any item? (for retrying purposes)
i want to retry an observable with its subscription. it all went good but now I'm trying to execute some code every time i retry this observable. any suggestions? </p>

```<code>observableItem.retry(1).subscribeWith(subscriber);
</code>```

答:
You need doOnSubscribe operator that works when observable is subscribed(before observable emit any item).

```<code>...
observableItem
        .doOnSubscribe(subscriber1 -> {
            // Do whatever you want to de before retry.
        })
        .retry(1)
        .subscribeWith(subscriber)
...
</code>```

Note: i have not tested it. Please test it and let me know.

Hope it helps.

Body:
i want to retry an observable with its subscription. it all went good but now I'm trying to execute some code every time i retry this observable. any suggestions?

observableItem.retry(1).subscribeWith(subscriber);

Body:
You need doOnSubscribe operator that works when observable is subscribed(before observable emit any item).

...
observableItem
        .doOnSubscribe(subscriber1 -> {
            // Do whatever you want to de before retry.
        })
        .retry(1)
        .subscribeWith(subscriber)
...

Note: i have not tested it. Please test it and let me know.

Hope it helps.


问:
PHP Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

```<code>$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));
</code>```

My code

```<code><fieldset>
    <legend>New hero</legend>
                    <label for="nom">Nom : </label><input type="text"     name="nom" id="nom" size="40" required><br>
                    <label for="age">Âge : </label><input type="number" name="age" id="age" size="40" required><br>
                    <label for="race">Race : </label><select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> <a href="race.php">Édition des races</a><br>
                    <label for="faction">Faction : </label><select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> <a href="faction.php">Édition des factions</a><br>
                    <label for="description">Description : </label><input type="text" name="description" id="description" size="40" required>
                    <br>
                    <br>
                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    <label for="fichier">Fichier d'image : </label>
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">
                    <img alt="Image" id="preview" title="image" src="#" />
                    <br>
                    <br>
                    <input type="submit" name="action" value="Ajouter">
                </fieldset>
</code>```

答:
```<code><?php
$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter")
{
    $sql="INSERT into `personnage` SET `nom`='$nom',`faction`='$faction',`race`='$race',`age`='$age',`description`='$description',`image`='$fichier'";
    odbc_exec($odbc, $sql) or die(odbc_error($odbc));
}

?>
</code>```

Body:
Error

Warning: odbc_exec(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement., SQL state 37000 in SQLExecDirect in E:\DEP\Prog\PHP6\starcraft\starcraft\personnage_traitement.php on line 61
  [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

SQL query when using the Ajouter action (ADD in english)

$nom =$_POST["nom"];
$faction = $_POST["faction"];
$age = $_POST["age"];
$race = $_POST["race"];
$description = $_POST["description"];
$fichier = $_POST["image"];

if ($_POST["action"] == "Ajouter") {

  $sql="Insert into personnage (nom,  faction, race, age, description, image) values ('$nom', $faction, $race, $age,'$description', '$fichier')";

  odbc_exec($odbc, $sql) or die(odbc_error($odbc));

My code

<fieldset>
    <legend>New hero</legend>
                    Nom : <input type="text"     name="nom" id="nom" size="40" required>

                    Âge : <input type="number" name="age" id="age" size="40" required>

                    Race : <select name="race" id="race" size="1" >
                        <?php
                        $sql2 = "SELECT NomRace FROM Race;";
                        $resultat2 = odbc_exec($odbc, $sql2) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat2, 0);

                        while (odbc_fetch_row($resultat2)) {

                            $idS = odbc_result($resultat2, "IDRace");

                            $race = utf8_encode(odbc_result($resultat2, "NomRace"));

                            echo "<OPTION VALUE=\"$idS\">$race</OPTION>";
                        }
                        ?>
                    </select> Édition des races

                    Faction : <select name="faction" id="faction" size="1" >
                        <?php

                        $sql3 = "SELECT NomFaction FROM Faction;";
                        $resultat3 = odbc_exec($odbc, $sql3) or die(odbc_error($odbc));

                        odbc_fetch_row($resultat3, 0);

                        while (odbc_fetch_row($resultat3)) {

                            $idS = odbc_result($resultat3, "IDFaction");

                            $faction = utf8_encode(odbc_result($resultat3, "NomFaction"));

                            echo "<OPTION VALUE=\"$idS\">$faction</OPTION>";
                        }
                        ?>
                    </select> Édition des factions

                    Description : <input type="text" name="description" id="description" size="40" required>

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000">
                    Fichier d'image :
                    <input type="file" onchange="readURL(this);" name="fichier" id="fichier">

                    <input type="submit" name="action" value="Ajouter">
                </fieldset>


问:
Javascript chart pick sum data from database
Helloooo Guys, im stuck with something
I have a single line chart that should pick data from specific column on database sum it and display it in chart

```<code> <script>
           var ctx = document.getElementById('myChart').getContext('2d');
 var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',

// The data for our dataset
data: {
    labels: ["January", "February", "March", "April", "May", "June", "July", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
    datasets: [{
        label: "Vanzare Lunara",
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        data: [600, 800, 100, 16, 20, 21, 22, 23, 25, 26, 26],
    }]
},

// Configuration options go here
options: {}
});
</script>
</code>```

This is the script that picks the data (600, 800, 100, etc)

the database name is highmob_comenzi  it needs to pick data from 2 tables and colums and sum it
table 1 - players , column totalvanzare

table 2 - vanzari , column totalvanzare

any ideea how to do it? :(

答:
Well first you need to make a database call obviously that will get the sum of whatever it is. Then you can do this:

```<code>$.ajax({
    url: 'url',
    type: 'POST', //Change this base on your requirement
    data: { 'data', 'some data if you need' },
    success: function (data) {
      var lineChartData = {
            labels: ["January", "February", "March", "April", "May", "June", "July", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
            datasets: [
                {
                    label: "Data set 1",
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgb(23,127,255)",
                    pointColor: "rgb(23,127,255)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [data1, data2, data3]
                }
            ]

        }

        var options =
        {
            showTooltips: true,
            onAnimationComplete: function () { this.showTooltip(this.datasets[0].points, true); render(); },
            tooltipEvents: [],
            responsive: true,
            scaleFontColor: "#5BC236",
            scaleColor: "#000"
        }

        var ctx = document.getElementById("graph1").getContext("2d");
        var chart = new Chart(ctx).Line(lineChartData, options);
    }

function render() {
    var url = document.getElementById("graph1").toDataURL();
    document.getElementById("url1").src = url;
}
</code>```

Hope this helps.

Body:
Helloooo Guys, im stuck with something
I have a single line chart that should pick data from specific column on database sum it and display it in chart

This is the script that picks the data (600, 800, 100, etc)

the database name is highmob_comenzi  it needs to pick data from 2 tables and colums and sum it
table 1 - players , column totalvanzare

table 2 - vanzari , column totalvanzare

any ideea how to do it? :(

Body:
Well first you need to make a database call obviously that will get the sum of whatever it is. Then you can do this:

$.ajax({
    url: 'url',
    type: 'POST', //Change this base on your requirement
    data: { 'data', 'some data if you need' },
    success: function (data) {
      var lineChartData = {
            labels: ["January", "February", "March", "April", "May", "June", "July", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
            datasets: [
                {
                    label: "Data set 1",
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgb(23,127,255)",
                    pointColor: "rgb(23,127,255)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [data1, data2, data3]
                }
            ]

        }

        var options =
        {
            showTooltips: true,
            onAnimationComplete: function () { this.showTooltip(this.datasets[0].points, true); render(); },
            tooltipEvents: [],
            responsive: true,
            scaleFontColor: "#5BC236",
            scaleColor: "#000"
        }

        var ctx = document.getElementById("graph1").getContext("2d");
        var chart = new Chart(ctx).Line(lineChartData, options);
    }

function render() {
    var url = document.getElementById("graph1").toDataURL();
    document.getElementById("url1").src = url;
}

Hope this helps.


问:
How could I connect a program with interface in python
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

```<code>#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()
</code>```

This is the code of my python script:

```<code>#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))
</code>```

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?

答: If you want to processes to 'talk' to each other, you can use the subprocesses module in the Python Standard Library. </p>

Body:
I want to use tkinter to set a interface for my another program, but I do not know what is my next step.

I do not know how to connect each other.

I do not have that concept.

This is the code of trying to be a interface:

#!/usr/bin/env python -O
import subprocess
from tkinter import *
subprocess.call('/Users/Tsu-
AngChou/MasterProject/Practice/try_test/TEST5.py')

root = Tk(className ="Documents retriever")
svalue = StringVar() # defines the widget state as string
w = Entry(root,textvariable=svalue) # adds a textarea widget
w.pack()
def act():
    print ("you entered")
    print ('%s' % svalue.get())
foo = Button(root,text="Retrieve", command=act)
foo.pack()
root.mainloop()

This is the code of my python script:

#!/usr/bin/env python
import string
import os
from bs4 import BeautifulSoup as bs
from os import listdir
from os.path import isfile, join

mypath = "/Users/Tsu-AngChou/MasterProject/Practice/try_test/"
files = listdir(mypath)
storage = {}
translator = str.maketrans("","",string.punctuation)
for f in files:
  fullpath = join(mypath, f)
  if f == '.DS_Store':
            os.remove(f)
  elif isfile(fullpath):

    print(f)
    for html_cont in range(1):
        response = open(f,'r',encoding='utf-8')
        html_cont = response.read()
        soup = bs(html_cont, 'html.parser')
        regular_string = soup.get_text()
        new_string = regular_string.translate(translator).split()
        new_list = [item[:14] for item in new_string]
        a = dict.fromkeys(new_list, f)
        b = a
        storage.update(a)
        print(a)
        storage.append(new_list)

        wordfreq = []
        for w in new_list:
            wordfreq.append(new_list.count(w))
        print("Frequency:\n" ,list(zip(b,wordfreq)))

I want to use the value(a) and value(list(zip(b,wordfreq))
How could I give the Button value?


问:
Highlight rows if date is more than some time in past with AngularJS ng-repeat
I have a small web app using Bootstrap & AngularJS to display table data received remotely via JSON api request. Table are generated with ng-repeat. On of the columns contains date of the last update named 'last_seen'. I want to highlight rows where this field are more than 1 hour in past from the current date.

Searching for examples here or on the web most suggests using Date() object or AngularJS 'date' filter. Based on these I've managed to achieve desired result with this code:

```<code>    <script type="text/javascript">
    var dataApp = angular.module('dataApp', []);
    dataApp.controller('dataShow', function($scope, $http, $filter) {
        $http.get('api.php').success(function(data) {
            $scope.Data = data;
        })
        $scope.DangerDate = new Date() - 1000*60*60; // now - 1 hour
        $scope.dangerDate = $filter('date')($scope.DangerDate, 'yyyy-MM-dd HH:mm:ss');
    });
</script>
</code>```

'

```<code>    <div ng-app="dataApp" ng-controller="dataShow" class="panel-body">
        <div class="panel panel-default">
            <table class="table table-striped table-hover" id="output">
                <thead>
                    <tr>
                        <th class="{{header}}" ng-repeat="(header, value) in Data[0]"></i></th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="row in Data" ng-class="{ danger: row.last_seen <= dangerDate }">
                        <td ng-repeat="cell in row">{{cell}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</code>```

But these examples didn't compared date directly in HTML template like I did with row.last_seen <= dangerDate.

I also don't really like the way I've used to get 'current date - 1 hour' with JS - creating Date() object, subtracting seconds from it to get that and then using $filter to convert that to text value.

Is that ok to do those things or there is a better way?

答:
Your proplem isnt about angular but getting date comparison to work in javascript.
Below code will be helpful of understanding how such thing works.

```<code>var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!)
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
</code>```

Credits to @moonshadow from the this post ->.
source: Compare two dates with JavaScript

After converting your dates to new Date(); objects you can compare them within the

```<code>ng-class="{ danger: row.last_seen_withdateobject.getTime() <= dangerDate.getTime() }"
</code>```

Your code would have looked like this. Implying the logic. ( as far as I understood ) Your want to show posts highlighted that are 1 hour or much older than that.What I would do

set seperately for each row foreaching;

```<code>row.last_seen2 = new Date() - 1000*60*60;
$scope.now = new Date();

ng-class="{ danger: row.last_seen2.getTime() - now.getTime() }"
</code>```

check out this little fiddle I created for your demonstrating your needs and play with the hours and minutes to see how it works..
https://jsfiddle.net/xykqxmpy/6/

Body:
I have a small web app using Bootstrap & AngularJS to display table data received remotely via JSON api request. Table are generated with ng-repeat. On of the columns contains date of the last update named 'last_seen'. I want to highlight rows where this field are more than 1 hour in past from the current date.

Searching for examples here or on the web most suggests using Date() object or AngularJS 'date' filter. Based on these I've managed to achieve desired result with this code:

'

                    <tr ng-repeat="row in Data" ng-class="{ danger: row.last_seen <= dangerDate }">
                        {{cell}}

But these examples didn't compared date directly in HTML template like I did with row.last_seen <= dangerDate.

I also don't really like the way I've used to get 'current date - 1 hour' with JS - creating Date() object, subtracting seconds from it to get that and then using $filter to convert that to text value.

Is that ok to do those things or there is a better way?

Body:
Your proplem isnt about angular but getting date comparison to work in javascript.
Below code will be helpful of understanding how such thing works.

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!)
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

Credits to @moonshadow from the this post ->.
source: Compare two dates with JavaScript

After converting your dates to new Date(); objects you can compare them within the

ng-class="{ danger: row.last_seen_withdateobject.getTime() <= dangerDate.getTime() }"

Your code would have looked like this. Implying the logic. ( as far as I understood ) Your want to show posts highlighted that are 1 hour or much older than that.What I would do

set seperately for each row foreaching;

row.last_seen2 = new Date() - 1000*60*60;
$scope.now = new Date();

ng-class="{ danger: row.last_seen2.getTime() - now.getTime() }"

check out this little fiddle I created for your demonstrating your needs and play with the hours and minutes to see how it works..
https://jsfiddle.net/xykqxmpy/6/


问:
How do I swap endian-ness (byte order) of a variable in javascript
I am receiving and sending a decimal representation of two little endian numbers. I would like to:

shift one variable 8 bits left

OR them

shift a variable number of bits

create 2 8 bit numbers representing the first and second half of the 16 bit number.

javascript (according to https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators) uses big endian representation when shifting...

endianness is a bit foreign to me (I am only 90 percent sure that my outlined steps are what i want.) so swapping is a bit dizzying. please help! I only really need to know how to swap the order in an efficient manner. (I can only think of using a for loop on a toString() return value)

答:
Such function can be used to change endianness in js:</p>

```<code>const changeEndianness = (string) => {
        const result = [];
        let len = string.length - 2;
        while (len >= 0) {
          result.push(string.substr(len, 2));
          len -= 2;
        }
        return result.join('');
}

changeEndianness('AA00FF1234'); /// '3412FF00AA'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Such function can be used to change endianness in js:

const changeEndianness = (string) => {
        const result = [];
        let len = string.length - 2;
        while (len >= 0) {
          result.push(string.substr(len, 2));
          len -= 2;
        }
        return result.join('');
}

changeEndianness('AA00FF1234'); /// '3412FF00AA'


问:
JIT optimization in scenario combining inline and non-mutable boolean module property
In the following program,

```<code>module Program

let condition = System.DateTime.Now.Millisecond % 2 = 0

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    reliesOnConditional System.DateTime.Now.Second
    0
</code>```

will the JIT optimize away the expression reliesOnCondition System.DateTime.Now.Second if condition turns out to be false upon module loading?

答:
No*. When F# emits the IL for the program, all accesses to condition are done through a property accessor. Because of this extra layer of indirection the JIT engine cannot optimize away the entire body of reliesOnCondition.

Let me show how I found this out. (Also listed on an old blog post.)

Create new F# Project 'SOQ'

Build our F# application. I just hard-coded condition to be false.

```<code>module Program

let condition = false

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    printfn "(attach a debugger and press any key)"
    System.Console.ReadKey(true) |> ignore

    reliesOnCondition System.DateTime.Now.Second
    0
</code>```

Disassemble it and reassemble it with IL opcodes in the PDB

Next use ildasm to disassemble the IL binary using the /SOURCE parameter. This will not only get you an IL dump of the source, but also include the original source code left as comments.

```<code>ildasm SOQ.exe /OUT=SOQ-annotated.exe.il /SOURCE
</code>```

Reassemble our binary from IL

Next use ilasm to reassemble the IL binary, but passing in the /DEBUG flag to get a PDB. The resulting application will have two levels of code. First, the origonal F# will be left in as comments, and the actual code will be IL instructions.

```<code>ilasm SOQ-annotated.exe.il /DEBUG
</code>```

Run the process and attach the Visual Studio debugger

Run the newly annotated program. This will cause the application to get JIT-ted like normal. Next, attach the Visual Studio debugger to the active process.

Step through the code

Looking at an IL dump in the VS debugger isn't sufficient. Right click the 'Stack Traces' window and check Go To Disassembly. This will give you a display of the actual x86-instructions.

Here is the x86 op code dump. Note the original F# source line up top (ildasm /SOURCE), the IL instructions beneath that (ilasm /DEBUG), and the x86 instructions below that (courtesy of Visual Studio).

```<code>//000014:     reliesOnCondition System.DateTime.Now.Second
    IL_0026:  call       valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
000000db  lea         ecx,[ebp-58h]
000000de  call        595E8C00
    IL_002b:  stloc.3
000000e3  lea         edi,[ebp-30h]
000000e6  lea         esi,[ebp-58h]
000000e9  movq        xmm0,mmword ptr [esi]
000000ed  movq        mmword ptr [edi],xmm0
    IL_002c:  ldloca.s   V_3
000000f1  lea         eax,[ebp-30h]
000000f4  mov         dword ptr [ebp-74h],eax
    IL_002e:  call       instance int32 [mscorlib]System.DateTime::get_Second()
000000f7  mov         ecx,dword ptr [ebp-74h]
000000fa  call        5960A670
000000ff  mov         dword ptr [ebp-5Ch],eax
    IL_0033:  stloc.2
00000102  mov         eax,dword ptr [ebp-5Ch]
00000105  mov         dword ptr [ebp-28h],eax
    IL_0034:  call       bool Program::get_condition()
00000108  call        dword ptr ds:[004232D8h]
0000010e  mov         dword ptr [ebp-60h],eax
    IL_0039:  brfalse.s  IL_003d
00000111  cmp         dword ptr [ebp-60h],0
00000115  je          0000011A
... snip ...
</code>```

As you can see, the IL instruction 34 calls Program::get_condition(), so the JIT doesn't have enough information to properly eliminate the no-op function call. (Note that only functions can be marked inline, so you can't really go any further than this.)

*On my machine (x64 Win7). There is a difference between the x86 and x64 JIT engines as well as whether or not you used NGEN to produce your executable. Your mileage may vary.

Body:
In the following program,

module Program

let condition = System.DateTime.Now.Millisecond % 2 = 0

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    reliesOnConditional System.DateTime.Now.Second
    0

will the JIT optimize away the expression reliesOnCondition System.DateTime.Now.Second if condition turns out to be false upon module loading?

Body:
No*. When F# emits the IL for the program, all accesses to condition are done through a property accessor. Because of this extra layer of indirection the JIT engine cannot optimize away the entire body of reliesOnCondition.

Let me show how I found this out. (Also listed on an old blog post.)

Create new F# Project 'SOQ'

Build our F# application. I just hard-coded condition to be false.

module Program

let condition = false

let inline reliesOnCondition (x:int) =
    if condition then
        printfn "%i" x

[<EntryPoint>]
let main args =
    printfn "(attach a debugger and press any key)"
    System.Console.ReadKey(true) |> ignore

    reliesOnCondition System.DateTime.Now.Second
    0

Disassemble it and reassemble it with IL opcodes in the PDB

Next use ildasm to disassemble the IL binary using the /SOURCE parameter. This will not only get you an IL dump of the source, but also include the original source code left as comments.

ildasm SOQ.exe /OUT=SOQ-annotated.exe.il /SOURCE

Reassemble our binary from IL

Next use ilasm to reassemble the IL binary, but passing in the /DEBUG flag to get a PDB. The resulting application will have two levels of code. First, the origonal F# will be left in as comments, and the actual code will be IL instructions.

ilasm SOQ-annotated.exe.il /DEBUG

Run the process and attach the Visual Studio debugger

Run the newly annotated program. This will cause the application to get JIT-ted like normal. Next, attach the Visual Studio debugger to the active process.

Step through the code

Looking at an IL dump in the VS debugger isn't sufficient. Right click the 'Stack Traces' window and check Go To Disassembly. This will give you a display of the actual x86-instructions.

Here is the x86 op code dump. Note the original F# source line up top (ildasm /SOURCE), the IL instructions beneath that (ilasm /DEBUG), and the x86 instructions below that (courtesy of Visual Studio).

//000014:     reliesOnCondition System.DateTime.Now.Second
    IL_0026:  call       valuetype [mscorlib]System.DateTime [mscorlib]System.DateTime::get_Now()
000000db  lea         ecx,[ebp-58h]
000000de  call        595E8C00
    IL_002b:  stloc.3
000000e3  lea         edi,[ebp-30h]
000000e6  lea         esi,[ebp-58h]
000000e9  movq        xmm0,mmword ptr [esi]
000000ed  movq        mmword ptr [edi],xmm0
    IL_002c:  ldloca.s   V_3
000000f1  lea         eax,[ebp-30h]
000000f4  mov         dword ptr [ebp-74h],eax
    IL_002e:  call       instance int32 [mscorlib]System.DateTime::get_Second()
000000f7  mov         ecx,dword ptr [ebp-74h]
000000fa  call        5960A670
000000ff  mov         dword ptr [ebp-5Ch],eax
    IL_0033:  stloc.2
00000102  mov         eax,dword ptr [ebp-5Ch]
00000105  mov         dword ptr [ebp-28h],eax
    IL_0034:  call       bool Program::get_condition()
00000108  call        dword ptr ds:[004232D8h]
0000010e  mov         dword ptr [ebp-60h],eax
    IL_0039:  brfalse.s  IL_003d
00000111  cmp         dword ptr [ebp-60h],0
00000115  je          0000011A
... snip ...

As you can see, the IL instruction 34 calls Program::get_condition(), so the JIT doesn't have enough information to properly eliminate the no-op function call. (Note that only functions can be marked inline, so you can't really go any further than this.)

*On my machine (x64 Win7). There is a difference between the x86 and x64 JIT engines as well as whether or not you used NGEN to produce your executable. Your mileage may vary.


问:
vs 2017 could not connect to Team Foundation Service server
I recently installed vs 2017 enterprise on my local win-10 computer. But when I try to connect to my remote tfs server through Team Explorer, It pop out a error message which said that " An attempt was made to access a socket in a way forbidden by its access permission xxxxxxxxx", here "xxxx" is my remote server IP address. I think there must be some settings on my computer or VS settings that cause the problem, as I can connect to the servier through VS 2012. Is there any one who could help me solving this? Much thanks in advance.</p>

答:
According to the error info, it sounds like your connections for VS 2017 are being interrupted by your network. Are you behind a proxy or do you have some network security software running?

Suggest you move the proxy and temporarily disable your anti virus software. Then try to connect TFS and use VS2017 again.

In many cases when folks see this sort of behavior it's because they had network security exemptions for VS 2015 and none for 2017; please double check if that's the case

Our authentication scheme has also changed for 2017 from 2015 where
  the latter used credential cookies and the former is now using bearer
  authentication tokens. The two have different headers and we've seen
  some proxy software strip the bearer tokens from outgoing packets
  where it didn't do so for the 2015-and-before token headers.

Besides, also update your vs 2017 enterprise to latest version.


问:
Can new objects be instantiated without the = new Obj ()?
So String isn't a primitive type but rather a class and objects of classes have to be created in the form Obj x = new Obj (); usually. However, strings can be created by saying String x = "..."; and this is the preferred way rather than String x = new String ("...");.

So I was wondering why this is allowed for strings and would it be possible to create objects of other classes in a similar fashion if the constructor only required a single parameter.

For example, if a class had a constructor that only called one integer, would saying Obj x = 2; be syntactically correct because it has the object name and parameter still included in the same way that Strings are written.

答:
So String isn't a primitive type but rather a class and objects of classes have to be created in the form Obj x = new Obj (); usually. However, strings can be created by saying String x = "..."; and this is the preferred way rather than String x = new String ("...");

That's correct, it often a mistake to use new String(String). Since Strings are such a common type of value to create that Java, like most languages, has a string literal grammar construct. When evaluated the string literal expression returns a string instance representing the text.

Calling String y = new String("...") is roughly equivalent to String x = "..."; String y = new String(x);: the string literal evaluated to a string which was then supplied to a String constructor that returned a new string instance (albeit using the same backing character array to avoid copying data) - such a waste! As such the new String(String) constructor should probably "never" be called, with the exception of wishing to do something special wrt. string interning.

So I was wondering why this is allowed for strings and would it be possible to create objects of other classes in a similar fashion if the constructor only required a single parameter.

It is a special aspect of Java grammar, and most other languages, to create string objects with minimal fuss. It would be very annoying to have to create strings out of other values: new String(new char[] {'n','o',' ','t','h','a','n','k','s'}).

Java does not have support for custom parsing and thus it is not possible to extend this behavior to custom types in Java itself. The grammar of string literals (and behavior during execution) is covered in the Java Language Specification.

The very creation of string objects from string literals is largely "JVM magic / implementation details" (creation of strings from literals do not call the new String(String) constructor as then, how is the original string instance created?). Furthermore, the string object instances returned from evaluating string literals are not guaranteed to be unique / "new" per string interning rules.

For example if a class had a constructor that only called one integer, would saying Obj x = 2; be syntactically correct because it has the object name and parameter still included in the same way that Strings are written.

This is not how Java works. A language that did work as hypothesized would not be Java 8.

In this example the integer literal is 2: when evaluated as an expression it yields the value .. (int)2. Unlike with the case of a string literal, Java then performs an Integer autoboxing operation: 2 is an int which, unlike String, is not an Object and cannot be directly assigned. This makes the original similar to Object x = new Integer(2); where the int-value has been implicitly wrapped as an Integer-value.


问:
How can I compare all the values of an enum with a given array in java?
I have an enum class with values:

```<code>  enum carBrand{BMW,HONDA,MERC,AUDI};
</code>```

And there's an array called Sales with Array values:

```<code> sales[] = {CHEVVY, BMW , MERC, AUDI};
</code>```

So how could I check that the sales[] has all the values of enum carBrand?

I'm trying to put it in a for loop as:

```<code> for(int i = 0; i<sales.length;i++){
     if(carBrand.sales == sales[i]){
        return true;
     }
 return false;
 }
</code>```

答:
```<code>public class Enumeration {

    enum carBrand{BMW,HONDA,MERC,AUDI};

    public static void main(String[] args) {

        String sales[] = {"CHEVVY", "BMW" , "MERC", "AUDI"};

        for(carBrand brand:carBrand.values()) {
            boolean bran=false;
            for(int i=0;i<sales.length;i++) {
                if(brand.toString()==sales[i]) {
                    bran=true;
                    break;
                }
            }
            if(!bran==true) {
                System.out.println("Sales doesn't have " +brand);
            }
        }

    }
}
</code>```

Body:
I have an enum class with values:

  enum carBrand{BMW,HONDA,MERC,AUDI};

And there's an array called Sales with Array values:

 sales[] = {CHEVVY, BMW , MERC, AUDI};

So how could I check that the sales[] has all the values of enum carBrand?

I'm trying to put it in a for loop as:

 for(int i = 0; i<sales.length;i++){
     if(carBrand.sales == sales[i]){
        return true;
     }
 return false;
 }


问:
Sending Email with attachment from Asset folder
```<code>    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));
</code>```

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?

答:
You can not share Asset folder file to other application without ContentProvider. You can send file which can be accesible for every application.like some whare in intenal phone memory or sd card.

Sharing Asset Check This Answer of @CommonsWare

Or
Read your text file and use @RonTLV Answer and mail.

Or
Copy File in intenal memory and add to sending launch.
Hope this answer will help.

Body:
    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?


问:
YYYYMMDD Date Format regular Expression to validate a date in C# .net
I need to validate the date format using regular expression in C#.

Here is the format: "YYYYMMDD"

答:
Regular expressions aren't suitable for this task. It is difficult for example to write a regular expression that matches the valid date "20080229" but not the invalid date "20100229".

Instead you should use DateTime.TryParseExact with the format string "yyyyMMdd". Here is an example:

```<code>string s = "20100229";
DateTime result;
if (!DateTime.TryParseExact(
     s,
     "yyyyMMdd",
     CultureInfo.InvariantCulture,
     DateTimeStyles.AssumeUniversal,
     out result))
{
    Console.WriteLine("Invalid date entered.");
};
</code>```

Body:
Regular expressions aren't suitable for this task. It is difficult for example to write a regular expression that matches the valid date "20080229" but not the invalid date "20100229".

Instead you should use DateTime.TryParseExact with the format string "yyyyMMdd". Here is an example:

string s = "20100229";
DateTime result;
if (!DateTime.TryParseExact(
     s,
     "yyyyMMdd",
     CultureInfo.InvariantCulture,
     DateTimeStyles.AssumeUniversal,
     out result))
{
    Console.WriteLine("Invalid date entered.");
};


问:
SQL Inner Join for calculated column
I would like to set sales year to date to automatically equal the sum of invoice headers where the account codes equal.

```<code>ALTER TABLE DEBTORS_MASTER
    ALTER COLUMN Sales_Year_To_Date AS
          (SELECT SUM (INVOICE_HEADER.Total_Sell_Amount_Excl_VAT)
           FROM DEBTORS_MASTER
           INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE);
</code>```

I get this error

Incorrect syntax near the keyword 'AS'

答:
I think you have to do it seperately

Alter statement

```<code>ALTER TABLE DEBTORS_MASTER
ALTER COLUMN Sales_Year_To_Date INT
</code>```

Update statement

```<code>UPDATE t1
SET Sales_Year_To_Date = Sales_Year_To_Date
FROM DEBTORS_MASTER t1
INNER JOIN (
    SELECT SUM(INVOICE_HEADER.Total_Sell_Amount_Excl_VAT) AS Sales_Year_To_Date
    FROM DEBTORS_MASTER
    INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE
    ) t2 ON t2.ACCOUNT_CODE = t1.ACCOUNT_CODE
</code>```

Title: SQL Inner Join for calculated column

Body:
I would like to set sales year to date to automatically equal the sum of invoice headers where the account codes equal.

ALTER TABLE DEBTORS_MASTER
    ALTER COLUMN Sales_Year_To_Date AS
          (SELECT SUM (INVOICE_HEADER.Total_Sell_Amount_Excl_VAT)
           FROM DEBTORS_MASTER
           INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE);

I get this error

Incorrect syntax near the keyword 'AS'

Body:
I think you have to do it seperately

Alter statement

ALTER TABLE DEBTORS_MASTER
ALTER COLUMN Sales_Year_To_Date INT

Update statement

UPDATE t1
SET Sales_Year_To_Date = Sales_Year_To_Date
FROM DEBTORS_MASTER t1
INNER JOIN (
    SELECT SUM(INVOICE_HEADER.Total_Sell_Amount_Excl_VAT) AS Sales_Year_To_Date
    FROM DEBTORS_MASTER
    INNER JOIN DEBTORS_MASTER ON INVOICE_HEADER.Account_Code = DEBTORS_MASTER.ACCOUNT_CODE
    ) t2 ON t2.ACCOUNT_CODE = t1.ACCOUNT_CODE


问:
Calender.getInstance() gives error in Android Studio
I'm trying to pop-open a DatePicker dialogue box when my EditText is clicked. The problem is, when I try to instantiate my Calender object with Calender.getInstance() the creepy-red-underline appears below getInstance().

```<code>Calender myCalender = Calender.getInstance();
</code>```

Hover over it and it says

Call requires API level 24(current minimum is 15).

Obviously I expect my app to run on devices at the minimum API level 15. Please help me with this, I'm new to Android. Thank you.

I tried to follow this method to add a DatePicker to my EditText

答:
```<code>This code will help  you to solve your problem..
It will pop-open a DatePicker dialogue box when onClick EditText box:

1) MainActivity.java

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.icu.text.DateFormat;
import android.icu.util.Calendar;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity
{
    EditText editText1;
    private int nYear,nMonth,nDay,sYear,sMonth,sDay;
    static final int DATE_ID = 0;
    Calendar c = Calendar.getInstance();

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

        editText1 = (EditText) findViewById(R.id.editText1);
        sYear = c.get(Calendar.YEAR);
        sMonth = c.get(Calendar.MONTH);
        sDay = c.get(Calendar.DAY_OF_MONTH);
        //editText
        editText1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog(DATE_ID);
            }
        });

    /***************calender code*****************/
    private void calender_fetch()
    {
        editText1.setText((nMonth+1)+"/"+nDay+"/"+nYear+"");
    }

    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            nYear = year;
            nMonth = monthOfYear;
            nDay = dayOfMonth;
            calender_fetch();
        }
    };
    @Override
    protected Dialog onCreateDialog(int id)
    {
        switch (id)
        {
            case DATE_ID:
                return new DatePickerDialog(this, mDateSetListener, sYear, sMonth, sDay);
        }
        return null;
    }
    /*************************calender close*********************************/
</code>```

Body:
I'm trying to pop-open a DatePicker dialogue box when my EditText is clicked. The problem is, when I try to instantiate my Calender object with Calender.getInstance() the creepy-red-underline appears below getInstance().

Calender myCalender = Calender.getInstance();

Hover over it and it says

Call requires API level 24(current minimum is 15).

Obviously I expect my app to run on devices at the minimum API level 15. Please help me with this, I'm new to Android. Thank you.

I tried to follow this method to add a DatePicker to my EditText


问:
background image not taking up full width
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

```<code><html>
  <body>
    <div class="background">
      <div class=“header”></div>
      //some content
    </div>
    <footer><footer/>
  </body>
 </html>
</code>```

CSS

```<code>.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}
</code>```

答:
It is working with background-size:100%;

```<code>.background {
background-image: url("marakele-elephant1.jpg");
background-size: 100%;
background-repeat: no-repeat;
background-position-y: bottom;
</code>```

}

Body:
I am currently positioning a background image that is small in height but large in width to stretch all the way across the browser. I am only able to achieve this when I do background size cover, but not when I set a certain size to the image other than cover. I tried background repeat-x but that does not seem to work either.

      //some content

CSS

.background {
    background-image: url(some image);
    background-size: //tried cover and it works but not when I set it to width 100% or something like 2800px
    background-repeat: repeat-x;
    background-position-y: bottom;
}
html, body, .background {
    height: 100%;
}

Body:
It is working with background-size:100%;

.background {
background-image: url("marakele-elephant1.jpg");
background-size: 100%;
background-repeat: no-repeat;
background-position-y: bottom;

}


问:
Cost-sensitive loss function in Tensorflow
I'm doing research for cost-sensitive neural network based on Tensorflow. But because of the static graph structure of Tensorflow. Some NN structure couldn't be realized by myself.

My loss function(cost) ,cost matrix and the computational progress is described as follow and my target is to compute the total cost and then optimize the NN :

Approximately computational progress:

the y_ is the last full-connect output of a CNN which has shape (1024,5)

the y is a Tensor which has shape(1024) and indicates the ground truth of x[i]

the y_soft[i] [j] indicates the probability of x[i] to be class j

How can I realize this in Tensorflow?

答:
cost_matrix:

```<code>[[0,1,100],
[1,0,1],
[1,20,0]]
</code>```

label:

```<code>[1,2]
</code>```

y*:

```<code>[[0,1,0],
[0,0,1]]
</code>```

y(prediction):

```<code>[[0.2,0.3,0.5],
[0.1,0.2,0.7]]
</code>```

label,cost_matrix-->cost_embedding:

```<code>[[1,0,1],
[1,20,0]]
</code>```

It obvious 0.3 in [0.2,0.3,0.5] refers to right lable probility of [0,1,0], so it should not contibute to loss.

0.7 in [0.1,0.2,0.7] is the same. In other words, the pos with value 1 in y* not contibute to loss.

So I have (1-y*):

```<code>[[1,0,1],
[1,1,0]]
</code>```

Then the entropy is target*log(predict) + (1-target) * log(1-predict),and value 0 in y*,should use (1-target)*log(1-predict), so I use (1-predict) said (1-y)

1-y:

```<code>[[0.8,*0.7*,0.5],
[0.9,0.8,*0.3*]]
</code>```

(italic num is useless)

the custom loss is

```<code>[[1,0,1], [1,20,0]]   *   log([[0.8,0.7,0.5],[0.9,0.8,0.3]])    *
[[1,0,1],[1,1,0]]
</code>```

and you can see the (1-y*) can be drop here

so the loss is -tf.reduce_mean(cost_embedding*log(1-y))
,to make it applicable , should be:

```<code>-tf.reduce_mean(cost_embedding*log(tf.clip((1-y),1e-10)))
</code>```

the demo is below

```<code>import tensorflow as tf
import numpy as np
hidden_units = 50
num_class = 3
class Model():
    def __init__(self,name_scope,is_custom):
        self.name_scope = name_scope
        self.is_custom = is_custom
        self.input_x = tf.placeholder(tf.float32,[None,hidden_units])
        self.input_y = tf.placeholder(tf.int32,[None])

        self.instantiate_weights()
        self.logits = self.inference()
        self.predictions = tf.argmax(self.logits,axis=1)
        self.losses,self.train_op = self.opitmizer()

    def instantiate_weights(self):
        with tf.variable_scope(self.name_scope + 'FC'):
            self.W = tf.get_variable('W',[hidden_units,num_class])
            self.b = tf.get_variable('b',[num_class])

            self.cost_matrix = tf.constant(
                np.array([[0,1,100],[1,0,100],[20,5,0]]),
                dtype = tf.float32
            )

    def inference(self):
        return tf.matmul(self.input_x,self.W) + self.b

    def opitmizer(self):
        if not self.is_custom:
            loss = tf.nn.sparse_softmax_cross_entropy_with_logits\
                (labels=self.input_y,logits=self.logits)
        else:
            batch_cost_matrix = tf.nn.embedding_lookup(
                self.cost_matrix,self.input_y
            )
            loss = - tf.log(1 - tf.nn.softmax(self.logits))\
                     * batch_cost_matrix

        train_op = tf.train.AdamOptimizer().minimize(loss)
        return loss,train_op

import random
batch_size = 128
norm_model = Model('norm',False)
custom_model = Model('cost',True)
split_point = int(0.9 * dataset_size)
train_set = datasets[:split_point]
test_set = datasets[split_point:]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        batch_index = random.sample(range(split_point),batch_size)
        train_batch = train_set[batch_index]
        train_labels = lables[batch_index]
        _,eval_predict,eval_loss = sess.run([norm_model.train_op,
                  norm_model.predictions,norm_model.losses],
                  feed_dict={
                      norm_model.input_x:train_batch,
                      norm_model.input_y:train_labels
        })
        _,eval_predict1,eval_loss1 = sess.run([custom_model.train_op,
                  custom_model.predictions,custom_model.losses],
                  feed_dict={
                      custom_model.input_x:train_batch,
                      custom_model.input_y:train_labels
        })
        # print 'norm',eval_predict,'\ncustom',eval_predict1
        print np.sum(((eval_predict == train_labels)==True).astype(np.int)),\
            np.sum(((eval_predict1 == train_labels)==True).astype(np.int))
        if i%10 == 0:
            print  'norm_test',sess.run(norm_model.predictions,
                  feed_dict={
                      norm_model.input_x:test_set,
                      norm_model.input_y:lables[split_point:]
        })
            print  'custom_test',sess.run(custom_model.predictions,
                  feed_dict={
                      custom_model.input_x:test_set,
                      custom_model.input_y:lables[split_point:]
        })
</code>```

Body:
cost_matrix:

[[0,1,100],
[1,0,1],
[1,20,0]]

label:

[1,2]

y*:

[[0,1,0],
[0,0,1]]

y(prediction):

[[0.2,0.3,0.5],
[0.1,0.2,0.7]]

label,cost_matrix-->cost_embedding:

[[1,0,1],
[1,20,0]]

It obvious 0.3 in [0.2,0.3,0.5] refers to right lable probility of [0,1,0], so it should not contibute to loss.

0.7 in [0.1,0.2,0.7] is the same. In other words, the pos with value 1 in y* not contibute to loss.

So I have (1-y*):

[[1,0,1],
[1,1,0]]

Then the entropy is target*log(predict) + (1-target) * log(1-predict),and value 0 in y*,should use (1-target)*log(1-predict), so I use (1-predict) said (1-y)

1-y:

[[0.8,*0.7*,0.5],
[0.9,0.8,*0.3*]]

(italic num is useless)

the custom loss is

[[1,0,1], [1,20,0]]   *   log([[0.8,0.7,0.5],[0.9,0.8,0.3]])    *
[[1,0,1],[1,1,0]]

and you can see the (1-y*) can be drop here

so the loss is -tf.reduce_mean(cost_embedding*log(1-y))
,to make it applicable , should be:

-tf.reduce_mean(cost_embedding*log(tf.clip((1-y),1e-10)))

the demo is below

import tensorflow as tf
import numpy as np
hidden_units = 50
num_class = 3
class Model():
    def __init__(self,name_scope,is_custom):
        self.name_scope = name_scope
        self.is_custom = is_custom
        self.input_x = tf.placeholder(tf.float32,[None,hidden_units])
        self.input_y = tf.placeholder(tf.int32,[None])

        self.instantiate_weights()
        self.logits = self.inference()
        self.predictions = tf.argmax(self.logits,axis=1)
        self.losses,self.train_op = self.opitmizer()

    def instantiate_weights(self):
        with tf.variable_scope(self.name_scope + 'FC'):
            self.W = tf.get_variable('W',[hidden_units,num_class])
            self.b = tf.get_variable('b',[num_class])

            self.cost_matrix = tf.constant(
                np.array([[0,1,100],[1,0,100],[20,5,0]]),
                dtype = tf.float32
            )

    def inference(self):
        return tf.matmul(self.input_x,self.W) + self.b

    def opitmizer(self):
        if not self.is_custom:
            loss = tf.nn.sparse_softmax_cross_entropy_with_logits\
                (labels=self.input_y,logits=self.logits)
        else:
            batch_cost_matrix = tf.nn.embedding_lookup(
                self.cost_matrix,self.input_y
            )
            loss = - tf.log(1 - tf.nn.softmax(self.logits))\
                     * batch_cost_matrix

        train_op = tf.train.AdamOptimizer().minimize(loss)
        return loss,train_op

import random
batch_size = 128
norm_model = Model('norm',False)
custom_model = Model('cost',True)
split_point = int(0.9 * dataset_size)
train_set = datasets[:split_point]
test_set = datasets[split_point:]

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(100):
        batch_index = random.sample(range(split_point),batch_size)
        train_batch = train_set[batch_index]
        train_labels = lables[batch_index]
        _,eval_predict,eval_loss = sess.run([norm_model.train_op,
                  norm_model.predictions,norm_model.losses],
                  feed_dict={
                      norm_model.input_x:train_batch,
                      norm_model.input_y:train_labels
        })
        _,eval_predict1,eval_loss1 = sess.run([custom_model.train_op,
                  custom_model.predictions,custom_model.losses],
                  feed_dict={
                      custom_model.input_x:train_batch,
                      custom_model.input_y:train_labels
        })
        # print 'norm',eval_predict,'\ncustom',eval_predict1
        print np.sum(((eval_predict == train_labels)==True).astype(np.int)),\
            np.sum(((eval_predict1 == train_labels)==True).astype(np.int))
        if i%10 == 0:
            print  'norm_test',sess.run(norm_model.predictions,
                  feed_dict={
                      norm_model.input_x:test_set,
                      norm_model.input_y:lables[split_point:]
        })
            print  'custom_test',sess.run(custom_model.predictions,
                  feed_dict={
                      custom_model.input_x:test_set,
                      custom_model.input_y:lables[split_point:]
        })


问:
ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN
I have installed "erlang" and "rabbitmq" in my windows 7 machine. But when I am trying to run this code I am getting One exception.

```<code>package com.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class SendMessage {
  private final static String QUEUE_NAME = "hello";
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");
    channel.close();
    connection.close();
  }
}
</code>```

I am getting this Exception.

Exception in thread "main" com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED -
  Login was refused using authentication mechanism PLAIN. For details
  see the broker logfile.

This is the log:

11-Apr-2016::12:45:06 === Adding vhost 'localhost'

=INFO REPORT==== 11-Apr-2016::14:08:52 === accepting AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672)

=ERROR REPORT==== 11-Apr-2016::14:08:52 === Error on AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672, state: starting):

=INFO REPORT==== 11-Apr-2016::14:08:52 === closing AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672)

When I am trying to list the users I am not getting any existing user and add_user is also not working in cmd link

答:
you can create new user (userA) and password (userA123).

And set

```<code>factory.setHost("your_pc_ip");
factory.setUsername("userA");
factory.setPassword("userA123");
</code>```

in sender and receiver classes.

Body:
I have installed "erlang" and "rabbitmq" in my windows 7 machine. But when I am trying to run this code I am getting One exception.

package com.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class SendMessage {
  private final static String QUEUE_NAME = "hello";
  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");
    channel.close();
    connection.close();
  }
}

I am getting this Exception.

Exception in thread "main" com.rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED -
  Login was refused using authentication mechanism PLAIN. For details
  see the broker logfile.

This is the log:

11-Apr-2016::12:45:06 === Adding vhost 'localhost'

=INFO REPORT==== 11-Apr-2016::14:08:52 === accepting AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672)

=ERROR REPORT==== 11-Apr-2016::14:08:52 === Error on AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672, state: starting):

=INFO REPORT==== 11-Apr-2016::14:08:52 === closing AMQP connection <0.360.0> (127.0.0.1:55327 -> 127.0.0.1:5672)

When I am trying to list the users I am not getting any existing user and add_user is also not working in cmd link

Body:
you can create new user (userA) and password (userA123).

And set

factory.setHost("your_pc_ip");
factory.setUsername("userA");
factory.setPassword("userA123");

in sender and receiver classes.