问:
Simple jQuery problem
This one should be easy

I've got this HTML

```<code><table class="PageNumbers">
<tr>
    <td colspan="3">text3
    </td>
</tr>
<tr>
    <td colspan="2">text
    </td>
    <td>text2
    </td>
</tr>
<tr>
    <td>moretext
    </td>
    <td>moretext2
    </td>
<td>moretext3
    </td>
</tr>
</table>
</code>```

I need to change the colspan of the first rows first column to one

This is what i've got

```<code>$('.PageNumbers tr:first td:first').attr('colspan') = '1'
</code>```

Doesn't seem to work though

Any ideas?

Thanks

答:
Try this:</p>

```<code>$('.PageNumbers tr:first td:first').attr('colspan', '1');
</code>```

Title: Simple jQuery problem

Body:
This one should be easy

I've got this HTML

    text3

    text

    text2

    moretext

    moretext2

moretext3

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1'

Doesn't seem to work though

Any ideas?

Thanks

Body:
Try this:

$('.PageNumbers tr:first td:first').attr('colspan', '1');


来源: stackexchange

问:
Android Studio error: "Method getText must be called from the UI Thread, currently inferred thread is worker
I got a problem about gettext(), Android studio says that 'method getText must be called from the UI Thread,currently inferred thread is worker'. Can someone help me with this or can someone give an idea how to fix this?
Thanks!

```<code>package com.ibm.watsonvoicetts;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;

public class MainActivity extends AppCompatActivity {

TextView textView;
EditText editText;
Button button;

StreamPlayer streamPlayer;

private TextToSpeech initTextToSpeechService(){
    TextToSpeech service = new TextToSpeech();
    String username = "";
    String password = "";
    service.setUsernameAndPassword(username, password);
    return service;
}

private class WatsonTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... textToSpeak) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText("running the Watson thread");
            }
        });

        TextToSpeech textToSpeech = initTextToSpeechService();
        streamPlayer = new StreamPlayer();
        streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());

        return "text to speech done";
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText("TTS status: " + result);
    }

}

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

    editText = (EditText) findViewById(R.id.editText);
    button = (Button) findViewById(R.id.button);
    textView = (TextView) findViewById(R.id.textView);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("the text to speech: " + editText.getText());
            textView.setText("TTS: " + editText.getText());

            WatsonTask task = new WatsonTask();
            task.execute(new String[]{});

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

}

答:
doInBackground() method runs on different thread not in UI thread.

```<code>streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());
</code>```

You are calling getText() method of edittext in this doInBackground() method. That's why it's giving error. Any work of view related things, we have to do it in UI thread.

One thing you can do it, you can place this code within runOnUiThread.

ContentLicense: CC BY-SA 3.0

Body:
I got a problem about gettext(), Android studio says that 'method getText must be called from the UI Thread,currently inferred thread is worker'. Can someone help me with this or can someone give an idea how to fix this?
Thanks!

package com.ibm.watsonvoicetts;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;

public class MainActivity extends AppCompatActivity {

TextView textView;
EditText editText;
Button button;

StreamPlayer streamPlayer;

private TextToSpeech initTextToSpeechService(){
    TextToSpeech service = new TextToSpeech();
    String username = "";
    String password = "";
    service.setUsernameAndPassword(username, password);
    return service;
}

private class WatsonTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... textToSpeak) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText("running the Watson thread");
            }
        });

        TextToSpeech textToSpeech = initTextToSpeechService();
        streamPlayer = new StreamPlayer();
        streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());

        return "text to speech done";
    }

    @Override
    protected void onPostExecute(String result) {
        textView.setText("TTS status: " + result);
    }

}

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

    editText = (EditText) findViewById(R.id.editText);
    button = (Button) findViewById(R.id.button);
    textView = (TextView) findViewById(R.id.textView);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("the text to speech: " + editText.getText());
            textView.setText("TTS: " + editText.getText());

            WatsonTask task = new WatsonTask();
            task.execute(new String[]{});

        }
    });
}

}

Body:
doInBackground() method runs on different thread not in UI thread.

streamPlayer.playStream(textToSpeech.synthesize(
                String.valueOf(editText.getText()),【**here is the problem**】
                Voice.EN_MICHAEL).execute());

You are calling getText() method of edittext in this doInBackground() method. That's why it's giving error. Any work of view related things, we have to do it in UI thread.

One thing you can do it, you can place this code within runOnUiThread.


问:
Authentication login with Swagger
I am using Swagger UI for interactive REST endpoints representation. However, Swagger UI can be accessed by everyone who knows its URL. Is there any standard way to restrict Swagger UI access with user login.

```<code><dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>LATEST</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>LATEST</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-jersey2-jaxrs</artifactId>
    <version>LATEST</version>
</dependency>
</code>```

答:
No, that is outside of swagger's concern. You would just use your normal WebSecurityConfigurerAdapter to control permissions to the swagger-ui.html URL. Would also be pretty confusing if you used different ways of configuring security IMO.

Example

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/swagger-ui.html")
        .access("hasRole('ROLE_ADMIN')");
     }
}
</code>```

But that's if you wan't to do security based on URLs, you could just as much do controller based security, and security on your services if they were involved but they aren't in this case. Security is very much application specific. I can't say do it this way, you might not even want to use Spring Security at all, and just do your own thing, it's just another framework to make your life easier, you could just as easily access the current logged in user in the view resolver for the swagger-ui.html view and throw an Unauthorised exception or something like that.

Title: Authentication login with Swagger

Body:
I am using Swagger UI for interactive REST endpoints representation. However, Swagger UI can be accessed by everyone who knows its URL. Is there any standard way to restrict Swagger UI access with user login.

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>LATEST</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>LATEST</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-jersey2-jaxrs</artifactId>
    <version>LATEST</version>
</dependency>

Body:
No, that is outside of swagger's concern. You would just use your normal WebSecurityConfigurerAdapter to control permissions to the swagger-ui.html URL. Would also be pretty confusing if you used different ways of configuring security IMO.

Example

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/swagger-ui.html")
        .access("hasRole('ROLE_ADMIN')");
     }
}

But that's if you wan't to do security based on URLs, you could just as much do controller based security, and security on your services if they were involved but they aren't in this case. Security is very much application specific. I can't say do it this way, you might not even want to use Spring Security at all, and just do your own thing, it's just another framework to make your life easier, you could just as easily access the current logged in user in the view resolver for the swagger-ui.html view and throw an Unauthorised exception or something like that.


问:
How to appendString with spacing in between
I've got my 1st string and 2nd string by using appendString method, the result will be AB. I wanted to give a gap in between to display as A, B.

```<code>scanPackage = [NSString stringWithFormat:@"%@", result.text];

NSMutableString *string = [NSMutableString stringWithString:savedString];
[string appendString:scanPackage];

//Saved into memory
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setObject:string forKey:@"scanResult"];
</code>```

答:
You can use NSString function stringByAppendingFormat:.  Try this.

```<code>scanPackage = [NSString stringWithFormat:@"%@", result.text];
NSString *string = [savedString stringByAppendingFormat:@", %@",scanPackage];
//Saved into memory
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setObject:string forKey:@"scanResult"];
</code>```

Body:
I've got my 1st string and 2nd string by using appendString method, the result will be AB. I wanted to give a gap in between to display as A, B.

scanPackage = [NSString stringWithFormat:@"%@", result.text];

NSMutableString *string = [NSMutableString stringWithString:savedString];
[string appendString:scanPackage];

//Saved into memory
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setObject:string forKey:@"scanResult"];

Body:
You can use NSString function stringByAppendingFormat:.  Try this.

scanPackage = [NSString stringWithFormat:@"%@", result.text];
NSString *string = [savedString stringByAppendingFormat:@", %@",scanPackage];
//Saved into memory
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setObject:string forKey:@"scanResult"];


问:
Animated ActionButton do not fire click event
I am animating an action button:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ImageView iv = (ImageView)inflater.inflate(R.layout.iv_main_menu_icon, null);
    Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
    rotation.setRepeatCount(Animation.INFINITE);
    iv.startAnimation(rotation);
    menu.findItem(R.id.action_goto_menu).setActionView(iv);
    return super.onCreateOptionsMenu(menu);
}
</code>```

But the problem is, after applying this animation the click event isn't firing from this. What am I missing?

答:
I think you should put that code inside </p>

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {

default:
    return super.onOptionsItemSelected(item);
}
}
</code>```

<p>not inside </p>

```<code>onCreateOptionsMenu()
</code>```

Body:
I am animating an action button:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ImageView iv = (ImageView)inflater.inflate(R.layout.iv_main_menu_icon, null);
    Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
    rotation.setRepeatCount(Animation.INFINITE);
    iv.startAnimation(rotation);
    menu.findItem(R.id.action_goto_menu).setActionView(iv);
    return super.onCreateOptionsMenu(menu);
}

But the problem is, after applying this animation the click event isn't firing from this. What am I missing?

Body:
I think you should put that code inside

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {

default:
    return super.onOptionsItemSelected(item);
}
}

not inside

onCreateOptionsMenu()


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
Search for "Encapsulation".
There are so many easy materials to study it.</p>

ContentLicense: CC BY-SA 2.5

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?


问:
How to install a development Framework in MacOS for commandline build
I have an iOS application that needs to be integrated into CI/CD pipeline in CircleCI. Most of my dependencies have been added using CocoPods. There is one particular dependency of OpenCV2 that is manually compiled and used. On the local development machine, It is simple to use with drag & drop in Xcode. But, while running the build on a CI server. We don't have access to GUI and need to link dependency from the command line. I have not found much of the resources dealing with this issue.

I have tried few options from this link

https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPFrameworks/Tasks/InstallingFrameworks.html

The framework that I am trying to use is compiled and zipped in an archive (opencv2.framework.zip and uploaded on Amazon S3. It is because the compiled framework is about 300 MB in size. So, I can't push it to the source repository. So, I download it using curl and unzip on CI machine. I have tried unzipping it to

/System/Library/Frameworks

/Library/Frameworks

~/Library/Frameworks

gym --scheme "project" --workspace "project.xcworkspace"

None of them really worked.I would like a way to register this framework in the system so that linker can find it while linking.

Suggest a way to extract framework into a location which linker can automatically look into.

Suggest a way where I can link framework manually from command line build

答:
I have never used OpenCV but a quick pod search gives this result, so looks like they are already supporting cocoapods.....

```<code>pod search opencv
-> OpenCV2 (3.2.0)
   OpenCV (Computer Vision) for iOS.
   pod 'OpenCV2', '~> 3.2.0'
   - Homepage: http://opencv.org
   - Source:   http://github.com/bcomeau/opencv/releases/download/3.2.0/opencv-3.2.0-ios-framework.zip
   - Versions: 3.2.0 [master repo]
</code>```

Second:

You can use Carthage https://github.com/Carthage/Carthage

You can use both Cocoapods and Carthage at the same time as long as they are not downloading the same dependencies.

Create a private repo, follow the carthage tutorial for uploading frameworks https://github.com/Carthage/Carthage#supporting-carthage-for-your-framework

then put opencv2 to your repo.

Then add your repo to your cartfile

Then before or after you install cocoapods, install carthage frameworks too.

It is a bit work but can solve your problem.

Third:

Looks like they also support Carthage
https://github.com/card-io/card.io-iOS-source/issues/32

Look at the last couple of comments..

Body:
I have never used OpenCV but a quick pod search gives this result, so looks like they are already supporting cocoapods.....

pod search opencv
-> OpenCV2 (3.2.0)
   OpenCV (Computer Vision) for iOS.
   pod 'OpenCV2', '~> 3.2.0'
   - Homepage: http://opencv.org
   - Source:   http://github.com/bcomeau/opencv/releases/download/3.2.0/opencv-3.2.0-ios-framework.zip
   - Versions: 3.2.0 [master repo]

Second:

You can use Carthage https://github.com/Carthage/Carthage

You can use both Cocoapods and Carthage at the same time as long as they are not downloading the same dependencies.

Create a private repo, follow the carthage tutorial for uploading frameworks https://github.com/Carthage/Carthage#supporting-carthage-for-your-framework

then put opencv2 to your repo.

Then add your repo to your cartfile

Then before or after you install cocoapods, install carthage frameworks too.

It is a bit work but can solve your problem.

Third:

Looks like they also support Carthage
https://github.com/card-io/card.io-iOS-source/issues/32

Look at the last couple of comments..


问:
Replace the list items with specific characters using lambda

This will give me the list of string having "WIGS_AUTH_" in each item. Now I want to remove this part from the list items in the same expression. Or any better way to achieve this?

答:
you can try something like this:
result.Where(x => x.Contains("WIGS_AUTH")).Select(x => new Permision() { Name=x.Replace("WIGS_AUTH","") }).ToList();

First its filtering the result and taking items containing "WING_AUT"

now it is creating  new object of PermissionDto and set name property without "WIGS_AUTH"

adding new object to list and returning back


问:
Default value for models.GenericIpAddressField
i am trying to add another column in my model:

ip_address = models.GenericIPAddressField()

and when i run makemigrations, i have to set a default value. what should i put? thanks in advance.

models.py

```<code>class Prospect(models.Model):
    full_name = models.CharField(max_length=120)
    email = models.CharField(max_length=80)
    contact_number = models.CharField(max_length=14)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey(VendicsUser, null=True)
    ip_address = models.GenericIPAddressField()

    def __unicode__(self):
        return self.full_name

    def __str__(self):
        return self.email
</code>```

答:
either from shell when asked about default, you can enter any default ip for all the rows that are there, like 192.168.0.1 or you can change it in the model by putting an default value like</p>

```<code>ip_address = models.GenericIPAddressField(default='192.168.0.1')
</code>```

Body:
i am trying to add another column in my model:

ip_address = models.GenericIPAddressField()

and when i run makemigrations, i have to set a default value. what should i put? thanks in advance.

models.py

class Prospect(models.Model):
    full_name = models.CharField(max_length=120)
    email = models.CharField(max_length=80)
    contact_number = models.CharField(max_length=14)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey(VendicsUser, null=True)
    ip_address = models.GenericIPAddressField()

    def __unicode__(self):
        return self.full_name

    def __str__(self):
        return self.email

Body:
either from shell when asked about default, you can enter any default ip for all the rows that are there, like 192.168.0.1 or you can change it in the model by putting an default value like

ip_address = models.GenericIPAddressField(default='192.168.0.1')


问:
Viewing my IIS hosted site on other machines on my network
At home I have a simple network setup containing 2 machines.

On one machine i have a site hosted with IIS7. Rather than the standard localhost/index.htm address I have added an entry in the HOSTS file pointing the local IP (127.0.0.1) to this domain - www.mysite.dev.

I can access the site with www.mysite.dev with no problem.

what I would like to do is be able to view this site from my other machine on the network.

Initially I assumed this could be done with a URL like so
MACHINE-NAME/www.mysite.dev, but the connection always times out. But I can ping MACHINE-NAME without problems.

For testing purposes I have disabled the windows firewall on both machines but to no joy.

Like a typical web developer, my hardware/network skills are pretty poor.

Can anyone see where I'm going wrong?

答:
You have to do following steps.

Go to IIS ->

Sites->

Click on Your Web site ->

In Action Click on Edit Permissions ->

Security ->

Click on ADD ->

Advanced ->

Find Now ->

Add all the users in it ->

and grant all permissions to other users ->

click on Ok.

If you do above things properly you can access your web site by using your domain.

Suggestion - Do not add host name to your site it creates problem sometime. So please host your web site using your machines ip address.


问:
Java algorithm to check to detect if all characters in string are unique not working with Hashmap? Is there a better solution using map operators?
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

```<code>public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}
</code>```

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

答:
This is definitely not the best solution but don't forget about Set<> and fast iteration:</p>

```<code>public boolean hasUniqueChars(String word) {
    Set<Character> characters = new HashSet<>();
    for(Character c : word.toCharArray()) {
        if(characters.contains(c)) return false;
        characters.add(c);
    }
    return true;
}
</code>```

Body:
I have the following code for detecting if all the characters in a string are unique, return true if unique or false if not. Why do the characters in my map never increment beyond 1?

public static boolean hasUniqueChars(String word) {
    HashMap<String, Integer> map = new HashMap<>();
    for(int i = 0; i < word.length(); i++) {
        if(map.get(word.charAt(i)) == null) { // this appears to always equal null even though there is data after the first instance of a character is put into it?
            map.put(""+word.charAt(i), 1);
        } else {
            map.put(""+word.charAt(i), (Integer)map.get(""+word.charAt(i))+1);
        }
    }
    Iterator it = map.entrySet().iterator();
    while(it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        if((Integer)pair.getValue() != 1) {
            return false;
        }
    }
    return true;

}

Also is there a more "reactive" way to do this like maybe using map operators for each of the chars to help determine whether there is a duplicate character?

Body:
This is definitely not the best solution but don't forget about Set<> and fast iteration:

public boolean hasUniqueChars(String word) {
    Set<Character> characters = new HashSet<>();
    for(Character c : word.toCharArray()) {
        if(characters.contains(c)) return false;
        characters.add(c);
    }
    return true;
}


问:
How to Hide the Vertical Scrollbar While the Textbox is not Full and Display When it is Full
Can you please let me know how I can set the windows form textbox vertical scroller in a mood that Scrollbar displays only when the Text size is more that the space of textbox?

Thanks

答:
Here is another approach:

```<code>internal static Size GetTextDimensions(Control control, Font font, string stringData)
{
    using (Graphics g = control.CreateGraphics())
    {
        SizeF sizeF = g.MeasureString(stringData, font);
        return new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height));
    }
}
</code>```

Usuage:

```<code>        Size dimensions = ControlManager.GetTextDimensions(descriptionTextBox, descriptionTextBox.Font, descriptionTextBox.Text);

        descriptionTextBox.ScrollBars = dimensions.Height >
                                        descriptionTextBox.Height ?
                                        ScrollBars.Vertical : ScrollBars.None;
</code>```

You may have to add or subtract depending on padding, but this works great.  Here is an extension method version:

```<code>    public static Size GetTextDimensions(this Control control, Font font, string stringData)
    {
        using (Graphics g = control.CreateGraphics())
        {
            SizeF sizeF = g.MeasureString(stringData, font);
            return new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height));
        }
    }
</code>```

Body:
Here is another approach:

internal static Size GetTextDimensions(Control control, Font font, string stringData)
{
    using (Graphics g = control.CreateGraphics())
    {
        SizeF sizeF = g.MeasureString(stringData, font);
        return new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height));
    }
}

Usuage:

        Size dimensions = ControlManager.GetTextDimensions(descriptionTextBox, descriptionTextBox.Font, descriptionTextBox.Text);

        descriptionTextBox.ScrollBars = dimensions.Height >
                                        descriptionTextBox.Height ?
                                        ScrollBars.Vertical : ScrollBars.None;

You may have to add or subtract depending on padding, but this works great.  Here is an extension method version:

    public static Size GetTextDimensions(this Control control, Font font, string stringData)
    {
        using (Graphics g = control.CreateGraphics())
        {
            SizeF sizeF = g.MeasureString(stringData, font);
            return new Size((int)Math.Ceiling(sizeF.Width), (int)Math.Ceiling(sizeF.Height));
        }
    }


问:
Page doesn't open on clicking in side menu - ionic 2 app
I am unable to open a page upon clicking it in side menu.

This is my app.component.ts:

```<code>this.pages = [
                { title: 'NFC Page', component: NfcPage, note: 'NFC Page' },
                { title: 'Student Details', component: StudentDetails, note: 'Student Details' },
    ];
</code>```

This is my app.module.ts:

```<code>@NgModule({
  declarations: [
    StudentDetails,
    NfcPage,
],
entryComponents: [
    StudentDetails,
    NfcPage,
  ],
</code>```

This is my nfc.ts page:

```<code> import {Component} from '@angular/core';
    import {IonicPage, NavController, NavParams} from 'ionic-angular';
    import {NFC, Ndef} from '@ionic-native/nfc';

    @IonicPage()
    @Component({
        selector: 'page-nfc',
        templateUrl: 'nfc.html',
    })
    export class NfcPage {

        constructor(public navCtrl: NavController,
                    public navParams: NavParams,
                    private nfc: NFC,
                    private ndef: Ndef) {
}
}
</code>```

This is my nfc.html page:

```<code><ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>NFCPage</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <p>NFC Page!</p>
</ion-content>
</code>```

Student details page opens fine but when I click "Nfc page", nothing happens.

答: I have managed to find a solution. The problem is in the constructor of nfc.ts module. The two private parameters (private nfc: NFC and private ndef: Ndef) seem to be broken from the plugin that I am using. I removed these two parameters from the constructor and I was able to open the page. Sadly there was no exception thrown in the console or anywhere else. Hope it helps someone.

Body:
I am unable to open a page upon clicking it in side menu.

This is my app.component.ts:

this.pages = [
                { title: 'NFC Page', component: NfcPage, note: 'NFC Page' },
                { title: 'Student Details', component: StudentDetails, note: 'Student Details' },
    ];

This is my app.module.ts:

@NgModule({
  declarations: [
    StudentDetails,
    NfcPage,
],
entryComponents: [
    StudentDetails,
    NfcPage,
  ],

This is my nfc.ts page:

 import {Component} from '@angular/core';
    import {IonicPage, NavController, NavParams} from 'ionic-angular';
    import {NFC, Ndef} from '@ionic-native/nfc';

    @IonicPage()
    @Component({
        selector: 'page-nfc',
        templateUrl: 'nfc.html',
    })
    export class NfcPage {

        constructor(public navCtrl: NavController,
                    public navParams: NavParams,
                    private nfc: NFC,
                    private ndef: Ndef) {
}
}

This is my nfc.html page:

<ion-header>
    <ion-navbar>
        <button ion-button menuToggle>
            <ion-icon name="menu"></ion-icon>
        </button>
        <ion-title>NFCPage</ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>

NFC Page!

</ion-content>

Student details page opens fine but when I click "Nfc page", nothing happens.


问:
Entity Framework and Many-to-Many relationships, controlling the Intermediate table column names
I'm trying to wrap my head around a Many-to-Many relationship with Code-First mapping.

If I have an Album Class that can have many Genres (and vice-versa), I understand that I need to have an Intermediate table and Entity Framework will automatically do that for me.  However, I would like a little more control over the Intermediate table, so I am creating one myself, the main reason is that I would like to be able to mark the row as deleted from the front-end and leave it in the database.

To do this for all my Classes I have created a BaseObject that they are Inherit from (I've removed many of the Annotations and other code to simplify this post):

```<code>public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Oid { get; set;
    public DateTime DateCreated { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime? DeletedDate { get; set; }
}
</code>```

After that we have the Albums and Genres Classes:

```<code>public class Album : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Albums { get; set; }
}

public class Genre : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Genres { get; set; }
}
</code>```

Finally the AlbumsGenres Intermediate Class:

```<code>public class AlbumsGenres : BaseObject
{
    // Left blank because EF will create "Album_Oid" and "Genre_Oid" columns
    // Tried the below code, but EF still created it's own Columns
    /*
        public Guid Album { get; set; }
        public Guid Genre { get; set; }
    */
}
</code>```

The questions that I have; Is there a way to tell EF to create Album_Oid with a different Column Name like Album?

I would accept an answer of "Just don't worry about it", if a brief explanation (or link) was provided.

答:
You can control the intermediate table, Normally I use explicit mapping but the following works with CodeFirst:

In Album, you want a List<Genre> (not AlbumGenre)
In Genre, you want a List<Album>

In your context, add the following override for OnModelCreating:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Album>()
        .HasMany(a => a.Genres)
        .WithMany(g => g.Albums)
        .Map(x =>
        {
            x.MapLeftKey("AlbumId");
            x.MapRightKey("GenreId");
            x.ToTable("AlbumGenres");
        });

    base.OnModelCreating(modelBuilder);
}
</code>```

Body:
I'm trying to wrap my head around a Many-to-Many relationship with Code-First mapping.

If I have an Album Class that can have many Genres (and vice-versa), I understand that I need to have an Intermediate table and Entity Framework will automatically do that for me.  However, I would like a little more control over the Intermediate table, so I am creating one myself, the main reason is that I would like to be able to mark the row as deleted from the front-end and leave it in the database.

To do this for all my Classes I have created a BaseObject that they are Inherit from (I've removed many of the Annotations and other code to simplify this post):

public class BaseObject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid Oid { get; set;
    public DateTime DateCreated { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime? DeletedDate { get; set; }
}

After that we have the Albums and Genres Classes:

public class Album : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Albums { get; set; }
}

public class Genre : BaseObject
{
    public string Name { get; set; }
    public virtual List<AlbumsGenres> Genres { get; set; }
}

Finally the AlbumsGenres Intermediate Class:

public class AlbumsGenres : BaseObject
{
    // Left blank because EF will create "Album_Oid" and "Genre_Oid" columns
    // Tried the below code, but EF still created it's own Columns
    /*
        public Guid Album { get; set; }
        public Guid Genre { get; set; }
    */
}

The questions that I have; Is there a way to tell EF to create Album_Oid with a different Column Name like Album?

I would accept an answer of "Just don't worry about it", if a brief explanation (or link) was provided.

Body:
You can control the intermediate table, Normally I use explicit mapping but the following works with CodeFirst:

In Album, you want a List<Genre> (not AlbumGenre)
In Genre, you want a List<Album>

In your context, add the following override for OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Album>()
        .HasMany(a => a.Genres)
        .WithMany(g => g.Albums)
        .Map(x =>
        {
            x.MapLeftKey("AlbumId");
            x.MapRightKey("GenreId");
            x.ToTable("AlbumGenres");
        });

    base.OnModelCreating(modelBuilder);
}


问:
POSTing a Sitefinity module with a classification to the oData web service fails
I have a custom module in Sitefinity where one field is a Classification.

I am trying to POST a JSON object to a Sitefinity 9 web service using a route like http://mywebsite.com/api/default/customModule

My POST body looks something like this:

```<code>{
"Field1": "sample string 1",
"Field2": "sample string 2",
"Field3": "sample string 3",
"Category": [
    "6bd9a66e-0e6e-4255-b628-89b86cde6eae"
]
}
</code>```

This is in line with the sfhelp documentation and everything works properly if I remove the "Category" field.

Currently I am getting an error of
Unable to cast object of type 'System.Collections.Generic.List'1[System.Guid]' to type 'Telerik.OpenAccess.TrackedList'1[System.Guid]'

答:
Looks like the field is single, e.g. you are only allowed to select one category, so the request should not send an array of categories:</p>

```<code>{

"Field1": "sample string 1",
"Field2": "sample string 2",
"Field3": "sample string 3",
"Category": "6bd9a66e-0e6e-4255-b628-89b86cde6eae"
}
</code>```

Body:
I have a custom module in Sitefinity where one field is a Classification.

I am trying to POST a JSON object to a Sitefinity 9 web service using a route like http://mywebsite.com/api/default/customModule

My POST body looks something like this:

{
"Field1": "sample string 1",
"Field2": "sample string 2",
"Field3": "sample string 3",
"Category": [
    "6bd9a66e-0e6e-4255-b628-89b86cde6eae"
]
}

This is in line with the sfhelp documentation and everything works properly if I remove the "Category" field.

Currently I am getting an error of
Unable to cast object of type 'System.Collections.Generic.List'1[System.Guid]' to type 'Telerik.OpenAccess.TrackedList'1[System.Guid]'

Body:
Looks like the field is single, e.g. you are only allowed to select one category, so the request should not send an array of categories:

{

"Field1": "sample string 1",
"Field2": "sample string 2",
"Field3": "sample string 3",
"Category": "6bd9a66e-0e6e-4255-b628-89b86cde6eae"
}


问:
How does one create a Python virtualenv in Jenkins?
I am using a Makefile to provide consistent single commands for setting up a virtualenv, running tests, etc.  I have configured my Jenkins instance to pull from a mercurial repo and then run "make virtualenv", which does this:

```<code>virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && pip install -r requirements.txt
</code>```

But for some reason it insists on using the system-installed pip and trying to install my package dependencies in the system site-packages rather than the virtualenv:

```<code>error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied
</code>```

If I add some debugging commands and explicitly point to the pip in my virtualenv, things get even more confusing:

```<code>virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && ls -l bin && which pip && pwd && ./bin/pip install -r requirements.txt
</code>```

Which generates the following output:

```<code>New python executable in ./bin/python2.7
Not overwriting existing python script ./bin/python (you must use ./bin/python2.7)
Installing setuptools, pip...done.
Running virtualenv with interpreter /usr/bin/python2.7
</code>```

It appears Jenkins doesn't rebuild the environment from scratch for each build, which strikes me as an odd choice, but shouldn't effect my immediate issue

The output from the "ls -l bin" shows pip to be installed in the virtualenv and executable:

```<code>-rw-r--r-- 1 jenkins jenkins    2248 Apr  9 21:14 activate
-rw-r--r-- 1 jenkins jenkins    1304 Apr  9 21:14 activate.csh
-rw-r--r-- 1 jenkins jenkins    2517 Apr  9 21:14 activate.fish
-rw-r--r-- 1 jenkins jenkins    1129 Apr  9 21:14 activate_this.py
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install-2.7
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python -> python2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python2 -> python2.7
-rwxr-xr-x 1 jenkins jenkins 3349512 Apr 10 19:31 python2.7
</code>```

The output of "which pip" seems to want to use the correct one:

```<code>/var/lib/jenkins/jobs/Run Tests/workspace/bin/pip
</code>```

My current working directory is what I expect it to be:

```<code>/var/lib/jenkins/jobs/Run Tests/workspace
</code>```

But... wtf?

```<code>/bin/sh: 1: ./bin/pip: Permission denied
make: *** [virtualenv] Error 126
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

答:
Jenkins pipelines can be made to run with virtual environments but there are multiple things to consider.

The default shell that Jenkins uses is /bin/sh - this is configurable in Manage Jenkins -> Configure System -> Shell -> Shell executable. Setting this to /bin/bash will make source work.

An activated venv simply changes environment variables, and environment variables do not persist between stages in jenkins. See withEnv

If you are using version controlled multibranch pipelines jenkins creates a workspace with the branch name and a commit hash in the path - which can be quite long. venv scripts (e.g. pip) all start with a hashbang line which includes the full path to the python interpreter in the venv (the python interpreter itself is a symlink). E.g.,

```<code>~/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSUDYPJ34QR63ITGMC5VJNB56W6ID244AA/env/bin$ cat pip
#!/var/jenkins_home/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSUDYPJ34QR63ITGMC5VJNB56W6ID244AA/env/bin/python3.5
</code>```

Bash only reads the first N characters of any executable file - which I found did not quite include the full venv path:

```<code>bash: ./pip: /var/jenkins_home/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSU: bad interpreter: No such file or directory
</code>```

This particular problem can be avoided by executing the script with Python instead. E.g. python3.5 ./pip

Body:
I am using a Makefile to provide consistent single commands for setting up a virtualenv, running tests, etc.  I have configured my Jenkins instance to pull from a mercurial repo and then run "make virtualenv", which does this:

virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && pip install -r requirements.txt

But for some reason it insists on using the system-installed pip and trying to install my package dependencies in the system site-packages rather than the virtualenv:

error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied

If I add some debugging commands and explicitly point to the pip in my virtualenv, things get even more confusing:

virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && ls -l bin && which pip && pwd && ./bin/pip install -r requirements.txt

Which generates the following output:

New python executable in ./bin/python2.7
Not overwriting existing python script ./bin/python (you must use ./bin/python2.7)
Installing setuptools, pip...done.
Running virtualenv with interpreter /usr/bin/python2.7

It appears Jenkins doesn't rebuild the environment from scratch for each build, which strikes me as an odd choice, but shouldn't effect my immediate issue

The output from the "ls -l bin" shows pip to be installed in the virtualenv and executable:

-rw-r--r-- 1 jenkins jenkins    2248 Apr  9 21:14 activate
-rw-r--r-- 1 jenkins jenkins    1304 Apr  9 21:14 activate.csh
-rw-r--r-- 1 jenkins jenkins    2517 Apr  9 21:14 activate.fish
-rw-r--r-- 1 jenkins jenkins    1129 Apr  9 21:14 activate_this.py
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install-2.7
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python -> python2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python2 -> python2.7
-rwxr-xr-x 1 jenkins jenkins 3349512 Apr 10 19:31 python2.7

The output of "which pip" seems to want to use the correct one:

/var/lib/jenkins/jobs/Run Tests/workspace/bin/pip

My current working directory is what I expect it to be:

/var/lib/jenkins/jobs/Run Tests/workspace

But... wtf?

/bin/sh: 1: ./bin/pip: Permission denied
make: *** [virtualenv] Error 126
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Body:
Jenkins pipelines can be made to run with virtual environments but there are multiple things to consider.

The default shell that Jenkins uses is /bin/sh - this is configurable in Manage Jenkins -> Configure System -> Shell -> Shell executable. Setting this to /bin/bash will make source work.

An activated venv simply changes environment variables, and environment variables do not persist between stages in jenkins. See withEnv

If you are using version controlled multibranch pipelines jenkins creates a workspace with the branch name and a commit hash in the path - which can be quite long. venv scripts (e.g. pip) all start with a hashbang line which includes the full path to the python interpreter in the venv (the python interpreter itself is a symlink). E.g.,

~/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSUDYPJ34QR63ITGMC5VJNB56W6ID244AA/env/bin$ cat pip
#!/var/jenkins_home/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSUDYPJ34QR63ITGMC5VJNB56W6ID244AA/env/bin/python3.5

Bash only reads the first N characters of any executable file - which I found did not quite include the full venv path:

bash: ./pip: /var/jenkins_home/workspace/ink_feature-use-jenkinsfile-VGRPYD53GGGDDSBIJDLSU: bad interpreter: No such file or directory

This particular problem can be avoided by executing the script with Python instead. E.g. python3.5 ./pip


问:
Revision control locking: Is the jury still out?
When I'm online it seems that everyone has agreed that using the exclusive locking workflow in source control is a Bad Thing. All the new revision control systems I see appear to be built for edit and merge workflows, and many don't even support exclusive locks at all.

However, everyone I work with is of the opinion that exclusive locks are a "must have" for any source control system, and working any other way would be a nightmare. Even recent hires from other companies seem to come in with this idea.

My question isn't who is right. I'm pretty sure what answer I'd get to that. My question is, is there really still any debate over this matter? Is there an honest "pro locking" camp out there that makes a serious case? Is any work being done to advance the art of revision control based around the locking model? Or are locking fans flogging a dead horse?

EDIT:
The answers so far have done a good job of explaining why exclusive locks are a good feature to use occasionally. However, I'm talking about promoting a workflow where exclusive locks are used for everything.

答:
I like having the option to exclusive-lock some file[s].

Having an exclusive lock is necessary, e.g. for binary files.

It's also semi-necessary for some machine-generated non-binary files (e.g. for Visual Studio project files, which don't 'merge' at all well if ever there are two parallel changes to be merged).

OwnerDisplayName: ChrisW


问:
How do you call a function once a day at a certain time in c++?
Well i need to figure out how to call a function at a certain time if my application is running.

it will probably be in a while loop and check the time but i don't want it to check the time every minute but i don't want it to miss the exact time, say 18:00.

is there any way do to this?

答: The best way would be to use the operating system tools that provide this and you only worry about writing your function.  But if thats not an option you will need to just check the clock periodicly as you said.</p>


问:
React Router v4 Redirect unit test
How do I unit test the  component in react router v4?
I am unsuccessfully trying to unit test a simple component with a redirect using jest and enzyme.

My component:

```<code> const AppContainer = ({ location }) =>
  (isUserAuthenticated()
    ? <AppWithData />
    : <Redirect
        to={{
          pathname: "/login",
          state: { from: location }
        }}
      />);
</code>```

My attempt to test it:

```<code>  function setup() {
      const enzymeWrapper = mount(
        <MemoryRouter initialEntries={["/"]}>
          <AppContainer />
        </MemoryRouter>
      );

      return {
        enzymeWrapper
      };
    }

    jest.mock("lib/authAPI", () => ({
      isUserAuthenticated: jest.fn(() => false)
    }));

    describe("AppContainer component", () => {
      it("renders redirect", () => {
        const { enzymeWrapper } = setup();

        expect(enzymeWrapper.find("<Redirect></Redirect>")).toBe(true);
      });
    });
</code>```

答:
Answering my own question.
Basically I'm making a shallow render of my component and verifying that if authenticated is rendering the redirect component otherwise the App one.
Here the code:</p>

```<code>function setup() {
  const enzymeWrapper = shallow(<AuthenticatedApp />);

  return {
    enzymeWrapper
  };
}

describe("AuthenticatedApp component", () => {
  it("renders Redirect when user NOT autheticated", () => {
    authApi.isUserAuthenticated = jest.fn(() => false);
    const { enzymeWrapper } = setup();

    expect(enzymeWrapper.find(Redirect)).toHaveLength(1);
  });

  it("renders AppWithData when user autheticated", () => {
    authApi.isUserAuthenticated = jest.fn(() => true);
    const { enzymeWrapper } = setup();

    expect(enzymeWrapper.find(AppWithData)).toHaveLength(1);
  });
});
</code>```

ContentLicense: CC BY-SA 4.0

Title: React Router v4 Redirect unit test

Body:
How do I unit test the  component in react router v4?
I am unsuccessfully trying to unit test a simple component with a redirect using jest and enzyme.

My component:

 const AppContainer = ({ location }) =>
  (isUserAuthenticated()
    ? <AppWithData />
    : <Redirect
        to={{
          pathname: "/login",
          state: { from: location }
        }}
      />);

My attempt to test it:

  function setup() {
      const enzymeWrapper = mount(
        <MemoryRouter initialEntries={["/"]}>
          <AppContainer />
        </MemoryRouter>
      );

      return {
        enzymeWrapper
      };
    }

    jest.mock("lib/authAPI", () => ({
      isUserAuthenticated: jest.fn(() => false)
    }));

    describe("AppContainer component", () => {
      it("renders redirect", () => {
        const { enzymeWrapper } = setup();

        expect(enzymeWrapper.find("<Redirect></Redirect>")).toBe(true);
      });
    });

Body:
Answering my own question.
Basically I'm making a shallow render of my component and verifying that if authenticated is rendering the redirect component otherwise the App one.
Here the code:

function setup() {
  const enzymeWrapper = shallow(<AuthenticatedApp />);

  return {
    enzymeWrapper
  };
}

describe("AuthenticatedApp component", () => {
  it("renders Redirect when user NOT autheticated", () => {
    authApi.isUserAuthenticated = jest.fn(() => false);
    const { enzymeWrapper } = setup();

    expect(enzymeWrapper.find(Redirect)).toHaveLength(1);
  });

  it("renders AppWithData when user autheticated", () => {
    authApi.isUserAuthenticated = jest.fn(() => true);
    const { enzymeWrapper } = setup();

    expect(enzymeWrapper.find(AppWithData)).toHaveLength(1);
  });
});


答:
Array can do it without manipulated the string, can add more in the array to combine:</p>

```<code>NSString *combined = [@[savedString, scanPackage] componentsJoinedByString:@", "];
</code>```

Title: How to appendString with spacing in between

Body:
I've got my 1st string and 2nd string by using appendString method, the result will be AB. I wanted to give a gap in between to display as A, B.

scanPackage = [NSString stringWithFormat:@"%@", result.text];

NSMutableString *string = [NSMutableString stringWithString:savedString];
[string appendString:scanPackage];

//Saved into memory
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
[preferences setObject:string forKey:@"scanResult"];

Body:
Array can do it without manipulated the string, can add more in the array to combine:

NSString *combined = [@[savedString, scanPackage] componentsJoinedByString:@", "];


问:
Chrome web request blocking not working
I'm trying to use the webrequest api and I'm having trouble using it to block a website.

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "blocktwitter",
  "description": "block twitter",
  "version": "1.0",

  "permissions": [
  "https://ajax.googleapis.com/",
  "activeTab",
  "storage",
  "webRequest",
  "webRequestBlocking"
  ],

"background": {
"scripts": ["background.js"],
"persistent": true
  }
}
</code>```

background.js:

```<code>chrome.webRequest.onBeforeRequest.addListener(
    function(details) { return {cancel: true}; },
    {urls: ["https://twitter.com"]},
    ["blocking"]);
</code>```

I copied the copy + pasted the url from twitter, and copied the code from the docs, but it's still not working. I'm not sure what I'm doing wrong. Help would be appreciated.

答:
You have two problems.

Problem #1: Invalid match pattern

The first problem is that the URL you are passing to chrome.webRequest.onBeforeRequest.addListener() is not a valid match pattern. Match patterns require a path component. If you had looked at the console for your background page/script you would have seen the following error:

_generated_background_page.html:1 Unchecked runtime.lastError while running webRequestInternal.addEventListener: 'https://twitter.com' is not a valid URL pattern.
```

<p>Your <em>background.js</em> should be something like:</p>

<pre class="lang-js prettyprint-override"><code>chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        console.log('In webRequest');
        return {cancel: true};
    }, {
        urls: ["https://*.twitter.com/*"]
    }, ["blocking"]
);
</code>```

Problem #2: No host permission for twitter.com

You need to have permission for the host that you are blocking. You have to declare the host in your permissions array in manifest.json. Something like:

{
  "manifest_version": 2,

  "name": "blocktwitter",
  "description": "block twitter",
  "version": "1.0",

  "permissions": [
    "https://ajax.googleapis.com/*",
    "https://*.twitter.com/*",
    "activeTab",
    "storage",
    "webRequest",
    "webRequestBlocking"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  }
}
```

Title: Chrome web request blocking not working

Body:
I'm trying to use the webrequest api and I'm having trouble using it to block a website.

manifest.json

{
  "manifest_version": 2,

  "name": "blocktwitter",
  "description": "block twitter",
  "version": "1.0",

  "permissions": [
  "https://ajax.googleapis.com/",
  "activeTab",
  "storage",
  "webRequest",
  "webRequestBlocking"
  ],

"background": {
"scripts": ["background.js"],
"persistent": true
  }
}

background.js:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) { return {cancel: true}; },
    {urls: ["https://twitter.com"]},
    ["blocking"]);

I copied the copy + pasted the url from twitter, and copied the code from the docs, but it's still not working. I'm not sure what I'm doing wrong. Help would be appreciated.

Body:
You have two problems.

Problem #1: Invalid match pattern

The first problem is that the URL you are passing to chrome.webRequest.onBeforeRequest.addListener() is not a valid match pattern. Match patterns require a path component. If you had looked at the console for your background page/script you would have seen the following error:

_generated_background_page.html:1 Unchecked runtime.lastError while running webRequestInternal.addEventListener: 'https://twitter.com' is not a valid URL pattern.

Your background.js should be something like:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        console.log('In webRequest');
        return {cancel: true};
    }, {
        urls: ["https://*.twitter.com/*"]
    }, ["blocking"]
);

Problem #2: No host permission for twitter.com

You need to have permission for the host that you are blocking. You have to declare the host in your permissions array in manifest.json. Something like:

{
  "manifest_version": 2,

  "name": "blocktwitter",
  "description": "block twitter",
  "version": "1.0",

  "permissions": [
    "https://ajax.googleapis.com/*",
    "https://*.twitter.com/*",
    "activeTab",
    "storage",
    "webRequest",
    "webRequestBlocking"
  ],

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  }
}


问:
Concatenating 2 bytes in Java efficiently
I am working on a program where I am trying to reduce the amount of memory allocated, I previously use to concatenate strings but the problem was that I do this process several million times and the more I did it the longer it took to allocate these strings. Instead now I am trying work with bytes. I want to do something like this:

```<code>byte[] arr = new byte[5];
byte cat = arr[0] + arr[1]  //this addition would give me an error obviously. It's for demostration purposes

System.out.println(cat);
</code>```

I just want to take the first byte and put the second one right after it without using any form of String Class as it requires more overhead to concatenate strings as such. Is there a way I can do this with minimal operations?

答:
Create a new output byte array of the size equal to the sum of all your bytes that are to concatenated in a new byte array using System.arraycopy()

As System.arraycopy() is native call, it will be certainly faster than String concatenation.

Body:
I am working on a program where I am trying to reduce the amount of memory allocated, I previously use to concatenate strings but the problem was that I do this process several million times and the more I did it the longer it took to allocate these strings. Instead now I am trying work with bytes. I want to do something like this:

byte[] arr = new byte[5];
byte cat = arr[0] + arr[1]  //this addition would give me an error obviously. It's for demostration purposes

System.out.println(cat);

I just want to take the first byte and put the second one right after it without using any form of String Class as it requires more overhead to concatenate strings as such. Is there a way I can do this with minimal operations?


问:
Validate form field only on submit or user input
I have form fields that are validated using required. The problem is, that the error is displayed immediately when the form is rendered. I want it only to be displayed after the user actually typed in the text field, or on submit.

How can I implement this?

答:
Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

```<code>$scope.formName.elementName.$$element.change();
</code>```

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

```<code>vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};
</code>```

c) and one more way for that

```<code>    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };
</code>```

Body:
Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

$scope.formName.elementName.$$element.change();

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};

c) and one more way for that

    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };


问:
How do I iterate through an object but display then in separate rows?
What I'm trying to accomplish is iterating through an object, each of the object has a type property. The goal is to iterate through each object and display them in a row designated by their type.

Right now it looks like this

What I'm trying to do is have the Frontend, Backend, and UI on separate rows.

I'm using Aurelia Framework, here's my View:

```<code><template>
<div class="project-preview-container container">
    <div class="row" repeat.for="projectType of projectTypes">
        <div class="col-md-3 project-preview" repeat.for="project of projects">
            <h3 class="${project.type}">${project.type}</h3>
            <h1>${project.name}</h1>
        </div>
    </div>
</div>
</code>```

Here's my Model:

```<code>export class Portfolio {

constructor() {
    this.header = "Portfolio";
    this.projectTypes = ["Frontend", "Backend", "UI"];
    this.projects = [
        {
            name: "Project Name 1",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 2",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 3",
            type: "Backend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 4",
            type: "UI",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        }
    ]
}
</code>```

}

Any and all feedback is accepted, thank you!

答:
You are just looping through the project types but don't use that data for anything. The inner loop goes through all projects and lists them all, no matter what their type is.

You'll need to either restructure your data so that projectType acts as a container for all projects of that type, or add an if that checks that the project's type matches projectType like this: (pardon me, I've never actually used Aurelia so might not work as-is)

```<code><div if.bind="projectType == project.type">
  <h3 class="${project.type}">${project.type}</h3>
  <h1>${project.name}</h1>
</div>
</code>```

Body:
What I'm trying to accomplish is iterating through an object, each of the object has a type property. The goal is to iterate through each object and display them in a row designated by their type.

Right now it looks like this

What I'm trying to do is have the Frontend, Backend, and UI on separate rows.

I'm using Aurelia Framework, here's my View:

<template>

${project.type}

${project.name}

Here's my Model:

export class Portfolio {

constructor() {
    this.header = "Portfolio";
    this.projectTypes = ["Frontend", "Backend", "UI"];
    this.projects = [
        {
            name: "Project Name 1",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 2",
            type: "Frontend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 3",
            type: "Backend",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        },
        {
            name: "Project Name 4",
            type: "UI",
            img: [
                "Image 1",
                "Image 2",
                "Image 3"
            ],
            descriptionTitle: [
                "Description Title 1",
                "Description Title 2",
                "Description Title 3"
            ],
            description: [
                "Description 1",
                "Description 2",
                "Description 3"
            ]
        }
    ]
}

}

Any and all feedback is accepted, thank you!

Body:
You are just looping through the project types but don't use that data for anything. The inner loop goes through all projects and lists them all, no matter what their type is.

You'll need to either restructure your data so that projectType acts as a container for all projects of that type, or add an if that checks that the project's type matches projectType like this: (pardon me, I've never actually used Aurelia so might not work as-is)

<div if.bind="projectType == project.type">
  <h3 class="${project.type}">${project.type}</h3>
  <h1>${project.name}</h1>
</div>


问:
Iteratively Subset DataFrame based on Unique Times
Given the following example DataFrame:

```<code>>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6
</code>```

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

```<code>>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
</code>```

and

```<code>>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6
</code>```

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

Body:
Given the following example DataFrame:

>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3

and

>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

Body:
Convert Times to a hour period, groupby and then extract each group as a DF.

df1,df2=[g.drop('hour',1) for n,g in\
         df.assign(hour=pd.DatetimeIndex(df.Times)\
           .to_period('h')).groupby('hour')]

df1
Out[874]:
                Times  Values
0 2017-05-10 01:01:03       1
1 2017-05-10 01:05:00       2
2 2017-05-10 01:06:10       3

df2
Out[875]:
                Times  Values
3 2017-05-11 08:25:20       4
4 2017-05-11 08:30:14       5
5 2017-05-11 08:30:35       6


问:
Spring Boot Security: security.basic.path
What is the purpose of having

```<code>security.basic.path=/any-secured-path/**
</code>```

this setting in application.properties?

It seems that Basic Auth is not kicking in automatically accessing this url (or suburls).

答: The security.basic.path starts after context path. So no matter what the context path is, just set the protected path after that. For example, the full url is /mycontextpath/pathA/pathB, if you want to have /pathB to be protected, just set security.basic.path=/pathA/pathB. If context path is / only, you should still set security.basic.path=/pathA/pathB.

Body:
What is the purpose of having

security.basic.path=/any-secured-path/**

this setting in application.properties?

It seems that Basic Auth is not kicking in automatically accessing this url (or suburls).


问:
How do I move a file from one location to another in Java?
How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?</p>

答:
Try this :-</p>

```<code>  boolean success = file.renameTo(new File(Destdir, file.getName()));
</code>```

Body:
Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));


问:
Python BeautifulSoup cannot find table ID
I am running into some trouble scraping a table using BeautifulSoup. Here is my code

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats = soup.find('table',  id = 'totals')

In [78]: print(stats)
None
</code>```

When I right click on the table to inspect the element the HTML looks as I'd expect, however when I view the source the only element with id = 'totals' is commented out. Is there a way to scrape a table from the commented source code?

I have referenced this post but can't seem to replicate their solution.

Here is a link to the webpage I am interested in. I'd like to scrape the table labeled "Totals" and store it as a data frame.

I am relatively new to Python, HTML, and web scraping. Any help would be greatly appreciated.

Thanks in advance.

Michael

答:
Comments are string instances in BeautifulSoup.  You can use BeautifulSoup's find method with a regular expression to find the particular string that you're after.  Once you have the string, have BeautifulSoup parse that and there you go.

In other words,

```<code>import re
from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats_html = soup.find(string=re.compile('id="totals"'))
stats_soup = BeautifulSoup(stats_html, "html.parser")

print(stats_soup.table.caption.text)
</code>```

Body:
I am running into some trouble scraping a table using BeautifulSoup. Here is my code

from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats = soup.find('table',  id = 'totals')

In [78]: print(stats)
None

When I right click on the table to inspect the element the HTML looks as I'd expect, however when I view the source the only element with id = 'totals' is commented out. Is there a way to scrape a table from the commented source code?

I have referenced this post but can't seem to replicate their solution.

Here is a link to the webpage I am interested in. I'd like to scrape the table labeled "Totals" and store it as a data frame.

I am relatively new to Python, HTML, and web scraping. Any help would be greatly appreciated.

Thanks in advance.

Michael

Body:
Comments are string instances in BeautifulSoup.  You can use BeautifulSoup's find method with a regular expression to find the particular string that you're after.  Once you have the string, have BeautifulSoup parse that and there you go.

In other words,

import re
from urllib.request import urlopen
from bs4 import BeautifulSoup

site = "http://www.sports-reference.com/cbb/schools/clemson/2014.html"
page = urlopen(site)
soup = BeautifulSoup(page,"html.parser")

stats_html = soup.find(string=re.compile('id="totals"'))
stats_soup = BeautifulSoup(stats_html, "html.parser")

print(stats_soup.table.caption.text)


问:
Arduino Loop Break
at school currently we are creating a robot using an arduino that can be controlled by Bluetooth, using Thunkable. Currently the app sends the arduino characters that the arduino will recognise and will follow an IF STATEMENT. I've created a Figure 8 command, which works as of now, but it's stuck in loop and won't stop, even if the STOP button is pressed. I made sure to set x = false in the off if statement, but I don't think it's working with the current code. I've tried using a break, but to no avail. All I want to do, is stop the loop from continuing, using the off command. Any help would be appreciated.</p>

```<code>//L293D
// connect motor controller pins to Arduino digital pins
// motor one
char input;
boolean x = false;
boolean timer = true;
int enA = 12;
int in1 = 11;
int in2 = 10;
// motor two
int enB = 8;
int in3 = 9;
int in4 = 7;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  Serial.begin(9600);
  Serial.println(">> START <<");
}
void demoOne()
{
  if(Serial.available() >= 0)
  {
    input = Serial.read();
    if(input=='k')
    {
      Serial.println("ON");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'q')
    {
      Serial.println("REVERSE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'l')
    {
      x = false;
      Serial.println("OFF");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
    else if(input == 'c')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    // THIS IS THE HIGHLIGHTED CODE THAT I NEED HELP WITH
    else if(input == 'i')
    {
      for(x == true; x = true;)
      {
        if(x == false)
        {
          break;
        }
      Serial.println("FIGURE EIGHT MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);

      }
    }

    else if(input == 'r')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else
    {
      Serial.println("NO INPUT");
      Serial.println(input);
      delay(1000);
    }
  }

  /* this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // digitalWrite(in1, HIGH);
  // digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  // analogWrite(enA, 200);
  // turn on motor B
  // digitalWrite(in3, HIGH);
  // digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}
void demoTwo()
{
  /* this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}

void loop()
{
  demoOne();

}
</code>```

答: Arduino loops are not exactly the same as loops you might write in a normal piece of code. What I like to do for my arduino programs is to declare a global boolean variable called "isOn" or something similar. If you surround the entire loop with an if statement checking if this is true, then you will be able to shut off your figure 8 loop by changing the value of this global variable so that your loop stops running. Break statements won't work on the entirety of this loop as you might expect from other programming you have done in the past.</p>

Title: Arduino Loop Break

Body:
at school currently we are creating a robot using an arduino that can be controlled by Bluetooth, using Thunkable. Currently the app sends the arduino characters that the arduino will recognise and will follow an IF STATEMENT. I've created a Figure 8 command, which works as of now, but it's stuck in loop and won't stop, even if the STOP button is pressed. I made sure to set x = false in the off if statement, but I don't think it's working with the current code. I've tried using a break, but to no avail. All I want to do, is stop the loop from continuing, using the off command. Any help would be appreciated.

//L293D
// connect motor controller pins to Arduino digital pins
// motor one
char input;
boolean x = false;
boolean timer = true;
int enA = 12;
int in1 = 11;
int in2 = 10;
// motor two
int enB = 8;
int in3 = 9;
int in4 = 7;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  Serial.begin(9600);
  Serial.println(">> START <<");
}
void demoOne()
{
  if(Serial.available() >= 0)
  {
    input = Serial.read();
    if(input=='k')
    {
      Serial.println("ON");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'q')
    {
      Serial.println("REVERSE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else if(input == 'l')
    {
      x = false;
      Serial.println("OFF");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
    }
    else if(input == 'c')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    // THIS IS THE HIGHLIGHTED CODE THAT I NEED HELP WITH
    else if(input == 'i')
    {
      for(x == true; x = true;)
      {
        if(x == false)
        {
          break;
        }
      Serial.println("FIGURE EIGHT MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
      delay(1000);

      }
    }

    else if(input == 'r')
    {
      Serial.println("CIRCLE MODE");
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      analogWrite(enA, 200);
      analogWrite(enB, 200);
    }
    else
    {
      Serial.println("NO INPUT");
      Serial.println(input);
      delay(1000);
    }
  }

  /* this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // digitalWrite(in1, HIGH);
  // digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  // analogWrite(enA, 200);
  // turn on motor B
  // digitalWrite(in3, HIGH);
  // digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}
void demoTwo()
{
  /* this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i < 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i >= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW); */
}

void loop()
{
  demoOne();

}


问:
Python next iterator in a loop
I have a small routine like this:

```<code>to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)
</code>```

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

答:
Thanks to smarx's comment after the question, I was able to solve this. The iterator will go through million entries in to_use everytime its called. Since I know that to_use entries do not change after being set to False, I wrote an explicit loop keeping track of where the previous loop left off, and started searching from there.

```<code>val = next((i for i in range(n) if to_use[i]),None)
</code>```

cProfile shows 208 seconds for the whole code, most of which is from this line:

```<code>         900811 function calls in 208.227 seconds
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   199599  207.427    0.001  207.427    0.001 toposort.py:43(<genexpr>)
</code>```

Explicit call

```<code>start = 0
to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = None
   for i in range(start,n):
      if to_use[i]:
           val = i
           start = i
           break
</code>```

cProfile shows 0.513 seconds for the whole code

Title: Python next iterator in a loop

Body:
I have a small routine like this:

to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = next((i for i in range(n) if to_use[i]),None)

In my sample, n is of the order of a millon. Is the last like with the iterator the most efficient way to get the next "val"?. Or will it go through to_use from 0 each time in the loop? Note that once to_use[i]=False, its never reset to True.

Body:
Thanks to smarx's comment after the question, I was able to solve this. The iterator will go through million entries in to_use everytime its called. Since I know that to_use entries do not change after being set to False, I wrote an explicit loop keeping track of where the previous loop left off, and started searching from there.

val = next((i for i in range(n) if to_use[i]),None)

cProfile shows 208 seconds for the whole code, most of which is from this line:

         900811 function calls in 208.227 seconds
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   199599  207.427    0.001  207.427    0.001 toposort.py:43(<genexpr>)

Explicit call

start = 0
to_use = [True] * n
val = 0
while (val is not None) :
   # various manipulations on val
   # so the val below is different from
   # val entering the loop
   to_use[val] = False
   val = None
   for i in range(start,n):
      if to_use[i]:
           val = i
           start = i
           break

cProfile shows 0.513 seconds for the whole code


问:
How to set text from bundle (toolbar)
How to set text from bundle (toolbar) I have no idea how to set it.

toolbar.xml

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ToolbarColor">

    <TextView
        android:id="@+id/textView_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My example"
        android:gravity="center"/>
</android.support.v7.widget.Toolbar>
</code>```

DetailActivity.java

```<code>Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            String name = bundle.getString("nameCar");
        }

   Toolbar toolbar = (Toolbar) findViewById(R.id.m_tool_bar_detail);
        TextView textToolbar = (TextView) toolbar.findViewById(R.id.textView_toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar()!=null){

            textToolbar.setText(name); ///ERROR(name)
            getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_name));
        }
</code>```

I've tried textToolbar.setText("xxxxx"); but it gives an error.

I want to get name in bundle to set Textview in toolbar.

答:
I want to get name in bundle to set Textview in toolbar

You should set String name as global.

```<code>String name = null;
</code>```

Then

```<code>if (bundle!=null){
     name = bundle.getString("nameCar");
  }
</code>```

Title: How to set text from bundle (toolbar)

Body:
How to set text from bundle (toolbar) I have no idea how to set it.

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ToolbarColor">

    <TextView
        android:id="@+id/textView_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="My example"
        android:gravity="center"/>
</android.support.v7.widget.Toolbar>

DetailActivity.java

Bundle bundle = getIntent().getExtras();
        if (bundle!=null){
            String name = bundle.getString("nameCar");
        }

   Toolbar toolbar = (Toolbar) findViewById(R.id.m_tool_bar_detail);
        TextView textToolbar = (TextView) toolbar.findViewById(R.id.textView_toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar()!=null){

            textToolbar.setText(name); ///ERROR(name)
            getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_name));
        }

I've tried textToolbar.setText("xxxxx"); but it gives an error.

I want to get name in bundle to set Textview in toolbar.

Body:
I want to get name in bundle to set Textview in toolbar

You should set String name as global.

String name = null;

Then

if (bundle!=null){
     name = bundle.getString("nameCar");
  }


问:
Why Python `Memory Error` with list `append()` lots of RAM left
I am building a large data dictionary from a set of text files.  As I read in the lines and process them, I append(dataline) to a list.

At some point the append() generates a Memory Error exception.  However, watching the program run in the Windows Task Manager, at the point of the crash I see 4.3 GB available and 1.1 GB free.

Thus, I do not understand the reason for the exception.

Python version is 2.6.6.  I guess, the only reason is that it is not able to use more of the available RAM.  If this is so, is it possible to increase the allocation?

答:
If you're open to restructuring the code instead of throwing more memory at it, you might be able to get by with this:

```<code>data = (processraw(raw) for raw in lines)
</code>```

where lines is either a list of lines or file.xreadlines() or similar.

Body:
If you're open to restructuring the code instead of throwing more memory at it, you might be able to get by with this:

data = (processraw(raw) for raw in lines)

where lines is either a list of lines or file.xreadlines() or similar.


问:
Multi form Projects in c# - Displaying multiple windows
My main form is this

Now my problem occurs when I click Add -> Student, which is meant to bring up a new window that, instead it does this

So as you can see it opens the new form inside the same window. It didn't use to do this, then I made the main form an MdiContainer and set it as the MdiParent of the second form.

Is there a property I can change to make this new form pop up in a new window? Becuase I need to leave the MdiContainer property as True so that I can take data from Form2 and use it in Form1

Please let me know any other information you may need to help me fix this issue, as I'm not sure what caused it so I don't know what to change in order to fix it or even where I'm meant to be looking

答:
you need to hide form enroll
when you open add window add.show()

you need to hide enroll form enroll.hide()