问:
Image alignment using Homography with reduced opacity
I have a program to align two images using homography. I am using cv2 in python. Here is the code I am using:

```<code>import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)
</code>```

The above code works fine. Now I want to reduce the opacity of im_dst in im_out (say opacity=0.5), so that I can see both im_src and im_dst in im_out.
How to do that?

I checked a lot online and most use cv2.addWeighted, but I want reduced opacity of im_dst in cv2.warpPerspective, not just simple overlaying.

I am new to openCV, so I might be missing something simple. Thanks for help!

EDIT:

I tried the below to decrease the opacity of im_dst but all I am getting is a blackened wrapped image

```<code>import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
img1 = np.array(im_dst , dtype=np.float)
img2 = np.array(im_src , dtype=np.float)
img1 /= 255.0
# pre-multiplication
a_channel = np.ones(img1.shape, dtype=np.float)/2.0
im_dst = img1*a_channel
im_src = img2*(1-a_channel)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)
</code>```

答:
Finally got the solution! To get what I want we should add the faded and warped image to the destination image and output that. Also, its better to use getPerspectiveTransform() when we have four matching points, and findHomography() when we have more than four.

```<code>import cv2
import numpy as np

# Read source image.
im_src = cv2.imread('src.jpg')
# Four corners of the book in source image
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)

# Read destination image.
im_dst = cv2.imread('dst.jpg')
# Four corners of the book in destination image.
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

# Calculate Homography
h = cv2.getPerspectiveTransform(pts_src, pts_dst)

# Warp source image to destination based on homography
warp_src = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

# Blend the warped image and the destination image
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, warp_src, beta, 0.0)

# Show the output
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)
</code>```

Body:
I have a program to align two images using homography. I am using cv2 in python. Here is the code I am using:

import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)

The above code works fine. Now I want to reduce the opacity of im_dst in im_out (say opacity=0.5), so that I can see both im_src and im_dst in im_out.
How to do that?

I checked a lot online and most use cv2.addWeighted, but I want reduced opacity of im_dst in cv2.warpPerspective, not just simple overlaying.

I am new to openCV, so I might be missing something simple. Thanks for help!

EDIT:

I tried the below to decrease the opacity of im_dst but all I am getting is a blackened wrapped image

import cv2
import numpy as np
im_src = cv2.imread('src.jpg')
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])
im_dst = cv2.imread('dst.jpg')
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]])
h, status = cv2.findHomography(pts_src, pts_dst)
img1 = np.array(im_dst , dtype=np.float)
img2 = np.array(im_src , dtype=np.float)
img1 /= 255.0
# pre-multiplication
a_channel = np.ones(img1.shape, dtype=np.float)/2.0
im_dst = img1*a_channel
im_src = img2*(1-a_channel)
im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))
cv2.imshow("Warped Image", im_out)
cv2.waitKey(0)

Body:
Finally got the solution! To get what I want we should add the faded and warped image to the destination image and output that. Also, its better to use getPerspectiveTransform() when we have four matching points, and findHomography() when we have more than four.

import cv2
import numpy as np

# Read source image.
im_src = cv2.imread('src.jpg')
# Four corners of the book in source image
pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]], dtype=np.float32)

# Read destination image.
im_dst = cv2.imread('dst.jpg')
# Four corners of the book in destination image.
pts_dst = np.array([[318, 256],[534, 372],[316, 670],[73, 473]], dtype=np.float32)

# Calculate Homography
h = cv2.getPerspectiveTransform(pts_src, pts_dst)

# Warp source image to destination based on homography
warp_src = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))

# Blend the warped image and the destination image
alpha = 0.5
beta = (1.0 - alpha)
dst_warp_blended = cv2.addWeighted(im_dst, alpha, warp_src, beta, 0.0)

# Show the output
cv2.imshow('Blended destination and warped image', dst_warp_blended)
cv2.waitKey(0)


来源: stackexchange

问:
Invalid argument supplied for foreach() laravel using whereIn (laravel 5.3)
I am getting ids using jquery in my controller its as

```<code>if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }
</code>```

I try dd($ids)

Output is as in my console

```<code>array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]
</code>```

When i pass ids to my query as

Query

```<code>$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');
</code>```

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

答:
Change:

```<code>where('students.id', '=', $ids)
</code>```

To:

```<code>whereIn('students.id', $ids);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting ids using jquery in my controller its as

if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }

I try dd($ids)

Output is as in my console

array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]

When i pass ids to my query as

Query

$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

Body:
Change:

where('students.id', '=', $ids)

To:

whereIn('students.id', $ids);


问:
is getOpenGLMatrix changing rotation?
It looks like btTransform::getOpenGLMatrix is changing orientation.
The sign of x is flipped, but I don't find anything about this in the docs for getOpenGLMatrix.</p>

```<code>auto t = btTransform( btQuaternion(0.7,0,0,0.7), bt(0,0,0));
glm::mat4 ogl_t;
t.getOpenGLMatrix(glm::value_ptr(ogl_t));

glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;

glm::decompose(ogl_t,scale,orientation,translation,skew,perspective); // returns true

assert(fabs(orientation.x - 0.7 ) < 0.02); // fails because x is -0.7
</code>```

答:
It can be the same orientation.

Let's look at Quaternion's definition [x y z w]: -

```<code>// RotationAngle is in radians
x = RotationAxis.x * sin(RotationAngle / 2)
y = RotationAxis.y * sin(RotationAngle / 2)
z = RotationAxis.z * sin(RotationAngle / 2)
w = cos(RotationAngle / 2)
</code>```

Example : [x=0.7,y=0,z=0,w=0.7] is the same as [x=-0.7,y=0,z=0,w=-0.7]

Thus, your experimental result is not an evidence that orientation is changed.

Read more :

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/  (long article)

https://math.stackexchange.com/questions/765363/can-different-quaternions-represent-the-same-orientation    (proof)

Title: is getOpenGLMatrix changing rotation?

Body:
It looks like btTransform::getOpenGLMatrix is changing orientation.
The sign of x is flipped, but I don't find anything about this in the docs for getOpenGLMatrix.

auto t = btTransform( btQuaternion(0.7,0,0,0.7), bt(0,0,0));
glm::mat4 ogl_t;
t.getOpenGLMatrix(glm::value_ptr(ogl_t));

glm::vec3 scale;
glm::quat orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;

glm::decompose(ogl_t,scale,orientation,translation,skew,perspective); // returns true

assert(fabs(orientation.x - 0.7 ) < 0.02); // fails because x is -0.7

Body:
It can be the same orientation.

Let's look at Quaternion's definition [x y z w]: -

// RotationAngle is in radians
x = RotationAxis.x * sin(RotationAngle / 2)
y = RotationAxis.y * sin(RotationAngle / 2)
z = RotationAxis.z * sin(RotationAngle / 2)
w = cos(RotationAngle / 2)

Example : [x=0.7,y=0,z=0,w=0.7] is the same as [x=-0.7,y=0,z=0,w=-0.7]

Thus, your experimental result is not an evidence that orientation is changed.

Read more :

http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/  (long article)

https://math.stackexchange.com/questions/765363/can-different-quaternions-represent-the-same-orientation    (proof)


问:
Why we create new thread and use join() to make parent thread waiting?
After reading about join method I've some doubt: I think multithreading is a way to introduce parallelism in our program and believe some time we need some thread finished before another. But I don't understand why a programmer write something like this:

```<code> public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.start();

    t1.join();

    t2.start();

    t2.join();
}
</code>```

whats the advantage of using thread in this example vs below code:

```<code>public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.run();//just run the task of thread without start new thread
    t2.run();
}
</code>```

in first example main thread should pause until t1 finished and then start t2 and wait until finished and in second example it happen too.

Why we create new thread and use join() to make parent thread waiting? why can't use parent thread instead of new thread?

答:
The first way doesn't take profit of multi threading.

We could write it with a single thread, it changes nothing in terms of multi threading :

```<code>Thread t1 = new Thread(new MyRunnable(), "t1");
t1.start();
t1.join();

t1 = new Thread(new MyRunnable(), "t2");
t1.start();
t1.join();
</code>```

The second way that uses t1.run(); instead of  t1.start();
doesn't start the thread and so these :

```<code>t1.run();
t2.run();
</code>```

are simple synchronous (blocking) calls to the Thread objects.

Only after t1.run() is returned, t2.run() is invoked.

Body:
After reading about join method I've some doubt: I think multithreading is a way to introduce parallelism in our program and believe some time we need some thread finished before another. But I don't understand why a programmer write something like this:

 public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.start();

    t1.join();

    t2.start();

    t2.join();
}

whats the advantage of using thread in this example vs below code:

public static void main(String[] args) {
    Thread t1 = new Thread(new MyRunnable(), "t1");
    Thread t2 = new Thread(new MyRunnable(), "t2");

    t1.run();//just run the task of thread without start new thread
    t2.run();
}

in first example main thread should pause until t1 finished and then start t2 and wait until finished and in second example it happen too.

Why we create new thread and use join() to make parent thread waiting? why can't use parent thread instead of new thread?

Body:
The first way doesn't take profit of multi threading.

We could write it with a single thread, it changes nothing in terms of multi threading :

Thread t1 = new Thread(new MyRunnable(), "t1");
t1.start();
t1.join();

t1 = new Thread(new MyRunnable(), "t2");
t1.start();
t1.join();

The second way that uses t1.run(); instead of  t1.start();
doesn't start the thread and so these :

t1.run();
t2.run();

are simple synchronous (blocking) calls to the Thread objects.

Only after t1.run() is returned, t2.run() is invoked.


问:
Firebase (FCM) Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001
I'm trying to use FCM for notification.

But <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" occurs so I can't get notification.
What's the problem?

At the console,

    Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

and below is my code on Appdelegate

```<code>import UIKit
import CoreData
import Alamofire
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var badgeCount : Int = 0;

    enum BasicValidity : String {
        case Success = "basicInfo"
        case Fail = "OauthAuthentificationError"
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        let uns: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(uns)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        if let token = FIRInstanceID.instanceID().token() {
            sendTokenToServer(token)
            print("token is < \(token) >:")
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){

        print("didRegisterForRemoteNotificationsWithDeviceToken()")

        // if FirebaseAppDelegateProxyEnabled === NO:
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)

        print("APNS: <\(deviceToken)>")
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){

         print("Registration for remote notification failed with error: \(error.localizedDescription)")
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){

        print("didReceiveRemoteNotification()")

        //if FirebaseAppDelegateProxyEnabled === NO:
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

       // handler(.NoData)

    }

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        print("tokenRefreshNotification()")
        if let token = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(token)")
            sendTokenToServer(token)
            FIRMessaging.messaging().subscribeToTopic("/topics/global")
            print("Subscribed to: /topics/global")
        }
        connectToFcm()
    }
    // [END refresh_token]

    func sendTokenToServer(currentToken: String) {
        print("sendTokenToServer() Token: \(currentToken)")
        // Send token to server ONLY IF NECESSARY
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error!)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

       // UIApplication.sharedApplication().applicationIconBadgeNumber = 0
         connectToFcm()

    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }
</code>```

I can get notification from Firebase consol if I send notifications by using bundle ID. But I can't get if our server send notification to specific device with token.

答:
It sounds like the server you're using to deliver the remote notification may have an old record of your FCM token. The Google FCM docs state that the FCM token can be rotated (changed) when:

The app is restored on a new device

The user uninstalls/reinstall the app

The user clears app data.

They quote that its good practice to update your server's record of this token using a delegate callback method:

```<code>func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // Send the token to your server here
}
</code>```

That method wasn't working for me, so I had to update it manually on every app launch (after a delay of about 20-25s as the rotation isn't always instant). You can do this with:

```<code>let token = Messaging.messaging().fcmToken  // Send this to your server
</code>```

After these changes I still get the warning console log message, but push notifications work perfectly every time.

Body:
I'm trying to use FCM for notification.

But <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)" occurs so I can't get notification.
What's the problem?

At the console,

    Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

and below is my code on Appdelegate

import UIKit
import CoreData
import Alamofire
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var badgeCount : Int = 0;

    enum BasicValidity : String {
        case Success = "basicInfo"
        case Fail = "OauthAuthentificationError"
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        let uns: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(uns)
        application.registerForRemoteNotifications()

        FIRApp.configure()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification), name: kFIRInstanceIDTokenRefreshNotification, object: nil)

        if let token = FIRInstanceID.instanceID().token() {
            sendTokenToServer(token)
            print("token is < \(token) >:")
        }

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){

        print("didRegisterForRemoteNotificationsWithDeviceToken()")

        // if FirebaseAppDelegateProxyEnabled === NO:
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .Sandbox)

        print("APNS: <\(deviceToken)>")
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){

         print("Registration for remote notification failed with error: \(error.localizedDescription)")
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){

        print("didReceiveRemoteNotification()")

        //if FirebaseAppDelegateProxyEnabled === NO:
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

       // handler(.NoData)

    }

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        print("tokenRefreshNotification()")
        if let token = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(token)")
            sendTokenToServer(token)
            FIRMessaging.messaging().subscribeToTopic("/topics/global")
            print("Subscribed to: /topics/global")
        }
        connectToFcm()
    }
    // [END refresh_token]

    func sendTokenToServer(currentToken: String) {
        print("sendTokenToServer() Token: \(currentToken)")
        // Send token to server ONLY IF NECESSARY
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connectWithCompletion { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error!)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

       // UIApplication.sharedApplication().applicationIconBadgeNumber = 0
         connectToFcm()

    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

I can get notification from Firebase consol if I send notifications by using bundle ID. But I can't get if our server send notification to specific device with token.

Body:
It sounds like the server you're using to deliver the remote notification may have an old record of your FCM token. The Google FCM docs state that the FCM token can be rotated (changed) when:

The app is restored on a new device

The user uninstalls/reinstall the app

The user clears app data.

They quote that its good practice to update your server's record of this token using a delegate callback method:

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // Send the token to your server here
}

That method wasn't working for me, so I had to update it manually on every app launch (after a delay of about 20-25s as the rotation isn't always instant). You can do this with:

let token = Messaging.messaging().fcmToken  // Send this to your server

After these changes I still get the warning console log message, but push notifications work perfectly every time.


问:
Cordova can't create app package for windows Store
I'm creating an app with cordova and I need to release it on the windows store (is already in the App store and in the process to be released on the play store so the app itself is working) so I've cloned my cordova app on a windows machine downloaded the Microsoft Visual Studio 2017 community edition and created a new project from existing code selecting apache cordova in the wizard.

And I can run the app on emulator and a real device but when I try to "Project" -> "Store" -> "Create App Packages..." I always fail the verification but the strange thing is that it looks that all the test are passed but at the end I got an error suggesting to check in the folder: "C:\Users[$user]\AppData\Local\Microsoft\AppCertKit" for the log but the AppcertKit folder dosen't even exist and even if I create a new one is always empty.

If I try to upload the .appxupload file created in  "\platforms\windows\AppPackages" I get always two errors about:
Invalid package family name
Invalid package publisher name: CN=Apache Cordova Team (expected

even if I select the remote app in the wizard for the creation of the packages.

I'm using:
Visual Studio 2017 15.2
Cordova (6.3.1 / 6.5 / 7.0.1) I've tried all of them.
Windows 10 Pro

答:
If I try to upload the .appxupload file created in
  "\platforms\windows\AppPackages" I get always two errors about:
  Invalid package family name Invalid package publisher name: CN=Apache
  Cordova Team (expected even if I select the remote app in the wizard
  for the creation of the packages.

According to the submission error, the identity info of your package cannot be recognized by Dev Center.

To upload your package, you need to associate your project with the app name you reserved in Dev Center to match the identity info:

For more details, you can refer to Package your Windows version Cordova app.


问:
How to convert all elements in an array to integer in JavaScript?
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

```<code>var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");
</code>```

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

答:
ECMAScript5 provides a map method for Arrays, applying a function to all elements of an array.
Here is an example:

var a = ['1','2','3']
var result = a.map(function (x) {
  return parseInt(x, 10);
});

console.log(result);```

See Array.prototype.map()

ContentLicense: CC BY-SA 4.0

Body:
I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

Body:
ECMAScript5 provides a map method for Arrays, applying a function to all elements of an array.
Here is an example:

var a = ['1','2','3']
var result = a.map(function (x) {
  return parseInt(x, 10);
});

console.log(result);

See Array.prototype.map()


问:
Form with Post Method and enctype Multipart/form-data is not being submitted on Nodejs Express multer module
I am using :

```<code>"ejs": "^2.5.6",
"express": "^4.14.0",
"express-validator": "^3.2.0",
"multer": "^1.3.0",
</code>```

My form is :

```<code>     <form id="offer-form" role="form" enctype="multipart/form-data" action="/subfolder/86" method="POST">
    <input type="text" name="name"/>
    <input type="file" name="images"/>
<input type="file" name="images"/>
    <button type="submit">Submit</submit>
    </form>
</code>```

My server route:

```<code>var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

  //Adding a new subfolder
        app.post('/subfolder/:id', multer.array({ name: 'images', maxCount: 6 }), expressValidator, function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });
</code>```

Normally this code should print on the console the message

Form submitted
  but the server is receiving nothing not even
  Not Found

I have just noticed the problem is with using multer and expressValidator. If I remove expressValidator, it is working but if I add it, it is not working. I need expressValidator to validate user data. Is there any other validator which will accept to be used with multer?

答:
I found the solution of using both of these middlewares, I just called the before the action and called the express-validator after calling multer:</p>

```<code>var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

app.get('/home',function(req,res){
console.log("Welcome Brother");
})
.use(multer.array({ name: 'images', maxCount: 6 });
.use(expressValidator);
.post('/subfolder/:id', function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });
</code>```

Body:
I am using :

"ejs": "^2.5.6",
"express": "^4.14.0",
"express-validator": "^3.2.0",
"multer": "^1.3.0",

My form is :

     <form id="offer-form" role="form" enctype="multipart/form-data" action="/subfolder/86" method="POST">
    <input type="text" name="name"/>
    <input type="file" name="images"/>
<input type="file" name="images"/>
    <button type="submit">Submit</submit>
    </form>

My server route:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

  //Adding a new subfolder
        app.post('/subfolder/:id', multer.array({ name: 'images', maxCount: 6 }), expressValidator, function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });

Normally this code should print on the console the message

Form submitted
  but the server is receiving nothing not even
  Not Found

I have just noticed the problem is with using multer and expressValidator. If I remove expressValidator, it is working but if I add it, it is not working. I need expressValidator to validate user data. Is there any other validator which will accept to be used with multer?

Body:
I found the solution of using both of these middlewares, I just called the before the action and called the express-validator after calling multer:

var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var osmodule = require('../../osmodule');
var Multer = require('multer');
var request = require('request');
const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
        fileSize: 5 * 1024 * 1024 // no larger than 5mb, you can change as needed.
    }
});

app.get('/home',function(req,res){
console.log("Welcome Brother");
})
.use(multer.array({ name: 'images', maxCount: 6 });
.use(expressValidator);
.post('/subfolder/:id', function (req, res, next) {
console.log("Form Submitted");
       }).use(function (req, res, next) {
    res.setHeader('Content-Type', 'text/plain');
    res.status(404).send('Not Found ! ');
    });


问:
Unable to upload iOS app with Application Loader
Tired of banging of head against the wall with Apple, so I'm asking the question here.

Application Loader gets stuck at "Uploading package to iTunes Store...", showing 616 bytes of 37.7 MB (0 bytes/sec). Screenshot:

It stays this way for about 20 minutes and then displays an indeterminate error message:

An exception has occurred: The transport has been detected as having
  stalled and has been aborted.  Please try again.

On one occasion the progress bar jumped to 10MB and it appeared to be uploading for a while, and then the error message appeared.

The error message does not show any information pertaining to the problem, or provide any hints as to the cause of the problem, or a potential solution. One line of the error hints at a "diagnostic mode" but provides no further information. Screenshot below:

I did try a workaround recommended elsewhere, of setting "https.proxyPort=80" in the "net.properties" file. This had no effect.

Application Loader has persistently given problems in the past, on other networks and computers, for no apparant reason. The internet connection I am on at the moment is fine. Every other site and service I use works perfectly. I am able to upload and download files from other servers, and I was able to submit the same app through Google Play without any problems.

Contacting Apple was not helpful. The first email response said that I need to verify the address and ports are accessible, and linked to the Using Application Loader document.

When I asked Apple what it meant to "verify", they responded that they were unwilling to assist, and recommended searching online for solutions.

I posted this same question on the dev forums and have received no response. Other posts on the internet suggest "going to the library", or "upload from your phone", neither of which are practical solutions.

Are there any known solutions to the problem? How can I go about diagnosing the issue? What is the "diagnostic mode" referred to in the error?

答:
Make sure that all below sites IP and Ports are accessible from your Mac,
http://help.apple.com/itc/apploader/e3#/itc8e7ec5a60</p>


问:
Why wont Mozilla Firefox support third party fonts on my Website?
I have a TTF (True Type Font) which I have used correctly, as it shows up in Safari and Chrome. Is there a way to enable third party fonts on Firefox, or a MAC friendly file extension which is universal across all internet browsers?

I read up about it, and people suggested WOFF files, but they are an executable file on MAC, and Font Book wont open these files. I'm not particularly interested in downloading a third party program to install this third party font.

(In case you are wondering, or it helps, the font is "Top Secret". It's like an ARMY font)

答:
EOT font files worked well for me, here is a detailed article

Hope that helps!


问:
pySerial 2.6: specify end-of-line in readline()
I am sending commands to Eddie using pySerial. I need to specify a carriage-return in my readline, but pySerial 2.6 got rid of it... Is there a workaround?

Here are the Eddie command set is listed on the second and third pages of this PDF. Here is a backup image in the case where the PDF is inaccessible.

General command form:

```<code>Input:              <cmd>[<WS><param1>...<WS><paramN>]<CR>
Response (Success): [<param1>...<WS><paramN>]<CR>
Response (Failure): ERROR[<SP>-<SP><verbose_reason>]<CR>
</code>```

As you can see all responses end with a \r. I need to tell pySerial to stop.

What I have now:

def sendAndReceive(self, content):
  logger.info('Sending {0}'.format(content))
  self.ser.write(content + '\r')
  self.ser.flush();
  response = self.ser.readline() # Currently stops reading on timeout...
  if self.isErr(response):
    logger.error(response)
    return None
  else:
    return response
```

答:
reading 10 data from port 3 with board rate 38400, The data is separated with \n character when comes in the incoming data</p>

```<code>import serial as self
ser=self.Serial("COM3", 38400)
buffer = []
count = 0.0
c = "\0"
while count < 10:
    c = "\0"
    if ser.inWaiting():
        while True:
            val = ser.read(1)
            if "\n" in val:
                break
            else:
                c += val
        buffer.append(c) # stores all data received into a list
        count += 1
print buffer
</code>```

Body:
I am sending commands to Eddie using pySerial. I need to specify a carriage-return in my readline, but pySerial 2.6 got rid of it... Is there a workaround?

Here are the Eddie command set is listed on the second and third pages of this PDF. Here is a backup image in the case where the PDF is inaccessible.

General command form:

Input:              <cmd>[<WS><param1>...<WS><paramN>]<CR>
Response (Success): [<param1>...<WS><paramN>]<CR>
Response (Failure): ERROR[<SP>-<SP><verbose_reason>]<CR>

As you can see all responses end with a \r. I need to tell pySerial to stop.

What I have now:

def sendAndReceive(self, content):
  logger.info('Sending {0}'.format(content))
  self.ser.write(content + '\r')
  self.ser.flush();
  response = self.ser.readline() # Currently stops reading on timeout...
  if self.isErr(response):
    logger.error(response)
    return None
  else:
    return response

Body:
reading 10 data from port 3 with board rate 38400, The data is separated with \n character when comes in the incoming data

import serial as self
ser=self.Serial("COM3", 38400)
buffer = []
count = 0.0
c = "\0"
while count < 10:
    c = "\0"
    if ser.inWaiting():
        while True:
            val = ser.read(1)
            if "\n" in val:
                break
            else:
                c += val
        buffer.append(c) # stores all data received into a list
        count += 1
print buffer


问:
on click removing all elements in jquery
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="comparision">
  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGIC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">PSMC</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>

  <div class="compraision index_opt co_heading_area pos">
    <div class="co_info"><span class="float-left">AGTL</span>
      <p class="float-right">44%</p>
      Remove
    </div>
    <div class="clearfix"></div>
  </div>
</div></code>```

Fiddle Link

答:
You just have to make your jquery like this:</p>

```<code>$(document).on("click", ".rmove", function() {
  $(this).parents(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});
</code>```

Body:
I have created a jquery dynamic elements showing As of now when ever I click on single elements it deletes all can anyone help me out why is this happening or is there a way it can be done if I click on 1 element it it will remove 1 only

$(document).on("click", ".rmove", function() {
  $(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});

AGIC

44%

      Remove

PSMC

44%

      Remove

AGTL

44%

      Remove

Fiddle Link

Body:
You just have to make your jquery like this:

$(document).on("click", ".rmove", function() {
  $(this).parents(".compraision").remove();
  $('#company_graph').show();
  $('#comparision_graph').hide();
});


问:
How to find month no,name from week number using php
How to find month no,name from week number using php</p>

答:
```<code>$myDate = "2010-05-12";

$weekNumber = date("W", strtotime($myDate));
</code>```

Just replace the "W" with the value you need. Full reference:

http://php.net/manual/en/function.date.php

If you have a week number, and want the date from it you can use:

```<code>date("d m Y", strtotime("1.1.2010 + 30 weeks"));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
$myDate = "2010-05-12";

$weekNumber = date("W", strtotime($myDate));

Just replace the "W" with the value you need. Full reference:

http://php.net/manual/en/function.date.php

If you have a week number, and want the date from it you can use:

date("d m Y", strtotime("1.1.2010 + 30 weeks"));


问:
Detect when a presented view controller is dismissed
Let's say, I have an instance of a view controller class called VC2.  In VC2, there is a "cancel" button that will dismiss itself.  But I can't detect or receive any callback when the "cancel" button got trigger.  VC2 is a black box.

A view controller (called VC1) will present VC2 using presentViewController:animated:completion: method.

What options does VC1 have to detect when VC2 was dismissed?

Edit:  From the comment of @rory mckinnel and answer of @NicolasMiari, I tried the following:

In VC2:

```<code>-(void)cancelButton:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{

    }];
//    [super dismissViewControllerAnimated:YES completion:^{
//
//    }];
}
</code>```

In VC1:

```<code>//-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
- (void)dismissViewControllerAnimated:(BOOL)flag
                           completion:(void (^ _Nullable)(void))completion
{
    NSLog(@"%s ", __PRETTY_FUNCTION__);
    [super dismissViewControllerAnimated:flag completion:completion];
//    [self dismissViewControllerAnimated:YES completion:^{
//
//    }];
}
</code>```

But the dismissViewControllerAnimated in the VC1 was not getting called.

答:
You can handle uiviewcontroller closed using with Unwind Segues.

https://developer.apple.com/library/content/technotes/tn2298/_index.html

https://spin.atomicobject.com/2014/12/01/program-ios-unwind-segue/

Body:
Let's say, I have an instance of a view controller class called VC2.  In VC2, there is a "cancel" button that will dismiss itself.  But I can't detect or receive any callback when the "cancel" button got trigger.  VC2 is a black box.

A view controller (called VC1) will present VC2 using presentViewController:animated:completion: method.

What options does VC1 have to detect when VC2 was dismissed?

Edit:  From the comment of @rory mckinnel and answer of @NicolasMiari, I tried the following:

In VC2:

-(void)cancelButton:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{

    }];
//    [super dismissViewControllerAnimated:YES completion:^{
//
//    }];
}

In VC1:

//-(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
- (void)dismissViewControllerAnimated:(BOOL)flag
                           completion:(void (^ _Nullable)(void))completion
{
    NSLog(@"%s ", __PRETTY_FUNCTION__);
    [super dismissViewControllerAnimated:flag completion:completion];
//    [self dismissViewControllerAnimated:YES completion:^{
//
//    }];
}

But the dismissViewControllerAnimated in the VC1 was not getting called.


问:
What is the recommended native JavaScript equivalent to a jQuery delegated event?
I'd like to know what is the best native js practice for a jQuery delegated event handler like this:

```<code>$('body').on('click','.my-class', event => {
  // perform action
});
</code>```

Event delegation like this allows you add click events to dynamically added HTMLElements as you are listening to all clicks on the body or document.

Right now I'm doing something like this, which feels a little messy and sometimes it breaks if the user clicks an svg for instance. Also, it becomes difficult when you want to target multiple classes in a rather long HTMLElement.classList eg '.my-main-class.my-temp-class'.

```<code>document.body.addEventListener('click', event => {
  if (event.target.classList.contains('my-class')) {
    // perform action
  }
});
</code>```

Even an NPM dom helper library that I could import would be appreciated.

答:
One way to do it:

Edit: Updated to handle dynamically added elements

// Handle clicks
function clickHandler(event)
{
  console.log(event.target.id);
}
// Handle  dynamic element changes
function domchangeHandler(mutations)
{
  console.log("changed");
  var eList=document.getElementsByClassName('my-class');
  for (var i = 0; i < eList.length; i++) {
     eList[i].addEventListener('click',clickHandler);
  }
}

// Create new MutationObserver
var observer = new MutationObserver(domchangeHandler);
var config = { attributes: true, childList: true };
observer.observe(document.body, config);

// Add dynamic elements
for (var i=1;i<4;i++){
  var button=document.createElement('button');
  button.id="div"+i;
  button.className="my-class class-"+i;
  button.innerText="Click me, I'm Button "+i;
  document.body.appendChild(button);
}

var div= document.createElement('div');
div.innerHTML='<svg id="svg1" width="100" height="100" style="background-color:blue;" class="my-class svg"><g><circle id="circle" cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" class="circle class"/></g></svg>'
document.body.appendChild(div);```

Body:
I'd like to know what is the best native js practice for a jQuery delegated event handler like this:

$('body').on('click','.my-class', event => {
  // perform action
});

Event delegation like this allows you add click events to dynamically added HTMLElements as you are listening to all clicks on the body or document.

Right now I'm doing something like this, which feels a little messy and sometimes it breaks if the user clicks an svg for instance. Also, it becomes difficult when you want to target multiple classes in a rather long HTMLElement.classList eg '.my-main-class.my-temp-class'.

document.body.addEventListener('click', event => {
  if (event.target.classList.contains('my-class')) {
    // perform action
  }
});

Even an NPM dom helper library that I could import would be appreciated.


问:
IBDesignable View - need ViewController at design time
I'm creating an IBDesignable component so that I can see the component render live in the Xcode storyboard.  The component is simply a composition of other components.  Unfortunately, one of those components requires a UIViewController to function properly.  Yes, bad, but I have no control over it.

The component works fine running in the app, but does not render properly at design time because the UIViewController for that scene is not available.  I have tried

marching up the responder chain looking for a UIViewController

creating an IBOutlet on the component and connecting it to the View
Controller in the storyboard

Neither of these has worked; the View Controller is always nil.  Any suggestions?

答: Unfortunately none of the IBDesignable component's surrounding environment can influence the component itself.  </p>


问:
azure webapp with c++ dll not working
I've created a Azure Web in C# which references to a native C++ Dynamic library. On the local host application is running well.

But when I've deployed the web app to Cloud Azure, its not working. Not getting clue how to go forward. please help.

On the reset API call getting following "An error has occurred."

答:
On the reset API call getting following "An error has occurred."

To get the detail error information from ASP.NET REST API, we need to set the value of IncludeErrorDetailPolicy property as 'Always' in WebApiConfig.cs.

```<code>config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
</code>```

If the exception you got after changed the IncludeErrorDetailPolicy is DllNotFoundException, please make sure the native DLL is deployed successfully to Azure Web App bin folder. By default, the native DLL file will not be deployed with your VS publish. You need to upload this file to the bin folder of your web app using FTP or Kudu site.

If the exception you got after changed the IncludeErrorDetailPolicy is BadImageFormatException, you need to check the platform of your Web App and your native DLL.

If the platform of your Web App is 32 bit, please make sure the native DLL was build target Win32 or All Platforms. If you build the DLL on a 64 bit machine. All Platforms is required.

In addition, Azure Web App run in a secure environment called a sandbox. The sandbox generally aims to restrict access to shared components of Windows. For detail information, link below is for your reference.

General Azure Web App Sandbox Restrictions

If your native DLL use one of the restricted APIs. Calling to your native DLL also will be failed. To see all the dependent modules of your native DLL, you could download and use Dependency Walker.

Title: azure webapp with c++ dll not working

Body:
On the reset API call getting following "An error has occurred."

To get the detail error information from ASP.NET REST API, we need to set the value of IncludeErrorDetailPolicy property as 'Always' in WebApiConfig.cs.

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

If the exception you got after changed the IncludeErrorDetailPolicy is DllNotFoundException, please make sure the native DLL is deployed successfully to Azure Web App bin folder. By default, the native DLL file will not be deployed with your VS publish. You need to upload this file to the bin folder of your web app using FTP or Kudu site.

If the exception you got after changed the IncludeErrorDetailPolicy is BadImageFormatException, you need to check the platform of your Web App and your native DLL.

If the platform of your Web App is 32 bit, please make sure the native DLL was build target Win32 or All Platforms. If you build the DLL on a 64 bit machine. All Platforms is required.

In addition, Azure Web App run in a secure environment called a sandbox. The sandbox generally aims to restrict access to shared components of Windows. For detail information, link below is for your reference.

General Azure Web App Sandbox Restrictions

If your native DLL use one of the restricted APIs. Calling to your native DLL also will be failed. To see all the dependent modules of your native DLL, you could download and use Dependency Walker.


问:
Sqlite redefine SQLITE_MAX_SQL_LENGTH c#
I am trying to change limit of sql length in sqlite DB, using c# connection.
Can someone help me, pls?

Here is the sqlitecommand:

json string is a very big one.

```<code>try
{
     string sql = "INSERT INTO SIP_JSON (sip_code, json) VALUES (" + nextSipCode
          + ",'" + json + "')";
     connection.Open();
     SQLiteCommand command = new SQLiteCommand(sql, connection);
     command.ExecuteNonQuery();
}
catch (Exception e)
{
     throw new Exception(Exceptions.GATEWAYDB_INSESRTSIPJSON_EXCEPTION, e);
}
finally
{
      connection.Close();
}
</code>```

Exception Is:out of memory

答:
Thanks TripeHound, I change my query to use prepared statements.</p>

```<code>   try
                {
                    connection.Open();
                    SQLiteCommand command = new SQLiteCommand(connection);
                    command.CommandText = "INSERT INTO SIP_JSON (sip_code, json) VALUES (?,?)";
                    command.Parameters.Add(new SQLiteParameter("sip_code",nextSipCode));
                    command.Parameters.Add(new SQLiteParameter("json", json));
                    command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw new Exception(Exceptions.GATEWAYDB_INSESRTSIPJSON_EXCEPTION, e);
                }
                finally
                {
                    connection.Close();
                }
</code>```

Body:
I am trying to change limit of sql length in sqlite DB, using c# connection.
Can someone help me, pls?

Here is the sqlitecommand:

json string is a very big one.

try
{
     string sql = "INSERT INTO SIP_JSON (sip_code, json) VALUES (" + nextSipCode
          + ",'" + json + "')";
     connection.Open();
     SQLiteCommand command = new SQLiteCommand(sql, connection);
     command.ExecuteNonQuery();
}
catch (Exception e)
{
     throw new Exception(Exceptions.GATEWAYDB_INSESRTSIPJSON_EXCEPTION, e);
}
finally
{
      connection.Close();
}

Exception Is:out of memory

Body:
Thanks TripeHound, I change my query to use prepared statements.

   try
                {
                    connection.Open();
                    SQLiteCommand command = new SQLiteCommand(connection);
                    command.CommandText = "INSERT INTO SIP_JSON (sip_code, json) VALUES (?,?)";
                    command.Parameters.Add(new SQLiteParameter("sip_code",nextSipCode));
                    command.Parameters.Add(new SQLiteParameter("json", json));
                    command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw new Exception(Exceptions.GATEWAYDB_INSESRTSIPJSON_EXCEPTION, e);
                }
                finally
                {
                    connection.Close();
                }


问:
PHP rand from list
What is the best way of doing this ?

```<code>rand('Helloworld','Hi world');
</code>```

I know this is not working as rand needs a min and max number, but what is the solution for this ?

答:
PHP's array_rand() for sure. Example:</p>

```<code><?php

$names = array('Neo', 'Morpheus', 'Trinity', 'Cypher', 'Tank');
echo 'Hello ' . $names[array_rand($names)];
</code>```

Title: PHP rand from list

Body:
What is the best way of doing this ?

rand('Helloworld','Hi world');

I know this is not working as rand needs a min and max number, but what is the solution for this ?

Body:
PHP's array_rand() for sure. Example:

<?php

$names = array('Neo', 'Morpheus', 'Trinity', 'Cypher', 'Tank');
echo 'Hello ' . $names[array_rand($names)];


问:
realloc function doesn't preserve existing memory for me
I created a memory block  with 4 units using calloc function where each unit is 1 byte.

Then I assigned it to a char pointer and filled the units with char values.

Then using realloc function I enlarged each unit to 4 bytes (size of an integer)
Then I assigned it to a int pointer and filled integers in 3 of the units.

Theoretically I expected that the for the 4th unit of the memory block, value I gave before realloc will be preserved. But it is not. When I compile, each time I get a random value for that.

```<code> int main() {

    //create a memory block of 4 units (each 1 bytes : char size)
    char *p = (char*)calloc(4,sizeof(char));

    //fill the memory units with chars
    p[0] = 'A';
    p[1] = 'B';
    p[2] = 'C';
    p[3] = 'D';

    //print
    for(int i = 0; i< 4 ; i++){
        printf("%c \n",p[i]);
    }

    //print integer value of third index
    printf("Third index integer value : %d\n",p[3]);

    printf("\n"); //space

    //change the memory block so that each unit = 4 byte (size of integers)
    int  *B = (int*)realloc(p, sizeof(int));
    p = NULL;

    //fill 3 of the 4 memory units with integers
    B[0] = 20;
    B[1] = 25;
    B[2] = 30;

    //print integers
    printf("%d \n", B[0]);
    printf("%d \n", B[1]);
    printf("%d \n", B[2]);
    printf("Third index integer value : %d \n", B[3]);

    printf("Third index char value : %c \n", B[3]);

    return 0;
}
</code>```

Outcome

attempt 1

```<code>B
C
D
Third index integer value : 68

20
25
30
Third index integer value : 53491
Third index char value : ó
</code>```

attempt 2

```<code>A
B
C
D
Third index integer value : 68

20
25
30
Third index integer value : 42319
Third index char value : O
</code>```

答:
Read suitable documentation of realloc: its size parameter is the new size of memory to allocate. You're asking it to allocate sizeof(int) bytes, which is likely 4 (the same as the size of your previous allocation).

From the C-style allocation functions, calloc is the only one which works in terms of cells & cell size. Everything else (malloc, realloc, even the C++ allocation functions ::operator new and ::operator new[]) works in raw memory size only. So change you call to:

```<code>int  *B = (int*)realloc(p, 4 * sizeof(int));
</code>```

Body:
I created a memory block  with 4 units using calloc function where each unit is 1 byte.

Then I assigned it to a char pointer and filled the units with char values.

Then using realloc function I enlarged each unit to 4 bytes (size of an integer)
Then I assigned it to a int pointer and filled integers in 3 of the units.

Theoretically I expected that the for the 4th unit of the memory block, value I gave before realloc will be preserved. But it is not. When I compile, each time I get a random value for that.

 int main() {

    //create a memory block of 4 units (each 1 bytes : char size)
    char *p = (char*)calloc(4,sizeof(char));

    //fill the memory units with chars
    p[0] = 'A';
    p[1] = 'B';
    p[2] = 'C';
    p[3] = 'D';

    //print
    for(int i = 0; i< 4 ; i++){
        printf("%c \n",p[i]);
    }

    //print integer value of third index
    printf("Third index integer value : %d\n",p[3]);

    printf("\n"); //space

    //change the memory block so that each unit = 4 byte (size of integers)
    int  *B = (int*)realloc(p, sizeof(int));
    p = NULL;

    //fill 3 of the 4 memory units with integers
    B[0] = 20;
    B[1] = 25;
    B[2] = 30;

    //print integers
    printf("%d \n", B[0]);
    printf("%d \n", B[1]);
    printf("%d \n", B[2]);
    printf("Third index integer value : %d \n", B[3]);

    printf("Third index char value : %c \n", B[3]);

    return 0;
}

Outcome

attempt 1

B
C
D
Third index integer value : 68

20
25
30
Third index integer value : 53491
Third index char value : ó

attempt 2

A
B
C
D
Third index integer value : 68

20
25
30
Third index integer value : 42319
Third index char value : O

Body:
Read suitable documentation of realloc: its size parameter is the new size of memory to allocate. You're asking it to allocate sizeof(int) bytes, which is likely 4 (the same as the size of your previous allocation).

From the C-style allocation functions, calloc is the only one which works in terms of cells & cell size. Everything else (malloc, realloc, even the C++ allocation functions ::operator new and ::operator new[]) works in raw memory size only. So change you call to:

int  *B = (int*)realloc(p, 4 * sizeof(int));


问:
How to save matplotlib plot with the same file name as its filename.py
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

```<code>if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')
</code>```

I want to change the last line to something like

```<code>  # pseudocode
  plt.savefig(variable, '.png')
</code>```

I tested

```<code>  plt.savefig(__file__, ".png")
</code>```

The saved filename had .py, the file path, and the space before .png which I don't want

答:
You can use Python's splitext() to break __file__ into two parts and then add the required extension as follows:

```<code>import os

output_filename = os.path.splitext(__file__)[0] + '.png'
plt.savefig(output_filename)
</code>```

Body:
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')

I want to change the last line to something like

  # pseudocode
  plt.savefig(variable, '.png')

I tested

  plt.savefig(__file__, ".png")

The saved filename had .py, the file path, and the space before .png which I don't want

Body:
You can use Python's splitext() to break __file__ into two parts and then add the required extension as follows:

import os

output_filename = os.path.splitext(__file__)[0] + '.png'
plt.savefig(output_filename)


问:
Python RecursionError: maximum recursion depth exceeded while calling a Python object
I have been trying to fix this error using all sorts of methods and still could not find any error. What I'm doing is retrieving 2 strings from a HTML form and then send it over to my database as JSON. Here are the codes.

HTML Form:

```<code><link rel="stylesheet" href="/static/css/loginstyle.css" type="text/css">
<form action="/registerUser" method="POST">
<div class="login">
    <div class="login-screen">
        <div class="app-title">
            <h1>Register</h1>
        </div>

        <div class="login-form">
            <div class="control-group">
                <input type="text" class="login-field" value="" placeholder="Username" name="username">
                <label class="login-field-icon fui-user" for="login-name"></label>
            </div>

            <div class="control-group">
                <input type="password" class="login-field" value="" placeholder="password" name="password">
                <label class="login-field-icon fui-lock" for="login-pass"></label>
            </div>

            <input type="submit" value="Register" class="btn btn-primary btn-large btn-block">
            <br>
        </div>
    </div>
</div>
</code>```

Python Flask Code:

```<code>sys.setrecursionlimit(1500)
@app.route('/registerUser', methods=['POST'])
def register_user():
  if request.method == 'POST':
   idx = uuid.uuid4()
   uid = str(idx)
   username = request.form['username']
   password = request.form['password']
   password = password.encode('utf-8')
   sha1 = hashlib.sha1()
   sha1.update(password)
   password = sha1.hexdigest()
   data = {'uid': uid, 'username': username, 'password': password}
   db.child("users").child(username).set(data)
   return render_template('/login.html')
  else:
   error = 'What are you trying to do?'
   return render_template('/login.html', error = error)
</code>```

Error:

RecursionError: maximum recursion depth exceeded while calling a Python object

答: Solved by changing python version to a lower one.</p>

Body:
I have been trying to fix this error using all sorts of methods and still could not find any error. What I'm doing is retrieving 2 strings from a HTML form and then send it over to my database as JSON. Here are the codes.

HTML Form:

<link rel="stylesheet" href="/static/css/loginstyle.css" type="text/css">
<form action="/registerUser" method="POST">

Register

                <input type="text" class="login-field" value="" placeholder="Username" name="username">

                <input type="password" class="login-field" value="" placeholder="password" name="password">

            <input type="submit" value="Register" class="btn btn-primary btn-large btn-block">

Python Flask Code:

sys.setrecursionlimit(1500)
@app.route('/registerUser', methods=['POST'])
def register_user():
  if request.method == 'POST':
   idx = uuid.uuid4()
   uid = str(idx)
   username = request.form['username']
   password = request.form['password']
   password = password.encode('utf-8')
   sha1 = hashlib.sha1()
   sha1.update(password)
   password = sha1.hexdigest()
   data = {'uid': uid, 'username': username, 'password': password}
   db.child("users").child(username).set(data)
   return render_template('/login.html')
  else:
   error = 'What are you trying to do?'
   return render_template('/login.html', error = error)

Error:

RecursionError: maximum recursion depth exceeded while calling a Python object


问:
Excel to Access (ACE DAO) - How to flush write cache manually
To summarise my setup, I'm using an Excel/VBA front-end with an Access database (accdb) backend. The front end has a number of GUIs that use VBA to read/write to/from the database. When the application starts, it uses ACE DAO to open the database and this 'connection' remains open until the user closes the app.

The problem I'm having is that updates to records are not immediately visible to other users. I believe this is because updates/changes to records are being cached instead of being immediately written. The only way I've found to clear this cache and apply the changes is to close the connection.

Closing the connection isn't really an option because it would need to be done frequently (I would then need to constantly reconnect which takes time). The stripped down code I'm currently using is:

Opening the database:

```<code>Set oDB = DBEngine.OpenDatabase(TARGET_DB, False, False, "MS Access;PWD=" & TARGET_DB_PASS)
</code>```

I use query definitions within the access database to retrieve recordsets. Once I have the right DAO.QueryDef, I call the following to get the recordset:

```<code>Set oRS = oQryDef.OpenRecordset
</code>```

I then modify the fields I want to change, call .Update and close the recordset:

```<code>With oRS
        .Edit
        .Fields("Record_Locked") = True
        .Fields("Locked_By") = UCase(Environ("username"))
        .Fields("Locked_Date") = Now
        .Update
        .Close
End With
</code>```

At this point, the changes are not made to the database until oDB.Close is called.

What I have tried so far:

Explicitly opening the recordset as dbDynatset with dbSeeChanges

```<code>Set oRS = oQryDef.OpenRecordset(dbOpenDynaset, dbSeeChanges)
</code>```

Putting the changes to fields inside a transaction and using CommitTrans with dbForceOSFlush

```<code>DBEngine.BeginTrans
With oRS
        .Edit
        .Fields("Record_Locked") = True
        .Fields("Locked_By") = UCase(Environ("username"))
        .Fields("Locked_Date") = Now
        .Update
        .Close
End With
DBEngine.CommitTrans dbForceOSFlush
</code>```

答:
Try changing the recordset Type and Options enums.

```<code>Set oRS = oQryDef.OpenRecordset(dbOpenDynaset, dbSeeChanges)

'dbOpenDynaset = 2
'dbSeeChanges = 512
</code>```

Body:
To summarise my setup, I'm using an Excel/VBA front-end with an Access database (accdb) backend. The front end has a number of GUIs that use VBA to read/write to/from the database. When the application starts, it uses ACE DAO to open the database and this 'connection' remains open until the user closes the app.

The problem I'm having is that updates to records are not immediately visible to other users. I believe this is because updates/changes to records are being cached instead of being immediately written. The only way I've found to clear this cache and apply the changes is to close the connection.

Closing the connection isn't really an option because it would need to be done frequently (I would then need to constantly reconnect which takes time). The stripped down code I'm currently using is:

Opening the database:

Set oDB = DBEngine.OpenDatabase(TARGET_DB, False, False, "MS Access;PWD=" & TARGET_DB_PASS)

I use query definitions within the access database to retrieve recordsets. Once I have the right DAO.QueryDef, I call the following to get the recordset:

Set oRS = oQryDef.OpenRecordset

I then modify the fields I want to change, call .Update and close the recordset:

With oRS
        .Edit
        .Fields("Record_Locked") = True
        .Fields("Locked_By") = UCase(Environ("username"))
        .Fields("Locked_Date") = Now
        .Update
        .Close
End With

At this point, the changes are not made to the database until oDB.Close is called.

What I have tried so far:

Explicitly opening the recordset as dbDynatset with dbSeeChanges

Set oRS = oQryDef.OpenRecordset(dbOpenDynaset, dbSeeChanges)

Putting the changes to fields inside a transaction and using CommitTrans with dbForceOSFlush

DBEngine.BeginTrans
With oRS
        .Edit
        .Fields("Record_Locked") = True
        .Fields("Locked_By") = UCase(Environ("username"))
        .Fields("Locked_Date") = Now
        .Update
        .Close
End With
DBEngine.CommitTrans dbForceOSFlush

Body:
Try changing the recordset Type and Options enums.

Set oRS = oQryDef.OpenRecordset(dbOpenDynaset, dbSeeChanges)

'dbOpenDynaset = 2
'dbSeeChanges = 512


问:
How to make a excel export header with kendo UI Grid
How to add a header to excel using Kendo UI Grid

I am using Javascript and Jquery.

答:
You could add a new row/rows to the beginning of your exported file and modify the cell attributes to style it in the format of your attached image.

You could use unshift to insert a row at the beginning of your rows array containing the header title.

And then use additional cell attributes to style the header title (like textAlign and colSpan).

```<code>var rows = e.workbook.sheets[0].rows;
rows.unshift({
    cells: [ { value: "My title", background: "#ff0000", colSpan: 2, textAlign: "right" } ]
});
</code>```

Dojo example to demonstrate the above.

EDIT

In order to modify the size of the font used in the header cell, you can use the fontSize attribute.

```<code>var rows = e.workbook.sheets[0].rows;
rows.unshift({
    cells: [ { value: "My title", fontSize: 20, background: "#ff0000", colSpan: 2, textAlign: "right" } ]
});
</code>```

Body:
You could add a new row/rows to the beginning of your exported file and modify the cell attributes to style it in the format of your attached image.

You could use unshift to insert a row at the beginning of your rows array containing the header title.

And then use additional cell attributes to style the header title (like textAlign and colSpan).

var rows = e.workbook.sheets[0].rows;
rows.unshift({
    cells: [ { value: "My title", background: "#ff0000", colSpan: 2, textAlign: "right" } ]
});

Dojo example to demonstrate the above.

EDIT

In order to modify the size of the font used in the header cell, you can use the fontSize attribute.

var rows = e.workbook.sheets[0].rows;
rows.unshift({
    cells: [ { value: "My title", fontSize: 20, background: "#ff0000", colSpan: 2, textAlign: "right" } ]
});


问:
Java: How can I read and store them in array by a new line in ArrayList?
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

```<code>-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692
</code>```

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
</code>```

Any suggestion for making this works?

答:
Each line can be stored as an ArrayList and each ArrayList inside another ArrayList creating a 2-Dimensional ArrayList of Float type.
Read each line using java.util.Scanner.nextLine() and then parse each line for float value. I have used another scanner to parse each line for float values.
After parsing, store float values into a tmp ArrayList and add that list to the major List. Be sure to close the local scanner inside the while itself.

```<code>import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadStore {
    public static void main(String[] args) throws IOException {
        //Input File
        Scanner inFile =new Scanner(new File("Untitled1.txt")).useDelimiter("\\s");
        //Major List (2-D ArrayList)
        ArrayList<ArrayList<Float>> list = new ArrayList<ArrayList<Float>>();
        //Reading Each Line
        while (inFile.hasNextLine()) {
            //tmp ArrayList
            ArrayList<Float> arr = new ArrayList<Float>();

            String line = inFile.nextLine();
            //local scanner to be used for parsing
            Scanner local = new Scanner(line);
            //Parsing line for flat values
            while(local.hasNext()){
                if(local.hasNextFloat()){
                    float token = local.nextFloat();
                    arr.add(token);
                }
            }
            //closing local Scanner
            local.close();
            //Adding to major List
            list.add(arr);
        }
        inFile.close();
        //Display List values
        for(ArrayList<Float> arrList:list){

            for(Float f : arrList){
                System.out.print(f + " ");
            }
            System.out.println();
        }
    }
}
</code>```

Body:
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }

Any suggestion for making this works?

Body:
Each line can be stored as an ArrayList and each ArrayList inside another ArrayList creating a 2-Dimensional ArrayList of Float type.
Read each line using java.util.Scanner.nextLine() and then parse each line for float value. I have used another scanner to parse each line for float values.
After parsing, store float values into a tmp ArrayList and add that list to the major List. Be sure to close the local scanner inside the while itself.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadStore {
    public static void main(String[] args) throws IOException {
        //Input File
        Scanner inFile =new Scanner(new File("Untitled1.txt")).useDelimiter("\\s");
        //Major List (2-D ArrayList)
        ArrayList<ArrayList<Float>> list = new ArrayList<ArrayList<Float>>();
        //Reading Each Line
        while (inFile.hasNextLine()) {
            //tmp ArrayList
            ArrayList<Float> arr = new ArrayList<Float>();

            String line = inFile.nextLine();
            //local scanner to be used for parsing
            Scanner local = new Scanner(line);
            //Parsing line for flat values
            while(local.hasNext()){
                if(local.hasNextFloat()){
                    float token = local.nextFloat();
                    arr.add(token);
                }
            }
            //closing local Scanner
            local.close();
            //Adding to major List
            list.add(arr);
        }
        inFile.close();
        //Display List values
        for(ArrayList<Float> arrList:list){

            for(Float f : arrList){
                System.out.print(f + " ");
            }
            System.out.println();
        }
    }
}


问:
shell_exec and vlc issues?
I'm making a streaming server with the CLI vlc. To make this easier, I made a WEB control interface using HTML/PHP.  The problem is when I run the following command in a terminal it works perfectly, but when launch it from PHP it fails (it makes like there was no options after vlc).

> vlc -vvv movie.mp4 --sout=#rtp{sdp=rtsp://:8554} --sout-keep
```

<p>Here is my PHP file:</p>

<pre class="lang-php prettyprint-override"><code><?php
    $output = shell_exec($_POST['command']);
    echo $output;
?>
</code>```

Input file:

<form method="POST" action="textearea.php">
    <textarea  id="command" name="command">
    </textarea>
    <input type="submit" value="OK"/>
</form>
```

the $output variable says that:

VLC media player 2.2.4 Weatherwax Command Line Interface initialized. Type help for help. > Shutting down.

It is exactly the same as if I just typed vlc in the terminal by itself - and of course, the stream doesn't work.

答: ok I found the answer by myself. you just need to replace vlc by cvlc in the command. it's a right problem of the www-data user.</p>

Title: shell_exec and vlc issues?

Body:
I'm making a streaming server with the CLI vlc. To make this easier, I made a WEB control interface using HTML/PHP.  The problem is when I run the following command in a terminal it works perfectly, but when launch it from PHP it fails (it makes like there was no options after vlc).

> vlc -vvv movie.mp4 --sout=#rtp{sdp=rtsp://:8554} --sout-keep

Here is my PHP file:

<?php
    $output = shell_exec($_POST['command']);
    echo $output;
?>

Input file:

<form method="POST" action="textearea.php">
    <textarea  id="command" name="command">
    </textarea>
    <input type="submit" value="OK"/>
</form>

the $output variable says that:

VLC media player 2.2.4 Weatherwax Command Line Interface initialized. Type help for help. > Shutting down.

It is exactly the same as if I just typed vlc in the terminal by itself - and of course, the stream doesn't work.


问:
heroku deploy error in RoR(Github deploy) what should I do with postgresql error?
I'm deploying small app from C9 to github then to Heroku!
In heroku deploy dashboard, it says it's been deployed, but when I open the app, it just gives me error msg.
So I searched a lot of Stackoverflow answers and was following the direction from Heroku website(https://devcenter.heroku.com/articles/sqlite3) to remove sqlite3 and install the gem pg.

I did replace gem 'sqlite3' to gem 'pg' and did 'bundle install', and then

It says I need to convert my   config/database.yml file, So I replaced it like this:

```<code>development:
  adapter: postgresql
  database: my_database_development
  pool: 5
  timeout: 5000
test:
  adapter: postgresql
  database: my_database_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: my_database_production
  pool: 5
  timeout: 5000
</code>```

and then when I come back to c9 bash and type 'rake db:create',
it shows me

```<code>**rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist**
</code>```

this error.

someone said 'bundle exec rake db:setup' would work, so I did, and then it shows

```<code>**Couldn't create database for {"adapter"=>"postgresql", "database"=>"my_database_test", "pool"=>5, "timeout"=>5000}
/home/ubuntu/workspace/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ubuntu/workspace/config/application.rb to limit the frameworks that will be loaded.**
</code>```

I don't know how to react to this msg.... when I type 'rake db:migrate' and it shows this again.

```<code>rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist
</code>```

I'm not using database, so maybe I can try something on 'config/application.rb' file, but how should I do??

答: one of the solution that you can create database manually this is easily solut</p>

Body:
I'm deploying small app from C9 to github then to Heroku!
In heroku deploy dashboard, it says it's been deployed, but when I open the app, it just gives me error msg.
So I searched a lot of Stackoverflow answers and was following the direction from Heroku website(https://devcenter.heroku.com/articles/sqlite3) to remove sqlite3 and install the gem pg.

I did replace gem 'sqlite3' to gem 'pg' and did 'bundle install', and then

It says I need to convert my   config/database.yml file, So I replaced it like this:

development:
  adapter: postgresql
  database: my_database_development
  pool: 5
  timeout: 5000
test:
  adapter: postgresql
  database: my_database_test
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: my_database_production
  pool: 5
  timeout: 5000

and then when I come back to c9 bash and type 'rake db:create',
it shows me

**rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist**

this error.

someone said 'bundle exec rake db:setup' would work, so I did, and then it shows

**Couldn't create database for {"adapter"=>"postgresql", "database"=>"my_database_test", "pool"=>5, "timeout"=>5000}
/home/ubuntu/workspace/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/ubuntu/workspace/config/application.rb to limit the frameworks that will be loaded.**

I don't know how to react to this msg.... when I type 'rake db:migrate' and it shows this again.

rake aborted!
ActiveRecord::NoDatabaseError: FATAL:  database "my_database_development" does not exist

I'm not using database, so maybe I can try something on 'config/application.rb' file, but how should I do??


答:
```<code>function rand_of() {
    $_ = func_get_args();
    return $_[rand(0, count($_) - 1)];
}

echo rand_of("foo", "bar", "baz");
</code>```

Title: PHP rand from list


问:
Typescript : error TS1109: Expression expected
```<code>  getItems(){
      return.this._http.get('http://localhost/api/items').map(res=>res.json());
  };
</code>```

This error is coming in this simple code. Kindly tell me any fix of it. Thanks!

答:
Remove the "." after return

```<code>getItems() {  return this._http.get('http://localhost/api/items').map(res => res.json()) };
</code>```

Body:
  getItems(){
      return.this._http.get('http://localhost/api/items').map(res=>res.json());
  };

This error is coming in this simple code. Kindly tell me any fix of it. Thanks!

Body:
Remove the "." after return

getItems() {  return this._http.get('http://localhost/api/items').map(res => res.json()) };


问:
Invalid argument supplied for foreach() laravel using whereIn (laravel 5.3)
I am getting ids using jquery in my controller its as

```<code>if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }
</code>```

I try dd($ids)

Output is as in my console

```<code>array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]
</code>```

When i pass ids to my query as

Query

```<code>$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');
</code>```

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

答:
You should change this:

```<code>->whereIn('students.id','=', $ids)
</code>```

To this:

```<code>->whereIn('students.id', $ids)
</code>```

Because the second parameter should be iterable of IDs, but you're passing a string =. Also, make sure, you're passing an array or collection of IDs.

Body:
I am getting ids using jquery in my controller its as

if(!empty($request->input('ids'))) {
    $ids = $request->input('ids');
    }else{
                $ids = null;
            }

I try dd($ids)

Output is as in my console

array:3 [
  0 => "1"
  1 => "2"
  2 => "on"
]

When i pass ids to my query as

Query

$student_ids = DB::table('students')
             ->orderBy('name', 'asc')
              ->where('group_id', '<>', 0)
              ->whereIn('students.id','=', $ids)
              ->pluck('id');

Its not working

Error is : Invalid argument supplied for foreach

Please help where I am wrong. Thanks

Body:
You should change this:

->whereIn('students.id','=', $ids)

To this:

->whereIn('students.id', $ids)

Because the second parameter should be iterable of IDs, but you're passing a string =. Also, make sure, you're passing an array or collection of IDs.


问:
How to change font family only numbers
On whole my website there are many places that use numbers. because my font doesn't good to numbers.I would like to change font them to what I wanted.

now similar questions asked before but I not find a good answer to do this.
some answers suggests to use jquery/javascript function. but I think using jquery/javascript function make lazy my webpages.

Is there any better solution?

答:
in css :

```<code>input[type="number"] {
    font-family: 'customFont';
}
</code>```

in html :

```<code><input type="number" name="number">
</code>```

Title: How to change font family only numbers

Body:
in css :

input[type="number"] {
    font-family: 'customFont';
}

in html :

<input type="number" name="number">


问:
Setting the application focus to a java-program in Ubuntu/LTSP
We are using LTSP with Thin-Clients. We are using it, to run a Java-Swing-Application. The users should not be able to do anything else, so instead of a Gnome-Session we use a shell-script to start our application.

Nearly everything works perfect but one thing: When the Thin-Client starts, the application starts too but doesn't receive the focus. We have to click once with the mouse inside the application, which is not that good, because the application is designed to be used without a mouse.

I didn't found anything useful, a toFront() on my Main Frame wasn't successful.

Has anyone any better suggestions??

答: You can use method java.awt.Window#setAlwaysOnTop(boolean) to grab the focus and after the first user interaction reset the alwayOnTop property.