问:
Android: How to reset FirstRun SharedPreferences when my app is updated?
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?

Here is the relevant code:

```<code>/**
     * get if this is the first run
     *
     * @return returns true, if this is the first run
     */
        public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }

     /**
     * store the first run
     */
     public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }

     SharedPreferences mPrefs;

     /**
     * setting up preferences storage
     */
     public void firstRunPreferences() {
        Context mContext = this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
     }

     public void setStatus(String statustext) {
         SharedPreferences.Editor edit = mPrefs.edit();
         edit.putString("status", statustext);
         edit.commit();
      }

}
</code>```

答:
In my app, I save in my shared preferences the version code of the app. At every startup, I check to see if the saved version code is lower than my current version code. If it is, I show a "what's new" dialog.

Give this code a whirl - I use it in my main activity's onCreate:

```<code>    PackageInfo pInfo;
    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
        if ( prefs.getLong( "lastRunVersionCode", 0) < pInfo.versionCode ) {
            // TODO: Handle your first-run situation here

            Editor editor = prefs.edit();
            editor.putLong("lastRunVersionCode", pInfo.versionCode);
            editor.commit();
        }
    } catch (NameNotFoundException e) {
        // TODO Something pretty serious went wrong if you got here...
        e.printStackTrace();
    }
</code>```

prefs is a private SharedPreferences object. This works if it's truly the first run, and for upgrades. At the end of the first-run code, the editor.putLong updates your shared preferences with the current version code of your app so the next run doesn't trigger your first-run code.

This also benefits from the fact that your version code must increase for the app to be seen as an upgrade by the market, so you don't need to remember to change a separate value to detect the first-run.

Body:
My app copies files over from res/raw to the sdcard on first run. I want it to update those files on every subsequent app update. How can i have it reset the firstrun preference to true on every app update?

Here is the relevant code:

/**
     * get if this is the first run
     *
     * @return returns true, if this is the first run
     */
        public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }

     /**
     * store the first run
     */
     public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }

     SharedPreferences mPrefs;

     /**
     * setting up preferences storage
     */
     public void firstRunPreferences() {
        Context mContext = this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
     }

     public void setStatus(String statustext) {
         SharedPreferences.Editor edit = mPrefs.edit();
         edit.putString("status", statustext);
         edit.commit();
      }

}

Body:
In my app, I save in my shared preferences the version code of the app. At every startup, I check to see if the saved version code is lower than my current version code. If it is, I show a "what's new" dialog.

Give this code a whirl - I use it in my main activity's onCreate:

    PackageInfo pInfo;
    try {
        pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
        if ( prefs.getLong( "lastRunVersionCode", 0) < pInfo.versionCode ) {
            // TODO: Handle your first-run situation here

            Editor editor = prefs.edit();
            editor.putLong("lastRunVersionCode", pInfo.versionCode);
            editor.commit();
        }
    } catch (NameNotFoundException e) {
        // TODO Something pretty serious went wrong if you got here...
        e.printStackTrace();
    }

prefs is a private SharedPreferences object. This works if it's truly the first run, and for upgrades. At the end of the first-run code, the editor.putLong updates your shared preferences with the current version code of your app so the next run doesn't trigger your first-run code.

This also benefits from the fact that your version code must increase for the app to be seen as an upgrade by the market, so you don't need to remember to change a separate value to detect the first-run.


来源: stackexchange

问:
JMeter JSON Extractor to get values as an array
I would like to extract variable from a JSON output as an array of values. I use JSON extractor on Main samples and sub-samples. I got two variables, when I check it with a Debug sampler: myvariable has a single value and myvariable__matchNr=25. There are 25 occurences of this variable, so I need all the 25 values too.

答: Option Match No. in JSON extractor has to be -1 to get all the values with variable name: myvariable_X.

ContentLicense: CC BY-SA 3.0


问:
How to get a mysql output to a php variable?
Here I have two variables called $semresult, $examresult where i need to store the results of two respective queries. And then I need to do a calculation with them. The code I tried so far is

```<code>  $output = '';
  $connect = mysqli_connect("localhost", "root", "", "crudnew");

        $semfee = "select sum(amount) from semesterfees";
        $semresult = mysqli_query($connect,$semfee);

        $examfee = "select sum(amount) from examfees";
        $examresult = mysqli_query($connect,$examfee);

        $income = ((int)$semresult + (int)$examresult);
</code>```

But whenever I run the above code $semresult, $examresult gets the error "object of class mysqli_result could not be converted to int". Please help :')

答:
```<code>$semfee = "select sum(amount) as total from semesterfees";
$result = mysqli_query($connect,$semfee);

$row = mysqli_fetch_assoc($result);

$semresult = $row['total'];
</code>```

And then you do the same for the second query.

Here you can read more about mysqli_fetch_assoc and what it does.

Body:
Here I have two variables called $semresult, $examresult where i need to store the results of two respective queries. And then I need to do a calculation with them. The code I tried so far is

  $output = '';
  $connect = mysqli_connect("localhost", "root", "", "crudnew");

        $semfee = "select sum(amount) from semesterfees";
        $semresult = mysqli_query($connect,$semfee);

        $examfee = "select sum(amount) from examfees";
        $examresult = mysqli_query($connect,$examfee);

        $income = ((int)$semresult + (int)$examresult);

But whenever I run the above code $semresult, $examresult gets the error "object of class mysqli_result could not be converted to int". Please help :')

Body:
$semfee = "select sum(amount) as total from semesterfees";
$result = mysqli_query($connect,$semfee);

$row = mysqli_fetch_assoc($result);

$semresult = $row['total'];

And then you do the same for the second query.

Here you can read more about mysqli_fetch_assoc and what it does.


问:
WSO2 ESB / EI as JMS Topic consumer - Write to File
first of all: I'm quite new to the WSO2 products but I have taken the time to read through some post regarding to my issue.

What product I use: WSO EI 6.1.1

What I want to achive: Establish a  JMS-Connection to an TIBCO EMS (MOM), subscribe for a given topic and write the recived message to the filesystem as xml file. The given folder is a mounted netdrive and further applications will look up for new files inside the given folder, this is due to legacy code and I don't want (dont have the time) to change the folder lookup for e.g. a soap calls.

What I've already done: I've read through the latest documentation and found this one:
Configure with Tibco EMS

After some try and error I think I've achived to setting up the JMS Listener for the TIBCO EMS. At the beginning I've received a bunch of connection and auth errors which are fixed now, so I think the general connection to the tibco server works.

```<code><transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
<parameter name="TopicConnectionFactory" locked="false">
    <parameter locked="false" name="java.naming.factory.initial">com.tibco.tibjms.naming.TibjmsInitialContextFactory</parameter>
    <parameter locked="false" name="java.naming.provider.url">tcp://172.123.123.123:123</parameter>
    <parameter locked="false" name="java.naming.security.principal">user</parameter>
    <parameter locked="false" name="java.naming.security.credentials">pass</parameter>
    <parameter locked="false" name="transport.jms.ConnectionFactoryJNDIName">TopicConnectionFactory</parameter>
    <parameter locked="false" name="transport.jms.JMSSpecVersion">1.0.2b</parameter>
    <parameter locked="false" name="transport.jms.ConnectionFactoryType">topic</parameter>
    <parameter locked="false" name="transport.jms.UserName">user</parameter>
    <parameter locked="false" name="transport.jms.Password">pass</parameter>
    <parameter locked="false" name="transport.jms.CacheLevel">session</parameter>
</parameter>
</transportReceiver>
</code>```

I think the next step would be to subscribe to the specific topic and write it to the filesystem but I'm kind of stuck here. The other examples in the documentation sadly doesn't help me here, maybe I'm missing the big picture how to continue here because I'm quite new to the esb / ei product.

I simply don't know which functional component is needed (endpoint, proxy, to make use of the configured jms connection and how to write it to the filesystem.

It would be great if someone could push me into the right direction.

kind regards

答:
First you need to have a JMS proxy or a inbound endpoint to listen on your queue. Refer [1]. Then you need to use the file processing capabilities of WSO2 ESB (VFS transport). Refer [2] on fileWriteSequence sequence.After receiving a message from the queue, you should invoke this type of a sequence in your proxy service or the inbound endpoint.

[1] - https://docs.wso2.com/display/ESB500/ESB+as+a+JMS+Consumer
[2] - https://docs.wso2.com/display/ESB500/Sample+271%3A+File+Processing#Sample271:FileProcessing-CreateandConfigurefileWriteSequence

Body:
first of all: I'm quite new to the WSO2 products but I have taken the time to read through some post regarding to my issue.

What product I use: WSO EI 6.1.1

What I want to achive: Establish a  JMS-Connection to an TIBCO EMS (MOM), subscribe for a given topic and write the recived message to the filesystem as xml file. The given folder is a mounted netdrive and further applications will look up for new files inside the given folder, this is due to legacy code and I don't want (dont have the time) to change the folder lookup for e.g. a soap calls.

What I've already done: I've read through the latest documentation and found this one:
Configure with Tibco EMS

After some try and error I think I've achived to setting up the JMS Listener for the TIBCO EMS. At the beginning I've received a bunch of connection and auth errors which are fixed now, so I think the general connection to the tibco server works.

<transportReceiver name="jms" class="org.apache.axis2.transport.jms.JMSListener">
<parameter name="TopicConnectionFactory" locked="false">
    <parameter locked="false" name="java.naming.factory.initial">com.tibco.tibjms.naming.TibjmsInitialContextFactory</parameter>
    <parameter locked="false" name="java.naming.provider.url">tcp://172.123.123.123:123</parameter>
    <parameter locked="false" name="java.naming.security.principal">user</parameter>
    <parameter locked="false" name="java.naming.security.credentials">pass</parameter>
    <parameter locked="false" name="transport.jms.ConnectionFactoryJNDIName">TopicConnectionFactory</parameter>
    <parameter locked="false" name="transport.jms.JMSSpecVersion">1.0.2b</parameter>
    <parameter locked="false" name="transport.jms.ConnectionFactoryType">topic</parameter>
    <parameter locked="false" name="transport.jms.UserName">user</parameter>
    <parameter locked="false" name="transport.jms.Password">pass</parameter>
    <parameter locked="false" name="transport.jms.CacheLevel">session</parameter>
</parameter>
</transportReceiver>

I think the next step would be to subscribe to the specific topic and write it to the filesystem but I'm kind of stuck here. The other examples in the documentation sadly doesn't help me here, maybe I'm missing the big picture how to continue here because I'm quite new to the esb / ei product.

I simply don't know which functional component is needed (endpoint, proxy, to make use of the configured jms connection and how to write it to the filesystem.

It would be great if someone could push me into the right direction.

kind regards


问:
Remove all constraints affecting a UIView
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

```<code>[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];
</code>```

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

答:
Details

Xcode 10.2.1 (10E1001), Swift 5

Solution

```<code>import UIKit

extension UIView {

    func removeConstraints() { removeConstraints(constraints) }
    func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
    func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }

    func getAllConstraints() -> [NSLayoutConstraint] {
        var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
        if let superview = self.superview {
            subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
                if let view = constraint.firstItem as? UIView, view == self { return constraint }
                return nil
            }
        }
        return subviewsConstraints + constraints
    }

    class func getAllSubviews(view: UIView) -> [UIView] {
        return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
    }
}
</code>```

Usage

```<code>print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()
</code>```

Body:
I have a UIView which is placed on the screen via several constraints. Some of the constraints are owned by the superview, others are owned by other ancestors (e.g. perhaps the view property of a UIViewController).

I want to remove all of these old constraints, and place it somewhere new using new constraints.

How can I do this without creating an IBOutlet for every single constraint and having to remember which view owns said constraint?

To elaborate, the naive approach would be to create a bunch of IBOutlets for each of the constraints, and would then involve calling code such as:

[viewA removeConstraint:self.myViewsLeftConstraint];
[viewB removeConstraint:self.myViewsTopConstraint];
[viewB removeConstraint:self.myViewsBottomConstraint];
[self.view removeConstraint:self.myViewsRightConstraint];

The problem with this code is that even in the simplest case, I would need to create 2 IBOutlets. For complex layouts, this could easily reach 4 or 8 required IBOutlets. Furthermore, I would need to ensure that my call to remove the constraint is being called on the proper view. For example, imagine that myViewsLeftConstraint is owned by viewA. If I were to accidentally call [self.view removeConstraint:self.myViewsLeftConstraint], nothing would happen.

Note: The method constraintsAffectingLayoutForAxis looks promising, but is intended for debugging purposes only.

Update: Many of the answers I am receiving deal with self.constraints, self.superview.constraints, or some variant of those. These solutions won't work since those methods return only the constraints owned by the view, not the ones affecting the view.

To clarify the problem with these solutions, consider this view hierarchy:

Grandfather

Father

Me

Son

Daughter

Brother

Uncle

Now imagine we create the following constraints, and always attach them to their nearest common ancestor:

C0: Me: same top as Son (owned by Me)

C1: Me: width = 100 (owned by Me)

C2: Me: same height as Brother (owned by Father)

C3: Me: same top as Uncle (owned by Grandfather)

C4: Me: same left as Grandfather (owned by Grandfather)

C5: Brother: same left as Father (owned by Father)

C6: Uncle: same left as Grandfather (owned by Grandfather)

C7: Son: same left as Daughter (owned by Me)

Now imagine we want to remove all constraints affecting Me. Any proper solution should remove [C0,C1,C2,C3,C4] and nothing else.

If I use self.constraints (where self is Me), I will get [C0,C1,C7], since those are the only constraints owned by Me. Obviously it wouldn't be enough to remove this since it is missing [C2,C3,C4]. Furthermore, it is removing C7 unnecessarily.

If I use self.superview.constraints (where self is Me), I will get [C2,C5], since those are the constraints owned by Father. Obviously we cannot remove all these since C5 is completely unrelated to Me.

If I use grandfather.constraints, I will get [C3,C4,C6]. Again, we cannot remove all of these since C6 should remain intact.

The brute force approach is to loop over each of the view's ancestors (including itself), and seeing if firstItem or secondItem are the view itself; if so, remove that constraint. This will lead to a correct solution, returning [C0,C1,C2,C3,C4], and only those constraints.

However, I'm hoping there is a more elegant solution than having to loop through the entire list of ancestors.

Body:
Details

Xcode 10.2.1 (10E1001), Swift 5

Solution

import UIKit

extension UIView {

    func removeConstraints() { removeConstraints(constraints) }
    func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
    func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }

    func getAllConstraints() -> [NSLayoutConstraint] {
        var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
        if let superview = self.superview {
            subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
                if let view = constraint.firstItem as? UIView, view == self { return constraint }
                return nil
            }
        }
        return subviewsConstraints + constraints
    }

    class func getAllSubviews(view: UIView) -> [UIView] {
        return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
    }
}

Usage

print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()

ContentLicense: CC BY-SA 4.0


问:
Switching between inputs is slow in a large HTML table
I have created a wholesale order form in the form of a large HTML table with lots of number inputs. I've noticed that switching between number inputs and typing values in the inputs are very slow in this table (ie. when I click in an input, it takes time for the cursor to show up; when I type in an input, it takes time for the character to show up). Is there any way for me to remove the lag without paginating the table rows?

You can view and play around with the table here (use guest password "braese").

A screenshot of a Chrome Dev Tools performance recording for clicking inside a single input (I'm not really sure what to make of this):

答: I did some more digging and testing, and it turns out the lag (update layer tree) when clicking/typing in inputs is only an issue in Chrome. This answer on another question points to issues with Chrome since version 46. It's a shame that such a popular browser has allowed an issue like this to go on for 2+ years. We will have to paginate our order form since Chrome is so popular with our client's customers.</p>


问:
VMWare - Virtual operating system static IP address
What is the best way to have a virtual operating system have a static IP address in VMWware. I would like to keep the IP address static since it is a virtual server.</p>

答:
A simple workaround, configure the vmware dhcp server to use longer leases.
In the vmware config folder (on windows 7 -- C:\ProgramData\vmware) edit the file
vmnetdhcp.conf and change the values of default-lease-time and max-lease-time to
something bigger say 4 months (4mo*30days*24hours*60min*60sec = 10368000).
Then restart the vmware dhcp server.  Then release and renew the lease on the guest.
Now your guest IP is static for next four months.

OwnerDisplayName: Dan K.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: sascha


问:
Set up cron job every minute CPANEL
I tried to set up the cron job any minute, I tried 3 different commands.

Any of them is not working.
Below is the error:

答:
Run cron job every minute

The syntax is:

```<code>* * * * * /path/to/your/script > output
</code>```

Title: Set up cron job every minute CPANEL

Body:
Run cron job every minute

The syntax is:

* * * * * /path/to/your/script > output


问:
Watir cannot running correctly when executing cases:
Please help to have a look for error details in below when running watir for automation test.

Details:
1> watir version : 1.9.2
2> Ruby version: 1.8.7

```<code>2017-11-14 05:51:06 ERROR [xxx] Failed to create browser object for: IE
2017-11-14 05:51:06 ERROR [xxx] WIN32OLERuntimeError
Attach
    OLE error code:80004005 in HttpWatch.Controller
      Failed to attach to browser. Please check that both HttpWatch entries are enabled in IE's Tools->Manage Addons window and that 'Enable third-party browser extensions' is checked under Tools->Internet Options->Advanced->Browsing
    HRESULT error code:0x80020009
      Exception occurred.
</code>```

Note:
httpwatch was installed successfully and enabled it from manage-addon from IE.

IE version is :  9.11.9600.18697

I am confused why this happen and can reproduce 100%, and other test clients with same settings working fine.

答:
This looks like a problem connecting to HttpWatch in IE rather than directly a Watir problem.

Please check the following:

Can you manually open HttpWatch in IE and record log files?

There should be 3 entries for HttpWatch in Tools->Manage Add-ons.
Are all 3 entries enabled?

Do you have the latest update to HttpWatch installed from

https://www.httpwatch.com/download/ ?

If you have any further questions or problems please email support@neumetrix.com

Answer from Neumetrix, the developer of HttpWatch

Body:
Please help to have a look for error details in below when running watir for automation test.

Details:
1> watir version : 1.9.2
2> Ruby version: 1.8.7

2017-11-14 05:51:06 ERROR [xxx] Failed to create browser object for: IE
2017-11-14 05:51:06 ERROR [xxx] WIN32OLERuntimeError
Attach
    OLE error code:80004005 in HttpWatch.Controller
      Failed to attach to browser. Please check that both HttpWatch entries are enabled in IE's Tools->Manage Addons window and that 'Enable third-party browser extensions' is checked under Tools->Internet Options->Advanced->Browsing
    HRESULT error code:0x80020009
      Exception occurred.

Note:
httpwatch was installed successfully and enabled it from manage-addon from IE.

IE version is :  9.11.9600.18697

I am confused why this happen and can reproduce 100%, and other test clients with same settings working fine.


问:
Display errors messages for associated model
This is my Article Model

```<code>class Article

has_many :pictures, autosave: true, dependent: :destroy

validates :title, presence: true
validates :text, presence: true
</code>```

This is my Picture Model

```<code>class Picture
include Mongoid::Document
include Mongoid::Paperclip

belongs_to :article
has_mongoid_attached_file :pic,
    preserve_files: true,
    :url => "/public/pictures/:style/:basename.:extension",
    styles: { format: "400x400", thumb: "150x150>" }

validates_attachment :pic, content_type: { content_type: /\Aimage\/.*\z/ },
size: { in: 50.kilobytes..3.megabytes }
</code>```

I want to display all errors messages in my view, but if picture is invalid i have many messages for one error. For example if content type is invalid i have:

"Pictures invalid" in @article.errors.full_messages(i don't need it)

"Pic invalid" in @article.pictures.first.full_messages(i don't need it)

"Pic_content_type invalid" in @article.pictures.first.full_messages(it's only one message i really need)

Any ideas? Thanks in advance and sorry for my English

答:
I'm not sure I understand your question but a few things come to mind you might be able to investigate.

Paperclip comes with some validation options and you may want to consider modifying them to produce your desired error messages as discussed here.

It seems you may need to pick the proper error message(s) to display by traversing the array of error messages received.

```<code>@article.pictures.first.full_messages[index of message you want to display]
</code>```

On another note, I saw that you use a reg exp pattern for your content type validation and the Paperclip docs warn against vulnerabilities if this is left open. They recommend something like the this:

```<code>validates_attachment :pic,
 content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
</code>```

I hope that's at least little helpful.

Body:
This is my Article Model

class Article

has_many :pictures, autosave: true, dependent: :destroy

validates :title, presence: true
validates :text, presence: true

This is my Picture Model

class Picture
include Mongoid::Document
include Mongoid::Paperclip

belongs_to :article
has_mongoid_attached_file :pic,
    preserve_files: true,
    :url => "/public/pictures/:style/:basename.:extension",
    styles: { format: "400x400", thumb: "150x150>" }

validates_attachment :pic, content_type: { content_type: /\Aimage\/.*\z/ },
size: { in: 50.kilobytes..3.megabytes }

I want to display all errors messages in my view, but if picture is invalid i have many messages for one error. For example if content type is invalid i have:

"Pictures invalid" in @article.errors.full_messages(i don't need it)

"Pic invalid" in @article.pictures.first.full_messages(i don't need it)

"Pic_content_type invalid" in @article.pictures.first.full_messages(it's only one message i really need)

Any ideas? Thanks in advance and sorry for my English

Body:
I'm not sure I understand your question but a few things come to mind you might be able to investigate.

Paperclip comes with some validation options and you may want to consider modifying them to produce your desired error messages as discussed here.

It seems you may need to pick the proper error message(s) to display by traversing the array of error messages received.

@article.pictures.first.full_messages[index of message you want to display]

On another note, I saw that you use a reg exp pattern for your content type validation and the Paperclip docs warn against vulnerabilities if this is left open. They recommend something like the this:

validates_attachment :pic,
 content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }

I hope that's at least little helpful.


问:
Trigger AutoClosable on JVM Shutdown
TL;DR:
Is there a way to find out, that JVM-shutdown is only prevented from the threads started by my code? Is it for example possible to automatically trigger AutoCloseable.close() on Shutdown?

Context

I am building a library, that should be used by several customers. This means, besides providing a documentation, I can't enforce certain things.

Architecture

(I try to describe it as abstract as possible and avoid unnecessary details)

I have a "Manager" object (which is kind of a Factory), that is used to create a "Service" object, that in turn needs some data to work accordingly. Since that data is loaded from some "slow" backend service (which also might change from time to time), I use a separate (Daemon)-Thread that checks for updates and injects new data into that service as soon as available. (This also means that unless the first update, that service is simply in "noop mode". But that's ok.)

Now the "Updater" (which runs in my daemon thread) uses a library that again starts a thread when opening a connection and it's necessary to call "close" to ensure that this secondary thread is stopped - otherwise it is not possible, to shutdown the JVM properly.

As a safety-net I call the close() method inside the finalize() method of my "Manager" (which keeps a reference to all Updater instances). This is not 100% safe, since it's not predictable when GC runs (even more during shutdown!), but it's my only option.

Update: Here is some abstract example code that illustrates the architecture and the according problem

Problem

This architecture causes two possible pitfalls:

If the implementation does not keep a reference to the instance of the manager, it will be garbage collected at some point and trough the finalize method the necessary background updates will be stopped.

If the implementation keeps an instances of the manager, it must call the close method during the shutdown of the according system, otherwise the JVM can't terminate properly.

So my actual problem is the "potential unreliability" of the developers, which are using that library.

Does anyone have an idea how to build a solution, that could handle both pitfalls?
It would be nice to have some Auto-AutoCloseable ;) that is called during Shutdown (e.g by the DestroyJavaVM Thread or similar).

Solutions I tried unsuccessfully

Inside the Updater I am closing the "problematic" connection inside a "try-finally" block, but that daemon thread is not interrupted / stopped automatically as well.

I registered a Runtime.getRuntime().addShutdownHook(...) that would close all connections, but this shutdown hook is never called since a Shutdown is only initiated when all user-threads are stopped.

Update: Solved at my implementation, but not the problem

I solved my problem as I found that the third party library (RabbitMQ Client) offers a setThreadFactory method that I can use to ensure the spawned Threads are Daemon-Threads.
Good luck for me with my 3rd party library, but the described problem is still possible.

答:
You want the AutoCloseable resources to be closed so the shutdown is orderly, I guess.

AutoCloseable objects should be used (by your library clients) in a manner that ensures  they are closed when they are no longer needed. In almost all cases, they should be using a try-with-resources block, so they are closed even if an exception is thrown.

You should take advantage of that by requiring your library clients perform a controlled shutdown of each thread when they receive a request to shutdown the program. A thread performs a controlled shutdown by returning from each Runnable.run method, or throwing an exception from each Runnable.run method. I believe this is the only reliable means of closing resources, because it ensures nested resource allocations are reallocated in the correct order. More generally, as a library writer you can not know what other operations your library clients might want to do on shutdown, so you should give them complete control over the shutdown.

You can help them do that by having your library code properly handle InterruptedException and the Thread.interrupted flag.

Title: Trigger AutoClosable on JVM Shutdown


问:
What is the difference between an expression and a statement in Python?
In Python, what is the difference between expressions and statements?</p>

答:
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object.  Examples:

```<code>3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7
</code>```

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code.  Note that expressions are statements as well.  Examples:

```<code># all the above expressions
print 42
if x: do_y()
return
a = 7
</code>```

Body:
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator () the subscription operator [] and similar, and can be reduced to some kind of "value", which can be any Python object.  Examples:

3 + 5
map(lambda x: x*x, range(10))
[a.x for a in some_iterable]
yield 7

Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code.  Note that expressions are statements as well.  Examples:

# all the above expressions
print 42
if x: do_y()
return
a = 7


问:
How to show Git log history (i.e., all the related commits) for a sub directory of a Git repository
Let’s say that I have a Git repository that looks like this:

```<code>foo/
  .git/
  A/
   ... big tree here
  B/
   ... big tree here
</code>```

Is there a way to ask git log to show only the log messages for a specific directory? For example, I want to see what commits touched files in foo/A only.

答:
Enter

```<code>git log .
</code>```

from the specific directory. It also gives commits in that directory.

Body:
Let’s say that I have a Git repository that looks like this:

foo/
  .git/
  A/
   ... big tree here
  B/
   ... big tree here

Is there a way to ask git log to show only the log messages for a specific directory? For example, I want to see what commits touched files in foo/A only.

Body:
Enter

git log .

from the specific directory. It also gives commits in that directory.


问:
x86 Irvine Assembly jmp + cmp and conditional loops - craps game
Assembly is a fun language to learn. I still have a lot of room for improvement. I'm trying to make a simple craps game that should make random dice rolls x number of times based on user input. I have the code as follows:

```<code>TITLE Program Template          (main.asm)

INCLUDE Irvine32.inc

.data
diceOne                     DWORD ?
diceTwo                     DWORD ?
win                         DWORD 7, 11
lose                        DWORD 2, 3, 12
mark                        DWORD 4, 5, 6, 8, 9, 10
markCounter                 DWORD ?
userInput                   BYTE 'Enter integer: ', 0
numRolls                    DWORD ?
printWon                    BYTE 'Won: ', 0
wonCounter                  DWORD ?
printWin                    BYTE ' You win!', 0
printLost                   BYTE 'Lost: ', 0
lostCounter                 DWORD ?
printLose                   BYTE ' You lose!', 0
printTotal                  BYTE 'Total: ', 0
space                       DWORD ' ', 0
printPlus                   BYTE ' + ', 0
printMark                   BYTE ' Mark ', 0

.code
main PROC
    call randomize                      ; set random seed
    mov ecx, 6                          ; counter set to 6
    mov edx, offset userInput           ; print string
    call writeString
    call readInt                        ; read input
    mov numRolls, eax                   ; store input in variable
    mov ecx, numRolls
    mov eax, 0
    mov edi, offset win

    call gamesRolled

    exit
main ENDP
;number of games rolled based on user input
gamesRolled PROC uses eax ecx

DICEROLLS:
    call crlf
                                ;diceOne roll
    mov eax, 5                  ;move value into eax to pass as parameter for randomrange
    call randomRange            ;randomrange stored in eax 0-5
    inc eax
    mov diceOne, eax            ;mov the value of randomrange into variable
    call writeDec
    push edx                    ;push edx off stack to print space
    mov edx, OFFSET printPlus
    call writeString
    pop edx
                                ;diceTwo roll
    mov eax, 6
    call randomRange
    inc eax
    mov diceTwo, eax
    call writeDec

    add eax, diceOne            ; add diceOne roll to diceTwo roll
    cmp eax, win                ; comp eax value to win
    je wins
    cmp eax, lose
    je losses
    cmp eax, mark
    je marks
    LOOP DICEROLLS

    ret
gamesRolled ENDP

wins PROC uses edi ecx
    mov edi, offset win
    mov ecx, lengthof win
    cmp eax, [edi]
    add edi, type win
    push edx
    mov edx, offset printWin
    call writeString
    pop edx
    jmp gamesRolled
    ret

wins ENDP

losses PROC uses edi ecx
    mov edi, offset lose
    mov ecx, lengthof lose
    cmp eax, [edi]
    add edi, type lose
    push edx
    mov edx, offset printLose
    call writeString
    pop edx
    jmp gamesRolled
    ret
losses ENDP

marks PROC uses edi ecx
    mov edi, offset lose
    mov ecx, lengthof lose
    cmp eax, [edi]
    add edi, type lose

    push edx
    mov edx, offset printMark
    call writeString
    pop edx
    jmp gamesRolled
    ret
marks ENDP

END main
</code>```

So it seems simple enough from the examples and explanations I have seen. I'm using the cmp/je to work like an if statement while I'm looping the dice rolls. The idea is to have the wins or loss or marks increase and print it all out. It works fine without the cmp/je part. I'm able to print random dice rolls, however, once I start trying to cmp/je I get some weird freezing and sometimes crashing. I'm trying to learn how to code better in assembly. Would you please help me understand why this isn't working the way I thought it should. I figured if I compare the eax register which contains the combined total of diceOne + diceTwo than it should jump to the other functions and in those functions edi should be like a counter that tallies while printing a string that indicates a win, lose, or mark. So for example:

```<code>Enter integer: 5
2 + 3 Mark
1 + 5 Mark
5 + 6 You win!
5 + 1 Mark
2 + 6 Mark
Wins: 1 Losses: 0 Marks: 4
</code>```

I didn't get to the last part yet since I'm having trouble with the code as is. Appreciate any help with this. I'm at a loss.

This is an actual result I'm getting now:

```<code>Enter integer: 5

3 + 2
3 + 5
2 + 5 You win!
3 + 6
5 + 5
</code>```

答:
What your current version does:

First random call is 0-4 only.

cmp eax, win: You use MASM syntax, so this is cmp eax,[mem32] in Intel syntax, will compare eax against value 7 from win "array". Then je wins will jump for result 7 at code at wins: and that one will do some useless pointer stuff, reset ecx to 2, display message and jump back to main roll loop.

Similarly for lose/mark "arrays", the first element (2 for lose, 4 for mark) is tested, and when equal, the lose/mark message is displayed, with some useless stuff, resetting ecx and jumping straight back to rolling.

Only for the other values (3, 5, 6, 8, 9, 10, 11 (and missing 12 due to random bug)) the loop is executed, down-counting in ecx the total loops.

You should easily see this behaviour in debugger (and even find out any discrepancy to my description, if I did some mistake in my head, as my "emulation" of CPU is a bit limited and only about ~2Hz in speed), if you single-step over instructions and examine machine state after each step. Programming in assembly without debugger is like trying to assemble robot blindfolded. You can, but it is like 100x more difficult, so invest heavily into learning how to use debugger effectively, before continuing with assembly learning.

Some advices about code:

Overall you are a bit complicating it, I would do this otherwise, I would define in data the table (instead of the win/lose/mark arrays):

```<code>;             2L  3L  4M  5M  6M  7W  8M  9M 10M 11W 12L
outcome BYTE   1,  1,  2,  2,  2,  0,  2,  2,  2,  0,  1
outcomeMsgs:
    DWORD  OFFSET printWin, OFFSET printLose, OFFSET printMark
totalScore DWORD 0, 0, 0    ; wins / losses / marks
</code>```

Then in code after second throw is displayed and you have in eax the sum of throws, you can pick the outcome as this:

```<code>    ; decide what is the outcome of throws
    movzx   ebx,byte ptr [outcome + eax - 2]
      ; ebx = 0/1/2 = win/lose/mark
    ; display outcome message
    mov     edx,[outcomeMsgs + ebx*4]
    call    writeString
    ; add to total score
    inc     dword ptr [totalScore + ebx*4]
    ; do ecx-many rolls
    dec     ecx
    jnz     DICEROLLS
    ; ending sequence
    ; for example, display total losses
    mov     edx,OFFSET printLost
    call    writeString
    mov     eax,[totalScore+4]
    call    writeDec
    ret
</code>```

Unfortunately if you wanted to exercise that cmp against values from win/... arrays, this is avoiding that completely, so of little educational value. You should probably separately try to write that array test just to get more skill... after you learn to use debugger first, so you can actually check, what the code is truly doing.

Body:
Assembly is a fun language to learn. I still have a lot of room for improvement. I'm trying to make a simple craps game that should make random dice rolls x number of times based on user input. I have the code as follows:

TITLE Program Template          (main.asm)

INCLUDE Irvine32.inc

.data
diceOne                     DWORD ?
diceTwo                     DWORD ?
win                         DWORD 7, 11
lose                        DWORD 2, 3, 12
mark                        DWORD 4, 5, 6, 8, 9, 10
markCounter                 DWORD ?
userInput                   BYTE 'Enter integer: ', 0
numRolls                    DWORD ?
printWon                    BYTE 'Won: ', 0
wonCounter                  DWORD ?
printWin                    BYTE ' You win!', 0
printLost                   BYTE 'Lost: ', 0
lostCounter                 DWORD ?
printLose                   BYTE ' You lose!', 0
printTotal                  BYTE 'Total: ', 0
space                       DWORD ' ', 0
printPlus                   BYTE ' + ', 0
printMark                   BYTE ' Mark ', 0

.code
main PROC
    call randomize                      ; set random seed
    mov ecx, 6                          ; counter set to 6
    mov edx, offset userInput           ; print string
    call writeString
    call readInt                        ; read input
    mov numRolls, eax                   ; store input in variable
    mov ecx, numRolls
    mov eax, 0
    mov edi, offset win

    call gamesRolled

    exit
main ENDP
;number of games rolled based on user input
gamesRolled PROC uses eax ecx

DICEROLLS:
    call crlf
                                ;diceOne roll
    mov eax, 5                  ;move value into eax to pass as parameter for randomrange
    call randomRange            ;randomrange stored in eax 0-5
    inc eax
    mov diceOne, eax            ;mov the value of randomrange into variable
    call writeDec
    push edx                    ;push edx off stack to print space
    mov edx, OFFSET printPlus
    call writeString
    pop edx
                                ;diceTwo roll
    mov eax, 6
    call randomRange
    inc eax
    mov diceTwo, eax
    call writeDec

    add eax, diceOne            ; add diceOne roll to diceTwo roll
    cmp eax, win                ; comp eax value to win
    je wins
    cmp eax, lose
    je losses
    cmp eax, mark
    je marks
    LOOP DICEROLLS

    ret
gamesRolled ENDP

wins PROC uses edi ecx
    mov edi, offset win
    mov ecx, lengthof win
    cmp eax, [edi]
    add edi, type win
    push edx
    mov edx, offset printWin
    call writeString
    pop edx
    jmp gamesRolled
    ret

wins ENDP

losses PROC uses edi ecx
    mov edi, offset lose
    mov ecx, lengthof lose
    cmp eax, [edi]
    add edi, type lose
    push edx
    mov edx, offset printLose
    call writeString
    pop edx
    jmp gamesRolled
    ret
losses ENDP

marks PROC uses edi ecx
    mov edi, offset lose
    mov ecx, lengthof lose
    cmp eax, [edi]
    add edi, type lose

    push edx
    mov edx, offset printMark
    call writeString
    pop edx
    jmp gamesRolled
    ret
marks ENDP

END main

So it seems simple enough from the examples and explanations I have seen. I'm using the cmp/je to work like an if statement while I'm looping the dice rolls. The idea is to have the wins or loss or marks increase and print it all out. It works fine without the cmp/je part. I'm able to print random dice rolls, however, once I start trying to cmp/je I get some weird freezing and sometimes crashing. I'm trying to learn how to code better in assembly. Would you please help me understand why this isn't working the way I thought it should. I figured if I compare the eax register which contains the combined total of diceOne + diceTwo than it should jump to the other functions and in those functions edi should be like a counter that tallies while printing a string that indicates a win, lose, or mark. So for example:

Enter integer: 5
2 + 3 Mark
1 + 5 Mark
5 + 6 You win!
5 + 1 Mark
2 + 6 Mark
Wins: 1 Losses: 0 Marks: 4

I didn't get to the last part yet since I'm having trouble with the code as is. Appreciate any help with this. I'm at a loss.

This is an actual result I'm getting now:

Enter integer: 5

3 + 2
3 + 5
2 + 5 You win!
3 + 6
5 + 5

Body:
What your current version does:

First random call is 0-4 only.

cmp eax, win: You use MASM syntax, so this is cmp eax,[mem32] in Intel syntax, will compare eax against value 7 from win "array". Then je wins will jump for result 7 at code at wins: and that one will do some useless pointer stuff, reset ecx to 2, display message and jump back to main roll loop.

Similarly for lose/mark "arrays", the first element (2 for lose, 4 for mark) is tested, and when equal, the lose/mark message is displayed, with some useless stuff, resetting ecx and jumping straight back to rolling.

Only for the other values (3, 5, 6, 8, 9, 10, 11 (and missing 12 due to random bug)) the loop is executed, down-counting in ecx the total loops.

You should easily see this behaviour in debugger (and even find out any discrepancy to my description, if I did some mistake in my head, as my "emulation" of CPU is a bit limited and only about ~2Hz in speed), if you single-step over instructions and examine machine state after each step. Programming in assembly without debugger is like trying to assemble robot blindfolded. You can, but it is like 100x more difficult, so invest heavily into learning how to use debugger effectively, before continuing with assembly learning.

Some advices about code:

Overall you are a bit complicating it, I would do this otherwise, I would define in data the table (instead of the win/lose/mark arrays):

;             2L  3L  4M  5M  6M  7W  8M  9M 10M 11W 12L
outcome BYTE   1,  1,  2,  2,  2,  0,  2,  2,  2,  0,  1
outcomeMsgs:
    DWORD  OFFSET printWin, OFFSET printLose, OFFSET printMark
totalScore DWORD 0, 0, 0    ; wins / losses / marks

Then in code after second throw is displayed and you have in eax the sum of throws, you can pick the outcome as this:

    ; decide what is the outcome of throws
    movzx   ebx,byte ptr [outcome + eax - 2]
      ; ebx = 0/1/2 = win/lose/mark
    ; display outcome message
    mov     edx,[outcomeMsgs + ebx*4]
    call    writeString
    ; add to total score
    inc     dword ptr [totalScore + ebx*4]
    ; do ecx-many rolls
    dec     ecx
    jnz     DICEROLLS
    ; ending sequence
    ; for example, display total losses
    mov     edx,OFFSET printLost
    call    writeString
    mov     eax,[totalScore+4]
    call    writeDec
    ret

Unfortunately if you wanted to exercise that cmp against values from win/... arrays, this is avoiding that completely, so of little educational value. You should probably separately try to write that array test just to get more skill... after you learn to use debugger first, so you can actually check, what the code is truly doing.


问:
error installing 'create-react-native-app' npm
I am getting this issue while installing the create-react-native-app app

```<code>npm install -g create-react-native-app
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to https://registry.npmjs.org/create-react-native-app failed, reason: getaddrinfo ENOTFOUND genproxy genproxy:8080
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\krishna\AppData\Roaming\npm-cache\_logs\2017-11-14T08_10_48_970Z-debug.log
</code>```

I have tried removing any proxy that I was using still getting the same error.

```<code>C:\
λ npm -v
5.5.1

C:\
node -v
v8.9.1
</code>```

Let me know if more info is needed.
Thanks

答:
It was getting a wrong proxy which I didn't realised earlier.

I was under a corporate network so added the full name of the proxy 'genproxy.corporatename.com:8080' in place of 'genproxy:8080'.

Working fine!!

Body:
I am getting this issue while installing the create-react-native-app app

npm install -g create-react-native-app
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to https://registry.npmjs.org/create-react-native-app failed, reason: getaddrinfo ENOTFOUND genproxy genproxy:8080
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\krishna\AppData\Roaming\npm-cache\_logs\2017-11-14T08_10_48_970Z-debug.log

I have tried removing any proxy that I was using still getting the same error.

C:\
λ npm -v
5.5.1

C:\
node -v
v8.9.1

Let me know if more info is needed.
Thanks


问:
How to disable auto hide the solution explorer (Visual Studio 2017)
How to disable auto hide solution explorer (Visual Studio 2017)?

Every time after launching the project, the solution explorer does autohide.

How disable it?

答:
check this picture

click solution explorer and then right click on top of the solution explorer window and click dock.


问:
Docker Neo4j Container keeps stopping - how to debug?
We have a neo4j container and it keeps stopping.

There are 3 other containers (node servers) running on the box as well. It's on a dev box so it is low spec - only 588MB RAM- so I suspect that it keeps running out of memory.

But how do I verify why it keeps stopping?  Its only ever the neo container that stops. We launch it with:

```<code>$NEO4J_HOME/bin/neo4j console
</code>```

I suspect its the neo4j process itself that is exiting, thus closing the container.
Any tips on debugging this?

答:
If you start it with

```<code>docker run --name <container_name> ... neo4j`
</code>```

as official man propose, you can check errors with docker logs <container_name>

Also you can start it with additional volume

```<code>--volume=/path/to/logs:/logs
</code>```

and check them

Body:
We have a neo4j container and it keeps stopping.

There are 3 other containers (node servers) running on the box as well. It's on a dev box so it is low spec - only 588MB RAM- so I suspect that it keeps running out of memory.

But how do I verify why it keeps stopping?  Its only ever the neo container that stops. We launch it with:

$NEO4J_HOME/bin/neo4j console

I suspect its the neo4j process itself that is exiting, thus closing the container.
Any tips on debugging this?

Body:
If you start it with

docker run --name <container_name> ... neo4j`

as official man propose, you can check errors with docker logs <container_name>

Also you can start it with additional volume

--volume=/path/to/logs:/logs

and check them


问:
How to set maven plugin to run in git bash shell in Intellij Idea?
I have a lot of modules in IntelliJ IDEA Project (which was defined as maven module).

Each of these modules can be run successfully but only from Git Bash command Prompt.

Note from an editor: the original sentence was both incorrectly formatted and phrased as a possible part of the question, leading to some confusion. Here it is:

This each module can be run successfully only from git-bash Command Prompt?

So the question is: Can I run each module from Intellij GUI view as in Git Bash which is not the default windows command line? Does it mean from the maven plugin view [GUI]?

Is there any workaround not to run from the Terminal view?

答:
The question is not clearly formulated but I sounds like the OP wants to use git bash as the IntelliJ terminal. For anybody looking for an answer to this:

'Settings --> Tools --> Terminal' and in 'Shell Path' Field:

```<code>"C:\Program Files (x86)\Git\bin\sh.exe" --login -i
</code>```

Or whatever command you use to launch your git bash

UPDATE AFTER COMMENT BY OP:

Menu -> Run -> Edit Configurations... -> Add new configuration -> Maven

Name: whatever

Working directory: your module directory

Command line: clean install

Then you can run the maven goal from the menu in the upper right corner

Body:
The question is not clearly formulated but I sounds like the OP wants to use git bash as the IntelliJ terminal. For anybody looking for an answer to this:

'Settings --> Tools --> Terminal' and in 'Shell Path' Field:

"C:\Program Files (x86)\Git\bin\sh.exe" --login -i

Or whatever command you use to launch your git bash

UPDATE AFTER COMMENT BY OP:

Menu -> Run -> Edit Configurations... -> Add new configuration -> Maven

Name: whatever

Working directory: your module directory

Command line: clean install

Then you can run the maven goal from the menu in the upper right corner


问:
Build URL to data file download with link to folder
I have a web application that triggers actions at the server side which result in the generation of data files.

The so generated data files are stored within a folder at drive different from the one where the Web application is.

What I tried so far is to create a shortcut (Windows Server) next to the Index.html, where the shortcut points to the folder at the second drive.

This solution does not appear to work:

If I copy the data file to the same folder where the Index.html file is and enter navigate to the URL httm://127.0.0.1:324324/Data_File.xlsx I get the file downloaded.

If I enter httm://127.0.0.1:324324/MyShortcut/Data_File.xlsx (where MyShortcut points to a folder in drive D) the attempt fails.

How can I achieve this?

The need to access files in the different drive is essential.

答:
You need to configure your server to serve that folder under different location. The only reason you are able to see your app and access that folder is cause server is set up to serve it ATM, not because you are making the right calls from the front or cause the front is asking nicely.

Don't know what Windows server version you are using and IIS version that goes on it, or are you even using IIS (you most probably do) but depending on what you use you need to do something in a lines of this:

IIS7 config

What you probably wanna do is create virtual folder in IIS. Try looking into it, then if you fail ask a question with proper tags according where are you stuck.

I don't see how this is connected to front-end at all so front end tags wont get you far.

EDIT:

Oh, in that case get a second file server running for that folder? This should be the fastest way, use what you can from this list:  list


问:
Electron menu keeps saying that ipc is not defined when clicked even when the ipc is assigned globally in main
in my menu.js under "label:'Database'", the click event returns an error: ipc is not defined. I thought that if this is part of the main.js files and that if I already have a const declared as ipc globally then shouldn't JS look scopes above and find ipc?

main.js:

const electron = require('electron'),
{app, Menu} = require('electron'),
Window = electron.BrowserWindow,
path = require('path'),
url = require('url'),
ipc = require('electron').ipcMain,   // COMMUNICATIONS MODULE BETWEEN MAIN/RENDERER
template = require('./menu.js');

// let mainWindow
app.on('ready', () => {
  // LOADS THE DEFAULT WINDOW
  let first_Window = new Window({width:800, height:600, frame:false})
  first_Window.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:'
  }))
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
})
```

<p>Menu.js:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = [
  {
    label: 'stuff',
    submenu: [
      {role: 'undo'},
      {role: 'redo'},
      {type: 'separator'},
      {role: 'cut'},
      {role: 'copy'},
      {role: 'paste'},
      {role: 'pasteandmatchstyle'},
      {role: 'delete'},
      {role: 'selectall'}
    ]
  },
  {
    label: 'Database',
    click() {
       ipc.send('open_database', '')
    }
  },
  {
    label: 'View',
    submenu: [
      {role: 'reload'},
      {role: 'forcereload'},
      {role: 'toggledevtools'},
      {type: 'separator'},
      {role: 'resetzoom'},
      {role: 'zoomin'},
      {role: 'zoomout'},
      {type: 'separator'},
      {role: 'togglefullscreen'}
    ]
  },
  {
    role: 'window',
    submenu: [
      {role: 'minimize'},
      {role: 'close'}
    ]
  },
  {
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click () { require('electron').shell.openExternal('https://electron.atom.io') }
      }
    ]
  }
]
</code>```

Note: My menu shows up just fine. The error only occurs if I click on database.

答:
Since Menu is a main process class, you don't have to use ipc communication for doing things like opening a new BrowserWindow (what you apparently want).

const {BrowserWindow} = require('electron')

module.exports = [
  {
    label: 'Database',
    click (menuItem, browserWindow, event) {
      let win = new BrowserWindow()
      win.loadURL('https://electron.atom.io/docs/api/menu-item/')
    }
  }
]
```

should be enough in your template for this.

Note that if you plan to communicate with your window's renderer process, click callback comes with browserWindow argument giving you access to the window containing the menu item (see click property of MenuItem in documentation). You can then executeJavascript or send ipc message to renderer process using this argument.

Also note, that despite the fact that BrowserWindow (or ipc or whatever) is already defined in an other file which requires this template, you have to define it again. Require/import/include chains doesn't work in two direction

Body:
in my menu.js under "label:'Database'", the click event returns an error: ipc is not defined. I thought that if this is part of the main.js files and that if I already have a const declared as ipc globally then shouldn't JS look scopes above and find ipc?

main.js:

const electron = require('electron'),
{app, Menu} = require('electron'),
Window = electron.BrowserWindow,
path = require('path'),
url = require('url'),
ipc = require('electron').ipcMain,   // COMMUNICATIONS MODULE BETWEEN MAIN/RENDERER
template = require('./menu.js');

// let mainWindow
app.on('ready', () => {
  // LOADS THE DEFAULT WINDOW
  let first_Window = new Window({width:800, height:600, frame:false})
  first_Window.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:'
  }))
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
})

Menu.js:

module.exports = [
  {
    label: 'stuff',
    submenu: [
      {role: 'undo'},
      {role: 'redo'},
      {type: 'separator'},
      {role: 'cut'},
      {role: 'copy'},
      {role: 'paste'},
      {role: 'pasteandmatchstyle'},
      {role: 'delete'},
      {role: 'selectall'}
    ]
  },
  {
    label: 'Database',
    click() {
       ipc.send('open_database', '')
    }
  },
  {
    label: 'View',
    submenu: [
      {role: 'reload'},
      {role: 'forcereload'},
      {role: 'toggledevtools'},
      {type: 'separator'},
      {role: 'resetzoom'},
      {role: 'zoomin'},
      {role: 'zoomout'},
      {type: 'separator'},
      {role: 'togglefullscreen'}
    ]
  },
  {
    role: 'window',
    submenu: [
      {role: 'minimize'},
      {role: 'close'}
    ]
  },
  {
    role: 'help',
    submenu: [
      {
        label: 'Learn More',
        click () { require('electron').shell.openExternal('https://electron.atom.io') }
      }
    ]
  }
]

Note: My menu shows up just fine. The error only occurs if I click on database.

Body:
Since Menu is a main process class, you don't have to use ipc communication for doing things like opening a new BrowserWindow (what you apparently want).

const {BrowserWindow} = require('electron')

module.exports = [
  {
    label: 'Database',
    click (menuItem, browserWindow, event) {
      let win = new BrowserWindow()
      win.loadURL('https://electron.atom.io/docs/api/menu-item/')
    }
  }
]

should be enough in your template for this.

Note that if you plan to communicate with your window's renderer process, click callback comes with browserWindow argument giving you access to the window containing the menu item (see click property of MenuItem in documentation). You can then executeJavascript or send ipc message to renderer process using this argument.

Also note, that despite the fact that BrowserWindow (or ipc or whatever) is already defined in an other file which requires this template, you have to define it again. Require/import/include chains doesn't work in two direction


问:
Firebase for Unity – Offline Persistence
I'm using the brand new Firebase SDK for Unity for an Augmented Reality application that I'd like to function offline. I've used the following statement for offline persistence on iOS before but don't see anything in the docs for Unity.

```<code>FIRDatabase.database().persistenceEnabled = true

// Keeps a specific location synced.
scenesRef.keepSynced(true)
</code>```

So for Unity, is there anything I can do to make Firebase keep all of its state even after an app restart? Keep a reference synced?

答: It's currently not supported. I think that the plugin is open source so you can add it yourself. In the end, a unity app is compiled to each platform natively so you can just add the relevant lines in the modified plugin.</p>

Body:
I'm using the brand new Firebase SDK for Unity for an Augmented Reality application that I'd like to function offline. I've used the following statement for offline persistence on iOS before but don't see anything in the docs for Unity.

FIRDatabase.database().persistenceEnabled = true

// Keeps a specific location synced.
scenesRef.keepSynced(true)

So for Unity, is there anything I can do to make Firebase keep all of its state even after an app restart? Keep a reference synced?


问:
Function evaluates to true, but using function as parameter of if-statement shows false
I have an assignment that calls for creating a person object.

```<code>    class Person {
        private String name;
        public Person parent1 = null;
        public Person parent2 = null;
        public Person spouse = null;
        public int numChildren = 0;
        public LinkedList<Person> children = new LinkedList<Person>();

        public Person(String n) {
            name = n;
            numChildren = 0;
        }
</code>```

Three functions of my program, M, Y, and Z, do the following:

M — Marry the two people.

```<code>        public static void M(String name, String name2) {
            if (findPerson(name).getSpouse() != null && findPerson(name).getSpouse().getName().equals(name2))
                System.out.println(name + " and " + name2 + "are already married.");
            else if (Y(name, name2) || Z(name, name2) || Z(name2, name))
                System.out.println("Unable to complete action. " + name + " and " + name2 + " are related.");
            else if (findPerson(name).spouse != null)
                System.out.println(findPerson(name).getName() + " is already married.");
            else if (findPerson(name2).spouse != null)
                System.out.println(findPerson(name2).getName() + " is already married.");
            else
                findPerson(name).marry(findPerson(name2));
        }
</code>```

Y — States whether name2 is an ancestor of name1.

```<code>        public static boolean Y(String name, String name2) {
            if (name.equals(name2))
                return true;
            else if (findPerson(name).getParent1() != null)
                Y(findPerson(name).getParent1().getName(), name2);
            else if (findPerson(name).getParent2() != null)
                Y(findPerson(name).getParent2().getName(), name2);
            else if (findPerson(name2).getParent1() != null)
                Y(findPerson(name2).getParent1().getName(), name);
            else if (findPerson(name2).getParent2() != null)
                Y(findPerson(name2).getParent2().getName(), name);
            return false;
        }
</code>```

Z — States whether name2 is a descendant of name1.

```<code>        public static boolean Z(String name, String name2) {

            LinkedList<Person> c1 = findPerson(name).getChildren();

            for (int i = 0; i < findPerson(name).getNumChildren(); i++) {
                if (c1.get(i).getName().equals(name2))
                    return true;
                else if (c1.get(i).getNumChildren() != 0)
                    if (Z((c1.get(i).getChildren().get(0).getName()), name2))
                        return true;
            }
            return false;
        }
</code>```

I use Y and Z to determine if name and name2 are related in any way. If they are, then in the function M, the second if statement prints out a message end exits the function.

Other related functions:

P — Record that name is a parent of name2.

T — Print out the tree of descendants of the specified person.

An example of a test input I've been working with:

```<code>    O Jon
    O Jane
    O Daniel
    O Kevin
    O Atticus
    P Atticus Jon
    P Atticus Jane
    P Jon Daniel
    P Jane Kevin
    T Atticus

    Atticus
        |---->Jon
        |       |--->Daniel
        |---->Jane
                |--->Kevin
</code>```

However, when I try to call M(Daniel, Kevin) it marries them, even though they're related (they would be cousins).

I input the line of code:

```<code>    System.out.println(name + ", " + name2);
</code>```

at the top of the function Y; for the sample input above, the output is:

```<code>    Daniel, Kevin
    Jon, Kevin
    Atticus, Kevin
    Jane, Atticus
    Atticus, Atticus
</code>```

So it's finding that Daniel and Kevin share a grandfather, Atticus.

I did a similar print statement and verified that my function was evaluating to true for this input, since the first thing Y checks is if name.equals(name2), in other words, ("Atticus").equals("Atticus").

But it's not triggering the second if-statement in M, and I don't know why. Am I missing something really simple?

If you'd like to see the rest of my code, let me know and I'll make an edit.

答: Your function Y will return true if and only if the names equal. It will run all the other checks, but then return false in the end. You probably meant to return the results of the recursive calls instead.

Body:
I have an assignment that calls for creating a person object.

    class Person {
        private String name;
        public Person parent1 = null;
        public Person parent2 = null;
        public Person spouse = null;
        public int numChildren = 0;
        public LinkedList<Person> children = new LinkedList<Person>();

        public Person(String n) {
            name = n;
            numChildren = 0;
        }

Three functions of my program, M, Y, and Z, do the following:

M — Marry the two people.

        public static void M(String name, String name2) {
            if (findPerson(name).getSpouse() != null && findPerson(name).getSpouse().getName().equals(name2))
                System.out.println(name + " and " + name2 + "are already married.");
            else if (Y(name, name2) || Z(name, name2) || Z(name2, name))
                System.out.println("Unable to complete action. " + name + " and " + name2 + " are related.");
            else if (findPerson(name).spouse != null)
                System.out.println(findPerson(name).getName() + " is already married.");
            else if (findPerson(name2).spouse != null)
                System.out.println(findPerson(name2).getName() + " is already married.");
            else
                findPerson(name).marry(findPerson(name2));
        }

Y — States whether name2 is an ancestor of name1.

        public static boolean Y(String name, String name2) {
            if (name.equals(name2))
                return true;
            else if (findPerson(name).getParent1() != null)
                Y(findPerson(name).getParent1().getName(), name2);
            else if (findPerson(name).getParent2() != null)
                Y(findPerson(name).getParent2().getName(), name2);
            else if (findPerson(name2).getParent1() != null)
                Y(findPerson(name2).getParent1().getName(), name);
            else if (findPerson(name2).getParent2() != null)
                Y(findPerson(name2).getParent2().getName(), name);
            return false;
        }

Z — States whether name2 is a descendant of name1.

        public static boolean Z(String name, String name2) {

            LinkedList<Person> c1 = findPerson(name).getChildren();

            for (int i = 0; i < findPerson(name).getNumChildren(); i++) {
                if (c1.get(i).getName().equals(name2))
                    return true;
                else if (c1.get(i).getNumChildren() != 0)
                    if (Z((c1.get(i).getChildren().get(0).getName()), name2))
                        return true;
            }
            return false;
        }

I use Y and Z to determine if name and name2 are related in any way. If they are, then in the function M, the second if statement prints out a message end exits the function.

Other related functions:

P — Record that name is a parent of name2.

T — Print out the tree of descendants of the specified person.

An example of a test input I've been working with:

    O Jon
    O Jane
    O Daniel
    O Kevin
    O Atticus
    P Atticus Jon
    P Atticus Jane
    P Jon Daniel
    P Jane Kevin
    T Atticus

    Atticus
        |---->Jon
        |       |--->Daniel
        |---->Jane
                |--->Kevin

However, when I try to call M(Daniel, Kevin) it marries them, even though they're related (they would be cousins).

I input the line of code:

    System.out.println(name + ", " + name2);

at the top of the function Y; for the sample input above, the output is:

    Daniel, Kevin
    Jon, Kevin
    Atticus, Kevin
    Jane, Atticus
    Atticus, Atticus

So it's finding that Daniel and Kevin share a grandfather, Atticus.

I did a similar print statement and verified that my function was evaluating to true for this input, since the first thing Y checks is if name.equals(name2), in other words, ("Atticus").equals("Atticus").

But it's not triggering the second if-statement in M, and I don't know why. Am I missing something really simple?

If you'd like to see the rest of my code, let me know and I'll make an edit.


问:
deselect all rows in ng grid
Please find the ng grid example in plunker

http://plnkr.co/edit/CncDWCktXTuBQdDVfuVv?p=preview

It will allow user to select only one row but there will be one selected row at all time. I want to deselect all rows.

答:
For Selecting ALL Rows We Use ::

$scope.GridOptions.api.selectAll()

Here $scope.GridOptions is your own grid data

And For Deselecting All Rows We use::

$scope.gridOptions.api.deselectAll();

Here (.api) is file and you get this file from
(ag-grid.js) file from internet
Url:https://cdnjs.com/libraries/ag-grid

Title: deselect all rows in ng grid


问:
Git incorrectly infers "rename"
Git has inferred a "rename" when I had no desire for it to do so (this question is effectively the opposite of, say, How to make git mark a deleted and a new file as a file move?):

I created a new file, and did git add.  (I did not do a git commit, as I have no desire to do so at this stage.)

Later on I did git rm on another file.

Now git status reports renamed: old-file -> new-file.  I have not committed yet.

The two files are in the same directory, have similar-ish names and a certain amount of common content.  However, I deliberately did not do a git mv, as this is not a rename, I want the two files tracked separately.  If I had wanted a rename I would have done a git mv rather than my deliberate git add/git rm.

What about the activity has caused git to decide it's a rename, and can it be told not to try to infer things I don't intend?

答:
Git's logical underlying storage model only stores the repo contents before and after a change, not the change itself.  So it has no way of distinguishing between, say, a move+modification and a delete+add.

Thus git mv is just convenience syntax for:

```<code>mv a b
git rm a
git add b
</code>```

git status is merely inferring the most likely cause of the underlying change (given before and after), in an effort to make the human-readable output useful.  There are certainly pathological edge cases - in your particular case it's inferred that the change was caused by a move and a small content change.

Update based on comments discussion: If you need to make it clear what's going on here, you could (as you suggested) perform the add and rm in separate commits. This has the downside of splitting a single "logical" commit into two, though that may be unimportant.

Title: Git incorrectly infers "rename"

Body:
Git's logical underlying storage model only stores the repo contents before and after a change, not the change itself.  So it has no way of distinguishing between, say, a move+modification and a delete+add.

Thus git mv is just convenience syntax for:

mv a b
git rm a
git add b

git status is merely inferring the most likely cause of the underlying change (given before and after), in an effort to make the human-readable output useful.  There are certainly pathological edge cases - in your particular case it's inferred that the change was caused by a move and a small content change.

Update based on comments discussion: If you need to make it clear what's going on here, you could (as you suggested) perform the add and rm in separate commits. This has the downside of splitting a single "logical" commit into two, though that may be unimportant.


问:
Are there md5 collisions for integers in range(1,1000000000)
I want to generate a uuid in python using the md5 hash of a preexisting unique identifier ranged between 1 and 999999999

It seems obvious that on numbers so small there couldn't be any worry... but it made me think, do we know the smallest two integers that have the same md5 hash ?

答:
You could test it using MongoDb as data store:

```<code>import hashlib
import sys
import pymongo

def int_to_bytes(x):
    return x.to_bytes((x.bit_length() + 7) // 8, byteorder=sys.byteorder)

CLIENT = pymongo.MongoClient('mongodb://localhost:27017/')
DB = CLIENT['md5test']
COLLECTION = DB['vals']

COLLECTION.create_index('value', unique=True)

for x in range(1000000000):
    if x % 1000000 == 0:
        print(x)
    m = hashlib.md5()
    m.update(int_to_bytes(x))
    value = m.digest()
    COLLECTION.insert_one({
        'value': value
    })

print('done!')
</code>```

It will throw in case of a duplicate. But it will take time to process your range.

Also it matters how you encode integers, see int_to_bytes().

Body:
You could test it using MongoDb as data store:

import hashlib
import sys
import pymongo

def int_to_bytes(x):
    return x.to_bytes((x.bit_length() + 7) // 8, byteorder=sys.byteorder)

CLIENT = pymongo.MongoClient('mongodb://localhost:27017/')
DB = CLIENT['md5test']
COLLECTION = DB['vals']

COLLECTION.create_index('value', unique=True)

for x in range(1000000000):
    if x % 1000000 == 0:
        print(x)
    m = hashlib.md5()
    m.update(int_to_bytes(x))
    value = m.digest()
    COLLECTION.insert_one({
        'value': value
    })

print('done!')

It will throw in case of a duplicate. But it will take time to process your range.

Also it matters how you encode integers, see int_to_bytes().


问:
One button with different actions each touch in iOS
I want to change the text (or the background or the animation or what ever) in each click, what is the best way to do it?</p>

```<code>@IBOutlet weak var text: UILabel!

@IBOutlet var background: UIView!

@IBOutlet weak var button: UIButton!

@IBAction func play(_ sender: UIButton) {

UIView.animate(withDuration: 1.5) {

    self.button.frame.origin.y = 30
    self.button.frame.size.height = 200
    self.button.frame.size.width = 130

    self.button.backgroundColor = .yellow

    self.text.textColor = .white

    self.text.frame.origin.y += 110
    self.background.backgroundColor = .black

    self.text.text = "Thanks for grabiN."

    // ..text = "Now click it until it's gone!"
    // ..text = "ComeOn you can do iT"
    // ..text = "Lest time"

    }

}
</code>```

答:
create massive and one count param</p>

```<code>var count = 0
var texts = ["Thanks for grabiN.", "ComeOn you can do iT"]

UIView.animate(withDuration: 1.5) {

   self.button.frame.origin.y = 30
   self.button.frame.size.height = 200
   self.button.frame.size.width = 130

   self.button.backgroundColor = .yellow

   self.text.textColor = .white

   self.text.frame.origin.y += 110
   self.background.backgroundColor = .black

   let index = self.count % self.texts.count
   self.text.text = self.texts[index]
   self.count+=1
}
</code>```

Body:
I want to change the text (or the background or the animation or what ever) in each click, what is the best way to do it?

@IBOutlet weak var text: UILabel!

@IBOutlet var background: UIView!

@IBOutlet weak var button: UIButton!

@IBAction func play(_ sender: UIButton) {

UIView.animate(withDuration: 1.5) {

    self.button.frame.origin.y = 30
    self.button.frame.size.height = 200
    self.button.frame.size.width = 130

    self.button.backgroundColor = .yellow

    self.text.textColor = .white

    self.text.frame.origin.y += 110
    self.background.backgroundColor = .black

    self.text.text = "Thanks for grabiN."

    // ..text = "Now click it until it's gone!"
    // ..text = "ComeOn you can do iT"
    // ..text = "Lest time"

    }

}

Body:
create massive and one count param

var count = 0
var texts = ["Thanks for grabiN.", "ComeOn you can do iT"]

UIView.animate(withDuration: 1.5) {

   self.button.frame.origin.y = 30
   self.button.frame.size.height = 200
   self.button.frame.size.width = 130

   self.button.backgroundColor = .yellow

   self.text.textColor = .white

   self.text.frame.origin.y += 110
   self.background.backgroundColor = .black

   let index = self.count % self.texts.count
   self.text.text = self.texts[index]
   self.count+=1
}


问:
Grid System Not Working Properly
For some reason, bootstrap is only allowing me to use the "col-sm" class. If I enter anything else into my code, including the "xs" class, the columns are stacked on top of one another. This is my code:

```<code>    <div class="container-fluid">
            <div class="row">
                <div class="col-xs-9">
                    <div class="well">something here</div>
                </div>
                <div class="col-xs-3">
                    <div class="well">something here</div>
                </div>
            </div>
        </div>
</code>```

I have ensured that the appropriate CSS, JS, and jQuery files are linked (hence why the "col-sm" class works), and only have my own personal CSS style-sheet linked in addition to them (which does not predefine any width or height for any element). Furthermore, I am viewing my work on the latest version of Mozilla Firefox.

Edit: I have closed the div with the class "fluid-container", it still produces the same problem. That is, instead of the two columns appearing on the same row, the two columns are stacked on top of one another. For some reason, the only class that works is "col-sm"--any other class, including the "xs", just lines the columns atop of one another.

答: Use the latest stable version 3.7.7 of bootstrap and this problem will be solved. You can download it from here. If you don't want to use the newest version, you can try to use col-sm-9 instead of col-xs-9 and col-sm-3 instead of col-xs-3, it will also solve the problem.

Title: Grid System Not Working Properly

Body:
For some reason, bootstrap is only allowing me to use the "col-sm" class. If I enter anything else into my code, including the "xs" class, the columns are stacked on top of one another. This is my code:

something here

something here

I have ensured that the appropriate CSS, JS, and jQuery files are linked (hence why the "col-sm" class works), and only have my own personal CSS style-sheet linked in addition to them (which does not predefine any width or height for any element). Furthermore, I am viewing my work on the latest version of Mozilla Firefox.

Edit: I have closed the div with the class "fluid-container", it still produces the same problem. That is, instead of the two columns appearing on the same row, the two columns are stacked on top of one another. For some reason, the only class that works is "col-sm"--any other class, including the "xs", just lines the columns atop of one another.


问:
Duplicate Virtual Object in Tango AR Unity
Can someone tell me why this is happen? i follow the tutorial from Tango AR to place virtual object in Augmented Reality. After i place the object, the camera freeze and the kitten got duplicate when i move the smartphone. I'm using Unity 5.6.2 and for Lenovo for Tango.

Below are the sample image from my android device.

答: Change the camera clear flags from depth to solid color and it should be ok</p>


问:
Converting Binary Search Tree to Linked List error
I am trying to convert a bst into a linked list, but am getting an error when trying to recall the list to print on the display.

Here is my code for the main functions,

```<code>ListNodePtr createListnode(int key) {
    ListNodePtr newList = (ListNodePtr)malloc(sizeof(struct ListNode));

    if (newList != NULL) {
            newList->key = key;
            newList->next = NULL;
            return newList;
    } else {
            return NULL;
    }
}

ListNodePtr insertNodeIntoList(ListNodePtr root, const ListNodePtr z) {
    if (root == NULL) {
            root = createListnode(z->key);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            ListNodePtr current = createListnode(root->key);
            list = insertNodeIntoList(list, current);
            linkedListINIT(list, root->right);
    }
    return;
}

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root) {
    ListNodePtr list = NULL;

    linkedListINIT(list, root);

    return list;
}
</code>```

Here is the initialization for the listNodePtr and the print function.

```<code>struct ListNode {
    int key;
    struct ListNode *next;
};

typedef struct ListNode *ListNodePtr;
</code>```

and

```<code>void printList(ListNodePtr head) {
    if (head != NULL) {
            printf("%d ", head->key);
            printList(head->next);
    }
    return;
}
</code>```

The issue is, when i try to print the final list, there is no output even though the 'current' variable outputs properly if I check it with print statements. I'm not really sure where it goes wrong, the main function just calls convertBSTtoLinkedList and printList. Any help would be appreciated!

答:
Modify functions insertNodeIntoList() and linkedListINIT() as follows

```<code>ListNodePtr insertNodeIntoList(ListNodePtr root, int z) {
    if (root == NULL) {
            root = createListnode(z);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            list = insertNodeIntoList(list, root->key);
            linkedListINIT(list, root->right);
    }
    return;
}
</code>```

Hope it worked for you!

Body:
I am trying to convert a bst into a linked list, but am getting an error when trying to recall the list to print on the display.

Here is my code for the main functions,

ListNodePtr createListnode(int key) {
    ListNodePtr newList = (ListNodePtr)malloc(sizeof(struct ListNode));

    if (newList != NULL) {
            newList->key = key;
            newList->next = NULL;
            return newList;
    } else {
            return NULL;
    }
}

ListNodePtr insertNodeIntoList(ListNodePtr root, const ListNodePtr z) {
    if (root == NULL) {
            root = createListnode(z->key);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            ListNodePtr current = createListnode(root->key);
            list = insertNodeIntoList(list, current);
            linkedListINIT(list, root->right);
    }
    return;
}

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root) {
    ListNodePtr list = NULL;

    linkedListINIT(list, root);

    return list;
}

Here is the initialization for the listNodePtr and the print function.

struct ListNode {
    int key;
    struct ListNode *next;
};

typedef struct ListNode *ListNodePtr;

and

void printList(ListNodePtr head) {
    if (head != NULL) {
            printf("%d ", head->key);
            printList(head->next);
    }
    return;
}

The issue is, when i try to print the final list, there is no output even though the 'current' variable outputs properly if I check it with print statements. I'm not really sure where it goes wrong, the main function just calls convertBSTtoLinkedList and printList. Any help would be appreciated!

Body:
Modify functions insertNodeIntoList() and linkedListINIT() as follows

ListNodePtr insertNodeIntoList(ListNodePtr root, int z) {
    if (root == NULL) {
            root = createListnode(z);
    } else {
            root->next = insertNodeIntoList(root->next, z);
    }
    return root;
}

void linkedListINIT(ListNodePtr list, TreeNodePtr root) {
    if (root != NULL) {
            linkedListINIT(list, root->left);
            list = insertNodeIntoList(list, root->key);
            linkedListINIT(list, root->right);
    }
    return;
}

Hope it worked for you!


问:
Thousand separator while typing and decimal (with comma)
I have a problem.

```<code>        $('#value-salary').on('keyup', function(){
            if($(this).val() != ""){
                var n = parseInt($(this).val().replace(/\D/g,''),10);
                $(this).val(n.toLocaleString());
            }
        });
</code>```

This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.

The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).

How can i fix this problem? Keypress or keydown are not good solutions...thanks!

答:
You can try this piece of code. It places , as thousand separator and you can use . for your decimal separator. You can easily customize the symbols you want to use for each purpose.</p>

```<code><html>
<head>
<script language="javascript" type="text/javascript">
    function thousandSeparator(n, sep) {
        var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
        sValue = n + '';

        if (sep == undefined) { sep = ','; }

        while (sRegExp.test(sValue)) {
            sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
        }

        return sValue;
    }

    function showSeparator() {
        var myValue = document.getElementById("txtInvoicePrice").value;
        myValue = thousandSeparator(myValue.replace(/,/g, ""), ',');
        document.getElementById("txtInvoicePrice").value = myValue;
    }

    function removeSeparator() {
        var myValue = document.getElementById("txtInvoicePrice").value;
        myValue = myValue.replace(',', '');
        document.getElementById("txtInvoicePrice").value = myValue;
    }
</script>
</head>
<body>
    <input type="text" id="txtInvoicePrice" onfocus="javascript:removeSeparator();" onblur="javascript:showSeparator();" />
</body>
</html>
</code>```

Body:
I have a problem.

        $('#value-salary').on('keyup', function(){
            if($(this).val() != ""){
                var n = parseInt($(this).val().replace(/\D/g,''),10);
                $(this).val(n.toLocaleString());
            }
        });

This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.

The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).

How can i fix this problem? Keypress or keydown are not good solutions...thanks!

Body:
You can try this piece of code. It places , as thousand separator and you can use . for your decimal separator. You can easily customize the symbols you want to use for each purpose.

<html>
<head>
<script language="javascript" type="text/javascript">
    function thousandSeparator(n, sep) {
        var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
        sValue = n + '';

        if (sep == undefined) { sep = ','; }

        while (sRegExp.test(sValue)) {
            sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
        }

        return sValue;
    }

    function showSeparator() {
        var myValue = document.getElementById("txtInvoicePrice").value;
        myValue = thousandSeparator(myValue.replace(/,/g, ""), ',');
        document.getElementById("txtInvoicePrice").value = myValue;
    }

    function removeSeparator() {
        var myValue = document.getElementById("txtInvoicePrice").value;
        myValue = myValue.replace(',', '');
        document.getElementById("txtInvoicePrice").value = myValue;
    }
</script>
</head>
<body>
    <input type="text" id="txtInvoicePrice" onfocus="javascript:removeSeparator();" onblur="javascript:showSeparator();" />
</body>
</html>


问:
Force Windows Batch Script Return Code 0
A vendor has provided us with a Windows Batch script that needs to have a return code of 0.

Per that vendor, there are safe to ignore messages being printed by the script.

The scripts are used for quiescing the application for a proper backup. Our backup software requires a return code of 0.

How can I do this?

答:
End the script with:</p>

```<code>exit /b 0
</code>```

Body:
End the script with:

exit /b 0


问:
How to implement an appdelegate in cocoa touch framework?
How to implement an appdelegate in own framework class?.Because i have to detect when app is entering to foreground/background.
Ex: like, in android Applifecycle run in service class</p>

答:
You can create your own App Delegate class by simply implementing the UIApplicationDelegate protocol:

```<code>@UIApplicationMain
class CustomAppDelegate: UIResponder, UIApplicationDelegate {}
</code>```

Note you will have to implement the various app delegate methods in this class.

EDIT:

In order to call this from another class you can cast the appDelegate singleton as follows:

```<code>if let appDelegate = UIApplication.shared.delegate as? CustomAppDelegate {}
</code>```

Body:
You can create your own App Delegate class by simply implementing the UIApplicationDelegate protocol:

@UIApplicationMain
class CustomAppDelegate: UIResponder, UIApplicationDelegate {}

Note you will have to implement the various app delegate methods in this class.

EDIT:

In order to call this from another class you can cast the appDelegate singleton as follows:

if let appDelegate = UIApplication.shared.delegate as? CustomAppDelegate {}


问:
SharePoint 2013 upload images in site assets using jquery
We have a requirement to upload images using jquery using input file picker. Is there any services or rest api available to upload images in site assets. </p>

答:
You can refer this.
Here you can get the idea how to achieve your goal. I have never tried this, if it works please let me know :)</p>


问:
How do I "un-revert" a reverted Git commit?
Given a change that has been committed using commit, and then reverted using revert, what is the best way to then undo that revert?

Ideally, this should be done with a new commit, so as to not re-write history.

答:
If you don't like the idea of "reverting a revert" (especially when that means losing history information for many commits), you can always head to the git documentation about "Reverting a faulty merge".

Given the following starting situation

```<code> P---o---o---M---x---x---W---x
  \         /
   A---B---C----------------D---E   <-- fixed-up topic branch
</code>```

(W is your initial revert of the merge M; D and E are fixes to your initially broken feature branch/commit)

You can now simply replay commits A to E, so that none of them "belongs" to the reverted merge:

```<code>$ git checkout E
$ git rebase --no-ff P
</code>```

The new copy of your branch can now be merged to master again:

```<code>   A'---B'---C'------------D'---E'  <-- recreated topic branch
  /
 P---o---o---M---x---x---W---x
  \         /
   A---B---C----------------D---E
</code>```

Body:
If you don't like the idea of "reverting a revert" (especially when that means losing history information for many commits), you can always head to the git documentation about "Reverting a faulty merge".

Given the following starting situation

 P---o---o---M---x---x---W---x
  \         /
   A---B---C----------------D---E   <-- fixed-up topic branch

(W is your initial revert of the merge M; D and E are fixes to your initially broken feature branch/commit)

You can now simply replay commits A to E, so that none of them "belongs" to the reverted merge:

$ git checkout E
$ git rebase --no-ff P

The new copy of your branch can now be merged to master again:

   A'---B'---C'------------D'---E'  <-- recreated topic branch
  /
 P---o---o---M---x---x---W---x
  \         /
   A---B---C----------------D---E