答:
You can use the replace function:

```<code>indexes <- as.integer(names(replace_support))
test_data$support <- replace(test_data$support,indexes,replace_support)
test_data
   support count
1  0.012352349   663
2 -0.008884196   737
3 -0.007991622   748
4 -0.011675116   679
5  0.015482356   831
6 -0.013086012   840
</code>```

If the names of replace_support don't match the appropriate indexes, you can supply them manually.

Body:
I want to replace data.frame using specified data set

> test_data
     support count
1 0.01235235   663
2 0.01373104   737
3 0.01393598   748
4 0.01265045   679
5 0.01548236   831
6 0.01565004   840
> replace_support
           2            3            4            6
-0.008884196 -0.007991622 -0.011675116 -0.013086012

names of replace_support corresponds with row name of test_data
my expect is replace the column support

     support count
1 0.01235235   663
2 -0.008884196   737
3 -0.007991622   748
4 -0.011675116   679
5 0.01548236   831
6 -0.013086012   840

hare are the example data

test_data <- structure(list(support = c(0.0123523493684093, 0.0137310429630734,
0.0139359839028207, 0.0126504452807691, 0.0154823564481872, 0.0156500353988896
), count = c(663, 737, 748, 679, 831, 840)), .Names = c("support",
"count"), row.names = c(NA, 6L), class = "data.frame")

replace_support <- structure(c(-0.00888419577036815, -0.00799162193023339, -0.0116751160488589,
-0.0130860121134779), .Names = c("2", "3", "4", "6"))

Body:
You can use the replace function:

indexes <- as.integer(names(replace_support))
test_data$support <- replace(test_data$support,indexes,replace_support)
test_data
   support count
1  0.012352349   663
2 -0.008884196   737
3 -0.007991622   748
4 -0.011675116   679
5  0.015482356   831
6 -0.013086012   840

If the names of replace_support don't match the appropriate indexes, you can supply them manually.


来源: stackexchange

问:
Output UTF-8 (u8) std::string
In C++11 and later, using the u8 prefix on a string literal can create char (byte) sequences that are UTF-8 encoded.

How do you output those sequences to a std::ostream? How do you tell a std::ostream that a const char * or std:string to be output contains characters encoded in UTF-8, rather than the default encoding?

答: You don't. The stream does not know or care what the encoding of the text is. Despite it's name, a char is not treated by std:ostream as containing a character encoded in the platform encoding. It must treats a char as a byte to be written out. It writes the "text" (byte sequence) as given (outside of possibly performing \n translation), assuming you don't imbue it with a facet that changes this. If you write characters that conform to UTF-8, then that's what ends up in the output.

ContentLicense: CC BY-SA 3.0

Title: Output UTF-8 (u8) std::string


问:
Match any url in Mongoose with or without http(s) or www
What I'm trying to achieve is to find a way to verify if a URL already exists in a MongoDB document, without saving the URL twice, one with HTTP(s)(www) protocol, and other clean of HTTP(s)(www) to perform the match.
For example, if the MongoDB document contains a record:

```<code>'url': "http://mysite.co?search=pattern&co=43"
</code>```

So, I want to perform a search:

```<code>MyCollection.find({'url': "mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://www.mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://www.mysite.co?search=pattern&co=43"})...
</code>```

The search should match with the URL actually saved in the document.

I'm trying to use the following regex:

```<code>MyCollection.find({'url': new RegExp('^https?:\/\/(www.)?(' + 'mysite.co?search=pattern&co=43' + ')+$', 'gim')})...
</code>```

However, I'm not very clever creating regex expressions, and I still struggle with it. Seems that the question mark in the URL breaks the regex, and I'm not pretty sure if just using a replace from '?' to '\?' is the right way to go.

The search must match 'exactly' the URL in the DB, except for the HTTP(s)(www) protocol. I mean, if the URL in the document contains other params:

```<code>'url': "http://mysite.co?search=pattern&co=43&other=more_params"
</code>```

The search should not be matched this time.

I'm using Mongoose and nodejs.

Thanks in advance.

UPDATE:

Based on your answers, I have improved a little bit the regex and scaping for the URL:

First, a function to trim and 'clean' the URL of HTTP(s) or (www):

```<code>String.prototype.url_clean = function() {
    return this.trim().replace(/^(http(s|):\/\/)?(www\.|)/g, '');
};
</code>```

And a function to escape the URL:

```<code>RegExp.escape = function(s) {
    return s.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
};
</code>```

So I can perform the search:

```<code>MyCollection.find({'url': new RegExp('^(http(s|):\/\/)?(www\.|)(' + RegExp.escape(url.url_clean()) + ')(|\s)+$', "gim")})
</code>```

答:
It looks fine you just forgot to escape some characters:

```<code>db.getCollection('regex').find({
    "url": new RegExp('^https?:\/\/(www.)?(' + 'mysite\.co\\?search=pattern&co=43' + ')+$', 'gim')
})
</code>```

More on regex in MongoDB you can read here

Body:
What I'm trying to achieve is to find a way to verify if a URL already exists in a MongoDB document, without saving the URL twice, one with HTTP(s)(www) protocol, and other clean of HTTP(s)(www) to perform the match.
For example, if the MongoDB document contains a record:

'url': "http://mysite.co?search=pattern&co=43"

So, I want to perform a search:

MyCollection.find({'url': "mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "http://www.mysite.co?search=pattern&co=43"})...
MyCollection.find({'url': "https://www.mysite.co?search=pattern&co=43"})...

The search should match with the URL actually saved in the document.

I'm trying to use the following regex:

MyCollection.find({'url': new RegExp('^https?:\/\/(www.)?(' + 'mysite.co?search=pattern&co=43' + ')+$', 'gim')})...

However, I'm not very clever creating regex expressions, and I still struggle with it. Seems that the question mark in the URL breaks the regex, and I'm not pretty sure if just using a replace from '?' to '\?' is the right way to go.

The search must match 'exactly' the URL in the DB, except for the HTTP(s)(www) protocol. I mean, if the URL in the document contains other params:

'url': "http://mysite.co?search=pattern&co=43&other=more_params"

The search should not be matched this time.

I'm using Mongoose and nodejs.

Thanks in advance.

UPDATE:

Based on your answers, I have improved a little bit the regex and scaping for the URL:

First, a function to trim and 'clean' the URL of HTTP(s) or (www):

String.prototype.url_clean = function() {
    return this.trim().replace(/^(http(s|):\/\/)?(www\.|)/g, '');
};

And a function to escape the URL:

RegExp.escape = function(s) {
    return s.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g, '\\$&');
};

So I can perform the search:

MyCollection.find({'url': new RegExp('^(http(s|):\/\/)?(www\.|)(' + RegExp.escape(url.url_clean()) + ')(|\s)+$', "gim")})

Body:
It looks fine you just forgot to escape some characters:

db.getCollection('regex').find({
    "url": new RegExp('^https?:\/\/(www.)?(' + 'mysite\.co\\?search=pattern&co=43' + ')+$', 'gim')
})

More on regex in MongoDB you can read here


问:
Can't execute my SQL Data
```<code>CREATE TABLE Vet
(
     VET_NUM CHAR(2) PRIMARY KEY,
     LAST_NAME CHAR(15),
     FIRST_NAME CHAR(15),
     STREET CHAR(15),
     CITY CHAR(15),
     STATE CHAR(3),
     POSTAL_CODE CHAR(5),
     SALARY DECIMAL(7,2),
     DEGREE CHAR(10),
     POSITION CHAR(15)
);

INSERT INTO Vet (VET_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, POSTAL_CODE, SALARY, DEGREE, POSITION)
VALUES ('1', 'Skechley', 'Cristine', '24340 7th Plaza', 'Pittsburgh', 'PA', '15274', 88053.30, 'Masters', 'Vet'),
       ('2', 'Fishpoole', 'Sig', '06784 Anthes Point', 'Philadelphia', 'PA', '19184', 45525.56, 'Associates', 'Receptionist'),
       ('3', 'Stother', 'Rycca', '04304 Superior Hill', 'Allentown', 'PA', '18105', 90553.37, 'Masters', 'Vet'),
       ('4', 'Scandrite', 'Kerrill', '30320 Express Crossing', 'Harrisburg', 'PA', '17126', 102553.59, 'Doctorates', 'Vet'),
       ('5', 'Glassman', 'Rhett', '33418 Tomscot Trail', 'Mc Keesport', 'PA', '15134', 56052.24, 'Bachelor', 'Management'),
       ('6', 'Gioan', 'Rab', '1 Pennsylvania Street', 'Hatfield', 'PA', '19440', 35880.76, 'Student', 'Janitor');
</code>```

The error I keep getting is

Msg 2627, Level 14, State 1, Line 35

  Violation of PRIMARY KEY constraint 'PK__Vet__7C53690AE94CBCDD'

  Cannot insert duplicate key in object 'dbo.Vet'. The duplicate key value is (1 ).

Msg 8152, Level 16, State 14, Line 38

  String or binary data would be truncated.

Msg 8152, Level 16, State 14, Line 41

  String or binary data would be truncated.

Msg 8152, Level 16, State 14, Line 44

  String or binary data would be truncated.

I don't know what I am doing wrong. Can anyone help me with this? I have looked on YouTube, and the video I watched said that the Data I have entered might not be good. I think my data is alright, but for some reason, I just can't get it to execute. I want to be able to see "Row has been effected"

答:
try this

```<code>CREATE TABLE Vet
(VET_NUM CHAR(2) PRIMARY KEY,
LAST_NAME CHAR(20),
FIRST_NAME CHAR(20),
STREET CHAR(30),
CITY CHAR(20),
STATE CHAR(20),
POSTAL_CODE CHAR(20),
SALARY DECIMAL(8,2),
DEGREE CHAR(20),
POSITION CHAR(20));
    INSERT INTO Vet(VET_NUM,LAST_NAME,FIRST_NAME,STREET,CITY,STATE,POSTAL_CODE,SALARY,DEGREE,POSITION)
    VALUES
    ('1','Skechley','Cristine','24340 7th Plaza','Pittsburgh','PA','15274',88053.30,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('2','Fishpoole','Sig','06784 Anthes Point','Philadelphia','PA','19184',45525.56,'Associates','Receptionist');
    INSERT INTO Vet
    VALUES
    ('3','Stother','Rycca','04304 Superior Hill','Allentown','PA','18105',90553.37,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('4','Scandrite','Kerrill','30320 Express Crossing','Harrisburg','PA','17126',102553.59,'Doctorates','Vet');
    INSERT INTO Vet
    VALUES
    ('5','Glassman','Rhett','33418 Tomscot Trail','Mc Keesport','PA','15134',56052.24,'Bachelor','Management');
    INSERT INTO Vet
    VALUES
    ('6','Gioan','Rab','1 Pennsylvania Street' ,'Hatfield','PA','19440',35880.76,'Student','Janitor');
</code>```

column length  is low

Title: Can't execute my SQL Data

Body:
CREATE TABLE Vet
(
     VET_NUM CHAR(2) PRIMARY KEY,
     LAST_NAME CHAR(15),
     FIRST_NAME CHAR(15),
     STREET CHAR(15),
     CITY CHAR(15),
     STATE CHAR(3),
     POSTAL_CODE CHAR(5),
     SALARY DECIMAL(7,2),
     DEGREE CHAR(10),
     POSITION CHAR(15)
);

INSERT INTO Vet (VET_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, POSTAL_CODE, SALARY, DEGREE, POSITION)
VALUES ('1', 'Skechley', 'Cristine', '24340 7th Plaza', 'Pittsburgh', 'PA', '15274', 88053.30, 'Masters', 'Vet'),
       ('2', 'Fishpoole', 'Sig', '06784 Anthes Point', 'Philadelphia', 'PA', '19184', 45525.56, 'Associates', 'Receptionist'),
       ('3', 'Stother', 'Rycca', '04304 Superior Hill', 'Allentown', 'PA', '18105', 90553.37, 'Masters', 'Vet'),
       ('4', 'Scandrite', 'Kerrill', '30320 Express Crossing', 'Harrisburg', 'PA', '17126', 102553.59, 'Doctorates', 'Vet'),
       ('5', 'Glassman', 'Rhett', '33418 Tomscot Trail', 'Mc Keesport', 'PA', '15134', 56052.24, 'Bachelor', 'Management'),
       ('6', 'Gioan', 'Rab', '1 Pennsylvania Street', 'Hatfield', 'PA', '19440', 35880.76, 'Student', 'Janitor');

The error I keep getting is

Msg 2627, Level 14, State 1, Line 35

  Violation of PRIMARY KEY constraint 'PK__Vet__7C53690AE94CBCDD'

  Cannot insert duplicate key in object 'dbo.Vet'. The duplicate key value is (1 ).

Msg 8152, Level 16, State 14, Line 38

  String or binary data would be truncated.

Msg 8152, Level 16, State 14, Line 41

  String or binary data would be truncated.

Msg 8152, Level 16, State 14, Line 44

  String or binary data would be truncated.

I don't know what I am doing wrong. Can anyone help me with this? I have looked on YouTube, and the video I watched said that the Data I have entered might not be good. I think my data is alright, but for some reason, I just can't get it to execute. I want to be able to see "Row has been effected"

Body:
try this

CREATE TABLE Vet
(VET_NUM CHAR(2) PRIMARY KEY,
LAST_NAME CHAR(20),
FIRST_NAME CHAR(20),
STREET CHAR(30),
CITY CHAR(20),
STATE CHAR(20),
POSTAL_CODE CHAR(20),
SALARY DECIMAL(8,2),
DEGREE CHAR(20),
POSITION CHAR(20));
    INSERT INTO Vet(VET_NUM,LAST_NAME,FIRST_NAME,STREET,CITY,STATE,POSTAL_CODE,SALARY,DEGREE,POSITION)
    VALUES
    ('1','Skechley','Cristine','24340 7th Plaza','Pittsburgh','PA','15274',88053.30,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('2','Fishpoole','Sig','06784 Anthes Point','Philadelphia','PA','19184',45525.56,'Associates','Receptionist');
    INSERT INTO Vet
    VALUES
    ('3','Stother','Rycca','04304 Superior Hill','Allentown','PA','18105',90553.37,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('4','Scandrite','Kerrill','30320 Express Crossing','Harrisburg','PA','17126',102553.59,'Doctorates','Vet');
    INSERT INTO Vet
    VALUES
    ('5','Glassman','Rhett','33418 Tomscot Trail','Mc Keesport','PA','15134',56052.24,'Bachelor','Management');
    INSERT INTO Vet
    VALUES
    ('6','Gioan','Rab','1 Pennsylvania Street' ,'Hatfield','PA','19440',35880.76,'Student','Janitor');

column length  is low


问:
Regex to match a variable in Batch scripting
```<code>@echo off

SET /p var=Enter:
echo %var% | findstr /r "^[a-z]{2,3}$">nul 2>&1
if errorlevel 1 (echo does not contain) else (echo contains)
pause
</code>```

I'm trying to valid a input which should contain 2 or 3 letters. But I tried all the possible answer, it only runs if error level 1 (echo does not contain).

Can someone help me please. thanks a lot.

答:
Since other answers are not against findstr, howabout running cscript? This allows us to use a proper Javascript regex engine.

@echo off
SET /p var=Enter:
cscript //nologo match.js "^[a-z]{2,3}$" "%var%"
if errorlevel 1 (echo does not contain) else (echo contains)
pause
```

<p>Where <code>match.js</code> is defined as:</p>

<pre class="lang-js prettyprint-override"><code>if (WScript.Arguments.Count() !== 2) {
  WScript.Echo("Syntax: match.js regex string");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var str = WScript.Arguments(1);
WScript.Quit(str.match(rx) ? 0 : 1);
</code>```

Body:
@echo off

SET /p var=Enter:
echo %var% | findstr /r "^[a-z]{2,3}$">nul 2>&1
if errorlevel 1 (echo does not contain) else (echo contains)
pause

I'm trying to valid a input which should contain 2 or 3 letters. But I tried all the possible answer, it only runs if error level 1 (echo does not contain).

Can someone help me please. thanks a lot.

Body:
Since other answers are not against findstr, howabout running cscript? This allows us to use a proper Javascript regex engine.

@echo off
SET /p var=Enter:
cscript //nologo match.js "^[a-z]{2,3}$" "%var%"
if errorlevel 1 (echo does not contain) else (echo contains)
pause

Where match.js is defined as:

if (WScript.Arguments.Count() !== 2) {
  WScript.Echo("Syntax: match.js regex string");
  WScript.Quit(1);
}
var rx = new RegExp(WScript.Arguments(0), "i");
var str = WScript.Arguments(1);
WScript.Quit(str.match(rx) ? 0 : 1);

ContentLicense: CC BY-SA 4.0


问:
phpMyAdmin reports 'No Privileges'
Long story short, I ended up deleting the root user from PHPMyAdmin in EasyPHP.  After some researching, I used skip-grant-tables to regain database access.  Now, however, I cannot do anything as the root user has 'No Privileges.'

That stated, when logged in as 'root,' I do, indeed, have the ability to create a database via SQL.

I've tried the following, and similar:

```<code>GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
</code>```

Still, I can't do anything.  Additionally, I have this message:

The additional features for working with linked tables have been deactivated. To find out why click here.

Clicking through shows:

```<code>$cfg['Servers'][$i]['pmadb'] ...    OK
$cfg['Servers'][$i]['relation'] ... not OK [ Documentation ]
General relation features: Disabled

$cfg['Servers'][$i]['table_info'] ...   not OK [ Documentation ]
Display Features: Disabled

$cfg['Servers'][$i]['table_coords'] ... not OK [ Documentation ]
$cfg['Servers'][$i]['pdf_pages'] ...    not OK [ Documentation ]
Creation of PDFs: Disabled

$cfg['Servers'][$i]['column_info'] ...  not OK [ Documentation ]
Displaying Column Comments: Disabled
Browser transformation: Disabled

$cfg['Servers'][$i]['bookmarktable'] ...    not OK [ Documentation ]
Bookmarked SQL query: Disabled

$cfg['Servers'][$i]['history'] ...  not OK [ Documentation ]
SQL history: Disabled

$cfg['Servers'][$i]['designer_coords'] ...  not OK [ Documentation ]
Designer: Disabled

$cfg['Servers'][$i]['tracking'] ... not OK [ Documentation ]
Tracking: Disabled
</code>```

Reinstalling EasyPHP doesn't fix the problem, and nothing exists in VirtualStore (as one forum post suggested).  Is there a specific MySQL file I should be looking for?

Any ideas?  This has really put a stop to my application development.

Thanks.

答:
If your machine has IPv6 enabled, "localhost" will resolve to ::1, rather than 127.0.0.1.  This can cause issues.

Try connecting to "127.0.0.1" rather than "localhost".  That ought to force mysql to authenticate by IPv4 address, so make sure 127.0.0.1 is in there.

Alternatively, if you have admin access, you can map localhost back to 127.0.0.1 in c:\Windows\System32\Drivers\etc\hosts.

ContentLicense: CC BY-SA 2.5

Title: phpMyAdmin reports 'No Privileges'

Body:
Long story short, I ended up deleting the root user from PHPMyAdmin in EasyPHP.  After some researching, I used skip-grant-tables to regain database access.  Now, however, I cannot do anything as the root user has 'No Privileges.'

That stated, when logged in as 'root,' I do, indeed, have the ability to create a database via SQL.

I've tried the following, and similar:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

Still, I can't do anything.  Additionally, I have this message:

The additional features for working with linked tables have been deactivated. To find out why click here.

Clicking through shows:

$cfg['Servers'][$i]['pmadb'] ...    OK
$cfg['Servers'][$i]['relation'] ... not OK [ Documentation ]
General relation features: Disabled

$cfg['Servers'][$i]['table_info'] ...   not OK [ Documentation ]
Display Features: Disabled

$cfg['Servers'][$i]['table_coords'] ... not OK [ Documentation ]
$cfg['Servers'][$i]['pdf_pages'] ...    not OK [ Documentation ]
Creation of PDFs: Disabled

$cfg['Servers'][$i]['column_info'] ...  not OK [ Documentation ]
Displaying Column Comments: Disabled
Browser transformation: Disabled

$cfg['Servers'][$i]['bookmarktable'] ...    not OK [ Documentation ]
Bookmarked SQL query: Disabled

$cfg['Servers'][$i]['history'] ...  not OK [ Documentation ]
SQL history: Disabled

$cfg['Servers'][$i]['designer_coords'] ...  not OK [ Documentation ]
Designer: Disabled

$cfg['Servers'][$i]['tracking'] ... not OK [ Documentation ]
Tracking: Disabled

Reinstalling EasyPHP doesn't fix the problem, and nothing exists in VirtualStore (as one forum post suggested).  Is there a specific MySQL file I should be looking for?

Any ideas?  This has really put a stop to my application development.

Thanks.


问:
How to restore own nuget package in another solution
I have C# solution called commons where I have my Model and some common stuff that will be used by other solutions.

As a Post Build Event I create a nuget package and copy it to my local Nuget folder ("C:\packages")

Post Build Event:

"$(ProjectDir)nuget.exe" pack "$(ProjectDir)Commons.csproj" -
IncludeReferencedProjects

xcopy Commons.1.0.0.nupkg c:\packages /Y

Note: Version never changes.

That creates successfully my new nuget package.

Then on the other solution I reference that package and I can see everything ok.
I can access all my models and everything.

The problem I have is

if I make any change to my Common projects (e.g add a new field to my model) this will not appear on my solution.

What am I missing??

答:
So... after trying 1000 things I was able to figure it out.

The correct command is :
nuget pack Commons.csproj -BasePath .\ -IncludeReferencedProjects

So missing the basepath was basically all

Post Build Event for someone else

"$(ProjectDir)nuget.exe" pack "$(ProjectDir)Commons.csproj" -BasePath "$(ProjectDir)-IncludeReferencedProjects


问:
Return a boolean value based on the booleans of two other columns
I'm trying to add a new column to a DataFrame based on the boolean values of two other columns. If one of the two columns has a true value, then I would like the new column to return, True. Only if both the columns have a false value, then I would like this new column to return False.

As I am pretty new to python, I have not gotten very far.

A DataFrame like this would be a good example:

```<code>data = DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'],
                   'has_a_pass': [False, False, False, True, False],
                   'is_an_employee': [True, False, True, True, False] })
</code>```

Anyone have any useful suggestions for solving this?

答:
Not sure if it was intentional that the is_an_employee field were strings and not booleans, but assuming theyre supposed to be booleans:

```<code>data = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'], 'has_a_pass': [False, False, False, True, False], 'is_an_employee': [True, False, True, True, False] })
data['new column'] = data['is_an_employee'] | data['has_a_pass']
data
Out[49]:
   has_a_pass  is_an_employee name  new column
0       False            True    A        True
1       False           False    B       False
2       False            True    C        True
3        True            True    D        True
4       False           False    E       False
</code>```

Body:
I'm trying to add a new column to a DataFrame based on the boolean values of two other columns. If one of the two columns has a true value, then I would like the new column to return, True. Only if both the columns have a false value, then I would like this new column to return False.

As I am pretty new to python, I have not gotten very far.

A DataFrame like this would be a good example:

data = DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'],
                   'has_a_pass': [False, False, False, True, False],
                   'is_an_employee': [True, False, True, True, False] })

Anyone have any useful suggestions for solving this?

Body:
Not sure if it was intentional that the is_an_employee field were strings and not booleans, but assuming theyre supposed to be booleans:

data = pd.DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'], 'has_a_pass': [False, False, False, True, False], 'is_an_employee': [True, False, True, True, False] })
data['new column'] = data['is_an_employee'] | data['has_a_pass']
data
Out[49]:
   has_a_pass  is_an_employee name  new column
0       False            True    A        True
1       False           False    B       False
2       False            True    C        True
3        True            True    D        True
4       False           False    E       False


问:
AEM How to package user group and permission in AEM 6
I got a problem in AEM 6.1.
I created some groups in an author instance (ex: group1, group2) and assign these groups to contributor group of AEM. After that, grant some permissions (read, modify, delete in /content node) for these groups.

I would like to package these groups (include permissions) and install into other author instance.
Package node under /home/groups, /content/rep:policy and even /jcr:system/rep:permissionStore/crx.default, then install into other author instance.

Problem: In the second author instance, only have the groups. The permissions of the groups cannot installed into this instance. Need to grant permissions again.

Does anyone have a solution for this.

Thank you very much.

答:
Here are detailed instructions on how to migrate users, groups and permissions between AEM 6.x instances:
https://gist.github.com/andrewmkhoury/c32e6bd4e339a7c9944e0399254eb2b5

This includes the case where you need to migrate both users, groups and ACLs without installing any special tools.


问:
Making an array out of doubles from a text file
I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:

```<code>90.0
71.5
87.9
95.0
98.1
</code>```

Code:

```<code>File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();

//create array
double[] array = new double[12];

//variable to increment
int u = 0;

//loop to put data into array
while(gradesFile.hasNextDouble())

    array[u] = gradesFile.nextDouble();
    u += 1;

gradesFile.close();
</code>```

答:
A. As @hnefatl said you need to group statements in the loop,

```<code>while(<condition>) {
   statement1;
   ...
   statementN;
}
</code>```

otherwise only next one executes.

```<code>while(<condition>) statement1;
...
</code>```

B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.

So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.

If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:

```<code>    Scanner gradesFile = new Scanner(file1);
    // create array
    double[] array = new double[12];
    // variable to increment
    int u = 0;
    // loop to put data into array
    while (gradesFile.hasNextLine()) {
        String line = gradesFile.nextLine();
        array[u] = Double.parseDouble(line);
        u += 1;
    }

    gradesFile.close();
</code>```

or if you'd like to use nextDouble() you do not mix it with nextLine()

```<code>    Scanner gradesFile = new Scanner(file1);
    // create array
    double[] array = new double[12];
    // variable to increment
    int u = 0;
    // loop to put data into array
    while (gradesFile.hasNextDouble()) {
        array[u] = gradesFile.nextDouble();
        u++;
    }

    gradesFile.close();
</code>```

Body:
I need to read a file of grades and input them into an array. I cant seem to figure it out though. Any suggestions. Thanks for your help :)
The grades.txt file looks like this:

90.0
71.5
87.9
95.0
98.1

Code:

File file1 = new File("grades.txt");
Scanner gradesFile = new Scanner(file1);
String line = gradesFile.nextLine();

//create array
double[] array = new double[12];

//variable to increment
int u = 0;

//loop to put data into array
while(gradesFile.hasNextDouble())

    array[u] = gradesFile.nextDouble();
    u += 1;

gradesFile.close();

Body:
A. As @hnefatl said you need to group statements in the loop,

while(<condition>) {
   statement1;
   ...
   statementN;
}

otherwise only next one executes.

while(<condition>) statement1;
...

B. When you did String line = gradesFile.nextLine();
you got full first line from file and Scanner position is at next line if there is any.

So by doing gradesFile.hasNextDouble() after that, Scaner looks for double in next line.

If you'd like to use nextLine() and your doubles are "one-per-line" you need to work with them in a loop as:

    Scanner gradesFile = new Scanner(file1);
    // create array
    double[] array = new double[12];
    // variable to increment
    int u = 0;
    // loop to put data into array
    while (gradesFile.hasNextLine()) {
        String line = gradesFile.nextLine();
        array[u] = Double.parseDouble(line);
        u += 1;
    }

    gradesFile.close();

or if you'd like to use nextDouble() you do not mix it with nextLine()

    Scanner gradesFile = new Scanner(file1);
    // create array
    double[] array = new double[12];
    // variable to increment
    int u = 0;
    // loop to put data into array
    while (gradesFile.hasNextDouble()) {
        array[u] = gradesFile.nextDouble();
        u++;
    }

    gradesFile.close();


问:
Can I run a Azure function once on a specific date triggered by my asp.net mvc site?
I know I can create a scheduled Azure function to run on a schedule. But what I want is to be able to run a Azure function once given a specific date/time I pass it, along with some data parameters.

Ex. I'm scheduling classes in my site and I want to email out all students when the class is over. So when the class is created for Monday October 9th @ 4:00PM I want to send a message to trigger my Azure function on that same day, but like 1 hour later at 5:00PM. And I want to pass it some info like the class id or something. I also want to be able to remove this queued trigger if the class is canceled.

Is this possible in Azure and my ASP.Net MVC site?

答:
You should be using the queue trigger for this. You can have your MVC app add CloudQueueMessage objects to an Azure Storage Queue. These messages can contain the data parameters (i.e. student list, professor name, etc.) that are unique to the class, and you can delay the visibility in the Queue with the visibilitytimeout parameter when you perform the "Put Message".

You can calculate the visibilitytimeout by subtracting the desired time from the current time. Note that the timeout cannot be longer than 7 days, so if these events are being queued for long periods of times, you may be forced to reinsert the message into the queue repeatedly until you get within the 7 day range and you can successfully process the message.


问:
How can I get sum of value from a column based on condition mixed with second list using R?
When I try to do operation on 2 lists I get a error messages and the calculation does not work properly.(see end of question)

```<code>list2 <- list2 %>%
mutate(sum_of_part = sum(list1$part[(list1$id < list2$id) & (list1$id >= lag(list2$id))]))

</code>```

So what I want to do is:
Get the sum of "part" of all rows in list1 where the "id" is between the "id" of the current row in list2 and the "id" of the row before.
I also want to count the number of rows which are used to calculate the column sum_of_parts.

list1

```<code>id    Part   ...
1      2
2      3
3      4
4      6
99     11
100    11
191    11
222    11
333    11
</code>```

list2

```<code>id   ...
1
3
4
88
99
</code>```

solution

```<code>id   ...  sum_of_parts    count
 1   ...        2           1
 3   ...        9           3
 4   ...        10          2
88   ...        6           1
99   ...        11          1
</code>```

But because my list2 is a lot smaller then my list1, I do get this errors(there are some more but they look almost the same):
In list1$id < list2$id :   longer object length is not a multiple of shorter object length

答:
You were really close, this one gets me all the time!

mutate operates by group I believe, so if you haven't specified a group it will try to use the whole column in a vectorised operation (which is usually more efficient), and thus the error about different lengths.

If you want to operate on each row, you can use rowwise(), to make the following calculations treat each row as a group. So id will be a length one vector in the mutate call.

Note we need to specify the lag before grouping, otherwise using the logic above, there will be no previous id in a length one vector.

library(dplyr)

list1 <- readr::read_csv(
'id,part
1,2
2,3
3,4
4,6
99,11
100,11
191,11
222,11
333,11')

list2 <- readr::read_csv(
'id
 1
 3
 4
 88
 99'
)

list2 %>%
  mutate(lag_id = lag(id, default = 0)) %>%
  rowwise() %>%
  mutate(sum_of_part = sum(list1$part[(list1$id <= id) & (list1$id > lag_id)]),
         count = length(list1$part[(list1$id <= id) & (list1$id > lag_id)])) %>%
  select(-lag_id)
#> Source: local data frame [5 x 3]
#> Groups: <by row>
#>
#> # A tibble: 5 x 3
#>      id sum_of_part count
#>   <int>       <int> <int>
#> 1     1           2     1
#> 2     3           7     2
#> 3     4           6     1
#> 4    88           0     0
#> 5    99          11     1
```

Body:
When I try to do operation on 2 lists I get a error messages and the calculation does not work properly.(see end of question)

list2 <- list2 %>%
mutate(sum_of_part = sum(list1$part[(list1$id < list2$id) & (list1$id >= lag(list2$id))]))

So what I want to do is:
Get the sum of "part" of all rows in list1 where the "id" is between the "id" of the current row in list2 and the "id" of the row before.
I also want to count the number of rows which are used to calculate the column sum_of_parts.

list1

id    Part   ...
1      2
2      3
3      4
4      6
99     11
100    11
191    11
222    11
333    11

list2

id   ...
1
3
4
88
99

solution

id   ...  sum_of_parts    count
 1   ...        2           1
 3   ...        9           3
 4   ...        10          2
88   ...        6           1
99   ...        11          1

But because my list2 is a lot smaller then my list1, I do get this errors(there are some more but they look almost the same):
In list1$id < list2$id :   longer object length is not a multiple of shorter object length


问:
Hadoop HA Namenode goes down with the Error: flush failed for required journal (JournalAndStream(mgr=QJM to [< ip >:8485, < ip >:8485, < ip >:8485]))
Hadoop Namenode goes down almost everyday once.

```<code>FATAL namenode.FSEditLog (JournalSet.java:mapJournalsAndReportErrors(398)) -

**Error: flush failed for required journal** (JournalAndStream(mgr=QJM to [< ip >:8485, < ip >:8485, < ip >:8485], stream=QuorumOutputStream starting at txid <>))
java.io.IOException: Timed out waiting 20000ms for a quorum of nodes to respond.
    at org.apache.hadoop.hdfs.qjournal.client.AsyncLoggerSet.waitForWriteQuorum(AsyncLoggerSet.java:137)
    at org.apache.hadoop.hdfs.qjournal.client.QuorumOutputStream.flushAndSync(QuorumOutputStream.java:107)
    at org.apache.hadoop.hdfs.server.namenode.EditLogOutputStream.flush(EditLogOutputStream.java:113)
    at
</code>```

Can someone suggest what are the things that I need to look into for resolving this issue?

I am using VMs for the journal nodes and master nodes. Does it cause any issue?

答:
In my case, this issue was caused due to the difference in the system time between the nodes of the cluster.

To keep the system time in sync, we can execute the commands below in each node.

```<code>sudo service ntpd stop

sudo ntpdate pool.ntp.org  # Run this command multiple times

sudo service ntpd start
</code>```

If hue is down, run below command on the hue server machine

```<code>sudo service hue start
</code>```

If namenode is down, start the namenode.

Recurring fix

Add a crontab for the root user on all the nodes of the environment.

or

Install VM tools, to keep the system time in sync.

Body:
Hadoop Namenode goes down almost everyday once.

FATAL namenode.FSEditLog (JournalSet.java:mapJournalsAndReportErrors(398)) -

**Error: flush failed for required journal** (JournalAndStream(mgr=QJM to [< ip >:8485, < ip >:8485, < ip >:8485], stream=QuorumOutputStream starting at txid <>))
java.io.IOException: Timed out waiting 20000ms for a quorum of nodes to respond.
    at org.apache.hadoop.hdfs.qjournal.client.AsyncLoggerSet.waitForWriteQuorum(AsyncLoggerSet.java:137)
    at org.apache.hadoop.hdfs.qjournal.client.QuorumOutputStream.flushAndSync(QuorumOutputStream.java:107)
    at org.apache.hadoop.hdfs.server.namenode.EditLogOutputStream.flush(EditLogOutputStream.java:113)
    at

Can someone suggest what are the things that I need to look into for resolving this issue?

I am using VMs for the journal nodes and master nodes. Does it cause any issue?

Body:
In my case, this issue was caused due to the difference in the system time between the nodes of the cluster.

To keep the system time in sync, we can execute the commands below in each node.

sudo service ntpd stop

sudo ntpdate pool.ntp.org  # Run this command multiple times

sudo service ntpd start

If hue is down, run below command on the hue server machine

sudo service hue start

If namenode is down, start the namenode.

Recurring fix

Add a crontab for the root user on all the nodes of the environment.

or

Install VM tools, to keep the system time in sync.


问:
Have a text from database to get a color out from what it says

Hey guys, im not good with coding so after failing to find out how from googling Im gonna try get help from the pros.

So, im just making something for fun cause im bored. I have a sql database with a table that consists of name, link and status.
The status has 3 options, Permanently Banned, Temporarily Banned and Kicked.

Currently I have it like this putting font color in the code, but then it all get in red text.

```<code>while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='red'> " . $row["status"] . "</font></b></td></tr>";

}
</code>```

I want Permanently Banned to be in red, Temporarily Banned in orange and Kicked in green. I don't understand how to make the colors appear like that.

I appreciate any help, im still a newbie when it comes to coding so im sorry if this is a really easy solution that I failed to find :P

I also have a problem with the link, but im just gonna let it be for now, maybe I'l ask after this is fixed..

Thanks! :)

答:
A quick solution that only affects the short example of code you provided might be to use an inline if

```<code>while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='" . ($row["status"]=="Permanently Banned" ? "red" : ($row["status"]=="Temporarily Banned" ? "orange" : "green")) . "'> " . $row["status"] . "</font></b></td></tr>";
}
</code>```

You could also do the conditional logic very easily in SQL, for new developers I often find this is an easier approach because it can be easier to manipulate the sql query than it might be to mess with the rendering code. You didn't provide your query, so I will assume what it is, (in future posts, please provide the sql query so we can provide a more complete solution) hopefully you can follow the switch logic and apply that to your own code:

```<code>SELECT name, link, status,
    CASE status
        WHEN 'Permanently Banned' THEN 'Red'
        WHEN 'Temporarily Banned' THEN 'Orange'
        ELSE 'Green'
    END as color
FROM MyStatusTable
</code>```

Then your rendering code is cleaner:

```<code>while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='" . $row["color"] . "'> " . $row["status"] . "</font></b></td></tr>";
}
</code>```

Happy coding :)

Body:
Hey guys, im not good with coding so after failing to find out how from googling Im gonna try get help from the pros.

So, im just making something for fun cause im bored. I have a sql database with a table that consists of name, link and status.
The status has 3 options, Permanently Banned, Temporarily Banned and Kicked.

Currently I have it like this putting font color in the code, but then it all get in red text.

while($row = $result->fetch_assoc()) {
    echo "

     ". $row["name"]. "
     ". $row["link"]. "
     " . $row["status"] . "
";

}

I want Permanently Banned to be in red, Temporarily Banned in orange and Kicked in green. I don't understand how to make the colors appear like that.

I appreciate any help, im still a newbie when it comes to coding so im sorry if this is a really easy solution that I failed to find :P

I also have a problem with the link, but im just gonna let it be for now, maybe I'l ask after this is fixed..

Thanks! :)

Body:
A quick solution that only affects the short example of code you provided might be to use an inline if

while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='" . ($row["status"]=="Permanently Banned" ? "red" : ($row["status"]=="Temporarily Banned" ? "orange" : "green")) . "'> " . $row["status"] . "</font></b></td></tr>";
}

You could also do the conditional logic very easily in SQL, for new developers I often find this is an easier approach because it can be easier to manipulate the sql query than it might be to mess with the rendering code. You didn't provide your query, so I will assume what it is, (in future posts, please provide the sql query so we can provide a more complete solution) hopefully you can follow the switch logic and apply that to your own code:

SELECT name, link, status,
    CASE status
        WHEN 'Permanently Banned' THEN 'Red'
        WHEN 'Temporarily Banned' THEN 'Orange'
        ELSE 'Green'
    END as color
FROM MyStatusTable

Then your rendering code is cleaner:

while($row = $result->fetch_assoc()) {
    echo "<tr>
    <td class='text-left'> ". $row["name"]. " </td>
    <td class='text-left'> ". $row["link"]. "</td>
    <td class='text-left'><b><font color='" . $row["color"] . "'> " . $row["status"] . "</font></b></td></tr>";
}

Happy coding :)


问:
How do I run a method while a timer is running on screen?
First off- this is a homework assignment. I'm supposed to go beyond what we have learned, so I thought of a WPM console application.
I did a lot of searching on Timers, but that's way too over my head for first semester.
So I found an easier way. The thing is, I want to be able to call some string and have the user type them in, and run a calculation in the end to determine their words per minute. I read that using Task.Factory.StartNew should let me run two methods.

```<code>class Program
{
    static void Main( string[] args )
    {
        Timer go = new Timer( );
        WordBank display = new WordBank( );

        Task.Factory.StartNew(go.timer1_Tick);
        Task.Factory.StartNew(display.LevelOneWords);
        Console.ReadKey( );

    }
}//end main

class Timer
{
public Timer()
{}
    public void timer1_Tick(  )
    {
        int seconds= 0;
        DateTime dt = new DateTime( );

        do
        {
            Console.Write("One minute timer: " + dt.AddSeconds(seconds).ToString("ss"));
            Console.Write("\r");
            seconds++;
            Thread.Sleep(1000);
        } while ( seconds< 60 );
    }
}//end Timer

class WordBank
{
public WordBank()
{ }

public void LevelOneWords()
{
        string easyWords = "the boy had so much fun at the park.";
        Console.WriteLine("\n\n", easyWords);
        Console.ReadKey( );
}
</code>```

When I run the program the timer starts for a second and then is immediately replaced with the string. Am I using Task.Factory.StartNew incorrectly?

答:
Instead of running a timer while they are typing (requiring two programs simultaneously), instead try getting the time when they initially start typing, the time when they end typing, and then do some division.  IE:

```<code>static void Main()
{
    // Displays WordBank
    WordBank display = new WordBank();

    var startTime = DateTime.Now;

    // Let them type for X amount of time
    var totalWords = TakeUserInputForXSeconds(45);

    var endTime = DateTime.Now;

    var wpm = totalWords / (endTime.Subtract(startTime).TotalMinutes);
}
</code>```

For the TakeUserInputForXSeconds method, I would look at the information in this post: Stop running the code after 15 seconds

Body:
First off- this is a homework assignment. I'm supposed to go beyond what we have learned, so I thought of a WPM console application.
I did a lot of searching on Timers, but that's way too over my head for first semester.
So I found an easier way. The thing is, I want to be able to call some string and have the user type them in, and run a calculation in the end to determine their words per minute. I read that using Task.Factory.StartNew should let me run two methods.

class Program
{
    static void Main( string[] args )
    {
        Timer go = new Timer( );
        WordBank display = new WordBank( );

        Task.Factory.StartNew(go.timer1_Tick);
        Task.Factory.StartNew(display.LevelOneWords);
        Console.ReadKey( );

    }
}//end main

class Timer
{
public Timer()
{}
    public void timer1_Tick(  )
    {
        int seconds= 0;
        DateTime dt = new DateTime( );

        do
        {
            Console.Write("One minute timer: " + dt.AddSeconds(seconds).ToString("ss"));
            Console.Write("\r");
            seconds++;
            Thread.Sleep(1000);
        } while ( seconds< 60 );
    }
}//end Timer

class WordBank
{
public WordBank()
{ }

public void LevelOneWords()
{
        string easyWords = "the boy had so much fun at the park.";
        Console.WriteLine("\n\n", easyWords);
        Console.ReadKey( );
}

When I run the program the timer starts for a second and then is immediately replaced with the string. Am I using Task.Factory.StartNew incorrectly?

Body:
Instead of running a timer while they are typing (requiring two programs simultaneously), instead try getting the time when they initially start typing, the time when they end typing, and then do some division.  IE:

static void Main()
{
    // Displays WordBank
    WordBank display = new WordBank();

    var startTime = DateTime.Now;

    // Let them type for X amount of time
    var totalWords = TakeUserInputForXSeconds(45);

    var endTime = DateTime.Now;

    var wpm = totalWords / (endTime.Subtract(startTime).TotalMinutes);
}

For the TakeUserInputForXSeconds method, I would look at the information in this post: Stop running the code after 15 seconds


问:
How can I get only 1 result to be printed to the console and not both of them?

My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

```<code>keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)
</code>```

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

```<code>Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print
</code>```

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

答:
```<code>>>> keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-':    0.3, ' ': 0.0}
>>> grade = input('Grade:') + ' '
>>> if grade[0] in keydict and grade[1] in keydict:
       print(grade, keydict[grade[0]]+ keydict[grade[1]])
    else:
       print(grade, 'is an invalid input')
</code>```

B  3.0
banana  is an invalid input
B-  2.7

Body:
My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

Body:
>>> keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-':    0.3, ' ': 0.0}
>>> grade = input('Grade:') + ' '
>>> if grade[0] in keydict and grade[1] in keydict:
       print(grade, keydict[grade[0]]+ keydict[grade[1]])
    else:
       print(grade, 'is an invalid input')

B  3.0
banana  is an invalid input
B-  2.7


问:
Windows Phone 7 Download Versions
For windows phone addon, do I have to install the express tools download?  There isn't any add-on for users who already have Visual Studio RTM?  I can't find that anywhere...  I don't want to have to install express tools, there's probably an option, but curious if anyone has found that alternative download anywhere.

Thanks,

Brian

答: Yeah, I was miffed by that too.  Don't worry, Express and VS2010 sit side-by-side just fine and if you just use 2010 normally everything works.  Just install the tools and trust that everything will be okay.  :)</p>

Title: Windows Phone 7 Download Versions


问:
RAW (JSON) POST data arrives as NULL or EMPTY ARRAY
Im trying to make a REST API with PHP and I've got a problem receiving POST data, if i send it with a form, it arrives perfectly fine.
But when i try to send it with Content-Type application/json it arrives as empty array.

Here is the code that receives the data:

```<code>$data = json_decode(file_get_contents('php://input'), true);
die(var_dump($data));
</code>```

the data is sent with Boomerang REST client.

This are the HEADERS of the request:

```<code>POST /miel/api/inscripcion-tutoria HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 0
Origin: chrome-extension://eipdnjedkpcnlmmdfdkgfpljanehloah
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Content-Type: application/json
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: es-419,es;q=0.9,en;q=0.8,fr;q=0.7
Cookie: PHPSESSID=b586e11ef9d81...bd992603a; _ga=GA1.1.20...67.151250
</code>```

The response is this one:

```<code>HTTP/1.1 200 OK
Date: Thu, 07 Dec 2017 15:49:46 GMT
Server: Apache/2.4.27 (Unix) PHP/7.1.7
X-Powered-By: PHP/7.1.7
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
</code>```

Notice that Content-Length is 0, and when y execute the var_dump the data is completely empty.

I've also tried with this:

```<code>die(var_dump($_POST));
</code>```

That last example only works when I send the data with a FORM like

```<code><form action=http://localhost/miel/api/inscripcion-tutoria method=post >
</code>```

In case of the form the content type is

```<code>Content-Type: application/x-www-form-urlencoded
</code>```

Content length in the response headers are the same.

But if I change the content type in the boomerang REST client and put it like the one sent in the form it doesn't work neither.

I tried with the variable $HTTP_RAW_POST_DATA and the var_dump returned NULL.

Any clue on the solution would be very appreciated!
Thank you!

答:
I've finally found the solution to the problem. It was very simple and a matter of inexperience.

When you send a request with POSTMAN or Boomerang or any other REST client, the data must be on the body of the request.

I was using the empty fields of the "PARAMS" given by the client, but those are meant to add items to the URL, not to make a data structure for the body.

Body:
Im trying to make a REST API with PHP and I've got a problem receiving POST data, if i send it with a form, it arrives perfectly fine.
But when i try to send it with Content-Type application/json it arrives as empty array.

Here is the code that receives the data:

$data = json_decode(file_get_contents('php://input'), true);
die(var_dump($data));

the data is sent with Boomerang REST client.

This are the HEADERS of the request:

POST /miel/api/inscripcion-tutoria HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 0
Origin: chrome-extension://eipdnjedkpcnlmmdfdkgfpljanehloah
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Content-Type: application/json
Accept: */*
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: es-419,es;q=0.9,en;q=0.8,fr;q=0.7
Cookie: PHPSESSID=b586e11ef9d81...bd992603a; _ga=GA1.1.20...67.151250

The response is this one:

HTTP/1.1 200 OK
Date: Thu, 07 Dec 2017 15:49:46 GMT
Server: Apache/2.4.27 (Unix) PHP/7.1.7
X-Powered-By: PHP/7.1.7
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

Notice that Content-Length is 0, and when y execute the var_dump the data is completely empty.

I've also tried with this:

die(var_dump($_POST));

That last example only works when I send the data with a FORM like

<form action=http://localhost/miel/api/inscripcion-tutoria method=post >

In case of the form the content type is

Content-Type: application/x-www-form-urlencoded

Content length in the response headers are the same.

But if I change the content type in the boomerang REST client and put it like the one sent in the form it doesn't work neither.

I tried with the variable $HTTP_RAW_POST_DATA and the var_dump returned NULL.

Any clue on the solution would be very appreciated!
Thank you!


问:
Goal: stripping whitespace adjacent to certain characters
What I am doing:

```<code>> ' { foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s[{}():]\s/g, '');
< "foobar: 8{ baz: 9 fun: bun} "
</code>```

What I am trying to do:

```<code>> ???
< "{foo(bar:8){baz:9 fun:bun}}"
</code>```

This has to do with compressing queries for sending from a client to a graphql server. ;-)

答:
I'm afraid regexes won't suit your needs here, a proper library would be much more appropriate.

In the mean time, you can give a try to .replace(/\B | \B/, ""), but it for sure does not cover all the cases, plus certainly breaks some requests. This covers your example at least.

Body:
What I am doing:

> ' { foo ( bar: 8 ) { baz: 9 fun: bun } } '.replace(/\s[{}():]\s/g, '');
< "foobar: 8{ baz: 9 fun: bun} "

What I am trying to do:

> ???
< "{foo(bar:8){baz:9 fun:bun}}"

This has to do with compressing queries for sending from a client to a graphql server. ;-)


问:
Count all entries of child tables in single query
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

```<code>MainTable
  |--Child1
  |--Child2
</code>```

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.

答:
```<code>declare @Number int = number;

select  M.IdMain
        , SUM( Count(C1.Id) + Count(C2.Id) ) as TotalSum
from    Main M, Child1 C1, Child2 C2
where   IdMain = @Number
and     M.IdMain = C1.Id
and     M.IdMain = C2.Id
group
by      M.IdMain
</code>```

Body:
I have a parent table which holds a primary key (IdMain) that two separate tables use as a foreign key.

e.g.

MainTable
  |--Child1
  |--Child2

Is there a simple way to count the number of entries in Child1 and Child2 with a specific IdMain?

I can do it with two queries, both inner joins, then add the result - and I've tried by having MainTable mt1  and MainTable mt2 in the same FROM but not got the results I expected.


问:
Display block and height not working for image
So I want my image to be automatically resized when screen resolution is under 740 pixels.
This code is outside @media.

header img {
  display: block;
  height: 150px;
  margin: auto;
}

@media screen and (max-width: 740px) {
  header img {
    display: block;
    width: 100%;
    height: auto;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <img src="https://images.vexels.com/media/users/3/137694/isolated/lists/35e10823069d1767521320dc34475465-triangle-logo-geometric.png">
</header></code>```

This code is not working! Why? When I check the code in chrom dev tools, these properties are deleted out except width:100%;!

答:
The first definition is the default style. Add !important to enforce the screen style</p>

```<code>@media screen and (max-width: 740px){
   header img{
       height:auto !important;
   }
</code>```

Body:
So I want my image to be automatically resized when screen resolution is under 740 pixels.
This code is outside @media.

header img {
  display: block;
  height: 150px;
  margin: auto;
}

@media screen and (max-width: 740px) {
  header img {
    display: block;
    width: 100%;
    height: auto;
  }
}

This code is not working! Why? When I check the code in chrom dev tools, these properties are deleted out except width:100%;!

Body:
The first definition is the default style. Add !important to enforce the screen style

@media screen and (max-width: 740px){
   header img{
       height:auto !important;
   }


问:
Setting id tag dynamically using vuejs
I have a vue.js template that has a todo prop. I want to dynamically set the id value of each element. This what I have tried so far, is something like this possible and if not what are some other options?</p>

```<code><canvas class="canvas" id="cv`${{todo.id}}`" width="500" height="700"></canvas>
</code>```

答:
This should work.

```<code>:id="`cv${todo.id}`"
</code>```

or

```<code>v-bind:id="`cv${todo.id}`"
</code>```

Or do it the old-school way if the browser doesn't support string interpolation:

```<code>:id="'cv' + todo.id"
</code>```

This is essentially a duplicate but I couldn't determine how to escape the backticks in a comment!

Title: Setting id tag dynamically using vuejs

Body:
I have a vue.js template that has a todo prop. I want to dynamically set the id value of each element. This what I have tried so far, is something like this possible and if not what are some other options?

<canvas class="canvas" id="cv`${{todo.id}}`" width="500" height="700"></canvas>

Body:
This should work.

:id="`cv${todo.id}`"

or

v-bind:id="`cv${todo.id}`"

Or do it the old-school way if the browser doesn't support string interpolation:

:id="'cv' + todo.id"

This is essentially a duplicate but I couldn't determine how to escape the backticks in a comment!


答:
IIUC:</p>

```<code>In [170]: data['new'] = data[['has_a_pass','is_an_employee']].any(1)

In [171]: data
Out[171]:
   has_a_pass  is_an_employee name    new
0       False            True    A   True
1       False           False    B  False
2       False            True    C   True
3        True            True    D   True
4       False           False    E  False
</code>```

Title: Return a boolean value based on the booleans of two other columns

Body:
I'm trying to add a new column to a DataFrame based on the boolean values of two other columns. If one of the two columns has a true value, then I would like the new column to return, True. Only if both the columns have a false value, then I would like this new column to return False.

As I am pretty new to python, I have not gotten very far.

A DataFrame like this would be a good example:

data = DataFrame({ 'name': ['A', 'B', 'C', 'D', 'E'],
                   'has_a_pass': [False, False, False, True, False],
                   'is_an_employee': [True, False, True, True, False] })

Anyone have any useful suggestions for solving this?

Body:
IIUC:

In [170]: data['new'] = data[['has_a_pass','is_an_employee']].any(1)

In [171]: data
Out[171]:
   has_a_pass  is_an_employee name    new
0       False            True    A   True
1       False           False    B  False
2       False            True    C   True
3        True            True    D   True
4       False           False    E  False


问:
Django - Trying to a field that is not in the form but is in the model
Right now I have a model.form with one field nothing more, but the model has 3 fields(see reference down below) and 1 of them set by the form, one has a default to false as it should be and the last one I will set in the view but it won't correctly do it and idk why.

Model & Form.

```<code>class TeamMembership(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    leader = models.BooleanField(default=False)

class TeamSettings_acceptForm(forms.ModelForm):
    class Meta:
        model = TeamMembership
        fields = ('user',)
</code>```

View

```<code>@login_required
def teamsettings_accept_applications(request, team_pk):
    if request.method == 'POST':
        logged_in_user = get_object_or_404(User, pk=request.user.pk)
        requested_team = get_object_or_404(Team, pk=team_pk)
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                formaccept = TeamSettings_acceptForm(request.POST)
                accepteduserid = formaccept.data['user']
                teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid).count()
                if teamapplications > 1:
                    messages.success(request, "Error")
                    return redirect('teamsettings_applications', team_pk=team_pk)
                else:
                    if formaccept.is_valid():
                        teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
                        teamapplications.update(accepted=True)
                        formaccept.team = requested_team.pk
                        formaccept.save()
                        messages.success(request, "User has now been added to your team!")
                        return redirect('teamsettings_applications', team_pk=team_pk)
</code>```

it should create a new row with that data and update the others.

All I get in return from Django is

```<code>staff_teammembership.team_id may not be NULL
</code>```

答:
You haven't processed the Model form into an instance of a model yet. So formaccept doesn't know what team is here, because it's an instance of TeamSettings_acceptForm which doesn't have team as a field. To fix this change the is_valid code:

```<code>if formaccept.is_valid():
    teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
    teamapplications.update(accepted=True)

    # New code here
    new_team_membership = formaccept.save(commit=false)
    new_team_membership.team = requested_team.pk
    new_team_membership.save()

    messages.success(request, "User has now been added to your team!")
    return redirect('teamsettings_applications', team_pk=team_pk)
</code>```

Using commit=false is really handy with Modelforms.

Body:
Right now I have a model.form with one field nothing more, but the model has 3 fields(see reference down below) and 1 of them set by the form, one has a default to false as it should be and the last one I will set in the view but it won't correctly do it and idk why.

Model & Form.

class TeamMembership(models.Model):
    user = models.ForeignKey(User)
    team = models.ForeignKey(Team)
    leader = models.BooleanField(default=False)

class TeamSettings_acceptForm(forms.ModelForm):
    class Meta:
        model = TeamMembership
        fields = ('user',)

View

@login_required
def teamsettings_accept_applications(request, team_pk):
    if request.method == 'POST':
        logged_in_user = get_object_or_404(User, pk=request.user.pk)
        requested_team = get_object_or_404(Team, pk=team_pk)
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                formaccept = TeamSettings_acceptForm(request.POST)
                accepteduserid = formaccept.data['user']
                teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid).count()
                if teamapplications > 1:
                    messages.success(request, "Error")
                    return redirect('teamsettings_applications', team_pk=team_pk)
                else:
                    if formaccept.is_valid():
                        teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
                        teamapplications.update(accepted=True)
                        formaccept.team = requested_team.pk
                        formaccept.save()
                        messages.success(request, "User has now been added to your team!")
                        return redirect('teamsettings_applications', team_pk=team_pk)

it should create a new row with that data and update the others.

All I get in return from Django is

staff_teammembership.team_id may not be NULL

Body:
You haven't processed the Model form into an instance of a model yet. So formaccept doesn't know what team is here, because it's an instance of TeamSettings_acceptForm which doesn't have team as a field. To fix this change the is_valid code:

if formaccept.is_valid():
    teamapplications = TeamApplication.objects.all().filter(from_user=accepteduserid)
    teamapplications.update(accepted=True)

    # New code here
    new_team_membership = formaccept.save(commit=false)
    new_team_membership.team = requested_team.pk
    new_team_membership.save()

    messages.success(request, "User has now been added to your team!")
    return redirect('teamsettings_applications', team_pk=team_pk)

Using commit=false is really handy with Modelforms.


问:
TCP Socket communication Java - Python
I want to transmit an integer number throught a socket.
I have a python script that open a socket and wait for requests, in the other side there is a Java servlet that send a request at this socket to obtain a value.

All the communication works well the problem is that the value obtained from java cause a EOFexception. I've tried some convertion and formats in the python script (I'm not expert of this language) but nothing works.

Instead, if I use in python a echo socket, picking all that socket receive and send back to java, all working fine.

But I need to send a simple value.

The following is the portion of code that I use, I've tried with float, this is with a String value:

[Python socket related istructions]

```<code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(server_address)
sock.listen(1)
connection = sock.accept()
</code>```

[Python echo socket working]

```<code>data = connection.recv(16)
if data:
    connection.sendall(data)
</code>```

instead I want to do:

[Python return a example value]

```<code> connection.sendall('55')
</code>```

That working if I send request from a client like Hercules but cause a EOFexception in Java

[Java Servlet - send request]

```<code>socket = new Socket(address, port);
dataInputStream = new DataInputStream(socket.getInputStream());
String content = dataInputStream.readUTF(); //EOFexception
Destination.value = content;
</code>```

答: Solved the problem by using InputStream instead of DataInputStream, write the python socket to send string as byte and changed the java receiver to read byte stream and convert in to string (good format for my purpose).</p>

Title: TCP Socket communication Java - Python

Body:
I want to transmit an integer number throught a socket.
I have a python script that open a socket and wait for requests, in the other side there is a Java servlet that send a request at this socket to obtain a value.

All the communication works well the problem is that the value obtained from java cause a EOFexception. I've tried some convertion and formats in the python script (I'm not expert of this language) but nothing works.

Instead, if I use in python a echo socket, picking all that socket receive and send back to java, all working fine.

But I need to send a simple value.

The following is the portion of code that I use, I've tried with float, this is with a String value:

[Python socket related istructions]

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(server_address)
sock.listen(1)
connection = sock.accept()

[Python echo socket working]

data = connection.recv(16)
if data:
    connection.sendall(data)

instead I want to do:

[Python return a example value]

 connection.sendall('55')

That working if I send request from a client like Hercules but cause a EOFexception in Java

[Java Servlet - send request]

socket = new Socket(address, port);
dataInputStream = new DataInputStream(socket.getInputStream());
String content = dataInputStream.readUTF(); //EOFexception
Destination.value = content;


问:
How to determine graphics capabilities of an x11 terminal window
The standard xterm program has a Tek4014 emulation for some simple graphics output. This is however not implemented in most (all?) sucessors, like rxvt, gnome-terminal, or kterm.

However, almost all X11 terminals report xterm as (part of) the environment variable TERM, which makes it difficult for a program to determine whether the underlying terminal has graphics capabilities.

Is it possible to find that out programmatically? And, are there modern terminal windows (beside xterm) that implement Tek4014 graphics, maybe as an add-on?

答:
The send device attributes sequence will cause the terminal to reply back with a cryptic string. Programs like vim use this to probe what version of xterm they are dealing with, but I don't know of specific documentation to interpret the results. Perhaps reading source?

See:

What is the ANSI escape code sequence "ESC[>c"?

Try it yourself:

```<code> printf "\E[c\n" ; sleep 1 ; echo
</code>```

My non-xterm xterm compatible terminal says "\E[?1;2c" back.

Body:
The send device attributes sequence will cause the terminal to reply back with a cryptic string. Programs like vim use this to probe what version of xterm they are dealing with, but I don't know of specific documentation to interpret the results. Perhaps reading source?

See:

What is the ANSI escape code sequence "ESC[>c"?

Try it yourself:

 printf "\E[c\n" ; sleep 1 ; echo

My non-xterm xterm compatible terminal says "\E[?1;2c" back.


问:
what is the difference saving a byte in OutputStream
Hello I have the next code:

```<code>package com.jucepho;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

class Copy{
public Copy(byte[] buffer,int count) {
    this.buffer = buffer;
    this.count = count;
}
private byte[] buffer;
private int count;

public byte[] getBuffer() {
    return buffer;
}
public int getCount() {
    return count;
}
}

public class ReaderTwo {

public static void main(String[] args) throws IOException {
    InputStream is = new FileInputStream("ex.docx");
     OutputStream os = new FileOutputStream("exBu.docx");
     OutputStream os2 = new FileOutputStream("exBu2.docx");
    ArrayList<Copy> lista = new ArrayList<>();
    byte[] buffer = new byte[4096];
    int count;
    while ((count = is.read(buffer)) > 0)
    {
           os.write(buffer, 0, count);
        lista.add(new Copy(buffer,count));
    }

    for(Copy c: lista) {
        os2.write(c.getBuffer(), 0, c.getCount());
    }

}

}
</code>```

I want to read a file more than 5 GB in order to save it. So I saw that I have to read it in this way (Encrypting a large file with AES using JAVA)

My question is, why

```<code>OutputStream os = new FileOutputStream("exBu.docx");
</code>```

copy the data good, i mean the file is correct but

```<code>OutputStream os2 = new FileOutputStream("exBu2.docx");
</code>```

is not correct, is corrupted or I don't know why if I am doing the same, right? I am saving in my ArrayList the same information so why my file is corrupted. (and yeah I need to save all the information in an Object called Copy as you see because I will use serialization and save it in other HD)

Thank you

答:
```<code>new Copy(buffer,count)
</code>```

This doesn't create a new byte[], it just passes the same array over and over into the Copy instance; next time you read data into that array, you overwrite the contents of the array in all previous Copy instances.

If you want the Copy to remain unchanged, copy the buffer:

```<code>new Copy(Arrays.copyOf(buffer, count), count)
</code>```

(or do it in the constructor: this.buffer = Arrays.copyOf(buffer, count);)

Body:
Hello I have the next code:

package com.jucepho;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

class Copy{
public Copy(byte[] buffer,int count) {
    this.buffer = buffer;
    this.count = count;
}
private byte[] buffer;
private int count;

public byte[] getBuffer() {
    return buffer;
}
public int getCount() {
    return count;
}
}

public class ReaderTwo {

public static void main(String[] args) throws IOException {
    InputStream is = new FileInputStream("ex.docx");
     OutputStream os = new FileOutputStream("exBu.docx");
     OutputStream os2 = new FileOutputStream("exBu2.docx");
    ArrayList<Copy> lista = new ArrayList<>();
    byte[] buffer = new byte[4096];
    int count;
    while ((count = is.read(buffer)) > 0)
    {
           os.write(buffer, 0, count);
        lista.add(new Copy(buffer,count));
    }

    for(Copy c: lista) {
        os2.write(c.getBuffer(), 0, c.getCount());
    }

}

}

I want to read a file more than 5 GB in order to save it. So I saw that I have to read it in this way (Encrypting a large file with AES using JAVA)

My question is, why

OutputStream os = new FileOutputStream("exBu.docx");

copy the data good, i mean the file is correct but

OutputStream os2 = new FileOutputStream("exBu2.docx");

is not correct, is corrupted or I don't know why if I am doing the same, right? I am saving in my ArrayList the same information so why my file is corrupted. (and yeah I need to save all the information in an Object called Copy as you see because I will use serialization and save it in other HD)

Thank you

Body:
new Copy(buffer,count)

This doesn't create a new byte[], it just passes the same array over and over into the Copy instance; next time you read data into that array, you overwrite the contents of the array in all previous Copy instances.

If you want the Copy to remain unchanged, copy the buffer:

new Copy(Arrays.copyOf(buffer, count), count)

(or do it in the constructor: this.buffer = Arrays.copyOf(buffer, count);)


问:
How to make nodes line reader skip lines conditionally
I'm currently working on a project where I'm using a line reader to input credit card numbers into a validator and identifier. Lets say I input 10 numbers, and they are from four different credit card companies. I want to ignore three companies and only show the numbers from the remaining companies.

This companies rules (conditions) are that it must have 15 digits in it, and start with 37 or 34

```<code>4111111111111111
4111111111111
4012888888881881
378282246310005
6011111111111117
5105105105105100
5105105105105106
9111111111111111
371449635398431
378734493671000
</code>```

Here is my current makeshift module:

```<code>export const isAmex = (creditCard: string): boolean =>
creditCard.length === 15 &&
(creditCard.substring(0, 2) === '37' || creditCard.substring(0, 2) === '34')

export const is2Amex = (creditCard: string): boolean =>
creditCard.length === 15 &&
(creditCard.substring(0, 2) === '37' || creditCard.substring(0, 2) === '34')

export const ifIsntAmex = (creditCard: string) => {
    if (!is2Amex(creditCard)) {
        return ' '
    } else {
        return creditCard
    }
}

export const getAmexName = (creditCard: string) => {
    if (!isAmex(creditCard)) {
        return ' '
    } else {
        return 'AMEX'
    }
}
</code>```

Here is part of the index:

```<code>const outputAmex: string[] = []

lineReader.on('line', (creditCard: string) => {
    outputAmex.push(
    `${getAmexName(creditCard)}: ${ifIsntAmex(creditCard)}
    (${cardValidator(creditCard) ? 'valid' : 'invalid'})`
    )
})

lineReader.on('close', () => {
    fs.writeFile('./data/Amex.txt', outputAmex.join('\n'), err => {
    if (err) throw err
    console.log('The file has been saved!')
    })
})
</code>```

It returns something like this:

```<code>:   (valid)
:   (invalid)
:   (valid)
AMEX: 378282246310005 (invalid)
:   (valid)
:   (valid)
:   (invalid)
:   (invalid)
AMEX: 371449635398431 (invalid)
AMEX: 378734493671000 (invalid)
</code>```

How would I ignore the non-Amex lines?

答:
```<code>lineReader.on('line', (creditCard: string) => {
   if (is2Amex(creditCard)) {
      outputAmex.push();
   }
})
</code>```

something like that?

Body:
I'm currently working on a project where I'm using a line reader to input credit card numbers into a validator and identifier. Lets say I input 10 numbers, and they are from four different credit card companies. I want to ignore three companies and only show the numbers from the remaining companies.

This companies rules (conditions) are that it must have 15 digits in it, and start with 37 or 34

4111111111111111
4111111111111
4012888888881881
378282246310005
6011111111111117
5105105105105100
5105105105105106
9111111111111111
371449635398431
378734493671000

Here is my current makeshift module:

export const isAmex = (creditCard: string): boolean =>
creditCard.length === 15 &&
(creditCard.substring(0, 2) === '37' || creditCard.substring(0, 2) === '34')

export const is2Amex = (creditCard: string): boolean =>
creditCard.length === 15 &&
(creditCard.substring(0, 2) === '37' || creditCard.substring(0, 2) === '34')

export const ifIsntAmex = (creditCard: string) => {
    if (!is2Amex(creditCard)) {
        return ' '
    } else {
        return creditCard
    }
}

export const getAmexName = (creditCard: string) => {
    if (!isAmex(creditCard)) {
        return ' '
    } else {
        return 'AMEX'
    }
}

Here is part of the index:

const outputAmex: string[] = []

lineReader.on('line', (creditCard: string) => {
    outputAmex.push(
    `${getAmexName(creditCard)}: ${ifIsntAmex(creditCard)}
    (${cardValidator(creditCard) ? 'valid' : 'invalid'})`
    )
})

lineReader.on('close', () => {
    fs.writeFile('./data/Amex.txt', outputAmex.join('\n'), err => {
    if (err) throw err
    console.log('The file has been saved!')
    })
})

It returns something like this:

:   (valid)
:   (invalid)
:   (valid)
AMEX: 378282246310005 (invalid)
:   (valid)
:   (valid)
:   (invalid)
:   (invalid)
AMEX: 371449635398431 (invalid)
AMEX: 378734493671000 (invalid)

How would I ignore the non-Amex lines?

Body:
lineReader.on('line', (creditCard: string) => {
   if (is2Amex(creditCard)) {
      outputAmex.push();
   }
})

something like that?


问:
libPods google map iOS , Install
I have This code in Podfile

```<code>source 'https://github.com/CocoaPods/Specs.git'
target 'Kine' do
pod 'GoogleMaps'
pod 'GooglePlaces'
end
</code>```

I want Install in Terminal

```<code>cd /Users/-----
pod Install
</code>```

I received this error

[!] Automatically assigning platform ios with version 11.0 on target because no platform was specified. Please specify a platform for this target in your Podfile. See https://guides.cocoapods.org/syntax/podfile.html#platform.

and in the site I see iOS 10.6 but I don't have iOS 10.6 in Xcode when I change the target in iOS 8.0 or 9.0 or 10 it's not work again and received the same error

and the libPods.a its missing (Red)

答:
Follow these steps:

Open terminal

type

sudo gem install cocoapods

create Podfile in your project root directory

Open Podfile

Type

```<code>platform :ios, '10.0'

use_frameworks!

target 'Kine' do

    pod 'GoogleMaps'
    pod 'GooglePlaces'
end
</code>```

open terminal goto: cd /Users/path/to/project/root

type pod Install and press enter

goto your project root using Finder

open file Kine.xcworkspace

Run your project

Title: libPods google map iOS , Install

Body:
I have This code in Podfile

source 'https://github.com/CocoaPods/Specs.git'
target 'Kine' do
pod 'GoogleMaps'
pod 'GooglePlaces'
end

I want Install in Terminal

cd /Users/-----
pod Install

I received this error

[!] Automatically assigning platform ios with version 11.0 on target because no platform was specified. Please specify a platform for this target in your Podfile. See https://guides.cocoapods.org/syntax/podfile.html#platform.

and in the site I see iOS 10.6 but I don't have iOS 10.6 in Xcode when I change the target in iOS 8.0 or 9.0 or 10 it's not work again and received the same error

and the libPods.a its missing (Red)

Body:
Follow these steps:

Open terminal

type

sudo gem install cocoapods

create Podfile in your project root directory

Open Podfile

Type

platform :ios, '10.0'

use_frameworks!

target 'Kine' do

    pod 'GoogleMaps'
    pod 'GooglePlaces'
end

open terminal goto: cd /Users/path/to/project/root

type pod Install and press enter

goto your project root using Finder

open file Kine.xcworkspace

Run your project


问:
How to determine whether a language is LL(1) LR(0) SLR(1)
Is there a simple way to determine whether a grammar is LL(1), LR(0), SLR(1)... just from looking on the grammar without doing any complex analysis?

For instance: To decide whether a BNF Grammar is LL(1) you have to calculate First and Follow sets - which can be time consuming in some cases.

Has anybody got an idea how to do this faster?
Any help would really be appreciated!

答: One aspect, "is the language/grammar ambiguous", is a known undecidable question like the Post correspondence and halting problems.</p>

OwnerDisplayName: Chris

LastEditorDisplayName: Jay Bazuzi

OwnerDisplayName: BCS

LastEditorDisplayName: BCS


问:
Running `pip` gives 'command not found' after successful Python homebrew install
To preface, I am very bad with the terminal, please be patient with me.

when I run pip I get:
    zsh: command not found: pip

I have installed Python 2.7.11 with brew, which should allow pip to work
When I run echo $PATH I get

```<code>/usr/local/sbin /Users/Nicolas/.composer/vendor/bin /Library/Frameworks/Python.framework/Versions/3.4/bin /usr/local/bin /usr/bin /bin /usr/sbin /sbin
</code>```

I notice that /usr/local/bin/ is in there, which I understand is where brew executables are linked to

when I run which -a python I get

```<code>/usr/local/bin/python
/usr/bin/python
</code>```

So-- two Python installs. I'm guessing one is the native OSX one and one is the homebrew install.
When I run which python I get

```<code>/usr/local/bin/python
</code>```

So this is the python that gets run when python is called, right?
When I run ls -l $(which python) I get

```<code>lrwxr-xr-x  1 Nicolas  admin  34 Feb  3 14:26 /usr/local/bin/python -> ../Cellar/python/2.7.11/bin/python
</code>```

I think this is where the problem is; I notice that there is a /python/2.7.11/libexec folder...

I have also tried brew unlink python && brew link python to no avail

when I try brew list python | grep pip I get a very long list of results

This is probably the most important one

```<code>/usr/local/Cellar/python/2.7.11/libexec/pip/pip/__init__.py
</code>```

I don't know how to proceed from here... I think it has to do with pip being in python/2.7.11/libexec instead of python/2.7.11/bin

I am not familiar with most of this stuff; my understanding of terminal is very limited. I am not sure how to proceed from here. Any and all help is appreciated, thanks.

答:
I ran into this problem myself on OS X. In my case, I finally did a listing of /usr/local/bin, and found that I had links from pip2, pip2.7, pip3, and pip3.6. What I lacked was a link from just pip. I don't know if this is just part of a new standard, or if I was missing something that would select one of the two, or if having both Python 2 and Python 3 installed meant that I didn't get a simple pip command. Either way, running brew doctor didn't reveal or solve any issues.

In this case, just running pip3 or pip2 (instead of pip) seemed to do the trick for me. In my case, I ran pip3 and everything installed and ran as expected.

Body:
To preface, I am very bad with the terminal, please be patient with me.

when I run pip I get:
    zsh: command not found: pip

I have installed Python 2.7.11 with brew, which should allow pip to work
When I run echo $PATH I get

/usr/local/sbin /Users/Nicolas/.composer/vendor/bin /Library/Frameworks/Python.framework/Versions/3.4/bin /usr/local/bin /usr/bin /bin /usr/sbin /sbin

I notice that /usr/local/bin/ is in there, which I understand is where brew executables are linked to

when I run which -a python I get

/usr/local/bin/python
/usr/bin/python

So-- two Python installs. I'm guessing one is the native OSX one and one is the homebrew install.
When I run which python I get

/usr/local/bin/python

So this is the python that gets run when python is called, right?
When I run ls -l $(which python) I get

lrwxr-xr-x  1 Nicolas  admin  34 Feb  3 14:26 /usr/local/bin/python -> ../Cellar/python/2.7.11/bin/python

I think this is where the problem is; I notice that there is a /python/2.7.11/libexec folder...

I have also tried brew unlink python && brew link python to no avail

when I try brew list python | grep pip I get a very long list of results

This is probably the most important one

/usr/local/Cellar/python/2.7.11/libexec/pip/pip/__init__.py

I don't know how to proceed from here... I think it has to do with pip being in python/2.7.11/libexec instead of python/2.7.11/bin

I am not familiar with most of this stuff; my understanding of terminal is very limited. I am not sure how to proceed from here. Any and all help is appreciated, thanks.


问:
unknown type of struct in parameter function C when using Struct type data in parameter

how to pass struct type data using parameters to another function ? i have already create a global struct but i think i've miss something

```<code>#include <stdio.h>
#include <stdlib.h>

struct Stuff
{
    int id;
    String name[20];
}

// call another function
int myFunctionInsert(Stuff *stuff);

int main()
{
    struct Stuff *stuff[20];
    myFunctionInsert(*stuff);
}

int myFunctionInsert(Stuff *stuff)
{
    int x;
    for(x = 0; x < 25; x++){
        stuff[x].id = x;
        stuff[x].name = 'stuff';
    }
}
</code>```

so my purpose is when i already call the myFunctionInsert, the struct data same as i was input in that function.

for example, when i call myFunctionShow (which is i'm not write in) the data show should be like this

```<code>id   : 1
name : stuff

// until 25
</code>```

when i tried my code above, i got an error

Unknown type name 'Stuff' (in line i call myFunctionInsert(Stuff *stuff))

any help will be appreciated

thanks

答:
The type you defined is struct Stuff not Stuff. Hence:

```<code>// call another function
int myFunctionInsert(struct Stuff *stuff);
</code>```

Alternatively use typedef:

```<code>typedef struct Stuff
{
    int id;
    String name[20];
} Stuff;
</code>```

Body:
how to pass struct type data using parameters to another function ? i have already create a global struct but i think i've miss something

#include <stdio.h>
#include <stdlib.h>

struct Stuff
{
    int id;
    String name[20];
}

// call another function
int myFunctionInsert(Stuff *stuff);

int main()
{
    struct Stuff *stuff[20];
    myFunctionInsert(*stuff);
}

int myFunctionInsert(Stuff *stuff)
{
    int x;
    for(x = 0; x < 25; x++){
        stuff[x].id = x;
        stuff[x].name = 'stuff';
    }
}

so my purpose is when i already call the myFunctionInsert, the struct data same as i was input in that function.

for example, when i call myFunctionShow (which is i'm not write in) the data show should be like this

id   : 1
name : stuff

// until 25

when i tried my code above, i got an error

Unknown type name 'Stuff' (in line i call myFunctionInsert(Stuff *stuff))

any help will be appreciated

thanks

Body:
The type you defined is struct Stuff not Stuff. Hence:

// call another function
int myFunctionInsert(struct Stuff *stuff);

Alternatively use typedef:

typedef struct Stuff
{
    int id;
    String name[20];
} Stuff;


问:
How do I use IFF in SSRS 2012
I am trying to get a average of a cycle times for all Serial numbers where cycle time <10 .

Here is the expressions I am using
=Avg(Fields!CycleTime.Value) IFF ( CycleTime<10),"Fields!CycleTime.Value","0")

答:
I'm not sure where you got your syntax from but it's all wrong....

For a start it's IIF not IFF

The expression you need is

```<code>=AVG(IIF(Fields!CycleTime.Value <10, Fields!CycleTime.Value,Nothing))
</code>```

The explanation if you are interested

The inner part simply evaluates each record to either it's value if it's <10 or nothing if it's >=10.

We then just take an average of these results.

Note We can't return a 0 for the records that are 10 or greater because this would cause them to be included in the average. By returning Nothing the AVG function will ignore these.

To illustrate lets say we had the following values

```<code>5,6,7,8,9,10,11,12,13
</code>```

If our IIF function returned zeros for values >=10 then we would get these results

```<code>5,6,7,8,9,0,0,0,0
</code>```

The sum of these is 35 but we have 9 values for the AVG would be 3.89

If we change the IIF function to return `Nothing' then the results would look like this.

```<code>5,6,7,8,9, Nothing, Nothing, Nothing, Nothing
</code>```

again our sum is 35 but AVG ignores the nothing values so divides the result by 5 giving us an average of 7.

Title: How do I use IFF in SSRS 2012

Body:
I'm not sure where you got your syntax from but it's all wrong....

For a start it's IIF not IFF

The expression you need is

=AVG(IIF(Fields!CycleTime.Value <10, Fields!CycleTime.Value,Nothing))

The explanation if you are interested

The inner part simply evaluates each record to either it's value if it's <10 or nothing if it's >=10.

We then just take an average of these results.

Note We can't return a 0 for the records that are 10 or greater because this would cause them to be included in the average. By returning Nothing the AVG function will ignore these.

To illustrate lets say we had the following values

5,6,7,8,9,10,11,12,13

If our IIF function returned zeros for values >=10 then we would get these results

5,6,7,8,9,0,0,0,0

The sum of these is 35 but we have 9 values for the AVG would be 3.89

If we change the IIF function to return `Nothing' then the results would look like this.

5,6,7,8,9, Nothing, Nothing, Nothing, Nothing

again our sum is 35 but AVG ignores the nothing values so divides the result by 5 giving us an average of 7.


问:
Bug while checking for symbols inside of a string?
I'm creating a small calculator script and I've got stumbled on a strange bug. Everything seems to work but not when I input anything starting with (. When I do that if gives false and the code inside of else executes. I've tried a lot of ways rewriting how should "$input" =~ [-,+,*,/,\(,\)] look like but nothing worked. Do you have any idea why that's happening and how to solve this bug?

```<code>#!/bin/bash
read -p "Input: " input
if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~ ^[0-9] && "$input" =~ [-,+,*,/,\(,\)] ]]; then
 (echo $input = $(($input))) 2>- || echo "Please, do not input ..."
else
 echo "Please, do not input letters or other special symbols and type in only expressions."
fi
</code>```

答:
...when I input anything starting with (. When I do that if gives false

That is because the second test requires that expressions start with a number: when an expression starts with (, the test "$input" =~ ^[0-9] fails.

[-,+,*,/,\(,\)] can be simplified to [-,+*/()].  This is because (a) the parens do not need to be escaped inside [...], and (b) there is no reason to specify , five times within a square bracket expression, [...].  If you want the regex to match a comma, listing it once is sufficient.   If you don't want it to match a comma, don't put the comma inside [...].

Body:
I'm creating a small calculator script and I've got stumbled on a strange bug. Everything seems to work but not when I input anything starting with (. When I do that if gives false and the code inside of else executes. I've tried a lot of ways rewriting how should "$input" =~ [-,+,*,/,\(,\)] look like but nothing worked. Do you have any idea why that's happening and how to solve this bug?

#!/bin/bash
read -p "Input: " input
if [[ ! "$input" =~ ^[A-Za-z_]+$ && "$input" =~ ^[0-9] && "$input" =~ [-,+,*,/,\(,\)] ]]; then
 (echo $input = $(($input))) 2>- || echo "Please, do not input ..."
else
 echo "Please, do not input letters or other special symbols and type in only expressions."
fi