text:
Q: How does this functional Javascript example work? I just don't seem to be able to wrap my head around this snippet of code. Could you give me a hint or two on it?
  var filteredList = watchList.map(function(e) {
  return {title: e["Title"], rating: e["imdbRating"]}
  }).filter((e) => e.rating >= 8);

The question: I understand that 'e' is the parameter passed on to the callback of the map method but what are e["Title"] and e["imdbRating"]? We are expected to run this function on an array of objects. I don't understand the syntax, and how this can even invoke something. Extremely perplexed.
I UNDERSTAND WHAT THE CODE DOES BUT HOW COME ARE WE USING THIS title: e["Title"], rating: e["imdbRating"] ???
THIS IS A SAMPLE OF AN ARRAY OF OBJECTS!
var watchList = [
                 {
                   "Title": "Inception",
                   "Year": "2010",
                   "Rated": "PG-13",
                   "Released": "16 Jul 2010",
                   "Runtime": "148 min",
                   "Genre": "Action, Adventure, Crime",
                   "Director": "Christopher Nolan",
                   "Writer": "Christopher Nolan",
                   "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
                   "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
                   "Language": "English, Japanese, French",
                   "Country": "USA, UK",
                   "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Rated": "PG-13",
                   "Released": "07 Nov 2014",
                   "Runtime": "169 min",
                   "Genre": "Adventure, Drama, Sci-Fi",
                   "Director": "Christopher Nolan",
                   "Writer": "Jonathan Nolan, Christopher Nolan",
                   "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
                   "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
                   "Language": "English",
                   "Country": "USA, UK",
                   "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
                   "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },

A: e is an object with some properties. Imagine it looks like this:
var e = {
    Title: 'foo',
    imdbRating: 7.2,
};

so e["Title"] will return 'foo' and e["imdbRating"] will return 7.2.
the function you posted could also be written like this:
  var filteredList = watchList.map(function(e) {
      return {title: e.Title, rating: e.imdbRating}
  }).filter((e) => e.rating >= 8);

Maybe that makes it easier to understand.

A: Here e points to the current element being processed in the array. So e will basically represent each object inside the array. You can replace e with any other valid name.
In your code first map is creating a new array of object and each object have tw keys title & imbRating , then again applying filter on it to create another new array where the value of imbRating is more than 8

var watchList = [{
    "Title": "Inception",
    "Year": "2010",
    "Rated": "PG-13",
    "Released": "16 Jul 2010",
    "Runtime": "148 min",
    "Genre": "Action, Adventure, Crime",
    "Director": "Christopher Nolan",
    "Writer": "Christopher Nolan",
    "Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
    "Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
    "Language": "English, Japanese, French",
    "Country": "USA, UK",
    "Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.8",
    "imdbVotes": "1,446,708",
    "imdbID": "tt1375666",
    "Type": "movie",
    "Response": "True"
  },
  {
    "Title": "Interstellar",
    "Year": "2014",
    "Rated": "PG-13",
    "Released": "07 Nov 2014",
    "Runtime": "169 min",
    "Genre": "Adventure, Drama, Sci-Fi",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan, Christopher Nolan",
    "Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
    "Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
    "Language": "English",
    "Country": "USA, UK",
    "Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
    "Metascore": "74",
    "imdbRating": "8.6",
    "imdbVotes": "910,366",
    "imdbID": "tt0816692",
    "Type": "movie",
    "Response": "True"
  }
]

var filteredList = watchList.map(function(e) {
  return {
    title: e["Title"],
    rating: e["imdbRating"]
  }
}).filter((e) => e.rating >= 8);

console.log(filteredList)

A: var filteredList = watchList.map(function(e) {
  return {title: e["Title"], rating: e["imdbRating"]}
  }).filter((e) => e.rating >= 8);

In the above code, the map function is used to iterate all the elements from watchList array. Map iterates all the values one by one which are objects. e is assigned the object. It returns an object with property and its value as e["Title"]. It is a way of accessing the properties of an object.e["Title"] and e.imdbRating will respectively call the values related to the title and imdbRating values.

A: Let's split it up so it makes more sense
First, we create a new array with map. Map works by iterating over array(watchList in this case), at each iteration it passes the current array element to the provided callback function, the returned value defines that value at index i in new array where index i is the position of the element passed to the callback function.
Take for example:
const timeTwo = [1, 2, 3].map(num => num * 2);
// timesTwo = [2, 4, 6]

In the example your providing, map returns a new array of objects containing properties title, and rating. title remains the same from original array, but rating is the mapped value of e.imdbRating.
var filteredList = watchList.map(function(e){
  return {
    title: e.title,
    rating: e.imdbRating,
  };
});

Now lets look at the next part. Filter, creates a new array, by iterating over an old array, if the callback passed to filter returns true that element is added to the new array if it returns false the element is excluded.
In this case, the final value of filtered list will be an array of objects with properties title and rating, where the rating is greater than or equal to 8;
  var filteredList = filteredList.filter((e) => e.rating >= 8);

Lets put it all together, watchList.map returns a new array, and all arrays have a filter method, so we can chain filter off map(like below). Finally filter, returns an array which will be stored in the variable filteredList.
  var filteredList = watchList.map(function(e) {
      return {title: e.Title, rating: e.imdbRating}
  }).filter((e) => e.rating >= 8);


text:
Q: In Boost serialization,boost_shared pointer does not compile.. give error I'm trying to serialize shared pointer using boost but it gives error :
Error 1   error C4308: negative integral constant converted to unsigned type c:\users\allwork\hope\lib\boost_1_55_0\boost\mpl\print.hpp   51  1   Input
I even tried the solution given at link - https://stackoverflow.com/questions/22409755/boost-serialization-fails-gives-compile-time-error-c4308
but still issue exists.
If i comment line - " ar & MyStruct; " error goes off. Please let me know where mistake or issue is exist with respect to current code.
Below is the code :
// MyStruct.hpp file
struct MyStruct
{
std::string rollno;
std::string address;
***boost::shared_ptr<MyStruct> Mydata;***

private:
friend class boost::serialization::access;
template
void serialize(Archive &ar, const unsigned int version)
{
ar & rollno;
ar & address;
ar & Mydata;
}

public:
MyStruct(void);
MyStruct(const parameter_strings & parms);

virtual ~MyStruct(void);
};
}

// MyStruct.cpp file

MyStruct::MyStruct(void)
{
}

MyStruct::~MyStruct(void)
{
}

MyStruct::MyStruct(const parameter_strings & parms)
{
// implementation
}

BOOST_CLASS_EXPORT_IMPLEMENT(MyStruct);   BOOST_CLASS_IMPLEMENTATION(MyStruct,boost::serialization::object_serializable);
BOOST_CLASS_TRACKING(MyStruct,boost::serialization::track_selectively);

A: Don't forget to include
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/shared_ptr.hpp>

redpajama_set_name: RedPajamaStackExchange


text:
Q: getting first part of a string that has two parts I have a string that has two parts (path and owner) both separated by a space.
This is the input file input.txt
/dir1/dir2/file1 @owner1
/dir1/dir2/foo\ bar @owner2

I want to extract all the paths to a separate output file - output.txt
I cannot use space as delimiter since paths can also have filenames with space and delimiter in them
/dir1/dir2/file1
/dir1/dir2/foo\ bar

A: Here could be a different way of doing it with rev + GNU grep:
rev file | grep -oP '.*@ \K.*' | rev

OR
rev file | grep -oP '.*@\s+\K.*' | rev

With original simple solution go with:
awk -F' @' '{print $1}' Input_file

A: Assuming spaces that shouldn't be parsed as delimiters are escaped by a backslash as in your sample, you could use the following regex :
^(\\ |[^ ])*

For instance with grep :
grep -oE '^(\\ |[^ ])*'

The regex matches from the start of the line any number of either a backslash followed by a space or any other character than a space and will stop at the first occurence of a space that isn't preceded by a backslash.
You can try it here.

A: I would trim the ending part with sed.
sed 's/ [^ ]*$//' /path/to/file
This will match from the end of the line:

*

* (blank) matches the space character

*[^ ]* matches the longest string that contains no spaces, i.e. @owner1

*$ matches the end of the line

And they will be replaced by nothing, which will act as if you deleted the matched string.

A: A one-line would do it:
while read p _; do printf '%q\n' "$p"; done <input.txt >output.txt

A: You can put them in an array and process
mapfile test < input.txt; test=("${test[@]% *}")
echo "${test[@]}"
echo "${test[0]}"
echo "${test[1]}"

A: You can try with simple awk
awk ' { $NF=""; print } '

Try it here https://ideone.com/W8J1ZO


text:
Q: Prevent label click event as default behavior I have in a winform a label in a user control
when i click anywhere in the user control the user control is painted in blue
When I click on the label, The user control doesn't painted in blue , meaning it doesn't fires the click event because of the label
the label has no click event handler
Click on the user control:

click on the label: Nothing happends............................................

A: You can attach an event handler to your Label and trigger the click event of UserControl from there:
private void Label_Click(object s, EventArgs e)
{
     UserControlClickHandler(s, e);
}

A: It seems that you are working on Window Forms.
Label control has click event and it is inherited from control class.
So you have to bubble up event upto maincontainer ( in your case UserControl ) to change background color.
public void Label1_Click(object sender,EventArgs arg)
{
     // your usercontrol event click event
     UserControl_Click(sender, arg);
}


text:
Q: Given an adjacency list of a bidirectional graph, how to return a collection containing all possible paths from the root node of a certain length? I have an adjacency graph of nodes (in a bidirectional graph), and I was wondering how I would print all possible paths from the root of a certain length. As a result, repetition is allowed.
e.g., given the following graph
    1
   / \
  2   3
 /     \
4       5

represented with the adjacency lists:
1 [2 3]
2 [1 4]
3 [1 5]
4 [2]
5 [3]

How would I return a collection of all paths from the root node of length 4? I'm looking to use Java, but just an algorithmic solution would help greatly. Some example of possible paths. The tree is not necessarily binary:
1 -> 2 -> 1 -> 3
1 -> 2 -> 4 -> 2
1 -> 3 -> 5 -> 3
1 -> 3 -> 1 -> 3
1 -> 2 -> 1 -> 2
1 -> 3 -> 1 -> 2

This would be represented as:
[1213,
1242,
1353,
1313,
1212,
1312]

I've been trying to apply some variation of the depth first search algorithm, but I'm not sure of how to keep track of the nodes.

A: You should go with DFS, that tracks "How many nodes I have left" (remaining distance).
Each node recursively invoke DFS on all its neighbors, and when you reach the case where the number of nodes left is 0, stop and print the current path.
Pseudo code:
DFS(source, distance):
   List current = new LinkedList()
   DFS(source,distance,current)
DFS(source,distance,soFar):
   if (distance == 0): //stopping when distance is reached
      print (soFar + source) //never added the last node, doing it now
   else:
      soFar.append(source)
      for each neighbour v of source:
         DFS(v,distance-1,soFar) //recursively call with shorter distance left
      soFar.removeLast() //remove the source that was added to the list


text:
Q: How to speed up the MySQL query needed for pagination - million records in the table There is about 1 milion records.
Query is needed for the pagination system.
Query looks like this:
SELECT field1, field2, field3 FROM table
WHERE field4 = '$value'
ORDER BY field5 ASC limit $offset, 30;

There is index on field4 and field5.
All fields are varchar type.
Field5 was tested as int but no real improvement notice.
Right now query with limit 0, 30 takes about 1 second, but query with limit 119970, 30 takes about 20 seconds.
Is this realistic to obtain result less than 0.1 second on paginated pages? Such loading time is needed for the website to offer good user experience.
EXPLAIN (select with limit 0,30)
id: 1
select_type: SIMPLE
table: table
type: index
possible_keys: NULL
key: field5
key_len: 768
ref: NULL
rows: 223636
Extra: Using where

A: You could try table partitioning:
http://dev.mysql.com/doc/refman/5.1/en/partitioning.html

A: Depending on how much your data is changing, you could use memcached to reduce the amount of times a certain query needs to get run and reduce the response time for most users.

A: It should have index "B-TREE (field4, field5)".
This index will allow MySQL to use field4 to find the records and limit them with order on field5.

A: I have a suggestion that the data should not be fully loaded into pagination directly instead using ajax query again for different page when user click it. So in exact page it only shows the current page number data. Hope it helps and Good Luck.

A: Is this table have PK?
Select field1,field2,field3 from table as a
join (select PK from table WHERE field4 = '$value'
ORDER BY field5 ASC limit $offset, 30) as b
on a.PK=b.PK;

A: Have you considered making another table (table 6) that is an indexed hash of table4? Searching numbers instead of text is going to be a lot faster so the query is something like:
SELECT field1, field2, field3 Force Index(Table6) FROM table
WHERE field 6 = '$hashvalue' AND field4 = '$value'
ORDER BY field5 ASC limit $offset, 30;
It should help to eliminate 99.99% of data before it has to text search and should speed up your queries regardless of the offset....


text:
Q: Amazon S3 read file operation times out from Lambda function with Task timed out after 30.03 seconds This code works in .net core console on my local machine
await S3Client.GetObjectAsync(new GetObjectRequest { BucketName = bucketName, Key = key });

but same line does not work in Lambda function in aws, it times out with "Task timed out after 30.03 seconds"
I have done following

*

*Increased the timeout for lambda function to 5 mins.

*Increased the memory usage limit for lambda function.

*Attached policy "AmazonS3FullAccess" to lambda function IAMRole.
Also attached policy "AmazonS3ReadOnlyAccess" to the same role (desperate measures)

*Made the Bucket public for everyone.

*Made sure bucket and function live in same region.

Still no luck, what am I doing wrong here? Thanks

A: Yes, need to remove VPC to make it work.
However, if you dont want to remove your VPC, do following.

*

*create a new nat gateway in public subnet.

*add a new role in private route table to allow 0.0.0.0 to nat gateway.

Ta da, now your Lambda can read files from s3 bucket. However, note that nat gateway has a cost associated with it. so it is not free option.
There is a new way of doing things. read This and apply it.


text:
Q: None Unicode library and windows locale I'm using(what seems to be) an ansi(or ascii??) dll library. I think it is such because the header file provided with the lib shows function using char*'s and LPSTR and LPCSTR and structs with char arrays.
This dll is loaded via ::LoadLibrary from a cpp/cli class library that wraps its functionality and exposes it to c#. A c# console app and various other class libs use this cli lib to perform operation.
I can make the cli assembly ether mutibyte or Unicode(which as far as I understand is the same in terms of language support) and c# apps are always Unicode.
This native dll is essentially a broker for a propriety back end server, it passes information back and froth from and to the server.
The issue I'm running into is that the native dll lib will only operate correctly for a particular language if the os locale, for none Unicode apps, its running in is set to that particular language.
I.e. if i want the app to correctly work with Chinese characters, that locale needs to be set. What I find hard to grasp is why does the locale matter for the broker. I understand that if the server is an ansi app if a user wanted to store none Unicode Chinese on it setting the locale on the server would make sense so it would in the client, but not in the middle man that just passes things along. Furthermore the whole thing is getting very confusing.
Is there away to pass Unicode to something like a char array in c++? Wold that even work in this scenario?
Here's a scenario I'm thinking about:

*

*c# app gets url encoded string

*c# app decodes the string and passes it to cli

*cli somehow converts the String^(or should it be byte[] at
this point) to char[] and passes it to the native lib

Should this really be possible? In terms of memory layout it should, i mean char is just a byte no?
Am I approaching this the right way? is there there a better way to accomplish cross language support. Mind you the vendor is on record saying that there is no way to mix languages in the api, but that's not what I'm looking for. I just dont want to have to run an instance of the software on a separate os for each language i want to support.

A: What is confusing in this case, is that the DLL has a broken interface. Broken in the following sense: it does not support all of the Unicode codepoints. This is regardless of the type of parameters: char array is perfectly good for supporting all of unicode.
How do we know this? It is because, according to you, what it does depends on the system locale setting.
So, what to do? If the DLL source code is not under your control, you will not have it. You can, however, solve the problem of one ANSI codepage by setting the locale. It does not work for some languages.
Better would be to urge the DLL vendor to support unicode. Best encoding is, of course, UTF-8 - and this way it does not break existing code because the types LPCSTR remain the same.

A: I ended up using the approach described here:
Is it possible to set ANSI encoding per application in windows
This is what worked for me


text:
Q: Google Cloud Debian VM. Node Red stops working I am a Windows user trying to use Linux for my online server.
I am testing a Debian VM running on the Google Cloud.
There I installed Node-Red, Apache and mySQL.
Every day when I am going to start my testing Node-red is down, the VM, Apache and mySQL are running but for Node-Red I have to open the terminal console and type node-red start.
Assistance welcome.

A: There can be a lots of different factors. In order to be able to give a better answer we would need to see your logs.
However, a few things that you should know either way. Debian (and other linux distors) use systemd for ensuring that a background service is running, and is starting up at boot time. So when you restart a computer systemd is responsible to start up all software's that you would like to run.
More about systemd here. Generally what you want is to have the application in an "enabled" state to ensure that it starts up after a reboot.
However, if you do not shut down your VM between your sessions, then the application is most likely crashing from a different factor. Crashing can be caused by lots of different things, and this is where the logs would be appreciated. To find logs about the application you can most likely find it in /var/log/<application-name>/. Or if you want to view them in real time you can do sudo journalctl -fu <application-name>
More info on journalctl can be found here.


text:
Q: AV1 decoder required to play the video in smplayer I often download youtube videos to watch them later. But some of them does not show any thumbnail and if I try to play them in smplayer it only renders audio and doesn't support video. When I try to open them with ubuntu default video player error message is showing up as shown in the image.

On clicking on find in software it doesn't find anything. I have already installed ubuntu restricted codecs. I know vlc can play this but vlc has other playback issues for me. It is playing in mpv but I want to use smplayer. Any workaround to play this type of video in smplayer? Thanks in advance.

A: It could be that there exists other missing codecs and decoders for multimedia. I have encountered it recently as well and got it solved by installing via terminal
$ sudo apt-get update
$ sudo apt install libdvdnav4 libdvd-pkg \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly libdvd-pkg

Crd - https://websiteforstudents.com/how-to-enable-ubuntu-18-04-lts-beta-to-play-videos-files/

A: If mplayer will not play the video portion of your file (e.g. running "mplayer file.mkv" on the command line yields errors of the form "Cannot find codec matching selected -vo and video format 0x31307661," indicating lack of support for the av1 video codec), then you still might be able to play the video with smplayer by changing the multimedia engine that smplayer uses.  In the "Options" tab, open "Preferences," and under General -> General, open the drop-down menu for the multimedia engine.  If the options you see are "mplayer," "mpv," and "other," then select mpv in place of mplayer.
Of course, for this to work you do need mpv installed ("sudo apt-get install mpv").

A: Convert the file to mp4
For that install ffmpeg version 4
Commands to install that: (from: https://www.cloudbooklet.com/how-to-install-and-use-ffmpeg-on-ubuntu-18-04/)
sudo add-apt-repository ppa:jonathonf/ffmpeg-4
sudo apt install ffmpeg

Command to convert mkv to mp4:
ffmpeg -i filename.mkv filename.mp4


text:
Q: Extract the value of field in php and save Hello I have a textArea sms and another textfield sms_count..
The value of sms_count is like this Used: 0/765 (1/5) | Left: 765 Whenever user type anything in textArea sms it counts the characters and shows it in sms_count
if user has typed 30 characters so far, so the value of sms_count will be like this Used: 30/765 (1/5) | Left: 765
When clicking on submit button, I get the value of sms_count like this..
sms_count => Used: 30/765 (1/5) | Left: 735

How do i get the characters that he entered which is 30, I need to save the value 1 in (1/5) only instead of Used: 30/765 (1/5) | Left: 748
I need to get only the used value which is 1 in this case but it can be different... if user type more than 160 characters then sms_count value will be 2 (2/5) then again if user has enter more than 320 characters then value be 3 in (3/5)
example
30/765 (1/5) | Left: 735
161/765 (2/5) | Left: 604
330/765 (3/5) | Left: 435
So how do i extract those values in save in database through PHP?
Below is the screenshot of two fields one is textArea sms and textfield sms_count

<div class="form-group">
<?PHP echo $form->textArea($model, 'sms', array('class' => 'form-control', 'id'=>'Campaigns_welcome_sms', 'onpaste' => "return textCounter(this.form.Campaigns_welcome_sms,this.form.smsAndCharactersCount,this.form.smsAndCharactersCount);", 'onkeyup'=>"textCounter(this.form.Campaigns_welcome_sms,this.form.smsAndCharactersCount,this.form.smsAndCharactersCount);", 'onkeypress'=>"textCounter(this.form.Campaigns_welcome_sms,this.form.smsAndCharactersCount,this.form.smsAndCharactersCount);")); ?>
<?php echo $form->textField($model, 'sms_count', array('class' => 'form-control', 'style'=>"width: 370px", 'id'=>"smsAndCharactersCount", 'value'=>"Used: 0/765 (1/5) | Left: 765", 'readonly'=>"readonly")); ?>
</div>

A: With a little bit of string manipulation you can extract the numbers you want like this:
$sms_count = 'Used: 30/765 (1/5) | Left: 735'; // YOUR VARIABLE FROM SUBMITTED DATA

$sms = explode('/',$sms_count); // SPLIT STRING TO ARRAY BY SLASHES:

//CREATE VARIABLE $user THAT CONTAINS THE NUMBER OF CHARACTERS USED:
$used = substr($sms[0], stripos($sms[0],' ')+1); //FINDS THE SPACE ' ' AND RETURNS THE REST OF THE STRING STARTING FROM THERE...

//CREATE VARIABLE $count THAT CONTAINS THE NEXT NUMBER YOU WANT:
$count = substr($sms[1], -1, 1); // EXTRACTS THE LAST CHARACTHER/NUMBER

You could use echo 'used: '. $used .' count: '.$count; to check if the results is what you are after. In this case i would output: used: 30 count: 1
How you choose to save this to your database depends on your setup. It's just an ordinary insert or update query to make. A regular SQL insert query would be something like:
$sql = "INSERT INTO table_name (identifier, used, counts)
        VALUES ('$identifier', '$used', '$count')";


text:
Q: password checker attemp 2 After my third attempt, if I input a k7e15 the output should be
"The password is correct"

but it is
"The system is disable"

what I need to change?
p = input("Enter a password: ")
count=0
while count<2:
    if p=="k7e15":
        print("The password is correct.")
        break
    else:
        p = input("The password is wrong,please try again:")
        count +=1
    if count>=2:
        print("The system is disable.")

A: This should do the job, you just weren't checking the password in the second input (inside the else), also you are checking the password at the top of the loop so at the third try, you insert the password but you add 1 to the count variable, so your count is equal to 3, and you jump to the if count>=2 which gives you back system is disable
p = input("Enter a password: ")
count=0
while count<2:
    if p=="k7e15":
        print("The password is correct.")
        break
    else:
        p = input("The password is wrong,please try again:")
        if p=="k7e15":
            print("The password is correct.")
            break
        count +=1
    if count>=2:
        print("The system is disable.")


text:
Q: Clarification in definition of Holt-Winters algorithm The algorithm mentioned on Wikipedia has a line $$s_t = \alpha \frac{x_t}{c_{t-L}} + (1-\alpha) (s_{t-1} + b_{t-1})$$.
For $1 < t < L$ how should we interpret $c_{t-L}$?  On that interval, should we replace it with $c_t$?

A: For triple exponential smoothing it says that at least one seasonal cycle of length L must be completed. So t is actually greater than L.  The notation is 1 < t < L but the t is given modulo L.


text:
Q: VS cant browse SSAS cube When I try to browse a cube in VS2012 it will crash my VS instance even though it deployed perfectly fine.  I have tried different combinations of uninstalling and re-installing software.  I am wondering what could possibly be missing.
I have analysis services running as a service
I have SQL server Data tools installed
I have Office Dev Tools for VS2012 installed
I have SQL Server Management studio installed
I have Office installed
I am able to browse the cube fine in excel

A: My team was unable to pinpoint the problem.  Reformatting the machine and installing everything fresh fixed the problem quickly.  No way to fully know what went wrong but there were some strange registry entries that may or may not have contributed to the problem even if the logs didn't show that.


text:
Q: NGINX unescapes %2f to a forward slash. How can I stop it? Say I want to encode an article title in a URL and that contains a slash. If I URL encode the article title I get:
http://example.com/articles/foo%2fbar/view/

NGINX passes this to my FastCGI application as:
http://example.com/articles/foo/bar/view/

Which rather ruins the idea.
I notice that if NGINX is serving a file, say /path/to/page.html, then it can be reached by either of the following two URLs:
http://example.com/path/to/page.html
http://example.com/path/to%2fpage.html

However this is not the case for (for example) Apache.
Is there any way to fix this behavior?
I've tried the docs and Google with no luck.
Thanks.
UPDATE
nginx config:
worker_processes  1;
pid ./nginx.pid;
events {
    worker_connections  1024;
}
http {
    server_tokens off;
    server {
        listen 80;
        server_name localhost;
        location /mysite/{
            fastcgi_pass   unix: ./mysite.fcgi.socket;

            fastcgi_param SERVER_NAME $server_name;
            fastcgi_param SERVER_PORT $server_port;
            fastcgi_param SERVER_PROTOCOL $server_protocol;
            fastcgi_param SCRIPT_NAME "/mysite/";
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_param REQUEST_METHOD $request_method;
            fastcgi_param QUERY_STRING $query_string;
            fastcgi_param CONTENT_TYPE $content_type;
            fastcgi_param CONTENT_LENGTH $content_length;
            fastcgi_pass_header Authorization;
            fastcgi_intercept_errors off;
        }
    }

}

A: Try escaping "%" as "%25"
http://example.com/articles/foo%252fbar/view/

A: More details on this issue are provided over at Nginx pass_proxy subdirectory without url decoding, which has a full solution if you're a proxy_pass user.
With fastcgi_pass, this could happen due to the default conf/fastcgi.conf in nginx, where the DOCUMENT_URI variable is set to http://nginx.org/r/$document_uri, which is equivalent to just http://nginx.org/r/$uri, which, in turn, is the normalised (decoded and unescaped), query-less and potentially rewritten version of http://nginx.org/r/$request_uri (which, in turn, could be accessed through REQUEST_URI instead):

  fastcgi_param  REQUEST_URI        $request_uri;
  fastcgi_param  DOCUMENT_URI       $document_uri;

In your case, however, you don't actually seem to specify DOCUMENT_URI at all, since http://nginx.org/r/fastcgi_param is not inherited from a prior level if used at the current level, so, it's possible that the decoded path comes out of your http://nginx.org/r/$fastcgi_path_info, which is supposed to be paired with http://nginx.org/r/fastcgi_split_path_info, which you omit from the provided configuration, so, the original question may appear to be inconsistent, as the exact paths between the provided requests and the sample configuration don't match, either.
Regardless, the best fix with fastcgi would depend on the application, and may be one of the following:

*

*Not depend on paths not being decoded and cleaned up properly by nginx.  This is probably the best fix security-wise, as you're basically asking nginx to not clean up stuff like /../, either (including all the escaped variations), which is certainly intended to protect you against a whole class of vulnerabilities in your backend.

*Redesign the whole interface to use the query parameters within QUERY_STRING to ensure paths aren't mingled or decoded prematurely.

*Use REQUEST_URI to get the original request URI without any normalisation or decoding taking place.

*Pay closer attention to all instances of using $uri or $document_uri, and possibly $fastcgi_path_info as well, which would usually contain the decoded and normalised paths.

*Use the rewrite tricks as outlined in the linked answer to place undecoded $request_uri back into $uri.  Note that you also might have to strip out the query string manually if you go this route.

BTW, note that what you're doing in the first place is kind of playing with fire, because it's very easy to introduce security vulnerabilities if you don't fully understand what you're doing, and if someone one day does decide to take advantage of you relying on these encoded paths bypassing proper handling and scrutiny of nginx.
The fact that what you want to do works in Apache as-is is more of a bug than a feature — this works differently in nginx by design and in order to prevent a whole class of security vulnerabilities.

A: I had the same issue with my nginx + uWSGI + flask stack.
I solved it by introducing a rewrite rule to the nginx config:
location @app {
    rewrite ./ $request_uri break;
    include uwsgi_params;
    uwsgi_pass unix:/tmp/uwsgi.sock;
}

Update: this seems to break query parameters, so I had to do this:
location @app {
    set $plain_uri $request_uri ;
    if ( $plain_uri ~ (.*)\?.* ) {
        set $plain_uri $1 ;
    }
    rewrite .* $plain_uri break;
    include uwsgi_params;
    uwsgi_pass unix:/tmp/uwsgi.sock;
}

The issue with this is that the URL originally encoded gets encoded again, so I need to unencode 4 times in total.

A: You won't have any trouble, if you use URL query parameters.
When you can control your servers routes you could go for:
http://example.com/articles/view/?path=foo%2fbar
and nginx won't touch %2f


text:
Q: Animations for the group of markers to rotate at the same time in google maps v2 android I'm implementing the animations for the group of cars(Markers) to rotate at the same time in google map v2.
so that i need to code my animation part inside handler.post() method.
By doing this the animation part(handler.post() method) is running for only one marker.
i have coded handler.post() method inside the for loop. It runs only for the first time which means only one marker is rotating. after that it is not working. My code is as follows.
private void animateCarsInMarkers(final MarkerOptions mark, final long bearing, final LatLng startPosition, final int position){

    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final long duration = 3000;
    final Interpolator interpolator = new LinearInterpolator();
    final Marker marker = mGoogleMap.addMarker(mark);

    final float rotationValue = Float.parseFloat(String.valueOf(bearing));

    try {
        if(tempCarsArray != null && !tempCarsArray.isEmpty()){
            sLongitude = tempCarsArray.get(position).getDouble(LONGITUDE);
            sLatitude = tempCarsArray.get(position).getDouble(LATITUDE);
            sBearing = tempCarsArray.get(position).getLong("Bearing");

            final double dLongitude = startPosition.longitude;
            final double dLatitude = startPosition.latitude;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    long elapsed = SystemClock.uptimeMillis() - start;
                    float time = interpolator.getInterpolation((float) elapsed / duration);
                    double lng = time * dLongitude + (1 - time) * sLongitude;
                    double lat = time * dLatitude + (1 - time) * sLatitude;
                    float rotationValue = time *  dbearing + (1-time) * sBearing;
                    marker.setRotation((-rotationValue > 180) ? (rotationValue / 2) : rotationValue);
                    marker.setPosition(new LatLng(lat, lng));
                    if (time < 1.0) {
                        handler.postDelayed(this, 16);
                    }
                }
            });
        tempCarsArray.clear();
    } else {

            marker.setPosition(startPosition);
            marker.setRotation(-rotationValue > 180 ? rotationValue / 2 : rotationValue);
        }
    }catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is the method which i called inside for loop. But it runs only for the first time in loop. Later it is not working. So only one marker is animated among the group of markers. My for loop is as follows :
for(int i=0; i<size; i++){
animateCarsInMarkers(mark, bearing, latLng, i);
}

This loop runs only when the value of i=0 and it wont runs again.
Thanks in advance.

A: If your 'for loop' ran only once, it means that your "for loop condition part", i<size for this instance, has already satisfied the condition. What I would suggest is for you to actually log "size" and check its value.
If you're looking for the size of an array, use tempCarsArray.length like:
for(int i=0; i < tempCarsArray.length; i++){
    animateCarsInMarkers(mark, bearing, latLng, i);
}

To check if size is causing the problem, try this.
If you know the actual number of markers you're expecting to rotate, try to substitute with an integer for now, like:
//if you're expecting 5 markers
for(int i=0; i < 5 ; i++){
     animateCarsInMarkers(mark, bearing, latLng, i);
}

If all markers did rotate, it means your size variable has only a value of 1.


text:
Q: Yii, Selenium and multiple submit buttons I've got a form with two submit buttons which I want to test using Selenium.
View:
<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'profile-form',
    'enableAjaxValidation' => true,
    'action' => '',
    'clientOptions' => array(
        'validateOnSubmit' => true,
        'validateOnChange' => true,
        'validateOnType' => false,
    ),
));
?>

<input name="cancel" type="submit" value="Cancel" />
<input name="submit" type="submit" value="Save changes" />

<?php $this->endWidget(); ?>

Controller is nothing special, you can assume it just prints "Your profile has been saved" or "Your profile was not saved" depending on what $_POST['cancel'] it gets
Test code:
<?php
$this->open('/profile_form_url');
$submit_button_selector = 'css=#profile-form input[name="submit"]';
$cancel_button_selector = 'css=#profile-form input[name="cancel"]';

$this->clickAndWait($cancel_button_selector);
$this->assertTextPresent('Your profile was not saved');

$this->open('/profile_form_url');
$this->clickAndWait($submit_button_selector);
$this->assertTextPresent('Your profile has been saved');

The problem is that code works great in browser but not when running tests in Selenium/Firefox. When running tests, it "sees" the first button only (Cancel), clicking "Save changes" has the same effect. If you place Save changes button first, it will not "see" Cancel button.
If you turn enableAjaxValidation off, it works both in browser and Selenium, but I'd like to have a more elegant solution of course. Like for example turning off the AJAX validation on clicking on Cancel.
No, the problem doesn't depend on which locator you use for buttons (xpath, css, id).

A: clickAndWait() calls waitForPageToLoad() - ajax form validation will generally not trigger this event (unless a page loads), so your test will never complete; this is probably why if you turn ajax validation off it works.
You might want to look at the other options selenium provides (this is an old link to the free phpunit pocket guide that describes some other options - it's based on phpunit 3.1 though) such as using click() and then using waitForCondition() with some javascript to run and return true if the new text is displayed.


text:
Q: Local eventEmitter listening to global eventEmitter I almost wrote the question title as - Communicating between eventEmitters
I have a node.js module (X) that is on the global scope (it uses eventEmitter). I then have code that is local to each socket (user connected).
right now i am carrying X through the process on a global variable G={'X':X} so that the socket can then access X like this:
G.X.on('someEvent',doSomething);

This is dumb! Now every time i start my server it seems to act fine (I receive the event), but then if I refresh the page and emit an event I get it twice. If I refresh the page again I get the event 3 times.
I think that I am binding the listener to the same eventEmitter that is global.
How can I make a separate local eventListener to listen for the emits of the global eventEmiter?
I know how to set up an eventEmiter:
var events = require('events');
var ee = new events.EventEmitter();

ee.on('someEvent',function(){console.log('hello');});

but it does not catch the event of another...
I have also tried copying the module using the eventEmitter
var ee = G.X;
ee.on('someEvent',function() { console.log('hello'); });

But it still receives multiples of an event.
hello
hello
hello

A: This question was asked quite some time ago, but here's my answer anyways, seeing as there's no answer for it yet.
Listen to the socket object's "close" event, then remove the callbacks to your global. So it would look like:
X.addListener("someEvent", callback);

X.on("someEvent", function(socket){
  socket.on("close", function(){
    X.removeListener("someEvent", callback);
  });
});


text:
Q: Multiplication of the numbers $1$ to $n$ Let's say I want to find  the product of $1,2,3, \dots, 10$. Do I need to do $1 \cdot 2 \cdot 3 \cdot \dots \cdot 10$ manually or is there an easier way to do it?
Something like the sumation of  $1$ to $n$ which gives $\frac{n(n+1)}{2}$.
I tried to search but couldn't find a way to do it directly.

A: It is known as factorial and denoted as $n!$.
The case $10!$ can be reduced:
\begin{eqnarray}
1 \cdot 2 \cdot 3 \cdots \cdot 8 \cdot 9 \cdot 10 &=& 10 \Big(5-4\Big) \Big(5-3\Big) \cdots \Big(5+4\Big)\\
&=& 50 \Big(25-16\Big) \Big(25-9\Big) \Big(25-4\Big) \Big(25-1\Big)\\
&=& 50 \Big(15-6\Big) \Big(15+6\Big) \Big(20-4\Big)  \Big(20+4\Big)\\
&=& 50 \Big(225 - 36\Big) \Big(400 - 16\Big)\\
&=& 50 \times 189 \times 384 = 3,628,800
\end{eqnarray}

If you have to do it by head, collect easy factors:
\begin{eqnarray}
1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 \cdot 6 \cdot 7 \cdot 8 \cdot 9 \cdot 10 &=&
\Big( 2 \cdot 4 \cdot 5 \cdot 10 \Big) \Big( 3 \cdot 6 \cdot 8 \cdot 9 \Big) \cdot 7\\
&=& 20^2 \cdot 6^4 \cdot 7\\
&=& 400 \times 1296 \times 7
\end{eqnarray}

A: The fact that there is a special notation for the factorial suggests that there is no simpler formula for it other than the definition.
Note that there is no special notation for $\sum_{i=1}^n i$, since it can be written as $n(n+1)/2$. (I'm not sure $\binom{n+1}{2}$ counts as special notation in this context.)
If you need a formula, you could use $n! = \Gamma(n+1)$, but using $n!$ is probably much clearer.


text:
Q: Neo4J - How to create relationship based on an attribute value - if exists or not? In an existing relationship I want to add an additional one. The new relation should depend on a specific attribute value.
E.g. if an Employee has a value -1 in department_id property, then he should have a relationship: MEMBER_OF to department table, if he has 1, 2 or 3, then he should have a relation as HEAD_OF.
And I think the direction (arrow) for relationships would be opposite to each other  -[:HEAD_OF]-> or <-[:MEMBER_OF]-
One important thing to add is that the value -1 doesn't exist in the department graph. The dep graph has IDs just from 1 till 8.
In other words, this could be something like: if any employee has an ID which doesn't exist in dep Graph... in this case -1

A: EDIT
After discussing by chat, the queries that best fits the requirements is:
The first query create a :HEAD_OF relationship between all employees that have department_id <> -1 and the respective department.
MATCH (emp:Employee)
WHERE emp.department_id <> -1
MATCH (dep:Department)
WHERE dep.id = emp.department_id
CREATE (emp)-[:HEAD_OF]->(dep)

The second query will create a relation :MEMBER_OF between employees that have department_id = -1 and a random department.
MATCH (emp:Employee {department_id : -1})
MATCH (randomDep:Department)
WITH collect(emp) as emps, randomDep LIMIT 1
UNWIND emps as emp
CREATE (emp)-[:MEMBER_OF]->(randomDep)


text:
Q: How to customize Sphinx doc images folder? I'm working with Sphinx doc and I want to translate my documentation to other languages. I want to make images language dependent so screenshots in English will be in one folder and screenshots in German in other.
Currently Sphinx takes all images from /images folder. As I see in other stackoverflow questions it is impossible to modify image directive path with variable substitutions.
Is it possible to change default images folder by some CLI option or other way?
UPD. I use Sphinx 1.3.1.

A: I asked this question in Sphinx github.
Takeshi Komiya gave answer which solved my problem.
He suggests to use figure_language_filename option. I tried and it works. I can flexibly set path to image folders.
Note: figure_language_filename option is available since Sphinx 1.4.


text:
Q: Converting nested json into a pandas data frame in Python I have a nested data frame in JSON. I have no problem with taking a data frame that isn't nested and converting into pandas data frame.
What I am having issues is when there are multiple levels of the data frame and I need to write independent records for each of the json entries.
{
  'type': 'text1',
  'key': ['key1'],

},
{
  'type': 'text2',
  'key': ['key1', 'key2'],
},
 'type': 'text3',
 'key': 'key',
}

I used the following code to write this into a data frame.
 df = pd.DataFrame.from_dict(json)

Unfortunately for each of the entries, I have to include a record. So if key has 2 elements in the array, 2 entries will need to be created. And an additional column (key index) will be created. So what I am trying to get is something similar to below.

Any help would be greatly appreciated on this as I have been stuck on this for a while!

A: Use explode:
json = [{'type': 'text1', 'key': ['key1']},
        {'type': 'text2', 'key': ['key1', 'key2']},
        {'type': 'text3', 'key': 'key'}]

df = pd.DataFrame(json).explode('key') \
       .assign(key_index=lambda x: x.groupby(level=0).cumcount())
print(df)

# Output
    type   key  key_index
0  text1  key1          0
1  text2  key1          0
1  text2  key2          1
2  text3   key          0

Update

How would you start the key index at 1 instead of 0 in the case of multiple entries. For text 1, the generated index is 0. For text 2, the generated index starts at 1 and so there is 1 and 2.

df = pd.DataFrame(json).explode('key') \
       .assign(key_index=lambda x: x.groupby(level=0)['key'].transform(cumcount))
print(df)

# Output
    type   key  key_index
0  text1  key1          0
1  text2  key1          1
1  text2  key2          2
2  text3   key          0


text:
Q: Can the prime gap record of Liu be improved further? Let $d$ be the least positive integer such that there are infinitely many distinct prime pairs $\{p,q\}$ with $|q-p|\le d$. The twin prime conjecture is equivalent to $d=2$. In 2013 Yitang Zhang proved that $d\le 7\times10^7$. Maynard improved this to $d\le600$, and a Polymath Team led by Tao obtained further that $d\le 246$.
Quite recently, Chunlei Liu released a prperint On the gap between primes in which he modified Maynard's approach to get $d\le 130$.
Question. What's the advantage in Liu's modification of Maynard's method?
Can Liu's work be improved further? Can one prove $d<130$ via suitable refinements?
I have not read Liu's paper very carefully. Your helpful comments are welcome!


text:
Q: Drupal custom field customization I am using Drupal 7.
I created a custom field for article nodes, which is a text field, with unlimited values so it's essentially an unordered list. I want to be able to customize the area in which the new field is displayed, but no page.tpl.php it renders under the page content, with the body. The new field does not create a new block in which I can edit. I want to limit the containing div to 350px, and then place a 300x250px ad to the right. So the custom field list on the left, with an ad on the right. If anyone knows a way to doing this rather than finding the div ids and sloppily overriding the CSS to do this please let me know.

A: I'm not sure your use case and requirements are completely clear to me, but it sounds like you might want to read up on "Render arrays", a new-in-Drupal 7 feature which allows more fine-grained control of content output/display. This is part of the Drupal Core and the official documentation might be a good starting point, but there are many other articles and tutorials (use: "render array" Drupal <-- your search on Google) which might be helpful.


text:
Q: Shrink to fit content in flexbox, or flex-basis: content workaround? I have a webapp with which I'm using flexbox for layout.
I'm trying to both fill the screen (it's an app, not a document), and as far as possible to not specify any fixed widths or heights as the content could be all sorts of things (Full fluid layout! The dream!)
So I need fluid height, full width headers and footers, and then a main panel in the middle filling the remaining vertical space, divided into columns, each of which scrolls when too high, and where the width of each non-primary column should shrink to fit its content, and a primary column which uses up the remaining space.
I am so close, but have had to resort to explicitly sizing the non-main columns - I believe that flex-basis: content; is supposed to do this but isn't supported by browsers yet.
Here's a minimal demo showing fixed size columns:

var list = document.querySelector('ul')

for (var i = 0; i < 100; i++) {
  var li = document.createElement('li')
  li.textContent = i
  list.appendChild(li)
}
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
}
main {
  display: flex;
  flex-direction: row;
  overflow: hidden;
}
main > section {
  overflow-y: auto;
  flex-basis: 10em;
  /* Would be better if it were fluid width/shrink to fit, unsupported: */
  /* flex-basis: content; */
}
main > section:last-child {
  display: flex;
  flex: auto;
  flex-direction: column;
}
main > section:last-child > textarea {
  flex: auto;
}

Heading

One

Two

Three

    <textarea></textarea>

Footer

Footer

Which looks like this - I want columns One and Two to shrink/grow to fit rather than being fixed:

My question is, is there a CSS-only workaround for flex-basis: content, or an alternative way to realise this goal?
I can possibly live with fixing the column sizes as above, or using javascript, but I HAVE A DREAM DAMN IT.

A:
I want columns One and Two to shrink/grow to fit rather than being
fixed.

Have you tried: flex-basis: auto
or this:
flex: 1 1 auto, which is short for:

*

*flex-grow: 1 (grow proportionally)

*flex-shrink: 1 (shrink proportionally)

*flex-basis: auto (initial size based on content size)

or this:
main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;
}

revised demo
Related:

*

*Make flex items take content width, not width of parent container

*Make flex container take width of content, not width 100%

A: It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.
You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:
http://jsfiddle.net/2w157dyL/1/
However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.
So the fix is very, very simple - add enough right padding to account for the scrollbar:
http://jsfiddle.net/2w157dyL/2/

  main > section {
    overflow-y: auto;
    padding-right: 2em;
  }

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!
Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help


text:
Q: Insert into select from clause causes 'cannot insert multiple rows error' I am using insert into select from clause to insert data to the table, but it doesn't work.
Please see here:
insert into STAGES_ROLES_REL
              select
                  (select stage_id
                   from
                  (select ws2.workflow_stage_id as stage_id
                         from
                        ( select ws.workflow_stage_name as workflow_stage_name
                          from   workflow_stages ws
                          join   stages_roles_rel sr
                            on   ws.workflow_stage_id = sr.workflow_stage_id ) table1
                  join workflow_stages ws2
                  on   table1.workflow_stage_name =  ws2.workflow_stage_name
                  order by ws2.workflow_stage_id))
             ,role_id
             ,current_date created_date, user created_by
             ,null modified_date, null modified_by
              from stages_roles_rel

The error is cannot insert multiple rows, but I don't know how to put filter and fetch individual row.
Thank you very much for your help!

A: My guess is that this query is returning multiple results:
select stage_id
    from (
      select ws2.workflow_stage_id as stage_id
      from (
        select ws.workflow_stage_name as workflow_stage_name
        from workflow_stages AS ws
        inner join stages_roles_rel AS sr
          on ws.workflow_stage_id = sr.workflow_stage_id
        ) AS table1
      inner join workflow_stages ws2
      on table1.workflow_stage_name =  ws2.workflow_stage_name
      order by ws2.workflow_stage_id
    )

If that's what you want (multiple rows out of that query), move your constants into that query and get rid of the outer query:
insert into STAGES_ROLES_REL
select
  stage_id,
  role_id,
  current_date AS created_date,
  user AS created_by,
  null AS modified_date,
  null AS modified_by
from (
  select ws2.workflow_stage_id as stage_id
  from (
    select ws.workflow_stage_name as workflow_stage_name
    from workflow_stages AS ws
    inner join stages_roles_rel AS sr
      on ws.workflow_stage_id = sr.workflow_stage_id
    ) AS table1
  inner join workflow_stages ws2
  on table1.workflow_stage_name =  ws2.workflow_stage_name
  order by ws2.workflow_stage_id
    )
   [add a cross join to the original table if that's what you're wanting, I don't know the intent of your original query]

Otherwise, you'll need to fix your query to only return one row.


text:
Q: Check AWS Cognito to make sure the email does not exist Hey everyone so I have the following route below. It works great however I want to be able to check AWS Cognito to make sure the users email does not already exist before I insert them into the RDS database. Is there a simple way to do this? Currently I just insert them and throw an error when they try to login to the site but I really hate that user flow and am trying to make it better. I am using nodejs and the AWS SDK.
router.post("/signup", async (req, res, next) => {
  try {
    const { username, password, plan, isDisplayOwner, optIn } = req.body;
    const bannerToken = null;
    const userAttributes = [
      {
        Name: "given_name",
        Value: req.body.firstName
      },
      {
        Name: "family_name",
        Value: req.body.lastName
      },
      {
        Name: "email",
        Value: req.body.email
      },
      {
        Name: "phone_number",
        Value: req.body.phone
      },
      {
        Name: "custom:company",
        Value: req.body.company
      }
    ];
    await cognito
      .signUp({
        ClientId: process.env.AWS_COGNITO_CLIENT_ID,
        Username: username,
        Password: password,
        UserAttributes: userAttributes
      })
      .promise();
    const dbPlanName = plan !== "FREE" ? "Braintree" : plan;

    const [[{ insertId }]] = await database.query(
      "CALL insertUser (?, ?, ?, ?)",
      [username, dbPlanName, isDisplayOwner, bannerToken]
    );

    const paramsId = {
      UserAttributes: [
        {
          Name: "custom:CE_user_id",
          Value: insertId.toString()
        }
      ],
      UserPoolId: process.env.AWS_COGNITO_USER_POOL_ID,
      Username: username
    };
    await cognito.adminUpdateUserAttributes(paramsId).promise();

    if (dbPlanName === "Braintree") {
      await database.query(
        "INSERT INTO pending_subscriptions (user_id, plan) VALUES(?,?)",
        [insertId, plan]
      );
    }

    if (optIn) {
      await database.query(
        "INSERT INTO new_email_list_opt_ins (user_id) VALUES(?)",
        insertId
      );
    }

    res.send("Signup completed. Confirm account.");
  } catch (error) {
    error.status = 409;
    next(error);
  }
});

A: Hey Everyone here was my solution to search to see if the user exists in cognito. You simply use the listUsers function from the AWS SDK. Note it does not return a boolean but you can just do emailExists.Users.length and if the length is greater than 0 the email already exists.
    const emailParams =
    {
        AttributesToGet: [],
        Filter: 'email = "' + req.body.email + '"',
        UserPoolId: process.env.AWS_COGNITO_USER_POOL_ID
    };
    const emailExists = await cognito.listUsers(emailParams).promise()
    if(emailExists.Users.length>0){
        //user exists
        throw "user exists"
    } else {
        // user does not exist
    }


text:
Q: How to put exclude rule if property value contains specific value in search results In share point we have top right corner search box. From that results, I need to add rule for exclude peoples those have profile property value = "1". Per example
urn:schemas-microsoft-com:sharepoint:portal:profile:WebEnabled

WebEnabled is the SSP profile property. Now results are pulling all users those have property value "0" or "1". Now I need exclude profile those have WebEnabled =1 value.
I added rule in scope. I don't know. How to set value for that.
contentclass = urn:schemas-microsoft-com:sharepoint:portal:profile:WebEnabled

Please let me know, How to do this?. Thanks in advance

A: On the Add a Scope Rule page you'll find this text

Enter the property restriction as a comparison of property to a value. All items matching the property query will be added to the scope. To make additional properties available for use in scopes, navigate to the managed properties list and select "Allow this property to be used in scopes" for the desired managed propertes.

So you'll need to find what Managed Property that belongs to and flip that bit so that you can use it in your scope rule.


text:
Q: Percent-format strings with named keys don't accept hashes with string keys? I am using the percent string formatting like so:
'fetching imap (%<host>s/%<user>s port=%<port>s...' % options

This works fine when the options hash has symbol keys { host: 'example.com' }, but raises a KeyError when it has string keys { 'host' => 'example.com' }:
KeyError: key<host> not found

This is problematic because Rails' HashWithIndifferentAccess uses string keys by default. If using ActiveSupport, one solution is to call symbolize_keys on the hash.
Is there an alternative way to make the String#% method try string keys as well as symbol keys?
Is this a bug in Ruby that deserves a bug report? Or are there reasons for enforcing this behavior, like the edge case where both :host and 'host' keys exist?

A: It's not a bug that Ruby doesn't treat strings and symbols interchangeably; as you note, you're using Rails' HashWithIndifferentAccess, which exists exactly because Ruby regularly considers strings and symbols unrelated.
This is a similar situation to keyword arguments, which also do not allow string-keyed hashes.
At best, you could try to argue that sprintf should use the ruby-level accessors methods ([] or fetch), which HashWithIndifferentAccess overrides, instead of directly doing the C-level rb_hash_lookup2.
Alternatively, Rails might be able to make this work by partly restoring the default behaviour that existed between c918a3a0691 and a218a35e660.

A:
I am using the percent string formatting … This works fine when the options hash has symbol keys … but raises a KeyError when it has string keys
If using ActiveSupport [from Rails], one solution is to call symbolize_keys on the hash.

For a solution without Rails you can use:
options = options.transform_keys(&:to_sym)

or
options.transform_keys!(&:to_sym)

See the manual. This requires Ruby 2.5.0 or higher, though. For more options, also for earlier Ruby versions, see this related question.


text:
Q: How to put required validation in javascript innerhtml input box function edit_row(id)
{
    document.getElementById("monthly_val"+id).innerHTML="<input type='text' id='monthly_text"+id+"' value='"+monthly+"' onkeyup='this.value=Comma(this.value)' 'required'>";
}

The above code is an example of my input field and i want to put required validation so that the data will not be saved when the field is empty.

A: if you have textbox id then you can easily find and then you can check input empty or not. you need use this process before saving data.
 document.getElementById("monthly_val" + id).innerHTML = "<input type='text' id='monthly_text" + id + "' value='" + monthly + "' onkeyup='this.value=Comma(this.value)'>";
if ($('#monthly_text' + id + '').val() == '') { alert('wala'); }

use this. it helps you

A: Try this...
var a = document.getElementById("monthly"+id),
b = document.createElement("INPUT");
b.setAttribute("pattern", "regexp string");
b.setAttribute("formnovalidate", " false");
b.setAttribute("type", "text");
//add other attributes
a.appendChild(b);

/*
Just replace the regexp string*/


text:
Q: What does x=x[class_id] do when used on NumPy arrays I am learning Python and solving a machine learning problem.
class_ids=np.arange(self.x.shape[0])
np.random.shuffle(class_ids)
self.x=self.x[class_ids]

This is a shuffle function in NumPy but I can't understand what self.x=self.x[class_ids] means. because I think it gives the value of the array to a variable.

A: It's a very complicated way to shuffle the first dimension of your self.x. For example:
>>> x = np.array([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> x
array([[1, 1],
       [2, 2],
       [3, 3],
       [4, 4],
       [5, 5]])

Then using the mentioned approach
>>> class_ids=np.arange(x.shape[0])  # create an array [0, 1, 2, 3, 4]
>>> np.random.shuffle(class_ids)     # shuffle the array
>>> x[class_ids]                     # use integer array indexing to shuffle x
array([[5, 5],
       [3, 3],
       [1, 1],
       [4, 4],
       [2, 2]])

Note that the same could be achieved just by using np.random.shuffle because the docstring explicitly mentions:

This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.

>>> np.random.shuffle(x)
>>> x
array([[5, 5],
       [3, 3],
       [1, 1],
       [2, 2],
       [4, 4]])

or by using np.random.permutation:
>>> class_ids = np.random.permutation(x.shape[0])  # shuffle the first dimensions indices
>>> x[class_ids]
array([[2, 2],
       [4, 4],
       [3, 3],
       [5, 5],
       [1, 1]])

A: Assuming self.x is a numpy array:
class_ids is a 1-d numpy array that is being used as an integer array index in the expression: x[class_ids].  Because the previous line shuffled class_ids, x[class_ids] evaluates to self.x shuffled by rows.
The assignment self.x=self.x[class_ids] assigns the shuffled array to self.x


text:
Q: How to Edit the Pub/Sub url after publishing the application We published the wrong Pub/Sub url by mistake. How can we edit the Pub/Sub url after publishing the application?

A: To change a URL for a published app, please email apisupport @ jawbone.com for assistance.
When an app is published, any UP user can connect to that app. For this reason, Jawbone chooses to err on the side of security for the user's data and requires a manual review of any app changes.


text:
Q: GDI+ gif speed problem I am using C++ GDI+ to open a gif
however I find the frame interval is really strange.
It is different from played it by window's pic viewer.
The code I written is as follow.
pMultiPageImg = new Bitmap(XXXXX);
int size = m_pMultiPageImg->GetPropertyItemSize(PropertyTagFrameDelay);
m_pTimeDelays = (PropertyItem*) malloc (size);
m_pMultiPageImg->GetPropertyItem(PropertyTagFrameDelay, size, m_pTimeDelays);
int frameSize =  m_pMultiPageImg->GetFrameDimensionsCount();();

// the interal of frame FrameNumber:
long lPause = ((long*)m_pTimeDelays->value)[FrameNumber] * 10;

however I found some frame the lPause <= 0.
What does this mean?
And are code I listed right for get the interval?
Many thanks!

A: The frame duration field in the gif header is only two bytes long (interpreted as 100ths of a second - allowing values from 0 to 32.768 seconds).
You seem to be interpreting it as long, which is probably 4 bytes on your platform so you will be reading another field along with the duration. It is hard to tell from the code you provide, but I think this is the problem.

A: Frame delays should not be negative numbers. I think the error comes in during the array type conversion or "FrameNumber" goes out of bounds.

*

*GetPropertyItemSize(PropertyTagFrameDelay) returns a native byte array. It'll be safer to convert it to an Int32 array instead of a "long" array. "long" is always 4 bytes long under 32-bit systems, but could be 8 bytes under some 64-bit systems.

*m_pMultiPageImg->GetFrameDimensionsCount() returns the number of frame dimensions in the image, not the number of frames. The dimension of the first frame (master image) is usually used in order to get the frame count.

In your case, the code looks like
int count = m_pMultiPageImg->GetFrameDimensionsCount();
GUID* dimensionIDs = new GUID[count];
m_pMultiPageImg->GetFrameDimensionsList(dimensionIDs, count);
int frameCount = m_pMultiPageImg->GetFrameCount(&m_pDimensionIDs[0]);

Hope this helps.


text:
Q: Export menu and tooltips for Toast UI Chart not working Is Toast UI Chart compatible with Angular? I followed the instructions to set it up and copy & pasted one of their examples, but the tooltips and export menu aren't working. Here is what I get:

The export menu is for some reason at the bottom, overflowing the container, and an unstyled list that doesn't actually do anything. When hovering over the graph, nothing happens (there should be tooltips popping up). Toggling lines via the legend works, so it's not like the entire thing is broken. I am using Angular 9 and version 3.11.2 of tui-chart.
I'm also curious how to hide/remove the entire legend. I couldn't find anything about that in the docs.

A: Check your project's main css file.
Need to import "~tui-chart/dist/tui-chart.css" there.


text:
Q: Why does using regex in Mongodb query causes it to scan all documents instead of index? While I was trying to investigate performance issue with queries, I found that the source was this query. I am using Rails 4 with Mongoid gem.
Order.where("customer.email" => /\Atest@email.com\z/i) where test@email.com is just an example.
Customer is an embedded document in Order document and customer's email is indexed.
When I benchmarked performance using Benchmark.bmbm where Order.where("customer.email" => /\Atest@email.com\z/i).count was repeated 100 times, I got the following result.
       user     system      total        real
   0.090000   0.010000   0.100000 ( 27.656723)

I thought perhaps \A and \z was causing the slowness, so I tried the following where it looks for emails that start with given argument: Order.where("customer.email" => /^test/i).count
And result wasn't much different.
       user     system      total        real
   0.090000   0.010000   0.100000 ( 28.712883)

As the last resort, I tried just matching the entire string without regexp. This time, it made a huge difference: Order.where("customer.email" => "test@email.com").count
       user     system      total        real
   0.080000   0.000000   0.080000 (  0.122888)

When I looked at output of explain, it shows that using regexp scans all documents.
{
                     "cursor" => "BtreeCursor customer.email_1",
                 "isMultiKey" => false,
                          "n" => 781,
            "nscannedObjects" => 781,
                   "nscanned" => 500000,
    "nscannedObjectsAllPlans" => 781,
           "nscannedAllPlans" => 500000,
               "scanAndOrder" => false,
                  "indexOnly" => false,
                    "nYields" => 1397,
                "nChunkSkips" => 0,
                     "millis" => 406,
            "indexBounds" => {
    "customer.email" => [
        [0] [
            [0] "",
            [1] {}
        ],
        [1] [
            [0] /test/i,
            [1] /test/i
        ]
    ]
  }
}

While using entire string only scanned subset, which was what I expected.
{
                     "cursor" => "BtreeCursor customer.email_1",
                 "isMultiKey" => false,
                          "n" => 230,
            "nscannedObjects" => 230,
                   "nscanned" => 230,
    "nscannedObjectsAllPlans" => 230,
           "nscannedAllPlans" => 230,
               "scanAndOrder" => false,
                  "indexOnly" => false,
                    "nYields" => 1,
                "nChunkSkips" => 0,
                     "millis" => 0,
            "indexBounds" => {
    "customer.email" => [
        [0] [
            [0] "test@email.com",
            [1] "test@email.com"
        ]
    ]
  }
}

Can someone please explain to me why using regexp in mongodb query causes it to scan all documents instead of index?
EDIT: Added indexBounds in the explain output, which was omitted in the original post.

A: The quick version:
You have a case-insensitive regex here (the /i flag); that means that Mongo can't do prefix matching on the index, and thus has to scan the entire index (since it doesn't know if you want test@example.com or TEST@example.com or teST@exAMple.com or whatnot).
If you want case-insensitive lookups in Mongo, the correct solution is to downcase them prior to storage. If you need to not affect the user-entered input, then store it in a secondary field on the document (ie, email and email_normalized).
The longer version
Mongo's indexes are B-Trees, and when you perform a regex query, it will see a) if it can use an index (by field) and b) how much of that tree it has to scan to be assured of a result. In the case where you have a specific prefix, Mongo knows that it can limit its search to only a portion of the tree. You left out the most important part of your explains - the index bounds. Given a collection with an index and some emails:
kerrigan:PRIMARY> db.test.ensureIndex({email: 1})
kerrigan:PRIMARY> db.test.insert({email: "test@example.com"})
kerrigan:PRIMARY> db.test.insert({email: "teTE@example.com"})
kerrigan:PRIMARY> db.test.insert({email: "teST@example.com"})
kerrigan:PRIMARY> db.test.insert({email: "TEst@example.com"})

If we explain the find on a non-case-insensitive match:
kerrigan:PRIMARY> db.test.find({email: /\Atest@example.com\z/}).explain()
{
        "cursor" : "IndexCursor email_1 multi",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "email" : [
                        [
                                "test@example",
                                "test@examplf"
                        ],
                        [
                                /\Atest@example.com\z/,
                                /\Atest@example.com\z/
                        ]
                ]
        },
        "server" : "luna:27019"
}

You'll see that it only has to scan one document, and that the scan upper and lower bounds are well-defined ("test@example".."test@examplf"). This is because Mongo looks at the prefix and says "That explicit prefix is guaranteed to be in every matching result", and thus knows that it can limit the portion of the index that it has to scan.
If we add the /i flag though:
kerrigan:PRIMARY> db.test.find({email: /\Atest@example.com\z/i}).explain()
{
        "cursor" : "IndexCursor email_1 multi",
        "isMultiKey" : false,
        "n" : 3,
        "nscannedObjects" : 3,
        "nscanned" : 4,
        "nscannedObjectsAllPlans" : 3,
        "nscannedAllPlans" : 4,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "email" : [
                        [
                                "",
                                {

                                }
                        ],
                        [
                                /\Atest@example.com\z/i,
                                /\Atest@example.com\z/i
                        ]
                ]
        },
        "server" : "luna:27019"
}

Suddenly those index bounds are "".."", or a full index scan; because there's no guaranteed static prefix for the field, Mongo has to scan and check each value in the index to see if it matches your provided regex.


text:
Q: Problem in complex analysis involving Liouville's Theorem Let $f:\mathbb{C}\rightarrow \mathbb{C}$, $f$ bounded and $a,b \in \mathbb{C}$ ($a\neq b$). For $R>max(|a|,|b|)$ we have $I_{n}=\displaystyle\int_{|z|=R}\frac{f(z)}{(z-a)(z-b)}dz$. Calculate $I_{n}$ and the limit $\lim_{R\rightarrow \infty}I_{n}$

*

*My thoughts
First I used Liouville's theorem since its bounded when  $f:\mathbb{C}\rightarrow \mathbb{C}$ so $f(z)\equiv constant$. Then I wrote that since $a,b\notin D(r,R)$ there are no anomalies in the Integral. So can i declare $\frac{f(z)}{(z-a)(z-b)}$ holomorphic in this Disc and say that the $I_{n}=0$?

A: My guess is that the goal of the exercise is to prove Liouville's theorem. The residue if $\frac{f(z)}{(z-a)(z-b)}$ at $a$ and $b$ is $\frac{f(a)}{a-b}$ and $\frac{f(b)}{b-a}$ respectively. Therefore,$$I_n=2\pi i\left(\frac{f(a)}{a-b}+\frac{f(b)}{b-a}\right)=2\pi i\frac{f(b)-f(a)}{b-a}.$$On the other hand, $\lim_{R\to+\infty}I_n=0$. Therefore$$(\forall a,b\in\mathbb{C}):f(a)=f(b),$$which means that $f$ is constant.


text:
Q: Why mysqli_escape_string() adds backslash in database ? (PHP 7.4) I'm trying to put strings containing single and double quotes in my database but when I use mysqli_escape_string() on it before, it adds backslashes. If I am not mistaken, normally once in the database there should no longer be backslashes ?
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) die('Database error : '.$conn->connect_error);

$strValue = mysqli_escape_string($conn,"a'b");

$sql = "INSERT INTO test (strValue) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $strValue);
$stmt->execute();

// a'b becomes a\'b in database


text:
Q: Acessar índice negativo de um array BUG?
Estava construindo uma biblioteca para tratamento de Arrays e me deparei com a seguinte situação: Ao incluir um valor à um índice negativo dentro do meu Array, este índice não aparece ao utilizar alguns métodos:
Exemplo:
var array = new Array("Maria", "João", "Carlos");
array[-3] = "Bernardo";

console.log(array[-3]); //Bernardo
console.log(array.length); //3
console.log(JSON.stringify(array)); //"["Maria", "João", "Carlos"]"

Note-se que a quantidade continua como 3 ao utilizar length e o método JSON.stringify mostra apenas os 3 originais, porém, ao exibir no console o array[-3] o nome vem corretamente.
Pergunta:
O correto não seria aparecer length = 4 e aparecer no método JSON.stringify? Porque isso ocorre? Seria algum tipo de bug a linguagem me permitir adicionar um valor à um índice negativo?

A: Em ECMAScript (base do JavaScript e ActionScript) arrays não são "especiais" de nenhuma forma: são apenas um objeto normal com um atributo length. Isso significa que:

*

*Internamente, suas chaves são strings, não inteiros:
var arr = [10, 20, 30];
console.log(arr[0]);   // 10
console.log(arr["0"]); // também 10

*Pode-se adicionar qualquer propriedade adicional que você quiser:
var arr = [10, 20, 30];
arr.teste = 42;
console.log(arr.teste);    // 42
console.log(arr["teste"]); // 42

Em geral, objetos que possuem o tipo Array se encarregam de atualizar seu length conforme propriedades numéricas (não negativas) são adicionadas. Isso ocorre independentemente delas serem adicionadas com o push, com um índice numérico ou com um índice string:
var arr = [];  // length: 0
arr.push(10);  // length: 1
arr[1] = 20;   // length: 2
arr["2"] = 30; // length: 3
arr[10] = null; // length: 11

Mas se você adiciona outras propriedades, de qualquer tipo, ele considera que isso é apenas uma propriedade "normal" - que não tem nada a ver com arrays - e não mexe no length:
arr.foo = "bar"; // length: 11
arr["foo"] = 42; // length: 11
arr["+"] = 9001; // length: 11
arr["-3"] = 123; // length: 11

É por isso que se pode acrescentar elementos num "índice negativo": pois o ECMAScript não considera isso como um "índice", mas apenas como uma propriedade normal.
Exemplos no jsFiddle. No console do Chrome, ele mostra não só os índices posicionados mas também as propriedades "avulsas". Ex.: [10, 20, 30, 10:null, foo:"bar"]

A: Arrays em Javascript não possuem índices negativos.
O que acontece aqui é que você está criando uma nova propriedade no objeto Array, de nome "-3".
Acontece a mesma coisa se você utilizar uma palavra. Por exemplo:
var v = new Array("abra", "cadabra", "alacazan");
v["-5"] = "isto não é um índice";
v["banana"] = "muito menos isto";
v[-7] = "nem isto";

v.length // 3
v["-5"] // "isto não é um ndice"
v.banana // "muito menos isto"
v["banana"] // "muito menos isto"
v["-7"] // "nem isto"

A: Eu achei a resposta do @mgibsonbr correta, mas um pouco confusa. Vou deixar minha contribuição, uma tradução e adaptação de uma resposta do SOEn, que deixa mais evidente para os burricos do JavaScript como eu. >.<

Quando se referencia diretamente um índice ou posição, os valores são adicionados ao array:
var array = [];

array[0] = "Foo";
array[1] = "Bar";

// Result: ["Foo", "Bar"]
// Length: 2

O que não é o caso quando referenciando índices negativos:
var array = [];

array[0]  = "Foo";
array[1]  = "Bar";
array[-1] = "Fizzbuzz"; // Índice inválido - Pega, Rex! Pega!

// Result: ["Foo", "Bar"]
// Length: 2

Os valores somente serão adicionados se você brincar de acordo com as regras. Se não seguí-las, os valores não vão ser adicionados. Simples assim!
Mas apesar de não serem aceitas como parte do conjunto de dados, as informações associadas à indíces negativos são aceitas pelo objeto Array e, por isso ainda é possível acessar esse valor, como qualquer outra propriedade:
array[-1]; // "Fizzbuzz"

Quando construímos um objeto Array, mesmo que não tenhamos definido nenhum valor para ele, ele não está vazio, afinal, todos os métodos pertencentes ao objeto, sejam eles nativos ou prototipados já estão lá a disposição e podem, inclusive, ser acessados da mesma forma:
array["pop"]; // function pop() { [native code] }

Aqui acessamos o índice prop que não é um índice válido para o cojunto de dados, mas é válido como propriedade do objeto Array e está associado o código nativo Array.pop().
E por isso propriedade como length e métodos como Array.prototype.pop() ou Array.prototype.slice(), que trabalham unicamente com índices inteiros e positivos mostram resultados diferentes do que você espera.
Mais uma vez, pra reforçar. O valor não está no array e sim no objeto Array.


text:
Q: How to collect custom metrics from Spark based application I have a Spark (java) based application which scans few tables in Hive and then based on some condition, it gives a list of table/partitions which satisfy the condition.
I want to know how I can collect information regarding this scan?
For eg: How much time it took the application to perform the scan of different tables? How much memory was being used while performing the scan? etc.
I know i can use simple stopwatch for time calculation and print them to the log. But i do not want them to print into logs. I want to push the to a custom Kafka producer that i have created.

*

*I looked into using spark listener and extending them: https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.scheduler.SparkListener
But these are based on spark specific events(onJobStart, onJobEnd, etc.). I want to trigger my listener on business specific events. For eg: onTableRead, onSpecificMethodCall

2)https://github.com/groupon/spark-metrics
I had a look at this library and it is quite simple to use. But the problem here I am facing is that my Spark application is java based.
In the spark-metrics documentation, they have mentioned the metrics should be initialized as lazy vals to get correct data.
public List getFilteredPartList(){
List<String> fileteredPartitions = utils.getPartNames(getTable().getDbName(), getTable().getTableName(),getConfiguration().getEnvCode(), partNames,
getTableProperties(), getDataAccessManager(), true, true, false, true).getPartNames()};

I want to know the time taken for the execution of above method and push it to my custom Kafka producer.


text:
Q: Which Android Target supports Safari or Google Chrome? I'm trying to run an app on an Android Emulator and in the current Target I'm using the animations stop working - but I think it's just because neither Safari nor Google Chrome aren't supported in the target I'm using (it's 4.1.2). Is there a target which does support either of these?
Thanks a lot in advance xxx

A: according to the Google chrome specification it will work on android 4.0 and above so you should try it on mobile.


text:
Q: The proper way to manage a Google Drive account using Java console application? I have enabled Google Drive API on Google Developer Console and created a service account credential which is bundled with a service account ID and key ID. Despite that I have tried various ways to manage my own Google Drive account, I could not find a solution which fits for my aim. I need to upload, download and delete the files stored in my own Google Drive. The application that I am going to connect Google Drive is a console one which will be solely used for an academic research.

A: it's pretty simple. The steps to achieve this are at How do I authorise an app (web or installed) without user intervention? (canonical ?)
Be careful about how securely the refresh token is being stored and what scopes you grant to the app.


text:
Q: Angular 4 - Added non-passive event listener to a scroll-blocking 'mousewheel' event. In my Angular 4 Project I get the following warning when I click on a date-picker or a select-option menu, running it in Google Chrome:

[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.

I already saw an issue here on stack-overflow but that one was about 'touchstart',  not 'mousewheel'. I don't really know what Code-examples I could give you because I don't know where the warning comes from.
Can anybody help me with this issue?

A: What is a passive event?

Passive event listeners are a new feature in the DOM spec that enable developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners. Developers can annotate touch and wheel listeners with {passive: true} to indicate that they will never invoke preventDefault. This feature shipped in Chrome 51, Firefox 49 and landed in WebKit. Reference.

Chrome throws the warning ...
[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive.

...when you bind to mouse scroll events, to essentially warn that you may have inhibited scroll performance in your event or disabled default events by making a call to preventDefault().
Chrome also throws the error when you try and still call preventDefault() in a passive event.
Unable to preventDefault inside passive event listener invocation.

Firefox has a similar error for this, however does not seem to throw a warning like Chrome:
Ignoring 'preventDefault()' call on event of type 'wheel' from a listener registered as 'passive'.

Warning showcase
Run the following snippet and view the Chrome console in Verbose mode.

// WILL throw violation
document.addEventListener("wheel", function(e) {
  e.preventDefault(); // prevents default browser functionality
});

// will NOT throw violation
document.addEventListener("wheel", function(e) {
  e.preventDefault(); // does nothing since the listener is passive
}, {
  passive: true
});

Resolving the issue
A similar SO post was made about the implications of this in javascript.

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault() to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

Angular has not yet implemented a generic / ease of use solution for this and can be followed here.
However due to the fact that typescript is compiled to javascript, implementing the above snippet in typescript should still negate the violation.

Performance Impacts
The violation itself is not at all harmful to application performance, however the contents of your event function could be - and thus is why Chrome throws this warning. Note that this warning is only shown in Verbose console mode and will not be shown to general users.
As far as I am aware, there is no way to disable such warnings as they are generated by Chrome's interpretation of the code at run time.

A: Many libraries and frameworks add non-passive event listeners by default. Not much you can do about it.. Instead of waiting for a support I Would recommend using highly flexible and configurable passive-events-support package to debug and make event listeners passive without touching 3rd party source code.
First, after installing the package debug the touch and wheel event listeners and their parameters:
import { passiveSupport } from 'passive-events-support/src/utils'
passiveSupport({ debug: true })

This should console log all the event listeners
[Passive Events Support] Non-passive Event Listener
  element: div.some-element
  event: 'mousewheel'
  handler:
    fn: ƒ (e)
    fnArgument: 'e'
    fnContent: 'console.log(e)'
    fnPrevented: false
  arguments: false

Notice arguments parameter, if it is false, undefined or object without passive parameter inside, this event is what causes your browser to throw a warning and is impacting the scroll performance.
To fix it just use the package and logged information to make this exact event listener as passive:
import { passiveSupport } from 'passive-events-support/src/utils'
passiveSupport({
  debug: false,
  // add this one
  listeners: [
    {
      element: 'div.some-element',
      event: 'mousewheel'
    }
  ]
})

Be careful tho, event listeners that call preventDefault() should not be marked as passive, but to fix the warning should still have passive parameter with a value of false instead.
By default the package will check if it is prevented from the handler itself, but in case the event listener is prevented from the method called inside the handler, the package loses track of it. To force assign passive: false just pass prevented: true parameter to listeners item:
passiveSupport({
  //...
  listeners: [
    {
      element: 'div.some-element',
      event: 'mousewheel',
      prevented: true
    }
  ]
})

For me, this package fixed all the warnings cause by materialize and jquery. Hope it helps you too.


text:
Q: Back one item before in a for loop after a certain condition is meet I am working with selenium and inside my function I have to do some operations several times, the point here is when I get 40 iterations on that page, the selenium breaks and I need to restart the function. I've already solved this by putting a count variable that when a certain number of iterations are met, selenium will close the controller and reopen it, but here's the problem, when this happens, the element in the for loop where the count variable meets the condition is not taken when selenium is restarted, this goes to next item in my list.
Here is my code:
import os
import time
from selenium import webdriver

def prueba(n=2):

    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_experimental_option('useAutomationExtension', False)
    chromeOptions.add_argument('log-level=3')
    chromeOptions.add_argument('--ignore-certificate-errors')
    prefs = {"download.default_directory": os.getcwd(),
                  "directory_upgrade": True}
    chromeOptions.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities(),executable_path='/Users/kev/Documents/Proyectos/Selenium/chromedriver')
    driver.get("https://www.google.com.mx/")

    count = 0

    for i in ['a', 'b', 'c', 'd']:
        if count < n:
            if i == 'a':
                try:
                    driver.get("https://www.youtube.com")
                    print('a')
                    time.sleep(1)
                except Exception as e:
                    print(e)
            elif i == 'b':
                try:
                    driver.get("https://www.facebook.com")
                    print('b')
                    time.sleep(1)
                except Exception as e:
                    print(e)
            elif i == 'c':
                try:
                    driver.get("https://www.twitter.com")
                    print('c')
                    time.sleep(1)
                except Exception as e:
                    print(e)
            else:
                try:
                    driver.get("https://www.instagram.com")
                    print('d')
                    time.sleep(1)
                except Exception as e:
                    print(e)

            count+=1
            print(count)

        else:
            count = 0
            driver.close()
            print('Esperando 5 segundos...')
            time.sleep(2)
            driver = webdriver.Chrome(chrome_options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities(),executable_path='/Users/kev/Documents/Proyectos/Selenium/chromedriver')
            driver.get("https://www.google.com.mx/")
            continue

prueba()

So here when I run my function everything works fine but when i = 'c' the count variable is meet, here the function passes to the else statement resetting the count variable and the Selenium, and when starts again it goes directly into 'd' instead of continue with 'c'

A: Your logic doesn't seem to be correct. The for loop you define is hard set at doing four iterations ['a', 'b', 'c', 'd']. With each iteration, it adds 1 to the count. When it gets to 'c', the 3rd iteration, the count is 2. So it fails the first conditional.
Instead, you should specify either a nested for loop:
n = 2
for _ in range(n):
    for i in ['a', 'b', 'c', 'd']:
        # Do Stuff

Or use a while loop with a counter.
n = 2
counter = 0
while counter < n:
   for i in ['a', 'b', 'c', 'd']:
        # Do Stuff
   counter +=1


text:
Q: How to display the cart value individual? I am using the CodeIgniter shopping cart. I am fetching the product data using ajax.
Now in my ajax success
Fetching data
    public function viewPrimaryCart()
     {

      $output = '';
      $count = 0;
      foreach($this->cart->contents() as $items)
      {
       $count++;
       $output .= '

    '.$items["name"].'
    '.$items["qty"].'
    '.$items["price"].'
    '.$items["subtotal"].'

   ';
      }
      if($count == 0)
      {
       $output = '
Nothing selected yet
';
      }
      return $output;

    }

Ajax
$.ajax({
    url:"<?php echo base_url(); ?>Member_controller/primaryMemberCart",
    method:"POST",
    data:{product_id:product_id, product_name:product_name, product_price:product_price,quantity:quantity},
    success:function(data)
    {
      alert(data);
     //alert("Product Added into Cart");
     $('#primarycart_details').html(data);
    }
   });

I  want to know how to display the cart data individual? I mean I have to get the quantity and pass to my jquery.
I tried
alert(data.qty),alert(data['qty']),alert(data[0]).

what is the correct way to display?
I refer this link for cart https://www.webslesson.info/2017/03/ajax-jquery-codeigniter-shopping-cart.html
Would you help me out on this issue?

A: it gonna be little complex
Your dataType: "json" tells jQuery that you want it to parse the returned JSON, it does not mean that jQuery will automatically stringify your request data.
use
dataType: "json"

And udpate your view() function like store whole view in one array like
$array  = ('view'=>'your_html_view_code','name'=>$items['name'],'name'=>$qty['qty'])

and send to response by encoding via json_encode()
And get values by response.name

A: Just add a class on the td quantity
$output .= '

        '.$items["name"].'
        '.$items["qty"].'
        '.$items["price"].'
        '.$items["subtotal"].'

       ';

Then u can get the value with jquery
$('.quantity').innerHTML();

A: success: function(data){
    var obj = JSON.parse(data); // add this part
    alert(obj.qty);
}

A: Finally, I found my answer. I tried below code and it's working for me.
Controller
public function viewPrimaryCart()
 {
  $output = '';
  $count = 0;
  foreach($this->cart->contents() as $items)
  {
   $count++;
   $output = array('qty' =>$items["qty"],'subtotal'=>$items["subtotal"] );
  }
  if($count == 0)
  {
   $output = '
Nothing selected yet
';
  }

 echo json_encode($output);
 exit();
}

Ajax success
 success:function(data)
    {
        var obj = JSON.parse(data);
       alert(obj.qty);
       alert(obj.subtotal);
    }