问:
Counting days between two dates Y/m/d returns wrong number
I'm trying to count the days between 2 dates. It goes well if both dates are in the same month but not if they are in different.
Here is an example where it returns the correct number(1 day):

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,29);
var secondDate = new Date(2017,11,30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);
</code>```

Here is another example. In this case counting the days between last day of november and the 1st day of december, that should be 1 but returns 2

```<code>var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,30);
var secondDate = new Date(2017,12,1);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);
</code>```

I have observed that it returns wrong number if the months are different and if one or both months are conformed by less than 31 days, it adds the number of days missing from the month(s) that have less that 31, in this case 1 because november has 30 days and december 31, 1 + 1(missing days) = 2.
Any Idea of how to get it right is very welcomed.

答:
When creating a date with new Date(year, month, date), please be aware that the month argument is 0-based not 1-based. Read more on MDN: Date.

Therefore, in your second example, you are calculating the dates between 30 December 2017 and 1 January 2018, which is indeed 2 days rather than 1.

Body:
I'm trying to count the days between 2 dates. It goes well if both dates are in the same month but not if they are in different.
Here is an example where it returns the correct number(1 day):

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,29);
var secondDate = new Date(2017,11,30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

Here is another example. In this case counting the days between last day of november and the 1st day of december, that should be 1 but returns 2

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,30);
var secondDate = new Date(2017,12,1);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

I have observed that it returns wrong number if the months are different and if one or both months are conformed by less than 31 days, it adds the number of days missing from the month(s) that have less that 31, in this case 1 because november has 30 days and december 31, 1 + 1(missing days) = 2.
Any Idea of how to get it right is very welcomed.


来源: stackexchange

问:
Python random.randrange producing everything but the step
When using this following code:

```<code>import random
sticks = 100
randomstep = random.randint(1, 6)
expertmarbles = random.randrange(1, sticks, 2**randomstep)
</code>```

the output is producing everything excluding the step, so for example i would like this to output a random from these numbers: 2,4,8,16,32,64. However it will output everything but these numbers. Can anyone offer any advice, the reason i'm using variables here is because the amount of sticks will decrease.

答:
You can try this

```<code>def myRand(pow_min,pow_max):
    return 2**random.randint(pow_min,pow_max)
</code>```

I would suggest you to use this instead of random.choice, which requires you to generate a list, which is unnecessary.

ContentLicense: CC BY-SA 3.0

Body:
When using this following code:

import random
sticks = 100
randomstep = random.randint(1, 6)
expertmarbles = random.randrange(1, sticks, 2**randomstep)

the output is producing everything excluding the step, so for example i would like this to output a random from these numbers: 2,4,8,16,32,64. However it will output everything but these numbers. Can anyone offer any advice, the reason i'm using variables here is because the amount of sticks will decrease.

Body:
You can try this

def myRand(pow_min,pow_max):
    return 2**random.randint(pow_min,pow_max)

I would suggest you to use this instead of random.choice, which requires you to generate a list, which is unnecessary.


问:
How to make a div span 100% of the page even when scrolling to the right
This has probably been answered before somewhere, but I cant find a good solution. I want to create a header, which behaves like a div which is  position:absolute in the sense that it will stay at the top of the page when one scrolls down. Although, I would also like the user to be able to scroll right and left and have the header maintain its 100% width of the view port. Right now, with position absolute there becomes a white space to the right of the header as seen in the image. How can I create a header which maintains 100% width when scrolling right to left, but also stays at the top of the page when scrolling down using only css?

答:
You can use position:fixed to fix your header to the top of the page
https://developer.mozilla.org/en-US/docs/Web/CSS/position


问:
Sort columns automatically
I have a database-table with some football-matches, 3 per week, and I wrote them in a table like this example:

```<code>week  |team1   |team2   |date1   |time1   |team3  |team4  |date2  |time2  |
46    |Chelsea |Man Utd |18/11   |13:30   |Arsenal|Stoke  |19/11  |18:00  |
</code>```

Then I have this code to call them:

```<code>"SELECT * FROM table_name WHERE week = '$week'";
</code>```

...where $week = Date('W');

```<code>echo $row['team1'].' - '.$row['team2'].'<br />
'.$row['team3'].' - '.$row['team4'].';
</code>```

and so on. But sometimes the date or time changes, so I have to make the whole row again, because else it will still show the first match first, even though the other match will be played first. Let say Chelea - Man Utd is moved to the 20/11 at 18:00. Can I somehow just change the date and time in the row and make the matches rearrange on the front-end?

Sorry if it's a bit difficult to understand what I'm talking about :)

答:
First, I think your tables has not correctly formatted, you shouldn't have fields like field1, field2, field3... If you require that : you should be create another table :D Like that: Or you have a logical problem. I think an architecture like that is better addapted to your database :

```<code># table team
id  | name
1   | Chelsea
2   | Man Utd
3   | Arsenal
4   | Stoke
</code>```

If a team change this name, is more efficient, if value is once in other table.

```<code># table match
id  | local_team_id | external_team_id | dateTime             | week | score ^_^
1   | 1             | 2                | 2017-11-14 19:30:06  | 46   | 2-0
2   | 3             | 4                | 2017-11-15 18:30:21  | 46   | 2-0
</code>```

Also, if possible, never use the SELECT * FROM your_table is not effective, and very not good for performance. You must just return in your request the values you need in your PHP. Not more.

From your sample you can write:

```<code>"SELECT team1, team2, team3, team4 FROM table_name WHERE week='$week'"
</code>```

But, even with that, you can have a problem of SQL injection. You can fix it with PHP method, or with using PDO and prepare query. A sample of your request with PDO :

```<code>$query = "SELECT team1, team2, team3, team4 FROM table_name WHERE week= :week"
$dbh->prepare($query, , array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$dbh->execute([':week' => $week]);
</code>```

So, for answer to your question, you can order the result column, with define fields in your request :

```<code>SELECT first, second, third FROM table_name
</code>```

And you can order the rows results with the ORDER BY clause (see the doc here ) like that :

```<code>SELECT team1, team2, team3, team4, week FROM table_name ORDER_BY week DESC
</code>```

Hope I help you.

Title: Sort columns automatically

Body:
I have a database-table with some football-matches, 3 per week, and I wrote them in a table like this example:

week  |team1   |team2   |date1   |time1   |team3  |team4  |date2  |time2  |
46    |Chelsea |Man Utd |18/11   |13:30   |Arsenal|Stoke  |19/11  |18:00  |

Then I have this code to call them:

"SELECT * FROM table_name WHERE week = '$week'";

...where $week = Date('W');

echo $row['team1'].' - '.$row['team2'].'

'.$row['team3'].' - '.$row['team4'].';

and so on. But sometimes the date or time changes, so I have to make the whole row again, because else it will still show the first match first, even though the other match will be played first. Let say Chelea - Man Utd is moved to the 20/11 at 18:00. Can I somehow just change the date and time in the row and make the matches rearrange on the front-end?

Sorry if it's a bit difficult to understand what I'm talking about :)

Body:
First, I think your tables has not correctly formatted, you shouldn't have fields like field1, field2, field3... If you require that : you should be create another table :D Like that: Or you have a logical problem. I think an architecture like that is better addapted to your database :

# table team
id  | name
1   | Chelsea
2   | Man Utd
3   | Arsenal
4   | Stoke

If a team change this name, is more efficient, if value is once in other table.

# table match
id  | local_team_id | external_team_id | dateTime             | week | score ^_^
1   | 1             | 2                | 2017-11-14 19:30:06  | 46   | 2-0
2   | 3             | 4                | 2017-11-15 18:30:21  | 46   | 2-0

Also, if possible, never use the SELECT * FROM your_table is not effective, and very not good for performance. You must just return in your request the values you need in your PHP. Not more.

From your sample you can write:

"SELECT team1, team2, team3, team4 FROM table_name WHERE week='$week'"

But, even with that, you can have a problem of SQL injection. You can fix it with PHP method, or with using PDO and prepare query. A sample of your request with PDO :

$query = "SELECT team1, team2, team3, team4 FROM table_name WHERE week= :week"
$dbh->prepare($query, , array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$dbh->execute([':week' => $week]);

So, for answer to your question, you can order the result column, with define fields in your request :

SELECT first, second, third FROM table_name

And you can order the rows results with the ORDER BY clause (see the doc here ) like that :

SELECT team1, team2, team3, team4, week FROM table_name ORDER_BY week DESC

Hope I help you.


问:
chrome extension dynamically change icon (without clicking)
how can I make my chrome extension change icon (without clicking on it). I've got script that's checking if page has certain string and if it has I want my extension icon change from grey to colored one. </p>

答:
Updated Answer: For Manifest V3

Use chrome.action.setIcon({ path: "/example/path/image.png" }).

Source

Original Answer: For Manifest V2 and Under

The content script will need to send a message when it wants to set the icon e.g.

```<code>chrome.runtime.sendMessage({
    action: 'updateIcon',
    value: false
});
</code>```

Then in the background script:

```<code>chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "updateIcon") {
        if (msg.value) {
            chrome.browserAction.setIcon({path: "/assets/tick.png"});
        } else {
            chrome.browserAction.setIcon({path: "/assets/cross.png"});
        }
    }
});
</code>```

Body:
Updated Answer: For Manifest V3

Use chrome.action.setIcon({ path: "/example/path/image.png" }).

Source

Original Answer: For Manifest V2 and Under

The content script will need to send a message when it wants to set the icon e.g.

chrome.runtime.sendMessage({
    action: 'updateIcon',
    value: false
});

Then in the background script:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "updateIcon") {
        if (msg.value) {
            chrome.browserAction.setIcon({path: "/assets/tick.png"});
        } else {
            chrome.browserAction.setIcon({path: "/assets/cross.png"});
        }
    }
});

ContentLicense: CC BY-SA 4.0


问:
Change words order in a long string using regular expression
I have a long string in which I want to change words order.  I want to use regular expression as I have multiple elements to change and I want to learn at the same time.  Here is an example of my strings:

```<code>vec1 <- c("Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]",
     "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]",
     "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]",
     "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]")

vec1
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"
</code>```

I want it to become:

```<code>[1] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Self[Desktop Computer]"
[2] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Other HH Member[Tablet]"
[3] "Internet-Devices Used to Access Internet Past 30 Days -Made Available by Your Employer[Laptop Computer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"
</code>```

So I think the algorithm should work like this:

Find part of the string following the "Past 30 Days" and stop at the hyphen,

Copy this extracted string exactly before the last character of the main string,

Delete the extracted string from step 1 in the main string (but not what you just add).

For step 1, I've ask a similar question yesterday (Ignore part of a string when splitting using regular expression in R) and used it to find this regular expression (?<=Past 30 Days ).+(?![^-]) which works on regex101.com but not in R (doesn't stop at the hyphen):

```<code>reg1 <- regexec(pattern = "(?<=Past 30 Days ).+(?![^-])", vec1, perl=T)
ext1 <- unname(mapply(function(xx,yy) substr(xx, yy, yy+attr(yy,"match.length")), vec1, reg1))
ext1
[1] "[Desktop Computer-Owned by Self]"                  "[Tablet-Owned by Other HH Member]"
[3] "[Laptop Computer-Made Available by Your Employer]" ""
</code>```

As you can see, it doesn't stop at the hyphen.

And for the second step, I was thinking of something like this:

```<code>vec2 <- unname(mapply(gsub, ext1, vec1, MoreArgs = list(pattern="]")))
vec2
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self[Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member[Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer[Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)"
</code>```

Which does pretty much what I want except for removing the "]" in the last element of the vector and not adding the right string (because of problem 1).

Finally, I remove the initial part of the string:

```<code>unname(mapply(gsub, paste0(stringr::str_sub(ext1, end=-2),"["), vec2, MoreArgs = list(replacement="[", fixed=T)))
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)"
</code>```

This kind of work but I have the same 2 problems as in step 2.

My whole code seems pretty heavy and complicated.  Any better way of doing this?

Note:

I'm not looking for a super robust solution

I never have nested brackets

my strings always finish with brackets

答:
You may use

```<code>(Past 30 Days\s*)([^-]*)([^]]+)
</code>```

and replace with \1\3\2. See the regex demo.

Details

(Past 30 Days\s*) - Group 1 (referred to with \1 backreference from the replacement pattern):

Past 30 Days - a literal substring

\s* - 0+ whitespaces

([^-]*) - Group 2: zero or more chars other than -

([^]]+) - Group 3: one or more chars other than ].

See an R demo online:

```<code>vec1 <- c("Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]",
     "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]",
     "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]",
     "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]")
gsub("(Past 30 Days\\s*)([^-]*)([^]]+)", "\\1\\3\\2", vec1)
# [1] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Self[Desktop Computer]"
# [2] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Other HH Member[Tablet]"
# [3] "Internet-Devices Used to Access Internet Past 30 Days -Made Available by Your Employer[Laptop Computer]"
# [4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"
</code>```

Body:
I have a long string in which I want to change words order.  I want to use regular expression as I have multiple elements to change and I want to learn at the same time.  Here is an example of my strings:

vec1 <- c("Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]",
     "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]",
     "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]",
     "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]")

vec1
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"

I want it to become:

[1] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Self[Desktop Computer]"
[2] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Other HH Member[Tablet]"
[3] "Internet-Devices Used to Access Internet Past 30 Days -Made Available by Your Employer[Laptop Computer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"

So I think the algorithm should work like this:

Find part of the string following the "Past 30 Days" and stop at the hyphen,

Copy this extracted string exactly before the last character of the main string,

Delete the extracted string from step 1 in the main string (but not what you just add).

For step 1, I've ask a similar question yesterday (Ignore part of a string when splitting using regular expression in R) and used it to find this regular expression (?<=Past 30 Days ).+(?![^-]) which works on regex101.com but not in R (doesn't stop at the hyphen):

reg1 <- regexec(pattern = "(?<=Past 30 Days ).+(?![^-])", vec1, perl=T)
ext1 <- unname(mapply(function(xx,yy) substr(xx, yy, yy+attr(yy,"match.length")), vec1, reg1))
ext1
[1] "[Desktop Computer-Owned by Self]"                  "[Tablet-Owned by Other HH Member]"
[3] "[Laptop Computer-Made Available by Your Employer]" ""

As you can see, it doesn't stop at the hyphen.

And for the second step, I was thinking of something like this:

vec2 <- unname(mapply(gsub, ext1, vec1, MoreArgs = list(pattern="]")))
vec2
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self[Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member[Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer[Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)"

Which does pretty much what I want except for removing the "]" in the last element of the vector and not adding the right string (because of problem 1).

Finally, I remove the initial part of the string:

unname(mapply(gsub, paste0(stringr::str_sub(ext1, end=-2),"["), vec2, MoreArgs = list(replacement="[", fixed=T)))
[1] "Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]"
[2] "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]"
[3] "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]"
[4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)"

This kind of work but I have the same 2 problems as in step 2.

My whole code seems pretty heavy and complicated.  Any better way of doing this?

Note:

I'm not looking for a super robust solution

I never have nested brackets

my strings always finish with brackets

Body:
You may use

(Past 30 Days\s*)([^-]*)([^]]+)

and replace with \1\3\2. See the regex demo.

Details

(Past 30 Days\s*) - Group 1 (referred to with \1 backreference from the replacement pattern):

Past 30 Days - a literal substring

\s* - 0+ whitespaces

([^-]*) - Group 2: zero or more chars other than -

([^]]+) - Group 3: one or more chars other than ].

See an R demo online:

vec1 <- c("Internet-Devices Used to Access Internet Past 30 Days [Desktop Computer-Owned by Self]",
     "Internet-Devices Used to Access Internet Past 30 Days [Tablet-Owned by Other HH Member]",
     "Internet-Devices Used to Access Internet Past 30 Days [Laptop Computer-Made Available by Your Employer]",
     "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]")
gsub("(Past 30 Days\\s*)([^-]*)([^]]+)", "\\1\\3\\2", vec1)
# [1] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Self[Desktop Computer]"
# [2] "Internet-Devices Used to Access Internet Past 30 Days -Owned by Other HH Member[Tablet]"
# [3] "Internet-Devices Used to Access Internet Past 30 Days -Made Available by Your Employer[Laptop Computer]"
# [4] "Radio Stations-Listened to Past Week-Quebec City [FM-CFEL-102.1 (blvd 102.1)]"


问:
Structuring Database First model classes with MVVM in WPF App
I am following this course on integrating an MVVM architecture with an WPF app, but using code first. For my own app I am using database first, with only a
few tables.

This is my project structure, with the 3 layers, Model-View-ViewModel. In the course he creates two model classes, of course using code first in the model project, while the Data Access project handles migrations and the DbContext.

Now, when I use Database First, EF creates all the model classes for me, but the database context is included as well. My edmx is structured like this:

My question is what I need to place in which project? I'm aware that I have my view models in the UI project, which then use a data service to create a new context, but it seems I can do this all in the UI project.

答:
My question is what I need to place in which project?

The entity classes go in the model project and the DbContext belongs to the data access layer.

You should be able to move the Nolek.tt file to the model projecy by doing the following.

Open File Explorer (right-click on the solution in Visual Studio and choose the “Open Folder in File Explorer” option) and move the Nolek.tt file to the model project folder.

Back in Visual Studio, include the Nolek.tt file in the model project by clicking on the “Show All Files” icon at the top of the Solution Explorer and then right-click on the Nolek.tt file and choose the “Include In Project” option.

Delete the Nolek.tt file from the DAL project.

For the template in the model project to be able to find the model you then need to modify it to point to the correct EDMX path. You can do this by setting the inputFile variable in the Nolek.tt template file to point to an explicit path where to find the model:

```<code>const string inputFile = @"../NolekWPF.DataAccess/Nolek.edmx";
</code>```

Once you save the file, the entity classes should be generated in the model project.

Please refer to the following blog post for more information: https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/

Body:
My question is what I need to place in which project?

The entity classes go in the model project and the DbContext belongs to the data access layer.

You should be able to move the Nolek.tt file to the model projecy by doing the following.

Open File Explorer (right-click on the solution in Visual Studio and choose the “Open Folder in File Explorer” option) and move the Nolek.tt file to the model project folder.

Back in Visual Studio, include the Nolek.tt file in the model project by clicking on the “Show All Files” icon at the top of the Solution Explorer and then right-click on the Nolek.tt file and choose the “Include In Project” option.

Delete the Nolek.tt file from the DAL project.

For the template in the model project to be able to find the model you then need to modify it to point to the correct EDMX path. You can do this by setting the inputFile variable in the Nolek.tt template file to point to an explicit path where to find the model:

const string inputFile = @"../NolekWPF.DataAccess/Nolek.edmx";

Once you save the file, the entity classes should be generated in the model project.

Please refer to the following blog post for more information: https://blog.magnusmontin.net/2013/05/30/generic-dal-using-entity-framework/


问:
How do I add data to particular column in exisiting table?
How can I insert data to only one column in an existing table?

I dont want other column get disturbed or altered..

答:
I think you're looking for an update query:

```<code>UPDATE
  table_name
SET
  column = 'value';
</code>```

That will only "insert" data into a single column while leaving everything else undisturbed.

If you want to update from the results of another table, you can also do joins:

```<code>UPDATE
  table_name
    INNER JOIN source_table ON
      table_name.some_id = source_table.some_id
SET
  table_name.column = source_table.column;
</code>```

Hope that helps.  You might want to try clarifying the question with some more information.

Body:
I think you're looking for an update query:

UPDATE
  table_name
SET
  column = 'value';

That will only "insert" data into a single column while leaving everything else undisturbed.

If you want to update from the results of another table, you can also do joins:

UPDATE
  table_name
    INNER JOIN source_table ON
      table_name.some_id = source_table.some_id
SET
  table_name.column = source_table.column;

Hope that helps.  You might want to try clarifying the question with some more information.

ContentLicense: CC BY-SA 2.5


问:
Unable to use variable passed from C# into XSLT in a template match
I'm trying to pass in a variable / parameter to an XSLT stylesheet. The variable is entered by the user via a Windows Form.

The XSLT stylesheet is quite simple and it processes lots of XML documents to filter out unwanted data, but leave specific data which has been selected by the user.

The XSLT works perfectly well when I 'hard code' the variable into the template match (i.e. not trying to programatically pass it in) so the parameter is clearly not being passed to the XSLT prior to transformation.

XSLT:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method = "xml" indent="yes"/>
   <xsl:strip-space elements = "*" />

      <xsl:param name="applic"/>

        <xsl:template match = "@*|node()" >
          <xsl:copy>
          <xsl:apply-templates select = "@*|node()" />
         </xsl:copy>
        </xsl:template>

        <xsl:template match = "dmodule/content//*[applic/model[@*]/version[@version != '$applic']]" />
        <xsl:template match = "version[@version != '$applic']" />

        <xsl:template match = "dmodule/content//applic" />

 </xsl:stylesheet>
</code>```

This is how i'm passing the variable to the XSLT in C#

```<code> XsltArgumentList args = new XsltArgumentList();
 args.AddParam("applic", "", applicToSearch); //applicToSearch contains the user variable

 var myXslTrans = new XslCompiledTransform(true);
 myXslTrans.Load(stylesheet);

 using (StreamWriter sw = new StreamWriter(Path.Combine(outputFolder, fileNameNoExt + ".xml")))
  {
       myXslTrans.Transform(outputFolder + "\\temp.xml", args, sw);
  }
</code>```

As I say, clearly the variable / parameter isn't being passed successfully to the XSLT stylesheet.

Any idea why? I've exhausted Google and other posts.

答: You would need to use @version != $applic on the XSLT/XPath side. However, I think in XSLT 1 you can't use a variable in a match pattern so you would need to move such conditions into the template body with an xsl:if or xsl:choose/xsl:when.

Body:
I'm trying to pass in a variable / parameter to an XSLT stylesheet. The variable is entered by the user via a Windows Form.

The XSLT stylesheet is quite simple and it processes lots of XML documents to filter out unwanted data, but leave specific data which has been selected by the user.

The XSLT works perfectly well when I 'hard code' the variable into the template match (i.e. not trying to programatically pass it in) so the parameter is clearly not being passed to the XSLT prior to transformation.

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method = "xml" indent="yes"/>
   <xsl:strip-space elements = "*" />

      <xsl:param name="applic"/>

        <xsl:template match = "@*|node()" >
          <xsl:copy>
          <xsl:apply-templates select = "@*|node()" />
         </xsl:copy>
        </xsl:template>

        <xsl:template match = "dmodule/content//*[applic/model[@*]/version[@version != '$applic']]" />
        <xsl:template match = "version[@version != '$applic']" />

        <xsl:template match = "dmodule/content//applic" />

 </xsl:stylesheet>

This is how i'm passing the variable to the XSLT in C#

 XsltArgumentList args = new XsltArgumentList();
 args.AddParam("applic", "", applicToSearch); //applicToSearch contains the user variable

 var myXslTrans = new XslCompiledTransform(true);
 myXslTrans.Load(stylesheet);

 using (StreamWriter sw = new StreamWriter(Path.Combine(outputFolder, fileNameNoExt + ".xml")))
  {
       myXslTrans.Transform(outputFolder + "\\temp.xml", args, sw);
  }

As I say, clearly the variable / parameter isn't being passed successfully to the XSLT stylesheet.

Any idea why? I've exhausted Google and other posts.


问:
how to access to many webpages in casperjs
I'm a beginner in casperjs, I'm tryin to automatically access to a website and scrape some information, I start the url and then store  some links in a table called "links" and then I try to click on the first element(links[0]) in that table and finally test if the link that has the id("ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2")exists.

the problem is, i can't get any output, i guess it's because the program can't access to the link(links[0]) in the first place, that's why it can't find the id i'm looking for.
this is the code I wrote.

```<code> var url=''; //first link
 var casper = require('casper').create();
 var links;
 var lien;// second link
 function getLinks() {
 var links = document.querySelectorAll('td a');
 return Array.prototype.map.call(links, function (e) {
  return e.getAttribute('href')
 });
 }
 casper.start(url);
 casper.then(function () {
 links = this.evaluate(getLinks);
 });

 casper.then(function () {
 lien = links[0];
 });
 casper.thenOpen(lien , function(){
 if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
 this.echo('the heading exists');
 }
 else {console.log('does not exist');
 }
    });
 casper.run(function () {
 this.exit();
 });`
</code>```

this is the link I'm trying the find

Note that the versions o casperjs I'm using is 1.1.4

this is what shows the console

答:
In order for this to work you need to wrap it in test suite. At least that is how I did it. I am not up to date with casper and I don't know if anything changed in past year, but formerly issue was that you could not start casper without test suite in v1.

Please start following code in your terminal with following command

casperjs test filename.js

in your filename.js put the following code

```<code>var url = 'https://www.marchespublics.gov.ma/pmmp/';
var url2 = 'https://www.marchespublics.gov.ma/index.php5?page=entreprise.EntrepriseAdvancedSearch&AllCons&EnCours&domaineActivite=1.15';

casper.test.begin('Scraping start', 3, function(test) {
    casper.start(url, function() {
        this.test.pass('Opened 1st page');
    })
    .thenOpen(url2, function(){
        this.test.pass('Opened 2nd page')
    })
    .then(function() {
        if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
            this.test.pass('the heading exists');
        } else {
            this.test.fail('Does not exist');
        }
    })
    .run(function() {
        test.done();
    });
});
</code>```

for more details from casperjs in execution of the script try running it with additional parameters like this

casperjs test filename.js --verbose --log-level=debug

Hope that helps

EDIT 1:

This works as well without test suite just call this code

casperjs filename.js

```<code>var casper = require('casper').create();
var url = 'https://www.marchespublics.gov.ma/index.php5?page=entreprise.EntrepriseAdvancedSearch&AllCons&EnCours&domaineActivite=1.15';

casper
    .start(url, function() {
        this.echo('Opened page')
    })
    .then(function() {
        if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
            this.echo('the heading exists');
        } else {
            this.echo('Does not exist');
        }
    })
    .run();
</code>```

Body:
I'm a beginner in casperjs, I'm tryin to automatically access to a website and scrape some information, I start the url and then store  some links in a table called "links" and then I try to click on the first element(links[0]) in that table and finally test if the link that has the id("ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2")exists.

the problem is, i can't get any output, i guess it's because the program can't access to the link(links[0]) in the first place, that's why it can't find the id i'm looking for.
this is the code I wrote.

 var url=''; //first link
 var casper = require('casper').create();
 var links;
 var lien;// second link
 function getLinks() {
 var links = document.querySelectorAll('td a');
 return Array.prototype.map.call(links, function (e) {
  return e.getAttribute('href')
 });
 }
 casper.start(url);
 casper.then(function () {
 links = this.evaluate(getLinks);
 });

 casper.then(function () {
 lien = links[0];
 });
 casper.thenOpen(lien , function(){
 if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
 this.echo('the heading exists');
 }
 else {console.log('does not exist');
 }
    });
 casper.run(function () {
 this.exit();
 });`

this is the link I'm trying the find

Note that the versions o casperjs I'm using is 1.1.4

this is what shows the console

Body:
In order for this to work you need to wrap it in test suite. At least that is how I did it. I am not up to date with casper and I don't know if anything changed in past year, but formerly issue was that you could not start casper without test suite in v1.

Please start following code in your terminal with following command

casperjs test filename.js

in your filename.js put the following code

var url = 'https://www.marchespublics.gov.ma/pmmp/';
var url2 = 'https://www.marchespublics.gov.ma/index.php5?page=entreprise.EntrepriseAdvancedSearch&AllCons&EnCours&domaineActivite=1.15';

casper.test.begin('Scraping start', 3, function(test) {
    casper.start(url, function() {
        this.test.pass('Opened 1st page');
    })
    .thenOpen(url2, function(){
        this.test.pass('Opened 2nd page')
    })
    .then(function() {
        if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
            this.test.pass('the heading exists');
        } else {
            this.test.fail('Does not exist');
        }
    })
    .run(function() {
        test.done();
    });
});

for more details from casperjs in execution of the script try running it with additional parameters like this

casperjs test filename.js --verbose --log-level=debug

Hope that helps

EDIT 1:

This works as well without test suite just call this code

casperjs filename.js

var casper = require('casper').create();
var url = 'https://www.marchespublics.gov.ma/index.php5?page=entreprise.EntrepriseAdvancedSearch&AllCons&EnCours&domaineActivite=1.15';

casper
    .start(url, function() {
        this.echo('Opened page')
    })
    .then(function() {
        if (this.exists('a[id="ctl0_CONTENU_PAGE_resultSearch_PagerTop_ctl2"]')) {
            this.echo('the heading exists');
        } else {
            this.echo('Does not exist');
        }
    })
    .run();


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答: Try to download and install this kotlin plugin for android studio 3.1 </p>

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


问:
Copying Character array into char array
Hi I want to fast copy array of Characters to array of chars I can write a method that copies Character array into char array, by converting every Charater in array to char but is there any ready method which is faster just as Arrays.copyOf for two arrays of same type?

答:
```<code>    char[] myCharArray = Arrays.stream(myCharacterArray)
            .map(ch -> ch.toString())
            .collect(Collectors.joining())
            .toCharArray();
</code>```

It was fast to write. Whether it will execute fast? Unless you have a very big array or do this conversion often, you shouldn‘t need to care.

Title: Copying Character array into char array

Body:
    char[] myCharArray = Arrays.stream(myCharacterArray)
            .map(ch -> ch.toString())
            .collect(Collectors.joining())
            .toCharArray();

It was fast to write. Whether it will execute fast? Unless you have a very big array or do this conversion often, you shouldn‘t need to care.


问:
Authentification NodeJS Sequelize Express
I'm trying implement NodeJS authentification with express, sequelize, and mysql, but i'm blocked. I get login and password values by webservice. I want to match them with database value :

```<code>app.get('/login', function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

    if (!req.query.login || !req.query.password) {
        res.send('login failed');
//Here my code is wrong !
I try to compare login and password values with database login and passwword values
            } else if (req.query.login && req.query.password == UsrPerson.findOne({ where: whereUser })) {
                console.log("auth ok")
                req.session.user = "amy";
                req.session.admin = true;
                res.send("login success!");
            } else {
                console.log("ERROR")
                res.send(err)
            }
        });
</code>```

How can I do that ? Thank you

答:
```<code>app.get('/login', function (req, res, err) {
  const { login, password } = req.query;

  UsrPerson
    .findOne({
      where: {
        login: login,
        password: password
      }
    })
    .then((foundUser) => {
      if(!foundUser){
        res.send('login failed');
      } else {
        console.log("auth ok");
        req.session.user = "amy";
        req.session.admin = true;
        res.send("login success!");
      }
    })
    .catch((err) => {
      console.log('ERROR');
      res.send(err);
    });
});
</code>```

You want to compare if the user with the given username and password combination exists.

And seems like you are storing the password without any encryption, in plain text. This is not secure at all. You have to use a library like bcrypt and only store the encrypted password in your database

Body:
I'm trying implement NodeJS authentification with express, sequelize, and mysql, but i'm blocked. I get login and password values by webservice. I want to match them with database value :

app.get('/login', function (req, res, err) {
    var whereUser = {
        login: req.query.login,
        password: req.query.password
    }

    if (!req.query.login || !req.query.password) {
        res.send('login failed');
//Here my code is wrong !
I try to compare login and password values with database login and passwword values
            } else if (req.query.login && req.query.password == UsrPerson.findOne({ where: whereUser })) {
                console.log("auth ok")
                req.session.user = "amy";
                req.session.admin = true;
                res.send("login success!");
            } else {
                console.log("ERROR")
                res.send(err)
            }
        });

How can I do that ? Thank you

Body:
app.get('/login', function (req, res, err) {
  const { login, password } = req.query;

  UsrPerson
    .findOne({
      where: {
        login: login,
        password: password
      }
    })
    .then((foundUser) => {
      if(!foundUser){
        res.send('login failed');
      } else {
        console.log("auth ok");
        req.session.user = "amy";
        req.session.admin = true;
        res.send("login success!");
      }
    })
    .catch((err) => {
      console.log('ERROR');
      res.send(err);
    });
});

You want to compare if the user with the given username and password combination exists.

And seems like you are storing the password without any encryption, in plain text. This is not secure at all. You have to use a library like bcrypt and only store the encrypted password in your database


问:
NoReverseMatch at /account/profile
I'm getting the following error message when attempting to run a JS function and Ajax click call on a button press.

NoReverseMatch at /account/profile/
Reverse for '' not found. '' is not a valid view function or pattern name.

I know it's because the url, but i'm not sure what is incorrect with my url.

I also get the commented error message about a missing semicolon in my code when using a linting tool, but adding a comma seems to break the code.  If I change my url to just '/requestaccess/' i'll see the post in the console, but that view is not valid.

in the JS my var is defined as

```<code>                  var url = '{% url requestaccess %}';
</code>```

in the ajax i'm attempting to call the url using:

```<code>                  $.ajax({
                      url: url,
                      data: JSON.stringify({ report_id: SelectedItems }),
                      dataType: 'json',
                      type: 'post',
                      success: function (data) {
</code>```

The URL.py is setup as:

```<code>   url(r'^requestaccess/$', views.requestaccess, name='requestaccess')
</code>```

My entire block of code is:

```<code>                  <script>
$(document).ready(function () {
                      var SelectedItems = [];
                      $('.checkbox').click(function () {
                          var SelectedItems = $(this).val();
                          var index = SelectedItems.indexOf(SelectedItems);
                          var url = '{% url requestaccess %}';
                          if (index == -1)
                          {
                            SelectedItems.push(SelectedItems);
                          }        else {
                            SelectedItems.splice(index, 1);
                          }
                        });

                      $('#submit-button').click(function (event) {
                          event.preventDefault();
                          $.ajax({
                              url: url,
                              data: JSON.stringify({ report_id: SelectedItems }),
                              dataType: 'json',
                              type: 'post',
                              success: function (data) {
                              }  //missing comma before closing curly brace
                            });
                        });
                    });
                  </script>
</code>```

答:
when using the URL tag put two quotes around the url name like this

```<code>var url = "{% url 'requestaccess' %}";
</code>```

Done!

Title: NoReverseMatch at /account/profile

Body:
I'm getting the following error message when attempting to run a JS function and Ajax click call on a button press.

NoReverseMatch at /account/profile/
Reverse for '' not found. '' is not a valid view function or pattern name.

I know it's because the url, but i'm not sure what is incorrect with my url.

I also get the commented error message about a missing semicolon in my code when using a linting tool, but adding a comma seems to break the code.  If I change my url to just '/requestaccess/' i'll see the post in the console, but that view is not valid.

in the JS my var is defined as

                  var url = '{% url requestaccess %}';

in the ajax i'm attempting to call the url using:

                  $.ajax({
                      url: url,
                      data: JSON.stringify({ report_id: SelectedItems }),
                      dataType: 'json',
                      type: 'post',
                      success: function (data) {

The URL.py is setup as:

   url(r'^requestaccess/$', views.requestaccess, name='requestaccess')

My entire block of code is:

Body:
when using the URL tag put two quotes around the url name like this

var url = "{% url 'requestaccess' %}";

Done!


问:
How can I send trade offer
Actually I am working on Steam trade offer functionality, in which I am getting a problem.  I have downloaded the Steam class library and implement it in Codeigniter. I am following the setup guide from https://github.com/halipso/php-steam-tradeoffers#setupsessionid-cookies this. Actually I don't know about session id and cookie:

```<code>$steam->setup('sessionID', 'cookies');
</code>```

What will be sessionID and cookies?

I have read about it but did not get any solution. How can I get and implement it in my code?

答:
Well if this is on Laravel you can send _token which call as csrf_field by them.

In CI you can do like this. (csrf generate unique session id)

Path - application/config/config.php

```<code>$config['csrf_protection'] = TRUE;
</code>```

In Login form, you can add this or in page initialize you can add this

```<code>$csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
);

<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />
</code>```

So when saving you can add this to the session. BTW this token can use for cookie as well.

Read this Cross-site request forgery (CSRF)

Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter

Source Codeigniter documentation

If it's not in a login page, then

Its better to se this false,(due to this Tokens may be either regenerated on every submission (default))

```<code>$config['csrf_regenerate'] = FALSE;
</code>```

Title: How can I send trade offer

Body:
Actually I am working on Steam trade offer functionality, in which I am getting a problem.  I have downloaded the Steam class library and implement it in Codeigniter. I am following the setup guide from https://github.com/halipso/php-steam-tradeoffers#setupsessionid-cookies this. Actually I don't know about session id and cookie:

$steam->setup('sessionID', 'cookies');

What will be sessionID and cookies?

I have read about it but did not get any solution. How can I get and implement it in my code?

Body:
Well if this is on Laravel you can send _token which call as csrf_field by them.

In CI you can do like this. (csrf generate unique session id)

Path - application/config/config.php

$config['csrf_protection'] = TRUE;

In Login form, you can add this or in page initialize you can add this

$csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
);

<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />

So when saving you can add this to the session. BTW this token can use for cookie as well.

Read this Cross-site request forgery (CSRF)

Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter

Source Codeigniter documentation

If it's not in a login page, then

Its better to se this false,(due to this Tokens may be either regenerated on every submission (default))

$config['csrf_regenerate'] = FALSE;


问:
extract name from specific occurence of a pattern in a large file
I have a FASTA file which is basically a text file for depicting biological sequence data (https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp) having more than 10,000 FASTA sequences (starting with >). The beginning of the file looks like:

```<code>>Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
>Gene B
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
AAAGTAAATATTATAAAAGCCCTC
>Gene C
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
>Gene D
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
</code>```

and so on for approximately 10,000 genes.
I want to:

find which of the genes contain a specific pattern (CTTTGTA)

how many times is this pattern present in that gene?

export the list of gene names containing the pattern with the frequency of the pattern.

Any solution in Bash or Python (or R) is appreciated.

P.S. What I have tried thus far but didn't work: extracting genes with their sequences into separate files and then grep for the pattern in separate files. I could, however, not generate these separate files. I used

```<code>grep '^>' file.txt > new_file.txt
</code>```

but the output I get is a single file containing all the gene names only.

答:
```<code>sequences = open('fastafile.txt').read().split('>')  # Creates a list of sequences.

needle = 'CTTTGTA'

occurrences = {}

for sequence in sequences:
   occ = sequence.count(needle)  # Returns the number of times the substring occurs in the string sequence.
   if occ:  # If greater than 0, create an entry in our dictionary. The sequence being the key and the count the value.
      occurrences[sequence] = occ

output = []

sorted_occurrences = sorted(occurrences.items(), key=operator.itemgetter(1))  # Sort the dictionary by length, so sequences with the highest occurrence of the needle appear at the top.

for seq, occ_count in sorted_occurrences.iteritems():
    gene_name, sequence = seq.split('\n')
    formatted_line = '{gene_name} - {occ_count}'.format(gene_name=gene_name, occ_count=str(occ_count))  # Format the lines the way you want.
    output.append(formatted_line)

with open('occurences.txt') as o_f:
    o_f.write('\n'.join(output))
</code>```

Body:
I have a FASTA file which is basically a text file for depicting biological sequence data (https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=BlastHelp) having more than 10,000 FASTA sequences (starting with >). The beginning of the file looks like:

>Gene A
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATT
>Gene B
GAACTACACAAACGTAAAATGTAAAACAAAGGTATAAATTCCAGAAGTTGGACAGACATATATAGACAGCACATATATTA
TCTTTATTTTTTTATGTATGATAACATTAAATATAACGTTCAACAATTACACCGTTAGCAGTGTGAGCAAAAACGATTAA
AAAGTAAATATTATAAAAGCCCTC
>Gene C
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT
>Gene D
AACAACAAATTGCCATCTACCCGTTTGAATCCTGTAATAATAACTTGCCCAGATTTGCTGCAGCATACTCCTAGAGTTGG
GCTGGGTGGCCCACACAAGCGATAATAACATTTAACAATTGTTTGATATATGTACTTTTTTTTAAGTTTTTTTCTCCTCG
TACTTGCCTTCCAAAAACTCGTTAGCTTTGTACACATACGCCTTTAATTAAAATACTGATAGATGCGTACCACTTACGTC
ATTAGAAAAAGTCACCAAAAGGAAAAATATGGACGACACAAGAACGAGGAGATCTAAGCCACTCGTAGACCACTAAGCAC
AAAATACCCGAAAAATATAACTGATATGATTGCCAACTACCCTGCGACTATGTAAACCCAACCTTCCCCCCTCCTTTACC
CTCTTATTCAAATCGACGCGTGTGTAGAAGATACACTTATTATATTTTTTTTCTGAGATACAATTATAAACACAAAAACG
ACTTTTAACTATATATTAAATAAAAACAAAAGGAAAAACATAATAATTT

and so on for approximately 10,000 genes.
I want to:

find which of the genes contain a specific pattern (CTTTGTA)

how many times is this pattern present in that gene?

export the list of gene names containing the pattern with the frequency of the pattern.

Any solution in Bash or Python (or R) is appreciated.

P.S. What I have tried thus far but didn't work: extracting genes with their sequences into separate files and then grep for the pattern in separate files. I could, however, not generate these separate files. I used

grep '^>' file.txt > new_file.txt

but the output I get is a single file containing all the gene names only.


答:
Your problem right now isn't the way to get Days (Although due to leap seconds, days and confusing times, that's a problem that could happen, see: How do I get the number of days between two dates in JavaScript?).

Your problem is that you're expecting different behaviour out of the Date constructor.

The Date constructor is using 0 indexed months, as such

```<code>var firstDate = new Date(2017,11,30); // 30th of december of 2017
var secondDate = new Date(2017,12,1); // 1st of January of 2018
// Second date is the 1st of january because it rolls over.

new Date(2016,0,1) // the 1st of January of 2016.
</code>```

refer to the 30th of december and the 1st of January of 2018, hence the answer says there's the 31th and the 1st between them, hence 2 days.

Title: Counting days between two dates Y/m/d returns wrong number

Body:
I'm trying to count the days between 2 dates. It goes well if both dates are in the same month but not if they are in different.
Here is an example where it returns the correct number(1 day):

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,29);
var secondDate = new Date(2017,11,30);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

Here is another example. In this case counting the days between last day of november and the 1st day of december, that should be 1 but returns 2

var oneDay = 24*60*60*1000;
var firstDate = new Date(2017,11,30);
var secondDate = new Date(2017,12,1);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
console.log(diffDays);

I have observed that it returns wrong number if the months are different and if one or both months are conformed by less than 31 days, it adds the number of days missing from the month(s) that have less that 31, in this case 1 because november has 30 days and december 31, 1 + 1(missing days) = 2.
Any Idea of how to get it right is very welcomed.

Body:
Your problem right now isn't the way to get Days (Although due to leap seconds, days and confusing times, that's a problem that could happen, see: How do I get the number of days between two dates in JavaScript?).

Your problem is that you're expecting different behaviour out of the Date constructor.

The Date constructor is using 0 indexed months, as such

var firstDate = new Date(2017,11,30); // 30th of december of 2017
var secondDate = new Date(2017,12,1); // 1st of January of 2018
// Second date is the 1st of january because it rolls over.

new Date(2016,0,1) // the 1st of January of 2016.

refer to the 30th of december and the 1st of January of 2018, hence the answer says there's the 31th and the 1st between them, hence 2 days.


问:
Baffling Sudden Error on loading data table
I'm using VB.net and WPF 4, as well as an SQL database.

I have been using this EXACT code successfully for several days now, with absolutely no problems whatsoever. However, now, suddenly, it is throwing the weirdest exception...

```<code>Public Class ROSTER
   Dim table_adapter As New AGENT_ROSTERTableAdapters.AGENTROSTERTableAdapter
   Dim roster_table As New AGENT_ROSTER.AGENT_ROSTERDataTable
...
</code>```

I have not deleted anything relating to this, and I can still do things similar to this, but I cannot, for the life of me, figure out why I am getting the following error:

XamlParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '106'.

On detail, every field contains the following:

{Cannot evaluate expression because we are stopped in a place where garbage collection is impossible, possibly because the code of the current method may be optimized.}

Why is this doing this, and what can I do to fix it??

答: I figured it out! This particular error is caused by my debugger having a bug in itself. To fix it, I will have to reinstall Visual Studio Express 2010, etc. Meanwhile, I have another computer I can work on my project on.</p>

Body:
I'm using VB.net and WPF 4, as well as an SQL database.

I have been using this EXACT code successfully for several days now, with absolutely no problems whatsoever. However, now, suddenly, it is throwing the weirdest exception...

Public Class ROSTER
   Dim table_adapter As New AGENT_ROSTERTableAdapters.AGENTROSTERTableAdapter
   Dim roster_table As New AGENT_ROSTER.AGENT_ROSTERDataTable
...

I have not deleted anything relating to this, and I can still do things similar to this, but I cannot, for the life of me, figure out why I am getting the following error:

XamlParseException occured
  'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '4' and line position '106'.

On detail, every field contains the following:

{Cannot evaluate expression because we are stopped in a place where garbage collection is impossible, possibly because the code of the current method may be optimized.}

Why is this doing this, and what can I do to fix it??


问:
Yii2 overidden fields()
I have overridden the fields function like so in models/CallerIdentity.php.

```<code>public function fields()
{
  $fields = parent::fields();
  $fields[] = 'ehadata';

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

CallerIdentity has this relation...

```<code>public function getEhadata()
{
  return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}
</code>```

Controller class is NumbersController. So now if I fire off GET request to api.dev/v1/numbers the response is like so, which is what I was aiming for.

```<code> {
    "cidref": 411,
    "custref": 178,
    "caller_id": "978378478",
    "expiry": "2021-06-27",
    "conf_call": "n",
    "type": "F",
    "redirect": null,
    "destination": "help@help.com",
    "status": 1,
    "start_date": "2010-09-17",
    "last_polled": "2012-12-07 08:30:02",
    "ehadata": [
        {
            "status": 0,
            "name": "Blah ",
            "bussuffix": "Ltd",
            "premesis": "Blah House",
            "thoroughfare": "Blah Road",
            "locality": "Manchester",
            "postcode": "T56 T4G"
        }
    ]
},
</code>```

Come to writing tests for the endpoint and I cannot access any of the ehadata fields.

I can do:

```<code>$I->seeResponseJsonMatchesJsonPath('$[0].ehadata');
</code>```

va_dump($fields) output

```<code>array (size=12)
'cidref' => string 'cidref' (length=6)
'custref' => string 'custref' (length=7)
'caller_id' => string 'caller_id' (length=9)
'expiry' => string 'expiry' (length=6)
'conf_call' => string 'conf_call' (length=9)
'type' => string 'type' (length=4)
'redirect' => string 'redirect' (length=8)
'destination' => string 'destination' (length=11)
'status' => string 'status' (length=6)
'start_date' => string 'start_date' (length=10)
'last_polled' => string 'last_polled' (length=11)
1 => string 'ehadata' (length=7)
</code>```

To check that the array is there but I can't check any of the individual fields, no matter what I try. This made me think about when I come to write the update function, how can I access/manipulate the fields? Has anyone got any ideas?

Any help would be massively appreciated.

答:
In general, if you override fields() as:

```<code>public function fields()
{
  $fields = parent::fields();
  $fields['ehadata'] = 'ehadata';

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

Then accessing the fields will be easy, through looping through $model->ehadata for example, since $model->ehadata is an array of objects

example:

```<code>foreach($model->ehadata as $temp)
{
   $temp->status = 2;
}
</code>```

Title: Yii2 overidden fields()

Body:
I have overridden the fields function like so in models/CallerIdentity.php.

public function fields()
{
  $fields = parent::fields();
  $fields[] = 'ehadata';

 return $fields;
}

CallerIdentity has this relation...

public function getEhadata()
{
  return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}

Controller class is NumbersController. So now if I fire off GET request to api.dev/v1/numbers the response is like so, which is what I was aiming for.

 {
    "cidref": 411,
    "custref": 178,
    "caller_id": "978378478",
    "expiry": "2021-06-27",
    "conf_call": "n",
    "type": "F",
    "redirect": null,
    "destination": "help@help.com",
    "status": 1,
    "start_date": "2010-09-17",
    "last_polled": "2012-12-07 08:30:02",
    "ehadata": [
        {
            "status": 0,
            "name": "Blah ",
            "bussuffix": "Ltd",
            "premesis": "Blah House",
            "thoroughfare": "Blah Road",
            "locality": "Manchester",
            "postcode": "T56 T4G"
        }
    ]
},

Come to writing tests for the endpoint and I cannot access any of the ehadata fields.

I can do:

$I->seeResponseJsonMatchesJsonPath('$[0].ehadata');

va_dump($fields) output

array (size=12)
'cidref' => string 'cidref' (length=6)
'custref' => string 'custref' (length=7)
'caller_id' => string 'caller_id' (length=9)
'expiry' => string 'expiry' (length=6)
'conf_call' => string 'conf_call' (length=9)
'type' => string 'type' (length=4)
'redirect' => string 'redirect' (length=8)
'destination' => string 'destination' (length=11)
'status' => string 'status' (length=6)
'start_date' => string 'start_date' (length=10)
'last_polled' => string 'last_polled' (length=11)
1 => string 'ehadata' (length=7)

To check that the array is there but I can't check any of the individual fields, no matter what I try. This made me think about when I come to write the update function, how can I access/manipulate the fields? Has anyone got any ideas?

Any help would be massively appreciated.

Body:
In general, if you override fields() as:

public function fields()
{
  $fields = parent::fields();
  $fields['ehadata'] = 'ehadata';

 return $fields;
}

Then accessing the fields will be easy, through looping through $model->ehadata for example, since $model->ehadata is an array of objects

example:

foreach($model->ehadata as $temp)
{
   $temp->status = 2;
}


问:
Hide New Sheet tab
How can I get rid of the last workbook tab that allows a user to add a new sheet in my Excel Viewer control?

I have found the following code to hide the button in the above image:

```<code>ExcelViewer1.Application.CommandBars["Workbook tabs"]._
              Controls["Sheet List"].Visible = false;
</code>```

but it throws a COM Exception:

"Error HRESULT E_FAIL has been returned from a call to a com component".

The same command works for other commandbars like Ply, Cell.

答:
Sample code to hide the tab bar (at bottom) of excel through C#...

```<code>object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application appExcel = new
Microsoft.Office.Interop.Excel.Application();
appExcel.Visible = false;
Microsoft.Office.Interop.Excel.Workbook workbook = appExcel.Workbooks.Add(misValue);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
workbook.SaveAs(Environment.CurrentDirectory + @"\a.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
</code>```

appExcel.ActiveWindow.DisplayWorkbookTabs = false;

```<code>appExcel.Workbooks.Close();
appExcel.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
</code>```

Title: Hide New Sheet tab

Body:
How can I get rid of the last workbook tab that allows a user to add a new sheet in my Excel Viewer control?

I have found the following code to hide the button in the above image:

ExcelViewer1.Application.CommandBars["Workbook tabs"]._
              Controls["Sheet List"].Visible = false;

but it throws a COM Exception:

"Error HRESULT E_FAIL has been returned from a call to a com component".

The same command works for other commandbars like Ply, Cell.

Body:
Sample code to hide the tab bar (at bottom) of excel through C#...

object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application appExcel = new
Microsoft.Office.Interop.Excel.Application();
appExcel.Visible = false;
Microsoft.Office.Interop.Excel.Workbook workbook = appExcel.Workbooks.Add(misValue);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
workbook.SaveAs(Environment.CurrentDirectory + @"\a.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

appExcel.ActiveWindow.DisplayWorkbookTabs = false;

appExcel.Workbooks.Close();
appExcel.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);


问:
didUpdateUserLocation not called when view for userLocation is custom
I have an MKMapView that's supposed to track the user's location using a custom view (not the blue dot). In order to substitute this view for the blue dot, I return it thusly:

```<code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if (annotation == [mapView userLocation])
    {
        return userLocationView;
    }
}
</code>```

To initialize tracking, I call

```<code>[mapView setShowsUserLocation: YES];
[mapView setUserTrackingMode: MKUserTrackingModeFollow animated: NO];
[mapView setDelegate: self];
</code>```

As would be expected, -mapView:didUpdateUserLocation: gets called once when the app loads. Unfortunately, it's never called again unless I change -mapView:viewForAnnotation: to have the following implementation:

```<code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if (annotation == [mapView userLocation])
    {
        return nil;
    }
}
</code>```

With these changes, the map loads the blue dot as the indicator of the user's location, and -mapView:didUpdateUserLocation: gets called frequently, as would be expected.

Is there some sort of mutual exclusivity for tracking users' locations and have a custom user location view? How can I make both happen?

Source

This project demonstrates this issue. https://dl.dropbox.com/u/2338382/MapKitFuckery.zip

Bug

This is most likely a bug, which I've filed as a radar. In the interim, the accepted answer should prove sufficient. However, it bears noting that I had to give up entirely on [mapView userLocation] and [mapView showsUserLocation], in favor of simply a custom annotation and the CLLocationManager.

答:
An old question that I would like to answer my own way. I was having an issue somewhat similar. I just needed to make a web service call, passing the user location as a GET parameter, when my MapView's ViewController/Screen was loaded and user location retrieved by the mapView. It made sense then to call the web service within the delegate method didUpdateUserLocation. I didn't notice the wrong behaviour first because things seemed to work properly but then for some reasons sometimes upon opening the mapView screen, the user blue dot would show but the map would not "zoom in" and neither didUpdateUserLocation was called nor my inner web service call obviously. After a few seconds of staring at the screen, the map would "zoom in" and the didUpdateUserLocation/web service was called. Some small glitch I thought, not a big deal. Now my detail-oriented developer's mind was still frustrated and after a few weeks of thinking this over, I decided to take action on this. Stackoverflow didn't give me the answer straight away but pointed me towards the right direction nonetheless. And here was the culprit: Sequence of calls! Maddening but made total sense once I figured things out. I knew that in order to see the blue dot and get the user location I had to tell the mapView to do so. So being an Interface Builder lover, I set things up properly for my mapView in IB, that is I checked the box: "User Location", easy. Then carefully reading the mapView documentation I realised that my ViewController needed to conform to MKMapViewDelegate, done deal. As I said, things seemed to work ok, the blue dot would show right away but sometimes the "zoom in" of the map would take a few seconds... well my iPhone is already 3 years old, things are getting slow, I'd deal with the sluggishness... Then I read this stack overflow post (https://stackoverflow.com/a/37407955) and things became clear. In my case, since using IB, here was the sequence of calls:

User Location checkbox checked in IB

In viewDidLoad, call: mapView.delegate = self

Whereas, here is how the sequence of calls should have been:

User Location checkbox NOT checked in IB (This is important)

mapView.delegate = self

mapView.showsUserLocation = true

And this changes EVERYTHING. Instead of having the mapView zooming in sometimes right away and sometimes after a few seconds, the mapView now zooms in right away when the screen opens, and the didUpdateUserLocation/web service IS called.

Now a little more on the why, it still "sometimes" worked. This is simply due to the fact that the location of my iPhone was sometimes updated right after the map screen was loaded and sometimes not :-). I have to say that besides the stackoverflow post I mentioned above, what helped me too was testing my app in the Simulator since I needed to use a gpx file with obviously static location coordinate, the non predictable behaviour I described was then systematic.

So as much as I love Interface Builder, I might have to reconsider how unconditional that love is.

PS: I know this post is old and my answer not entirely related to the issue @Patrick Perini had but I wish it helps others and that it might answer @Patrick Perini's conclusion regarding the fact that a Bug was at fault when it's not. Thanks for reading this blog post :-)

Body:
I have an MKMapView that's supposed to track the user's location using a custom view (not the blue dot). In order to substitute this view for the blue dot, I return it thusly:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if (annotation == [mapView userLocation])
    {
        return userLocationView;
    }
}

To initialize tracking, I call

[mapView setShowsUserLocation: YES];
[mapView setUserTrackingMode: MKUserTrackingModeFollow animated: NO];
[mapView setDelegate: self];

As would be expected, -mapView:didUpdateUserLocation: gets called once when the app loads. Unfortunately, it's never called again unless I change -mapView:viewForAnnotation: to have the following implementation:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if (annotation == [mapView userLocation])
    {
        return nil;
    }
}

With these changes, the map loads the blue dot as the indicator of the user's location, and -mapView:didUpdateUserLocation: gets called frequently, as would be expected.

Is there some sort of mutual exclusivity for tracking users' locations and have a custom user location view? How can I make both happen?

Source

This project demonstrates this issue. https://dl.dropbox.com/u/2338382/MapKitFuckery.zip

Bug

This is most likely a bug, which I've filed as a radar. In the interim, the accepted answer should prove sufficient. However, it bears noting that I had to give up entirely on [mapView userLocation] and [mapView showsUserLocation], in favor of simply a custom annotation and the CLLocationManager.


问:
Processes accessing a Shared Memory segment returning different values
I'm new to the IPCS concept,i want to achieve that one process creates and initializes a shared memory and then calls another process which attaches to the same shared memory segment and prints the data in the shared memory.
However i'm unable to achieve it:

AlgoCommon.h

```<code>struct sub_algo_shm
{
int time;
int pno;
};
struct AlgoShm
{
int head;
int tail;
char fFlag;
struct sub_algo_shm algoshm;
};
</code>```

AlgoThrottle.c

```<code>#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
        {
                int shmid ;
                struct timeval CurTime;
                struct timespec nTime;
                struct AlgoShm *shmaddr,*ptr;

                ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
                //Creating Shared Memory
                if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
                {
                        perror("shmget:error");
                }
                else
                {
                        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                        //Attaching to Shared Memory
                        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
                        if(shmaddr < 0)
                        {
                                perror(" shmat :error");
                        }
                        else
                        {
                                printf(" SHM Segment attached at [%x] ",shmaddr);
                        }
                        //Loading/Initializing Data Blocks in SHM
                        clock_gettime(CLOCK_REALTIME,&nTime);
                        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                        ptr->head = 5;
                        ptr->tail = 3;
                        ptr->fFlag = '0';
                        ptr->algoshm.time = 0;
                        ptr->algoshm.pno = 1;
                        //memcpy(shmaddr,&ptr,sizeof(ptr));
                        printf(" AlgoThrottle|ptr->head [%d] ",ptr->head);
                //      sleep(1);
                        system("./AlgoRead");

                }

        return 0;
        }
</code>```

AlgoRead.c

```<code>#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
    {

    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    //memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

    return 0;
    }
</code>```

This is my output:

```<code>Shm created key=[111119]
 Segment Id [1179615678]  SHM Segment attached at [4a6b4000]  Time in N secs[114594083]
 AlgoRead|SHM Created shmid [1179615678]  AlgoRead|Attached to Segment at Address[624cb000]
  AlgoRead|ptr1->head [36810768] ptr1->tail [0] ptr1->fFlag[▒]
   AlgoThrottle|ptr->head [5]
</code>```

Also,system call's output is showing first then the printf statement even after i used a sleep(1) before invoking system()

答:
Please see your mistakes below
why are you allocating 10 times of the structure?

correct line

```<code> ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
</code>```

to:-

```<code>ptr = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));
</code>```

Do the above changes at both the c files

Now in memcpy why are you providing the address of a pointer ptr like &ptr? Just remove the &. This is not a object hence you just need to provide the pointer ptr. Correct it like below

```<code>memcpy(shmaddr,ptr,sizeof(ptr));
</code>```

Instead of memcpy better use like below.

```<code>shmaddr->head = ptr->head;
shmaddr->tail = ptr->tail;
shmaddr->fFlag=ptr->fFlag;
</code>```

I have re-write you code below. Try with that. Better correct your own code as per my advice.

AlgoThrottle.c

```<code>int main()
{
    int shmid ;
    struct timeval CurTime;
    struct timespec nTime;
    struct AlgoShm *shmaddr,*ptr;

    ptr = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));
    //Creating Shared Memory
    if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
    {
        perror("shmget:error");
    }
    else
    {
        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
        //Attaching to Shared Memory
        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
        if(shmaddr < 0)
        {
                perror(" shmat :error");
        }
        else
        {
                printf(" SHM Segment attached at [%x] ",shmaddr);
        }
        //Loading/Initializing Data Blocks in SHM
        clock_gettime(CLOCK_REALTIME,&nTime);
        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
        ptr->head = 5;
        ptr->tail = 3;
        ptr->fFlag = '0';
        ptr->algoshm.time = 0;
        ptr->algoshm.pno = 1;
        //memcpy(shmaddr,ptr,sizeof(ptr));
        shmaddr->head = ptr->head;
        shmaddr->tail = ptr->tail;
        shmaddr->fFlag=ptr->fFlag;
        printf(" AlgoThrottle|ptr->head [%d] \n",ptr->head);
        //sleep(1);
        system("./AlgoRead");

    }

    return 0;
}
</code>```

AlgoRead.c

int main()
    {

```<code>    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

return 0;
}
</code>```

Body:
I'm new to the IPCS concept,i want to achieve that one process creates and initializes a shared memory and then calls another process which attaches to the same shared memory segment and prints the data in the shared memory.
However i'm unable to achieve it:

AlgoCommon.h

struct sub_algo_shm
{
int time;
int pno;
};
struct AlgoShm
{
int head;
int tail;
char fFlag;
struct sub_algo_shm algoshm;
};

AlgoThrottle.c

#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
        {
                int shmid ;
                struct timeval CurTime;
                struct timespec nTime;
                struct AlgoShm *shmaddr,*ptr;

                ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));
                //Creating Shared Memory
                if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
                {
                        perror("shmget:error");
                }
                else
                {
                        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
                        //Attaching to Shared Memory
                        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
                        if(shmaddr < 0)
                        {
                                perror(" shmat :error");
                        }
                        else
                        {
                                printf(" SHM Segment attached at [%x] ",shmaddr);
                        }
                        //Loading/Initializing Data Blocks in SHM
                        clock_gettime(CLOCK_REALTIME,&nTime);
                        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
                        ptr->head = 5;
                        ptr->tail = 3;
                        ptr->fFlag = '0';
                        ptr->algoshm.time = 0;
                        ptr->algoshm.pno = 1;
                        //memcpy(shmaddr,&ptr,sizeof(ptr));
                        printf(" AlgoThrottle|ptr->head [%d] ",ptr->head);
                //      sleep(1);
                        system("./AlgoRead");

                }

        return 0;
        }

AlgoRead.c

#define key (key_t)111119
#define SHM_SIZE 1024

    int main()
    {

    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    //memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

    return 0;
    }

This is my output:

Shm created key=[111119]
 Segment Id [1179615678]  SHM Segment attached at [4a6b4000]  Time in N secs[114594083]
 AlgoRead|SHM Created shmid [1179615678]  AlgoRead|Attached to Segment at Address[624cb000]
  AlgoRead|ptr1->head [36810768] ptr1->tail [0] ptr1->fFlag[▒]
   AlgoThrottle|ptr->head [5]

Also,system call's output is showing first then the printf statement even after i used a sleep(1) before invoking system()

Body:
Please see your mistakes below
why are you allocating 10 times of the structure?

correct line

 ptr = (struct AlgoShm *)malloc(10*sizeof(struct AlgoShm));

to:-

ptr = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));

Do the above changes at both the c files

Now in memcpy why are you providing the address of a pointer ptr like &ptr? Just remove the &. This is not a object hence you just need to provide the pointer ptr. Correct it like below

memcpy(shmaddr,ptr,sizeof(ptr));

Instead of memcpy better use like below.

shmaddr->head = ptr->head;
shmaddr->tail = ptr->tail;
shmaddr->fFlag=ptr->fFlag;

I have re-write you code below. Try with that. Better correct your own code as per my advice.

AlgoThrottle.c

int main()
{
    int shmid ;
    struct timeval CurTime;
    struct timespec nTime;
    struct AlgoShm *shmaddr,*ptr;

    ptr = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));
    //Creating Shared Memory
    if((shmid = shmget(key,SHM_SIZE,0644 |IPC_CREAT)) < 0)
    {
        perror("shmget:error");
    }
    else
    {
        printf("Shm created key=[%d] \n Segment Id [%d] ",key,shmid);
        //Attaching to Shared Memory
        shmaddr = (struct AlgoShm *)shmat(shmid,0,0);
        if(shmaddr < 0)
        {
                perror(" shmat :error");
        }
        else
        {
                printf(" SHM Segment attached at [%x] ",shmaddr);
        }
        //Loading/Initializing Data Blocks in SHM
        clock_gettime(CLOCK_REALTIME,&nTime);
        printf(" Time in N secs[%ld] \n ",nTime.tv_nsec);
        ptr->head = 5;
        ptr->tail = 3;
        ptr->fFlag = '0';
        ptr->algoshm.time = 0;
        ptr->algoshm.pno = 1;
        //memcpy(shmaddr,ptr,sizeof(ptr));
        shmaddr->head = ptr->head;
        shmaddr->tail = ptr->tail;
        shmaddr->fFlag=ptr->fFlag;
        printf(" AlgoThrottle|ptr->head [%d] \n",ptr->head);
        //sleep(1);
        system("./AlgoRead");

    }

    return 0;
}

AlgoRead.c

int main()
    {

    int shmid ;
    struct AlgoShm *shmaddr,*ptr1 ;
    ptr1 = (struct AlgoShm *)malloc(sizeof(struct AlgoShm));

    if((shmid = shmget(key,SHM_SIZE,0)) < 0)
    {

    perror(" AlgoRead|shmget:error ");
    }
    else
    {
            printf(" AlgoRead|SHM Created shmid [%d] ",shmid);

            if((shmaddr = (struct AlgoShm *)shmat(shmid,0,0)) < 0)
            {
                    perror("AlgoRead|shmat error");
            }
            else
            {
                    memcpy(ptr1,shmaddr,sizeof(struct AlgoShm));
                    printf(" AlgoRead|Attached to Segment at Address[%x] \n ",shmaddr);
                    printf(" AlgoRead|ptr1->head [%d] ptr1->tail [%d] ptr1->fFlag[%c] \n ",ptr1->head,ptr1->tail,ptr1->fFlag);
            }
    }

return 0;
}


问:
Qt Creator color scheme
I like the dark "FakeVim" color scheme in Qt Creator. However it only makes the editor part dark while everything else stays normal, which is a bit disturbing. Is there any way to make such dark scheme global for Qt Creator?

Vim (dark) Color Scheme

Color scheme is applied solely to text editor (as this is the only option), and not the environment.

答:
In newer versions of Qt Creator (Currently using 4.4.1), you can follow these simple steps:

Tools > Options > Environment > Interface

Here you can change the theme to Flat Dark.

It will change the whole Qt Creator theme, not just the editor window.

Title: Qt Creator color scheme


问:
Dynamic Menus Paper Item
I am currently  using paper dropdown menu, paper listbox  and paper item web components to try and create a list. The code is the following:

```<code><paper-dropdown-menu label="Assigned" vertical-align>
 <paper-listbox attr-for-selected="id" class="dropdown-content" fallback-selection="default" selected="{{assignedFilter}}">
  <paper-item id="default">Select Configs</paper-item>
  <paper-item id="displayAssignedConfigs">TRUE</paper-item>
  <paper-item id="displayAllConfigs">ALL</paper-item>
 </paper-listbox>
</paper-dropdown-menu>
</code>```

In this example, there are 3 paper items that have static text. I would like the number of items in the list and the text in these items to be generated dynamically based on the response from an Ajax request I am making.

Any ideas or devs that have done this kind of thing before would be a great help. I am programming using Polymer 1.0.

答:
Use dom-repeat helper element:

```<code><paper-dropdown-menu label="Assigned" vertical-align>
  <paper-listbox attr-for-selected="id" class="dropdown-content" fallback-selection="default" selected="{{assignedFilter}}">
    <template is="dom-repeat" items="{{ajaxResponse}}">
      <paper-item id="{{item.id}}">{{item.label}}</paper-item>
    </template>
  </paper-listbox>
</paper-dropdown-menu>
</code>```

The above assuming that your ajax returns a response in the form of:

```<code>[
  {id: "default", label: "Select Configs"},
  {id: "displayAssignedConfigs", label: "TRUE"},
  {id: "displayAllConfigs", label: "ALL"},
  ...
]
</code>```

Title: Dynamic Menus Paper Item

Body:
I am currently  using paper dropdown menu, paper listbox  and paper item web components to try and create a list. The code is the following:

<paper-dropdown-menu label="Assigned" vertical-align>
 <paper-listbox attr-for-selected="id" class="dropdown-content" fallback-selection="default" selected="{{assignedFilter}}">
  <paper-item id="default">Select Configs</paper-item>
  <paper-item id="displayAssignedConfigs">TRUE</paper-item>
  <paper-item id="displayAllConfigs">ALL</paper-item>
 </paper-listbox>
</paper-dropdown-menu>

In this example, there are 3 paper items that have static text. I would like the number of items in the list and the text in these items to be generated dynamically based on the response from an Ajax request I am making.

Any ideas or devs that have done this kind of thing before would be a great help. I am programming using Polymer 1.0.

Body:
Use dom-repeat helper element:

<paper-dropdown-menu label="Assigned" vertical-align>
  <paper-listbox attr-for-selected="id" class="dropdown-content" fallback-selection="default" selected="{{assignedFilter}}">
    <template is="dom-repeat" items="{{ajaxResponse}}">
      <paper-item id="{{item.id}}">{{item.label}}</paper-item>
    </template>
  </paper-listbox>
</paper-dropdown-menu>

The above assuming that your ajax returns a response in the form of:

[
  {id: "default", label: "Select Configs"},
  {id: "displayAssignedConfigs", label: "TRUE"},
  {id: "displayAllConfigs", label: "ALL"},
  ...
]


问:
Converting datetime format to text format in excel
I have an excel file which has data like "04 17" (right aligned) but the format is showing as DateTime i.e 4/1/2017.

My C# Production code is written in such a way that it recognizes if that is mentioned as text format (left aligned).

In the below screenshot all data in "Project Start Date" column need to be left aligned (like I manually wrote in 3rd line).

I am new to excel & macro, please give some clue how to convert these values. I have around 6000 lines, so cant re enter all the columns manually.

答:
Set "Custom" format on column S, enter "MM YY" in the 'Type' slot (without the quotes) ... then set left alignment for the whole column from the menu.

If you need the text version, enter this formula in an adjacent column, let's say column T, row 6:
=TEXT(S6,"MM YY")

Extend the formula in the column to fill the 6000 row range.  You can optionally lock in the text values by copying the column and then doing a 'Paste Special - Values' into a new column.


问:
How to get Index of an Item in ICollection<T>
I have this list of cars

```<code>ICollection<Cars> Cars
</code>```

and I also have a single car object, which I know is in the ICollection how do I get the index/position of the car in the list? I need to add it to a list of strings

This is what I have so far:

```<code>var index = cars.Where(b=> b.Id == car.id).Single().iWantTheIndex
stringList.Add(index)
</code>```

Any ideas?

答:
This will give you the index of the current iteration:

```<code>var index = cars.Select((c, i) => new{ Index = i, Car = c })
                .Where(item => item.Car.Id == car.id)
                .Single()
                .Index;

stringList.Add(index);
</code>```

Please note that the next iteration may have a different order (depending on the actual implementation of your ICollection<>) and may result in a completely different index, so be careful what you use this index for.

Body:
I have this list of cars

ICollection<Cars> Cars

and I also have a single car object, which I know is in the ICollection how do I get the index/position of the car in the list? I need to add it to a list of strings

This is what I have so far:

var index = cars.Where(b=> b.Id == car.id).Single().iWantTheIndex
stringList.Add(index)

Any ideas?

Body:
This will give you the index of the current iteration:

var index = cars.Select((c, i) => new{ Index = i, Car = c })
                .Where(item => item.Car.Id == car.id)
                .Single()
                .Index;

stringList.Add(index);

Please note that the next iteration may have a different order (depending on the actual implementation of your ICollection<>) and may result in a completely different index, so be careful what you use this index for.


问:
Can I rename a check constraint on a table type in SQL Server 2014?
Through SQL Server 2014, CREATE TYPE ... TABLE does not support named check constraints.

This in turn results in check constraints with cryptic names (e.g. CK__TT_Income__Incom__72BBEAA9).

Such constraints are persisted in sys.check_constraints, but I have been unable to rename one of them using sp_rename.

All attempts to rename the constraint associated with a table type result in the following error message:

Msg 15248, Level 11, State 1, Procedure sp_rename, Line 424

  Either the parameter @objname is ambiguous or the claimed @objtype (object) is wrong.

Here's my table type:

```<code>CREATE TYPE IncomeCodeTable AS
   TABLE(IncomeCode char(1)
        CHECK (IncomeCode IN ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                              'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                              'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                              'Y', 'Z', '1', '2', '3', '4'))
                              )*
</code>```

The "most correct" attempt is first in the following list:

```<code>EXECUTE sp_rename N'sys.CK__TT_Income__Incom__72BBEAA9',
                  N'CK_TT_IncomeCodeTable', 'object'
</code>```

Next, try the internal form of the the table type

```<code>EXECUTE sp_rename
          N'TT_IncomeCodeTable_71C7C670.CK__TT_Income__Incom__72BBEAA9',
          N'CK_TT_IncomeCodeTable', 'object'
</code>```

Finally, try the "user" form of the table type

```<code>EXECUTE sp_rename N'IncomeCodeTable.CK__TT_Income__Incom__72BBEAA9',
                  N'CK_TT_IncomeCodeTable', 'object'
</code>```

Bottom line, is there a way to rename a check constraint associated with a user-defined table type?

答: First find the constraint and drop it then re-create it using Alter Table which allows you to set the name. Unfortunately this requires you to enter the constraint's definition. Using a tool that can generate DDL from an existing table might be useful for that. E.g.: MSSMS </p>

Body:
Through SQL Server 2014, CREATE TYPE ... TABLE does not support named check constraints.

This in turn results in check constraints with cryptic names (e.g. CK__TT_Income__Incom__72BBEAA9).

Such constraints are persisted in sys.check_constraints, but I have been unable to rename one of them using sp_rename.

All attempts to rename the constraint associated with a table type result in the following error message:

Msg 15248, Level 11, State 1, Procedure sp_rename, Line 424

  Either the parameter @objname is ambiguous or the claimed @objtype (object) is wrong.

Here's my table type:

CREATE TYPE IncomeCodeTable AS
   TABLE(IncomeCode char(1)
        CHECK (IncomeCode IN ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                              'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                              'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                              'Y', 'Z', '1', '2', '3', '4'))
                              )*

The "most correct" attempt is first in the following list:

EXECUTE sp_rename N'sys.CK__TT_Income__Incom__72BBEAA9',
                  N'CK_TT_IncomeCodeTable', 'object'

Next, try the internal form of the the table type

EXECUTE sp_rename
          N'TT_IncomeCodeTable_71C7C670.CK__TT_Income__Incom__72BBEAA9',
          N'CK_TT_IncomeCodeTable', 'object'

Finally, try the "user" form of the table type

EXECUTE sp_rename N'IncomeCodeTable.CK__TT_Income__Incom__72BBEAA9',
                  N'CK_TT_IncomeCodeTable', 'object'

Bottom line, is there a way to rename a check constraint associated with a user-defined table type?