问:
Split a string into character efficiently
I am searching for an efficient way to split word into char( I have some special characters like ",). ) . I have done something using loop and substring function but it is super slow.

Example:
Code Input

```<code>words <- data.frame(V1 = c("blibli","blabla","\"","]"))
words$V1 <- as.character(words$V1)
</code>```

Input looks like:

```<code>      V1
1 blibli
2 blabla
3      "
4      ]
</code>```

Code that i have done:

```<code>char_df <- NULL
for(i in 1:nrow(words)){
  print(i)
  temp <- substring(words[i,][1],1:nchar(words[i,]),1:nchar(words[i,]))
  char_df <- rbind(char_df,
                   data.frame(char = temp,
                              idx = 1:nchar(words[i,]) )
  )

}
</code>```

expected output:

```<code> char idx
1     b   1
2     l   2
3     i   3
4     b   4
5     l   5
6     i   6
7     b   1
8     l   2
9     a   3
10    b   4
11    l   5
12    a   6
13    "   1
14    ]   1
</code>```

I am open to any technique dplyr , data.table , base R.

答:
Additionally, I would add the pretty nifty package stringi

```<code>library(stringi)
x<-c("dog","cat","@@$")
unlist(stri_extract_all(x,regex = "."))
[1] "d" "o" "g" "c" "a" "t" "@" "@" "$"
</code>```

Body:
I am searching for an efficient way to split word into char( I have some special characters like ",). ) . I have done something using loop and substring function but it is super slow.

Example:
Code Input

words <- data.frame(V1 = c("blibli","blabla","\"","]"))
words$V1 <- as.character(words$V1)

Input looks like:

      V1
1 blibli
2 blabla
3      "
4      ]

Code that i have done:

char_df <- NULL
for(i in 1:nrow(words)){
  print(i)
  temp <- substring(words[i,][1],1:nchar(words[i,]),1:nchar(words[i,]))
  char_df <- rbind(char_df,
                   data.frame(char = temp,
                              idx = 1:nchar(words[i,]) )
  )

}

expected output:

 char idx
1     b   1
2     l   2
3     i   3
4     b   4
5     l   5
6     i   6
7     b   1
8     l   2
9     a   3
10    b   4
11    l   5
12    a   6
13    "   1
14    ]   1

I am open to any technique dplyr , data.table , base R.

Body:
Additionally, I would add the pretty nifty package stringi

library(stringi)
x<-c("dog","cat","@@$")
unlist(stri_extract_all(x,regex = "."))
[1] "d" "o" "g" "c" "a" "t" "@" "@" "$"


来源: stackexchange

问:
How to Zoom/Scale an Android WebView in Java
Actually I have two webviews and I want to zoom/pan other webview based on first webview. For this the application already uses the following code that works fine upto android 3.0 but on later devices it doesnt work. I checked and Exception is thrown i - e Field Not Found exception for mZoomManager.

I'd like to know any alternative for zooming the webview? Can't use webView.setInitialScale();

```<code>public void setScale(float scale_factor) throws IllegalArgumentException,
        IllegalAccessException, ClassNotFoundException {
    try {
        float temp_scale = scale_factor * 0.01f;
        Class<WebView> webViewClass = (Class<WebView>) this.getClass()
                .getSuperclass();
        Field mZoomManagerField = webViewClass
                .getDeclaredField("mZoomManager");
        mZoomManagerField.setAccessible(true);
        Object mZoomManagerInstance = mZoomManagerField.get(this);

        Class<?> zoomManagerClass;
        try {
            zoomManagerClass = Class.forName("android.webkit.ZoomManager");
            Field mInitialScale = zoomManagerClass
                    .getDeclaredField("mInitialScale");
            mInitialScale.setAccessible(true);
            mInitialScale.set(mZoomManagerInstance, temp_scale);

            Field mActualScale = zoomManagerClass
                    .getDeclaredField("mActualScale");
            mActualScale.setAccessible(true);
            if (temp_scale >=1) {
                mActualScale.set(mZoomManagerInstance, temp_scale);
            } else {
                Field mDefaultScale = zoomManagerClass
                        .getDeclaredField("mDefaultScale");
                mDefaultScale.setAccessible(true);
                Object obj=temp_scale;
                mDefaultScale.set(mZoomManagerInstance, obj);
                mActualScale.set(mZoomManagerInstance, temp_scale);
            }

            Field mInvActualScale = zoomManagerClass
                    .getDeclaredField("mInvActualScale");
            mInvActualScale.setAccessible(true);
            mInvActualScale.set(mZoomManagerInstance, 1 / temp_scale);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

}
</code>```

答:
After researching for three days I wasn't able to find any solution as I had to give support from android level 8 to 23.

So i came up with using

```<code>dependentWebView.setInitialScale(mainWebView.getScale()*100);
</code>```

and loading the dependentWebView Again.

The scaling in this case is not perfect. I tried overriding setInitialScale to give it a float value for more accuracy but couldn't do it as scaling is handled differently in different android versions.

Posting this solution so someone else might get help.

ContentLicense: CC BY-SA 3.0

Body:
Actually I have two webviews and I want to zoom/pan other webview based on first webview. For this the application already uses the following code that works fine upto android 3.0 but on later devices it doesnt work. I checked and Exception is thrown i - e Field Not Found exception for mZoomManager.

I'd like to know any alternative for zooming the webview? Can't use webView.setInitialScale();

public void setScale(float scale_factor) throws IllegalArgumentException,
        IllegalAccessException, ClassNotFoundException {
    try {
        float temp_scale = scale_factor * 0.01f;
        Class<WebView> webViewClass = (Class<WebView>) this.getClass()
                .getSuperclass();
        Field mZoomManagerField = webViewClass
                .getDeclaredField("mZoomManager");
        mZoomManagerField.setAccessible(true);
        Object mZoomManagerInstance = mZoomManagerField.get(this);

        Class<?> zoomManagerClass;
        try {
            zoomManagerClass = Class.forName("android.webkit.ZoomManager");
            Field mInitialScale = zoomManagerClass
                    .getDeclaredField("mInitialScale");
            mInitialScale.setAccessible(true);
            mInitialScale.set(mZoomManagerInstance, temp_scale);

            Field mActualScale = zoomManagerClass
                    .getDeclaredField("mActualScale");
            mActualScale.setAccessible(true);
            if (temp_scale >=1) {
                mActualScale.set(mZoomManagerInstance, temp_scale);
            } else {
                Field mDefaultScale = zoomManagerClass
                        .getDeclaredField("mDefaultScale");
                mDefaultScale.setAccessible(true);
                Object obj=temp_scale;
                mDefaultScale.set(mZoomManagerInstance, obj);
                mActualScale.set(mZoomManagerInstance, temp_scale);
            }

            Field mInvActualScale = zoomManagerClass
                    .getDeclaredField("mInvActualScale");
            mInvActualScale.setAccessible(true);
            mInvActualScale.set(mZoomManagerInstance, 1 / temp_scale);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

}

Body:
After researching for three days I wasn't able to find any solution as I had to give support from android level 8 to 23.

So i came up with using

dependentWebView.setInitialScale(mainWebView.getScale()*100);

and loading the dependentWebView Again.

The scaling in this case is not perfect. I tried overriding setInitialScale to give it a float value for more accuracy but couldn't do it as scaling is handled differently in different android versions.

Posting this solution so someone else might get help.


问:
"Uncaught EXCEPTION" in view binding brings down entire Angular 2 app
My template contains an expression that produces an exception:

```<code><h1>Foo: {{model.somebodyForgotToInitializeMe.foo}}</h1>
</code>```

An error the model produces the following output on the console:

```<code>Uncaught EXCEPTION: TypeError: Cannot read property 'foo' of null in [
                {{model.somebodyForgotToInitializeMe.foo}}
             in SomeView@21:73]
</code>```

That's not surprising. What is surprising is that this error brings down the entire Angular 2 application. Nothing else in the app responds after this has happened.

Is there a global exception handler I need to installed to prevent an error in a single binding expression killing my entire app?

This is a large medical application worked on by alot of developers. An exception in a UI component shouldn't take down the entire application.

答:
I have one hack

Foo: {{(model.somebodyForgotToInitializeMe || {}).foo}}

We use OR here when the variable is not available it used {} (blank object).

Body:
My template contains an expression that produces an exception:

Foo: {{model.somebodyForgotToInitializeMe.foo}}

An error the model produces the following output on the console:

Uncaught EXCEPTION: TypeError: Cannot read property 'foo' of null in [
                {{model.somebodyForgotToInitializeMe.foo}}
             in SomeView@21:73]

That's not surprising. What is surprising is that this error brings down the entire Angular 2 application. Nothing else in the app responds after this has happened.

Is there a global exception handler I need to installed to prevent an error in a single binding expression killing my entire app?

This is a large medical application worked on by alot of developers. An exception in a UI component shouldn't take down the entire application.

Body:
I have one hack
<h1>Foo: {{(model.somebodyForgotToInitializeMe || {}).foo}}</h1>
We use OR here when the variable is not available it used {} (blank object).


问:
Is it possible to wrap a C# singleton in an interface?
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.

But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?

答:
Interfaces can not have instances in C#, I think you only need to:

Implement the singleton pattern (yes, you'll need a static attribute or method to get the  instance, but everything else does not require to be static)

On the other hand, your singleton can implement an interface if you want, just remember that other classes can also implement that same interface

ContentLicense: CC BY-SA 2.5


问:
how to reduce number of condition checks when I select one/two/three/four/five/six from the 6 select options?
Example: When I have only two select options

```<code>input_one = 'one';
input_two = 'two';
</code>```

when I select only input_one

```<code>if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}
</code>```

When I select only input_two

```<code>elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}
</code>```

When I don't select any of those

```<code>elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

When I select both of them

```<code>elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?

答:
I will give my answer based on the hypothesis, that the inputs are dependent on each other. Or let's call it interdependent.

If you are looking at your code, you'll notice that your conditions can be abstracted by basic binary calculations.

So let's assume we speak about two states:

```<code>isset = 1,
!isset = 0
</code>```

And each input can have one of the two states.

If you have 1 input, then you can have 2exp(1) = 2 possibilities.

```<code>0
1
</code>```

If you have 2 inputs, then you can have 2exp(2) = 4 possibilities. Nota bene: each column represents the states that an input can take in dependence with the other one.

```<code>00
01
10
11
</code>```

If you have 3 inputs, then you can have 2exp(3) = 8 possibilities.

```<code>000
001
010
011
100
101
110
111
</code>```

...

If you have 6 inputs, then you can have 2exp(6) = 64 states in total.

```<code>000000
000001
...
111110
111111
</code>```

The general formula is:

```<code>N = 2exp(x)

Where:
N = total number of possibilities;
x: Number of observable elements, each can achieve 2 states (0 or 1).
</code>```

So, as you see, it's hard to maintain such a structure.
And take into consideration that you'll probably need to make validations on empty() values too. At least.

I recommend you, that you really change something in your code, so that your inputs are not anymore so dependable on each other.

So, my answer would be "no", there is no way to do it, better than you already do it. The if-elseif-else is the proper one. But that doesn't help you a lot if you have more than, let's say 3 interdependent inputs.

EDIT 1:

One relative maintainable solution would be to divide the interdependent inputs in groups of maximum 3. And only for these 3 to send a request to the server.

EDIT 2:

Or to ensure that in one request moment, only one input has been set or have a value.

Or to ensure that each of the inputs have at least a default value (like '0') on the request moment.

Body:
Example: When I have only two select options

input_one = 'one';
input_two = 'two';

when I select only input_one

if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}

When I select only input_two

elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}

When I don't select any of those

elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

When I select both of them

elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?

Body:
I will give my answer based on the hypothesis, that the inputs are dependent on each other. Or let's call it interdependent.

If you are looking at your code, you'll notice that your conditions can be abstracted by basic binary calculations.

So let's assume we speak about two states:

isset = 1,
!isset = 0

And each input can have one of the two states.

If you have 1 input, then you can have 2exp(1) = 2 possibilities.

0
1

If you have 2 inputs, then you can have 2exp(2) = 4 possibilities. Nota bene: each column represents the states that an input can take in dependence with the other one.

00
01
10
11

If you have 3 inputs, then you can have 2exp(3) = 8 possibilities.

000
001
010
011
100
101
110
111

...

If you have 6 inputs, then you can have 2exp(6) = 64 states in total.

000000
000001
...
111110
111111

The general formula is:

N = 2exp(x)

Where:
N = total number of possibilities;
x: Number of observable elements, each can achieve 2 states (0 or 1).

So, as you see, it's hard to maintain such a structure.
And take into consideration that you'll probably need to make validations on empty() values too. At least.

I recommend you, that you really change something in your code, so that your inputs are not anymore so dependable on each other.

So, my answer would be "no", there is no way to do it, better than you already do it. The if-elseif-else is the proper one. But that doesn't help you a lot if you have more than, let's say 3 interdependent inputs.

EDIT 1:

One relative maintainable solution would be to divide the interdependent inputs in groups of maximum 3. And only for these 3 to send a request to the server.

EDIT 2:

Or to ensure that in one request moment, only one input has been set or have a value.

Or to ensure that each of the inputs have at least a default value (like '0') on the request moment.


问:
show div after scrolling in mobile devices
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

```<code>$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}
</code>```

can somebody help me to fix this problem.

thank you

答:
Please try this one,</p>

```<code>$(function(){
   $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();
        if(scroll >= 150){
            phonebox.show();
        }else{
            phonebox.hide();
        }
    });
});
</code>```

Body:
i want show a div after scrolling 150px just in mobile devices.
this is my code but it doesnt work :

$(document).load($(window).bind("resize", checkPosition));
var phonebox = $(".phonebox");
function checkPosition()
{
    if($(window).width() < 460)
    {
      $(window).scroll(function() {
        if ($(window).scrollTop() > 100) {
       phonebox.show();
      }
    else {
       phonebox.hide();
    }
});
    }
}

can somebody help me to fix this problem.

thank you

Body:
Please try this one,

$(function(){
   $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();
        if(scroll >= 150){
            phonebox.show();
        }else{
            phonebox.hide();
        }
    });
});


问:
How to do transclusion md-menu items into Material md-menu
How to include menu-items into child components

See example:

dropdown.component.html

```<code><div class="dropdown">
    <button md-icon-button
            [mdMenuTriggerFor]="dropMenu">
        <i class="glyphicon glyph-more"></i>
    </button>
</div>
<md-menu #navMenu="dropMenu" [overlapTrigger]="false">
    <ng-content></ng-content>
    <!-- after rendering I'm able to see all buttons,
         and interact with them my mouse click.
         But they not accessible with keyboard -->
</md-menu>
</code>```

header.component.html

```<code><div class="header">
  ...
  <dropdown>
    <button md-menu-item>Button 1</button>
    <button md-menu-item>Button 2</button>
    <button md-menu-item>Button 3</button>
  </dropdown>
  ...
</div>
</code>```

It works, but not as expected.

I can see that items, and menu working by click, but I'm unable to use keyboard for items access.
Also in dropdown.component.ts if I get access to MdMenu component via @ViewChild('navMenu') it shows me 0 items

this.mdMenu.items // 0

答:
MdMenu directive uses @ContentChildren to get list of MdMenuItem.

```<code>@ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

ngAfterContentInit() {
  this._keyManager = new FocusKeyManager(this.items).withWrap();
  this._tabSubscription = this._keyManager.tabOut.subscribe(() => this._emitCloseEvent());
}
</code>```

As ContentChildren works only for the component-owner of template your menu directive will always have 0 items.

Workaround could be as follows

dropdown.component.ts

```<code>...
export class DropDownComponent {
  @ViewChild(MdMenu) menu: MdMenu;

  @ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

  ngAfterViewInit() {
    this.menu.items = this.items;
    this.menu.ngAfterContentInit();
  }
}
</code>```

Plunker Example

See also

https://github.com/angular/angular/issues/8937

https://github.com/angular/angular/issues/16299

Body:
How to include menu-items into child components

See example:

dropdown.component.html

    <button md-icon-button
            [mdMenuTriggerFor]="dropMenu">

    </button>

<md-menu #navMenu="dropMenu" [overlapTrigger]="false">
    <ng-content></ng-content>

</md-menu>

header.component.html

  ...
  <dropdown>
    <button md-menu-item>Button 1</button>
    <button md-menu-item>Button 2</button>
    <button md-menu-item>Button 3</button>
  </dropdown>
  ...

It works, but not as expected.

I can see that items, and menu working by click, but I'm unable to use keyboard for items access.
Also in dropdown.component.ts if I get access to MdMenu component via @ViewChild('navMenu') it shows me 0 items

this.mdMenu.items // 0

Body:
MdMenu directive uses @ContentChildren to get list of MdMenuItem.

@ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

ngAfterContentInit() {
  this._keyManager = new FocusKeyManager(this.items).withWrap();
  this._tabSubscription = this._keyManager.tabOut.subscribe(() => this._emitCloseEvent());
}

As ContentChildren works only for the component-owner of template your menu directive will always have 0 items.

Workaround could be as follows

dropdown.component.ts

...
export class DropDownComponent {
  @ViewChild(MdMenu) menu: MdMenu;

  @ContentChildren(MdMenuItem) items: QueryList<MdMenuItem>;

  ngAfterViewInit() {
    this.menu.items = this.items;
    this.menu.ngAfterContentInit();
  }
}

Plunker Example

See also

https://github.com/angular/angular/issues/8937

https://github.com/angular/angular/issues/16299


问:
how to achieve synchronization of threads using synchronized method in java?
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

```<code>class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}
</code>```

Current Output :

```<code>        [Hello [Synchronized [World] ] ] ]
</code>```

Desired Output :

```<code>        [Hello]
        [Synchronized]
        [World]
</code>```

答:
When you synchronize on an instance method:

```<code>class ABC
{
    synchronized public void meth(String msg)
    { ... }
}
</code>```

this is the same as:

```<code>class ABC
{
    public void meth(String msg) {
        synchronized (this) { ... }
    }
}
</code>```

i.e. the monitor you're acquiring is the instance of that class. But you're creating 3 separate instances (each thread calls new ABC()), and acquiring the monitor on each of them separately, so the synchronization is effectively a no-op.

You need to synchronize on a common object. For example:

```<code>class ABC
{
    public void meth(String msg) {
        synchronized (ABC.class) { ... }
    }
}
</code>```

In general, synchronizing on a class is ill-advised, though, because any code anywhere in your program can acquire that monitor, so you might get unexpected contention.

Instead, pass in a lock object:

```<code>class ABC
{
    private final Object lock;

    ABC(Object lock) { this.lock = lock; }

    public void meth(String msg) {
        synchronized (lock) { ... }
    }
}
</code>```

and pass the same lock to all ABC instances that you want to be synchronized.

But rather than doing this, as urag points out in his/her answer, you can pass the same instance of ABC to all of your threads, rather than creating a new instance in each SyncMethod. Sometimes the simplest solutions just escape me when I'm writing an answer ;)

Body:
i am unable to achieve synchronization of thread here .i used a synchronized method "meth" her . so according to definition only one thread should enter at a single time and print my desired output . but this is not happening . Need help. Thank you.

class ABC {

    synchronized public void meth(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + " Thread Interrupted");
        }
        System.out.println("]");
    }
}

class SyncMethod implements Runnable {

    ABC a = new ABC();
    Thread t;

    SyncMethod(String s) {
        t = new Thread(this, s);
        t.start();
    }

    public void run() {
        a.meth(t.getName());
    }

    public static void main(String args[]) {
        new SyncMethod("Hello");
        new SyncMethod("Synchronized");
        new SyncMethod("World");
    }
}

Current Output :

        [Hello [Synchronized [World] ] ] ]

Desired Output :

        [Hello]
        [Synchronized]
        [World]

Body:
When you synchronize on an instance method:

class ABC
{
    synchronized public void meth(String msg)
    { ... }
}

this is the same as:

class ABC
{
    public void meth(String msg) {
        synchronized (this) { ... }
    }
}

i.e. the monitor you're acquiring is the instance of that class. But you're creating 3 separate instances (each thread calls new ABC()), and acquiring the monitor on each of them separately, so the synchronization is effectively a no-op.

You need to synchronize on a common object. For example:

class ABC
{
    public void meth(String msg) {
        synchronized (ABC.class) { ... }
    }
}

In general, synchronizing on a class is ill-advised, though, because any code anywhere in your program can acquire that monitor, so you might get unexpected contention.

Instead, pass in a lock object:

class ABC
{
    private final Object lock;

    ABC(Object lock) { this.lock = lock; }

    public void meth(String msg) {
        synchronized (lock) { ... }
    }
}

and pass the same lock to all ABC instances that you want to be synchronized.

But rather than doing this, as urag points out in his/her answer, you can pass the same instance of ABC to all of your threads, rather than creating a new instance in each SyncMethod. Sometimes the simplest solutions just escape me when I'm writing an answer ;)


问:
How get numbers from string (C#)
I have the following string:

```<code>{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}
</code>```

I need to get as result an array of numbers:

5

19

34

I can't find the necessary regex expression for this action.
Thanks for help in advance.

答:
Here you go:

```<code>string input = "{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}";
Regex regex = new Regex(@"(\d+)");
List<int> numbers = new List<int>();

var matches = regex.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
    numbers.Add(Int32.Parse(matches[i].Value));
}
</code>```

If you insist on arrays use this instead:

```<code>var matches = regex.Matches(input);
int[] numbers = new int[matches.Count];

for (int i = 0; i < matches.Count; i++)
{
    numbers[i] = Int32.Parse(matches[i].Value);
}
</code>```

Title: How get numbers from string (C#)

Body:
I have the following string:

{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}

I need to get as result an array of numbers:

5

19

34

I can't find the necessary regex expression for this action.
Thanks for help in advance.

Body:
Here you go:

string input = "{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}";
Regex regex = new Regex(@"(\d+)");
List<int> numbers = new List<int>();

var matches = regex.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
    numbers.Add(Int32.Parse(matches[i].Value));
}

If you insist on arrays use this instead:

var matches = regex.Matches(input);
int[] numbers = new int[matches.Count];

for (int i = 0; i < matches.Count; i++)
{
    numbers[i] = Int32.Parse(matches[i].Value);
}


问:
CSS organization chart line connectors issue
How do I give space between each li with out disturbing line connectors. I applied margin-top:20px but this space affecting to connecting lines also.
How can I add more space between the li and also have the same applied on the line connectors?

JSFIDDLE DEMO

.mobile,
.mobile ul,
.mobile li {
  position: relative;
}

.mobile ul {
  list-style: none;
  padding-left: 32px;
}

.mobile li::before,
.mobile li::after {
  content: "";
  position: absolute;
  left: -12px;
}

.mobile li::before {
  border-top: 3px solid #94a0b4;
  top: 9px;
  width: 12px;
  height: 0;
}

.mobile li::after {
  border-left: 3px solid #003B46;
  height: 100%;
  width: 0px;
  top: 2px;
}

.mobile ul>li:last-child::after {
  height: 8px;
}

.mobile #ulCollapse {
  width: 320px !important;
}

.mobile li .emplist {
  border: 1px solid #003B46;
  border-radius: 5px;
  width: 30%;
  height: 35px;
  transition: background-color 0.5s ease;
}

.mobile ul li .emplist:hover {
  background-color: #003B46;
  color: #fff;
}

.mobile li .emplist:hover~ul li .emplist {
  background-color: #07575b;
  color: #fff;
  border: 1px solid #003B46;
  border-radius: 5px;
}

/*Connector styles on hover*/

.mobile li .emplist:hover~ul li::after,
.mobile li .emplist:hover~ul li::before,
.mobile li .emplist:hover~ul::before,
.mobile li .emplist:hover~ul ul::before {
  border-color: #003B46;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mobile">
  <ul id="ulCollapse">
    <li>
      <div class="emplist">
        Parent 1
      </div>
      <ul>
        <li>
          <div class="emplist">
            child 1.1

          </div>
        </li>
        <li>
          <div class="emplist">
            child 1.2</div>
        </li>
      </ul>
    </li>
  </ul>

</div></code>```

答:
change some css & HTML

```<code>.mobile,
        .mobile ul,
        .mobile li {
          position: relative;
        }

        .mobile ul {
          list-style: none;
          padding-left: 32px;
        }

        .mobile li::before,
        .mobile li::after {
          content: "";
          position: absolute;
          left: -12px;
        }

        .mobile li::before {
          border-top: 3px solid #94a0b4;
          top: 25px;
          width: 12px;
          height: 0;
          left:-12px;
        }

        .mobile li::after {
          border-left: 3px solid #003B46;
          height: 100%;
          width: 0px;
          top: 2px;
        }

        .mobile ul > li:last-child::after {
          height: 26px;
        }

        .mobile #ulCollapse {
          width: 320px !important;
        }
        .mobile li .emplist{padding-top:10px;}
        .mobile li .emplist .inner{
          border: 1px solid #003B46;
          border-radius: 5px;
          width: 30%;
          height: 35px;
          transition: background-color 0.5s ease;
        }

        .mobile ul li .emplist .inner:hover {
          background-color: #003B46;
          color: #fff;
        }

        .mobile li .emplist .inner:hover ~ ul li .emplist {
          background-color: #07575b;
          color: #fff;
          border: 1px solid #003B46;
          border-radius: 5px;
        }

        /*Connector styles on hover*/

        .mobile li .emplist:hover ~ ul li::after,
        .mobile li .emplist:hover ~ ul li::before,
        .mobile li .emplist:hover ~ ul::before,
        .mobile li .emplist:hover ~ ul ul::before {
          border-color: #003B46;
        }

    <div class="mobile">
      <ul id="ulCollapse">
        <li>
          <div class="emplist">
          <div class="inner">

            Parent 1

          </div>
          </div>
          <ul>
            <li>
              <div class="emplist">
               <div class="inner">

                child 1.1
     </div>
              </div>
            </li>
            <li>
              <div class="emplist">
                <div class="inner">
                child 1.2</div>
                </div>
            </li>
          </ul>
        </li>
      </ul>

    </div>
</code>```

https://jsfiddle.net/zmsL4cxc/5/

Body:
How do I give space between each li with out disturbing line connectors. I applied margin-top:20px but this space affecting to connecting lines also.
How can I add more space between the li and also have the same applied on the line connectors?

JSFIDDLE DEMO

.mobile,
.mobile ul,
.mobile li {
  position: relative;
}

.mobile ul {
  list-style: none;
  padding-left: 32px;
}

.mobile li::before,
.mobile li::after {
  content: "";
  position: absolute;
  left: -12px;
}

.mobile li::before {
  border-top: 3px solid #94a0b4;
  top: 9px;
  width: 12px;
  height: 0;
}

.mobile li::after {
  border-left: 3px solid #003B46;
  height: 100%;
  width: 0px;
  top: 2px;
}

.mobile ul>li:last-child::after {
  height: 8px;
}

.mobile #ulCollapse {
  width: 320px !important;
}

.mobile li .emplist {
  border: 1px solid #003B46;
  border-radius: 5px;
  width: 30%;
  height: 35px;
  transition: background-color 0.5s ease;
}

.mobile ul li .emplist:hover {
  background-color: #003B46;
  color: #fff;
}

.mobile li .emplist:hover~ul li .emplist {
  background-color: #07575b;
  color: #fff;
  border: 1px solid #003B46;
  border-radius: 5px;
}

/*Connector styles on hover*/

.mobile li .emplist:hover~ul li::after,
.mobile li .emplist:hover~ul li::before,
.mobile li .emplist:hover~ul::before,
.mobile li .emplist:hover~ul ul::before {
  border-color: #003B46;
}

        Parent 1

            child 1.1

            child 1.2

Body:
change some css & HTML

.mobile,
        .mobile ul,
        .mobile li {
          position: relative;
        }

        .mobile ul {
          list-style: none;
          padding-left: 32px;
        }

        .mobile li::before,
        .mobile li::after {
          content: "";
          position: absolute;
          left: -12px;
        }

        .mobile li::before {
          border-top: 3px solid #94a0b4;
          top: 25px;
          width: 12px;
          height: 0;
          left:-12px;
        }

        .mobile li::after {
          border-left: 3px solid #003B46;
          height: 100%;
          width: 0px;
          top: 2px;
        }

        .mobile ul > li:last-child::after {
          height: 26px;
        }

        .mobile #ulCollapse {
          width: 320px !important;
        }
        .mobile li .emplist{padding-top:10px;}
        .mobile li .emplist .inner{
          border: 1px solid #003B46;
          border-radius: 5px;
          width: 30%;
          height: 35px;
          transition: background-color 0.5s ease;
        }

        .mobile ul li .emplist .inner:hover {
          background-color: #003B46;
          color: #fff;
        }

        .mobile li .emplist .inner:hover ~ ul li .emplist {
          background-color: #07575b;
          color: #fff;
          border: 1px solid #003B46;
          border-radius: 5px;
        }

        /*Connector styles on hover*/

        .mobile li .emplist:hover ~ ul li::after,
        .mobile li .emplist:hover ~ ul li::before,
        .mobile li .emplist:hover ~ ul::before,
        .mobile li .emplist:hover ~ ul ul::before {
          border-color: #003B46;
        }

    <div class="mobile">
      <ul id="ulCollapse">
        <li>
          <div class="emplist">
          <div class="inner">

            Parent 1

          </div>
          </div>
          <ul>
            <li>
              <div class="emplist">
               <div class="inner">

                child 1.1
     </div>
              </div>
            </li>
            <li>
              <div class="emplist">
                <div class="inner">
                child 1.2</div>
                </div>
            </li>
          </ul>
        </li>
      </ul>

    </div>

https://jsfiddle.net/zmsL4cxc/5/


问:
Retrofit2 and RxJava2 : How to detect the network error
I'm using Retofit2 and RxJava2 to fetch data from API. I am using the following code

```<code>Observable<Recipe> recipeObservable = getDataManager().getRecipes(String.valueOf(page));

        recipeObservable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Recipe>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Recipe recipe) {

                        getMvpView().updateRecipeList(recipe.getResults());
                        ++page;
                        //getMvpView().hideLoading();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        if (e instanceof HttpException)
                            Timber.d("Network Error");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
</code>```

But the problem is Timber.d("Network Error"); never gets executed. I looked on various websites but could not solve the problem. I'm use to Retrofit2 but not fimiliar with RxJava2. So Please help. If more information is required please ask, I'll post it.

答: HttpException is not related to network failures. IOException is what you are looking for.</p>

Body:
I'm using Retofit2 and RxJava2 to fetch data from API. I am using the following code

Observable<Recipe> recipeObservable = getDataManager().getRecipes(String.valueOf(page));

        recipeObservable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Recipe>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Recipe recipe) {

                        getMvpView().updateRecipeList(recipe.getResults());
                        ++page;
                        //getMvpView().hideLoading();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        if (e instanceof HttpException)
                            Timber.d("Network Error");
                    }

                    @Override
                    public void onComplete() {

                    }
                });

But the problem is Timber.d("Network Error"); never gets executed. I looked on various websites but could not solve the problem. I'm use to Retrofit2 but not fimiliar with RxJava2. So Please help. If more information is required please ask, I'll post it.


问:
SAXParseException: Unexpected token when trying to parse remote XML on Android
I am trying to parse an XML from the internet and display some of its data in a simple TextView. Here is my code:

```<code>    public class MainActivity extends AppCompatActivity {

    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1=(TextView)findViewById(R.id.textView1);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {

            String UTF8 = "utf-8";
            URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml");
            URLConnection urlConnection = url.openConnection();
            //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            //InputStream in = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml").openStream();
            //getAssets().open("file.xml");
            InputStream in = url.openStream();

            //InputStream is2 = new FileInputStream(file);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            //Document doc = dBuilder.parse(new InputSource(new InputStreamReader(in, "UTF-8")));
            Document doc = dBuilder.parse(in, "UTF-8");
            //Document doc = dBuilder.parse(in);

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("allergyForecast");

            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    tv1.setText(getValue("Day0", element2));
                }
            }

        } catch (Exception e) {e.printStackTrace();}

    }

    private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }
}
</code>```

This code works as intended when I run it on a local file (one of those commended out InputStreams is for a local file) but when I try to run it on the XML file from the internet, I get the following error:

```<code>07-04 12:58:06.550 23289-23289/mystikos.pollentest W/System.err: org.xml.sax.SAXParseException: Unexpected token (position:TEXT {"allergyForecas...@1:990 in java.io.InputStreamReader@2ff0997)
</code>```

Based on some research it seems like the parser can't tell what type of encoding the XML file has, so I need to define it. However, I am not sure how to define it here... my attempts at defining "UTF-8" encoding are visible in commented out lines, but those did not work. Any suggestions?

XML: http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml

Thank you!

答:
Data that You get in response is in json, not in xml. Prefix .xml in your url is not take data in xml when you get inputStream from UrlOpenConnection, and can be removed.
To see the data that you got:

```<code>        String data = "";
        while (in.available() > 0)
            data += (char)in.read();
        System.out.println(data);
</code>```

Result is : {"allergyForecast":{"Day0":4.1,"Day1":3.7,"Day2":4.6,"Day3":1.4,"Day4":2.9," ... }

To parse date you can use Gson for example. Code snippet to parse element:

```<code>        JsonElement jelement = new JsonParser().parse(new InputStreamReader(in));
     // or from readed from inputStream string:
     // JsonElement jelement = new JsonParser().parse(data);
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("allergyForecast");
</code>```

And than you can get required values from jsonObject.
Or you can check API how to get response in xml if you need only xml.

Body:
I am trying to parse an XML from the internet and display some of its data in a simple TextView. Here is my code:

    public class MainActivity extends AppCompatActivity {

    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1=(TextView)findViewById(R.id.textView1);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        try {

            String UTF8 = "utf-8";
            URL url = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml");
            URLConnection urlConnection = url.openConnection();
            //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            //BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
            //InputStream in = new URL("http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml").openStream();
            //getAssets().open("file.xml");
            InputStream in = url.openStream();

            //InputStream is2 = new FileInputStream(file);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            //Document doc = dBuilder.parse(new InputSource(new InputStreamReader(in, "UTF-8")));
            Document doc = dBuilder.parse(in, "UTF-8");
            //Document doc = dBuilder.parse(in);

            Element element = doc.getDocumentElement();
            element.normalize();

            NodeList nList = doc.getElementsByTagName("allergyForecast");

            for (int i=0; i<nList.getLength(); i++) {

                Node node = nList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element2 = (Element) node;
                    tv1.setText(getValue("Day0", element2));
                }
            }

        } catch (Exception e) {e.printStackTrace();}

    }

    private static String getValue(String tag, Element element) {
        NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }
}

This code works as intended when I run it on a local file (one of those commended out InputStreams is for a local file) but when I try to run it on the XML file from the internet, I get the following error:

07-04 12:58:06.550 23289-23289/mystikos.pollentest W/System.err: org.xml.sax.SAXParseException: Unexpected token (position:TEXT {"allergyForecas...@1:990 in java.io.InputStreamReader@2ff0997)

Based on some research it seems like the parser can't tell what type of encoding the XML file has, so I need to define it. However, I am not sure how to define it here... my attempts at defining "UTF-8" encoding are visible in commented out lines, but those did not work. Any suggestions?

XML: http://pollenapps.com/AllergyAlertWebSVC/api/1.0/Forecast/ForecastForZipCode?Zipcode=02145&Affiliateid=9642&AppID=2.1.0&uid=6693636764.xml

Thank you!

Body:
Data that You get in response is in json, not in xml. Prefix .xml in your url is not take data in xml when you get inputStream from UrlOpenConnection, and can be removed.
To see the data that you got:

        String data = "";
        while (in.available() > 0)
            data += (char)in.read();
        System.out.println(data);

Result is : {"allergyForecast":{"Day0":4.1,"Day1":3.7,"Day2":4.6,"Day3":1.4,"Day4":2.9," ... }

To parse date you can use Gson for example. Code snippet to parse element:

        JsonElement jelement = new JsonParser().parse(new InputStreamReader(in));
     // or from readed from inputStream string:
     // JsonElement jelement = new JsonParser().parse(data);
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("allergyForecast");

And than you can get required values from jsonObject.
Or you can check API how to get response in xml if you need only xml.


问:
Why can't I create an OData service?
My machine has VS 2010 Premium installed and I'm having a bit of trouble with item templates.

I'm wanting to follow along with a simple MSDN Tutorial to build an OData service so I can learn about them. It says I need to create an ASP.Net application, which I did. Next it says to add an "ADO.NET Entity Data Model" item, which I don't have available in my item templates.

Even worse, there is no "WCF Data Service" which is kind of crucial for this exercise. What am I missing? Is there some type of SDK or other download that installs OData/WCF Data Service components and templates?

Update

I looked at the install logs for ADO.Net Entity Framework Tools and it appears that it installed all the templates into an old VS 2010 *express edition folder. I no longer have that installed, is there a tool or a method to remove any traces of express so the installer will deploy files to the premium edition I have installed?

答:
Problem Source: ADO.Net Entity Framework Tools must have been installed with VS 2010 Express which was installed before Premium. When I uninstalled Express it must have kept ADO.Net EF tools and it's references to Express. This is what I did to fix it:

Uninstalled "Microsoft Visual Studio 2010 ADO.NET Entity Framework Tools" from Control Panel

On the VS 2010 Setup disc, navigated to \WCU\EFTools with the command line

Used msiexec: msiexec /i ADONETEntityFrameworkTools_enu.msi USING_EXUIH=1 to install by itself (VS 2010 maintenance mode wouldn't install it again after I removed it)

Now I have all the appropriate templates to create OData services :)

Title: Why can't I create an OData service?


问:
Volley Timeout Error
I am trying to hit a rest service using Volley.

```<code>public class AuthFunctions {
    private static final String LOGIN_URL = "http://10.0.2.2:8080/stewayservices/user-management/users/10";
    boolean result;
    public boolean loginUser(String email,String password){

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,LOGIN_URL,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("JsonObject Response",response.toString());
                try {
                    JSONObject user = response.getJSONObject("user");
                    String firstName = user.getString("firstName");
                    if (firstName.equals("Lokesh")){
                        result = true;
                    }
                    else{
                        result = false;
                    }
                } catch (JSONException e) {
                    Log.d("Web Service Error",e.getMessage());
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("JsonObject Error Response",volleyError.toString());
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(500000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(request);
        return result;
    }
}
</code>```

But it is giving me the Volley Timeout error. Below is the Logcat

```<code> D/JsonObject Error Response﹕ com.android.volley.TimeoutError
</code>```

Please let me know know if I am doing it wrong. This is my first question in stackoverflow regarding Android.

答:
Volley throws timeouterror when it couldn't connect to the url provided in request. reasons could be:

1)connectivity.
2)Url is not valid.

Try running it on emulator.It should work on emulator as emualator runs on same machine and has same ip as your wamp running on.

To make it work on real device connect your device to same WLAN as your wampserver is running on. If not connected to same WLAN you have to host your php scripts to web. To do this there are many free web hosting sites like https://www.000webhost.com/ are available check them out.

Hope this help!

Title: Volley Timeout Error

Body:
I am trying to hit a rest service using Volley.

public class AuthFunctions {
    private static final String LOGIN_URL = "http://10.0.2.2:8080/stewayservices/user-management/users/10";
    boolean result;
    public boolean loginUser(String email,String password){

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,LOGIN_URL,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("JsonObject Response",response.toString());
                try {
                    JSONObject user = response.getJSONObject("user");
                    String firstName = user.getString("firstName");
                    if (firstName.equals("Lokesh")){
                        result = true;
                    }
                    else{
                        result = false;
                    }
                } catch (JSONException e) {
                    Log.d("Web Service Error",e.getMessage());
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("JsonObject Error Response",volleyError.toString());
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(500000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(request);
        return result;
    }
}

But it is giving me the Volley Timeout error. Below is the Logcat

 D/JsonObject Error Response﹕ com.android.volley.TimeoutError

Please let me know know if I am doing it wrong. This is my first question in stackoverflow regarding Android.


问:
How to change the redirect url when logging out?
I'm working with Laravel 5 authentification system provided by default.
After logging out, a user is redirected to the root page but I'd like to change that.
I managed to do it for the "login" and "registering" process by defining "$redirectTo" in "AuthController.php". But for "logout", I defined "$redirectAfterLogout" at the same place but it seems to not be taken into account.

Could anyone explain me where is the problem and how to fix it please?
Thanks a lot.

答:
it'only laravel versi 5.4 if you want custom redirect url logout,
open <code>/your-project-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php</code>
and edit redirect based on you needed </p>

```<code>  public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/login');
    }
</code>```

Body:
it'only laravel versi 5.4 if you want custom redirect url logout,
open /your-project-laravel/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
and edit redirect based on you needed

  public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->flush();

        $request->session()->regenerate();

        return redirect('/login');
    }


问:
Is XMPP fast enough for MMO-like collaboration?
I'm looking to create an architecture for my dissertation that will combine IM features (chat messages + rosters) with collaboration (file transfer, simultaneous editing and collaborative drawing).

The clients will be a mixture of iPhone (and possibly Android) and desktop apps.

The list of technologies I've looked at is almost too long to mention, but I've narrowed it down to the MQ-like RedDwarf/Project Darkstar or XMPP with an OpenFire server.

The problem is, XMPP seems ideal for the IM functions but the overhead of XML seems to me like it might be an issue when communicating the touches on a screen involved in drawing over, say a 3G connection. Conversely, the binary messages of RedDwarf (or ZeroMQ/RabbitMQ etc) seem very fast but lack some of the higher level features of XMPP.

The question for me is, has anyone had experience using XMPP in this way (I'm aware Google Wave use(d) Google's variant of XMPP so perhaps it is), and is it efficient enough to  send hundreds of small messages from a mobile device?

答:
XMPP is fast, but parsing xml does take some more cpu power than a binary format. However it is much easier to user/debug than binary protocols.

Your server is not going to be limited unless there are thousands of devices communicating at the same time, so the bottleneck will probably be your mobile device parsing and creating xml stanzas.

XMPP can also be a drain on your mobile battery life if there are lots of friends connecting/disconnecting (resulting in presence updates to be processed). That might also be something to consider.

ContentLicense: CC BY-SA 4.0


问:
How to add keys and values from two dictionaries to third without mixing between them?
I have two dictionaries and I want to add their content to third dictionary naturally without mixing their between them.</p>

```<code>a = {'life':'1','arts':'2'}
b = {'technology':'3', 'culture':'4'}
c = {} # here must be keys and values of the `a` and `b` dicts
</code>```

答:
Maybe you can try to use zip keyword

```<code>a = {'life':'1','arts':'2'}
b = {'technology':'3', 'culture':'4'}
for q, s in zip(a, b):
    print(q, a[q])
    print(s, b[s])
</code>```

Body:
I have two dictionaries and I want to add their content to third dictionary naturally without mixing their between them.

a = {'life':'1','arts':'2'}
b = {'technology':'3', 'culture':'4'}
c = {} # here must be keys and values of the `a` and `b` dicts

Body:
Maybe you can try to use zip keyword

a = {'life':'1','arts':'2'}
b = {'technology':'3', 'culture':'4'}
for q, s in zip(a, b):
    print(q, a[q])
    print(s, b[s])


问:
Accessing one Dataset in Another Dataset (SSRS)
There are 2 Tables on Two Different Servers,
I Have Dataset1 pointing to Server1.
Similarly I have Dataset2 Pointing to Server2.

Now I want to Use some Values from Dataset1 in Dataset2.

Dataset1:-

```<code>Select * from Table1
</code>```

This has Name,Lessthan,GreaterThan

Dataset2:-

```<code>Select * from TableX X inner join Dataset1 on Dataset1.name=TableX.name
Where X.Time>Dataset1.Lessthan and  X.Time>Dataset1.GreaterThan
</code>```

Have tried doing the same as above but we are not able to Access the contents of Dataset1 in Dataset2

It Throws error As 'Invalid Object :-Dataset1'

Please guide me on this.

答:
You're right: a Dataset's query can't access another Dataset: the query is sent to the database server, which knows nothing of your other Dataset which is defined in the report only.

You can make some report parameters (which can be hidden from the user), which use your Dataset 1 to provide their values.

Then you can pass the parameter values to Dataset 2: when you open Dataset 2's properties you will see 'Parameters' on the left. In Dataset 2's query, include things like @paramvalue, and you will be able to supply it with your values from your report parameters.

Body:
There are 2 Tables on Two Different Servers,
I Have Dataset1 pointing to Server1.
Similarly I have Dataset2 Pointing to Server2.

Now I want to Use some Values from Dataset1 in Dataset2.

Dataset1:-

Select * from Table1

This has Name,Lessthan,GreaterThan

Dataset2:-

Select * from TableX X inner join Dataset1 on Dataset1.name=TableX.name
Where X.Time>Dataset1.Lessthan and  X.Time>Dataset1.GreaterThan

Have tried doing the same as above but we are not able to Access the contents of Dataset1 in Dataset2

It Throws error As 'Invalid Object :-Dataset1'

Please guide me on this.


问:
With Android api level 25 it is showing InstrumentationTestCase is deprecated , what is alternative for this?
Was trying to automate an android app by UI Automator, but when I extends InstrumentationTestCase, i found it is deprecated with my api level 25 . So how I can solve this problem any alternative class, please provide a example .

答:
As per the doc InstrumentationTestCase was deprecated in Api 24

This class was deprecated in API level 24. Use InstrumentationRegistry
  instead. New tests should be written using the Android Testing Support
  Library.

You can follow this tutorial for a working example.


问:
Why does Resources.Load <Sprite> return null?
My project has multiple sprites located in Assets\Sprites which I want to load using C# script.

I have tested this:

```<code>Sprite myFruit = Resources.Load <Sprite> ("Graphics_3");
</code>```

But myFruit is still null.

答: Unity's scripting reference doesn't says that you need write  <Sprite> right after Load. So I had problem with loading sprites, although my sprite was in Resources directory.

Body:
My project has multiple sprites located in Assets\Sprites which I want to load using C# script.

I have tested this:

Sprite myFruit = Resources.Load <Sprite> ("Graphics_3");

But myFruit is still null.


问:
Extraction SimpleXMLElement PHP
I have this file in XML:

http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml

I would like to print the content xml tag

I've tried that:

```<code><?php

$xml = 'http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml';
$xmlcont = new SimpleXMLElement($xml);

echo $xmlcont->track->title;

?>
</code>```

but it does not work!!

答:
Use following:

```<code>$xmlObj = new SimpleXMLElement('http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml', NULL, TRUE);
$tracks = $xmlObj->xpath("//tracks");
if(count($tracks) > 0) {
    foreach($tracks as $track) {
        echo $track->track->title . "\n";
    }
}
</code>```

Just set the 3rd parameter of SimpleXMLElement to true when you need to get data from URL

Title: Extraction SimpleXMLElement PHP

Body:
I have this file in XML:

http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml

I would like to print the content xml tag

I've tried that:

<?php

$xml = 'http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml';
$xmlcont = new SimpleXMLElement($xml);

echo $xmlcont->track->title;

?>

but it does not work!!

Body:
Use following:

$xmlObj = new SimpleXMLElement('http://api.radionomy.com/currentsong.cfm?radiouid=80b5e81c-c769-478a-aee7-fbe149aacfe3&apikey=cf415862-c0ac-4085-bc03-be80a26f9063&callmeback=yes&type=xml&cover=yes&previous=yes.xml', NULL, TRUE);
$tracks = $xmlObj->xpath("//tracks");
if(count($tracks) > 0) {
    foreach($tracks as $track) {
        echo $track->track->title . "\n";
    }
}

Just set the 3rd parameter of SimpleXMLElement to true when you need to get data from URL


问:
Changing Tabs in a Tab Control does not send Child a Message
In a C# Windows Forms application using Framework 2.X, clicking on a tab control does not send a message to the child controls (such as a lost focus event).  Using Microsoft Spy++, I do not see messages sent to my child control.  I do get messages when I click back on the tab hosting the control.

Any ideas on what I need to do to have my child control know that its not displayed after the tab was changed.  I would like the code to be in the control, not the parent.  I am guessing that I am missing out on some event or registration.

Thanks in advance,

Craig

答:
I am guessing that I am missing out on some event or registration.

I don't think you are.

The a lost focus event would be too soon since it happens before the page changes.

The Child Control's VisibleChanged event only fires when the parent TabPage is shown and not when it is hidden which is not what you want.

You can handle either the TabPage.VisibleChanged or the TabControl.SelectedIndexChanged. This of course is from the Parent not the Child, which is also not what you want.

Incidently I believe the TCM_SETCURSEL message is sent to the control on tab change (again not helping with the "not in the Parent requriement"


答:
You could add the following CSS

```<code>.mobile li{
  width: 100%;
  display: table;
  margin-top: -5px;
}
</code>```

and then add margin: 5px 0; to .mobile li .emplist. Of course, you could change the gap in between to whatever you want. Just make sure to change it in both .mobile li and .mobile li .emplist. Please see the JSFiddle: https://jsfiddle.net/zmsL4cxc/6/

Title: CSS organization chart line connectors issue

Body:
You could add the following CSS

.mobile li{
  width: 100%;
  display: table;
  margin-top: -5px;
}

and then add margin: 5px 0; to .mobile li .emplist. Of course, you could change the gap in between to whatever you want. Just make sure to change it in both .mobile li and .mobile li .emplist. Please see the JSFiddle: https://jsfiddle.net/zmsL4cxc/6/


问:
Swifty way to get value associated with another in struct
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

```<code>struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}
</code>```

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

答:
Create another struct for your colours and create your own types. And RGB values are float. Values should be divided by 255.0

```<code> struct CustomColors {

    struct Blue {
        static let primary = UIColor(colorLiteralRed: 24.0/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 18.0/255.0, green: 191.0/255.0, blue: 191/255.0, alpha: 1.0)
    }

    struct Orange {
        static let primary = UIColor(colorLiteralRed: 255.0/255.0, green: 110.0/255.0, blue: 64/255.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 230.0/255.0, green: 74.0/255.0, blue: 25/255.0, alpha: 1.0)
    }

    struct Yellow {
        static let primary = UIColor(colorLiteralRed: 255.0/255.0, green: 255.0/255.0, blue: 0.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 255.0/255.0, green: 193.0/255.0, blue: 7/255.0, alpha: 1.0)
    }

}
</code>```

Now you can access like CustomColors.Blue.primary

```<code>let blueColor = CustomColors.Blue.primary
</code>```

Body:
I have a CustomColors struct which contains static lets that define primary and secondary colors for my app.

struct CustomColors {

    static let orangePrimary = UIColor(r: 255, g: 110, b: 64, a: 1)
    static let orangeSecondary = UIColor(r: 230, g: 74, b: 25, a: 1)

    static let bluePrimary = UIColor(r: 24, g: 255, b: 255, a: 1)
    static let blueSecondary = UIColor(r: 18, g: 191, b: 191, a: 1)

    static let yellowPrimary = UIColor(r: 255, g: 255, b: 0, a: 1)
    static let yellowSecondary = UIColor(r: 255, g: 193, b: 7, a: 1)
}

Because secondary colors are completely dependent from the primary ones, I am looking for a way to build a data structure (in the swiftiest way) that would allow me to call for example: CustomColors.bluePrimary.secondary to get the blueSecondary color.

I feel I am missing something pretty basic here as I cannot seem to see how I could do this in the most simple way.

Thanks in advance for your help !

Body:
Create another struct for your colours and create your own types. And RGB values are float. Values should be divided by 255.0

 struct CustomColors {

    struct Blue {
        static let primary = UIColor(colorLiteralRed: 24.0/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 18.0/255.0, green: 191.0/255.0, blue: 191/255.0, alpha: 1.0)
    }

    struct Orange {
        static let primary = UIColor(colorLiteralRed: 255.0/255.0, green: 110.0/255.0, blue: 64/255.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 230.0/255.0, green: 74.0/255.0, blue: 25/255.0, alpha: 1.0)
    }

    struct Yellow {
        static let primary = UIColor(colorLiteralRed: 255.0/255.0, green: 255.0/255.0, blue: 0.0, alpha: 1.0)
        static let secondary = UIColor(colorLiteralRed: 255.0/255.0, green: 193.0/255.0, blue: 7/255.0, alpha: 1.0)
    }

}

Now you can access like CustomColors.Blue.primary

let blueColor = CustomColors.Blue.primary


问:
Do i need to have office installed to use Microsoft.Office.Interop.Excel.dll
I'm trying to develop a new app to process excel files.As far as i know -in order to use the Built in Excel Manipulation functionality i need to have Microsoft Office installed (i'm i right)?

Or can i just download the dll  Microsoft.Office.Interop.Excel.dll,add a reference and make the solution work on every machine?

答:
Yes, you are right. You need Excel to be installed to use the Excel Manipulation feature with Microsoft.Office.Interop.Excel.dll.

If you need to edit only .xlsx files, then you can use libraries like EPPlus. These libraries do NOT need Excel to be installed.


问:
How to get/change the first paragraph in a selection via word-js?
I am developing an Add-In for Word with the javascript api. I am trying to display the text of the first paragraph in the selection. Later I want to change this paragraph.

However, already displaying the text fails if the paragraph is enclosed in a table. If table cells are selected, none of the paragraphs enclosed in the cells seem to be included in the context.document.getSelection().paragraphs collection.

Why is this the case? How am I supposed to navigate to the first paragraph in a selection if the selection includes a table cell in a big table?

Here is the code I use for debugging the problem:

```<code>(function () {
    "use strict";

    // The initialize function is run each time the page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Use this to check whether the API is supported in the Word client.
            if (Office.context.requirements.isSetSupported('WordApi', 1.1)) {
                // Do something that is only available via the new APIs
                $('#button').click(doSomething);
                $('#status').html('Everything is fine.');
            }
            else {
                // Just letting you know that this code will not work with your version of Word.
                $('#supportedVersion').html('This code requires WordApi 1.1 or greater.');
            }
        });
    };

    function doSomething() {
        Word.run(function (context) {
            // get selection
            var selection = context.document.getSelection();
            // load the text of all paragraphs in the selection
            var paragraphs = selection.paragraphs.load('text');

            // Synchronize the document state by executing the queued commands,
            // and return a promise to indicate task completion.
            return context.sync().then(function() {
                $('#status').html(JSON.stringify(paragraphs.items));
            });
        })
        .catch(function (error) {
            $('#status').html('Error: ' + JSON.stringify(error));
            console.log('Error: ' + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log('Debug info: ' + JSON.stringify(error.debugInfo));
            }
        });
    }
})();
</code>```

The selection in the first image returns [{"text":"Content21"}], as expected.

The selection in the second image returns no text at all: []. The paragraps-collection seems to be empty. This does not seem to make any sense to me. There are paragraphs in the selection.

What am I doing wrong?

答:
I'm not familiar with the Word API but according the documentation the selection contains a range and the range contains a list of paragraphs in the table row selection case.

So you can try this:

```<code>var range = context.document.getSelection();
var paragraphs = range.paragraphs;
var textFirstParagraph = paragraphs.items[0].getRange().load('text');
</code>```

Links to the documentation for further studies:

Document object

ParagraphCollection object

Paragraph object

Range object

Body:
I am developing an Add-In for Word with the javascript api. I am trying to display the text of the first paragraph in the selection. Later I want to change this paragraph.

However, already displaying the text fails if the paragraph is enclosed in a table. If table cells are selected, none of the paragraphs enclosed in the cells seem to be included in the context.document.getSelection().paragraphs collection.

Why is this the case? How am I supposed to navigate to the first paragraph in a selection if the selection includes a table cell in a big table?

Here is the code I use for debugging the problem:

(function () {
    "use strict";

    // The initialize function is run each time the page is loaded.
    Office.initialize = function (reason) {
        $(document).ready(function () {

            // Use this to check whether the API is supported in the Word client.
            if (Office.context.requirements.isSetSupported('WordApi', 1.1)) {
                // Do something that is only available via the new APIs
                $('#button').click(doSomething);
                $('#status').html('Everything is fine.');
            }
            else {
                // Just letting you know that this code will not work with your version of Word.
                $('#supportedVersion').html('This code requires WordApi 1.1 or greater.');
            }
        });
    };

    function doSomething() {
        Word.run(function (context) {
            // get selection
            var selection = context.document.getSelection();
            // load the text of all paragraphs in the selection
            var paragraphs = selection.paragraphs.load('text');

            // Synchronize the document state by executing the queued commands,
            // and return a promise to indicate task completion.
            return context.sync().then(function() {
                $('#status').html(JSON.stringify(paragraphs.items));
            });
        })
        .catch(function (error) {
            $('#status').html('Error: ' + JSON.stringify(error));
            console.log('Error: ' + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log('Debug info: ' + JSON.stringify(error.debugInfo));
            }
        });
    }
})();

The selection in the first image returns [{"text":"Content21"}], as expected.

The selection in the second image returns no text at all: []. The paragraps-collection seems to be empty. This does not seem to make any sense to me. There are paragraphs in the selection.

What am I doing wrong?

Body:
I'm not familiar with the Word API but according the documentation the selection contains a range and the range contains a list of paragraphs in the table row selection case.

So you can try this:

var range = context.document.getSelection();
var paragraphs = range.paragraphs;
var textFirstParagraph = paragraphs.items[0].getRange().load('text');

Links to the documentation for further studies:

Document object

ParagraphCollection object

Paragraph object

Range object


问:
create dtype array column in dataframe
How to create 'col new' in dataframe ?

```<code>          'col 1'   'col 2'   'col new'
0           a         b         [a, b]
1           c         d         [c, d]
2           e         f         [e, f]
</code>```

Thank in advance

答:
You can use list comprehension with convert values to list from tuples:

```<code>df['col new'] = [list(x) for x in zip(df['col 1'],df['col 2'])]

print (df)
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]

print (type(df.loc[0, 'col new']))
<class 'list'>
</code>```

Another solution with apply:

```<code>df['col new'] = df.apply(lambda x: [x['col 1'], x['col 2']], axis=1)
print (df)
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]

print (type(df.loc[0, 'col new']))
<class 'list'>
</code>```

If need numpy arrays:

```<code>df['col new'] = [np.array(x) for x in zip(df['col 1'],df['col 2'])]

print (type(df.loc[0, 'col new']))
<class 'numpy.ndarray'>
</code>```

Title: create dtype array column in dataframe

Body:
How to create 'col new' in dataframe ?

          'col 1'   'col 2'   'col new'
0           a         b         [a, b]
1           c         d         [c, d]
2           e         f         [e, f]

Thank in advance

Body:
You can use list comprehension with convert values to list from tuples:

df['col new'] = [list(x) for x in zip(df['col 1'],df['col 2'])]

print (df)
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]

print (type(df.loc[0, 'col new']))
<class 'list'>

Another solution with apply:

df['col new'] = df.apply(lambda x: [x['col 1'], x['col 2']], axis=1)
print (df)
  col 1 col 2 col new
0     a     b  [a, b]
1     c     d  [c, d]
2     e     f  [e, f]

print (type(df.loc[0, 'col new']))
<class 'list'>

If need numpy arrays:

df['col new'] = [np.array(x) for x in zip(df['col 1'],df['col 2'])]

print (type(df.loc[0, 'col new']))
<class 'numpy.ndarray'>


问:
Display hex data from serial port in print function
I receive data from serial port. It is not ASCII data (like from putty), but hex data from modbus rtu line (for example there is 0103AABBCCDD816E data on the line, where 01 is one byte in raw hex, 03 is another byte in raw hex... etc)

I am using python 3.6

I need to simply print as 0103AABBCCDD816E

I tried this code:

```<code>rx_raw = ser.read(8)
rx=binascii.hexlify(bytearray(rx_raw))
print("raw:  ")
print(rx_raw)   # gives:  b'\x01\x03\xaa\xbb\xcc\xdd\x81n'
print("\n")
print("hexiflied:  ")
print(rx)       # gives: b'0103aabbccdd816e'
</code>```

binascii.hexlify(bytearray(rx_raw)) is almost what I need, but I need to get rid of b'  '.

答:
If you want to convert a binary string to a normal string you should decode it:

```<code>b = b'0103aabbccdd816e'
s = b.decode('ascii')

print(b, s, s.upper())
# b'0103aabbccdd816e' 0103aabbccdd816e 0103AABBCCDD816E
</code>```

From the docs:

bytes.decode(encoding="utf-8", errors="strict")

bytearray.decode(encoding="utf-8", errors="strict")

Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

Body:
I receive data from serial port. It is not ASCII data (like from putty), but hex data from modbus rtu line (for example there is 0103AABBCCDD816E data on the line, where 01 is one byte in raw hex, 03 is another byte in raw hex... etc)

I am using python 3.6

I need to simply print as 0103AABBCCDD816E

I tried this code:

rx_raw = ser.read(8)
rx=binascii.hexlify(bytearray(rx_raw))
print("raw:  ")
print(rx_raw)   # gives:  b'\x01\x03\xaa\xbb\xcc\xdd\x81n'
print("\n")
print("hexiflied:  ")
print(rx)       # gives: b'0103aabbccdd816e'

binascii.hexlify(bytearray(rx_raw)) is almost what I need, but I need to get rid of b'  '.

Body:
If you want to convert a binary string to a normal string you should decode it:

b = b'0103aabbccdd816e'
s = b.decode('ascii')

print(b, s, s.upper())
# b'0103aabbccdd816e' 0103aabbccdd816e 0103AABBCCDD816E

From the docs:

bytes.decode(encoding="utf-8", errors="strict")

bytearray.decode(encoding="utf-8", errors="strict")

Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.


问:
How to create GitHub repository under an organization from the command-line?
It's my understanding that to create a personal repository on the command line, using the GitHub v3 API, one can do this (replacing USERNAME and REPONAME appropriately):

```<code>curl -u 'USERNAME' https://api.github.com/user/repos -d '{"name":"REPONAME"}'
</code>```

The user then enters their username and password, and GitHub will create a new empty repository at "github.com/USERNAME/REPONAME".

My question is, how do I create an organization-owned repository via command line? I tried replacing USERNAME with the organization's name, and it prompted me for the 'host password'. I own the organization so I entered my password but I got "Bad credentials". Does this method not work for organization-owned repositories? Or am I doing something wrong?

答:
Just for completeness: Example for Git Api v3:</p>

```<code>curl -u USERNAME https://api.github.com/orgs/ORGNAME/repos -d '{"name":"NAME_OF_REPO", "description":"SOME_DESCRIPTION", "private": true, "has_issues": true, "has_projects": true, "has_wiki":false }'
</code>```

Body:
It's my understanding that to create a personal repository on the command line, using the GitHub v3 API, one can do this (replacing USERNAME and REPONAME appropriately):

curl -u 'USERNAME' https://api.github.com/user/repos -d '{"name":"REPONAME"}'

The user then enters their username and password, and GitHub will create a new empty repository at "github.com/USERNAME/REPONAME".

My question is, how do I create an organization-owned repository via command line? I tried replacing USERNAME with the organization's name, and it prompted me for the 'host password'. I own the organization so I entered my password but I got "Bad credentials". Does this method not work for organization-owned repositories? Or am I doing something wrong?

Body:
Just for completeness: Example for Git Api v3:

curl -u USERNAME https://api.github.com/orgs/ORGNAME/repos -d '{"name":"NAME_OF_REPO", "description":"SOME_DESCRIPTION", "private": true, "has_issues": true, "has_projects": true, "has_wiki":false }'


问:
Append List of Strings to ComboBox
So I have a List<T> where type T is integers. Now I am retrieving this list from a function that uses a SqlDataReader to read my database records (DBMS: Sql Server). Essentially what I want to do is check that if the list say, returns the following:

```<code>1
7
4
</code>```

I want to make a comparison to a string list (List <string> outcome = new List<string>()) where:

```<code>1 = apples
7 = bananas
4 = oranges
</code>```

And finally add these strings to a list then bind them to a ComboBox control in my C# Windows Forms Application.

The problem with approach is that I am using an if-condition to check if the integer (which I am retrieving from the database) exists in the initial list which in this case we can call List<int> checkInt = new List<int>()) exists and if it is, add the string (Banana, apple, oranges or whatever) to the outcome list.

Below is my actual code:

```<code>  public List<int> getSubGroupsBelongingToUser()
        {
            List<int> DepartmentSubGroupIds = new List<int>();

            myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (mySQLConnection = new SqlConnection(myConnectionString))
            {
                SqlParameter parameter = new SqlParameter("@UserId", getUserID(cbxSelectUser.Text));
                mySQLCommand = new SqlCommand("Test", mySQLConnection);
                mySQLCommand.CommandType = CommandType.StoredProcedure;
                mySQLCommand.Parameters.Add(parameter);
                mySQLConnection.ConnectionString = myConnectionString;
                mySQLConnection.Open();

                SqlDataReader sqlDataReader = mySQLCommand.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    DepartmentSubGroupIds.Add(Convert.ToInt32(sqlDataReader["DepartmentSubGroupId"]));
                }
            }
            return DepartmentSubGroupIds;
        }
</code>```

So the function above will return 1 and 3. And I call it as below:

```<code>  private List<string> getSubGroupPerID()
        {
            List<string> outcome = new List<string>();

            if (getSubGroupsBelongingToUser().Contains(1))
            {
                outcome.Add("Apple");
            }
            else if (getSubGroupsBelongingToUser().Contains(2))
            {
                outcome.Add("Oranges");
            }
            else if (getSubGroupsBelongingToUser().Contains(3))
            {
                outcome.Add("Pineapples");
            }
            else
            {
                outcome.Add("All");
            }
            return outcome;
        }
</code>```

Now the problem is that, once it executes, the compiler will check the if-condition and if its true, it will only add that one fruit and finish execution (which is correctly how an if-condition gets executed). But I want it to check all the .Contains(int) and if those comparisons meet then add the fruits only at the end. I already know what the problem is, me using an if-condition. How can I get the result that I want after taking the above into cognisance?

Note: Due to time constraints, I didn't alter my actual code to match the fruit example I gave but surely you should get what I am trying to accomplish.

答:
You could use a Dictionary for that:

```<code>    Dictionary<int, string> fruit = new Dictionary<int, string>();

    fruit.Add(1, "Apple");
    fruit.Add(2, "Oranges");
    fruit.Add(3, "Pineapple");

    private List<string> getSubGroupPerID()
    {
        List<string> outcome = new List<string>();
        List<int> keys = getSubGroupsBelongingToUser();

        if(keys.Count > 0)
        {
            foreach(int key in keys)
            {
                outcome.Add(fruit[key]);
            }
        }
        else
        {
            outcome.Add("All");
        }

        return outcome;
    }
</code>```

If you prefer the pattern you were using, the problem is that you if-else there. That means, if the first condition was true the others won't be checked. You can solve this by only using if and then check if anything was added:

```<code>    private List<string> getSubGroupPerID()
    {
        List<string> outcome = new List<string>();

        if (getSubGroupsBelongingToUser().Contains(1))
        {
            outcome.Add("Apple");
        }
        if (getSubGroupsBelongingToUser().Contains(2))
        {
            outcome.Add("Oranges");
        }
        if (getSubGroupsBelongingToUser().Contains(3))
        {
            outcome.Add("Pineapples");
        }
        if(outcome.Count == 0)
        {
            outcome.Add("All");
        }
        return outcome;
    }
</code>```

Title: Append List of Strings to ComboBox

Body:
So I have a List<T> where type T is integers. Now I am retrieving this list from a function that uses a SqlDataReader to read my database records (DBMS: Sql Server). Essentially what I want to do is check that if the list say, returns the following:

1
7
4

I want to make a comparison to a string list (List <string> outcome = new List<string>()) where:

1 = apples
7 = bananas
4 = oranges

And finally add these strings to a list then bind them to a ComboBox control in my C# Windows Forms Application.

The problem with approach is that I am using an if-condition to check if the integer (which I am retrieving from the database) exists in the initial list which in this case we can call List<int> checkInt = new List<int>()) exists and if it is, add the string (Banana, apple, oranges or whatever) to the outcome list.

Below is my actual code:

  public List<int> getSubGroupsBelongingToUser()
        {
            List<int> DepartmentSubGroupIds = new List<int>();

            myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (mySQLConnection = new SqlConnection(myConnectionString))
            {
                SqlParameter parameter = new SqlParameter("@UserId", getUserID(cbxSelectUser.Text));
                mySQLCommand = new SqlCommand("Test", mySQLConnection);
                mySQLCommand.CommandType = CommandType.StoredProcedure;
                mySQLCommand.Parameters.Add(parameter);
                mySQLConnection.ConnectionString = myConnectionString;
                mySQLConnection.Open();

                SqlDataReader sqlDataReader = mySQLCommand.ExecuteReader();
                while (sqlDataReader.Read())
                {
                    DepartmentSubGroupIds.Add(Convert.ToInt32(sqlDataReader["DepartmentSubGroupId"]));
                }
            }
            return DepartmentSubGroupIds;
        }

So the function above will return 1 and 3. And I call it as below:

  private List<string> getSubGroupPerID()
        {
            List<string> outcome = new List<string>();

            if (getSubGroupsBelongingToUser().Contains(1))
            {
                outcome.Add("Apple");
            }
            else if (getSubGroupsBelongingToUser().Contains(2))
            {
                outcome.Add("Oranges");
            }
            else if (getSubGroupsBelongingToUser().Contains(3))
            {
                outcome.Add("Pineapples");
            }
            else
            {
                outcome.Add("All");
            }
            return outcome;
        }

Now the problem is that, once it executes, the compiler will check the if-condition and if its true, it will only add that one fruit and finish execution (which is correctly how an if-condition gets executed). But I want it to check all the .Contains(int) and if those comparisons meet then add the fruits only at the end. I already know what the problem is, me using an if-condition. How can I get the result that I want after taking the above into cognisance?

Note: Due to time constraints, I didn't alter my actual code to match the fruit example I gave but surely you should get what I am trying to accomplish.

Body:
You could use a Dictionary for that:

    Dictionary<int, string> fruit = new Dictionary<int, string>();

    fruit.Add(1, "Apple");
    fruit.Add(2, "Oranges");
    fruit.Add(3, "Pineapple");

    private List<string> getSubGroupPerID()
    {
        List<string> outcome = new List<string>();
        List<int> keys = getSubGroupsBelongingToUser();

        if(keys.Count > 0)
        {
            foreach(int key in keys)
            {
                outcome.Add(fruit[key]);
            }
        }
        else
        {
            outcome.Add("All");
        }

        return outcome;
    }

If you prefer the pattern you were using, the problem is that you if-else there. That means, if the first condition was true the others won't be checked. You can solve this by only using if and then check if anything was added:

    private List<string> getSubGroupPerID()
    {
        List<string> outcome = new List<string>();

        if (getSubGroupsBelongingToUser().Contains(1))
        {
            outcome.Add("Apple");
        }
        if (getSubGroupsBelongingToUser().Contains(2))
        {
            outcome.Add("Oranges");
        }
        if (getSubGroupsBelongingToUser().Contains(3))
        {
            outcome.Add("Pineapples");
        }
        if(outcome.Count == 0)
        {
            outcome.Add("All");
        }
        return outcome;
    }


问:
passing iterators to lambda
I want to use the lambda expression for the following codes,

```<code>long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }
</code>```

I particularly want to convert  for loop to a lambda expression. How can I do that?

答:
You can abstract it just in case you need to reuse it in the same block

```<code>auto f = [](auto& itercollection)
{
    for(auto iter = itercollection.begin()+1;iter!=itercollection.end();iter++)
    {
        dist+=*(iter)-*(iter-1);
        noOfways+=  minOper(dist);
    }
}
</code>```

then just call it over:

```<code>f(noChocolets)
f(noChocolets2)
f(noChocolets3)
</code>```

Title: passing iterators to lambda

Body:
I want to use the lambda expression for the following codes,

long long noOfways =0;
 auto dist =0;
 for(auto iter = noChocolets.begin()+1;iter!=noChocolets.end();iter++)
 {
     dist+=*(iter)-*(iter-1);
     noOfways+=  minOper(dist);
 }

I particularly want to convert  for loop to a lambda expression. How can I do that?

Body:
You can abstract it just in case you need to reuse it in the same block

auto f = [](auto& itercollection)
{
    for(auto iter = itercollection.begin()+1;iter!=itercollection.end();iter++)
    {
        dist+=*(iter)-*(iter-1);
        noOfways+=  minOper(dist);
    }
}

then just call it over:

f(noChocolets)
f(noChocolets2)
f(noChocolets3)