问:
Error: Cannot read property 'replace' of undefined when building iOS Cordova
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

```<code>at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44
</code>```

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.

答:
New solution

This issue is fixed in the latest version of the "ios-sim" package (so now this is probably the easier solution - compared to the old one which is listed below). In order to update the "ios-sim" package to the latest version run this in your terminal/cmd:

```<code>cd platforms/ios/cordova/node_modules/
sudo npm install -g ios-sim@latest
</code>```

Old solution

The problem is that the name_id_map[deviceName] returns undefined for "iPad Pro (12.9-inch)" and "iPad Pro (10.5-inch)".

You can check it with a console.log('name_id_map[ deviceName ]: ' + name_id_map[ deviceName ]);.

I fixed this bug by adding an if statements which checks if the device is defined in "platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282".

I replaced this:

```<code>list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
        };
</code>```

with this:

```<code>list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            if (name_id_map[deviceName] && runtime) {
                list.push(util.format('%s, %s', name_id_map[deviceName].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
            }
        };
</code>```

The "iPad Pro (10.5-inch)" simulator won't be on the list (but it doesn't probably work anyway - didn't check).

Bug report on github: https://github.com/phonegap/ios-sim/issues/210

Body:
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.

Body:
New solution

This issue is fixed in the latest version of the "ios-sim" package (so now this is probably the easier solution - compared to the old one which is listed below). In order to update the "ios-sim" package to the latest version run this in your terminal/cmd:

cd platforms/ios/cordova/node_modules/
sudo npm install -g ios-sim@latest

Old solution

The problem is that the name_id_map[deviceName] returns undefined for "iPad Pro (12.9-inch)" and "iPad Pro (10.5-inch)".

You can check it with a console.log('name_id_map[ deviceName ]: ' + name_id_map[ deviceName ]);.

I fixed this bug by adding an if statements which checks if the device is defined in "platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282".

I replaced this:

list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
        };

with this:

list = [];
        var remove = function(runtime) {
            // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
            if (name_id_map[deviceName] && runtime) {
                list.push(util.format('%s, %s', name_id_map[deviceName].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
            }
        };

The "iPad Pro (10.5-inch)" simulator won't be on the list (but it doesn't probably work anyway - didn't check).

Bug report on github: https://github.com/phonegap/ios-sim/issues/210


来源: stackexchange

问:
Create list of tuples , tuple elements taken as Input
I wish to create a list whose members are tuples, taken from console input. I've seen other questions which describe about tuples and lists. But how to create tuples from input and append them to list till the choice to take tuple elements is no, 'n'? I tried the following code.

```<code>"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    print("Add an element for the tuple ? y/n : ")
    ch=str(input())
    while(ch=='y') :
        print("Enter the tuple element : ")
        i=input()
        l=l.append(tuple(i))
        print("Add an element for the tuple ? y/n : ")
        ch=str(input())
    return l

l2=createTupledList()
print(l2)
</code>```

Please help.

My inputs and error output :

```<code>C:\Users\vikranth\myproject\Python\Lists\Day 0>py tuplesortlist.py
Add an element for the tuple ? y/n :
y
Enter the tuple element :
1
Add an element for the tuple ? y/n :
y
Enter the tuple element :
2
Traceback (most recent call last):
  File "tuplesortlist.py", line 19, in <module>
    l2=createTupledList()
  File "tuplesortlist.py", line 12, in createTupledList
    l=l.append(tuple(i))
AttributeError: 'NoneType' object has no attribute 'append'
</code>```

答:
Code to add multiple elements into a tuple and to add multiple tuples to a list.</p>

```<code>"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    while True:
      t=tuple()
      print("Add an element for the tuple ? y/n : ")
      if input()!='y':
        break
      else:
        print("Keep adding the tuple elements : (x to break)")
        while True:
          i=input()
          if i=='x':
            break
          else:
            t+=(i,)
          print(t)
        l.append(t)
    return l

l2=createTupledList()
print(l2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wish to create a list whose members are tuples, taken from console input. I've seen other questions which describe about tuples and lists. But how to create tuples from input and append them to list till the choice to take tuple elements is no, 'n'? I tried the following code.

"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    print("Add an element for the tuple ? y/n : ")
    ch=str(input())
    while(ch=='y') :
        print("Enter the tuple element : ")
        i=input()
        l=l.append(tuple(i))
        print("Add an element for the tuple ? y/n : ")
        ch=str(input())
    return l

l2=createTupledList()
print(l2)

Please help.

My inputs and error output :

C:\Users\vikranth\myproject\Python\Lists\Day 0>py tuplesortlist.py
Add an element for the tuple ? y/n :
y
Enter the tuple element :
1
Add an element for the tuple ? y/n :
y
Enter the tuple element :
2
Traceback (most recent call last):
  File "tuplesortlist.py", line 19, in <module>
    l2=createTupledList()
  File "tuplesortlist.py", line 12, in createTupledList
    l=l.append(tuple(i))
AttributeError: 'NoneType' object has no attribute 'append'

Body:
Code to add multiple elements into a tuple and to add multiple tuples to a list.

"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    while True:
      t=tuple()
      print("Add an element for the tuple ? y/n : ")
      if input()!='y':
        break
      else:
        print("Keep adding the tuple elements : (x to break)")
        while True:
          i=input()
          if i=='x':
            break
          else:
            t+=(i,)
          print(t)
        l.append(t)
    return l

l2=createTupledList()
print(l2)


问:
SFSafariViewController init method forced to use iOS11 supported version
With the recent update on Xcode 9 Beta and iOS11 preview, there are some changes to SFSafariViewController init methods.

```<code>@available(iOS 11.0, *)
public init(url URL: URL, configuration: SFSafariViewController.Configuration)

@available(iOS, introduced: 9.0, deprecated: 11.0)
public convenience init(url URL: URL, entersReaderIfAvailable: Bool)
</code>```

There is one new init method that is supported from iOS11 onwards while the currently available init method will be deprecated by iOS11. The problem is that the current method is not exposed and could not be overwritten. This forces the use of the new init method if we want to use the beta to run the existing project. Has anyone found a way to use the existing init method in the new Xcode Beta?

Edit: For clarification, this is a snippet of the init method in my subclass

```<code>class BPSafariViewController: SFSafariViewController {
    override init(url URL: URL, entersReaderIfAvailable: Bool) {
        super.init(url: URL, entersReaderIfAvailable: entersReaderIfAvailable)
        if #available(iOS 10.0, *) {
            preferredControlTintColor = UIColor.BPUIColor()
        } else {
            view.tintColor = UIColor.BPUIColor()
        }
    }
}
</code>```

答:
You can do that while checking the iOS version as below.

```<code>var safariController: SFSafariViewController?
if #available(iOS 11.0, *) {
    safariController = SFSafariViewController(url: URL(string: "your_url")!)
} else {
    safariController = SFSafariViewController(url: URL(string: "")!, entersReaderIfAvailable: true)
}
</code>```

Body:
With the recent update on Xcode 9 Beta and iOS11 preview, there are some changes to SFSafariViewController init methods.

@available(iOS 11.0, *)
public init(url URL: URL, configuration: SFSafariViewController.Configuration)

@available(iOS, introduced: 9.0, deprecated: 11.0)
public convenience init(url URL: URL, entersReaderIfAvailable: Bool)

There is one new init method that is supported from iOS11 onwards while the currently available init method will be deprecated by iOS11. The problem is that the current method is not exposed and could not be overwritten. This forces the use of the new init method if we want to use the beta to run the existing project. Has anyone found a way to use the existing init method in the new Xcode Beta?

Edit: For clarification, this is a snippet of the init method in my subclass

class BPSafariViewController: SFSafariViewController {
    override init(url URL: URL, entersReaderIfAvailable: Bool) {
        super.init(url: URL, entersReaderIfAvailable: entersReaderIfAvailable)
        if #available(iOS 10.0, *) {
            preferredControlTintColor = UIColor.BPUIColor()
        } else {
            view.tintColor = UIColor.BPUIColor()
        }
    }
}

Body:
You can do that while checking the iOS version as below.

var safariController: SFSafariViewController?
if #available(iOS 11.0, *) {
    safariController = SFSafariViewController(url: URL(string: "your_url")!)
} else {
    safariController = SFSafariViewController(url: URL(string: "")!, entersReaderIfAvailable: true)
}


问:
UIWebView is not shown
WebView in Mainstoryboard is not shown anything. I wanna show yahoo page in my app.When I run my app in an emulator(that is not my real iPhone), it is like only　black screen.

Any error does not happen in that time, but
warning

In this part, I got a warning

"signal SIGABRT"

My code is like

```<code>import Foundation
import Alamofire
import UIKit

class webViewController: UIViewController {

    @IBOutlet var webBrowser: UIWebView! = nil

    var targetURL = "https://www.yahoo.co.jp"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL as! URL)
        webBrowser.loadRequest(req as URLRequest)
    }

}
</code>```

I think a connection of WebView & WebViewController is ok. I tried to do Add Exception Breakpoint,and find a point of this error.
The result is
result

My app dropped in

"Thread1:breakpoint4.1".

What is wrong with my app?

答:
You cannot assign nil value to @IBOutlet var webBrowser: UIWebView!.

Leave:

```<code>@IBOutlet weak var webBrowser: UIWebView!
</code>```

BTW, I'm assuming that you create correctly @IBOutlet by holding ctr and dragging from storyboard to you view controller. But I'm afraid that because of lack weak next to your @IBOutlet you created it manually in code so you need to clip it to the view in storyboard

Title: UIWebView is not shown

Body:
WebView in Mainstoryboard is not shown anything. I wanna show yahoo page in my app.When I run my app in an emulator(that is not my real iPhone), it is like only　black screen.

Any error does not happen in that time, but
warning

In this part, I got a warning

"signal SIGABRT"

My code is like

import Foundation
import Alamofire
import UIKit

class webViewController: UIViewController {

    @IBOutlet var webBrowser: UIWebView! = nil

    var targetURL = "https://www.yahoo.co.jp"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //loadAddressURL()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(url: requestURL as! URL)
        webBrowser.loadRequest(req as URLRequest)
    }

}

I think a connection of WebView & WebViewController is ok. I tried to do Add Exception Breakpoint,and find a point of this error.
The result is
result

My app dropped in

"Thread1:breakpoint4.1".

What is wrong with my app?

Body:
You cannot assign nil value to @IBOutlet var webBrowser: UIWebView!.

Leave:

@IBOutlet weak var webBrowser: UIWebView!

BTW, I'm assuming that you create correctly @IBOutlet by holding ctr and dragging from storyboard to you view controller. But I'm afraid that because of lack weak next to your @IBOutlet you created it manually in code so you need to clip it to the view in storyboard


问:
Remove primary key and auto-increment in database using migration in laravel
I have table with primary key and auto-increment field, I want make new migration to drop primary key index and also remove the auto increment field. How can i achieve this.

I created new migration as

```<code>public function up()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->unsignedInteger('message_id');
    });
}
</code>```

It gave me error in command as [Illuminate\Database\QueryException]

  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'message _id' (SQL: alter table tbl_'message_read_state' add 'message_id' int unsigned not null)

Whats Wrong ?????

答:
You can try this</p>

```<code>$table->dropPrimary('id_primary');
</code>```

Body:
I have table with primary key and auto-increment field, I want make new migration to drop primary key index and also remove the auto increment field. How can i achieve this.

I created new migration as

public function up()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('tbl_message_read_state', function (Blueprint $table) {

        $table->dropPrimary('message_id');
        $table->unsignedInteger('message_id');
    });
}

It gave me error in command as [Illuminate\Database\QueryException]

  SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'message _id' (SQL: alter table tbl_'message_read_state' add 'message_id' int unsigned not null)

Whats Wrong ?????

Body:
You can try this

$table->dropPrimary('id_primary');


问:
Develop Blackberry apps using native API or J2ME?
We're about to build a Blackberry application but would love some input on whether to implement using J2ME (MIDlet based) or Blackberry native (UIApplication).

I understand some of the tradeoffs.  J2ME will be more flexible if we want to port the app to other devices.  RIM has better support for Blackberry native.

The place I'm still lacking information, though, is on the UI side.  We want to build an app that has a great user experience, and one that looks like other apps BB users are accustomed to.  Can we do this if we go the J2ME route?

Apologies for the somewhat subjective and less technical nature of the question.

答:
I've tried it both ways - building a pure MIDP app to run on BlackBerry and non-BLackBerry platforms and building a separate BlackBerry app (often using much of the same business-logic and networking code as the MIDP app).  Definitely go the BlackBerry native route.

It's all about the BB UI classes.  They'll give you the ability to (among other things) respond to the different type of menu events (trackball and menu key), respond to BB specific key codes, if you're interested in the Storm take advantage of the orientation sensor and touch support.  Plus they're a much richer set of UI elements to work with.  You can build up a lot (but not all) of what they do in pure MIDP, but end up customizing so much of it for each platform that you won't save anything in the end.  Starting with the BB UI and customizing saves a lot of time and effort.

Even in gaming applications, or for applications where you're custom drawing all your components, you have better access to the BlackBerry graphics APIs and get better performance going the BlackBerry native app route.  And you still have better detail about input events.

Finally there are some nice lifecycle things you can do with BlackBerry native apps, like pushing to the background, or auto-running on system startup that you can't do with MIDlets, which may be of interest depending on your application.

Also think about market - if you're planning on supporting BlackBerry right away, and then maybe other MIDP platforms down the road, it's usually a better plan to execute the best you can on your initial platform.  There probably won't be much of a reason to port to MIDP later if you don't succeed on BlackBerry first.

OwnerDisplayName: Eric

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Anthony Rizk


问:
top two elements of an associative array in php
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

```<code>$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);
</code>```

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

```<code>arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second
</code>```

答:
Something like this:</p>

```<code>$array = array (
    'wood'  => 2,
    'metal' => 1,
    'blah'  => 4
);

$first  = end($array);
$second = prev($array);
</code>```

Body:
I've accomplished the end goal for this already, but maybe there is a more elegant way of accomplishing this.

If I have an array like such:

$data = array(
    'wood' => 2,
    'metal' => 5,
    'plastic' => 3,
);

I want to get the top 2 key/value pairs from $data (ie metal:5 & plastic:3). Here's what I came up with:

arsort($data);       //put values in order
reset($data);           //set pointer to first element
$first = each($data);    //assign first element to $first
array_shift($data); //remove first element from array
reset($data);           //set pointer to the new first element
$second = each($data); //assign the new first element to $second

Body:
Something like this:

$array = array (
    'wood'  => 2,
    'metal' => 1,
    'blah'  => 4
);

$first  = end($array);
$second = prev($array);


问:
NullPointerException in Kotlin
When I write this code in kotlin activity

```<code>var tv: TextView = findViewById(R.id.tv_kotlin) as TextView
</code>```

It always crashes with the following error:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
</code>```

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

```<code>private var btn: Button? = null
</code>```

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

```<code>class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}
</code>```

And the error messages :

```<code>06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
</code>```

答:
You can try this in your Gradle file

apply plugin: 'kotlin-android-extensions'

you can directly use the View id

Title: NullPointerException in Kotlin

Body:
When I write this code in kotlin activity

var tv: TextView = findViewById(R.id.tv_kotlin) as TextView

It always crashes with the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

And I find when I convert my Java codes to kotlin codes,the auto converter always does like this:

private var btn: Button? = null

And when I use the reference, I have to put a !! behind it which make the codes really ugly.So what is the correct way binding UI in kotlin android?

The completed code:

class JavaToKotlinActivity : AppCompatActivity() {

    private var tv: TextView = findViewById(R.id.tv) as TextView
    private var btn: Button? = null
    private var et: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_java_to_kotlin)
        initView()
    }

    private fun initView() {
        btn = findViewById(R.id.btn) as Button
        et = findViewById(R.id.et) as EditText
        btn!!.setOnClickListener { tv.text = "haha" }
        et!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }
}

And the error messages :

06-09 14:25:38.574 9770-9770/com.mimi E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: com.mimi, PID: 9770
                                                        java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.mimi/com.mimi.Views.JavaToKotlinActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2488)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                            at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
                                                            at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
                                                            at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
                                                            at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
                                                            at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:199)
                                                            at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
                                                            at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
                                                            at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                            at com.mimi.Views.JavaToKotlinActivity.<init>(JavaToKotlinActivity.kt:20)
                                                            at java.lang.Class.newInstance(Native Method)
                                                            at android.app.Instrumentation.newActivity(Instrumentation.java:1072)
                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2478)
                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2643)
                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1480)
                                                            at android.os.Handler.dispatchMessage(Handler.java:111)
                                                            at android.os.Looper.loop(Looper.java:207)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5799)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)

ContentLicense: CC BY-SA 4.0


问:
Call a function in a sibling component Reactjs
There are 3 components. First one is the parent component called A. The others are X and Y.

X is a toolbar component that has a Save button. And Y is a Form component that has some inputs (obviously). And both of them are imported and rendered in A.

So what I am trying to do is when the Save button in X clicked, I want the Form in the B to be submitted.

Thanks in advance.

答:
You can communicate with the parent from child and vice versa.

What you need to do is pass a handler to Component X from Component A and then in this handler using refs you can access the Child component form and trigger a submit like

A:

```<code>class A extends React.Component {
    constructor(props) {
        super(props);
    }
    buttonSubmit = () => {
           this.Yform.childForm.submit()

    }
    render() {
          return <div>
                <X triggerSubmit={this.buttonSubmit}/>
                <Y ref={(form) => this.Yform = form}/>
           </div>
    }
}
</code>```

X

```<code>class X extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <button onClick={() => this.props.triggerSubmit()}>Submit</button>
           </div>
    }
}
</code>```

Y:

```<code>class Y extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <form ref={(childForm) => {this.childForm = childForm}}>
                    ...
                </form>
           </div>
    }
}
</code>```

In case you are using Redux, then you need to do call an onSubmit like

```<code>  this.YForm.getWrappedInstance().submit()
</code>```

Body:
You can communicate with the parent from child and vice versa.

What you need to do is pass a handler to Component X from Component A and then in this handler using refs you can access the Child component form and trigger a submit like

A:

class A extends React.Component {
    constructor(props) {
        super(props);
    }
    buttonSubmit = () => {
           this.Yform.childForm.submit()

    }
    render() {
          return <div>
                <X triggerSubmit={this.buttonSubmit}/>
                <Y ref={(form) => this.Yform = form}/>
           </div>
    }
}

X

class X extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <button onClick={() => this.props.triggerSubmit()}>Submit</button>
           </div>
    }
}

Y:

class Y extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <form ref={(childForm) => {this.childForm = childForm}}>
                    ...
                </form>
           </div>
    }
}

In case you are using Redux, then you need to do call an onSubmit like

  this.YForm.getWrappedInstance().submit()


答:
Blueprint class offers dropPrimary methods that allow you to remove primary key.</p>

```<code>public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropPrimary();
        $table->unsignedInteger('id'); // for removing auto increment

    });
}
</code>```

Title: Remove primary key and auto-increment in database using migration in laravel

Body:
Blueprint class offers dropPrimary methods that allow you to remove primary key.

public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropPrimary();
        $table->unsignedInteger('id'); // for removing auto increment

    });
}


问:
git fails because of an untracked working tree file
I'm not an expert at google. Needless to say, I'm not even sure what this means or how to resolve it?

```<code>>> git merge admin_playground
error: Untracked working tree file 'vendor/gems/panda-1.0.0/.gitignore' would be overwritten by merge.
fatal: merging of trees 538b2824765956cc44c42a8ad628e4f4 and d5d4cda68518cd1c81bf70ba8c339fea6 failed
</code>```

I am trying to perform a git merge and getting this failing statement.

答:
Try running below commands :</p>

```<code>git add *

git stash

git pull
</code>```

Body:
I'm not an expert at google. Needless to say, I'm not even sure what this means or how to resolve it?

>> git merge admin_playground
error: Untracked working tree file 'vendor/gems/panda-1.0.0/.gitignore' would be overwritten by merge.
fatal: merging of trees 538b2824765956cc44c42a8ad628e4f4 and d5d4cda68518cd1c81bf70ba8c339fea6 failed

I am trying to perform a git merge and getting this failing statement.

Body:
Try running below commands :

git add *

git stash

git pull


问:
Python reading xml file with multiple namespace
```<code>  <?xml version="1.0" encoding="UTF-8"?>
        <country:list version="3.0" xmlns:country="http://Some/www.home.com" xmlns:region="http://some/www.hello.com" xmlns:Location="http://Some/www.home.com">
            <country:Region111>
                <Some_child_tags>
                    <region:tag1 name="1">some contents in country:Region111 </region:tag1>

                    <tags>

                            .
                            .
                            .
                            .
                    </tags>
                    <region:tag1 name="2">Some other contents in country:Region111</region:tag1>
                </Some_child_tags>
            </country:Region111>

            <Location:Region222>
            <Some_child_tags>
                    <region:tag1 name="1">some contents in Location:Region222</region:tag1>
                    <tags>

                            .
                            .
                            .
                            .
                    </tags>
                    <region:tag1 name="2">Some other contents in Location:Region222</region:tag1>
                </Some_child_tags>
            </Location:Region222>
        </country:list>
</code>```

I want to retrieve all the <region:tag1> tag contens and attribute
  values also that is comming under
  <country:Region111>...</country:Region111> not under
    <Location:Region222> ....</Location:Region222>.       So the final
  output should be the following

```<code>name 1 some contents in country:Region111
name 2 Some other contents in country:Region111
</code>```

```<code>      It should eliminate the <region:tag1> contents that is coming from <Location:Region222>.
</code>```

答:
Your input XML document should look as below (to be valid):

```<code><?xml version="1.0" encoding="UTF-8"?>
<country:list version="3.0" xmlns:country="http://Some/www.home.com" xmlns:region="http://some/www.hello.com">
<country:Region111>
     <Some_child_tags>
      <region:tag1>some contents</region:tag1>
     </Some_child_tags>
</country:Region111>
</country:list>
</code>```

The solution using xml.etree.ElementTree module:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse("yourfile.xml")
root = tree.getroot()
tag1 = root.find('.//{http://some/www.hello.com}tag1')  # accessing tag with namespace

print(tag1.text)
</code>```

The output:

```<code>some contents
</code>```

Body:
  <?xml version="1.0" encoding="UTF-8"?>
        <country:list version="3.0" xmlns:country="http://Some/www.home.com" xmlns:region="http://some/www.hello.com" xmlns:Location="http://Some/www.home.com">
            <country:Region111>
                <Some_child_tags>
                    <region:tag1 name="1">some contents in country:Region111 </region:tag1>

                    <tags>

                            .
                            .
                            .
                            .
                    </tags>
                    <region:tag1 name="2">Some other contents in country:Region111</region:tag1>
                </Some_child_tags>
            </country:Region111>

            <Location:Region222>
            <Some_child_tags>
                    <region:tag1 name="1">some contents in Location:Region222</region:tag1>
                    <tags>

                            .
                            .
                            .
                            .
                    </tags>
                    <region:tag1 name="2">Some other contents in Location:Region222</region:tag1>
                </Some_child_tags>
            </Location:Region222>
        </country:list>

I want to retrieve all the <region:tag1> tag contens and attribute
  values also that is comming under
  <country:Region111>...</country:Region111> not under
    <Location:Region222> ....</Location:Region222>.       So the final
  output should be the following

name 1 some contents in country:Region111
name 2 Some other contents in country:Region111

      It should eliminate the <region:tag1> contents that is coming from <Location:Region222>.

Body:
Your input XML document should look as below (to be valid):

<?xml version="1.0" encoding="UTF-8"?>
<country:list version="3.0" xmlns:country="http://Some/www.home.com" xmlns:region="http://some/www.hello.com">
<country:Region111>
     <Some_child_tags>
      <region:tag1>some contents</region:tag1>
     </Some_child_tags>
</country:Region111>
</country:list>

The solution using xml.etree.ElementTree module:

import xml.etree.ElementTree as ET

tree = ET.parse("yourfile.xml")
root = tree.getroot()
tag1 = root.find('.//{http://some/www.hello.com}tag1')  # accessing tag with namespace

print(tag1.text)

The output:

some contents


问:
how to solve this exception :Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
i got this exception after i run my code i don't know what is the problem!!

the program initially creates int array then string array with the same length same as int,then take every index in v and convert it to binary and adds zeroes if the digits less than 4 then store it in the string index after manipulating the string array it passes it to method Called toBinaryInteger which return int array the toBinaryInteger method creates an array of length st.length*4 which supposed to be 32 then takes each entery from st and takes each digit of it and stores it in the p array then the program print the result but the exception is shown up at this moment of time . i hope i explain the program very well . any idea help please.

hi every body problem solved  the problem is i was printing the wrong array insted of result i printed st special tankx for the good debugger

```<code> public static void main(String [] arg)
    {
        int [] v={0,11,12,13,14,15,7,8};
        String [] st=new String [v.length];
        String x="";
        for(int i=0;i<st.length;i++)
        {
            x=Integer.toBinaryString(v[i]);
            while (x.length()<4)    // add zeroed to left if needed to fit in 4 bits
                x="0"+x;
            st[i]=x;

        }
        int [] result=toBinaryInteger(st);
        int count=0;
        for(int k=0;k<result.length;k++)
        {
            System.out.print(st[k]);
            if(count==4){
                System.out.print("  ");
                count=0;
            }

        }

    }

public static int [] toBinaryInteger(String [] s)
    {
        int [] p=new int [s.length*4];
        for(int i=0;i<s.length;i++)
            {
            for(int j=0; j<s[i].length();j++){
                p[i*4+j]=Integer.parseInt(s[i].substring(j,j+1));//create array of 32 lenght

                }
            }
            return p;
    }
</code>```

答:
I compiled your code.  The resulting error told me that the problem appears to be this line:

```<code>System.out.print(st[k]);
</code>```

Perhaps you meant to print result[k] there instead?

Body:
i got this exception after i run my code i don't know what is the problem!!

the program initially creates int array then string array with the same length same as int,then take every index in v and convert it to binary and adds zeroes if the digits less than 4 then store it in the string index after manipulating the string array it passes it to method Called toBinaryInteger which return int array the toBinaryInteger method creates an array of length st.length*4 which supposed to be 32 then takes each entery from st and takes each digit of it and stores it in the p array then the program print the result but the exception is shown up at this moment of time . i hope i explain the program very well . any idea help please.

hi every body problem solved  the problem is i was printing the wrong array insted of result i printed st special tankx for the good debugger

 public static void main(String [] arg)
    {
        int [] v={0,11,12,13,14,15,7,8};
        String [] st=new String [v.length];
        String x="";
        for(int i=0;i<st.length;i++)
        {
            x=Integer.toBinaryString(v[i]);
            while (x.length()<4)    // add zeroed to left if needed to fit in 4 bits
                x="0"+x;
            st[i]=x;

        }
        int [] result=toBinaryInteger(st);
        int count=0;
        for(int k=0;k<result.length;k++)
        {
            System.out.print(st[k]);
            if(count==4){
                System.out.print("  ");
                count=0;
            }

        }

    }

public static int [] toBinaryInteger(String [] s)
    {
        int [] p=new int [s.length*4];
        for(int i=0;i<s.length;i++)
            {
            for(int j=0; j<s[i].length();j++){
                p[i*4+j]=Integer.parseInt(s[i].substring(j,j+1));//create array of 32 lenght

                }
            }
            return p;
    }

Body:
I compiled your code.  The resulting error told me that the problem appears to be this line:

System.out.print(st[k]);

Perhaps you meant to print result[k] there instead?


问:
Processing - Image array error - "Type mismatch, 'processing .core.PImage' does not match.."
I'm trying to load images into an array in the void setup(), but when I do it gives me this error: "Type mismatch, 'processing .core.PImage' does not match 'processing.core.PImage'. Any idea what this means and how to fix it? Here's my simplified code:

```<code>PImage [] goodCandy = new PImage [3];
int rand=(int) (2*Math.random()) +1;

void setup() {
for (int i=0; i<goodCandy.length; i++) {
  goodCandy = loadImage ("goodCandy" + i + ".png");
}
}
void draw() {
if (current=="play") {
loadStuff();
}
}
void loadStuff() {
image(goodCandy[rand], 0, 0, 50, 50);
}
</code>```

I basically want to generate a random candy from the array and have it appear, but I get this error. I have all 3 images in the folder named goodCandy1, 2, 3.png. Any ideas how to fix this?

答:
goodCandy[i] = loadImage("goodCandy" + i + ".png");

The mismatch occurred because you tried to store PImage in PImage[].
remember that loadImage() returns a PImage and not an array of PImage, i.e., PImage[]

Body:
I'm trying to load images into an array in the void setup(), but when I do it gives me this error: "Type mismatch, 'processing .core.PImage' does not match 'processing.core.PImage'. Any idea what this means and how to fix it? Here's my simplified code:

PImage [] goodCandy = new PImage [3];
int rand=(int) (2*Math.random()) +1;

void setup() {
for (int i=0; i<goodCandy.length; i++) {
  goodCandy = loadImage ("goodCandy" + i + ".png");
}
}
void draw() {
if (current=="play") {
loadStuff();
}
}
void loadStuff() {
image(goodCandy[rand], 0, 0, 50, 50);
}

I basically want to generate a random candy from the array and have it appear, but I get this error. I have all 3 images in the folder named goodCandy1, 2, 3.png. Any ideas how to fix this?


问:
PHP POST not saving my data in mysql , checking my api using postman
I am playing around with php, i wish to make a simple api to save my name field in database using chrome postman

The is my php code:

```<code><?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
header('Cache-Control: max-age=900');
header("Content-Type: application/json"); // tell client that we are sending json data

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$dxname  =$_GET['name'];

$sql = "INSERT INTO crudtable(firstname, lastname, email,favjob)
VALUES ('".$dxname."', 'Doe', 'john@example.com','coder')";

if ($conn->query($sql) === TRUE) {
    echo json_encode("New record created successfully");
   // echo "New record created successfully";
} else {
    echo json_encode("Some error");
   // echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

When i am using postman ,
1. the name is not getting saved in db [only hard coded values are being saved]
2. I am not getting echo json_encode("New record created successfully"); once data is saved.

Please help, attaching screenshot of my postman result and how i am passing the name variable

Click here to see the image

答:
Json should be an array.. try this

```<code>echo json_encode(array("Success"));
</code>```

where did you get the $_GET method? can you show us the html page? you can try using
 $_POST['name'];

Body:
I am playing around with php, i wish to make a simple api to save my name field in database using chrome postman

The is my php code:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
header('Cache-Control: max-age=900');
header("Content-Type: application/json"); // tell client that we are sending json data

$servername = "localhost";
$username = "";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$dxname  =$_GET['name'];

$sql = "INSERT INTO crudtable(firstname, lastname, email,favjob)
VALUES ('".$dxname."', 'Doe', 'john@example.com','coder')";

if ($conn->query($sql) === TRUE) {
    echo json_encode("New record created successfully");
   // echo "New record created successfully";
} else {
    echo json_encode("Some error");
   // echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

When i am using postman ,
1. the name is not getting saved in db [only hard coded values are being saved]
2. I am not getting echo json_encode("New record created successfully"); once data is saved.

Please help, attaching screenshot of my postman result and how i am passing the name variable

Click here to see the image

Body:
Json should be an array.. try this

echo json_encode(array("Success"));

where did you get the $_GET method? can you show us the html page? you can try using
 $_POST['name'];


问:
Get free disk space
Given each of the inputs below, I'd like to get free space on that location. Something like

```<code>long GetFreeSpace(string path)
</code>```

Inputs:

```<code>c:

c:\

c:\temp

\\server

\\server\C\storage
</code>```

答:
I had the same problem and i saw waruna manjula giving the best answer.
However writing it all down on the console is not what you might want.
To get string off al info use the following

Step one: declare values at begin

```<code>    //drive 1
    public static string drivename = "";
    public static string drivetype = "";
    public static string drivevolumelabel = "";
    public static string drivefilesystem = "";
    public static string driveuseravailablespace = "";
    public static string driveavailablespace = "";
    public static string drivetotalspace = "";

    //drive 2
    public static string drivename2 = "";
    public static string drivetype2 = "";
    public static string drivevolumelabel2 = "";
    public static string drivefilesystem2 = "";
    public static string driveuseravailablespace2 = "";
    public static string driveavailablespace2 = "";
    public static string drivetotalspace2 = "";

    //drive 3
    public static string drivename3 = "";
    public static string drivetype3 = "";
    public static string drivevolumelabel3 = "";
    public static string drivefilesystem3 = "";
    public static string driveuseravailablespace3 = "";
    public static string driveavailablespace3 = "";
    public static string drivetotalspace3 = "";
</code>```

Step 2: actual code

```<code>                DriveInfo[] allDrives = DriveInfo.GetDrives();
                int drive = 1;
                foreach (DriveInfo d in allDrives)
                {
                    if (drive == 1)
                    {
                        drivename = String.Format("Drive {0}", d.Name);
                        drivetype = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 2;
                    }
                    else if (drive == 2)
                    {
                        drivename2 = String.Format("Drive {0}", d.Name);
                        drivetype2 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 3;
                    }
                    else if (drive == 3)
                    {
                        drivename3 = String.Format("Drive {0}", d.Name);
                        drivetype3 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 4;
                    }
                    if (drive == 4)
                    {
                        drive = 1;
                    }
                }

                //part 2: possible debug - displays in output

                //drive 1
                Console.WriteLine(drivename);
                Console.WriteLine(drivetype);
                Console.WriteLine(drivevolumelabel);
                Console.WriteLine(drivefilesystem);
                Console.WriteLine(driveuseravailablespace);
                Console.WriteLine(driveavailablespace);
                Console.WriteLine(drivetotalspace);

                //drive 2
                Console.WriteLine(drivename2);
                Console.WriteLine(drivetype2);
                Console.WriteLine(drivevolumelabel2);
                Console.WriteLine(drivefilesystem2);
                Console.WriteLine(driveuseravailablespace2);
                Console.WriteLine(driveavailablespace2);
                Console.WriteLine(drivetotalspace2);

                //drive 3
                Console.WriteLine(drivename3);
                Console.WriteLine(drivetype3);
                Console.WriteLine(drivevolumelabel3);
                Console.WriteLine(drivefilesystem3);
                Console.WriteLine(driveuseravailablespace3);
                Console.WriteLine(driveavailablespace3);
                Console.WriteLine(drivetotalspace3);
</code>```

I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it.
If you display all these after each other you get the same list as waruna majuna

Drive C:\
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user:   134880153600 bytes
Total available space:   134880153600 bytes
Total size of drive:   499554185216 bytes

Drive D:\
Drive type: CDRom

Drive H:\
Drive type: Fixed
Volume label: HDD
File system: NTFS
Available space to current user:  2000010817536 bytes
Total available space:  2000010817536 bytes
Total size of drive:  2000263573504 bytes

However you can now acces all of the loose information at strings

Title: Get free disk space

Body:
Given each of the inputs below, I'd like to get free space on that location. Something like

long GetFreeSpace(string path)

Inputs:

c:

c:\

c:\temp

\\server

\\server\C\storage

Body:
I had the same problem and i saw waruna manjula giving the best answer.
However writing it all down on the console is not what you might want.
To get string off al info use the following

Step one: declare values at begin

    //drive 1
    public static string drivename = "";
    public static string drivetype = "";
    public static string drivevolumelabel = "";
    public static string drivefilesystem = "";
    public static string driveuseravailablespace = "";
    public static string driveavailablespace = "";
    public static string drivetotalspace = "";

    //drive 2
    public static string drivename2 = "";
    public static string drivetype2 = "";
    public static string drivevolumelabel2 = "";
    public static string drivefilesystem2 = "";
    public static string driveuseravailablespace2 = "";
    public static string driveavailablespace2 = "";
    public static string drivetotalspace2 = "";

    //drive 3
    public static string drivename3 = "";
    public static string drivetype3 = "";
    public static string drivevolumelabel3 = "";
    public static string drivefilesystem3 = "";
    public static string driveuseravailablespace3 = "";
    public static string driveavailablespace3 = "";
    public static string drivetotalspace3 = "";

Step 2: actual code

                DriveInfo[] allDrives = DriveInfo.GetDrives();
                int drive = 1;
                foreach (DriveInfo d in allDrives)
                {
                    if (drive == 1)
                    {
                        drivename = String.Format("Drive {0}", d.Name);
                        drivetype = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 2;
                    }
                    else if (drive == 2)
                    {
                        drivename2 = String.Format("Drive {0}", d.Name);
                        drivetype2 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel2 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem2 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace2 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace2 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace2 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 3;
                    }
                    else if (drive == 3)
                    {
                        drivename3 = String.Format("Drive {0}", d.Name);
                        drivetype3 = String.Format("Drive type: {0}", d.DriveType);
                        if (d.IsReady == true)
                        {
                            drivevolumelabel3 = String.Format("Volume label: {0}", d.VolumeLabel);
                            drivefilesystem3 = String.Format("File system: {0}", d.DriveFormat);
                            driveuseravailablespace3 = String.Format("Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
                            driveavailablespace3 = String.Format("Total available space:{0, 15} bytes", d.TotalFreeSpace);
                            drivetotalspace3 = String.Format("Total size of drive:{0, 15} bytes ", d.TotalSize);
                        }
                        drive = 4;
                    }
                    if (drive == 4)
                    {
                        drive = 1;
                    }
                }

                //part 2: possible debug - displays in output

                //drive 1
                Console.WriteLine(drivename);
                Console.WriteLine(drivetype);
                Console.WriteLine(drivevolumelabel);
                Console.WriteLine(drivefilesystem);
                Console.WriteLine(driveuseravailablespace);
                Console.WriteLine(driveavailablespace);
                Console.WriteLine(drivetotalspace);

                //drive 2
                Console.WriteLine(drivename2);
                Console.WriteLine(drivetype2);
                Console.WriteLine(drivevolumelabel2);
                Console.WriteLine(drivefilesystem2);
                Console.WriteLine(driveuseravailablespace2);
                Console.WriteLine(driveavailablespace2);
                Console.WriteLine(drivetotalspace2);

                //drive 3
                Console.WriteLine(drivename3);
                Console.WriteLine(drivetype3);
                Console.WriteLine(drivevolumelabel3);
                Console.WriteLine(drivefilesystem3);
                Console.WriteLine(driveuseravailablespace3);
                Console.WriteLine(driveavailablespace3);
                Console.WriteLine(drivetotalspace3);

I want to note that you can just make all the console writelines comment code, but i thought it would be nice for you to test it.
If you display all these after each other you get the same list as waruna majuna

Drive C:\
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user:   134880153600 bytes
Total available space:   134880153600 bytes
Total size of drive:   499554185216 bytes

Drive D:\
Drive type: CDRom

Drive H:\
Drive type: Fixed
Volume label: HDD
File system: NTFS
Available space to current user:  2000010817536 bytes
Total available space:  2000010817536 bytes
Total size of drive:  2000263573504 bytes

However you can now acces all of the loose information at strings


问:
JScrollPane is not Working in JPanel
I have to use JScrollPane in my Project but it is not working.

I have pasted my code where I use a JSCrollPane in my main JPanel.

```<code>frame = new JFrame();
        frame.setBounds(100, 100, 1179, 733);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setBounds(0, 0, 1163, 694);
        frame.getContentPane().add(scrollPane_1);

        JPanel panel = new JPanel();
        scrollPane_1.setViewportView(panel);
        panel.setLayout(null);
</code>```

答:
Setting the layout to Null means you need to handle the placement manually --> Specify the pixel location and handle the size of the container.

A layout manager handles this placement for you. The manager calculates its preferred size based on its content. The ScrollPane uses this calculated size from the layout manager.

This means you should use a layout manager, place your components within it. The rest should work automatically.

```<code> public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(30, 15));
    for (int row = 0; row < 30; row++) {
        for (int col = 0; col < 15; col++) {
            panel.add(new Button("Button" + row + "/" + col));
        }
    }

    frame.getContentPane().add(new JScrollPane(panel));
    frame.setVisible(true);
}
</code>```

Title: JScrollPane is not Working in JPanel

Body:
I have to use JScrollPane in my Project but it is not working.

I have pasted my code where I use a JSCrollPane in my main JPanel.

frame = new JFrame();
        frame.setBounds(100, 100, 1179, 733);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setBounds(0, 0, 1163, 694);
        frame.getContentPane().add(scrollPane_1);

        JPanel panel = new JPanel();
        scrollPane_1.setViewportView(panel);
        panel.setLayout(null);

Body:
Setting the layout to Null means you need to handle the placement manually --> Specify the pixel location and handle the size of the container.

A layout manager handles this placement for you. The manager calculates its preferred size based on its content. The ScrollPane uses this calculated size from the layout manager.

This means you should use a layout manager, place your components within it. The rest should work automatically.

 public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(500, 500);

    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(30, 15));
    for (int row = 0; row < 30; row++) {
        for (int col = 0; col < 15; col++) {
            panel.add(new Button("Button" + row + "/" + col));
        }
    }

    frame.getContentPane().add(new JScrollPane(panel));
    frame.setVisible(true);
}


问:
Webpack where is that /main/ folder coming from?
When I reload my first page, I get this error. (sorry I am pretty new at this)

```<code>Uncaught Error: Module build failed: Error: ENOENT: no such file or directory, open 'G:\Github\thaihome\app\main\app.js'
    at Error (native)
    at Error (native)
    at eval (eval at <anonymous> (http://localhost:8080/app.bundle.js:305:1), <anonymous>:1:7)
</code>```

I did a search for main in all files but cannot find main anywhere.

This is from my webpack:

```<code>  config.entry = {
    app: './app/app.js'
  };
</code>```

Also as I understand, it compiles to app.bundle.js but where is that file located?

I wonder if the main is some default setting somewhere I have not looked?

Here is a screenshot of my folder structure:

答: Solution to the problem is to change /* comment to /**. Thanks @torbenrudgaard</p>

Body:
When I reload my first page, I get this error. (sorry I am pretty new at this)

Uncaught Error: Module build failed: Error: ENOENT: no such file or directory, open 'G:\Github\thaihome\app\main\app.js'
    at Error (native)
    at Error (native)
    at eval (eval at <anonymous> (http://localhost:8080/app.bundle.js:305:1), <anonymous>:1:7)

I did a search for main in all files but cannot find main anywhere.

This is from my webpack:

  config.entry = {
    app: './app/app.js'
  };

Also as I understand, it compiles to app.bundle.js but where is that file located?

I wonder if the main is some default setting somewhere I have not looked?

Here is a screenshot of my folder structure:


问:
Bootstrap 4 Cards of same height in columns
I'm currently working on Cards from Bootstrap.

Depending on the text title I will get the different height for the cards and would like to have the same height as the tallest one.

I don't mind using JS I actually think is probably the best way to approach the problem.

I have tried using different solutions from the CSS like using flexbox.

The rendered HTML as it is rendered dynamically here's a simple example:

.card {
  float: left;
  width: 100%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 0;
  box-shadow: 0px 0px 8px 0.3px rgba(0, 0, 0, 1);
}

.card>img {
  margin-bottom: .75rem;
  display: block;
  width: 80%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}

.card-text {
  font-size: 85%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SMITE FR</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/album.css" rel="stylesheet">
  <link href="css/ie10-viewport-bug-workaround.min.css" rel="stylesheet">
  <script src="https://www.w3schools.com/lib/w3data.js"></script>
  <link rel="import" href="navigation.html">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="card-deck">
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="BeatsX">
            <h1 class="card-title">BeatsX</h1>
            <div class="text-center">
              <p>1188.0000</p>
              <p>2017-06-09 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="Nitendo Switch">
            <h1 class="card-title">Nitendo Switch</h1>
            <div class="text-center">
              <p>2899.0000</p>
              <p>2017-06-10 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
        <div class="col-md-4 col-sm-6 col-12">
          <div class="card">
            <img src="images/dieux/Agni.jpg" alt="iPhone 7 128GB (Jet Blakc)">
            <h1 class="card-title">iPhone 7 128GB (Jet Blakc)</h1>
            <div class="text-center">
              <p>6388.0000</p>
              <p>2017-06-06 10:00:00</p>
              Voir la Fiche
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html></code>```

答: As far as I know not doable without either javascript or flexbox (https://osvaldas.info/flexbox-based-responsive-equal-height-blocks-with-javascript-fallback)</p>

Body:
I'm currently working on Cards from Bootstrap.

Depending on the text title I will get the different height for the cards and would like to have the same height as the tallest one.

I don't mind using JS I actually think is probably the best way to approach the problem.

I have tried using different solutions from the CSS like using flexbox.

The rendered HTML as it is rendered dynamically here's a simple example:

.card {
  float: left;
  width: 100%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 0;
  box-shadow: 0px 0px 8px 0.3px rgba(0, 0, 0, 1);
}

.card>img {
  margin-bottom: .75rem;
  display: block;
  width: 80%;
  height: auto;
  margin-left: auto;
  margin-right: auto;
}

.card-text {
  font-size: 85%;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>SMITE FR</title>
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/album.css" rel="stylesheet">
  <link href="css/ie10-viewport-bug-workaround.min.css" rel="stylesheet">

  <link rel="import" href="navigation.html">

BeatsX

1188.0000

2017-06-09 10:00:00

              Voir la Fiche

Nitendo Switch

2899.0000

2017-06-10 10:00:00

              Voir la Fiche

iPhone 7 128GB (Jet Blakc)

6388.0000

2017-06-06 10:00:00

              Voir la Fiche


问:
KonvaJS rotate on touch devices
can you assist me?

https://konvajs.github.io/docs/sandbox/Multi-touch_Scale_Stage.html

this tutorial works perfectly, can you help me please make the rotation in same manner? i want to rotate my stage clockwise and counterclockwise.

答:
This simplest way is to add gesture recognition library and then use rotate event.

For example, I added https://zingchart.github.io/zingtouch/ library.

```<code>var containerElement = document.getElementById('container');
var activeRegion = ZingTouch.Region(containerElement);

var childElement = document.getElementById('container');
activeRegion.bind(childElement, 'rotate', function(event){
    stage.rotation(-event.detail.angle);
    stage.draw();
});
</code>```

Demo: https://jsfiddle.net/lavrton/7nLte356/9/

Title: KonvaJS rotate on touch devices

Body:
This simplest way is to add gesture recognition library and then use rotate event.

For example, I added https://zingchart.github.io/zingtouch/ library.

var containerElement = document.getElementById('container');
var activeRegion = ZingTouch.Region(containerElement);

var childElement = document.getElementById('container');
activeRegion.bind(childElement, 'rotate', function(event){
    stage.rotation(-event.detail.angle);
    stage.draw();
});

Demo: https://jsfiddle.net/lavrton/7nLte356/9/


问:
Bash script that analyzes report files
I have the following bash script which I will use to analyze all report files in the current directory:

```<code>#!/bin/bash

# methods
analyzeStructuralErrors()
{
    # do something with $1
}

# main
reportFiles=`find $PWD -name "*_report*.txt"`;
for f in $reportFiles
do
    echo "Processing $f"
    analyzeStructuralErrors $f
done
</code>```

My report files are formatted as such:

```<code>Error Code for Issue X - Description Text - Number of errors.
col1_name,col2_name,col3_name,col4_name,col5_name,col6_name
   1143-1-1411-247-1-72953-1
   1143-2-1411-247-436-72953-1
   2211-1-1888-204-442-22222-1
Error Code for Issue Y - Description Text - Number of errors.
col1_name,col2_name,col3_name,col4_name,col5_name,col6_name
   Other data
   .
   .
   .
</code>```

I'm looking for a way to go through each file and aggregate the report data.  In the above example, we have two unique issues of type X, which I would like to handle in analyzeStructural.  Other types of issues can be ignored in this routine.  Can anyone offer advice on how to do this?  I want to read each line until I hit the next error basically, and put that data into some kind of data structure.

答:
As suggested by Dave Jarvis, awk will:

handle this better than bash

is fairly easy to learn

likely available wherever bash is available

I've never had to look farther than The AWK Manual.

It would make things easier if you used a consistent field separator for both the list of column names and the data.  Perhaps you could do some pre-processing in a bash script using sed before feeding to awk.  Anyway, take a look at multi-dimensional arrays and reading multiple lines in the manual.

Title: Bash script that analyzes report files

Body:
I have the following bash script which I will use to analyze all report files in the current directory:

#!/bin/bash

# methods
analyzeStructuralErrors()
{
    # do something with $1
}

# main
reportFiles=`find $PWD -name "*_report*.txt"`;
for f in $reportFiles
do
    echo "Processing $f"
    analyzeStructuralErrors $f
done

My report files are formatted as such:

Error Code for Issue X - Description Text - Number of errors.
col1_name,col2_name,col3_name,col4_name,col5_name,col6_name
   1143-1-1411-247-1-72953-1
   1143-2-1411-247-436-72953-1
   2211-1-1888-204-442-22222-1
Error Code for Issue Y - Description Text - Number of errors.
col1_name,col2_name,col3_name,col4_name,col5_name,col6_name
   Other data
   .
   .
   .

I'm looking for a way to go through each file and aggregate the report data.  In the above example, we have two unique issues of type X, which I would like to handle in analyzeStructural.  Other types of issues can be ignored in this routine.  Can anyone offer advice on how to do this?  I want to read each line until I hit the next error basically, and put that data into some kind of data structure.


答:
I am not sure which layout you are using, but you need to set your panel layout something like this </p>

```<code>panel.setLayout(new FormLayout(
                        "default:grow",
                        "fill:default:grow"));
</code>```

Title: JScrollPane is not Working in JPanel

Body:
I am not sure which layout you are using, but you need to set your panel layout something like this

panel.setLayout(new FormLayout(
                        "default:grow",
                        "fill:default:grow"));


答:
Use flex for get it below an example

        .main {
            display: flex;
        }
        .child {
            flex:1;
            border:1px solid tomato;
        }
        .content {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-flow: column nowrap;
        }
        .content-child{
            padding: 5px;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
    <div class="child">
        <div class="content">
            <div class="content-child">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
            <div class="content-child">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
        </div>
    </div>
    <div class="child"></div>
</div></code>```

Title: Bootstrap 4 Cards of same height in columns

Body:
Use flex for get it below an example

        .main {
            display: flex;
        }
        .child {
            flex:1;
            border:1px solid tomato;
        }
        .content {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-flow: column nowrap;
        }
        .content-child{
            padding: 5px;
        }

<div class="main">
    <div class="child">
        <div class="content">
            <div class="content-child">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
            <div class="content-child">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
        </div>
    </div>
    <div class="child"></div>
</div>


问:
How to make two microservices listen on same port in azure service fabric
I have created a project with two microservices and want both of them to listen to same port.
I have two separate ServiceManifest File in which i have defined same endpoint for both of them but when i deploy it locally or remotely it doesn't work.

When I deploy it locally it shows following Exception:
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll

答:
Keep the "port number same in ServiceManifest.xml file for both the Microservices."

Just make the URL different for different services

For Ex localhost:8100/service1/....

 localhost:8100/service2/....

"Different appRoot for different services"


问:
Can I modify an xml file only from command line?
There is an auto-generated xml file.

```<code><?xml version="1.0" encoding="UTF-8"?>
  <widget id="some ID" modes="max">
  <icon src="icon.png"/>
  <name>StackOverflow</name>
  <feature name="some feature"/>
</code>```

I would like to achieve following:

subtitute modes with "full"

subtitute name with ${name}

remove <feature>

add <content src="index.html"/> in between <icon> and <name>

Can this be done?

[adding more background]

It is an website mostly made of node.js.  This shell command will be run on server-side Javascript and will be executed using child_process.exec().

答:
Since awk is also an standard GNU tool, I think it might meet your requirement.
It's an very straightforward script you can adopt.

```<code>awk '
  /modes/{gsub(/modes=".*"/,"modes=\"full\"") }
  /<icon/{$0=$0"\n  <content src=\"index.html\"/>"}
  /<name>/{gsub(/>.*</,">$name<")}
  !/feature/{print}
' Your_XML_file
</code>```

Output:

```<code><?xml version="1.0" encoding="UTF-8"?>
  <widget id="some ID" modes="full">
  <icon src="icon.png"/>
  <content src="index.html"/>
  <name>$name</name>
</code>```

And here's the brief explain I would give,

find modes and  in your xml file, and modify as you desire

find "< icon", and insert  below it.

remove the line contain feature

Body:
There is an auto-generated xml file.

<?xml version="1.0" encoding="UTF-8"?>
  <widget id="some ID" modes="max">
  <icon src="icon.png"/>
  <name>StackOverflow</name>
  <feature name="some feature"/>

I would like to achieve following:

subtitute modes with "full"

subtitute name with ${name}

remove <feature>

add <content src="index.html"/> in between <icon> and <name>

Can this be done?

[adding more background]

It is an website mostly made of node.js.  This shell command will be run on server-side Javascript and will be executed using child_process.exec().

Body:
Since awk is also an standard GNU tool, I think it might meet your requirement.
It's an very straightforward script you can adopt.

awk '
  /modes/{gsub(/modes=".*"/,"modes=\"full\"") }
  /<icon/{$0=$0"\n  <content src=\"index.html\"/>"}
  /<name>/{gsub(/>.*</,">$name<")}
  !/feature/{print}
' Your_XML_file

Output:

<?xml version="1.0" encoding="UTF-8"?>
  <widget id="some ID" modes="full">
  <icon src="icon.png"/>
  <content src="index.html"/>
  <name>$name</name>

And here's the brief explain I would give,

find modes and  in your xml file, and modify as you desire

find "< icon", and insert  below it.

remove the line contain feature


问:
IFTTT : Trying to run a php script using Maker webhooks
Good day,

I have created an IFTTT receipe that if a "myfox" alarm system is armed, a php script is executed on my NAS (192.165.x.x). The php script is supposed to trigger a stored procedure in my mysql database.

The following PHP script has been tested by other means and I'm sure that it works :

```<code><?php

/*
    php_update_mode_armed.php

    *****************************************************************************************
    * This script updates the value of the components in the table tbl_eedomus_current_mode
    * It calls the stored procedure 'sp_tbl_eedomus_current_mode_armed'
    *****************************************************************************************

    Version 1.00, 09.06.2017, Initial version of the script
*/

mainProcess();

function mainProcess()
{
    $ServerIP = "192.165.x.x";
    $sqlUser = "domoos";
    $sqlDatabase = "domoos";
$pw = "myPass";

    // Connect
    $mysqli = new mysqli($ServerIP, $sqlUser, $pw, $sqlDatabase);
    if(!$mysqli) {[![enter image description here][1]][1]
    header('Location: error.php?error=DbConnectionFailure');
    die();
    }

    // Call stored procedure sp_tbl_eedomus_current_mode_armed
    if(!$mysqli->query("CALL sp_tbl_eedomus_current_mode_armed ()"))
    {
        echo "OK";
    if($mysqli) $mysqli->close(); // Close DB connection
    //header('Location: error.php?error=QueryFailure');
    die();
    }

    if($mysqli) $mysqli->close(); // Close DB connection
}

?>
</code>```

Below, also, a screen shot of my "then" part of the IFTTT receipe.

Am I doing something wrong here or is the use of IFTTT not fit for the purpose I'm trying to achieve here?

Many thanks for your help on this matter and have a great day.

答:
Most likly IFTTT can't access your NAS from the internet due to home router firewall etc. Also the ip address used in IFTTT shouldn't be a local ip like 192.168.* but your public ip address. You can figure this out by googling for "whats my ip".

Best way to test your setup using your laptop is to disconnect from local wifi network, tether your phone to your laptop and try visiting the NAS ip url to see if it still works. You can use chrome postman app to send out POST requests.

If that's all fine, get PHP to log incoming connections by writing to a file. file_put_contents("log.txt", print_r($_REQUESTS, true));

I would suggest trying with a GET request first with default content type. Good luck!

Body:
Good day,

I have created an IFTTT receipe that if a "myfox" alarm system is armed, a php script is executed on my NAS (192.165.x.x). The php script is supposed to trigger a stored procedure in my mysql database.

The following PHP script has been tested by other means and I'm sure that it works :

<?php

/*
    php_update_mode_armed.php

    *****************************************************************************************
    * This script updates the value of the components in the table tbl_eedomus_current_mode
    * It calls the stored procedure 'sp_tbl_eedomus_current_mode_armed'
    *****************************************************************************************

    Version 1.00, 09.06.2017, Initial version of the script
*/

mainProcess();

function mainProcess()
{
    $ServerIP = "192.165.x.x";
    $sqlUser = "domoos";
    $sqlDatabase = "domoos";
$pw = "myPass";

    // Connect
    $mysqli = new mysqli($ServerIP, $sqlUser, $pw, $sqlDatabase);
    if(!$mysqli) {[![enter image description here][1]][1]
    header('Location: error.php?error=DbConnectionFailure');
    die();
    }

    // Call stored procedure sp_tbl_eedomus_current_mode_armed
    if(!$mysqli->query("CALL sp_tbl_eedomus_current_mode_armed ()"))
    {
        echo "OK";
    if($mysqli) $mysqli->close(); // Close DB connection
    //header('Location: error.php?error=QueryFailure');
    die();
    }

    if($mysqli) $mysqli->close(); // Close DB connection
}

?>

Below, also, a screen shot of my "then" part of the IFTTT receipe.

Am I doing something wrong here or is the use of IFTTT not fit for the purpose I'm trying to achieve here?

Many thanks for your help on this matter and have a great day.


问:
my url does not work correctly with spaces
my url wheen i send with php & mysql i get not the full url
i get only url to H&M and after that it stops just but i need the full in https link

```<code>$username = mysqli_real_escape_string($db, $_POST['username']);
 $confirmcode = rand();

https://www.example.be/verification.php?username=$username&code=$confirmcode";
</code>```

i get this wheen my username contains spaces **https://www.example.be/verifcation.php?username=H&M** *Autos&code=716006183*

答:
Why are you escaping something that goes into a URL using MySQL functions?

You should be using urlencode:

```<code>$username = urlencode($_POST['username']);
</code>```

Not all escaping functions do the same thing. Pay very close attention to context.

Body:
my url wheen i send with php & mysql i get not the full url
i get only url to H&M and after that it stops just but i need the full in https link

$username = mysqli_real_escape_string($db, $_POST['username']);
 $confirmcode = rand();

https://www.example.be/verification.php?username=$username&code=$confirmcode";

i get this wheen my username contains spaces **https://www.example.be/verifcation.php?username=H&M** *Autos&code=716006183*

Body:
Why are you escaping something that goes into a URL using MySQL functions?

You should be using urlencode:

$username = urlencode($_POST['username']);

Not all escaping functions do the same thing. Pay very close attention to context.


问:
ng2-tag-input 'tag-input' is not a known element Angular 2
I am attempting to install ng2-tag-input into my ionic app.

After successfully installing it with npm install, here is my app.component.ts

```<code>import {TagInputModule} from 'ng2-tag-input';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
    declarations   : [
        MyApp,
    ],
    imports        : [
        CommonModule,
        BrowserModule,
        HttpModule,
        PagesModule,
        TagInputModule,
        BrowserAnimationsModule,
        IonicModule.forRoot(MyApp, {}, {
            // DeepLinker
            // http://blog.ionic.io/deeplinking-in-ionic-apps/
            links: [
                {component: ProfilePage, name: 'Profile', segment: 'profile/:username'},
                {component: PhotoCardComponent, name: 'Photo', segment: 'photo/:id'},
                {component: ChatMessagePage, name: 'Chat', segment: 'chat/:id'},
                {component: TermsPage, name: 'Terms', segment: 'terms'},
            ]
        })
    ],
    exports        : [
        BrowserModule,
        HttpModule,
        TagInputModule
    ],
</code>```

Then when I run

```<code>ionic serve
</code>```

The following issue happens

```<code>Error: Uncaught (in promise): Error: Template parse errors:
'tag-input' is not a known element:
1. If 'tag-input' is an Angular component, then verify that it is part of this module.
2. If 'tag-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
                </ion-select>
            </ion-item>
            [ERROR ->]<tag-input [(ngModel)]="items"></tag-input>
</code>```

I am not sure what I did wrong. Can anyone help point it out?

答:
add FormModule into import into your app.component.ts.
  [(ngModule)] so need to import FormModule.

Body:
I am attempting to install ng2-tag-input into my ionic app.

After successfully installing it with npm install, here is my app.component.ts

import {TagInputModule} from 'ng2-tag-input';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({
    declarations   : [
        MyApp,
    ],
    imports        : [
        CommonModule,
        BrowserModule,
        HttpModule,
        PagesModule,
        TagInputModule,
        BrowserAnimationsModule,
        IonicModule.forRoot(MyApp, {}, {
            // DeepLinker
            // http://blog.ionic.io/deeplinking-in-ionic-apps/
            links: [
                {component: ProfilePage, name: 'Profile', segment: 'profile/:username'},
                {component: PhotoCardComponent, name: 'Photo', segment: 'photo/:id'},
                {component: ChatMessagePage, name: 'Chat', segment: 'chat/:id'},
                {component: TermsPage, name: 'Terms', segment: 'terms'},
            ]
        })
    ],
    exports        : [
        BrowserModule,
        HttpModule,
        TagInputModule
    ],

Then when I run

ionic serve

The following issue happens

Error: Uncaught (in promise): Error: Template parse errors:
'tag-input' is not a known element:
1. If 'tag-input' is an Angular component, then verify that it is part of this module.
2. If 'tag-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
                </ion-select>
            </ion-item>
            [ERROR ->]<tag-input [(ngModel)]="items"></tag-input>

I am not sure what I did wrong. Can anyone help point it out?