问:
Draw text on a 3D plane sharpDX
I searched and didn't find a way to do that.
I want to attach labels to 3D objects using sharpDX in HoloLens app.

anyone knows how?

thanks

edit:
so I decided to convert the text to image and then put it as texture on a plane made of 2 triangles mesh.
so now I tried this code:
https://gist.github.com/naveedmurtuza/6600103

but can't include the references, how do I fix that?

thanks

答:
I wrote a game using SharpDx a few years ago, here's a video of it:

https://www.youtube.com/watch?v=tDRmIY6-8Z4

If I understand you correctly, you want 3D-texts just as the ones I'm using to explain the game elements? If so, you might get some ideas from this source code:

```<code>protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap)
        {
            if (drawingReason != DrawingReason.Normal)
                return true;

            camera.UpdateEffect(Effect);
            foreach (var item in Items)
            {
                Effect.World = Matrix.BillboardRH(item.Target.Position + item.GetOffset(item), camera.Position, -camera.Up, camera.Front);
                Effect.DiffuseColor = item.GetColor(item);
                SpriteBatch.Begin(SpriteSortMode.Deferred, Effect.GraphicsDevice.BlendStates.NonPremultiplied, null, Effect.GraphicsDevice.DepthStencilStates.DepthRead, null, Effect.Effect);
                SpriteBatch.DrawString(Font, item.Text, Vector2.Zero, Color.Black, 0, Font.MeasureString(item.Text) / 2, item.GetSize(item), 0, 0);
                SpriteBatch.End();
            }

            Effect.GraphicsDevice.SetDepthStencilState(Effect.GraphicsDevice.DepthStencilStates.Default);
            Effect.GraphicsDevice.SetBlendState(Effect.GraphicsDevice.BlendStates.Opaque);

            return true;
        }
</code>```

Full game code is open source and available here:
https://github.com/danbystrom/Larv/blob/master/src/factor10.VisionThing/FloatingText/FloatingTexts.cs#L32

Title: Draw text on a 3D plane sharpDX

Body:
I wrote a game using SharpDx a few years ago, here's a video of it:

https://www.youtube.com/watch?v=tDRmIY6-8Z4

If I understand you correctly, you want 3D-texts just as the ones I'm using to explain the game elements? If so, you might get some ideas from this source code:

protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap)
        {
            if (drawingReason != DrawingReason.Normal)
                return true;

            camera.UpdateEffect(Effect);
            foreach (var item in Items)
            {
                Effect.World = Matrix.BillboardRH(item.Target.Position + item.GetOffset(item), camera.Position, -camera.Up, camera.Front);
                Effect.DiffuseColor = item.GetColor(item);
                SpriteBatch.Begin(SpriteSortMode.Deferred, Effect.GraphicsDevice.BlendStates.NonPremultiplied, null, Effect.GraphicsDevice.DepthStencilStates.DepthRead, null, Effect.Effect);
                SpriteBatch.DrawString(Font, item.Text, Vector2.Zero, Color.Black, 0, Font.MeasureString(item.Text) / 2, item.GetSize(item), 0, 0);
                SpriteBatch.End();
            }

            Effect.GraphicsDevice.SetDepthStencilState(Effect.GraphicsDevice.DepthStencilStates.Default);
            Effect.GraphicsDevice.SetBlendState(Effect.GraphicsDevice.BlendStates.Opaque);

            return true;
        }

Full game code is open source and available here:
https://github.com/danbystrom/Larv/blob/master/src/factor10.VisionThing/FloatingText/FloatingTexts.cs#L32


来源: stackexchange

问:
How to stop chrome from auto reloading tab when it stays open longer?
I've been using Window 7. It is just a bit annoying when tab is auto reloaded in Chrome browser when tab is kept open for longer. It always loses my data when page is auto reloaded.

Do you have any advise to stop this Chrome's behavior?

Thanks in advance.

答:
you can disable this feature of chrome by going to this url :
*

chrome://flags/#automatic-tab-discarding

*

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

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

Result: abcnull

答:
String Concatenation in Java executes automatic conversion. The null string will be converted to the string 'null'. For reference, see f.e. this page:

A null operand is converted to the
  string literal "null".

To avoid this, you should check if one string is null yourself.

ContentLicense: CC BY-SA 2.5

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull


问:
Exception in thread "main" java.net.UnknownHostException: services.gradle.org
I am getting the below error when executing gradle.bat. I have checked the URL path and it looks fine. The URL is defined like this in the wrapper properties:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.1-bin.zip
</code>```

Here's the error message:

```<code>Downloading https://services.gradle.org/distributions/gradle-2.1-bin.zip
Exception in thread "main" java.net.UnknownHostException: services.gradle.org at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)
</code>```

Could someone help me on this?

答:
1) Go to your project directory

2) Find below file on your project directory:

```<code>gradlew
gradlew.bat
</code>```

3) Edit gradlew file and change DEFAULT_JVM_OPTS variable value as below:

```<code>DEFAULT_JVM_OPTS="-Dhttp.proxyHost=XXXX -Dhttp.proxyPort=XXXX -Dhttp.proxyUser=XXXX -Dhttp.proxyPassword=XXXX  -Dhttps.proxyHost=XXXX -Dhttps.proxyPort=XXXX -Dhttps.proxyUser=XXXX-Dhttps.proxyPassword=XXXX"
</code>```

save it.

4) Edit gradlew.bat file and change DEFAULT_JVM_OPTS variable value as below:

```<code>set DEFAULT_JVM_OPTS=-Dhttp.proxyHost=XXXX -Dhttp.proxyPort=XXXX -Dhttp.proxyUser=XXXX -Dhttp.proxyPassword=XXXX  -Dhttps.proxyHost=XXXX -Dhttps.proxyPort=XXXX -Dhttps.proxyUser=XXXX-Dhttps.proxyPassword=XXXX
</code>```

save it.

5) Now run your "gradlew clean build" and check.

Please set your appropriate value on the place of XXXX

Note: gradlew is use for linux system user and gradlew.bat is user for window system user

Body:
I am getting the below error when executing gradle.bat. I have checked the URL path and it looks fine. The URL is defined like this in the wrapper properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.1-bin.zip

Here's the error message:

Downloading https://services.gradle.org/distributions/gradle-2.1-bin.zip
Exception in thread "main" java.net.UnknownHostException: services.gradle.org at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195)

Could someone help me on this?

Body:
1) Go to your project directory

2) Find below file on your project directory:

gradlew
gradlew.bat

3) Edit gradlew file and change DEFAULT_JVM_OPTS variable value as below:

DEFAULT_JVM_OPTS="-Dhttp.proxyHost=XXXX -Dhttp.proxyPort=XXXX -Dhttp.proxyUser=XXXX -Dhttp.proxyPassword=XXXX  -Dhttps.proxyHost=XXXX -Dhttps.proxyPort=XXXX -Dhttps.proxyUser=XXXX-Dhttps.proxyPassword=XXXX"

save it.

4) Edit gradlew.bat file and change DEFAULT_JVM_OPTS variable value as below:

set DEFAULT_JVM_OPTS=-Dhttp.proxyHost=XXXX -Dhttp.proxyPort=XXXX -Dhttp.proxyUser=XXXX -Dhttp.proxyPassword=XXXX  -Dhttps.proxyHost=XXXX -Dhttps.proxyPort=XXXX -Dhttps.proxyUser=XXXX-Dhttps.proxyPassword=XXXX

save it.

5) Now run your "gradlew clean build" and check.

Please set your appropriate value on the place of XXXX

Note: gradlew is use for linux system user and gradlew.bat is user for window system user


问:
Unable to locate element when element is still present

Driver is unable to find element on the page even when its present
  . Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code  :

```<code>System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        //driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.get("https://www.sportskeeda.com/wwe");
        //WebElement popup=driver.findElement(By.className("bullbg"));
        WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));

        if (popup.isDisplayed())
        {

            System.out.println("True");
        }
        else
        {

            System.out.println("False");
        }
</code>```

ERROR

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to locate element: //div[contains(text(),'Close')]

Please click here to check there is a popup which gets display

答:
Use Instead:

Boolean popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]")).isDisplayed();

if (popup == true)
        {

```<code>        System.out.println("True");
    }
    else
    {

        System.out.println("False");
    }
</code>```

Body:
Driver is unable to find element on the page even when its present
  . Basically Im just trying that when a popup (ad popup which we see in many website) is present it should get clicked. Below is the code  :

System.setProperty("webdriver.gecko.driver","C:\\SeleniumDriver\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        //driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
        driver.get("https://www.sportskeeda.com/wwe");
        //WebElement popup=driver.findElement(By.className("bullbg"));
        WebElement popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]"));

        if (popup.isDisplayed())
        {

            System.out.println("True");
        }
        else
        {

            System.out.println("False");
        }

ERROR

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to locate element: //div[contains(text(),'Close')]

Please click here to check there is a popup which gets display

Body:
Use Instead:

Boolean popup=driver.findElement(By.xpath("//div[contains(text(),'Close')]")).isDisplayed();

if (popup == true)
        {

        System.out.println("True");
    }
    else
    {

        System.out.println("False");
    }


问:
Pandas length mismatch
I'm trying to run this code but it gives me the same error everytime.

```<code>def concatenate(indir="E:\\HOME\\NBAStats\\PlayByPlay",outfile="E:\\HOME\\NBAStats\\PlayByPlay\\Concatenated.csv",sep='\t'):
        os.chdir(indir)
        filelist=glob.glob("*.csv")
        dflist=[]
        colnames=['game_id', 'data_set', 'date', 'a1', 'a2', 'a3', 'a4', 'a5', 'h1', 'h2', 'h3', 'h4', 'h5', 'period', 'away_score', 'home_score', 'remaining_time', 'elapsed', 'play_length', 'play_id', 'team', 'event_type', 'assist', 'away', 'home', 'block', 'entered', 'left', 'num', 'opponent', 'outof', 'player', 'points', 'possession', 'reason', 'result', 'steal', 'type', 'shot_distance', 'original_x', 'original_y', 'converted_x', 'converted_y', 'description']
        for filename in filelist:
            print(filename)
            df=pandas.read_table(filename, header=None)
            dflist.append(df)
        concatdf=pandas.concat(dflist,axis=0)
        print(type(concatdf))
        concatdf.columns=colnames
        concatdf.head()
        concatdf.to_csv(outfile,index=False)
</code>```

The error is:

ValueError: Length mismatch: Expected axis has 1 elements, new values
  have 44 elements

答:
This is the Vale error occuring using read_csv instead of read_table</p>

```<code>>        File "<ipython-input-8-24ad9c1ee739>", line 1, in <module>
>     runfile('C:/Users/Fede/ToConcatenateNBA.py', wdir='C:/Users/Fede')
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 880, in runfile
>     execfile(filename, namespace)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 102, in execfile
>     exec(compile(f.read(), filename, 'exec'), namespace)
>
>   File "C:/Users/Fede/ToConcatenateNBA.py", line 29, in <module>
>     concatenate()
>
>   File "C:/Users/Fede/ToConcatenateNBA.py", line 25, in concatenate
>     concatdf.columns=colnames
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\generic.py",
> line 2983, in __setattr__
>     return object.__setattr__(self, name, value)
>
>   File "pandas\_libs\src\properties.pyx", line 65, in
> pandas._libs.lib.AxisProperty.__set__ (pandas\_libs\lib.c:45103)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\generic.py",
> line 471, in _set_axis
>     self._data.set_axis(axis, labels)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\internals.py",
> line 2836, in set_axis
>     (old_len, new_len))
>
> ValueError: Length mismatch: Expected axis has 46 elements, new values
> have 44 elements
</code>```

Title: Pandas length mismatch

Body:
I'm trying to run this code but it gives me the same error everytime.

def concatenate(indir="E:\\HOME\\NBAStats\\PlayByPlay",outfile="E:\\HOME\\NBAStats\\PlayByPlay\\Concatenated.csv",sep='\t'):
        os.chdir(indir)
        filelist=glob.glob("*.csv")
        dflist=[]
        colnames=['game_id', 'data_set', 'date', 'a1', 'a2', 'a3', 'a4', 'a5', 'h1', 'h2', 'h3', 'h4', 'h5', 'period', 'away_score', 'home_score', 'remaining_time', 'elapsed', 'play_length', 'play_id', 'team', 'event_type', 'assist', 'away', 'home', 'block', 'entered', 'left', 'num', 'opponent', 'outof', 'player', 'points', 'possession', 'reason', 'result', 'steal', 'type', 'shot_distance', 'original_x', 'original_y', 'converted_x', 'converted_y', 'description']
        for filename in filelist:
            print(filename)
            df=pandas.read_table(filename, header=None)
            dflist.append(df)
        concatdf=pandas.concat(dflist,axis=0)
        print(type(concatdf))
        concatdf.columns=colnames
        concatdf.head()
        concatdf.to_csv(outfile,index=False)

The error is:

ValueError: Length mismatch: Expected axis has 1 elements, new values
  have 44 elements

Body:
This is the Vale error occuring using read_csv instead of read_table

>        File "<ipython-input-8-24ad9c1ee739>", line 1, in <module>
>     runfile('C:/Users/Fede/ToConcatenateNBA.py', wdir='C:/Users/Fede')
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 880, in runfile
>     execfile(filename, namespace)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 102, in execfile
>     exec(compile(f.read(), filename, 'exec'), namespace)
>
>   File "C:/Users/Fede/ToConcatenateNBA.py", line 29, in <module>
>     concatenate()
>
>   File "C:/Users/Fede/ToConcatenateNBA.py", line 25, in concatenate
>     concatdf.columns=colnames
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\generic.py",
> line 2983, in __setattr__
>     return object.__setattr__(self, name, value)
>
>   File "pandas\_libs\src\properties.pyx", line 65, in
> pandas._libs.lib.AxisProperty.__set__ (pandas\_libs\lib.c:45103)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\generic.py",
> line 471, in _set_axis
>     self._data.set_axis(axis, labels)
>
>   File
> "C:\Users\Fede\Anaconda3\lib\site-packages\pandas\core\internals.py",
> line 2836, in set_axis
>     (old_len, new_len))
>
> ValueError: Length mismatch: Expected axis has 46 elements, new values
> have 44 elements


问:
Bootstrap 3 Grid: Responsive Position Absolute Bottom Width Issue
I need to position an element at the bottom of a container which is using the Bootstrap grid.

The issue I'm having is that the anchor is spanning outside of the parent width. I need the anchor to span 100% and remain within the width of the parent div content-wrapper.

I need to keep the 15px padding on each side of the button that comes from the parent container.

Here is a screenshot of the issue:

HTML:

```<code><div class="content-wrapper col-xs-12">
  <div class="content">
    <a class="button" href="#">See more</a>
  </div>
</div>
</code>```

CSS:

```<code>.content-wrapper {
  width: 100%;
  height: 450px;
  background-color: gray;
  position: relative;
}

.button {
  display: block;
  background: black;
  width: 100%;
  text-align: center;
  height: 50px;
  padding-top: 13px;
  position: absolute;
  bottom: 0;
}
</code>```

Here is a JSFIDDLE to see the issue in action.

答:
Just add left:0 to your .button class

```<code>.button {
  display: block;
  background: black;
  width: 100%;
  text-align: center;
  height: 50px;
  padding-top: 13px;
  position: absolute;
  bottom: 0;
  left: 0;
}
</code>```

Body:
I need to position an element at the bottom of a container which is using the Bootstrap grid.

The issue I'm having is that the anchor is spanning outside of the parent width. I need the anchor to span 100% and remain within the width of the parent div content-wrapper.

I need to keep the 15px padding on each side of the button that comes from the parent container.

Here is a screenshot of the issue:

HTML:

    See more

CSS:

.content-wrapper {
  width: 100%;
  height: 450px;
  background-color: gray;
  position: relative;
}

.button {
  display: block;
  background: black;
  width: 100%;
  text-align: center;
  height: 50px;
  padding-top: 13px;
  position: absolute;
  bottom: 0;
}

Here is a JSFIDDLE to see the issue in action.

Body:
Just add left:0 to your .button class

.button {
  display: block;
  background: black;
  width: 100%;
  text-align: center;
  height: 50px;
  padding-top: 13px;
  position: absolute;
  bottom: 0;
  left: 0;
}


问:
How can I use Guzzle to send a POST request in JSON?
Does anybody know the correct way to post JSON using Guzzle?

```<code>$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));
</code>```

I get an internal server error response from the server. It works using Chrome Postman.

答:
Simply use this it will work</p>

```<code>   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();
</code>```

Body:
Does anybody know the correct way to post JSON using Guzzle?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

I get an internal server error response from the server. It works using Chrome Postman.

Body:
Simply use this it will work

   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();


问:
How can I set up a 'Data Layer' variable to pass a 'Unique ID' back to our partners when a conversion occurs?
Currently we use GTM to house all of our partners conversion pixels that fire on our success page. We're trying to create a 'Data Layer' variable that we can add to our partners conversion pixels that will then send a 'Unique Conversion ID' back to the respective partner each time the conversion pixel fires. This will allow us to cross check our conversion data against our partners.

How can we accomplish this?

Can anyone help me. Thanks in advance.

答: You can do dataLayer.push(object) and it will trigger an event called Message and it will put in the dataLayer what you want.


问:
Can ES6 template literals be substituted at runtime (or reused)?
tl;dr: Is it possible to make a reusable template literal?

I've been trying to use template literals but I guess I just don't get it and now I'm getting frustrated. I mean, I think I get it, but "it" shouldn't be how it works, or how it should get. It should get differently.

All the examples I see (even tagged templates) require that the "substitutions" be done at declaration time and not run time, which seems utterly useless to me for a template. Maybe I'm crazy, but a "template" to me is a document that contains tokens which get substituted when you use it, not when you create it, otherwise it's just a document (i.e., a string). A template is stored with the tokens as tokens & those tokens are evaluated when you...evaluate it.

Everyone cites a horrible example similar to:

```<code>var a = 'asd';
return `Worthless ${a}!`
</code>```

That's nice, but if I already know a, I would just return 'Worthless asd' or return 'Worthless '+a. What's the point? Seriously. Okay the point is laziness; fewer pluses, more readability. Great. But that's not a template! Not IMHO. And MHO is all that matters! The problem, IMHO, is that the template is evaluated when it's declared, so, if you do, IMHO:

```<code>var tpl = `My ${expletive} template`;
function go() { return tpl; }
go(); // SPACE-TIME ENDS!
</code>```

Since expletive isn't declared, it outputs something like My undefined template. Super. Actually, in Chrome at least, I can't even declare the template; it throws an error because expletive is not defined. What I need is to be able to do the substitution after declaring the template:

```<code>var tpl = `My ${expletive} template`;
function go() { return tpl; }
var expletive = 'great';
go(); // My great template
</code>```

However I don't see how this is possible, since these aren't really templates. Even when you say I should use tags, nope, they don't work:

```<code>> explete = function(a,b) { console.log(a); console.log(b); }
< function (a,b) { console.log(a); console.log(b); }
> var tpl = explete`My ${expletive} template`
< VM2323:2 Uncaught ReferenceError: expletive is not defined...
</code>```

This all has led me to believe that template literals are horribly misnamed and should be called what they really are: heredocs. I guess the "literal" part should have tipped me off (as in, immutable)?

Am I missing something? Is there a (good) way to make a reusable template literal?

I give you, reusable template literals:

```<code>> function out(t) { console.log(eval(t)); }
  var template = `\`This is
  my \${expletive} reusable
  template!\``;
  out(template);
  var expletive = 'curious';
  out(template);
  var expletive = 'AMAZING';
  out(template);
< This is
  my undefined reusable
  template!
  This is
  my curious reusable
  template!
  This is
  my AMAZING reusable
  template!
</code>```

And here is a naive "helper" function...

```<code>function t(t) { return '`'+t.replace('{','${')+'`'; }
var template = t(`This is
my {expletive} reusable
template!`);
</code>```

...to make it "better".

I'm inclined to call them template guterals because of the area from which they produce twisty feelings.

答:
UPDATED: The following answer is limited to single variable names, so, templates like: 'Result ${a+b}' are not valid for this case. However you can always play with the template values:

```<code>format("This is a test: ${a_b}", {a_b: a+b});
</code>```

ORIGINAL ANSWER:

Based in the previous answers but creating a more "friendly" utility function:

```<code>var format = (template, params) => {
    let tpl = template.replace(/\${(?!this\.)/g, "${this.");
    let tpl_func = new Function(`return \`${tpl}\``);

    return tpl_func.call(params);
}
</code>```

You can invoque it just like:

```<code>format("This is a test: ${hola}, second param: ${hello}", {hola: 'Hola', hello: 'Hi'});
</code>```

And the resulting string should be:

```<code>'This is a test: Hola, second param: Hi'
</code>```

Body:
tl;dr: Is it possible to make a reusable template literal?

I've been trying to use template literals but I guess I just don't get it and now I'm getting frustrated. I mean, I think I get it, but "it" shouldn't be how it works, or how it should get. It should get differently.

All the examples I see (even tagged templates) require that the "substitutions" be done at declaration time and not run time, which seems utterly useless to me for a template. Maybe I'm crazy, but a "template" to me is a document that contains tokens which get substituted when you use it, not when you create it, otherwise it's just a document (i.e., a string). A template is stored with the tokens as tokens & those tokens are evaluated when you...evaluate it.

Everyone cites a horrible example similar to:

var a = 'asd';
return `Worthless ${a}!`

That's nice, but if I already know a, I would just return 'Worthless asd' or return 'Worthless '+a. What's the point? Seriously. Okay the point is laziness; fewer pluses, more readability. Great. But that's not a template! Not IMHO. And MHO is all that matters! The problem, IMHO, is that the template is evaluated when it's declared, so, if you do, IMHO:

var tpl = `My ${expletive} template`;
function go() { return tpl; }
go(); // SPACE-TIME ENDS!

Since expletive isn't declared, it outputs something like My undefined template. Super. Actually, in Chrome at least, I can't even declare the template; it throws an error because expletive is not defined. What I need is to be able to do the substitution after declaring the template:

var tpl = `My ${expletive} template`;
function go() { return tpl; }
var expletive = 'great';
go(); // My great template

However I don't see how this is possible, since these aren't really templates. Even when you say I should use tags, nope, they don't work:

> explete = function(a,b) { console.log(a); console.log(b); }
< function (a,b) { console.log(a); console.log(b); }
> var tpl = explete`My ${expletive} template`
< VM2323:2 Uncaught ReferenceError: expletive is not defined...

This all has led me to believe that template literals are horribly misnamed and should be called what they really are: heredocs. I guess the "literal" part should have tipped me off (as in, immutable)?

Am I missing something? Is there a (good) way to make a reusable template literal?

I give you, reusable template literals:

> function out(t) { console.log(eval(t)); }
  var template = `\`This is
  my \${expletive} reusable
  template!\``;
  out(template);
  var expletive = 'curious';
  out(template);
  var expletive = 'AMAZING';
  out(template);
< This is
  my undefined reusable
  template!
  This is
  my curious reusable
  template!
  This is
  my AMAZING reusable
  template!

And here is a naive "helper" function...

function t(t) { return '`'+t.replace('{','${')+'`'; }
var template = t(`This is
my {expletive} reusable
template!`);

...to make it "better".

I'm inclined to call them template guterals because of the area from which they produce twisty feelings.

Body:
UPDATED: The following answer is limited to single variable names, so, templates like: 'Result ${a+b}' are not valid for this case. However you can always play with the template values:

format("This is a test: ${a_b}", {a_b: a+b});

ORIGINAL ANSWER:

Based in the previous answers but creating a more "friendly" utility function:

var format = (template, params) => {
    let tpl = template.replace(/\${(?!this\.)/g, "${this.");
    let tpl_func = new Function(`return \`${tpl}\``);

    return tpl_func.call(params);
}

You can invoque it just like:

format("This is a test: ${hola}, second param: ${hello}", {hola: 'Hola', hello: 'Hi'});

And the resulting string should be:

'This is a test: Hola, second param: Hi'


问:
I need to parse a number by 4 digits in antlr4
I just started out using antlr4 I just want to write a grammar that can parse through a number series but only select 4 digits at a time

for example, I have a number 1234567891234567
then I want it to parse first 4 digits into 1 token the next into another and the next into another so that I get 4 different 4 digit tokens.

```<code>token1 = 1234,
token2 = 5678,
token3 = 9123,
token4 = 4567,
</code>```

can anyone help me write a grammar for this

```<code>   grammar TEST;

    /*
     * Parser Rules
     */

    test             :   (example+ EOF);
    example          :   digit COMMA digit2 NEWLINE;
    digit            :   SINGLE+;
    digit2           :   QUADRUPLE+;

    /*
     * Lexer Rules
     */

     SINGLE:
        INT
   ;

    QUADRUPLE:
       INT INT INT INT
   ;

   fragment INT:
       [0-9]
    ;
   NEWLINE    : ('\r'? '\n' | '\r')+ ;
   COMMA      : ',';
</code>```

here's the grammar I have written what I need it to print single digits as tokens 1st and then after a comma I need the numbers to be printed as 4digits in tokens please check the attached image and help me out

答:
The respective lexer rule would look like this:

```<code>QUADRUPLE:
    INT INT INT INT
;

fragment INT:
    [0-9]
;
</code>```

So the key to this problem is to renounce using one of ANTLR's "repeating-operators" (*, +) and simply write the repetition by hand so that it matches exactly the desired count.

Body:
I just started out using antlr4 I just want to write a grammar that can parse through a number series but only select 4 digits at a time

for example, I have a number 1234567891234567
then I want it to parse first 4 digits into 1 token the next into another and the next into another so that I get 4 different 4 digit tokens.

token1 = 1234,
token2 = 5678,
token3 = 9123,
token4 = 4567,

can anyone help me write a grammar for this

   grammar TEST;

    /*
     * Parser Rules
     */

    test             :   (example+ EOF);
    example          :   digit COMMA digit2 NEWLINE;
    digit            :   SINGLE+;
    digit2           :   QUADRUPLE+;

    /*
     * Lexer Rules
     */

     SINGLE:
        INT
   ;

    QUADRUPLE:
       INT INT INT INT
   ;

   fragment INT:
       [0-9]
    ;
   NEWLINE    : ('\r'? '\n' | '\r')+ ;
   COMMA      : ',';

here's the grammar I have written what I need it to print single digits as tokens 1st and then after a comma I need the numbers to be printed as 4digits in tokens please check the attached image and help me out

Body:
The respective lexer rule would look like this:

QUADRUPLE:
    INT INT INT INT
;

fragment INT:
    [0-9]
;

So the key to this problem is to renounce using one of ANTLR's "repeating-operators" (*, +) and simply write the repetition by hand so that it matches exactly the desired count.


问:
MATLAB: How to add custom ticks and labels to an imagesc plot?
I have made a matrix containing 13 different vectors with ~300K+ rows. I have visualized the matrix by transposing it and using the imagesc function to see the distribution of colors. All vectors have been resampled, processed and normalized between 0 & 1 individually.

The imagesc plot gives me this result (fig 1):

But, when I use the axis functionality to add x & y limits, I get this:

How do I maintain the imagesc plot while being able to add custom ticks and labels to the X & y axis? The x axis represents time, while the y axis will get its own labels with sensor names.

答:
You redefine limits from 0 to 30 on the x-axis while the initial xlimits goes up to 3e5. Same issue with the y-axis

Here's how to redefine the Y-axis to put sensor names:

```<code>C = [0 2 4 6 9 ; 8 10 12 44 14; 16 48 10 32 23];
image(C)
% Get axis handle
ax = gca;

% Set where ticks will be
ax.YTick = [1 2 3];
% Set TickLabels;
ax.YTickLabel = {'S1','S2','S3'};
</code>```

Figure out the ax.YTick where you want the labels to appear.

If you want the x-axis to go from 0 to 30, divide the x component of all vectors by 1e4 before plotting. Alternatively, you can add the line:

```<code>ax.XTickLabel = ax.XTick/1e4;
</code>```

Body:
You redefine limits from 0 to 30 on the x-axis while the initial xlimits goes up to 3e5. Same issue with the y-axis

Here's how to redefine the Y-axis to put sensor names:

C = [0 2 4 6 9 ; 8 10 12 44 14; 16 48 10 32 23];
image(C)
% Get axis handle
ax = gca;

% Set where ticks will be
ax.YTick = [1 2 3];
% Set TickLabels;
ax.YTickLabel = {'S1','S2','S3'};

Figure out the ax.YTick where you want the labels to appear.

If you want the x-axis to go from 0 to 30, divide the x component of all vectors by 1e4 before plotting. Alternatively, you can add the line:

ax.XTickLabel = ax.XTick/1e4;


问:
insertion problem in drupal 6
Code:

```<code>  $value["name"] = $form['name']['first'];
  $contact = db_fetch_array(db_query("INSERT INTO test values('4', $value["name"])"));
</code>```

error is shown here but what will be the correct code to submit $form data into a database?

Can anyone help me?

Thank you.

答:
INSERT queries don't return a result, so there's nothing to fetch. Despite that your query is syntactically wrong: string values must be wrapped in quotes, numeric values must not.

```<code>db_query("INSERT INTO {test} VALUES (4, '%s')", $form['name']['first']);
</code>```

As of Drupal 6 db_query("INSERT ...") is discouraged. drupal_write_record() should be used instead.

```<code>$record = array('id' => 4, 'firstname' => $form['name']['first']);
drupal_write_record('test', $record);
</code>```

For more information please refer to the docs.

Title: insertion problem in drupal 6

Body:
Code:

  $value["name"] = $form['name']['first'];
  $contact = db_fetch_array(db_query("INSERT INTO test values('4', $value["name"])"));

error is shown here but what will be the correct code to submit $form data into a database?

Can anyone help me?

Thank you.

Body:
INSERT queries don't return a result, so there's nothing to fetch. Despite that your query is syntactically wrong: string values must be wrapped in quotes, numeric values must not.

db_query("INSERT INTO {test} VALUES (4, '%s')", $form['name']['first']);

As of Drupal 6 db_query("INSERT ...") is discouraged. drupal_write_record() should be used instead.

$record = array('id' => 4, 'firstname' => $form['name']['first']);
drupal_write_record('test', $record);

For more information please refer to the docs.


问:
"No module named ipython" error despite already installed
I am trying to launch ipython using the command: python -m ipython

When launched I get the following error : C:\Program Files\Python36\python.exe: No module named ipython

This is strange because when I run python -m pip show ipython, I get the following message :

```<code>Name: ipython
Version: 6.2.1
Summary: IPython: Productive Interactive Computing
Home-page: https://ipython.org
Author: The IPython Development Team
Author-email: ipython-dev@python.org
License: BSD
Location: c:\program files\python36\lib\site-packages
Requires: simplegeneric, setuptools, decorator, pickleshare, traitlets,
pygments, colorama, prompt-toolkit, jedi
</code>```

I already ensured that all dependencies were correctly installed.
Could you please help me ?

答:
It is actually spelled IPython (upper case I and P to start).

```<code>python -m IPython
</code>```

will do.

Edit: confusion can arise because the pypi service allows the package name and module name to differ.

Body:
I am trying to launch ipython using the command: python -m ipython

When launched I get the following error : C:\Program Files\Python36\python.exe: No module named ipython

This is strange because when I run python -m pip show ipython, I get the following message :

Name: ipython
Version: 6.2.1
Summary: IPython: Productive Interactive Computing
Home-page: https://ipython.org
Author: The IPython Development Team
Author-email: ipython-dev@python.org
License: BSD
Location: c:\program files\python36\lib\site-packages
Requires: simplegeneric, setuptools, decorator, pickleshare, traitlets,
pygments, colorama, prompt-toolkit, jedi

I already ensured that all dependencies were correctly installed.
Could you please help me ?

Body:
It is actually spelled IPython (upper case I and P to start).

python -m IPython

will do.

Edit: confusion can arise because the pypi service allows the package name and module name to differ.


答:
Yes, you can perform a non-equi join.

(Note I've changed log and summary to Log and Summary as the originals are already functions in R.)

```<code>Log[Summary,
   on = c("date>=from_date", "date<=to_date"),
   nomatch=0L,
   allow.cartesian = TRUE][, .(from_date = date[1],
                               to_date = date.1[1],
                               event1 = sum(event1),
                               event2 = sum(event2)),
                           keyby = "period"]
</code>```

To sum over a pattern of columns, use lapply with .SD:

```<code>joined_result <-
  Log[Summary,
      on = c("date>=from_date", "date<=to_date"),
      nomatch = 0L,
      allow.cartesian = TRUE]

cols <- grep("event[a-z]?[0-9]", names(joined_result), value = TRUE)

joined_result[, lapply(.SD, sum),
              .SDcols = cols,
              keyby = .(period,
                        from_date = date,
                        to_date = date.1)]
</code>```

Title: aggregate/merge over date range using data.table

Body:
Suppose I have two data.tables:

summary <- data.table(period = c("A","B","C","D"),
                 from_date = ymd(c("2017-01-01", "2017-01-03", "2017-02-08", "2017-03-07")),
                 to_date = ymd(c("2017-01-31", "2017-04-01", "2017-03-08", "2017-05-01"))
)

log <- data.table(date = ymd(c("2017-01-03","2017-01-20","2017-02-01","2017-03-03",
                               "2017-03-15","2017-03-28","2017-04-03","2017-04-23")),
                  event1 = c(4,8,8,4,3,4,7,3), event2 = c(1,8,7,3,8,4,6,3))

which look like this:

> summary
   period  from_date    to_date
1:      A 2017-01-01 2017-01-31
2:      B 2017-01-03 2017-04-01
3:      C 2017-02-08 2017-03-08
4:      D 2017-03-07 2017-05-01
> log
         date event1 event2
1: 2017-01-03      4      1
2: 2017-01-20      8      8
3: 2017-02-01      8      7
4: 2017-03-03      4      3
5: 2017-03-15      3      8
6: 2017-03-28      4      4
7: 2017-04-03      7      6
8: 2017-04-23      3      3

I would like to get the sum of event1 and event2 for each time period in the table summary.

I know I can do this:

summary[, c("event1","event2") := .(sum(log[date>=from_date & date<=to_date, event1]),
                               sum(log[date>=from_date & date<=to_date, event2]))
   , by=period][]

to get the desired result:

   period  from_date    to_date event1 event2
1:      A 2017-01-01 2017-01-31     12      9
2:      B 2017-01-03 2017-04-01     31     31
3:      C 2017-02-08 2017-03-08      4      3
4:      D 2017-03-07 2017-05-01     17     21

Now, in my real-life problem, I have about 30 columns to be summed, which I may want to change later, and summary has ~35,000 rows, log has ~40,000,000 rows. Is there an efficient way to achieve this?

Note: This is my first post here. I hope my question is clear and specific enough, please do make suggestions if there is anything I should do to improve the question. Thanks!

Body:
Yes, you can perform a non-equi join.

(Note I've changed log and summary to Log and Summary as the originals are already functions in R.)

Log[Summary,
   on = c("date>=from_date", "date<=to_date"),
   nomatch=0L,
   allow.cartesian = TRUE][, .(from_date = date[1],
                               to_date = date.1[1],
                               event1 = sum(event1),
                               event2 = sum(event2)),
                           keyby = "period"]

To sum over a pattern of columns, use lapply with .SD:

joined_result <-
  Log[Summary,
      on = c("date>=from_date", "date<=to_date"),
      nomatch = 0L,
      allow.cartesian = TRUE]

cols <- grep("event[a-z]?[0-9]", names(joined_result), value = TRUE)

joined_result[, lapply(.SD, sum),
              .SDcols = cols,
              keyby = .(period,
                        from_date = date,
                        to_date = date.1)]


问:
How to solve 'Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies' error?
I upload my asp.net file in webserver. First it shows

```<code><!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>
</code>```

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's  configuration tag to point to a custom error page URL.

```<code><!-- Web.Config Configuration File -->

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration
</code>```

Then I add <customErrors mode="Off"> in web.config file.

After that when i run it shows the following error.

Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies. The system cannot find the file specified.

I upload my projects file completely such as bin, css, js, images and forms.
First time I am uploading in web server. Please tell me what should I do.

答:
You could follow the below steps to solve the issue:

Open IIS.

Right click the 'Default Web Site'. Go to 'Manage Web Site' > 'Advanced Settings..'

Check the 'Physical Path' value. It should be 'C:\inetpub\wwwroot'.

Note: The above steps would work if you have published your project as an Application under the 'Default Web Site' in IIS. In case you have publish your project as a different web site, you could try the similar steps to point it to your project and not to 'C:\inetpub\wwwroot'

Body:
I upload my asp.net file in webserver. First it shows

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Notes: The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's  configuration tag to point to a custom error page URL.

<configuration>
    <system.web>
        <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
    </system.web>
</configuration

Then I add <customErrors mode="Off"> in web.config file.

After that when i run it shows the following error.

Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies. The system cannot find the file specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies. The system cannot find the file specified.

I upload my projects file completely such as bin, css, js, images and forms.
First time I am uploading in web server. Please tell me what should I do.


问:
What's the difference between equal and identical comparison operators in PHP?

Possible Duplicate:

  How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?

I know the basic difference between == and === , but can some experienced coders tell me some practical examples for both cases?

答:
In addition to @DavidT.'s example, a more practical example is the following:</p>

```<code>$foo = "Goo";
$bar = "Good Morning";
if (strpos($bar,$foo))
  echo "Won't be seen, returns false because the result is in fact 0";
if (strpos($bar,$foo) !== false)
  echo "True, though 0 is returned it IS NOT false)";
</code>```

Body:
In addition to @DavidT.'s example, a more practical example is the following:

$foo = "Goo";
$bar = "Good Morning";
if (strpos($bar,$foo))
  echo "Won't be seen, returns false because the result is in fact 0";
if (strpos($bar,$foo) !== false)
  echo "True, though 0 is returned it IS NOT false)";


问:
angular2-jwt token alwas not valid
So I have a simple angular 2/laravel app wit jwt authentification support. I have a service that verifies everytime a route is called if the jwt token is valid or not using the angular2-jwt tokenNotExpired() function, but this function always return false for a reason, so the user would be always redirected to login page.

So it goes like that the user logs in, a token will be generated from the backend and saved on local storage, than a service will check if the token is valid before initiating any route using the CanActivate lifecycle hook.

Here is what i did so far:

Login Component:

```<code>   ...
            this.http.post(SERVER_URL + 'auth', body, {
                headers: headers
            }
            ).subscribe(
                data => {

                    localStorage.setItem('auth_token', data.json().token);
                    this.authHttp.get(SERVER_URL + 'auth/user', headers)
                        .subscribe(
                        data => {
                            this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: data.json().user });
                            localStorage.setItem('user', data.json().user);
                            this.router.navigate(['/home']);

                        },
                        err => console.log('Fehlermeldung: ' + err)
                        );

                },
...
</code>```

app.module :

```<code>...
 { provide: AuthConfig, useValue: new AuthConfig({
              headerName: 'Authorization',
              headerPrefix: 'Bearer ',
              tokenName: 'auth_token',
              tokenGetter: (() => localStorage.getItem('auth_token')),
              globalHeaders: [{ 'Content-Type': 'application/json' }],
              noJwtError: true,
              noTokenScheme: true
  })},
    AuthHttp
...
</code>```

auth.service :
// Check JWT token service

```<code>import { tokenNotExpired } from 'angular2-jwt';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService  {

    loggedIn() {
    return tokenNotExpired();
    }

}
</code>```

auth.guard.service :

```<code>// Check if the Token of the user is still valid
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { AppState } from '../shared/interfaces';
import { SET_CURRENT_USER_PROFILE } from '../shared/state.actions';

import { Store } from '@ngrx/store'

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthService, private router: Router, private store: Store<AppState>) {}

  canActivate() {
    if(this.auth.loggedIn()) {
      return true;
    } else {
        console.log ('Token expired or not valid')
        localStorage.setItem('auth_token', '');
        localStorage.setItem('user', '');
        this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: null });
        this.router.navigate(['/']);
      return false;
    }
  }
}
</code>```

app.routing :

```<code>const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'about', component: AboutComponent, canActivate: [AuthGuardService]},
  { path: 'profile/:id', component: ProfileComponent, canActivate: [AuthGuardService]},
  { path: '', component: LoginComponent}
];
</code>```

EDIT: From the backend side everything is normally ok since the token is generated and stored in the localstorage after the user logs in.

答:
Pass the token as a parameter.

Change

```<code>loggedIn() {
  return tokenNotExpired();
}
</code>```

to

```<code>loggedIn() {
  return tokenNotExpired('id_token');
}
</code>```

Title: angular2-jwt token alwas not valid

Body:
So I have a simple angular 2/laravel app wit jwt authentification support. I have a service that verifies everytime a route is called if the jwt token is valid or not using the angular2-jwt tokenNotExpired() function, but this function always return false for a reason, so the user would be always redirected to login page.

So it goes like that the user logs in, a token will be generated from the backend and saved on local storage, than a service will check if the token is valid before initiating any route using the CanActivate lifecycle hook.

Here is what i did so far:

Login Component:

   ...
            this.http.post(SERVER_URL + 'auth', body, {
                headers: headers
            }
            ).subscribe(
                data => {

                    localStorage.setItem('auth_token', data.json().token);
                    this.authHttp.get(SERVER_URL + 'auth/user', headers)
                        .subscribe(
                        data => {
                            this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: data.json().user });
                            localStorage.setItem('user', data.json().user);
                            this.router.navigate(['/home']);

                        },
                        err => console.log('Fehlermeldung: ' + err)
                        );

                },
...

app.module :

...
 { provide: AuthConfig, useValue: new AuthConfig({
              headerName: 'Authorization',
              headerPrefix: 'Bearer ',
              tokenName: 'auth_token',
              tokenGetter: (() => localStorage.getItem('auth_token')),
              globalHeaders: [{ 'Content-Type': 'application/json' }],
              noJwtError: true,
              noTokenScheme: true
  })},
    AuthHttp
...

auth.service :
// Check JWT token service

import { tokenNotExpired } from 'angular2-jwt';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService  {

    loggedIn() {
    return tokenNotExpired();
    }

}

auth.guard.service :

// Check if the Token of the user is still valid
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { AppState } from '../shared/interfaces';
import { SET_CURRENT_USER_PROFILE } from '../shared/state.actions';

import { Store } from '@ngrx/store'

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthService, private router: Router, private store: Store<AppState>) {}

  canActivate() {
    if(this.auth.loggedIn()) {
      return true;
    } else {
        console.log ('Token expired or not valid')
        localStorage.setItem('auth_token', '');
        localStorage.setItem('user', '');
        this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: null });
        this.router.navigate(['/']);
      return false;
    }
  }
}

app.routing :

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'about', component: AboutComponent, canActivate: [AuthGuardService]},
  { path: 'profile/:id', component: ProfileComponent, canActivate: [AuthGuardService]},
  { path: '', component: LoginComponent}
];

EDIT: From the backend side everything is normally ok since the token is generated and stored in the localstorage after the user logs in.

Body:
Pass the token as a parameter.

Change

loggedIn() {
  return tokenNotExpired();
}

to

loggedIn() {
  return tokenNotExpired('id_token');
}


问:
How to proxy a HTTP video stream to any amount of clients through a Spring Webserver
Provided that I have a video HTTP stream broadcasted on a server that is on the same network as my Spring Webserver is, for instance in some url such as:

http://localhost:9090/httpstream

How can I proxy this video stream to any amount of clients, using Spring?
The following example demonstrates the wanted flow:

Spring webserver can be found at http://localhost:9091/spring

A client wants to access a video stream, so he connects his video-stream-player to http://localhost:9091/spring (the spring webserver)

The Spring WebServer should redirect the stream found on http://localhost:9090/httpstream to the client, with the latter never knowing that he accessed the httpstream host. The connection is made by Spring, not by the client

This is needed because the HTTPStream is an unsecured and not authenticated host, and I wanted to wrap it around a Spring Webserver, so that I could use some form of Security, such as a Basic Auth.

I tried requesting some form of mapping, but I couldn't find what kind of object to return, nor how to make the connection, but the expected behaviour should be something like this:

```<code>@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring") {
    public /*Stream Object?*/ getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

       return   //What should be returned?
       }
   }
}
</code>```

答:
I am not sure what kind of source you are using for generating your video stream (live camera or a video file or youtube video or ..)

You can probably use StreamingResponseBody (requires Spring 4.2+). Refer following links

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/streaming-response-body/

http://shazsterblog.blogspot.in/2016/02/asynchronous-streaming-request.html

Try this -

```<code>    @GetMapping("/stream1")
        @ResponseBody
        public StreamingResponseBody getVidoeStream1(@RequestParam String any) throws IOException {
            /* do security check before connecting to stream hosting server */
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Resource> responseEntity = restTemplate.exchange( "http://localhost:8080/stream", HttpMethod.GET, null, Resource.class );
            InputStream st = responseEntity.getBody().getInputStream();
            return (os) -> {
                readAndWrite(st, os);
            };

    }

private void readAndWrite(final InputStream is, OutputStream os)
            throws IOException {
        byte[] data = new byte[2048];
        int read = 0;
        while ((read = is.read(data)) > 0) {
            os.write(data, 0, read);
        }
        os.flush();
    }
</code>```

It should work. You can write your own implementation of readAndWrite() depending on your requirements.

So, your spring proxy controller could be something like this...

```<code>@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring")
    @ResponseBody
    public StreamingResponseBody  getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

    RestTemplate restTemplate = new RestTemplate();
    // get video stream by connecting to stream hosting server  like this
            ResponseEntity<Resource> responseEntity = restTemplate.exchange( "https://ur-to-stream", HttpMethod.GET, null, Resource.class );
            InputStream st = responseEntity.getBody().getInputStream();
    // Or if there is any other preferred way of getting the video stream use that. The idea is to get the video input stream

    // now return a StreamingResponseBody  object created by following lambda
            return (os) -> {
                readAndWrite(st, os);
            };

       } else {
          return null;
       }

   }
}
</code>```

The StreamingResponseBody returned by your rest endpoint will work fine with HTML5, which could be something like ..

```<code><video width="320" height="240" controls>
  <source src="/spring" type="video/mp4">
  Your browser does not support the video tag
</video>
</code>```

Body:
Provided that I have a video HTTP stream broadcasted on a server that is on the same network as my Spring Webserver is, for instance in some url such as:

http://localhost:9090/httpstream

How can I proxy this video stream to any amount of clients, using Spring?
The following example demonstrates the wanted flow:

Spring webserver can be found at http://localhost:9091/spring

A client wants to access a video stream, so he connects his video-stream-player to http://localhost:9091/spring (the spring webserver)

The Spring WebServer should redirect the stream found on http://localhost:9090/httpstream to the client, with the latter never knowing that he accessed the httpstream host. The connection is made by Spring, not by the client

This is needed because the HTTPStream is an unsecured and not authenticated host, and I wanted to wrap it around a Spring Webserver, so that I could use some form of Security, such as a Basic Auth.

I tried requesting some form of mapping, but I couldn't find what kind of object to return, nor how to make the connection, but the expected behaviour should be something like this:

@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring") {
    public /*Stream Object?*/ getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

       return   //What should be returned?
       }
   }
}

Body:
I am not sure what kind of source you are using for generating your video stream (live camera or a video file or youtube video or ..)

You can probably use StreamingResponseBody (requires Spring 4.2+). Refer following links

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/streaming-response-body/

http://shazsterblog.blogspot.in/2016/02/asynchronous-streaming-request.html

Try this -

    @GetMapping("/stream1")
        @ResponseBody
        public StreamingResponseBody getVidoeStream1(@RequestParam String any) throws IOException {
            /* do security check before connecting to stream hosting server */
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Resource> responseEntity = restTemplate.exchange( "http://localhost:8080/stream", HttpMethod.GET, null, Resource.class );
            InputStream st = responseEntity.getBody().getInputStream();
            return (os) -> {
                readAndWrite(st, os);
            };

    }

private void readAndWrite(final InputStream is, OutputStream os)
            throws IOException {
        byte[] data = new byte[2048];
        int read = 0;
        while ((read = is.read(data)) > 0) {
            os.write(data, 0, read);
        }
        os.flush();
    }

It should work. You can write your own implementation of readAndWrite() depending on your requirements.

So, your spring proxy controller could be something like this...

@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring")
    @ResponseBody
    public StreamingResponseBody  getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

    RestTemplate restTemplate = new RestTemplate();
    // get video stream by connecting to stream hosting server  like this
            ResponseEntity<Resource> responseEntity = restTemplate.exchange( "https://ur-to-stream", HttpMethod.GET, null, Resource.class );
            InputStream st = responseEntity.getBody().getInputStream();
    // Or if there is any other preferred way of getting the video stream use that. The idea is to get the video input stream

    // now return a StreamingResponseBody  object created by following lambda
            return (os) -> {
                readAndWrite(st, os);
            };

       } else {
          return null;
       }

   }
}

The StreamingResponseBody returned by your rest endpoint will work fine with HTML5, which could be something like ..

<video width="320" height="240" controls>
  <source src="/spring" type="video/mp4">
  Your browser does not support the video tag
</video>


问:
Vue.js 2/Vuex - How to call getters from modules that has attribute namespaced:true without mapGetters?
This is my module:

```<code>const ModuleA={
   namespaced:true,
   state:{
      categoryList:[
         {name:'all', isActive:true},
         {name:'negotiation', isActive:false},
      ]
   },
   getters:{
      getCategory:(state)=>(index)=>{
        return state.categoryList[index];
      },
   }
}
</code>```

Without namespaced:true, I can call getCategory with this.$store.getters.getCategory(this.index).

How to call getCategory with namespaced:true? I can't use mapGetters because I have to pass parameter to the function.

答:
See 2nd answer to this How to access Vuex module getters and mutations</p>

```<code>this.$store.getters['ModuleA/getCategory'](this.index)
</code>```

Body:
This is my module:

const ModuleA={
   namespaced:true,
   state:{
      categoryList:[
         {name:'all', isActive:true},
         {name:'negotiation', isActive:false},
      ]
   },
   getters:{
      getCategory:(state)=>(index)=>{
        return state.categoryList[index];
      },
   }
}

Without namespaced:true, I can call getCategory with this.$store.getters.getCategory(this.index).

How to call getCategory with namespaced:true? I can't use mapGetters because I have to pass parameter to the function.

Body:
See 2nd answer to this How to access Vuex module getters and mutations

this.$store.getters['ModuleA/getCategory'](this.index)


问:
Generic types and polymorphism
I have BaseFragment:

```<code>    public abstract class BaseFragment extends Fragment implements BaseMvpView {

        private BasePresenter presenter;

        protected void syncLifeCycle(BasePresenter presenter) {
            this.presenter = presenter;
            this.presenter.onCreate();
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            //noinspection unchecked
            presenter.onAttachView(this); //it works with a warning
        }

        @Override
        public void onResume() {
            super.onResume();
            presenter.onResume();
        }

        @Override
        public void onPause() {
            super.onPause();
            presenter.onPause();
        }

        @Override
        public void onDestroyView() {
            super.onDestroyView();
            presenter.onDetachView();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            presenter.onDestroy();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            presenter.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

and many classes that extends it. For example MainFragment:

```<code>    public class MainFragment extends BaseFragment implements MainMvpView {

        MainPresenter<MainMvpView> presenter;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            syncLifeCycle(presenter);
            //presenter.onCreate();
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            //presenter.onAttachView(this);
        }

        @Override
        public void onResume() {
            super.onResume();
            //presenter.onResume();
        }

        @Override
        public void onPause() {
            super.onPause();
            //presenter.onPause();
        }

        @Override
        public void onDestroyView() {
            super.onDestroyView();
            //presenter.onDetachView();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            //presenter.onDestroy();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //presenter.onActivityResult(requestCode, resultCode, data);
        }
}
</code>```

I want to avoid repeating the life cycle synchronization code of each fragment and presenter. Therefore I want to implement this process in the BaseFragment. In Java this line presenter.onAttachView(this); works but with a warning "Unchecked call onAttachView(V)"(I can live with this). But Kotlin does not allow me to do this at all

```<code>abstract class BaseFragmentKotlin : Fragment(), BaseMvpView {

    private var presenter: BasePresenter<*>? = null

    //...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        presenter?.onAttachView(this) //Does not work. "Out-projected type 'BasePresenter<*>?' prohibits the use of 'public abstract fun onAttachView(mvpView: V!): Unit defined in com.example.test.BasePresenter"
    }

//...
}
</code>```

I really need advice on how to do this correctly.

Edited:

```<code>    public class BasePresenterImpl<V extends BaseMvpView> implements BasePresenter<V> {

        @Nullable
        public V mvpView;

        @Override
        public void onCreate() {

        }

        @Override
        public void onAttachView(V mvpView) {
            this.mvpView = mvpView;
        }

        @Override
        public void onResume() {

        }

        @Override
        public void onPause() {

        }

        @Override
        public void onDetachView() {
        mvpView = null;
        }

        @Override
        public void onDestroy() {

        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {

        }
}
</code>```

Here is the whole test code https://github.com/AlexNikolaTest/Test/tree/master/app/src/main/java/com/example/mytest

答:
Perhaps you can make it like this</p>

```<code>interface IView

interface IPresenter {
    fun attachView(v: IView)
    fun detachView()
}

abstract class BasePresenter<V :IView> : IPresenter {
    protected var view: V? = null

    override fun attachView(v: IView) {
        this.view = v as V
    }

    override fun detachView() {
        view = null
    }
}

abstract class BaseFragment<P : IPresenter> : Fragment(), IView {
    protected lateinit var presenter: P

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        presenter.attachView(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        presenter.detachView()
    }
}

interface TestView : IView {
    fun doSomething()
}

interface TestPresenter : IPresenter {
    fun doSomething()
}

class TestPresenterImpl : BasePresenter<TestView>(), TestPresenter {
    override fun doSomething() {
    }
}

class TestFragment : BaseFragment<TestPresenter>(), TestView {

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        presenter = TestPresenterImpl()
        presenter.doSomething()
    }

    override fun doSomething() {
    }
}
</code>```

Title: Generic types and polymorphism

Body:
I have BaseFragment:

    public abstract class BaseFragment extends Fragment implements BaseMvpView {

        private BasePresenter presenter;

        protected void syncLifeCycle(BasePresenter presenter) {
            this.presenter = presenter;
            this.presenter.onCreate();
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            //noinspection unchecked
            presenter.onAttachView(this); //it works with a warning
        }

        @Override
        public void onResume() {
            super.onResume();
            presenter.onResume();
        }

        @Override
        public void onPause() {
            super.onPause();
            presenter.onPause();
        }

        @Override
        public void onDestroyView() {
            super.onDestroyView();
            presenter.onDetachView();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            presenter.onDestroy();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            presenter.onActivityResult(requestCode, resultCode, data);
    }
}

and many classes that extends it. For example MainFragment:

    public class MainFragment extends BaseFragment implements MainMvpView {

        MainPresenter<MainMvpView> presenter;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            syncLifeCycle(presenter);
            //presenter.onCreate();
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            //presenter.onAttachView(this);
        }

        @Override
        public void onResume() {
            super.onResume();
            //presenter.onResume();
        }

        @Override
        public void onPause() {
            super.onPause();
            //presenter.onPause();
        }

        @Override
        public void onDestroyView() {
            super.onDestroyView();
            //presenter.onDetachView();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            //presenter.onDestroy();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            //presenter.onActivityResult(requestCode, resultCode, data);
        }
}

I want to avoid repeating the life cycle synchronization code of each fragment and presenter. Therefore I want to implement this process in the BaseFragment. In Java this line presenter.onAttachView(this); works but with a warning "Unchecked call onAttachView(V)"(I can live with this). But Kotlin does not allow me to do this at all

abstract class BaseFragmentKotlin : Fragment(), BaseMvpView {

    private var presenter: BasePresenter<*>? = null

    //...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        presenter?.onAttachView(this) //Does not work. "Out-projected type 'BasePresenter<*>?' prohibits the use of 'public abstract fun onAttachView(mvpView: V!): Unit defined in com.example.test.BasePresenter"
    }

//...
}

I really need advice on how to do this correctly.

Edited:

    public class BasePresenterImpl<V extends BaseMvpView> implements BasePresenter<V> {

        @Nullable
        public V mvpView;

        @Override
        public void onCreate() {

        }

        @Override
        public void onAttachView(V mvpView) {
            this.mvpView = mvpView;
        }

        @Override
        public void onResume() {

        }

        @Override
        public void onPause() {

        }

        @Override
        public void onDetachView() {
        mvpView = null;
        }

        @Override
        public void onDestroy() {

        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {

        }
}

Here is the whole test code https://github.com/AlexNikolaTest/Test/tree/master/app/src/main/java/com/example/mytest

Body:
Perhaps you can make it like this

interface IView

interface IPresenter {
    fun attachView(v: IView)
    fun detachView()
}

abstract class BasePresenter<V :IView> : IPresenter {
    protected var view: V? = null

    override fun attachView(v: IView) {
        this.view = v as V
    }

    override fun detachView() {
        view = null
    }
}

abstract class BaseFragment<P : IPresenter> : Fragment(), IView {
    protected lateinit var presenter: P

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        presenter.attachView(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        presenter.detachView()
    }
}

interface TestView : IView {
    fun doSomething()
}

interface TestPresenter : IPresenter {
    fun doSomething()
}

class TestPresenterImpl : BasePresenter<TestView>(), TestPresenter {
    override fun doSomething() {
    }
}

class TestFragment : BaseFragment<TestPresenter>(), TestView {

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        presenter = TestPresenterImpl()
        presenter.doSomething()
    }

    override fun doSomething() {
    }
}


问:
Writing FILE* through pipe
I have two file open in two different processes. There's a pipe connecting the two. Is it possible to write directly from one file to another? Especially if the process reading doesn't know the size of the file it's trying to read?

I was hoping to do something like this

```<code>#define length 100
int main(){
  int frk = fork();
  int pip[2];
  pipe(pip);
  if (frk==0){ //child
    FILE* fp fopen("file1", "r");
    write(pip[1],fp,length);
  }
  else {
    FILE* fp fopen("file2", "w");
    read(pip[0],fp,length);
}
</code>```

答:
In other unix systems, like BSD, there's a call to connect directly two file descriptors to do what you want, but don't know if there's a system call to do that in linux.  Anywya, this cannot be done with FILE * descriptors, as these are the instance of a buffered file used by <stdio.h> library to represent a file.  You can get the file descriptor (as the system knows it) of a FILE * instance by  a call to the getfd(3) function call.

The semantics you are trying to get from the system are quite elaborate, as you want something to pass directly the data from one file descriptor to another, without intervention of any process (directly in the kernel), and the kernel needs for that a pool of threads to do the work of copying directly from the read calls to the write ones.

The old way of doing this is to create a thread that makes the work of reading from one file descriptor (not a FILE * pointer) and write to the other.

Another thing to comment is that the pipe(2) system call gives you two connected descriptors, that allow you to read(2) in one (the 0 index) what is write(2)n in the second (the 1 index).  If you fork(2) a second process, and you do the pipe(2) call on both, you will have two pipes (with two descriptors each), one in each process, with no relationship between them.  You will be able only to communicate each process with itself, but not with the other (which doesn't know anything about the other process' pipe descriptors) so no communication between them will be possible.

Next is a complete example of what you try to do:

```<code>#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

#define length 100

#define FMT(fmt) "pid=%d:"__FILE__":%d:%s: " fmt, getpid(), __LINE__, __func__
#define ERR(fmt, ...) do {                  \
             fprintf(stderr,                     \
                     FMT(fmt ": %s (errno = %d)\n"), \
                     ##__VA_ARGS__,                  \
                     strerror(errno), errno);        \
             exit(1);                            \
        } while(0)

void copy(int fdi, int fdo)
{
    unsigned char buffer[length];
    ssize_t res, nread;

    while((nread = res = read(fdi, buffer, sizeof buffer)) > 0) {
        res = write(fdo, buffer, nread);
        if (res < 0) ERR("write");
    } /* while */
    if (res < 0) ERR("read");
} /* copy */

int main()
{
    int pip[2];
    int res;

    res = pipe(pip);
    if (res < 0) ERR("pipe");

    char *filename;

    switch (res = fork()) {
    case -1: /* error */
         ERR("fork");

    case 0:  /* child */
         filename = "file1";
         res = open(filename, O_RDONLY);
         if (res < 0) ERR("open \"%s\"", filename);
         close(pip[0]);
         copy(res, pip[1]);
         break;

    default: /* parent, we got the child's pid in res */
         filename = "file2";
         res = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
         if (res < 0) ERR("open \"%s\"", filename);
         close(pip[1]);
         copy(pip[0], res);
         int status;
         res = wait(&status); /* wait for the child to finish */
         if (res < 0) ERR("wait");
         fprintf(stderr,
                 FMT("The child %d finished with exit code %d\n"),
                 res,
                 status);
         break;
    } /* switch */
    exit(0);
} /* main */
</code>```

Title: Writing FILE* through pipe

Body:
I have two file open in two different processes. There's a pipe connecting the two. Is it possible to write directly from one file to another? Especially if the process reading doesn't know the size of the file it's trying to read?

I was hoping to do something like this

#define length 100
int main(){
  int frk = fork();
  int pip[2];
  pipe(pip);
  if (frk==0){ //child
    FILE* fp fopen("file1", "r");
    write(pip[1],fp,length);
  }
  else {
    FILE* fp fopen("file2", "w");
    read(pip[0],fp,length);
}

Body:
In other unix systems, like BSD, there's a call to connect directly two file descriptors to do what you want, but don't know if there's a system call to do that in linux.  Anywya, this cannot be done with FILE * descriptors, as these are the instance of a buffered file used by <stdio.h> library to represent a file.  You can get the file descriptor (as the system knows it) of a FILE * instance by  a call to the getfd(3) function call.

The semantics you are trying to get from the system are quite elaborate, as you want something to pass directly the data from one file descriptor to another, without intervention of any process (directly in the kernel), and the kernel needs for that a pool of threads to do the work of copying directly from the read calls to the write ones.

The old way of doing this is to create a thread that makes the work of reading from one file descriptor (not a FILE * pointer) and write to the other.

Another thing to comment is that the pipe(2) system call gives you two connected descriptors, that allow you to read(2) in one (the 0 index) what is write(2)n in the second (the 1 index).  If you fork(2) a second process, and you do the pipe(2) call on both, you will have two pipes (with two descriptors each), one in each process, with no relationship between them.  You will be able only to communicate each process with itself, but not with the other (which doesn't know anything about the other process' pipe descriptors) so no communication between them will be possible.

Next is a complete example of what you try to do:

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

#define length 100

#define FMT(fmt) "pid=%d:"__FILE__":%d:%s: " fmt, getpid(), __LINE__, __func__
#define ERR(fmt, ...) do {                  \
             fprintf(stderr,                     \
                     FMT(fmt ": %s (errno = %d)\n"), \
                     ##__VA_ARGS__,                  \
                     strerror(errno), errno);        \
             exit(1);                            \
        } while(0)

void copy(int fdi, int fdo)
{
    unsigned char buffer[length];
    ssize_t res, nread;

    while((nread = res = read(fdi, buffer, sizeof buffer)) > 0) {
        res = write(fdo, buffer, nread);
        if (res < 0) ERR("write");
    } /* while */
    if (res < 0) ERR("read");
} /* copy */

int main()
{
    int pip[2];
    int res;

    res = pipe(pip);
    if (res < 0) ERR("pipe");

    char *filename;

    switch (res = fork()) {
    case -1: /* error */
         ERR("fork");

    case 0:  /* child */
         filename = "file1";
         res = open(filename, O_RDONLY);
         if (res < 0) ERR("open \"%s\"", filename);
         close(pip[0]);
         copy(res, pip[1]);
         break;

    default: /* parent, we got the child's pid in res */
         filename = "file2";
         res = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0666);
         if (res < 0) ERR("open \"%s\"", filename);
         close(pip[1]);
         copy(pip[0], res);
         int status;
         res = wait(&status); /* wait for the child to finish */
         if (res < 0) ERR("wait");
         fprintf(stderr,
                 FMT("The child %d finished with exit code %d\n"),
                 res,
                 status);
         break;
    } /* switch */
    exit(0);
} /* main */


问:
Inherit copy/move constructor as constructor from base class in C++
I read inheriting constructors question and I broadly understand c++ constructor inheritance.

```<code>class X;

class A {
    A(const A& a); // (1)
    A(const X& x); // (2)
};

class B : A {
    using A::A;
}
</code>```

Copy constructors are specials so I cannot use (1) to build a B from an A although I can use (2) to build a B form an X;

However I can add a templated constructor in B:

```<code>template<class...T> B(T... t) : A(t...) {}
</code>```

This templated constructor will allow to build a B form an A.

I want to know what are the side effects of this method and what constructors does it effectively defines ?

For instance, can I move an A to a B this way. Do I still need the using A::A declaration in B? Do I need to add some std::forward black magic?

答:
what are the side effects of this method and what constructors does it effectively defines ?

It defines only one template c'tor. Its specializations will attempt to initialize A with whatever values you give it.

For instance, can I move an A to a B this way.

You aren't forwarding. Since you pass by value, even an explicit B b{std::move(a)}; will not move the argument into the A base.

Do I still need the using A::A declaration in B?

You may have it. It won't be ambiguous, since non-templates are favored over templates when doing overload resolution. That inherited c'tor will be used in B b{std::move(a)}; instead (since a const reference can bind to an xvalue). Essentially, the overload being picked may not always be what you want.

Do I need to add some std::forward black magic?

For the template c'tor? Definitely. Use forwarding references by default. And naturally std::forward to do the job of forwarding.

Body:
I read inheriting constructors question and I broadly understand c++ constructor inheritance.

class X;

class A {
    A(const A& a); // (1)
    A(const X& x); // (2)
};

class B : A {
    using A::A;
}

Copy constructors are specials so I cannot use (1) to build a B from an A although I can use (2) to build a B form an X;

However I can add a templated constructor in B:

template<class...T> B(T... t) : A(t...) {}

This templated constructor will allow to build a B form an A.

I want to know what are the side effects of this method and what constructors does it effectively defines ?

For instance, can I move an A to a B this way. Do I still need the using A::A declaration in B? Do I need to add some std::forward black magic?


问:
Surefire and OpenClover - Generate Clover report if tests fail
I am using the plugin maven-surefire-plugin version 2.20.1 and version 4.2.0 of the OpenClover plugin

Surefire Setup

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
        </plugin>
</code>```

OpenClover Setup

```<code><plugin>
    <groupId>org.openclover</groupId>
    <artifactId>clover-maven-plugin</artifactId>
    <version>4.2.0</version>
</plugin>
</code>```

If any tests fail - the clover report is not generated
Here is the command I use to generate my tests

```<code>mvn  clean clover:setup test clover:aggregate clover:clover -DskipTests=false -DtestFailureIgnore=true
</code>```

Any ideas on what I need to do in order to get clover to generate a report even with test failures?

Thank you
Damien

答:
I resolved this by adding the maven --fail-never option to my maven command

The updated command is

```<code>mvn  clean clover:setup test clover:aggregate clover:clover -DskipTests=false -DtestFailureIgnore=true -fail-never
</code>```

Body:
I am using the plugin maven-surefire-plugin version 2.20.1 and version 4.2.0 of the OpenClover plugin

Surefire Setup

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.20.1</version>
        </plugin>

OpenClover Setup

<plugin>
    <groupId>org.openclover</groupId>
    <artifactId>clover-maven-plugin</artifactId>
    <version>4.2.0</version>
</plugin>

If any tests fail - the clover report is not generated
Here is the command I use to generate my tests

mvn  clean clover:setup test clover:aggregate clover:clover -DskipTests=false -DtestFailureIgnore=true

Any ideas on what I need to do in order to get clover to generate a report even with test failures?

Thank you
Damien

Body:
I resolved this by adding the maven --fail-never option to my maven command

The updated command is

mvn  clean clover:setup test clover:aggregate clover:clover -DskipTests=false -DtestFailureIgnore=true -fail-never


问:
Sub Folder is affected by root web.config
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

```<code><pages theme="DefaultTheme">
</code>```

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

答:
Look into the:

```<code><location> ... </location>
</code>```

elements that can be loaded into the web.config.  Not everything will work under it, but you might be able to override the subfolder to have no theme.  Either that or maybe you can restrict the theme to only the top level folder with those tags?

OwnerDisplayName: Sypress

Body:
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

<pages theme="DefaultTheme">

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

Body:
Look into the:

<location> ... </location>

elements that can be loaded into the web.config.  Not everything will work under it, but you might be able to override the subfolder to have no theme.  Either that or maybe you can restrict the theme to only the top level folder with those tags?

OwnerDisplayName: Ian Jacobs


问:
How to disable email activation in django-registration app?
How to disable email activation in django-registration app?</p>

答:
Better to fix the problem at the root than bandage it by calling commands to automatically activate the user.

Add this method to registration models.py:

```<code>   def create_active_user(self, username, email, password,
                             site):
        """
        Create a new, active ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        """
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = True
        new_user.save()

        registration_profile = self.create_profile(new_user)

        return new_user
    create_active_user = transaction.commit_on_success(create_active_user)
</code>```

Then, edit registration/backend/defaults/init.py and find the register() method.

Change the following to call your new method:

```<code>#new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                            #password, site)
new_user = RegistrationProfile.objects.create_active_user(username, email,
                                                            password, site)
</code>```

Body:
Better to fix the problem at the root than bandage it by calling commands to automatically activate the user.

Add this method to registration models.py:

   def create_active_user(self, username, email, password,
                             site):
        """
        Create a new, active ``User``, generate a
        ``RegistrationProfile`` and email its activation key to the
        ``User``, returning the new ``User``.
        """
        new_user = User.objects.create_user(username, email, password)
        new_user.is_active = True
        new_user.save()

        registration_profile = self.create_profile(new_user)

        return new_user
    create_active_user = transaction.commit_on_success(create_active_user)

Then, edit registration/backend/defaults/init.py and find the register() method.

Change the following to call your new method:

#new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                            #password, site)
new_user = RegistrationProfile.objects.create_active_user(username, email,
                                                            password, site)


问:
Spock Spring inject mock and bean via constructor
I'm looking for way how to inject beans and mock in single constructor.

```<code>@Service
public class SomeService {

private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;

@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
  this.endpointUrlProvider = endpointUrlProvider;
  this.restTemplate = restTemplate;
}
</code>```

Test:

```<code>class SomeTest extends Specification {

@Autowired
EndpointUrlProvider endpointUrlProvider

RestTemplate restTemplate = Mock {
    postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
 }

SomeService someService = new SomeService(endpointUrlProvider, restTemplate)

//some tests
    }
</code>```

When I fire test my endpointUrlProvider in someService is null. What I did wrong  ? What is the best way to test this?

答:
As far as I see, you are trying to do partial mocking. To inject Spring beans, first you will need TestContextManager. Therefore, run the test with SpringRunner or SpringJUnit4ClassRunner. This should do the work:

```<code>@RunWith(SpringRunner.class)
public class SomeServiceTest {

    @Autowired
    private EndpointUrlProvider endpointUrlProvider;

    @Before
    public setUp() {
        RestTemplate restTemplate = mock(RestTemplate.class);
        SomeService someService = new SomeService(endpointUrlProvider, restTemplate);
    }
}
</code>```

Body:
I'm looking for way how to inject beans and mock in single constructor.

@Service
public class SomeService {

private EndpointUrlProvider endpointUrlProvider;
private RestTemplate restTemplate;

@Autowired
public SomeService(EndpointUrlProvider endpointUrlProvider, RestTemplate restTemplate){
  this.endpointUrlProvider = endpointUrlProvider;
  this.restTemplate = restTemplate;
}

Test:

class SomeTest extends Specification {

@Autowired
EndpointUrlProvider endpointUrlProvider

RestTemplate restTemplate = Mock {
    postForEntity(_, _, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
 }

SomeService someService = new SomeService(endpointUrlProvider, restTemplate)

//some tests
    }

When I fire test my endpointUrlProvider in someService is null. What I did wrong  ? What is the best way to test this?

Body:
As far as I see, you are trying to do partial mocking. To inject Spring beans, first you will need TestContextManager. Therefore, run the test with SpringRunner or SpringJUnit4ClassRunner. This should do the work:

@RunWith(SpringRunner.class)
public class SomeServiceTest {

    @Autowired
    private EndpointUrlProvider endpointUrlProvider;

    @Before
    public setUp() {
        RestTemplate restTemplate = mock(RestTemplate.class);
        SomeService someService = new SomeService(endpointUrlProvider, restTemplate);
    }
}


问:
Handling None when adding numbers
I would like to perform addition of 2 integers, which can also be None, with the following results:

```<code>add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b
</code>```

What is the most pythonic, concise expression for this?
So far I have:

```<code>def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b
</code>```

or

```<code>def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b
</code>```

Is there any shorter way to achieve it?

答:
Try this</p>

```<code>def add(a,b):
    a = 0 if not a else a
    b = 0 if not b else b
    return a+b
</code>```

Title: Handling None when adding numbers

Body:
I would like to perform addition of 2 integers, which can also be None, with the following results:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b

What is the most pythonic, concise expression for this?
So far I have:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b

or

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b

Is there any shorter way to achieve it?

Body:
Try this

def add(a,b):
    a = 0 if not a else a
    b = 0 if not b else b
    return a+b


问:
If `ModelState.IsValid==false`, we should return `View()` or `View(movie)`?
If ModelState.IsValid==false, we should return View() or View(movie)?

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
</code>```

or

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }
</code>```

?

答:
Depends if you want to clear the form or not.

Returning the Model will place the values the user entered back into the form where returning view() will display an empty form on post back.

Body:
If ModelState.IsValid==false, we should return View() or View(movie)?

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

or

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }

?


答:
With boolean logic:

Here's a Pythonic method, using lazy or:

```<code>def add(a, b):
    return (a or 0) + (b or 0)
</code>```

With filter

For an arbitrary number of summands, you could use filter and sum:

```<code>def add(*p):
    return sum(filter(None, p))

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None))
# 0
print(add(None, 0))
# 0
</code>```

With an exception

Note that the previous implementations will return 0 for add(None, None). This is the expected mathematical result of an empty sum.

Returning None is suprising and might lead to TypeErrors when you use the output of add.

One way to achieve the desired behaviour when users don't input any valid summand is to throw an exception:

```<code>def add(*p):
    summands = list(filter(None, p))
    if not summands:
        raise ValueError("There should be at least one defined value.")
    return sum(summands)

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None, 0))
# 0
print(add(0))
# 0
print(add(None))
# ValueError: There should be at least one defined value
print(add())
# ValueError: There should be at least one defined value
</code>```

Title: Handling None when adding numbers

Body:
With boolean logic:

Here's a Pythonic method, using lazy or:

def add(a, b):
    return (a or 0) + (b or 0)

With filter

For an arbitrary number of summands, you could use filter and sum:

def add(*p):
    return sum(filter(None, p))

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None))
# 0
print(add(None, 0))
# 0

With an exception

Note that the previous implementations will return 0 for add(None, None). This is the expected mathematical result of an empty sum.

Returning None is suprising and might lead to TypeErrors when you use the output of add.

One way to achieve the desired behaviour when users don't input any valid summand is to throw an exception:

def add(*p):
    summands = list(filter(None, p))
    if not summands:
        raise ValueError("There should be at least one defined value.")
    return sum(summands)

print(add(3))
# 3
print(add(3, 5))
# 8
print(add(3, 5, 7))
# 15
print(add(3, None))
# 3
print(add(None, 0))
# 0
print(add(0))
# 0
print(add(None))
# ValueError: There should be at least one defined value
print(add())
# ValueError: There should be at least one defined value


问:
Xamarin.Forms UWP - Display HTML in a Label
In Xamarin.Forms, how do I display HTML in a label? In other words, if I have new Label { Text = "some text and some bold text" }, I want it to display as "some text and some bold text".

I know I need to use a custom renderer, and I've implemented in iOS. I just don't know how to implement it in UWP.

答:
Maybe take a look at this https://blog.pieeatingninjas.be/2017/11/05/creating-a-hyperlinklabel-in-xamarin-forms/... It could be a good starting point to expand upon on what is still missing for your needs?

Currently it only supports hyperlinks, but the way to handle the  tag would be the same.