问:
Alert confirmed in Firefox but nothing happens after
Have a test that selects a radio button, and clicks a Delete button triggering a modal dialog/alert box pop up.

I'm using Cucumber so here's how the step works:

```<code>When /^i confirm the alert$/ do
      Watir::Wait.until(timeout: 10) {@browser.alert.exists?}
      puts "i see the alert"
      @browser.alert.ok
end
</code>```

I put in that lazy debug step because I was thinking this may be a browser/driver issue.

I've had this work in Chrome but it's not an option for the certain environment I'm in for this particular script.

Firefox is my only option and here is what happens:

"i see the alert" is returned

the dialog is confirmed on

then I receive unable to locate alert (Watir::Exception::UnknownObjectException)

I'm on Firefox 45 ESR / Selenium Webdriver 3.0.5

Not sure if it's a Firefox/Selenium compatibility issue or not?

The application doesn't do anything after the OK button is clicked on the alert

答:
Found the fix! And it was quite simple. I simply needed to send the Alert handling to Selenium instead of Watir.

Instead of calling the Watir::Alert class:

```<code>@browser.alert.ok
</code>```

I just needed to let Selenium handle it. This is working in both FF and Chrome now:

```<code>And(/^the user confirms the alert via selenium$/) do
    popup = @browser.driver.switch_to.alert
    popup.accept
end
</code>```

Body:
Have a test that selects a radio button, and clicks a Delete button triggering a modal dialog/alert box pop up.

I'm using Cucumber so here's how the step works:

When /^i confirm the alert$/ do
      Watir::Wait.until(timeout: 10) {@browser.alert.exists?}
      puts "i see the alert"
      @browser.alert.ok
end

I put in that lazy debug step because I was thinking this may be a browser/driver issue.

I've had this work in Chrome but it's not an option for the certain environment I'm in for this particular script.

Firefox is my only option and here is what happens:

"i see the alert" is returned

the dialog is confirmed on

then I receive unable to locate alert (Watir::Exception::UnknownObjectException)

I'm on Firefox 45 ESR / Selenium Webdriver 3.0.5

Not sure if it's a Firefox/Selenium compatibility issue or not?

The application doesn't do anything after the OK button is clicked on the alert

Body:
Found the fix! And it was quite simple. I simply needed to send the Alert handling to Selenium instead of Watir.

Instead of calling the Watir::Alert class:

@browser.alert.ok

I just needed to let Selenium handle it. This is working in both FF and Chrome now:

And(/^the user confirms the alert via selenium$/) do
    popup = @browser.driver.switch_to.alert
    popup.accept
end


来源: stackexchange

问:
Specflow hooks, how to get Inconclusive or Pending result?
I am having trouble detecting Inconclusive test results in the [AfterScenario] hook.

I've got a large suite of Specflow tests that I run most nights and in the hooks section I am logging whether the test passed or failed and some info on the tags, then at the end of the test run I output this to a file.
I am currently deciding whether a test has passed or failed by doing:

```<code>bool failed = ScenarioContext.Current.TestError != null;
string result = failed ? "failed" : "passed";
</code>```

This works most of the time, but when a test doesn't have all the steps completed (scenario result is inconclusive) that method reports the scenario as passing, which isn't really what I want. I've tried setting missingOrPendingStepsOutcome to error or ignore in App.Config, but neither of them have any effect upon the TestError property, so again it'll get calculated as "passed".

I've noticed a couple of handy-looking properties ( MissingSteps and PendingSteps ) in the ScenarioContext.Current, unfortunately they're private, so I can't access them.

I am using C#.4.5.2 and Specflow 1.9.0.77 with NUnit 2.6.4.14350 and running the tests in ReSharper 9.2's Unit Test Sessions window in Visual Studio Enterprise 2015 on Windows 7 x64

答:
@Florent B. solution is better but if you don't want to do it by reflexion, you can use a trick that i found in SpecFlow 1.9.

Indeed, the [BeforeStep] hook is never called when the step does not exists.

```<code>[BeforeScenario]
public void BeforeScenario()
{
    ScenarioContext.Current.Set(false, "HasNotImplementedStep");
}

[BeforeStep]
public void BeforeStep()
{
    ScenarioContext.Current.Set(true, "IsBeforeStepCalled");
}

[AfterStep]
public void AfterStep()
{
    var beforeStepCalled = ScenarioContext.Current.Get<bool>("IsBeforeStepCalled");
    if (!beforeStepCalled)
    {
        ScenarioContext.Current.Set(true, "HasNotImplementedStep");
    }

    ScenarioContext.Current.Set(false, "IsBeforeStepCalled");
}

[AfterScenario]
public void AfterScenario()
{
    var hasNotImplementedStep = ScenarioContext.Current.Get<bool>("HasNotImplementedStep");
    if (hasNotImplementedStep)
    {
        // Do your stuff
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble detecting Inconclusive test results in the [AfterScenario] hook.

I've got a large suite of Specflow tests that I run most nights and in the hooks section I am logging whether the test passed or failed and some info on the tags, then at the end of the test run I output this to a file.
I am currently deciding whether a test has passed or failed by doing:

bool failed = ScenarioContext.Current.TestError != null;
string result = failed ? "failed" : "passed";

This works most of the time, but when a test doesn't have all the steps completed (scenario result is inconclusive) that method reports the scenario as passing, which isn't really what I want. I've tried setting missingOrPendingStepsOutcome to error or ignore in App.Config, but neither of them have any effect upon the TestError property, so again it'll get calculated as "passed".

I've noticed a couple of handy-looking properties ( MissingSteps and PendingSteps ) in the ScenarioContext.Current, unfortunately they're private, so I can't access them.

I am using C#.4.5.2 and Specflow 1.9.0.77 with NUnit 2.6.4.14350 and running the tests in ReSharper 9.2's Unit Test Sessions window in Visual Studio Enterprise 2015 on Windows 7 x64

Body:
@Florent B. solution is better but if you don't want to do it by reflexion, you can use a trick that i found in SpecFlow 1.9.

Indeed, the [BeforeStep] hook is never called when the step does not exists.

[BeforeScenario]
public void BeforeScenario()
{
    ScenarioContext.Current.Set(false, "HasNotImplementedStep");
}

[BeforeStep]
public void BeforeStep()
{
    ScenarioContext.Current.Set(true, "IsBeforeStepCalled");
}

[AfterStep]
public void AfterStep()
{
    var beforeStepCalled = ScenarioContext.Current.Get<bool>("IsBeforeStepCalled");
    if (!beforeStepCalled)
    {
        ScenarioContext.Current.Set(true, "HasNotImplementedStep");
    }

    ScenarioContext.Current.Set(false, "IsBeforeStepCalled");
}

[AfterScenario]
public void AfterScenario()
{
    var hasNotImplementedStep = ScenarioContext.Current.Get<bool>("HasNotImplementedStep");
    if (hasNotImplementedStep)
    {
        // Do your stuff
    }
}


问:
ASP.NET MVC with EF and the Dispose Pattern
I'm writing an ASP.NET MVC application with EF. I have some questions regarding whether or not my approach is reasonable. Note: I simplified my basic structure for this question, in realitiy everything is coupled more loosely.

Let's assume a View that allows a user to change properties of a complex domain model. The data originates from the Database (via EF) and has to be written back again in the end.

From my understanding, each request results in a new controller instance being called. Therefore, I'm using the 'Dispose Pattern' described here as Option 2, which ensures a new DbContext for every request:

```<code>public class MyController : Controller
{
    private MyContext repo = new MyContext();

    protected override void Dispose(bool disposing)
    {
        this.repo.Dispose();
        base.Dispose(disposing);
    }

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

Now there is a public ActionResult Edit(elementId) method on the controller that will fetch an element from the database and displays an editor for it. Once this request is finished, any reference to the Dbcontext is gone, but I still have access to the Entity-Object fetched from the DB as I store it in my session.

Later on the user presses a 'Save' button on the View. The request to the Save-method of my Controller once again creates a new instance of the Controller and therefore a new DbContext. The Entity-object stored in my session is retrieved and its properties are modified according to the user's input. To save the new state to the database, I have to attach it to the new context:

```<code>public void Save()
{
    this.repo.MyTable.Attach(myEntity);
    myEntity.Name = "New Name";
    this.repo.SaveChanges();
}
</code>```

This can only work once the old Controller with the original DbContext of myEntity has been disposed, otherwise 'Attach' would fail (unable to attach Entity to two contexts). I'm concerned whether or not I can rely on the old DbContext being disposed here.

Also: I know that using an IoC framework would be an alternative. How would that apply to my situation, what would be the benefits?

答:
I think you've redacted too much of your code in an effort to "simplify" the question, and as a result, have actually obscured some important issues. However, based on the Save method you've posted, I can pretty well guess your issue. Your repo is most likely creating it's own context, which is a pretty big no-no.

To answer you overall question, the rationale for implementing IDisposable here is the same as anywhere else: any class that owns dependencies that implement IDisposable should also implement IDisposable. Here, your controller instantiates MyContext, so it should therefore dispose of MyContext when its done. Simple as that.

However, if you introduce dependency injection, and inject the context into the controller, then the controller no longer owns the context. Instead, the DI container will own it. Therefore, your controller should not dispose of the context, as it does not own it.

And, you should use dependency injection here. Your context should be injected into your repository and then your repository should be injected into your controller. This ensures that there's is only one context instance, and you won't have issues like you're experiencing now, where EF complains that the entity belongs to a different context.

Finally, I just want to parrot @SteveGreene in saying that there is absolutely no reason to store your entity in the session, and in fact there's many reasons you shouldn't, not the least of which being it will frustrate any efforts to move away from In Proc sessions to a more reliable session store. Once you're using something like StateServer, SQL Server, Redis, etc., anything you put in the session must be serializable, and entities are often quite difficult if not impossible to serialize, since they often have many relationships with other entities and often circular relationships with those entities.

Body:
I'm writing an ASP.NET MVC application with EF. I have some questions regarding whether or not my approach is reasonable. Note: I simplified my basic structure for this question, in realitiy everything is coupled more loosely.

Let's assume a View that allows a user to change properties of a complex domain model. The data originates from the Database (via EF) and has to be written back again in the end.

From my understanding, each request results in a new controller instance being called. Therefore, I'm using the 'Dispose Pattern' described here as Option 2, which ensures a new DbContext for every request:

public class MyController : Controller
{
    private MyContext repo = new MyContext();

    protected override void Dispose(bool disposing)
    {
        this.repo.Dispose();
        base.Dispose(disposing);
    }

    //more code...
}

Now there is a public ActionResult Edit(elementId) method on the controller that will fetch an element from the database and displays an editor for it. Once this request is finished, any reference to the Dbcontext is gone, but I still have access to the Entity-Object fetched from the DB as I store it in my session.

Later on the user presses a 'Save' button on the View. The request to the Save-method of my Controller once again creates a new instance of the Controller and therefore a new DbContext. The Entity-object stored in my session is retrieved and its properties are modified according to the user's input. To save the new state to the database, I have to attach it to the new context:

public void Save()
{
    this.repo.MyTable.Attach(myEntity);
    myEntity.Name = "New Name";
    this.repo.SaveChanges();
}

This can only work once the old Controller with the original DbContext of myEntity has been disposed, otherwise 'Attach' would fail (unable to attach Entity to two contexts). I'm concerned whether or not I can rely on the old DbContext being disposed here.

Also: I know that using an IoC framework would be an alternative. How would that apply to my situation, what would be the benefits?


问:
How to ensure that MySQL column only accepts X number of characters?
I've been doing some searching on the Internet, but I can't for the life figure this out:

Can I force a MySQL table column to ONLY accept a set number of characters (e.g. 5 numbers ONLY, not 4 numbers nor 6 numbers)? I've read the MySQL documentation for some various data types but haven't really discovered anything yet.

In a rather unfortunate move, I can't perform reg-ex checking in PHP that easily right now, and would like to take the easy way out by forcing this check in the database itself. Thanks in advance!

答: you need to write a layer of code to do things like  trigger BEFORE INSERT

ContentLicense: CC BY-SA 2.5


问:
Slicing each line from data CSV file
I have a movie dataset that looks like this:

```<code>1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children
</code>```

I want to extract only the last part (genres part, e.g, Adventure|Animation|Children|Comedy|Fantasy) and store them in a list list[Adventure, Animation, Children, Comedy, Fantasy]. However, I am still stuck at slicing step. I don't know how to do that since line[:-1] doesn't slice. I use Python 2.7

```<code>with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]
</code>```

答:
```<code>with open(path + 'movie.csv') as f:
    for line in f:
        print line.split(',')[:-1].rstrip('\n').split('|')
</code>```

Title: Slicing each line from data CSV file

Body:
I have a movie dataset that looks like this:

1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children

I want to extract only the last part (genres part, e.g, Adventure|Animation|Children|Comedy|Fantasy) and store them in a list list[Adventure, Animation, Children, Comedy, Fantasy]. However, I am still stuck at slicing step. I don't know how to do that since line[:-1] doesn't slice. I use Python 2.7

with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]


问:
Asp.net MVC Authentication issue
I created two different asp.net MVC application using the default template, and launches the two simultaneously, when I login with site a, and refresh site b, site b tries to use the login detail of site a. How do I stop it?</p>

答:
I suspect you are having an issue with the AntiForgery tokens. Something I add by default to my new MVC projects is this (add to Global.asax) :

```<code>AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
</code>```

I think this SO answer provides a fairly complete overview

Title: Asp.net MVC Authentication issue

Body:
I suspect you are having an issue with the AntiForgery tokens. Something I add by default to my new MVC projects is this (add to Global.asax) :

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

I think this SO answer provides a fairly complete overview


问:
Batch file and DEL errorlevel 0 issue
The batch has to remove files and directories from specific locations and output success or stdout/stderr messages to a new .txt file. I have created the most of the script and it performs exactly as it should, except when the deletion is successful it moves forward to the next line rather than echo a 'successful' message on the log.

```<code>echo Basic Deletion Batch Script > results.txt
@echo off
call :filelog >> results.txt 2>&1
notepad results.txt
exit /b

:filelog

call :delete new.txt
call :delete newer.txt
call :delete newest.txt
call :remove c:\NoSuchDirectory

GOTO :EOF

:delete
echo deleting %1
del /f /q c:\Users\newuser\Desktop\%1
if errorlevel 0 echo succesful

GOTO :EOF

:remove
echo deleting directory %1
rmdir /q /s %1

GOTO :EOF
</code>```

For some reason I can't find the syntax for if del succeeds echo 'successful'. In the above example if I remove the line

```<code>if errorlevel 0 echo successful
</code>```

Everything works fine, but no success message. With this line left in it echoes success for every line.

答:
The answer of aschipfl is great (thanks, helped me a lot!) using the code under Presetting ErrorLevel you get a nice standard function:

Take care to use %~1 instead of %1 in the del statement, or you will get errors if you use a quoted filename.

```<code>::######################################################################
::call :DELETE "file.txt"
::call :DELETE "file.txt" "error message"
:DELETE
  >nul ver && for /F "tokens=*" %%# in ('del /F /Q "%~1" 2^>^&1 1^> nul') do (2>nul set =) || (
    if NOT .%2==. echo %~2
  )
goto :EOF
</code>```

BTW 1: You can give a nifty error message as a second parameter

BTW 2: Using :: instead of REM for comments makes the code even more readable.

Title: Batch file and DEL errorlevel 0 issue

Body:
The batch has to remove files and directories from specific locations and output success or stdout/stderr messages to a new .txt file. I have created the most of the script and it performs exactly as it should, except when the deletion is successful it moves forward to the next line rather than echo a 'successful' message on the log.

echo Basic Deletion Batch Script > results.txt
@echo off
call :filelog >> results.txt 2>&1
notepad results.txt
exit /b

:filelog

call :delete new.txt
call :delete newer.txt
call :delete newest.txt
call :remove c:\NoSuchDirectory

GOTO :EOF

:delete
echo deleting %1
del /f /q c:\Users\newuser\Desktop\%1
if errorlevel 0 echo succesful

GOTO :EOF

:remove
echo deleting directory %1
rmdir /q /s %1

GOTO :EOF

For some reason I can't find the syntax for if del succeeds echo 'successful'. In the above example if I remove the line

if errorlevel 0 echo successful

Everything works fine, but no success message. With this line left in it echoes success for every line.

Body:
The answer of aschipfl is great (thanks, helped me a lot!) using the code under Presetting ErrorLevel you get a nice standard function:

Take care to use %~1 instead of %1 in the del statement, or you will get errors if you use a quoted filename.

::######################################################################
::call :DELETE "file.txt"
::call :DELETE "file.txt" "error message"
:DELETE
  >nul ver && for /F "tokens=*" %%# in ('del /F /Q "%~1" 2^>^&1 1^> nul') do (2>nul set =) || (
    if NOT .%2==. echo %~2
  )
goto :EOF

BTW 1: You can give a nifty error message as a second parameter

BTW 2: Using :: instead of REM for comments makes the code even more readable.


问:
Escaping 2017-03-30 gives 7-03-30 Javascript
I am trying to output the current page URL for Disqus comments. Since my page URL structure is like:

https://www.example.com/post/1234/2017-03-30/
```

<p>I am having a little issue with escaping 2017-03-30.</p>

<p>I don't know if this has been asked before, I tried searching for reasonable answer but couldn't find any. I am trying to escape date, since including it like 2017-03-30 will only subtract it. </p>

<p>This is the PHP code that outputs Javascript:</p>

<pre class="lang-php prettyprint-override"><code>echo 'this.page.url = "https://www.example.com/post/'. $id . '/\\'. $date . '\\/";';
</code>```

Although the output would be:

```<code>this.page.url = "https://www.example.com/post/1234/\2017-03-30\/";
</code>```

But the problem is Disqus will show the URL like:

https://www.example.com/post/1234/7-03-30
```

I know the problem is with \201 but what I don't know is how to fix it. I tried different ways. Nothing seems to be working. I am pretty much lost here. :/

答:
In a JavaScript string, \201 is an octal escape, giving you the character U+0081, which is an unused control character and therefore not displayed.

If the backslash is actually needed, you will need to double-escape it so that the resulting JavaScript looks like \\2017-03-30\\, so the PHP would need to be \\\\'.$date.'\\\\

When you get this many backslashes, though, it's a sure sign you're doing something wrong.

Body:
I am trying to output the current page URL for Disqus comments. Since my page URL structure is like:

https://www.example.com/post/1234/2017-03-30/

I am having a little issue with escaping 2017-03-30.

I don't know if this has been asked before, I tried searching for reasonable answer but couldn't find any. I am trying to escape date, since including it like 2017-03-30 will only subtract it.

This is the PHP code that outputs Javascript:

echo 'this.page.url = "https://www.example.com/post/'. $id . '/\\'. $date . '\\/";';

Although the output would be:

this.page.url = "https://www.example.com/post/1234/\2017-03-30\/";

But the problem is Disqus will show the URL like:

https://www.example.com/post/1234/7-03-30

I know the problem is with \201 but what I don't know is how to fix it. I tried different ways. Nothing seems to be working. I am pretty much lost here. :/


答:
Is it not possible for you to check the length of string for that column in php before sending it to database?

If you still need it in database level then, there is function Length in mysql. you might want to check it out.

Title: How to ensure that MySQL column only accepts X number of characters?

Body:
I've been doing some searching on the Internet, but I can't for the life figure this out:

Can I force a MySQL table column to ONLY accept a set number of characters (e.g. 5 numbers ONLY, not 4 numbers nor 6 numbers)? I've read the MySQL documentation for some various data types but haven't really discovered anything yet.

In a rather unfortunate move, I can't perform reg-ex checking in PHP that easily right now, and would like to take the easy way out by forcing this check in the database itself. Thanks in advance!


问:
MySQL Complex Count Issue
I am trying to do a query whereby if a football team wins a home game (e.g. Liverpool FC) then a 1 is added to a column, and the same for a loss (which would be AwayWins, and a draw would be 'Draw').

The following query works great, it just compares the goals scores and adds the 1 in the appropriate place.

```<code>SELECT *,
    IF(max(`goalsHomeTeam`)>`awayTeamName`,'1','') as HomeWins,
    IF(max(`goalsHomeTeam`)<`awayTeamName`,'1','') as AwayWins,
    IF(max(`goalsHomeTeam`)=`awayTeamName`,'1','') as Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY fixtures_id
LIMIT 10
</code>```

And this looks like:

However, what I'd really like to display is just the 3 fields:

HomeWins, AwayWins and Draw

and then a count for each box (e.g. based on the picture above HomeWins: 9, AwayWins: 0 and Draw: 0.

I've tried adding simple stuff like wrapping a count around the IF's but that didn't work. Any advice?

答:
You could try this query  </p>

```<code>SELECT
    SUM(IF(`goalsHomeTeam` > `awayTeamName`,1,0)) AS HomeWins,
    SUM(IF(`goalsHomeTeam` < `awayTeamName`,1,0)) AS AwayWins,
    SUM(IF(`goalsHomeTeam` = `awayTeamName`,1,0)) AS Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY `homeTeamName`
</code>```

Title: MySQL Complex Count Issue

Body:
I am trying to do a query whereby if a football team wins a home game (e.g. Liverpool FC) then a 1 is added to a column, and the same for a loss (which would be AwayWins, and a draw would be 'Draw').

The following query works great, it just compares the goals scores and adds the 1 in the appropriate place.

SELECT *,
    IF(max(`goalsHomeTeam`)>`awayTeamName`,'1','') as HomeWins,
    IF(max(`goalsHomeTeam`)<`awayTeamName`,'1','') as AwayWins,
    IF(max(`goalsHomeTeam`)=`awayTeamName`,'1','') as Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY fixtures_id
LIMIT 10

And this looks like:

However, what I'd really like to display is just the 3 fields:

HomeWins, AwayWins and Draw

and then a count for each box (e.g. based on the picture above HomeWins: 9, AwayWins: 0 and Draw: 0.

I've tried adding simple stuff like wrapping a count around the IF's but that didn't work. Any advice?

Body:
You could try this query

SELECT
    SUM(IF(`goalsHomeTeam` > `awayTeamName`,1,0)) AS HomeWins,
    SUM(IF(`goalsHomeTeam` < `awayTeamName`,1,0)) AS AwayWins,
    SUM(IF(`goalsHomeTeam` = `awayTeamName`,1,0)) AS Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY `homeTeamName`


问:
Front end development: where to start?
I'm very sorry if that question has been asked already, couldn't find anything closely related though.

By now I've pretty much learned HTML/HTML5, CSS/3, learned using JQuery (not saying there's nowhere to improve, obviously there is). I really want to start learning front-end dev (client MVC, etc). I've started learning backbone.js, but it turns out i'm having difficulties learning it. Am I missing something? I've read "JS: Good Parts" and Javascript Garden is basically my go-to source yet I still get confused.

I'd appreciate any recommendations as to what I should learn/practice first, thanks :)

答: A free online resource is w3schools, it teaches you back-end too(PhP and mySQL).I really suggest you to learn Angular2, this is a great js framework that most front-end developers use. Always practice,code at least 2 hours a day, make a lot of websites for your portofolio, learn how to make slideshows and animated text, you can even learn how to make a working login page, and a working contact form(a lot of cients want theese stuff). Learn photoshop and illustrator because clients want great design these days.One thing you have to remember is that you never stop learning,if you ever think that you finished learning it emans that you are at the beginning.Good luck and never forget the semicolons :) </p>

Title: Front end development: where to start?


问:
How to get the name of calling bat script
I need to have my 2.bat script behaviour depending on the name of calling script.

Scenario:
2.bat is invoked from many other external scripts, which I am not entitled to change. Only 2.bat is under my thumb.

1.bat:

```<code>...
call 2.bat
</code>```

2.bat:

```<code>...here place something extracting "1.bat"...
</code>```

答:
You can get the name of a calling batch with a trick.

Assuming you have a first.bat(you can't controll) it could look like this

```<code>@echo off
set caller=empty
echo This is %~0

for /L %%n in (1 1 3) do (
    echo(
    echo #1 before calling, n=%%n
    call second %%n
)

echo Back to %~0
</code>```

And your second.bat detects the caller

```<code>@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)
REM *** Get the name of the caller
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:mainFunc\..%~pnx0" %*
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:mainFunc\..%~pnx0" %*"
    )
    echo BACK
    endlocal
)
echo NEVER REACHED
exit /b

:mainFunc
echo :mainFunc of %~nx0 arg1=%1 is called from '%caller%'/%callType%
exit /b
</code>```

Body:
I need to have my 2.bat script behaviour depending on the name of calling script.

Scenario:
2.bat is invoked from many other external scripts, which I am not entitled to change. Only 2.bat is under my thumb.

1.bat:

...
call 2.bat

2.bat:

...here place something extracting "1.bat"...

Body:
You can get the name of a calling batch with a trick.

Assuming you have a first.bat(you can't controll) it could look like this

@echo off
set caller=empty
echo This is %~0

for /L %%n in (1 1 3) do (
    echo(
    echo #1 before calling, n=%%n
    call second %%n
)

echo Back to %~0

And your second.bat detects the caller

@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)
REM *** Get the name of the caller
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:mainFunc\..%~pnx0" %*
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:mainFunc\..%~pnx0" %*"
    )
    echo BACK
    endlocal
)
echo NEVER REACHED
exit /b

:mainFunc
echo :mainFunc of %~nx0 arg1=%1 is called from '%caller%'/%callType%
exit /b


问:
Accordion Toggle Arrows in Category Selection
i've made a codepen to make this as simple as possible. Open up the tree with the arrows and then click the word to 'select' that category.
http://codepen.io/johnsonjpj/pen/JWebwx?editors=0010

The issue I am having is that when I click a nested category its parents arrows are flipping to the right arrow instead of staying as the down arrow.

The main bit of code i'm working with for this piece is here:

```<code>var thisParents = $(this).parents('.list-group').not('.list-group-root');
$(".list-group").not(thisParents).collapse('hide');
$(".list-group").not(thisParents).find('.fa-chevron-down').addClass('fa-chevron-right').removeClass('fa-chevron-down');
</code>```

Thanks in advance!

答:
I have figured out how to solve my issue.</p>

```<code>var thisParents = $(this).parents('.list-group').not('.list-group-root');
$(".list-group").not(thisParents).collapse('hide');

var parentIcons = $(thisParents).prev('.list-group-item').find('.fa');
$(".list-group").find('.fa-chevron-down').not(parentIcons).addClass('fa-chevron-right').removeClass('fa-chevron-down');
</code>```

Body:
i've made a codepen to make this as simple as possible. Open up the tree with the arrows and then click the word to 'select' that category.
http://codepen.io/johnsonjpj/pen/JWebwx?editors=0010

The issue I am having is that when I click a nested category its parents arrows are flipping to the right arrow instead of staying as the down arrow.

The main bit of code i'm working with for this piece is here:

var thisParents = $(this).parents('.list-group').not('.list-group-root');
$(".list-group").not(thisParents).collapse('hide');
$(".list-group").not(thisParents).find('.fa-chevron-down').addClass('fa-chevron-right').removeClass('fa-chevron-down');

Thanks in advance!

Body:
I have figured out how to solve my issue.

var thisParents = $(this).parents('.list-group').not('.list-group-root');
$(".list-group").not(thisParents).collapse('hide');

var parentIcons = $(thisParents).prev('.list-group-item').find('.fa');
$(".list-group").find('.fa-chevron-down').not(parentIcons).addClass('fa-chevron-right').removeClass('fa-chevron-down');


问:
Related to datastage. Adding user variable to parameter
I have an user variable (say for ex var_ts) that stores the timestamp using the user variable stage in the job sequence.

Now I want to use the variable value in other jobs in the same job sequence.

How do I add it as a parameter, because when I am adding it the variable name is coming and not the timestamp within.

答:
You must use Activity Variable on Value Expression of Job Activity parameter.

On the following images there is a sequence with a User Variable UV and an Job Activity that call the job calledJob. On the UV, there is a variable var_ts valued with manipulation on timestamp.

The job calledJob want a only parameter, Timestamp. On the Properties of Job Activity calledJob, for the Timestamp parameter, select Activity Variable by 3 dot on right.

Now, select UV.var_ts for pass the User Variable value to job.


问:
Python mask image pixels from a set of values
Provided an image with labels (the value of a pixel corresponds to its label), and the list of labels that are accepted, I am trying to create a "mask" image with 255 value if the pixels label is accepted, 0 otherwise.

I know that this is a slow approach as it iterates over the image at python-speed (but it demonstrates the idea well):

```<code>mask = numpy.zeros(labels.shape[:2], dtype = "uint8")

for i in xrange(mask.shape[0]):
    for j in xrange(mask.shape[1]):
        if labels[i][j] in accepted:
            mask[i][j] = 255
</code>```

I know that it is much faster to use python slicing and masking, but I do not know how to compose a complicated condition. I still get a tremendous speed-up when I mask the pixels one-by-one accepted label, like so:

```<code>for value in accepted:
    mask[labels == value] = 255
</code>```

Can I somehow make a one-liner doing what I want? My python knowledge is rusty (read: almost no python in the last few years), so while I tried composing this using some examples I found, this is the closest I got:

```<code>mask[(labels in accepted).all()] = 255
</code>```

And in this case I get the following error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've looked at similar SO questions (e.g.here or here and more) but they all seem to cover the cases where either the values are from a range or lower/higher than a threshold (<10) , or where the image slice to change is continuous.

Any suggestion on how check "is value among accepted values" would be great.

答:
In the meantime, I found an acceptable-speed solution to my own question:

```<code>mask = numpy.zeros(labels.shape[:2], dtype = "uint8")
mask[numpy.in1d(labels, accepted).reshape(mask.shape)] = 255
</code>```

It consists in first using numpy.in1d to get a boolean array from the labels array, and check which ones are present in accepted (element-wise function of the python keyword "in").

As this apparently necessarily returns a 1D array, even if it can be applied to a 2D array (it simply unravels the array), so I follow by using reshape() to make the boolean array dimensions correspond to that of the mask.

Finally, I use this boolean array to index the required elements of mask and set them to a desired value.

Body:
Provided an image with labels (the value of a pixel corresponds to its label), and the list of labels that are accepted, I am trying to create a "mask" image with 255 value if the pixels label is accepted, 0 otherwise.

I know that this is a slow approach as it iterates over the image at python-speed (but it demonstrates the idea well):

mask = numpy.zeros(labels.shape[:2], dtype = "uint8")

for i in xrange(mask.shape[0]):
    for j in xrange(mask.shape[1]):
        if labels[i][j] in accepted:
            mask[i][j] = 255

I know that it is much faster to use python slicing and masking, but I do not know how to compose a complicated condition. I still get a tremendous speed-up when I mask the pixels one-by-one accepted label, like so:

for value in accepted:
    mask[labels == value] = 255

Can I somehow make a one-liner doing what I want? My python knowledge is rusty (read: almost no python in the last few years), so while I tried composing this using some examples I found, this is the closest I got:

mask[(labels in accepted).all()] = 255

And in this case I get the following error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've looked at similar SO questions (e.g.here or here and more) but they all seem to cover the cases where either the values are from a range or lower/higher than a threshold (<10) , or where the image slice to change is continuous.

Any suggestion on how check "is value among accepted values" would be great.

Body:
In the meantime, I found an acceptable-speed solution to my own question:

mask = numpy.zeros(labels.shape[:2], dtype = "uint8")
mask[numpy.in1d(labels, accepted).reshape(mask.shape)] = 255

It consists in first using numpy.in1d to get a boolean array from the labels array, and check which ones are present in accepted (element-wise function of the python keyword "in").

As this apparently necessarily returns a 1D array, even if it can be applied to a 2D array (it simply unravels the array), so I follow by using reshape() to make the boolean array dimensions correspond to that of the mask.

Finally, I use this boolean array to index the required elements of mask and set them to a desired value.


问:
Where in the Sabre API can I find commissionable rates on premium air travel (first and business) and hotels?
I'm looking to better understand what travel agents can earn on the products and services they sell, excluding fees.   </p>

答:
Airline commissions are almost never listed in any air pricing responses from carriers; they are mostly negotiated between the carriers and the TMCs privately (when they exist at all). Looking for that kind of info using a Sabre API is likely not going to work.

Hotel commissions are generally 10% unless otherwise listed in the pricing response as Non-Commissionable. In my experience, each hotel chain can return different verbiage about Commissionable vs. Non-Commissionable hotels in their pricing responses.


问:
WPF Combobox Background for Different Selected item
I have Combobox with Just 3 item : Planing, Progress and Done,

```<code><ComboBox SelectedIndex="0>
    <ComboBoxItem Content="Planing"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>
</code>```

How Can i Change Background Color Of ComboBox (which is by defult Gradiant) Depend on Which Item is Selected.

For Example : purple for Planing, blue for Progress and Green for Done.

Note: I mean ComboBox Background, not ComboBox Items List.

Thanks

答:
1) Using selectionChanged event

You could set it up in the comboBox_SelectionChanged event

```<code>private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox.SelectedItem.ToString() == "Planning")
    {
        comboBox.Background = Brushes.Purple;
    }
    else if (comboBox.SelectedItem.ToString() == "Progress")
    {
        comboBox.Background = Brushes.Blue;
    }
    else if (comboBox.SelectedItem.ToString() == "Done")
    {
        comboBox.Background = Brushes.Green;
    }
}
</code>```

The comboBox_SelectionChanged event will be called each time the selected value in the combobox is changed. Inside it you can simply verify the value of the selected item and apply the color you want.

This would be the xaml of the Combobox

```<code><ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>
</code>```

2) Using DataTriggers in XAML

It can also be done through the xaml by setting up multiple DataTrigger on the Style.Triggers like this

```<code><ComboBox x:Name="mycombobox">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Planning">
                    <Setter Property="Background" Value="Purple" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Progress">
                    <Setter Property="Background" Value="Blue" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Done">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    <ComboBoxItem Content="Planning"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>
</code>```

More information on DataTriggers:

Represents a trigger that applies property values or performs actions when the bound data meets a specified condition.

Body:
I have Combobox with Just 3 item : Planing, Progress and Done,

<ComboBox SelectedIndex="0>
    <ComboBoxItem Content="Planing"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

How Can i Change Background Color Of ComboBox (which is by defult Gradiant) Depend on Which Item is Selected.

For Example : purple for Planing, blue for Progress and Green for Done.

Note: I mean ComboBox Background, not ComboBox Items List.

Thanks

Body:
1) Using selectionChanged event

You could set it up in the comboBox_SelectionChanged event

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (comboBox.SelectedItem.ToString() == "Planning")
    {
        comboBox.Background = Brushes.Purple;
    }
    else if (comboBox.SelectedItem.ToString() == "Progress")
    {
        comboBox.Background = Brushes.Blue;
    }
    else if (comboBox.SelectedItem.ToString() == "Done")
    {
        comboBox.Background = Brushes.Green;
    }
}

The comboBox_SelectionChanged event will be called each time the selected value in the combobox is changed. Inside it you can simply verify the value of the selected item and apply the color you want.

This would be the xaml of the Combobox

<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged"/>

2) Using DataTriggers in XAML

It can also be done through the xaml by setting up multiple DataTrigger on the Style.Triggers like this

<ComboBox x:Name="mycombobox">
    <ComboBox.Style>
        <Style TargetType="{x:Type ComboBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Planning">
                    <Setter Property="Background" Value="Purple" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Progress">
                    <Setter Property="Background" Value="Blue" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=SelectedItem.Content, ElementName=mycombobox}" Value="Done">
                    <Setter Property="Background" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ComboBox.Style>
    <ComboBoxItem Content="Planning"/>
    <ComboBoxItem Content="Progress"/>
    <ComboBoxItem Content="Done"/>
</ComboBox>

More information on DataTriggers:

Represents a trigger that applies property values or performs actions when the bound data meets a specified condition.


问:
HTML Email Styling Issue
I have the current HTML email template to go out automagically to end user.

But the email that arrives seems to be formatted incorrectly..

Here is HTML code I have:

You've been sent a job opportunity

%EMAIL_YOUR_EMAIL% thought you might be interested the following role, currently being advertised on #

%EMAIL_POST_TITLE% advertised by %EMAIL_POST_AUTHOR%

%EMAIL_POST_CONTENT%

© %EMAIL_BLOG_NAME%, 2017

```

Which should include a grey background behind the email. But when recipient receives the email it doesn't include the grey background.. o_O

Here is an image showing the issue I'm facing

Does anyone have any ideas / can help? :)

答: It looks like you've checked this in Outlook. Have you tried another email client like Gmail? Outlook pretty much always makes emails look a bit different from how they're coded. I use Robly for work and those emails are always slightly different in Outlook compared to every other email client. </p>

Title: HTML Email Styling Issue

Body:
I have the current HTML email template to go out automagically to end user.

But the email that arrives seems to be formatted incorrectly..

Here is HTML code I have:

You've been sent a job opportunity

%EMAIL_YOUR_EMAIL% thought you might be interested the following role, currently being advertised on #

%EMAIL_POST_TITLE% advertised by %EMAIL_POST_AUTHOR%

%EMAIL_POST_CONTENT%

© %EMAIL_BLOG_NAME%, 2017

Which should include a grey background behind the email. But when recipient receives the email it doesn't include the grey background.. o_O

Here is an image showing the issue I'm facing

Does anyone have any ideas / can help? :)


问:
Multiple Shared Elements
I have the following situation inside of a soccer application.

We want to implement the shared elements between all these activities.

In my viewholder on the first Activity for the match I have set a android:transitionName which corresponds to the same transitionName on the second Activity.

```<code><!-- item_viewholder (first activity) -->
<CustomViewContainingImageViewAndTextView
     android:id="@+id/item_match_hometeam"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:transitionName="@string/transition_morph_match_header_homeTeam" />

<!-- header (second activity) -->
<CustomViewContainingImageViewAndTextView
     android:id="@+id/item_match_hometeam_header"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:transitionName="@string/transition_morph_match_header_homeTeam" />
</code>```

I start the second Activity with

```<code>final String awayTeamTransition = activityContext.getString(R.string.transition_morph_match_header_awayTeam);
final String homeTeamTransition = activityContext.getString(R.string.transition_morph_match_header_homeTeam);
final ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                   activityContext,
                   Pair.create(homeTeam, homeTeamTransition),
                   Pair.create(awayTeam, awayTeamTransition));
activityContext.startActivity(intent, options.toBundle());
</code>```

Now this transition works fine but what if I want to have an even deeper detail.

Displaying statistics about the selected team and I want to have shared transition there too?

I tried setting the transitionName programmatically when the CustomViewContainingImageViewAndTextView was clicked to the new transitionName.

```<code>final String teamViewTransition = activityContext.getString(R.string.transition_morph_teamview_to_detail);
//teamView is the view that was clicked.
ViewCompat.setTransitionName(teamView, teamViewTransition);

final ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
     activityContext,
     Pair.create(teamView, teamViewTransition));
activityContext.startActivity(teamInfoActivityIntent, options.toBundle());
</code>```

this transitionName corresponds to the ImageView on the third Activity

```<code><ImageView
   android:id="@+id/team_info_header_logo"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:transitionName="@string/transition_morph_teamview_to_detail" />
</code>```

However the enterTransition fails, but the exitTransition works!

However this breaks the exitTransition from 2 --> 1

Sight.
Hope someone takes some time to figure this out.

Thanks in advance

答:
I had this doubt myself, but I feel like the answer above is a little bit confusing. To put it simply if you have more than one shared elements to animate, you can create "Pair" of View & transitionName as much as you want. Here is a sample code for this:</p>

```<code>    Pair statusAnim = Pair.create(holder.getOrderStatusView(), "track_job_status");
    Pair driverBundleAnim = Pair.create(holder.getDriverProfileBundle(), "driver_profile_bundle");
    ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation((Activity) context, statusAnim, driverBundleAnim);
    context.startActivity(new Intent(context, TrackingActivity.class), transitionActivityOptions.toBundle());
</code>```

Title: Multiple Shared Elements

Body:
I have the following situation inside of a soccer application.

We want to implement the shared elements between all these activities.

In my viewholder on the first Activity for the match I have set a android:transitionName which corresponds to the same transitionName on the second Activity.

<CustomViewContainingImageViewAndTextView
     android:id="@+id/item_match_hometeam"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:transitionName="@string/transition_morph_match_header_homeTeam" />

<CustomViewContainingImageViewAndTextView
     android:id="@+id/item_match_hometeam_header"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:transitionName="@string/transition_morph_match_header_homeTeam" />

I start the second Activity with

final String awayTeamTransition = activityContext.getString(R.string.transition_morph_match_header_awayTeam);
final String homeTeamTransition = activityContext.getString(R.string.transition_morph_match_header_homeTeam);
final ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                   activityContext,
                   Pair.create(homeTeam, homeTeamTransition),
                   Pair.create(awayTeam, awayTeamTransition));
activityContext.startActivity(intent, options.toBundle());

Now this transition works fine but what if I want to have an even deeper detail.

Displaying statistics about the selected team and I want to have shared transition there too?

I tried setting the transitionName programmatically when the CustomViewContainingImageViewAndTextView was clicked to the new transitionName.

final String teamViewTransition = activityContext.getString(R.string.transition_morph_teamview_to_detail);
//teamView is the view that was clicked.
ViewCompat.setTransitionName(teamView, teamViewTransition);

final ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
     activityContext,
     Pair.create(teamView, teamViewTransition));
activityContext.startActivity(teamInfoActivityIntent, options.toBundle());

this transitionName corresponds to the ImageView on the third Activity

<ImageView
   android:id="@+id/team_info_header_logo"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:transitionName="@string/transition_morph_teamview_to_detail" />

However the enterTransition fails, but the exitTransition works!

However this breaks the exitTransition from 2 --> 1

Sight.
Hope someone takes some time to figure this out.

Thanks in advance

Body:
I had this doubt myself, but I feel like the answer above is a little bit confusing. To put it simply if you have more than one shared elements to animate, you can create "Pair" of View & transitionName as much as you want. Here is a sample code for this:

    Pair statusAnim = Pair.create(holder.getOrderStatusView(), "track_job_status");
    Pair driverBundleAnim = Pair.create(holder.getDriverProfileBundle(), "driver_profile_bundle");
    ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation((Activity) context, statusAnim, driverBundleAnim);
    context.startActivity(new Intent(context, TrackingActivity.class), transitionActivityOptions.toBundle());


问:
Dotted polyline on Google Maps IOS-Swift
I want to draw a dotted polyline on Google Maps using swift language, can anyone to help me?</p>

答:
Reference to the following link: http://www.appcoda.com/google-maps-api-tutorial/ that may be of help.

```<code>func drawRoute() {
    let route = mapTasks.overviewPolyline["points"] as String

    let path: GMSPath = GMSPath(fromEncodedPath: route)
    routePolyline = GMSPolyline(path: path)
    routePolyline.map = viewMap
}
</code>```

At the end of the above snippet, we necessarily have to set the map to the routePolyline property.

```<code>func displayRouteInfo() {
    lblInfo.text = mapTasks.totalDistance + "\n" + mapTasks.totalDuration
}
</code>```

Body:
Reference to the following link: http://www.appcoda.com/google-maps-api-tutorial/ that may be of help.

func drawRoute() {
    let route = mapTasks.overviewPolyline["points"] as String

    let path: GMSPath = GMSPath(fromEncodedPath: route)
    routePolyline = GMSPolyline(path: path)
    routePolyline.map = viewMap
}

At the end of the above snippet, we necessarily have to set the map to the routePolyline property.

func displayRouteInfo() {
    lblInfo.text = mapTasks.totalDistance + "\n" + mapTasks.totalDuration
}


问:
Querying for array whose values are in the specified array
Taking this document :

```<code>{
    "targets": [
        ['a', 'b'],
        ['a']
    ]
}
</code>```

I would like to retrieve it with the following targets :

```<code>['a', 'b']
['a']
['a', 'b', 'c'] //because one target contains 'a' and 'b'
</code>```

And not with this one :

```<code>['b'] //because non of the targets contains only 'b'
</code>```

I tried with this query criteria but it doesn't work at all :

```<code>'targets': {
    '$elemMatch': {
        '$elemMatch': { '$in': target }
    }
}
</code>```

答:
You can use below find query.

```<code>db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});
</code>```

$elemMatch with $nin selects all the documents with targets element have at least one array element with no value matching element in input array.

```<code>db.collection.find({
    targets: {
      $elemMatch: {
            $elemMatch: {
                $nin: input array
        }
    }
  }
});
</code>```

input array - selection

```<code>['a', 'b'] - false
['a'] - false
['a', 'b', 'c'] - false
['b'] - true
</code>```

$not to select the documents where targets element have array element which  is subset of input array.

```<code>db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});
</code>```

input array - selection

```<code>['a', 'b'] - true
['a'] - true
['a', 'b', 'c'] - true
['b'] - false
</code>```

Body:
Taking this document :

{
    "targets": [
        ['a', 'b'],
        ['a']
    ]
}

I would like to retrieve it with the following targets :

['a', 'b']
['a']
['a', 'b', 'c'] //because one target contains 'a' and 'b'

And not with this one :

['b'] //because non of the targets contains only 'b'

I tried with this query criteria but it doesn't work at all :

'targets': {
    '$elemMatch': {
        '$elemMatch': { '$in': target }
    }
}

Body:
You can use below find query.

db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});

$elemMatch with $nin selects all the documents with targets element have at least one array element with no value matching element in input array.

db.collection.find({
    targets: {
      $elemMatch: {
            $elemMatch: {
                $nin: input array
        }
    }
  }
});

input array - selection

['a', 'b'] - false
['a'] - false
['a', 'b', 'c'] - false
['b'] - true

$not to select the documents where targets element have array element which  is subset of input array.

db.collection.find({
    targets: {
      $elemMatch: {
        $not: {
            $elemMatch: {
                $nin: input array
            }
        }
    }
  }
});

input array - selection

['a', 'b'] - true
['a'] - true
['a', 'b', 'c'] - true
['b'] - false


问:
sed and awk: how to replace a section of file to another content?
File a.html:

```<code><!--TEMPLATE: banner-->
blahblah
<!--TEMPLATE-END: banner-->
</code>```

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

答:
If the text between the marker lines consists of one or more lines:

```<code>sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/aSome text to insert' a.html
</code>```

The i command could be changed to an r command and a file name to read the text from a file.

```<code>sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/r filename' a.html
</code>```

Body:
File a.html:

blahblah

I want to replace the middle text to some other text, how to achieve that using sed/awk/other tools?

Body:
If the text between the marker lines consists of one or more lines:

sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/aSome text to insert' a.html

The i command could be changed to an r command and a file name to read the text from a file.

sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/r filename' a.html


问:
How to execute once and expect multiple changes with RSpec?
If I want to test, that an operation produces certain side-effects, how can I execute the operation once and use the change rspec matcher. Example:

```<code>expect { some_method }.to change(Foo, :count).by(1)
expect { some_method }.to change(Bar, :count).by(1)
expect { some_method }.to change(Baz, :count).by(1)
</code>```

How can I execute some_method only once, instead of 3 times?

Or do I need to do something like:

```<code>foo_count_before = Foo.count
bar_count_before = Bar.count
baz_count_before = Baz.count

some_method

foo_count_after= Foo.count
bar_count_after= Bar.count
baz_count_after= Baz.count

expect(foo_count_after - foo_count_before).to eq 1
expect(bar_count_after - bar_count_before).to eq 1
expect(baz_count_after - baz_count_before).to eq 1
</code>```

答:
You can join multiple expectations together using compound expectations. In your example, this can look like this:</p>

```<code>expect { some_method }
  .to change(Foo, :count).by(1)
  .and change(Bar, :count).by(1)
  .and change(Baz, :count).by(1)
</code>```

Body:
If I want to test, that an operation produces certain side-effects, how can I execute the operation once and use the change rspec matcher. Example:

expect { some_method }.to change(Foo, :count).by(1)
expect { some_method }.to change(Bar, :count).by(1)
expect { some_method }.to change(Baz, :count).by(1)

How can I execute some_method only once, instead of 3 times?

Or do I need to do something like:

foo_count_before = Foo.count
bar_count_before = Bar.count
baz_count_before = Baz.count

some_method

foo_count_after= Foo.count
bar_count_after= Bar.count
baz_count_after= Baz.count

expect(foo_count_after - foo_count_before).to eq 1
expect(bar_count_after - bar_count_before).to eq 1
expect(baz_count_after - baz_count_before).to eq 1

Body:
You can join multiple expectations together using compound expectations. In your example, this can look like this:

expect { some_method }
  .to change(Foo, :count).by(1)
  .and change(Bar, :count).by(1)
  .and change(Baz, :count).by(1)


问:
Call JavaScript function in another file using JavaScript object
I want to call one JavaScript function from another JavaScript file

below is my code:

```<code> var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }
</code>```

when I call the function

```<code>var myClass = new exJS();
myClass.coolMethod();
</code>```

Why do I get the error that coolmethod is not defined?

答:
Another way using the Class declaration:</p>

```<code>class exJS {
    coolMethod () {
    alert("hello suraj");
  }
}

var myClass = new exJS();
myClass.coolMethod();
</code>```

Body:
I want to call one JavaScript function from another JavaScript file

below is my code:

 var exJS = function () {
     function coolMethod() {
       alert("hello suraj");
     }
  }

when I call the function

var myClass = new exJS();
myClass.coolMethod();

Why do I get the error that coolmethod is not defined?

Body:
Another way using the Class declaration:

class exJS {
    coolMethod () {
    alert("hello suraj");
  }
}

var myClass = new exJS();
myClass.coolMethod();


问:
How do you add the sum of lists when the sublist is int?
How do you add the sum of List of List when the sub list is int. I know you can't do mainList.Sum(); because you can't add a list data type so I have to use loops and another list to get around it. If I don't want to use loops is there a simpler way of doing it ?

```<code>var mainList = new List<List<int>>( );
mainList.Add(new List<int>{ 6});
mainList [0].Add (5);
mainList [0].Add (3);
mainList.Add(new List<int>{ 7});
mainList [1].Add (5);
mainList [1].Add (2);
mainList.Add(new List<int>{ 8});
mainList [2].Add (5);
mainList [2].Add (19);
</code>```

without having to do this..

```<code>List<int> list = new List<int>();
for (int i =0; i <3; i++)
{
    for (int j = 0; j <mainList[i].Count; j++)
    {
        list.Add (mainList [i] [j]);
    }
}
Console.Write (list.Sum ());
</code>```

答:
Or sum the sums:</p>

```<code>int sum = mainList.Sum(x => x.Sum());
</code>```

Body:
How do you add the sum of List of List when the sub list is int. I know you can't do mainList.Sum(); because you can't add a list data type so I have to use loops and another list to get around it. If I don't want to use loops is there a simpler way of doing it ?

var mainList = new List<List<int>>( );
mainList.Add(new List<int>{ 6});
mainList [0].Add (5);
mainList [0].Add (3);
mainList.Add(new List<int>{ 7});
mainList [1].Add (5);
mainList [1].Add (2);
mainList.Add(new List<int>{ 8});
mainList [2].Add (5);
mainList [2].Add (19);

without having to do this..

List<int> list = new List<int>();
for (int i =0; i <3; i++)
{
    for (int j = 0; j <mainList[i].Count; j++)
    {
        list.Add (mainList [i] [j]);
    }
}
Console.Write (list.Sum ());

Body:
Or sum the sums:

int sum = mainList.Sum(x => x.Sum());


问:
In C how do I detect whether an input is a character or integer at the same time?
Quite new to C so apologies for the long read and no doubt rubbish programming.

So my program is reading in a CSV file, containing the specification of 15 different transistors. It then compares an input to the data from the CSV file. After the data is input, the program determines which transistors are most suitable. This is meant to loop until the letter q is entered, which is when the program is meant to stop.

The input is entered as eg.

10 0.05 120 5000 20

for volt, amp, power, freq and gain respectively. The program doesn't care about type, company or price.

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
#define MAX_IN 10000

struct data{
char type[10], company[10];
int volt, power, freq, gain;
float amp, price;
};

struct input{
int volt, power, freq, gain;
float amp;
};
struct input inputs[MAX_IN];
struct data datas[MAX];

main()
{
    int chk = 1, num=0;
    while(chk == 1)
    {
        chk = input_function(&num);
    }
}

int input_function(int *number)
{
    int j=0;
    char check=0;

    scanf("%c%d %f %d %d %d", &check, &inputs[j].volt, &inputs[j].amp, inputs[j].power, &inputs[j].freq, &inputs[j].gain);

    if(check!='q')
    {
        check_function(j);
        ++*number;
        ++j;
        return 1;
     }
     else
     {
        return 0;
     }
}
</code>```

num is an integer used to determine how many inputs I have put in so that the check function compares the correct input for the input structure.

In a previously similar problem, using %c%d let it check for both a character and an integer at the same time, but this isn't working.

Previously I had it almost working, but it took q as the first input to voltage - so every input after was off by one. Anyone have any ideas?

答:
scanf, fscanf, and sscanf are broken-as-specified and shouldn't ever be used for anything.  Forget you ever heard of them.

Use fgets (or getline if available) to read the entire line. Examine its first character manually.  If it is q, exit.  Otherwise, use a chain of calls to strtol and strtod to parse the line and convert text to machine numbers.  (Pay close attention to the part of the strtol/strtod manpages where they explain how to check for errors; it's a little tricky.)

Body:
Quite new to C so apologies for the long read and no doubt rubbish programming.

So my program is reading in a CSV file, containing the specification of 15 different transistors. It then compares an input to the data from the CSV file. After the data is input, the program determines which transistors are most suitable. This is meant to loop until the letter q is entered, which is when the program is meant to stop.

The input is entered as eg.

10 0.05 120 5000 20

for volt, amp, power, freq and gain respectively. The program doesn't care about type, company or price.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
#define MAX_IN 10000

struct data{
char type[10], company[10];
int volt, power, freq, gain;
float amp, price;
};

struct input{
int volt, power, freq, gain;
float amp;
};
struct input inputs[MAX_IN];
struct data datas[MAX];

main()
{
    int chk = 1, num=0;
    while(chk == 1)
    {
        chk = input_function(&num);
    }
}

int input_function(int *number)
{
    int j=0;
    char check=0;

    scanf("%c%d %f %d %d %d", &check, &inputs[j].volt, &inputs[j].amp, inputs[j].power, &inputs[j].freq, &inputs[j].gain);

    if(check!='q')
    {
        check_function(j);
        ++*number;
        ++j;
        return 1;
     }
     else
     {
        return 0;
     }
}

num is an integer used to determine how many inputs I have put in so that the check function compares the correct input for the input structure.

In a previously similar problem, using %c%d let it check for both a character and an integer at the same time, but this isn't working.

Previously I had it almost working, but it took q as the first input to voltage - so every input after was off by one. Anyone have any ideas?


问:
Porting XML parsing from Java to Objective C
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

```<code>Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());
</code>```

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.

答: Well thanks to all for making the efforts to answer, but I got a nice library TouchXML that solves the purpose.</p>

Body:
I am trying to port code written in Java to Objective C (for iPhone), but I'm kind of confused about a few lines of my code (mentioned below). How should I port this efficiently?

Namespace nmgrhistory=Namespace.getNamespace("history", "http://www.mywebsite.com/History.xsd");
        pEventEl.addContent(new Element("History",nmgrhistory));
        Namespace nmgrState=Namespace.getNamespace("state", "http://www.mywebsite.com/State.xsd");
        pEventEl.addContent(new Element("State",nmgrState));

        Iterator<Element> eld=(Iterator<Element>) pEventEl.getChild(
                pEventEl.getName() == "event"?  "./history:history/state:state" : "./state:state",pEventEl.getNamespace());

I'm not very sure about the replacements for the classes Namespace, Iterator and Element.

Anybody having idea or having done this before, please enlighten me.


问:
MIME Binary Data to PDF
I'm receiving some data from an API call that returns some XML and associated files (PDFs):

```<code>var req = http.request(HTTPOPTIONS, function(resp){
var rawData = '';
//Build list from response data
resp.on('data', function (chunk) {
    rawData+= chunk;
});
//Process List
resp.on('end', function () {
        var breakStr = rawData.split('\n')[0];
        var fileSections = rawData.split(breakStr);
        for(var i in fileSections){
            var content = fileSections[i].split((/Content-Length: [0-9]*/));
            var fileName = content[0].split('filename=')[1].trim();
            var file = {Bucket : 'MyBucket', Key: ROOT+'/'+FOLDER+'/'+SUBFOLDER+'/'+fileName, Body: content[1]};
            console.log('Creating file: '+file.Key );
            promises.push(S3.upload(file).promise());
        }
        Promise.all(promises).then(...);
    });
});
req.write(XMLREQUEST);
req.end();
</code>```

But I when I try to open the file created I get [

Any ideas on where I'm going wrong?

UPDATE:

In addition to the above error message I also get [

On these files I get the metadata (Page size/formatting and Font data) but no content.

答:
It appears the problem was because I was storing the data in a string and trying to manipulate it from there.  The incoming data chunk is a buffer and using it in this form mean that, once you figure out how to remove the headers, you can create the PDF files.

```<code>var req = http.request(HTTPOPTIONS, function(resp){
var respChunks =[];
var respChunksLength = 0;

resp.on('data', function (chunk) {
    respChunks.push(chunk);
    respChunksLength+=chunk.length;
});

resp.on('end', function () {
    var confResp = Buffer.concat(respChunks, respChunksLength);
    var breakStr = confResp.slice(0,confResp.indexOf('\n'));
    var bufferArray = [];
    var startBreak = confResp.indexOf(breakStr);
    while(startBreak>-1){
        bufferArray.push(confResp.slice(startBreak+breakStr.length+1,confResp.indexOf(breakStr,startBreak+1)));
        startBreak = confResp.indexOf(breakStr,startBreak+1);
    }
    var trim=0;
    for(var i = 1; i<bufferArray.length;i++){
        trim = bufferArray[i].toString().indexOf('%');
        fs.writeFile('testFile'+i+'.pdf',bufferArray[1].slice(trim));
    });
});
req.write(generateProposalDetailXML());
req.end();
</code>```

the bufferArray is concatenated into a single buffer, this is then divided based on the MIME delimiter (breakStr) and the headers (clumsily) removed and written to a file.

Title: MIME Binary Data to PDF

Body:
I'm receiving some data from an API call that returns some XML and associated files (PDFs):

var req = http.request(HTTPOPTIONS, function(resp){
var rawData = '';
//Build list from response data
resp.on('data', function (chunk) {
    rawData+= chunk;
});
//Process List
resp.on('end', function () {
        var breakStr = rawData.split('\n')[0];
        var fileSections = rawData.split(breakStr);
        for(var i in fileSections){
            var content = fileSections[i].split((/Content-Length: [0-9]*/));
            var fileName = content[0].split('filename=')[1].trim();
            var file = {Bucket : 'MyBucket', Key: ROOT+'/'+FOLDER+'/'+SUBFOLDER+'/'+fileName, Body: content[1]};
            console.log('Creating file: '+file.Key );
            promises.push(S3.upload(file).promise());
        }
        Promise.all(promises).then(...);
    });
});
req.write(XMLREQUEST);
req.end();

But I when I try to open the file created I get [

Any ideas on where I'm going wrong?

UPDATE:

In addition to the above error message I also get [

On these files I get the metadata (Page size/formatting and Font data) but no content.

Body:
It appears the problem was because I was storing the data in a string and trying to manipulate it from there.  The incoming data chunk is a buffer and using it in this form mean that, once you figure out how to remove the headers, you can create the PDF files.

var req = http.request(HTTPOPTIONS, function(resp){
var respChunks =[];
var respChunksLength = 0;

resp.on('data', function (chunk) {
    respChunks.push(chunk);
    respChunksLength+=chunk.length;
});

resp.on('end', function () {
    var confResp = Buffer.concat(respChunks, respChunksLength);
    var breakStr = confResp.slice(0,confResp.indexOf('\n'));
    var bufferArray = [];
    var startBreak = confResp.indexOf(breakStr);
    while(startBreak>-1){
        bufferArray.push(confResp.slice(startBreak+breakStr.length+1,confResp.indexOf(breakStr,startBreak+1)));
        startBreak = confResp.indexOf(breakStr,startBreak+1);
    }
    var trim=0;
    for(var i = 1; i<bufferArray.length;i++){
        trim = bufferArray[i].toString().indexOf('%');
        fs.writeFile('testFile'+i+'.pdf',bufferArray[1].slice(trim));
    });
});
req.write(generateProposalDetailXML());
req.end();

the bufferArray is concatenated into a single buffer, this is then divided based on the MIME delimiter (breakStr) and the headers (clumsily) removed and written to a file.


问:
How to set selected on select element that is populated by Angular 2 *ngFor?
I have a <select> filter on my datatable. The datatable is populated with a list of competitions that are retrieved from a service. The select filter is populated with a list of sports, also retrieved from a service.

What I would like is to have an initial default option in the select element that would display all competitions, e.g. "Please select a Sport", and when the user selects a sport the competitions are filtered.

I have tried the following, but the select element is initially always empty. Is there a way to achieve this?

<select class="form-control" [(ngModel)]="filterQuery">
   <option selected="selected" disabled>Please select a Sport</option>
   <option id="sport" *ngFor="let sport of sports" [ngValue]=sport>{{sport.name}}</option>
</select>```
</div>
</div>
</p>

<p>I think the approach Gunter suggests would work fine if filterQuery was of type string but filterQuery is of type Sport. The Pipe I have is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>export class SportFilterPipe implements PipeTransform {

transform(array: any[], query: Sport): any {
    if (query) {
        var result = array.filter(function (obj) {
            return obj.sport === query.id;
        });
        return result;
    }
    return array;
}
}</code>```

Is there anything else I can do?

答:
By assigning the value to filterQuery.

The [] part of [(ngModel)]="filterQuery" sets the initial value.

Just remove selected="selected"

Body:
I have a <select> filter on my datatable. The datatable is populated with a list of competitions that are retrieved from a service. The select filter is populated with a list of sports, also retrieved from a service.

What I would like is to have an initial default option in the select element that would display all competitions, e.g. "Please select a Sport", and when the user selects a sport the competitions are filtered.

I have tried the following, but the select element is initially always empty. Is there a way to achieve this?

<select class="form-control" [(ngModel)]="filterQuery">
   <option selected="selected" disabled>Please select a Sport</option>
   <option id="sport" *ngFor="let sport of sports" [ngValue]=sport>{{sport.name}}</option>
</select>

I think the approach Gunter suggests would work fine if filterQuery was of type string but filterQuery is of type Sport. The Pipe I have is

export class SportFilterPipe implements PipeTransform {

transform(array: any[], query: Sport): any {
    if (query) {
        var result = array.filter(function (obj) {
            return obj.sport === query.id;
        });
        return result;
    }
    return array;
}
}

Is there anything else I can do?


问:
Ionic 2: Client certificate based authentication HTTP request
Did anyone already implement a HTTP request with certificate based authentication?
When I open the URL of my backend service with Chrome browser on my mobile phone, it is asking for client certificate, which is fine. When I open the URL in my Ionic 2 app, there is just "ERROR EMPTY RESPONSE".
Does anyone know how to handle this?
I am open for any ideas,
Thanks</p>

答:
You can try this code.If you get any error please comment.

$http({
        method: 'POST' or 'GET',
        url: //where your api locate,
        data: data,
        headers : {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
      }).then(function successCallback(response) {
          //response
      }, function errorCallback(err) {
          console.log(err);
      });

hope this will works for you :)


问:
laravel5.2 job, how to return data?

Job

```<code>class DataFormFields extends Job implements ShouldQueue
{
 use InteractsWithQueue, SerializesModels;

 protected $fieldList = [
        'name' => 'Tom',
        'age' => '20',
];
public function handle()
{
    $fields = $this->fieldList;

    return $fields;
}
}
</code>```

controller

```<code>public function create()
{
    $data = $this->dispatch(new DataFormFields());

    return view('create', $data);
}
</code>```

I try to dd($data); print 0

the code can work in laravel5.1 ,but in 5.2 it's not ok.help

答:
Yes you can. Simply return the value. Instead of calling dispatch, you can call the job's handle like this.

```<code>public function handle()
    {
            $a = "return value";
            return $a;
    }
}
</code>```

Now instead of calling $this->dispatch(new ExampleJob) in your controller. You can do this instead.

```<code>$exampleJob = new ExampleJob();
$retval = $exampleJob->handle();

echo $retval; //return value
</code>```

Please note that only works if you do not intend to queue the job.

Title: laravel5.2 job, how to return data?

Body:
Job

class DataFormFields extends Job implements ShouldQueue
{
 use InteractsWithQueue, SerializesModels;

 protected $fieldList = [
        'name' => 'Tom',
        'age' => '20',
];
public function handle()
{
    $fields = $this->fieldList;

    return $fields;
}
}

controller

public function create()
{
    $data = $this->dispatch(new DataFormFields());

    return view('create', $data);
}

I try to dd($data); print 0

the code can work in laravel5.1 ,but in 5.2 it's not ok.help

Body:
Yes you can. Simply return the value. Instead of calling dispatch, you can call the job's handle like this.

public function handle()
    {
            $a = "return value";
            return $a;
    }
}

Now instead of calling $this->dispatch(new ExampleJob) in your controller. You can do this instead.

$exampleJob = new ExampleJob();
$retval = $exampleJob->handle();

echo $retval; //return value

Please note that only works if you do not intend to queue the job.


问:
How to fully delete a git repository created with init?
I created a git repository with git init. I'd like to delete it entirely and init a new one.

答:
Alternative to killing TortoiseGit:

Open the TortoiseGit-Settings (right click to any folder, TortoiseGit → Settings)

Go to the Icon Overlays option.

Change the Status Cache from Default to None

Now you can delete the directory (either with Windows Explorer or rmdir /S /Q)

Set back the Status Cache from None to Default and you should be fine again...


问:
change format of date from JSON to first 2 letters and year
I have the following JSON, and I need to convert the date values eg. "December 2016" to "D16", not sure how I could do this, I guess with a Regex, any help would be appreciated.</p>

```<code>[["November 2016","December 2016","January 2017","February 2017","March 2017"],["total",2,43,59,51,41
],["mammo",1,20,33,12,12],["face",1,20,16,30,27],["body",0,3,10,9,2],["photo",0,19,27,12,5],["scan",2
,24,32,39,36]]
</code>```

答:
```<code>var dates = ["November 2016","December 2016","January 2017","February 2017","March 2017"];

dates = dates.map((date) => date[0] + date.split(' ')[1].slice(2, 4))

console.log(dates)
//["N16", "D16", "J17", "F17", "M17"]
</code>```

You could use some library like moment if you need to do some other magic with the date though.

Body:
I have the following JSON, and I need to convert the date values eg. "December 2016" to "D16", not sure how I could do this, I guess with a Regex, any help would be appreciated.

[["November 2016","December 2016","January 2017","February 2017","March 2017"],["total",2,43,59,51,41
],["mammo",1,20,33,12,12],["face",1,20,16,30,27],["body",0,3,10,9,2],["photo",0,19,27,12,5],["scan",2
,24,32,39,36]]

Body:
var dates = ["November 2016","December 2016","January 2017","February 2017","March 2017"];

dates = dates.map((date) => date[0] + date.split(' ')[1].slice(2, 4))

console.log(dates)
//["N16", "D16", "J17", "F17", "M17"]

You could use some library like moment if you need to do some other magic with the date though.


问:
Stripping all comments and console.logs with ng build --prod, possible?
I am using MEAN, Angular 2, Node/Express, Angular-CLI and ng build --prod to build my app and I have a travesty of commented out throwaway code and a billion debugging console.log statements throughout my app. Is there a way to have the build process remove all comments and console.log statements when it builds? The thought of doing it manually is scary!</p>

答:
You can use ng lint with --fix flag and no-console rule in tslint configuration file. And hook it to your build call in your package file.

eg.:

...
 "prebuild": "ng lint --fix",
 "build": "ng build -prod",
...

and build the app

npm run build

ref: https://github.com/angular/angular-cli/wiki/lint


问:
Slicing each line from data CSV file
I have a movie dataset that looks like this:

```<code>1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children
</code>```

I want to extract only the last part (genres part, e.g, Adventure|Animation|Children|Comedy|Fantasy) and store them in a list list[Adventure, Animation, Children, Comedy, Fantasy]. However, I am still stuck at slicing step. I don't know how to do that since line[:-1] doesn't slice. I use Python 2.7

```<code>with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]
</code>```

答:
Your slice will return the last character of each line, since the lines are not splitted when you read the file in regular manner. You should read the file using csv module that separates the lines automatically with ',' delimiter. Then split the result with |.

```<code>import csv
with open(path + 'movie.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row[-1].split('|'))
</code>```

Title: Slicing each line from data CSV file

Body:
I have a movie dataset that looks like this:

1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy
2,Jumanji (1995),Adventure|Children|Fantasy
3,Grumpier Old Men (1995),Comedy|Romance
4,Waiting to Exhale (1995),Comedy|Drama|Romance
5,Father of the Bride Part II (1995),Comedy
6,Heat (1995),Action|Crime|Thriller
7,Sabrina (1995),Comedy|Romance
8,Tom and Huck (1995),Adventure|Children

I want to extract only the last part (genres part, e.g, Adventure|Animation|Children|Comedy|Fantasy) and store them in a list list[Adventure, Animation, Children, Comedy, Fantasy]. However, I am still stuck at slicing step. I don't know how to do that since line[:-1] doesn't slice. I use Python 2.7

with open(path + 'movie.csv') as f:
    for line in f:
        print line[:-1]

Body:
Your slice will return the last character of each line, since the lines are not splitted when you read the file in regular manner. You should read the file using csv module that separates the lines automatically with ',' delimiter. Then split the result with |.

import csv
with open(path + 'movie.csv') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        print(row[-1].split('|'))


问:
angularjs routing tutorial bug not routing
I just created a simple project to learn angular routing, my project is the following:

index.html:

```<code><!DOCTYPE html>
<html ng-app="app">
<body>
    <div>
        <a href="#/">Home</a>
        <a href="#/hi">Hi</a>
        <a href="#/bye">bye</a>
    </div>
    <div class="ng-view"></div>
    <script src="https://code.angularjs.org/1.6.3/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.6.3/angular-route.min.js"></script>
    <script src="scripts.js"></script>
</body>
</html>
</code>```

scripts.js:

```<code>var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl: "home.html"
    })
    .when("/hi", {
        templateUrl: "hi.html"
    })
    .when("/bye", {
        templateUrl: "bye.html"
    });
});
</code>```

hi.html:
Hi

bye.html:
bye

home.html:
Home

The three html from above only contains a h1 tag to keep it simple

A plunker of my code: http://plnkr.co/edit/uNZicTuRKDkR7ATwdFE0

I'm following this tutorial: https://www.w3schools.com/angular/angular_routing.asp

Dunno if outdated or why its not working, thanks

答:
The problem is that you are using angular 1.6 and the toturial is using 1.4. Your links should be like this because of the new hash prefix in version 1.6:

```<code>  <div>
    <a ng-href="#!/">Home</a>
    <a ng-href="#!/hi">Hi</a>
    <a ng-href="#!/bye">bye</a>
  </div>
</code>```

See plunker.

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

Read more about what else to do at: https://stackoverflow.com/a/41655831/6682369

Body:
I just created a simple project to learn angular routing, my project is the following:

index.html:

<!DOCTYPE html>

        Home
        Hi
        bye

scripts.js:

var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl: "home.html"
    })
    .when("/hi", {
        templateUrl: "hi.html"
    })
    .when("/bye", {
        templateUrl: "bye.html"
    });
});

hi.html:
Hi

bye.html:
bye

home.html:
Home

The three html from above only contains a h1 tag to keep it simple

A plunker of my code: http://plnkr.co/edit/uNZicTuRKDkR7ATwdFE0

I'm following this tutorial: https://www.w3schools.com/angular/angular_routing.asp

Dunno if outdated or why its not working, thanks

Body:
The problem is that you are using angular 1.6 and the toturial is using 1.4. Your links should be like this because of the new hash prefix in version 1.6:

  <div>
    <a ng-href="#!/">Home</a>
    <a ng-href="#!/hi">Hi</a>
    <a ng-href="#!/bye">bye</a>
  </div>

See plunker.

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

Read more about what else to do at: https://stackoverflow.com/a/41655831/6682369


问:
(De)Normalization of two relations
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

```<code>r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35
</code>```

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.

答:
so r2 is a function of r1 which mean r2 is a materialized view of that function of r1

and in that example the it would be a view of select A, sum(C) from r1 group by A

views are not covered in codd's work on normalization, but i think he did write about them

materializing a view is normally done for caching reasons which some might think of as a form of denormalization so there were papers on automatically deciding which view to materialize thus making it just something the database could do with view to make them faster sometimes

but as updates to views are normally not permitted although i think i read that codd said something like all views that can be update-able should be and there were papers on getting that to work in some complex cases

Title: (De)Normalization of two relations

Body:
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.


问:
cleanup php session files
On  my website I use PHP sessions. Session information is stored in files in my ./session path. After a few months I discovered that these session files are never deleted, by now there are 145.000 of them in this directory.

How should these be cleaned up? Do I have to do it programmatically, or is ther a setting I can use somewhere that would have this cleanup happen automatically?

EDIT forgot to mention: This site runs at a provider, so I don't have access to a command line.  I do have ftp-access, but the session files belong to another user (the one the webserver proces runs I guess) From the first answers I got I think it's not just a setting on the server or PHP, so I guess I'll have to implement something for it in PHP, and call that periodically from a browser (maybe from a cron job running on my own machine at home)

答:
cd to sessions directory and then:

1) View sessions older than 40 min:
 find . -amin +40 -exec stat -c "%n %y" {} \;

2) Remove sessions older than 40 min:
find . -amin +40  -exec rm {} \;

OwnerDisplayName: Jack

Title: cleanup php session files

LastEditorDisplayName: Jack