问:
How to mute twilio calls in javascript
I am able to mute the sound going into the microphone, but not the sound coming out of the speakers.  To be specific, I'm only trying to mute the Twilio call, not other sounds in the browser, and certainly not system sounds.</p>

答:
Here is working example </p>

```<code>  $scope.togglePublishAudio = function togglePublishAudio() {
      $log.debug('Toggling publish audio');

      if (activeRoom.localParticipant.media.isMuted === false) {
        $scope.isMuted = true;
        activeRoom.localParticipant.media.mute();
      } else {
        $scope.isMuted = false;
        activeRoom.localParticipant.media.unmute();
      }

    };
</code>```

<p>In new Version of twilio </p>

```<code>  var localMedia = room.localParticipant;
  localMedia.tracks.forEach(function (track) {
    if (track.isEnabled) {
      track.disable();
      $scope.isPaused = true;
    } else {
      track.enable();
      $scope.isPaused = false;
    }
  });
</code>```

Title: How to mute twilio calls in javascript

Body:
Here is working example

  $scope.togglePublishAudio = function togglePublishAudio() {
      $log.debug('Toggling publish audio');

      if (activeRoom.localParticipant.media.isMuted === false) {
        $scope.isMuted = true;
        activeRoom.localParticipant.media.mute();
      } else {
        $scope.isMuted = false;
        activeRoom.localParticipant.media.unmute();
      }

    };

In new Version of twilio

  var localMedia = room.localParticipant;
  localMedia.tracks.forEach(function (track) {
    if (track.isEnabled) {
      track.disable();
      $scope.isPaused = true;
    } else {
      track.enable();
      $scope.isPaused = false;
    }
  });


来源: stackexchange

问:
what does (: ${foo%%bar}) mean in unix shell
```<code>#!/bin/sh
unset foo
(: ${foo%%bar}) 2> /dev/null
E1="$?"
</code>```

I know foo is a variable, ${foo%%bar} means remove last bar in $foo.

But what does (: ) mean there ?

I'm new to shell, can any one help me? Thanks!

答:
In bash, : means true.

Try :

```<code>: && echo ok; true && echo ok; : || echo ok; true || echo ok
</code>```

ContentLicense: CC BY-SA 3.0

Body:
#!/bin/sh
unset foo
(: ${foo%%bar}) 2> /dev/null
E1="$?"

I know foo is a variable, ${foo%%bar} means remove last bar in $foo.

But what does (: ) mean there ?

I'm new to shell, can any one help me? Thanks!

Body:
In bash, : means true.

Try :

: && echo ok; true && echo ok; : || echo ok; true || echo ok


问:
How can I validate regex?
I'd like to test the validity of a regular expression in PHP, preferably before it's used. Is the only way to do this actually trying a preg_match() and seeing if it returns FALSE?

Is there a simpler/proper way to test for a valid regular expression?

答:
If you want to dynamically test a regex preg_match(...) === false seems to be your only option. PHP doesn't have a mechanism for compiling regular expressions before they are used.

Also you may find preg_last_error an useful function.

On the other hand if you have a regex and just want to know if it's valid before using it there are a bunch of tools available out there. I found rubular.com to be pleasant to use.

Title: How can I validate regex?

ContentLicense: CC BY-SA 2.5


问:
Laravel: Get variable name from route
How can I get the name of the get variable from a route url?

```<code>http://localhost:8000/api/system/123
</code>```

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

```<code>http://localhost:8000/api/system?id=123
</code>```

How can this be done?

```<code>Route::get('api/system/{id}', 'ApiController@User');
</code>```

答:
Try this way</p>

```<code> namespace App\Http\Controllers;

    class ApiController extends Controller{

        public function User($id)
        {
           dd($id)
        }
    }
</code>```

Title: Laravel: Get variable name from route

Body:
How can I get the name of the get variable from a route url?

http://localhost:8000/api/system/123

Basically I want to know what the GET variable is called that holds the value of 123. For example here it is called id

http://localhost:8000/api/system?id=123

How can this be done?

Route::get('api/system/{id}', 'ApiController@User');

Body:
Try this way

 namespace App\Http\Controllers;

    class ApiController extends Controller{

        public function User($id)
        {
           dd($id)
        }
    }


问:
"open/close" SqlConnection or keep open?
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

```<code>public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}
</code>```

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

```<code>//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}
</code>```

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.

答:
There are distinctions between physical and logical connections. DbConnection is a kind of logical connection and it uses underlying physical connection to Oracle. Closing/opening DbConnection doesn't affect your performance, but makes your code clean and stable - connection leaks are impossible in this case.

Also you should remember about cases when there are limitations for parallel connections on db server - taking that into account it is necessary to make your connections very short.

Connection pool frees you from connection state checking - just open, use and immediately close them.

ContentLicense: CC BY-SA 4.0

Body:
I have my business-logic implemented in simple static classes with static methods. Each of these methods opens/closes SQL connection when called:

public static void DoSomething()
{
    using (SqlConnection connection = new SqlConnection("..."))
    {
        connection.Open();

        // ...

        connection.Close();
    }
}

But I think passing the connection object around and avoiding opening and closing a connection saves performance. I made some tests long time ago with OleDbConnection class (not sure about SqlConnection), and it definitely helped to work like this (as far as I remember):

//pass around the connection object into the method
public static void DoSomething(SqlConnection connection)
{
    bool openConn = (connection.State == ConnectionState.Open);
    if (!openConn)
    {
        connection.Open();
    }

    // ....

    if (openConn)
    {
        connection.Close();
    }
}

So the question is - should I choose the method (a) or method (b) ? I read in another stackoverflow question that connection pooling saved performance for me, I don't have to bother at all...

PS. It's an ASP.NET app - connections exist only during a web-request. Not a win-app or service.


问:
Read Multiple JSON object from a Text File
My Question is similar to what has been asked here .
few points :

I can not change the format. (No commas to be added etc)

This is basically a huge .txt file containing 1000's of Json objects.

My Json objects are HUGE.

This is what I am doing right now :

```<code>    FileReader fileReader = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(fileReader);
        String data = "";
        while((data = reader.readLine()) != null){
            ObjectMapper mapper = new ObjectMapper();
            Map<String,String> map = mapper.readValue(data, Map.class);
        }
</code>```

Currently I am using Jackson and Ideally I would like to read one Json Object from the file at a time, Parse it and then move on to the next one. I need to count let say unique number of id's from these Json object and do more operations. It will be best to read them one by one.

Is jackson would be the best way going forward ?
This is a good example of parsing huge Json, But it deals with only one object per file. My file has huge Jsons (1000s of them).

答:
Here is a more JAVA 8ish solution for your query, I always lean toward BufferedReader over InputStreams for any place where parsing is going to be done a lot of time. </p>

```<code> ObjectMapper mapper  = new ObjectMapper();
 JsonFactory jsonFactory = new JsonFactory();
 try(BufferedReader br = new BufferedReader(new FileReader("luser.txt"))) {
     Iterator<luser> value = mapper.readValues( jsonFactory.createParser(br), luser.class);
     value.forEachRemaining((u)->{System.out.println(u);});
 }
</code>```

<p>The deserialization for each object happens as part of next(), in each iteration. </p>

Body:
My Question is similar to what has been asked here .
few points :

I can not change the format. (No commas to be added etc)

This is basically a huge .txt file containing 1000's of Json objects.

My Json objects are HUGE.

This is what I am doing right now :

    FileReader fileReader = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(fileReader);
        String data = "";
        while((data = reader.readLine()) != null){
            ObjectMapper mapper = new ObjectMapper();
            Map<String,String> map = mapper.readValue(data, Map.class);
        }

Currently I am using Jackson and Ideally I would like to read one Json Object from the file at a time, Parse it and then move on to the next one. I need to count let say unique number of id's from these Json object and do more operations. It will be best to read them one by one.

Is jackson would be the best way going forward ?
This is a good example of parsing huge Json, But it deals with only one object per file. My file has huge Jsons (1000s of them).

Body:
Here is a more JAVA 8ish solution for your query, I always lean toward BufferedReader over InputStreams for any place where parsing is going to be done a lot of time.

 ObjectMapper mapper  = new ObjectMapper();
 JsonFactory jsonFactory = new JsonFactory();
 try(BufferedReader br = new BufferedReader(new FileReader("luser.txt"))) {
     Iterator<luser> value = mapper.readValues( jsonFactory.createParser(br), luser.class);
     value.forEachRemaining((u)->{System.out.println(u);});
 }

The deserialization for each object happens as part of next(), in each iteration.


问:
scraping website with login page
I currently login to the time from website using the following script.

```<code>browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()
</code>```

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?

答:
Using headless browser will consume significantly less CPU and memory, try using PhantomJS insist of Chrome. there is a nice blog post about using PhantomJS with selenium here:

https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/

Title: scraping website with login page

Body:
I currently login to the time from website using the following script.

browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F")
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()

it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?


问:
matching time on real-time graph
I set time/date as a x value in my real-time graph, but the time didn't match with my android's time, can someone check my code

```<code>final DateFormat sdf = android.text.format.DateFormat.getTimeFormat(this);
    graph.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter() {
        @Override
        public String formatLabel(double value, boolean isValueX) {
            if (isValueX) {
                long Valuemilis = (new Double(value)).longValue();
                return sdf.format(Valuemilis*1000);
            }
            else {
                return null;
            }
        }
    });
</code>```

app's picture

答:
To get your system time in milliseconds you can use Date.java class.
The below snippet of code may solve your problem.

```<code>long Valuemilis = new Date().getTime();
</code>```

Title: matching time on real-time graph

Body:
I set time/date as a x value in my real-time graph, but the time didn't match with my android's time, can someone check my code

final DateFormat sdf = android.text.format.DateFormat.getTimeFormat(this);
    graph.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter() {
        @Override
        public String formatLabel(double value, boolean isValueX) {
            if (isValueX) {
                long Valuemilis = (new Double(value)).longValue();
                return sdf.format(Valuemilis*1000);
            }
            else {
                return null;
            }
        }
    });

app's picture

Body:
To get your system time in milliseconds you can use Date.java class.
The below snippet of code may solve your problem.

long Valuemilis = new Date().getTime();


问:
in angular js how to call a function if ng-if is true?
i am totally new with angular js and trying to call a function when ng-if is true
my code =>

```<code>ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false && hellow()"
</code>```

and my js =>

```<code><script type="text/javascript">
       $scope.hellow = function ()
       {
           alert('hi');
       };
</script>
</code>```

also try=>

```<code><span ng-if="$index === 3" ng-init="hellow()"></span>
</code>```

problem is it is not alerting anything ?can anybody tell me what i have done wrong?

答:
Define angular(module and ng-app) first and then controller to bind the function hellow., then change it like :

```<code>  <div ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon=false; hellow();">
</code>```

Working
Fiddle

Updated fiddle with script tag.

Body:
i am totally new with angular js and trying to call a function when ng-if is true
my code =>

ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false && hellow()"

and my js =>

also try=>

problem is it is not alerting anything ?can anybody tell me what i have done wrong?

Body:
Define angular(module and ng-app) first and then controller to bind the function hellow., then change it like :

  <div ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon=false; hellow();">

Working
Fiddle

Updated fiddle with script tag.


问:
Nested layout using bootstrap causes misalignment
I am trying to create a nested layout using bootstrap 3. I followed the the tutorial (see the part regarding nesting). The layout basically only contains rows consisting of single columns, however I still need the nesting for technical reasons. My current version is in this fiddle.

In a nutshell, I use alternating row / column divs to achieve the nesting:

```<code><div class="row">
  <div class="col">
    <div class="row">
      <div class="col">
        Content row 1 (misaligned)
      </div>
    </div>
  </div>
</div>
</code>```

The problem is that the inner content is misaligned with respect to the surrounding one. I suspect that this is because rows have a negative margin. Is there a way to fix or circumvent this problem?

答:
There is no .col definition for bootstrap 3.

TWBS-3#css#grid syntax is: .col-${screen}-${span} where:

screen = ['xs', 'sm', 'md', 'lg']

span = [1-12]

So, assuming you want to work with extra small screens your html should look like:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

          Content row 1 (misaligned)

```
</div>
</div>
</p>

<p>here is the official example using <code>screen = xs</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.txt {
  background: cyan;
  height: 20px;
  display: flex;
  margin: 3px 0;
  align-items: center;
  justify-content: center;
}

.row { margin-bottom: 50px; }</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

1

1

1

1

1

1

1

1

1

1

1

1

.col-xs-8

.col-xs-4

.col-xs-4

.col-xs-4

.col-xs-4

.col-xs-6

.col-xs-6

```

Body:
I am trying to create a nested layout using bootstrap 3. I followed the the tutorial (see the part regarding nesting). The layout basically only contains rows consisting of single columns, however I still need the nesting for technical reasons. My current version is in this fiddle.

In a nutshell, I use alternating row / column divs to achieve the nesting:

        Content row 1 (misaligned)

The problem is that the inner content is misaligned with respect to the surrounding one. I suspect that this is because rows have a negative margin. Is there a way to fix or circumvent this problem?

Body:
There is no .col definition for bootstrap 3.

TWBS-3#css#grid syntax is: .col-${screen}-${span} where:

screen = ['xs', 'sm', 'md', 'lg']

span = [1-12]

So, assuming you want to work with extra small screens your html should look like:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<section class="container">

  <div class="row">
    <div class="col-xs-12">
      <div class="row">
        <div class="col-xs-12">
          Content row 1 (misaligned)
        </div>
      </div>
    </div>
  </div>

</section>

here is the official example using screen = xs

.txt {
  background: cyan;
  height: 20px;
  display: flex;
  margin: 3px 0;
  align-items: center;
  justify-content: center;
}

.row { margin-bottom: 50px; }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<section class="container">
<div class="row">
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
  <div class="col-xs-1"><div class="txt">1</div></div>
</div>
<div class="row">
  <div class="col-xs-8"><div class="txt">.col-xs-8</div></div>
  <div class="col-xs-4"><div class="txt">.col-xs-4</div></div>
</div>
<div class="row">
  <div class="col-xs-4"><div class="txt">.col-xs-4</div></div>
  <div class="col-xs-4"><div class="txt">.col-xs-4</div></div>
  <div class="col-xs-4"><div class="txt">.col-xs-4</div></div>
</div>
<div class="row">
  <div class="col-xs-6"><div class="txt">.col-xs-6</div></div>
  <div class="col-xs-6"><div class="txt">.col-xs-6</div></div>
</div>

</section>


问:
Get the day change point(s) between two UNIX timestamps
I have the date range (two UNIX timestamps) and I need to find point(s) at 23:59:59 if exists.
How I can do it with Perl?

P.S. I think for() is not good idea because I can have very big range. Anything another variants?

答:
Here's an example I scrapped together based on my semi-recent knowledge of the UNIX timestamp (school is such a long time ago...)

```<code>while (entry) {
   if ((timestamp-1) % 86400 == 0) {
      #match
   } else {
      #nomatch
   }
}
</code>```

However, like everybody else, I would suggest using other tools to do that since my example does not take leap seconds into account and I highly doubt it's POSIX-compliant. More info here.

Body:
Here's an example I scrapped together based on my semi-recent knowledge of the UNIX timestamp (school is such a long time ago...)

while (entry) {
   if ((timestamp-1) % 86400 == 0) {
      #match
   } else {
      #nomatch
   }
}

However, like everybody else, I would suggest using other tools to do that since my example does not take leap seconds into account and I highly doubt it's POSIX-compliant. More info here.


问:
Attaching click event won't work
I've wanted to attach click event to an object not yet added to the DOM like here.

I've used a code from the answer but nothing happens when I click anything.

Here's my HTML:

```<code><html>
<head>
<script src="resources/js/components/jquery/jquery-3.1.1.min.js"></script>
<script src="file.js"></script>
</head>
<body>
    <a href="#">asl;kdfjl</a>
    <div id="my-button">sdgdf</div>
</body>
</html>
</code>```

JavaScripts are in those location and I can see them in Sources tab in Chrome.

My file.js has content exactly copy-pasted from jsfiddle:

```<code>$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {
    $('a').after('<div id="my-button">test</div>');
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});
</code>```

答:
Your code working with snippet .Better use with document.ready.Post you js after document.ready .And change the selector document instead of body

$(document).ready(function() {

  $(document).on('click', 'a', function(e) {
    e.preventDefault();
    createMyButton();
  });

  createMyButton = function(data) {
    $('a').after('
test
');
  };

  $(document).on('click', '#my-button', function(e) {
    alert("yeahhhh!!! but this doesn't work for me :(");
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
asl;kdfjl
<div id="my-button">sdgdf</div></code>```

Title: Attaching click event won't work

Body:
I've wanted to attach click event to an object not yet added to the DOM like here.

I've used a code from the answer but nothing happens when I click anything.

Here's my HTML:

    asl;kdfjl

sdgdf

JavaScripts are in those location and I can see them in Sources tab in Chrome.

My file.js has content exactly copy-pasted from jsfiddle:

$('body').on('click','a',function(e){
    e.preventDefault();
    createMyButton();
});

createMyButton = function(data) {
    $('a').after('
test
');
};

$('body').on('click','#my-button',function (e) {
      alert("yeahhhh!!! but this doesn't work for me :(");
});

Body:
Your code working with snippet .Better use with document.ready.Post you js after document.ready .And change the selector document instead of body

$(document).ready(function() {

  $(document).on('click', 'a', function(e) {
    e.preventDefault();
    createMyButton();
  });

  createMyButton = function(data) {
    $('a').after('<div id="my-button">test</div>');
  };

  $(document).on('click', '#my-button', function(e) {
    alert("yeahhhh!!! but this doesn't work for me :(");
  });
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">asl;kdfjl</a>
<div id="my-button">sdgdf</div>


问:
What would be right place to put Categories under folder structure Xcode Project
I have structured my project following MVC pattern so took Folders like

Model

View

Controller

Helpers

Stores

Resources

I am not sure "Categories" comes under which folder.

答:
You can have a Category/Extension folder in top structure where-in the extension to classes that will be used throughout the app can be placed.

Model

View

Controller

Extensions

For Instance: The extensions for UIFont, String, UIColor, UIButton are
  something that will be of use across all the controllers. So these
  extensions can all go under the top level Category/Extension folder.

Furthermore, it is best if the extension of a ViewController, AppDelegate are grouped together in a folder of it's own thereby improving the organisation and readability of folders and classes in it.

For example the AppDelegate folder with extension will be something like this:

```<code>AppDelegate     //folder
   -AppDelegate  //classes
   -AppDelegate+RootHandling
</code>```

Body:
You can have a Category/Extension folder in top structure where-in the extension to classes that will be used throughout the app can be placed.

Model

View

Controller

Extensions

For Instance: The extensions for UIFont, String, UIColor, UIButton are
  something that will be of use across all the controllers. So these
  extensions can all go under the top level Category/Extension folder.

Furthermore, it is best if the extension of a ViewController, AppDelegate are grouped together in a folder of it's own thereby improving the organisation and readability of folders and classes in it.

For example the AppDelegate folder with extension will be something like this:

AppDelegate     //folder
   -AppDelegate  //classes
   -AppDelegate+RootHandling


问:
How do I get a human-readable file size in bytes abbreviation using .NET?
How do I get a human-readable file size in bytes abbreviation using .NET?

Example:
Take input 7,326,629 and display 6.98 MB

答:
Like @NET3's solution. Use shift instead of division to test the range of bytes, because division takes more CPU cost.

private static readonly string[] UNITS = new string[] { "B", "KB", "MB", "GB", "TB", "PB", "EB" };

public static string FormatSize(ulong bytes)
{
    int c = 0;
    for (c = 0; c < UNITS.Length; c++)
    {
        ulong m = (ulong)1 << ((c + 1) * 10);
        if (bytes < m)
            break;
    }

    double n = bytes / (double)((ulong)1 << (c * 10));
    return string.Format("{0:0.##} {1}", n, UNITS[c]);
}
```

OwnerDisplayName: DLarsen

LastEditorDisplayName: DLarsen


问:
Unable to scroll (broken TextBox) after Select and ChangeView in UWP
I just want to scroll to my regex result.
I notice that if I only use Select or only ChangeView , there is no error
(but no result too).

```<code>private void showrez()
        {
            if (head != null)
            {
                ContentBox.Focus(FocusState.Programmatic);
                ContentBox.Select(head.Index, head.Length);
                var r = ContentBox.GetRectFromCharacterIndex(ContentBox.SelectionStart, false);

                var grid = VisualTreeHelper.GetChild(ContentBox, 0);
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
                {
                    object obj = VisualTreeHelper.GetChild(grid, i);
                    if (obj is ScrollViewer)
                    {
                        ((ScrollViewer)obj).ChangeView(r.Left, r.Top, null);
                        break;
                    }
                }
            }
        }
</code>```

EDIT:

I just checked this works without bugs , but used methods are obsolete.

```<code>private void showrez()
        {
            if (head != null)
            {
                ContentBox.Focus(FocusState.Programmatic);
                ContentBox.Select(head.Index, head.Length);
                var r = ContentBox.GetRectFromCharacterIndex(ContentBox.SelectionStart, false);

                var grid = VisualTreeHelper.GetChild(ContentBox, 0);
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
                {
                    object obj = VisualTreeHelper.GetChild(grid, i);
                    if (obj is ScrollViewer)
                    {
                        //((ScrollViewer)obj).ChangeView(r.Left, r.Top, null);

                        ((ScrollViewer)obj).ScrollToVerticalOffset(r.Top);
                        ((ScrollViewer)obj).ScrollToHorizontalOffset(r.Left);

                        break;
                    }
                }

            }
        }
</code>```

答:
When we use the ChangeView(IReference<Double>, IReference<Double>, IReference<Single>) method it enable scrolling animation by default.
Please try to use the ChangeView(IReference<Double>, IReference<Double>, IReference<Single>, Boolean) and we should be able to set true to disable zoom/pan animations while changing the view. The default is false.

Foe example:

```<code>((ScrollViewer)obj).ChangeView(r.Left, r.Top, null,true);
</code>```

Body:
I just want to scroll to my regex result.
I notice that if I only use Select or only ChangeView , there is no error
(but no result too).

private void showrez()
        {
            if (head != null)
            {
                ContentBox.Focus(FocusState.Programmatic);
                ContentBox.Select(head.Index, head.Length);
                var r = ContentBox.GetRectFromCharacterIndex(ContentBox.SelectionStart, false);

                var grid = VisualTreeHelper.GetChild(ContentBox, 0);
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
                {
                    object obj = VisualTreeHelper.GetChild(grid, i);
                    if (obj is ScrollViewer)
                    {
                        ((ScrollViewer)obj).ChangeView(r.Left, r.Top, null);
                        break;
                    }
                }
            }
        }

EDIT:

I just checked this works without bugs , but used methods are obsolete.

private void showrez()
        {
            if (head != null)
            {
                ContentBox.Focus(FocusState.Programmatic);
                ContentBox.Select(head.Index, head.Length);
                var r = ContentBox.GetRectFromCharacterIndex(ContentBox.SelectionStart, false);

                var grid = VisualTreeHelper.GetChild(ContentBox, 0);
                for (var i = 0; i < VisualTreeHelper.GetChildrenCount(grid); i++)
                {
                    object obj = VisualTreeHelper.GetChild(grid, i);
                    if (obj is ScrollViewer)
                    {
                        //((ScrollViewer)obj).ChangeView(r.Left, r.Top, null);

                        ((ScrollViewer)obj).ScrollToVerticalOffset(r.Top);
                        ((ScrollViewer)obj).ScrollToHorizontalOffset(r.Left);

                        break;
                    }
                }

            }
        }

Body:
When we use the ChangeView(IReference<Double>, IReference<Double>, IReference<Single>) method it enable scrolling animation by default.
Please try to use the ChangeView(IReference<Double>, IReference<Double>, IReference<Single>, Boolean) and we should be able to set true to disable zoom/pan animations while changing the view. The default is false.

Foe example:

((ScrollViewer)obj).ChangeView(r.Left, r.Top, null,true);


答:
You have to specify the data in each geom seperately, like this for instance:

```<code>ggplot() +
  geom_bar(data=filter(df, group %in% c("group3", "group4")), aes(x = month, y = score, fill=group) , stat ="identity", position="dodge")+
  geom_point(data=filter(df, group %in% c("group1", "group2")),aes(x = month, y = score,colour=group)) +
  geom_line(data=filter(df, group %in% c("group1", "group2")), aes(x = month, y = score,colour=group, group=group)) +
  theme(axis.text.x = element_text(angle = 45),legend.position="bottom") +
  scale_fill_manual(values = ggcolors(4)[3:4])
</code>```

Title: How to combine line and bar chart in ggplot2 with just one grouping variable?

Body:
I have data frame with just one grouping variable. Is it possible to combine bars and lines in one ggplot2 chart without having to rearrange the data frame?

This is my dataframe:

df <- structure(list(month = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Label = c("2017-01",
"2017-02", "2017-03", "2017-04", "2017-05", "2017-06", "2017-07",
"2017-08", "2017-09", "2017-10", "2017-11", "2017-12"), class = "factor"),
    score = c(16610.726, 16220.9266093333, 13499.64666, 7197.6127,
    13558.9922, 13757.1462857143, 17569.2874603175, 12316.9047619048,
    10314.1709666667, 20670.2728, 9581.31135238095, 12197.9578666667,
    14381.7804, 11041.6698, 14180.1408, 17538.8314444444, 20716.3987333333,
    7478.66444444445, 3583.57866666667, 9729.769, 8947.99733333333,
    16408.5435, 10113.3729666667, 6295.22277777778, 11087.181456763,
    10501.219568, 10740.9389444, 9589.42535569615, 8731.001856,
    14532.887226, 6201.22673333333, 6240.31210733333, 13252.18944,
    21895.158224, 26057.8897973333, 15196.561848, 8243.45971166667,
    11167.29269775, 8123.32673125, 8235.66809083333, 3770.88105441667,
    6959.3694075, 3961.0981325, 7193.83911675, 7495.817416, 9350.171163,
    12899.7255705, 12052.6313529528), group = c("group1", "group1",
    "group1", "group1", "group1", "group1", "group1", "group1",
    "group1", "group1", "group1", "group1", "group2", "group2",
    "group2", "group2", "group2", "group2", "group2", "group2",
    "group2", "group2", "group2", "group2", "group3", "group3",
    "group3", "group3", "group3", "group3", "group3", "group3",
    "group3", "group3", "group3", "group3", "group4", "group4",
    "group4", "group4", "group4", "group4", "group4", "group4",
    "group4", "group4", "group4", "group4")), row.names = c(NA,
-48L), .Names = c("month", "score", "group"), class = "data.frame")

This is a plot showing lines only:

ggplot(df, aes(x = month, y = score,group=group,colour=group)) +
  geom_line(size=0.5) +
  geom_point(size = 1.5) + theme(axis.text.x = element_text(angle = 45),legend.position="bottom")

This is the result:

Now I want the lines group3 and group4 to be bars instead of lines. Is that possible with the data frame as it is?

Body:
You have to specify the data in each geom seperately, like this for instance:

ggplot() +
  geom_bar(data=filter(df, group %in% c("group3", "group4")), aes(x = month, y = score, fill=group) , stat ="identity", position="dodge")+
  geom_point(data=filter(df, group %in% c("group1", "group2")),aes(x = month, y = score,colour=group)) +
  geom_line(data=filter(df, group %in% c("group1", "group2")), aes(x = month, y = score,colour=group, group=group)) +
  theme(axis.text.x = element_text(angle = 45),legend.position="bottom") +
  scale_fill_manual(values = ggcolors(4)[3:4])


问:
How can I write this regex without using a look behind that isn't supported
I rarely use Regex's and I've gotten it to work on regex101.com

But I tried to use it and it says it's not supported by JS this is what I have

/(?<=[\]|>])(.*?)(?=$|\n)/g

https://regex101.com/r/sxUoDr/1

How can I substitute the look behind so it will work fine?

This is the data I'm trying to parse:

```<code><100>11m
[RIP]25s
[RIP] 2m
[RIP] 7m
[RIP] 1m
[RIP]12s
</code>```

I'm trying to extract the times away

答:
I don't think it can be written more simply than this...

var rgx = /\d+[ms]/g;  // capture 1 or more digits followed by m or s
var str = `<100>11m
[RIP]25s
[RIP] 2m
[RIP] 7m
[RIP] 1m
[RIP]12s`;
var res;

while(res=rgx.exec(str)){
    console.log(res[0]);
}```

Body:
I rarely use Regex's and I've gotten it to work on regex101.com

But I tried to use it and it says it's not supported by JS this is what I have

/(?<=[\]|>])(.*?)(?=$|\n)/g

https://regex101.com/r/sxUoDr/1

How can I substitute the look behind so it will work fine?

This is the data I'm trying to parse:

<100>11m
[RIP]25s
[RIP] 2m
[RIP] 7m
[RIP] 1m
[RIP]12s

I'm trying to extract the times away


问:
Insert_batch Error Codeigniter 3.1.4

A PHP Error was encountered

Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1

INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array

Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php

Line Number: 691

My Controller is:

```<code>public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post []= array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}
</code>```

My Model is:

```<code>public function add_payment($array)
{
     // echo "```";
     // print_r($array);
     // exit();
     return $this->db->insert_batch('paymentsize',$array);

}
```
<p>My View is:</p>
```

          <input type="hidden" name="pro_id[]"  value="<?= $project->pro_id; ?>" >

                Date
                  <input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >

                  Plot Category
                    <select name="category[]" class="form-control">
                      <option> </option>
                      <option>Residential</option>
                      <option>Commercial</option>
                    </select>

```

if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...

答:
You used $post for two purpose, change your controller codes as following code:

```<code>public function store_payment()
{
    $post = $this->input->post(NULL,TRUE);
    $count=count($this->input->post('pro_id'));
    echo CI_VERSION;

    $data = array();
    for($i = 0; $i < $count; $i++){
        $data []= array(
            'pro_id'        => $post['pro_id'][$i],
            'date_add'      => $post['date_add'][$i],
            'category'      => $post['category'][$i],
            'type'          => $post['type'][$i],
            'size'          => $post['size'][$i],
            'counts'        => $post['counts'][$i],
            'booking'       => $post['booking'][$i],
            'confirmation'  => $post['confirmation'][$i],
            'confirm_days'  => $post['confirm_days'][$i],
            'allocation'    => $post['allocation'][$i],
            'allocate_days' => $post['allocate_days'][$i],
            'm_installment' => $post['m_installment'][$i],
            'month'         => $post['month'][$i],
            'y_instalment'  => $post['y_instalment'][$i],
            'halfyear'      => $post['halfyear'][$i],
            'leveling'      => $post['leveling'][$i],
            'demarcation'   => $post['demarcation'][$i],
            'possession'    => $post['possession'][$i]
            );
    }
    $this->projects->add_payment($data);
}
</code>```

Title: Insert_batch Error Codeigniter 3.1.4

Body:
A PHP Error was encountered

Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1

INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array

Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php

Line Number: 691

My Controller is:

public function store_payment()
{
    $post = array();
        $post = $this->input->post(NULL,TRUE);
        $count=count($this->input->post('pro_id'));
        echo CI_VERSION;

        for($i = 0; $i < $count; $i++){
            $post []= array(
                'pro_id'        => $post['pro_id'][$i],
                'date_add'      => $post['date_add'][$i],
                'category'      => $post['category'][$i],
                'type'          => $post['type'][$i],
                'size'          => $post['size'][$i],
                'counts'        => $post['counts'][$i],
                'booking'       => $post['booking'][$i],
                'confirmation'  => $post['confirmation'][$i],
                'confirm_days'  => $post['confirm_days'][$i],
                'allocation'    => $post['allocation'][$i],
                'allocate_days' => $post['allocate_days'][$i],
                'm_installment' => $post['m_installment'][$i],
                'month'         => $post['month'][$i],
                'y_instalment'  => $post['y_instalment'][$i],
                'halfyear'      => $post['halfyear'][$i],
                'leveling'      => $post['leveling'][$i],
                'demarcation'   => $post['demarcation'][$i],
                'possession'    => $post['possession'][$i]
                );
        }
    $this->projects->add_payment($post);
}

My Model is:

public function add_payment($array)
{
     // echo "
";
     // print_r($array);
     // exit();
     return $this->db->insert_batch('paymentsize',$array);

}

My View is:

          <input type="hidden" name="pro_id[]"  value="<?= $project->pro_id; ?>" >

                Date
                  <input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >

                  Plot Category
                    <select name="category[]" class="form-control">
                      <option> </option>
                      <option>Residential</option>
                      <option>Commercial</option>
                    </select>

if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...

Body:
You used $post for two purpose, change your controller codes as following code:

public function store_payment()
{
    $post = $this->input->post(NULL,TRUE);
    $count=count($this->input->post('pro_id'));
    echo CI_VERSION;

    $data = array();
    for($i = 0; $i < $count; $i++){
        $data []= array(
            'pro_id'        => $post['pro_id'][$i],
            'date_add'      => $post['date_add'][$i],
            'category'      => $post['category'][$i],
            'type'          => $post['type'][$i],
            'size'          => $post['size'][$i],
            'counts'        => $post['counts'][$i],
            'booking'       => $post['booking'][$i],
            'confirmation'  => $post['confirmation'][$i],
            'confirm_days'  => $post['confirm_days'][$i],
            'allocation'    => $post['allocation'][$i],
            'allocate_days' => $post['allocate_days'][$i],
            'm_installment' => $post['m_installment'][$i],
            'month'         => $post['month'][$i],
            'y_instalment'  => $post['y_instalment'][$i],
            'halfyear'      => $post['halfyear'][$i],
            'leveling'      => $post['leveling'][$i],
            'demarcation'   => $post['demarcation'][$i],
            'possession'    => $post['possession'][$i]
            );
    }
    $this->projects->add_payment($data);
}


问:
How to use dataset to groupby
I have a request to use rdd to do so：

```<code>val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)
</code>```

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

答:
To create a data set first define a case class outside your class as

```<code>case class Employee(city: String, name: String)
</code>```

Then you can convert the list to Dataset as

```<code>  val spark =
    SparkSession.builder().master("local").appName("test").getOrCreate()
    import spark.implicits._
    val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
    ).toDF("city", "name")
    val data = test.as[Employee]
</code>```

Or

```<code>    import spark.implicits._
    val test = Seq(("New York", "Jack"),
      ("Los Angeles", "Tom"),
      ("Chicago", "David"),
      ("Houston", "John"),
      ("Detroit", "Michael"),
      ("Chicago", "Andrew"),
      ("Detroit", "Peter"),
      ("Detroit", "George")
    )

    val data = test.map(r => Employee(r._1, r._2)).toDS()
</code>```

Now you can groupby and perform any aggregation as

```<code>data.groupBy("city").count().show

data.groupBy("city").agg(collect_list("name")).show
</code>```

Hope this helps!

Title: How to use dataset to groupby

Body:
I have a request to use rdd to do so：

val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

Body:
To create a data set first define a case class outside your class as

case class Employee(city: String, name: String)

Then you can convert the list to Dataset as

  val spark =
    SparkSession.builder().master("local").appName("test").getOrCreate()
    import spark.implicits._
    val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
    ).toDF("city", "name")
    val data = test.as[Employee]

Or

    import spark.implicits._
    val test = Seq(("New York", "Jack"),
      ("Los Angeles", "Tom"),
      ("Chicago", "David"),
      ("Houston", "John"),
      ("Detroit", "Michael"),
      ("Chicago", "Andrew"),
      ("Detroit", "Peter"),
      ("Detroit", "George")
    )

    val data = test.map(r => Employee(r._1, r._2)).toDS()

Now you can groupby and perform any aggregation as

data.groupBy("city").count().show

data.groupBy("city").agg(collect_list("name")).show

Hope this helps!


问:
How does the prop `store` work in react-redux Provider?
In this tutorial, the author exports the below code and passes the entire called function, which returns an object, to the store prop in Provider. How does the runSaga part get ran? I don't see this in the docs.

```<code>const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  return {
    ...createStore(rootReducer,
      applyMiddleware(sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  };
};
</code>```

答:
I guess it's missing from the tutorial.

Look at the example at the official page of redux-saga.

The example explicitly calls the function runSaga

Body:
In this tutorial, the author exports the below code and passes the entire called function, which returns an object, to the store prop in Provider. How does the runSaga part get ran? I don't see this in the docs.

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  return {
    ...createStore(rootReducer,
      applyMiddleware(sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  };
};


问:
Disable a button when the input fields are empty in reactjs
Im new to reactJS. Im wondering why my code below doesnt work. Everything works except disabling my NEXT button when text fields are empty. My expectation is that after i fill out ALL the textboxes, the NEXT button will be enabled.

```<code>class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button}>Next</button>
                    </div>
                </form>
            </div>

    )
}
</code>```

THANKS!!!

I updated my code to this. And i tested it case by case. Only mobile works, the email and invitation code dont work for some reason.

```<code>class Registration extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            selectedGender: null,
            errors: [],
            initComplete: false
        }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this._handleInputEmailOnChange =
    this._handleInputEmailOnChange.bind(this);
    this._handleInputInvitationOnChange =
    this._handleInputInvitationOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

disable(){
    let disable = true;
    if (this.state.inputMobile || this.state.inputEmail || this.state.inputInvitation) {     //I tried && operator, still only mobile works
        disable = false;
    }
    return disable;
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputMobile: e.target.value})
}

_handleInputEmailOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputEmail: e.target.value})
}

_handleInputInvitationOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputInvitation: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={this._handleInputMobileOnChange}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={this._handleInputEmailOnChange}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={this._handleInputInvitationOnChange}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" disabled={this.disable()}>Next</button>
                    </div>
                </form>
            </div>

    )
}
</code>```

Nvm. I was being stupid. The code above works! :)))

答:
Keep a state disabled and then on change function check whether all inputs have value , then set the state disabled to false like below snippet</p>

```<code>class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false,
        disabled: true
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change = () => {
    if(this.inputMobile !== '' && this.inputEmail !== '' && this.inputInvitation != '' ) {
         this.setState({disabled: false});
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button} disabled={this.state.disabled}>Next</button>
                    </div>
                </form>
            </div>

    )
}
</code>```

Body:
Im new to reactJS. Im wondering why my code below doesnt work. Everything works except disabling my NEXT button when text fields are empty. My expectation is that after i fill out ALL the textboxes, the NEXT button will be enabled.

class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (

                <form onSubmit={this._handleSubmit}>

                        number *
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>

                        Email address *
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>

                        Invitation code
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>

       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button}>Next</button>

                </form>

    )
}

THANKS!!!

I updated my code to this. And i tested it case by case. Only mobile works, the email and invitation code dont work for some reason.

class Registration extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            selectedGender: null,
            errors: [],
            initComplete: false
        }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this._handleInputEmailOnChange =
    this._handleInputEmailOnChange.bind(this);
    this._handleInputInvitationOnChange =
    this._handleInputInvitationOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

disable(){
    let disable = true;
    if (this.state.inputMobile || this.state.inputEmail || this.state.inputInvitation) {     //I tried && operator, still only mobile works
        disable = false;
    }
    return disable;
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputMobile: e.target.value})
}

_handleInputEmailOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputEmail: e.target.value})
}

_handleInputInvitationOnChange(e){
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    this.setState({inputInvitation: e.target.value})
}

change(e){
    if("" != e.target.value){
        this.button.disabled = false;
    }
    else{
        this.button.disabled = true;
    }
}
render() {
    return (

                <form onSubmit={this._handleSubmit}>

                        number *
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={this._handleInputMobileOnChange}} defaultValue=""/>

                        Email address *
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={this._handleInputEmailOnChange}/>

                        Invitation code
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={this._handleInputInvitationOnChange}/>

       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" disabled={this.disable()}>Next</button>

                </form>

    )
}

Nvm. I was being stupid. The code above works! :)))

Body:
Keep a state disabled and then on change function check whether all inputs have value , then set the state disabled to false like below snippet

class Registration extends React.Component {
constructor (props) {
    super (props);
    this.state = {
        selectedGender: null,
        errors: [],
        initComplete: false,
        disabled: true
    }

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleInputMobileOnChange =
    this._handleInputMobileOnChange.bind(this);
    this.clearError = this.clearError.bind(this);
}
clearError () {
    this.setState({ errors: [] });
}

_handleInputMobileOnChange (e) {
    e.preventDefault();
    this.clearError();
    e.target.value = utils.removeNonNumbers(e.target.value);
    //this.setState({value: e.target.value})
}

change = () => {
    if(this.inputMobile !== '' && this.inputEmail !== '' && this.inputInvitation != '' ) {
         this.setState({disabled: false});
    }
}
render() {
    return (
            <div className="container-fluid">
                <form onSubmit={this._handleSubmit}>
                    <div className="form-group has-danger">
                        <label htmlFor="input-MobileNum">number *</label>
                        <input ref={(ref) => this.inputMobile = ref} type="tel" className={'form-control ' } id="input-MobileNum" onChange={()=>{ this._handleInputMobileOnChange; this.change.bind(this)}} defaultValue=""/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Email">Email address *</label>
                        <input ref={(ref) => this.inputEmail = ref} type="email" className={'form-control '} id="input-Email" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group has-danger">
                        <label htmlFor="input-Invitation">Invitation code</label>
                        <input ref={(ref) => this.inputInvitation = ref} type="text" className={'form-control '} id="input-Invitation" defaultValue="" onChange={()=>{ this.clearError; this.change.bind(this)}}/>
                    </div>
                    <div className="form-group cta">
       //NEXT BUTTON
                        <button type="submit" className="btn btn-primary" ref={(button) => this.button=button} disabled={this.state.disabled}>Next</button>
                    </div>
                </form>
            </div>

    )
}


问:
Authorization header not passed by ZuulProxy starting with Brixton.RC1
In switching from Spring Cloud Brixton.M5 to Brixton.RC1 my ZuulProxy no longer passes Authorization headers downstream to my proxied services.

There's various actors in play in my setup, but most all of them are fairly simple:
- AuthorizationServer: runs separately; hands out JWTs to clients
- Clients: get JWTs from OAuth server; each with access to a subset of resources.
- ResourceServers: consume JWTs for access decisions
- MyZuulProxy: proxies various resource servers; should relay JWTs.

It should be noted that MyZuulProxy has no security dependencies whatsoever; It passed the Authorization: Bearer {JWT} header it receives to the ResourceServers, pre-RC1. MyZuulProxy is explicitly not a Client itself, and does not use @EnableOAuth2SSO or similar at the moment.

What could I do to get MyZuulProxy to relay the JWTs to the ResourceServers again when using Spring Cloud Brixton.RC1?

There's very little code to post: It's just @EnableZuulProxy, @EnableAuthorizationServer and @EnableResourceServer in three different jars. My Clients are not Spring applications.

答:
Set the sensitiveHeaders globally helped me solve the issue

```<code> zuul:
  sensitiveHeaders: Cookie,Set-Cookie
</code>```

Please note that the property name is sensitiveHeaders not sensitive-headers
[I use spring-cloud-starter-zuul version:1.3.1.RELEASE ]

Body:
Set the sensitiveHeaders globally helped me solve the issue

 zuul:
  sensitiveHeaders: Cookie,Set-Cookie

Please note that the property name is sensitiveHeaders not sensitive-headers
[I use spring-cloud-starter-zuul version:1.3.1.RELEASE ]


问:
JavaScript Global variable value changes on Function value
Why am i getting two different results from the below code. The only change i am doing is passing the value to a function, in first code i am getting the value of global variable "count" as 10 and in the second code the global variables("count") value changes to 30.

            function addTen(count) {
                count = count + 20;
                return count;
            }

            var count = 10
            var result = addTen(count);
            console.log(count);    //10
            console.log(result);   //30```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>            function addTen(num) {
                count = num + 20;
                return count;
            }

            var count = 10
            var result = addTen(count);
            console.log(count);    //30
            console.log(result);   //30</code>```

答:
In your second function, the statement

```<code>count = num + 20;
</code>```

assigns to the global variable (it's the only count in scope). To make it a local variable for the function scope only, and not affect the global, use

```<code>var count = num + 20;
</code>```

In your first function, the parameter count implicitly declares such a local variable, shadowing the global variable of the same name.

Body:
Why am i getting two different results from the below code. The only change i am doing is passing the value to a function, in first code i am getting the value of global variable "count" as 10 and in the second code the global variables("count") value changes to 30.

            function addTen(count) {
                count = count + 20;
                return count;
            }

            var count = 10
            var result = addTen(count);
            console.log(count);    //10
            console.log(result);   //30

            function addTen(num) {
                count = num + 20;
                return count;
            }

            var count = 10
            var result = addTen(count);
            console.log(count);    //30
            console.log(result);   //30

Body:
In your second function, the statement

count = num + 20;

assigns to the global variable (it's the only count in scope). To make it a local variable for the function scope only, and not affect the global, use

var count = num + 20;

In your first function, the parameter count implicitly declares such a local variable, shadowing the global variable of the same name.


问:
why static method can not be called inside instance method?
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()</p>

```<code>class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)
</code>```

答:
Except for the fact they take neither the instance nor class as first argument, staticmethods are not different from instancemethods or classmethods: they are attributes of the class, and the same lookup rules apply as for any other attribute lookup. IOW: you have to look it up on either the class or an instance of it. Since you're calling from within an instancemethod, the obvious thing to do is an instance lookup, ie:

```<code>def train(self,item,cat):
    features = self.get_words(item)
</code>```

With your original code (features = get_words(...)), Python will look first for a local name (local to the function's body), then for a global (module-level) name - and fail with a NameError if it doesn't find any. Remember that in Python everything is an object (including functions, classes and modules) so everything shares the same namespace and lookup rules.

Body:
The error says that global name "get_words" is not defined. But I did define a static method named get_words. What should I do if I want to call get_words function inside train()

class classfier(object):
    def __init__(self):
        self.fc = {}
        self.cc = {}

    @staticmethod
    def get_words(item):
        words = re.split(r"\W+",item.strip())
        words =  [element.lower() for element in words if len(element)>2 and len(element)<20]
        return set(words)

    def train(self,item,cat):
        features = get_words(item)
        for f in features:
            self.incf(f,cat)
        self.incc(cat)

Body:
Except for the fact they take neither the instance nor class as first argument, staticmethods are not different from instancemethods or classmethods: they are attributes of the class, and the same lookup rules apply as for any other attribute lookup. IOW: you have to look it up on either the class or an instance of it. Since you're calling from within an instancemethod, the obvious thing to do is an instance lookup, ie:

def train(self,item,cat):
    features = self.get_words(item)

With your original code (features = get_words(...)), Python will look first for a local name (local to the function's body), then for a global (module-level) name - and fail with a NameError if it doesn't find any. Remember that in Python everything is an object (including functions, classes and modules) so everything shares the same namespace and lookup rules.


问:
SQL multi if statement
I have two tables, Data and Rate. In the Data table, I have the following info:-

As for Rate table, I hv the following info:-

The final output should be in this format:-

The conditions:-

a.  If both Local Currency and Document Current are the same, the ExRate must be equal to 1;

b.  If they are not the same, then the ExRate will be based on the Local Currency in the Rate table.

How can I generate the above output?

答:
You could use LEFT JOIN and CASE

```<code>SELECT d.*,
        CASE
            WHEN d.DocumentCurrency = r.LocalCurrency then 1
            ELSE r.ExRate
        END AS ExRate
FROM Data d
LEFT JOIN Rate r on d.DocumentCurrency = r.DocumentCurrency
                    AND d.LocalCurrency = r.LocalCurrency
</code>```

Title: SQL multi if statement

Body:
You could use LEFT JOIN and CASE

SELECT d.*,
        CASE
            WHEN d.DocumentCurrency = r.LocalCurrency then 1
            ELSE r.ExRate
        END AS ExRate
FROM Data d
LEFT JOIN Rate r on d.DocumentCurrency = r.DocumentCurrency
                    AND d.LocalCurrency = r.LocalCurrency


问:
How to write Query in Yii
how to write this in yii</p>

```<code>SELECT schedule.checkin, schedule.checkout, schedule.days,
employee.firstname, employee.lastname, week.start_date, week.end_date
FROM schedule
INNER JOIN employee_schedule
ON schedule.id=employee_schedule.sched_id
INNER JOIN employee
ON employee.id=employee_schedule.emp_id
INNER JOIN week
ON week.id=employee_schedule.week_id
</code>```

答:
```<code>Yii::app()->db->createCommand("your query")->queryScalar();
</code>```

can try this too

Title: How to write Query in Yii

Body:
how to write this in yii

SELECT schedule.checkin, schedule.checkout, schedule.days,
employee.firstname, employee.lastname, week.start_date, week.end_date
FROM schedule
INNER JOIN employee_schedule
ON schedule.id=employee_schedule.sched_id
INNER JOIN employee
ON employee.id=employee_schedule.emp_id
INNER JOIN week
ON week.id=employee_schedule.week_id

Body:
Yii::app()->db->createCommand("your query")->queryScalar();

can try this too


问:
Bazel build rules for BLAS & LAPACK
I have not found any project/repo providing Bazel build rules for Blas or Lapack.
This is quite unfortunate as these tools are often the primary libraries one must use for project oriented towards numerical computations.<br>
Does such thing already exist somewhere? </p>

答:
I am not aware of BUILD files for these libraries either.

If you do create them, sharing them publicly or trying to submit them upstream (in the library code) will be a great way for others to benefit from your efforts.

Title: Bazel build rules for BLAS & LAPACK

Body:
I have not found any project/repo providing Bazel build rules for Blas or Lapack.
This is quite unfortunate as these tools are often the primary libraries one must use for project oriented towards numerical computations.

Does such thing already exist somewhere?


问:
Is there "Java Bean" like technology in PHP?
Is there something like the Java Bean stuff in PHP? Thank you.</p>

答: Just going off the info you provided, if by similar to JavaBeans you mean a reusable directory of classes and objects that conform to reasonably unified standards then the closest thing I think would be PEAR.</p>


问:
Find and replace current cell value with cell number
I'm very new to VBA.  I've tried recording my Macro and still can't seem to figure it out.

I want the macro to the following:

On the selected cell I want to search the value and replace what is found by the selected cell "number".

Example : Say I select Cell A1 and its value is 666 I want it to search and replace all Cells on the sheet that contain 666 with "=A1".

In essence I want them all to point to the initial cell.

Thanks for any help.

答:
Basically, you loop through the cells in the used range on the current sheet and replace the cell values. Below is the code that will do what you're after. I commented each line to make clear what exactly is happening.

```<code>Sub Test()
'Range variable to use for looping
Dim rng As Range

'String variable for finding the values.
Dim searchvalue As String

'We'll loop on the current sheet
With ActiveSheet

    'You need to have a single cell selected, if that's not the case we exit the macro.
    If Selection.Count > 1 Then Exit Sub

    'Get the value to search for
    searchvalue = Selection.value

    'Loop over all cells in the sheet that have values.
    For Each rng In .UsedRange

        'We do not want to overwrite the range from where we search (the selection)
        If Intersect(rng, Selection) Is Nothing Then

             'And if we find the value that was in the selection
            If rng.value = searchvalue Then

                Then create the =cell we selected formula.
                rng.value = "=" & Selection.Address '
            End If
        End If

    'Next cell in the loop
    Next rng

'And we don't need the activesheet anymore.
End With
End Sub
</code>```

Since this is quite generic stuff, I'd suggest you read up on Excel VBA programming in general. Some great resources are:

Ozgrid

Rondebruin his website

Chip Pearson his website

Body:
Basically, you loop through the cells in the used range on the current sheet and replace the cell values. Below is the code that will do what you're after. I commented each line to make clear what exactly is happening.

Sub Test()
'Range variable to use for looping
Dim rng As Range

'String variable for finding the values.
Dim searchvalue As String

'We'll loop on the current sheet
With ActiveSheet

    'You need to have a single cell selected, if that's not the case we exit the macro.
    If Selection.Count > 1 Then Exit Sub

    'Get the value to search for
    searchvalue = Selection.value

    'Loop over all cells in the sheet that have values.
    For Each rng In .UsedRange

        'We do not want to overwrite the range from where we search (the selection)
        If Intersect(rng, Selection) Is Nothing Then

             'And if we find the value that was in the selection
            If rng.value = searchvalue Then

                Then create the =cell we selected formula.
                rng.value = "=" & Selection.Address '
            End If
        End If

    'Next cell in the loop
    Next rng

'And we don't need the activesheet anymore.
End With
End Sub

Since this is quite generic stuff, I'd suggest you read up on Excel VBA programming in general. Some great resources are:

Ozgrid

Rondebruin his website

Chip Pearson his website


问:
sum over past window-size dates per group
The problem is similar to How do I do a conditional sum which only looks between certain date criteria but slightly different and the answer from that does not fit into current problem. The main difference is that the date column based on each group may not necessarily be complete (i.e., certain date may be missing)

Input:

```<code>input <- read.table(text="
2017-04-01     A     1
2017-04-02     B     2
2017-04-02     B     2
2017-04-02     C     2
2017-04-02     A     2
2017-04-03     C     3
2017-04-04     A     4
2017-04-05     B     5
2017-04-06     C     6
2017-04-07     A     7
2017-04-08     B     8
2017-04-09     C     9")
colnames(input) <- c("Date","Group","Score")
</code>```

Rule: for each group at each date, looking back 3 calendar dates (include current date). calculate the sum.

Expected output:

```<code>    Date Group 3DaysSumPerGroup
    2017-04-01     A                1 #1  previous two dates are not available. partial is allowed
    2017-04-02     A                3 #2+1 both 4-01 and 4-02 are in the range
    2017-04-04     A                6 #4+2
    2017-04-07     A                7 #7
    2017-04-02     B                4 # 2+2 at the same day
    2017-04-05     B                5
    2017-04-08     B                8
    2017-04-02     C                2
    2017-04-03     C                5
    2017-04-06     C                6
    2017-04-09     C                9
</code>```

I tried to use rollapply with partial=T, but result doesn't seem correct.

```<code> input %>%
     group_by(Group) %>%
     arrange(Date) %>% mutate("3DaysSumPerGroup"=rollapply(data=Score,width=3,align="right",FUN=sum,partial=T,fill=NA,rm.na=T))
</code>```

答:
Here's a (supposedly efficient) solution using the new non-equi joins and the by = .EACHI features in data.table (v1.9.8+)

```<code>library(data.table) #v1.10.4

## Convert to a proper date class, and add another column in order to define the range
setDT(input)[, c("Date", "Date2") := {
  Date = as.IDate(Date)
  Date2 = Date - 2L
  .(Date, Date2)
}]

## Run a non-equi join against the unique Date/Group combination in input
## Sum the Scores on the fly
## You can ignore the second Date column

input[unique(input, by = c("Date", "Group")), ## This removes the dupes
      on = .(Group, Date <= Date, Date >= Date2), ## The join condition
      .(Score = sum(Score)), ## sum the scores
      keyby = .EACHI] ## Run the sum by each row in unique(input, by = c("Date", "Group"))

#     Group       Date       Date Score
#  1:     A 2017-04-01 2017-03-30     1
#  2:     A 2017-04-02 2017-03-31     3
#  3:     A 2017-04-04 2017-04-02     6
#  4:     A 2017-04-07 2017-04-05     7
#  5:     B 2017-04-02 2017-03-31     4
#  6:     B 2017-04-05 2017-04-03     5
#  7:     B 2017-04-08 2017-04-06     8
#  8:     C 2017-04-02 2017-03-31     2
#  9:     C 2017-04-03 2017-04-01     5
# 10:     C 2017-04-06 2017-04-04     6
# 11:     C 2017-04-09 2017-04-07     9
</code>```

Body:
The problem is similar to How do I do a conditional sum which only looks between certain date criteria but slightly different and the answer from that does not fit into current problem. The main difference is that the date column based on each group may not necessarily be complete (i.e., certain date may be missing)

Input:

input <- read.table(text="
2017-04-01     A     1
2017-04-02     B     2
2017-04-02     B     2
2017-04-02     C     2
2017-04-02     A     2
2017-04-03     C     3
2017-04-04     A     4
2017-04-05     B     5
2017-04-06     C     6
2017-04-07     A     7
2017-04-08     B     8
2017-04-09     C     9")
colnames(input) <- c("Date","Group","Score")

Rule: for each group at each date, looking back 3 calendar dates (include current date). calculate the sum.

Expected output:

    Date Group 3DaysSumPerGroup
    2017-04-01     A                1 #1  previous two dates are not available. partial is allowed
    2017-04-02     A                3 #2+1 both 4-01 and 4-02 are in the range
    2017-04-04     A                6 #4+2
    2017-04-07     A                7 #7
    2017-04-02     B                4 # 2+2 at the same day
    2017-04-05     B                5
    2017-04-08     B                8
    2017-04-02     C                2
    2017-04-03     C                5
    2017-04-06     C                6
    2017-04-09     C                9

I tried to use rollapply with partial=T, but result doesn't seem correct.

 input %>%
     group_by(Group) %>%
     arrange(Date) %>% mutate("3DaysSumPerGroup"=rollapply(data=Score,width=3,align="right",FUN=sum,partial=T,fill=NA,rm.na=T))

Body:
Here's a (supposedly efficient) solution using the new non-equi joins and the by = .EACHI features in data.table (v1.9.8+)

library(data.table) #v1.10.4

## Convert to a proper date class, and add another column in order to define the range
setDT(input)[, c("Date", "Date2") := {
  Date = as.IDate(Date)
  Date2 = Date - 2L
  .(Date, Date2)
}]

## Run a non-equi join against the unique Date/Group combination in input
## Sum the Scores on the fly
## You can ignore the second Date column

input[unique(input, by = c("Date", "Group")), ## This removes the dupes
      on = .(Group, Date <= Date, Date >= Date2), ## The join condition
      .(Score = sum(Score)), ## sum the scores
      keyby = .EACHI] ## Run the sum by each row in unique(input, by = c("Date", "Group"))

#     Group       Date       Date Score
#  1:     A 2017-04-01 2017-03-30     1
#  2:     A 2017-04-02 2017-03-31     3
#  3:     A 2017-04-04 2017-04-02     6
#  4:     A 2017-04-07 2017-04-05     7
#  5:     B 2017-04-02 2017-03-31     4
#  6:     B 2017-04-05 2017-04-03     5
#  7:     B 2017-04-08 2017-04-06     8
#  8:     C 2017-04-02 2017-03-31     2
#  9:     C 2017-04-03 2017-04-01     5
# 10:     C 2017-04-06 2017-04-04     6
# 11:     C 2017-04-09 2017-04-07     9


问:
Is it possible to restore a Joomla 2.5 backup on a new Joomla 3.7 server using akeeba
I have my web site running on Joomla 2.5.22, I made backup using Akeeba but I didn't make backup from Cpanel (I mean zipping all these files in cPanel).

Now I have to move to a new server and decide to upgrade to Joomla 3.7.1.
The backup (the JPA file) is already in the new server.

What should I do now?
- Should I kickstart it using Akeeba kickstart and upgrade it
- or should I install a new Joomla 3.7.1 first and restore my backup of joomla 2.5.22 on it.

I'm afraid of the second solution to work well !!!

Please I need suggestion what to do?

答:
No you cannot.

When you restore a backup made with Akeeba Backup, you are basically installing a new site which already contains your content and extensions.

If the webspace already contains a J3.7 site, that site is going to be overwritten (and in fact it may create troubles to have mixed files from different versions of Joomla, so it's probably best to clean up the webspace first).

You should just restore the J2.5 site, by using the kickstart tool from Akeeba.

After you are finished successfully and your J2.5 site is running fine on the new hosting, you can upgrade Joomla to 3.x following the guide https://docs.joomla.org/Joomla_2.5_to_3.x_Step_by_Step_Migration.


问:
What is the differences between updateOrCreate() and updateOrInsert() in Laravel
Both methods seem to create a new record if not existed or update a record with provided data. Whats the difference between the two?</p>

答:
updateOrCreate is method of Eloquent Builder and updateOrInsert is method of Query Builder.

updateOrCreate returns model, whereas updateOrInsert returns boolean

Signatures from Laravel code:

updateOrCreate

```<code>/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model|static
 */
public function updateOrCreate(array $attributes, array $values = [])
</code>```

updateOrInsert

```<code>/**
 * Insert or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return bool
 */
public function updateOrInsert(array $attributes, array $values = [])
</code>```

Body:
updateOrCreate is method of Eloquent Builder and updateOrInsert is method of Query Builder.

updateOrCreate returns model, whereas updateOrInsert returns boolean

Signatures from Laravel code:

updateOrCreate

/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model|static
 */
public function updateOrCreate(array $attributes, array $values = [])

updateOrInsert

/**
 * Insert or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return bool
 */
public function updateOrInsert(array $attributes, array $values = [])


问:
Creating and storing values of class objects from a text file
I am trying to find a way to creat class instances from a file and also to use that file as a way to give the class properties their values. I can manually put all the information in but it will be better to do it through a file so I can alter the file, which will alter the program for me.

Here is the code so far... When I run it, it says

```<code>class Program
{
    class dish
{
     public class starters { public string starter; public string alteration; }

    static void Main(string[] args)
    {
        List<dish.starters> starter = new List<dish.starters>();
        using (StreamReader reader = File.OpenText(@"D:\Visual Studio\Projects\Bella Italia\Food\Starters.txt"))
        {
            IDictionary<string, dish.starters> value = new Dictionary<string, dish.starters>();
            while (!reader.EndOfStream)
            {
                value[reader.ReadLine()] = new dish.starters();
                value[reader.ReadLine()].starter = reader.ReadLine();
            }
            foreach(var x in value.Values)
            {
                Console.WriteLine(x.starter);
            }

        }

        Console.ReadLine();

    }
}
</code>```

}

When I try to run it, it says

Exception Unhandled
System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'

答:
You are reading two consecutive line here. The second line probably doesn't have an associated entry in the dictionary (and you don't want that duplication either):

```<code>value[reader.ReadLine() /*one*/] = new dish.starters();
value[reader.ReadLine() /*two*/].starter = reader.ReadLine();
</code>```

Store the key in a variable and reuse that:

```<code>string key = reader.ReadLine();

value[key] = new dish.starters();
value[key].starter = reader.ReadLine();
</code>```

Or create the object and assign later:

```<code>string key = reader.ReadLine();

var starters = new dish.starters();
starters.starter = reader.ReadLine()

value[key] = starters;
</code>```

Body:
I am trying to find a way to creat class instances from a file and also to use that file as a way to give the class properties their values. I can manually put all the information in but it will be better to do it through a file so I can alter the file, which will alter the program for me.

Here is the code so far... When I run it, it says

class Program
{
    class dish
{
     public class starters { public string starter; public string alteration; }

    static void Main(string[] args)
    {
        List<dish.starters> starter = new List<dish.starters>();
        using (StreamReader reader = File.OpenText(@"D:\Visual Studio\Projects\Bella Italia\Food\Starters.txt"))
        {
            IDictionary<string, dish.starters> value = new Dictionary<string, dish.starters>();
            while (!reader.EndOfStream)
            {
                value[reader.ReadLine()] = new dish.starters();
                value[reader.ReadLine()].starter = reader.ReadLine();
            }
            foreach(var x in value.Values)
            {
                Console.WriteLine(x.starter);
            }

        }

        Console.ReadLine();

    }
}

}

When I try to run it, it says

Exception Unhandled
System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'

Body:
You are reading two consecutive line here. The second line probably doesn't have an associated entry in the dictionary (and you don't want that duplication either):

value[reader.ReadLine() /*one*/] = new dish.starters();
value[reader.ReadLine() /*two*/].starter = reader.ReadLine();

Store the key in a variable and reuse that:

string key = reader.ReadLine();

value[key] = new dish.starters();
value[key].starter = reader.ReadLine();

Or create the object and assign later:

string key = reader.ReadLine();

var starters = new dish.starters();
starters.starter = reader.ReadLine()

value[key] = starters;


问:
How can I assign access to an application provisioned in Azure via the Graph API?
We have several applications that rely on Azure AD to provision access. Having to manually assign access to each individual user is long-winded and I was looking to automate this process via the Graph API.

I'm using PowerShell to do so and I can successfully authenticate with the API and make calls to identify users etc.

What I'm struggling with is assigning access to an application programmatically.

According to the documentation this appears to only exist in the Beta version.
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/approleassignment_update

However when I use the Graph Explorer this method is not shown by intellisense.
https://developer.microsoft.com/en-us/graph/graph-explorer

If I try to call it anyway I get the error:

Unsupported segment type

This suggests to me that this method does not exist and was simply not removed from the documentation.

There's an open issue on the GitHub for Graph HERE.

There are some SO threads that had a reply from an MSFT and then no resolution HERE

I found a C# sample which looks like it might do this but it obscures the details away behind libraries and I don't want to maintain a C# application.

I cannot find any information on whether this is even possible via the Graph API. Given that some of these posts are a year old I'd be surprised if Microsoft hadn't moved forward with this. All I can see are documents referring to the old Graph API which AFAIK is no longer used.

Is is possible to assign access to an application provisioned in Azure using just REST and the Graph API?

答:
Based on my understanding, we can use the Azure Graph REST to achieve the same goal.

Here is the code for your reference:

```<code>public async void AssignRoleToUser()
{
    var client = GraphHelper.CreateGraphClient();

    ServicePrincipal servicePrincipal = (ServicePrincipal)client.ServicePrincipals.GetByObjectId("d90b4929-a2d5-43bc-8fc0-1e0adb640575").ExecuteAsync().Result;

    Microsoft.Azure.ActiveDirectory.GraphClient.User user =(Microsoft.Azure.ActiveDirectory.GraphClient.User)client.Users.GetByObjectId("b2d2cadd-21f5-4021-beb5-7b23ebd5364c").ExecuteAsync().Result;

    AppRoleAssignment appRoleAssignment = new AppRoleAssignment();

    // just use a known appRole id for this example
    appRoleAssignment.Id = servicePrincipal.AppRoles.FirstOrDefault().Id;

    // the service principal to add the group with the app role
    appRoleAssignment.ResourceId = Guid.Parse(servicePrincipal.ObjectId);

    appRoleAssignment.PrincipalType = "User";

    // the id of the user
    appRoleAssignment.PrincipalId = Guid.Parse("b2d2cadd-21f5-4021-beb5-7b23ebd5364c");

    user.AppRoleAssignments.Add(appRoleAssignment);
    await user.UpdateAsync();

}
</code>```

In addition, if you doesn't sepcify the customization role, you must use the default id (zero GUID).

More detail about Azure AD Graph entity reference, you can refer here.

Update

```<code>POST:https://graph.windows.net/{tenantId}/directoryObjects/{userId}/Microsoft.DirectoryServices.User/appRoleAssignments?api-version=1.6

{
    "odata.type":"Microsoft.DirectoryServices.AppRoleAssignment",
    "id":"{roleId}",
    "principalId":"{userId}",
    "principalType":"User",
    "resourceId":"{servicePrincipalId}"
}
</code>```

Body:
Based on my understanding, we can use the Azure Graph REST to achieve the same goal.

Here is the code for your reference:

public async void AssignRoleToUser()
{
    var client = GraphHelper.CreateGraphClient();

    ServicePrincipal servicePrincipal = (ServicePrincipal)client.ServicePrincipals.GetByObjectId("d90b4929-a2d5-43bc-8fc0-1e0adb640575").ExecuteAsync().Result;

    Microsoft.Azure.ActiveDirectory.GraphClient.User user =(Microsoft.Azure.ActiveDirectory.GraphClient.User)client.Users.GetByObjectId("b2d2cadd-21f5-4021-beb5-7b23ebd5364c").ExecuteAsync().Result;

    AppRoleAssignment appRoleAssignment = new AppRoleAssignment();

    // just use a known appRole id for this example
    appRoleAssignment.Id = servicePrincipal.AppRoles.FirstOrDefault().Id;

    // the service principal to add the group with the app role
    appRoleAssignment.ResourceId = Guid.Parse(servicePrincipal.ObjectId);

    appRoleAssignment.PrincipalType = "User";

    // the id of the user
    appRoleAssignment.PrincipalId = Guid.Parse("b2d2cadd-21f5-4021-beb5-7b23ebd5364c");

    user.AppRoleAssignments.Add(appRoleAssignment);
    await user.UpdateAsync();

}

In addition, if you doesn't sepcify the customization role, you must use the default id (zero GUID).

More detail about Azure AD Graph entity reference, you can refer here.

Update

POST:https://graph.windows.net/{tenantId}/directoryObjects/{userId}/Microsoft.DirectoryServices.User/appRoleAssignments?api-version=1.6

{
    "odata.type":"Microsoft.DirectoryServices.AppRoleAssignment",
    "id":"{roleId}",
    "principalId":"{userId}",
    "principalType":"User",
    "resourceId":"{servicePrincipalId}"
}