text:
Q: Error: operand size mismatch for `movq' I'm trying to compile the following assembly...
movq $0x3534373536383235, 0x000000000055638f8
movq $0x55638f8, %rdi
retq

The first line throws the error Error: operand size mismatch for 'movq'
Which doesn't make sense to me, because they are both 8 byte numbers.
I did a little research and movabsq was recommended, like so...
movabsq $0x3534373536383235, 0x000000000055638f8
movq $0x55638f8, %rdi
retq

But this throws the error: Error: operand size mismatch for 'movabs'
What am I missing?
Here's the entire error from my mac
level3.s:1:27: error: invalid operand for instruction
movq $0x3534373536383235, 0x000000000055638f8
                          ^~~~~~~~~~~~~~~~~~~

A: If you look in the manual under the lemma MOV (which is, admittedly, a bit intimidating), you will find that there is no mov r/m64, imm64.
There's a way to load a full 64bit constant into a register, and there's a way to load a sign-extended 32bit constant into a 64bit memory location, but there is no single instruction that takes a 64bit immediate and writes it to memory.
So you have to do it in two steps, such as by using a temporary register or by writing two dwords straight to memory separately.

A: One way to do it is:
movabsq  $0x3534373536383235, %rax
movabsq  %rax, 0x000000000055638f8

As the other comment says, you can't move a 64 bit immediate to a 64 bit memory address because there is no instruction that allows you to do this.  This opcode is missing because opcodes cannot currently exceed 15 bytes, and the two 64 bit values alone are 16 bytes, and would have to be part of the opcode.  This limitation applies to smaller opcodes that would become too large with prefixes as well.  Because you are moving to an absolute 64 bit memory address, you will want to use movabs or movabsq, whichever your assembler likes.


text:
Q: Unhandled Rejection (TypeError): Cannot read property 'value' of undefined error for const city I am getting error in const city Unhandled Rejection (TypeError): Cannot read property 'value' of undefined
handleClick = async(e) => {
    e.preventDefault();
    const city = e.target.elements.city.value;
    const api=await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=563f12881628bc03a04f230c259dd4f9`);
    const rtr = await api.json();
   this.setState({
     temperature:rtr.main.temp,
     humidity:rtr.main.humidity,
     city:rtr.name,
     country:rtr.sys.country
   });
  }

expected to fetch city by api calling

A: You should add if statements to check if the city exists.
handleClick = async(e) => {
    e.preventDefault();
    const city = !!e.target.elements.city && e.target.elements.city.value;
    if (!city) {
      return;
    }

    const api=await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=563f12881628bc03a04f230c259dd4f9`);
    const rtr = await api.json();
   this.setState({
     temperature:rtr.main.temp,
     humidity:rtr.main.humidity,
     city:rtr.name,
     country:rtr.sys.country
   });
  }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Threads produce same random number? I am trying to produce random numbers for each thread to use, but all the threads produce the same number.
The number changes when I run my program each time, but all the threads produce the same number for a given run.
What should I do to produce different random numbers for each thread?
void *Customer(void *customer_id)
{
    unsigned int iseed = (unsigned int)time(NULL);
    srand (iseed);
    int rastgele = rand() % 3 + 1;
    int *id_ptr,customer_idd;
    id_ptr=(int *) customer_id;
    customer_idd=*id_ptr;

    printf("This is thread : %d  %d \n",customer_idd,rastgele);
    pthread_exit(NULL);
}

A: Seeding the random number generator with the time will give you the same random number if the threads produce a random number at the same second. You could just seed with the time plus the thread number or something like that.
Or, as Dave suggested, you could just seed once outside the thread.

A: You shouldn't use rand for pseudo random generation in connection with threads. This function uses a shared state that is common to all threads. This creates dependencies between the PRN drawn by the threads and slows down substantially since the access to the state must be mutexted.
Alternatives on POSIX systems would be nrand48 and jrand48 that receive a state (that should be thread specific) as their argument. As others said, seeding that state just with a time value is not a good idea, threads may do that at the same moment.


text:
Q: Bindable data source with arbitary number of columns I need to display data with a fixed number of rows and a user changeable number of columns (time series of data). I'm not sure what type I should use as a data source. A 2d array is possible, but I'd prefer something fully supported by .NET Framework.

A: How about datatable. I think that is more flexible when your columns are changing and rows are going to be same.


text:
Q: gdm session without setting default I have a locally created session to let users login to a special session at times (i've called it /usr/share/xsessions/remote.desktop). The problem is that they normally login to gnome (/usr/share/xsessions/gnome.desktop) and get annoyed after logging in to the remote session and finding that is the default choice next time they login.
I would like my session to work a little like the failsafe gnome-session by not being the default session next time the user log in. Is it possible to configure a session to not set default session?


text:
Q: AWS EC2 - Get EBS Volume information Is there a way/method in the EC2/AWS API such that I can get the EBS volume that is attached to a particular EC2 instance?
IE:
I just want something that allows me to do something along the lines of:
method(instance_id) - returns the EBS volume that this particular instance_id is attached to.

A: Yes, you can use the describe-instances command from the AWS CLI.
An example:
aws ec2 describe-instances --query 'Reservations[*].Instances[?InstanceId==`i-058aba2af1c14e93e`].BlockDeviceMappings[*]'

A: If you know your instance ID, you can use CLI command:
aws ec2 describe-volumes \
    --region us-east-1 \
    --filters Name=attachment.instance-id,Values=i-08e0325f9e7218a02

where Values is my instance ID.
The answer looks like:
{
    "Volumes": [
        {
            "Attachments": [
                {
                    "AttachTime": "2023-02-28T23:44:46+00:00",
                    "Device": "/dev/xvda",
                    "InstanceId": "i-08e0325f9e7218a02",
                    "State": "attached",
                    "VolumeId": "vol-087d2d787f60de5d8",
                    "DeleteOnTermination": true
                }
            ],
            "AvailabilityZone": "us-east-1b",
            "CreateTime": "2023-02-28T23:44:46.880000+00:00",
            "Encrypted": false,
            "Size": 8,
            "SnapshotId": "snap-0d521a3c01cf13eee",
            "State": "in-use",
            "VolumeId": "vol-087d2d787f60de5d8",
            "Iops": 100,
            "VolumeType": "gp2",
            "MultiAttachEnabled": false
        }
    ]
}


text:
Q: Can i delete a message in kafka server if it is unconsumed? If I have the message id, is it possible for a client to delete a kafka message which is on a topic and is not still consumed by a consumer.

A: No, it is generally not possible (for a client) to delete an individual message out of a Kafka topic.
Removing messages from a Kafka topic is managed through the topic level configuration cleanup.policy. According to the documentation:

A string that is either "delete" or "compact". This string designates the retention policy to use on old log segments. The default policy ("delete") will discard old segments when their retention time or size limit has been reached. The "compact" setting will enable log compaction on the topic.

The "delete" mode is based on a time or byte size limit whereas the "compact" mode ensures that you have at least one message for the same key available in the topic.
As a workaround in your case, I can think of the following:

*

*enable log compaction for the topic

*ensure that you have defined an individual key for each different message in the topic

*if you plan to delete one particular message, send a message to the topic with the same key and a "null" value. In that case, this message will be eventually deleted through the compaction cleaner.

A detailed explanation on log compaction is given in the Kafka documentation.


text:
Q: Finding the domain of $ f(x)= 2\arcsin \left(\frac{x-2}{x+1}\right) $ Can somebody tell me how to find the domain of this function, please?
$$ f(x)= 2\arcsin \left(\frac{x-2}{x+1}\right)$$

A: Argument limits are $\pm 1 $ for arc sine function.
So solve for two $x$ domain values:
$$ +1 =  \left(\frac{x-2}{x+1}\right)  $$
does not give a finite limit, upper limit $x<\infty$
$$ -1 =  \left(\frac{x-2}{x+1}\right)  $$
$x$ lower limit
$$\rightarrow x=\frac12 $$
Domain
$$ \frac12 <x< \infty$$


text:
Q: How To sum timestamp column that is saved as varchar I have a table that has timestamp data in it but the type of the column is character varying. i.e.
totaltime
character varying
0000:00:08.00
0000:12:39.00
0000:01:09.00
0000:00:02.00
0000:03:53.00

Is there an easy way to take sum of the column?

A: That is not a timestamp but an interval:
select '0000:00:08.00'::timestamp;
ERROR:  invalid input syntax for type timestamp: "0000:00:08.00"
LINE 1: select '0000:00:08.00'::timestamp;

select '0000:00:08.00'::interval;
 interval
----------
 00:00:08

https://www.postgresql.org/docs/current/static/datatype-datetime.html


text:
Q: Pointers - Dynamic Allocation Confusion I was reading this article ( http://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers ) which has some code to explain one reason why we should use them. eg.  Dynamic Allocation.
Eg.1. The incorrect program:

"This program firstly calls the SomeFunction function, which creates a variable called nNumber and then makes the pPointer point to it. Then, however, is where the problem is. When the function leaves, nNumber is deleted because it is a local variable. Local variables are always deleted when execution leaves the block they were defined in. This means that when SomeFunction returns to main(), the variable is deleted. So pPointer is pointing at where the variable used to be, which no longer belongs to this program."
#include <stdio.h>

int *pPointer;

void SomeFunction()
{
    int nNumber;
    nNumber = 25;

    // make pPointer point to nNumber:
    pPointer = &nNumber;
}

void main()
{
    SomeFunction(); // make pPointer point to something

    // why does this fail?
    printf("Value of *pPointer: %d\n", *pPointer);
}

Eg.2. The Correct program:

"When SomeFunction is called, it allocates some memory and makes pPointer point to it. This time, when the function returns, the new memory is left intact, so pPointer still points to something useful. That's it for dynamic allocation!"
#include <stdio.h>

int *pPointer;

void SomeFunction()
{
    // make pPointer point to a new integer
    pPointer = new int;
    *pPointer = 25;
}

void main()
{
    SomeFunction(); // make pPointer point to something
    printf("Value of *pPointer: %d\n", *pPointer);
}

My Question:

This above explaination made complete sense to me and I was feeling good about why we use pointers. Then I decided to run the programs to see what happens. I was expecting the first one to display some random number for *pPointer because the 25 had been deleted. Both programs displayed "Value of *pPointer: 25" correctly. Shouldn't the first program have failed as the tutorial said it would?

A: It's because it's undefined behavior. You simply are lucky that the printf function haven't written over that location.
The nice thing (if I may be ironic) about undefined behavior, is that it's undefined, you can't really tell what will happen beforehand. Also see nasal demons.

A:
Both programs displayed "Value of *pPointer: 25" correctly. Shouldn't
  the first program have failed as the tutorial said it would?

In the first program, nNumber is located on the stack. When SomeFunction() exits, nNumber "goes out of scope," which is to say that it no longer exists from the program's point of view. The memory that was used for that variable is still there, however, and it will contain the same value that it did when nNumber was in scope until some new value is written there. pPointer continues to point to that location, of course, so you can keep looking at the value of that memory. As other functions are executed, that memory will eventually be used for some new variable, and the value will change. The danger is that if you continue to use pPointer expecting it to remain valid, you'll find that the value that it points to keeps changing unexpectedly.

A: That is undefined behaviour. There is no check to ensure that the pointer being de-referenced is pointing to a valid value or not. Check this awesome answer here.
In short,
When the variable goes out of scope, anything is possible at the location where the variable was previously stored (even after you do delete, delete just releases the memory it doesnt necessarily wipe it out).
It might be overwritten already, might be in the process of being over written, or nothing has changed till now. (like in your example). Since, its in a space that is valid to be accessed by your code you don't find any seg-faults etc.

A: Local variables are allocated on the stack. When a function exits, the pointer to the top of the stack is modified so that the local variables are off the stack, but the stack is not wiped. Therefore, the value 25 will still be at the memory location pointed to by pPointer. If you call another function with local variables, that memory will be overwritten.
printf() will overwrite the location, but pPointer will be dereferenced for use in an argument before printf() is executed.

A: The reason why the first program worked is because in c++ using a pointer to a destroyed variable is undefined.  But what c++ doesn't dictate is what happens to that memory.  Local variables are allocated using what is called a Stack Frame in c++ or if you are familiar with Assembly Language "The Stack" after completion of the function often times that memory is not actually destroyed but is rather just not protected from being overwritten.  So for a time that pointer may work but at some other point in time the memory that you are pointing too can be overwritten.
The technical explanation for this phenomenon is that when a function is entered its address is pushed onto the stack segment.  Local variables are then defined as an offset below this pushed address and the stack pointer.  This effectively gives you memory on the stack to access for local variables.  But once the function leaves rather than wasting time overwriting that memory the memory is left unprotected for reads and writes from later operations as such the behavior is undefined because we have no idea at what point that memory will no longer be valid and how long that memory is valid is not set in stone and often fluctuates.  If you are looking for an explanation this video gives a good overview without going into the hardcore details: http://www.youtube.com/watch?v=vcfQVwtoyHY.

A: In the first program, the pointer will still be pointing to the location in memory where the number 25 is stored.  This is correct.  The problem is not so much that the number 25 has been overwritten; it's that it might have been overwritten.  Other programs have free license to mess with that memory location without overstepping bounds with the first program, but until something actually gets around to changing that value, the hardware still stores the number 25.


text:
Q: POSTFIX-CYRUS SASL AUTHENTICATION I have a question regarding Postfix-SASL authentication. I have created a mail server with Postfix. I have a domain, a public IP, and an MX record pointing towards my IP. I can now send and receive email from my domain. Now I want to make it connect through a mail client.
I am using centos 7, quite new to this, so having some problems with it can anyone guide me through this? I have tried using cyrus but not working.

    yum install postfix -y
    yum -y install cyrus*

My main.cf file of Postfix looks like
    myhostname = mx12.example.com
    myorigin = $mydomain
    mydomain = example.com
    inet_interface = <my public ip>, localhost
    inet_protocol = all
    mydestination = localhost, $myhostname, $mydomain.....
    smtpd_sasl_auth_enable = yes
    broken_sasl_auth_clients = yes
    smtpd_sasl_type = cyrus
    smtpd_sasl_path = smtpd
    smtpd_sasl_security_options = noanonymous
    smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination

/etc/sasl2/smtpd.conf:
    pwcheck_method: saslauthd
    mech_list: plain login
    log_level: 7

/etc/pam.d/smtp:

    #%PAM-1.0
    auth       include      pam_unix.so
    account    include      pam_unix.so

/etc/postfix/master.cf:
    submission inet n       -       n       -       -       smtpd
      -o syslog_name=postfix/submission
      -o smtpd_tls_security_level=encrypt
      -o smtpd_sasl_auth_enable=yes
      -o smtpd_reject_unlisted_recipient=no
    #  -o smtpd_client_restrictions=$mua_client_restrictions
    #  -o smtpd_helo_restrictions=$mua_helo_restrictions
    #  -o smtpd_sender_restrictions=$mua_sender_restrictions
      -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
      -o milter_macro_daemon_name=ORIGINATING

Commands:
    systemctl enable --now postfix
    systemctl enable --now saslauthd
    testsaslauthd -u user -p password -s smtp

The firewall has open ports -: 25/tcp 143/tcp 587/tcp
So these are my configuration files. Anyone have a solution?


text:
Q: How to get item from ItemsSource for double clicked TreeViewItem's child TextBlock? I've got a TreeView with TreeViewItems, which ItemsSource is ObservableCollection<MyClass>
var myList = new ObservableCollection<MyClass>();
TreeView treeView = new TreeView();
TreeViewItem treeViewItem = new TreeViewItem {
    Header = headerStackPanel,
    ItemsSource = myList
};
treeView.Items.Add(treeViewItem);

How can I get object of MyClass when double clicking on corresponding TextBlock? Only thing that I've done is getting MyClass.ToString(), which stores in TextBlock.Text:
treeViewItem.MouseDoubleClick += (sender, args) => {
    TextBlock tb = args.OriginalSource as TextBlock;
    if (tb == null) {
         return;
    }
    string myClassToString = tb.Text;
};

Also: not from XAML, from code.

A: You can get the DataContext of your TextBlock.

A: Cast the SelectedItem of TreeView into MyClass:
treeViewItem.MouseDoubleClick += (sender, args) => {
    if (yourTreeView.SelectedItem is MyClass) {
        var myClass = yourTreeView.SelectedItem as MyClass;
        //Do something with myClass.
    }
    //Additionally in this aproach you can
    //check if selected item is TreeViewItem and get e.g. Header property.
    else if (yourTreeView.SelectedItem is TreeViewItem) {
        var treeViewItem = yourTreeView.SelectedItem as TreeViewItem;
        string header = treeViewItem.Header;
    }
};

or use DataContext property of TextBlock in the same way:
treeViewItem.MouseDoubleClick += (sender, args) => {
   TextBlock tb = args.OriginalSource as TextBlock;
   if (tb == null) {
       return;
   }
   else if (tb.DataContext is MyClass) {
       var myClass = tb.DataContext as MyClass;
       //Do something with myClass
   }
};


text:
Q: Count days between current row and last row with distinct value I have a  dataframe like:
        date  store   item    price  sales
0 2013-02-01     59  22154   999.00    1.0
1 2013-03-01     25   2552   899.00    1.0
2 2013-05-01     25   2552   899.00   -1.0
3 2013-06-01     25   2554  1709.05    1.0
4 2013-01-15     25   2555  1099.00    1.0

Now I am interested to get the days between each row and the row in past which has a price value different than the current one.
So I would like to have an extra column with the days how long time ago the price was different.
        date  store   item    price  sales  days_since
0 2013-02-01     59  22154   999.00    1.0   NaN
1 2013-03-01     25   2552   899.00    1.0   0
2 2013-05-01     25   2552   899.00   -1.0   1
3 2013-06-01     25   2554  1709.05    1.0   0
4 2013-01-15     25   2555  1099.00    1.0   0

In this example we just have 1 price which did not changed since yesterday.
How would I do that in the easiest way? Apply/Tranform/rolling window?
Thanks!

A: You wrote about counting days between the current and previous row,
so in my opinion the first step is to sort your DataFrame by date
(I assume that this column is of datetime type):
wrk = df.sort_values('date')

To compute the number of days define the following function:
def dayNo(grp):
    key = grp.grKey.iloc[0]
    if key > 1:
        return pd.Series((grp.date - lastDate[key - 1]).dt.days, index=grp.index)
    return pd.Series(0, index=grp.index)

For now skip it, I will explain details later.
And now the main code:

*

*Start from computing "group key" column:
wrk['grKey'] = wrk.price.diff().ne(0).cumsum()

It assigns consecutive numbers to each sequence of rows with the same price.

*Compute an auxiliary Series - the last date in each of the above groups:
lastDate = wrk.groupby('grKey').date.last()

*Now return to dayNo function.

*

*key is the current grouping key (the first group is a "special case").

*lastDate[key - 1] is the last date from the previous group.

*(grp.date - ...).dt.days is the number of days since the last
row in the previous group (when there was the previous price).

*return pd.Series(..., index=grp.index) returns a Series with
the above values and the index copied from the current group.

*return pd.Series(0, index=grp.index) is the result for the
first group (the initial date). My proposition is to return
0 here, so that the resulting column was not coerced to
float.

*Apply the above function to each group, generating the new column:
wrk['days_since'] = wrk.groupby('grKey').apply(dayNo).reset_index(level=0, drop=True)

reset_index is needed to drop additional index level, introduced by groupby.

*Drop grKey column:
wrk.drop(columns=['grKey'], inplace=True)

The result is:
        date  store   item    price  sales  days_since
4 2013-01-15     25   2555  1099.00    1.0           0
0 2013-02-01     59  22154   999.00    1.0          17
1 2013-03-01     25   2552   899.00    1.0          28
2 2013-05-01     25   2552   899.00   -1.0          89
3 2013-06-01     25   2554  1709.05    1.0          31

Discussion of the result:

*

*2013-01-15 - the initial date (no previous date), so, according
to my proposition, the result is 0.

*2013-02-01 - 17 days passed from the previous row and the price has changed.

*2013-03-01 - one month passed and the price has changed.

*2013-05-01 - since the price has not changed, the last row with
a distinct price is 2013-02-01 and since this date 89 days have passed.

*2013-06-01 - 31 days passed from the previous row (price has changed).


text:
Q: TomTom TrafficFlow API different OpenLR data using Protobuf and Datex2 (XML) We are planning to change our Java app from using TomTom Traffic Flow - Intermediate Service - DatexII to TomTom Traffic Flow - Intermediate Service - Protobuf, but we are facing a problem with OpenLR data.
In datexII, the response comes in a XML. The binary for OpenLR is a normal String like this: CwcZ6yJrqQslDgRLAQULFw==
But when we use the Protobuff option, we have a location object that contains:
openlr: "\v\377\276\372\036:a#\213\v\000\361\376\225$\r".
It has a .getOpenLR() method that returns a ByteString object like this (toString):
16 bytes [0x0b,0xff,0xbe,0xfa,0x1e,0x3a,0x61,0x23,0x8b,0x0b,0x00,0xf1,0xfe,0x95,0x24,0x0d]
We've tried everything, but we cannot get the same String from the XML or any format OpenLR can decode from there. As OpenLR is developed by TomTom and they recommend to use Protobuf to get data, there must be a way to get OpenLR locations from that ByteString. Any ideas?
PS: there is also another difference, the XML has an ID for each Object, which Protobuf doesn't.
PS2: there is no OpenLR tag :S


text:
Q: How to detach all processes from terminal and still get stdout in Docker? So it's easy to detach applications if you're calling them directly using something like
myapplication &

But what if I want to call myapplication which then forks off 100 mychildapplication processes? Well, apparently the same command still works. I can run it, exit the terminal, and see that the child processes are still there.
It gets complicated when I introduce a Docker container.
If I were to run docker exec -it --user myuser mycontainer sh -c 'source ~/.bashrc; cd mydir; ./myapplication myarg' in a Docker container, the child processes get killed right away. I can hack it by appending a sleep 10000000 but of course then my terminal will hang indefinitely.
I can also use nohup, but then I don't get the stdout. disown does not work because it's not running in the background.
My workaround right now is using jpetazzo:nsenter, but I don't want to type my password when I run the command.
Note: the reason I have all this sudo stuff is because exec doesn't source bashrc. I can hack it by manually sourcing bashrc and it would work. It doesn't really impact what I'm trying to do.
TLDR: I want myapplication to print to my terminal, finish executing, and have the child processes stick around after I exit, all in a Docker container. The only way this can happen is if somehow I can "nohup" all processes associated with my terminal.


text:
Q: Setting cookies in external domains in a web service A website, let's call it customerwebsite.com, loads a script from our domain. Let's call our domain trackingwebsite.com. This script calls a web service on the server (written in PHP) that logs some things and then sets a cookie to identify the user later.
The Set-Cookie header gets returned correctly. So far so good. However, on the next request that the script makes to the web service, the cookie is not sent back.
I'm setting the cookie with an expire time of 10 years, with the domain set to .customerwebsite.com (I've also tried this with .trackingwebsite.com to be sure)
After some googling and reading through various vague answers I think I've distilled that this set-up is not possible.
Am I correct in assuming that the web service cannot set cookies, and that the script calling the web service has to take care of getting and setting cookies and sending this to the web service if required?


text:
Q: Pulling data from text file and setting string values equal to the data in C# I am trying to pull data from a text file in the format:
    "UK,3"
    "USA,1"
    "CANADA,1"
where the Country (I.E Canada) is the name of the flag and thus it will update the background and name of the button to the correct flag and name of the country. And then the "1" corresponds to a pre-set continent.s
Basically how do I pull a line randomly and then set a string value equal to the name and a string value equal to the number?
UPDATE:
    // sets firstClicked and secondClicked to high value
    string firstClicked = "999";
    string secondClicked = "1000";
    string country1 = "5";
    string country2 = "1";
    string country3 = "2";
    string country4 = "3";
    string country5 = "4";
    string country6 = "1";
    string country7 = "5";
    string country8 = "4";
    string country9 = "2";
    string country10 = "5";
    string continent1 = "1";
    string continent2 = "2";
    string continent3 = "3";
    string continent4 = "4";
    string continent5 = "5";

    private void Country1_Click(object sender, RoutedEventArgs e)
    {
        firstClicked = country1;
        Timer.Start();

        if (Country1.Background != Brushes.Green)
        {
            if (firstClicked == secondClicked)
            {
                (new SoundPlayer(@"\Sounds\correct.wav")).Play();
                this.Country1.Background = Brushes.Green;

                // Add 1 to number (or any score you'd like)
                number = number + 10;

                // Add the new score to the label again
                score.Text = number.ToString();
            }

        }
        if (firstClicked != secondClicked)
        {
            firstClicked = "999";
            secondClicked = "1000";
            (new SoundPlayer(@"Sounds\wrong.wav")).Play();
        }

    }

At the moment if someone selects a flag and a country it will update a score and then highlight the country in Green.
Essentially what I'm trying to do is have a text document with country names and the corresponding continent values I.E. between 1 and 5 and then for the code to randomly pick a line and thus the buttons will be random countries every time. (continents can stay the same ofcourse)


text:
Q: Proper way in SQL stored procedure to append user input to a table and preventing sql injection I have a table in SQL with a varchar(max) field that is basically a log that is updated by end users with free-form entry (from a webpage).
How do I protect against SQL injection?  Or perhaps it already is?
create proc stored_procedure
@input varchar(max)
as

update mytable
set logfield = logfield + '  ' + @input;

It seems like it might be OK (SQL Server 2012). But everything I can read is adamant that you should never concatenate user input even in parameterized stored procedures.
Is there a different way to append the user input?

A: SQL injection will only happen on dynamic SQL (either on the SQL Server side or on the application side). Your code is not vulnerable to SQL injection. However, you're updating all the rows in the table. You should limit the update using a WHERE clause.


text:
Q: How to debug using rails console and puts in application I want to get some lines printed in irb opened through rails console. I have seen a lot of SO questions of how to achieve it. But I get nothing in the irb.
below is the code--
def show
puts 'in show method'
@post = Feed.find_by_id params[:id]
puts @post.inspect
redirect_to root_path unless @post.present?
end

now I have opened server by command rails server. Also, In another terminal I gave the command rails console, it opened the irb prompt. when in browser I run localhost:3000/posts/82 it gives the correct post, but nothing is shown in the console. What step am I missing? I want to print something in the console when a particular method is called.

A: The puts 'in show method' in line 2 won't show the output in rails console. Instead it shows the output in the same terminal where you did rails server. They might be lost with so much of output, so try to find it there itself.

A: Best way to debug is to use the debugger command.
If you are using ruby 2.0 or above, you have to use the gem 'byebug' and if you are using 1.9 or below, then gem ruby-debug
then, when you run your server in development mode, your server will stop when it reaches the debugger allowing you to see your objects' state and modify them (much better than simply using puts
The program will stop in the same window that your server runs.
Some basic commands:

*

*c continues the execution until next debugger is found

*n runs the next command. If it is a function executes the
function

*s step into the next command. If it is a
function, you will get into the function and see the variables

*display expression on every step display the result of the
expression you write (very useful when debugging loops)

*undisplay expression_number stops displaying the expresion

*display shows all the expressions being displayed

*list Displays the source code being executed

*help shows the available commands   help
command_name shows detailed info about a command

More info about debugging: http://guides.rubyonrails.org/debugging_rails_applications.html

A: *

*Use Rails.logger.debug "in show method" etc.

*In the second tab in terminal tail log/development.log like this
$ cd rails_app_root
$ tail -f log/development.log

or
$ cd rails_app_root
$ less +F log/development.log

There you will find all the output from the console.

A: Try to use Rails.logger

Rails.logger.info "Some debugging info I want to see in my
  development log.------#{@post.inspect}"

It will print @post value in log file.

A: I am a big fan of puts debugging. e.g;
def index
  method = Kernel.instance_method(:method)
  p method.bind(request).call(:headers).source_location
  @users = User.all
end

The above snippet helps you find where the method is implemented:
Processing by UsersController#index as */*
["/Users/aaron/git/rails/actionpack/lib/action_dispatch/http/request.rb", 201]

You can find more cool puts debugging here.


text:
Q: Want to provide only one time password on all servers I have created same ssh passphrase key from one main box to 10 servers, I want to deploy some commands and copy files from main box to other 10 servers with one time key. I don't want to use the passpharse key all time for logging on all servers.. i want to give key one time for on all servers..
Can anyone provide a small script or simplest method to accomplish?
[root@dasari9~] cat hostnames
localhost
remotehost
Sivaranjani
exlusive
[root@dasari9~]#

These all are hosts, I want to run some commands from main box to all above hosts.

A: If I understand the question correctly and you can connect to your hosts without being prompted, you can run a bash for loop:
for host in $(cat hostnames); do ssh $host <command to run>; scp <file to copy> $host:/path/to/target; done


text:
Q: Perl Hashes: Using key/value pairs from external text file I am trying to to create a hash which draws its key/value pairs from a separate text file on my server.
When I manually enter key/value pairs into a hash inside my perl script like in the example below, the hash works perfectly when I call it later on:
# Initialize hash
my %format_key = ('SGBK', 'PRINT', 'SGDVD', 'VIDEO');

# Call hash (this is much later in the program)
$item_format = $format_key{$fields[2]};

When I save those exact same arguments to a text file, and then read in that file, save the contents to a scalar variable, and assign that variable to the arguments in the hash, the hash does not function.  Here is what I have done:
# Open file path saved in $format_key_file and save contents to $output
open(my $fh, '<', $format_key_file) or die "Could not read from $format_key_file, program halting."; {
 local $/;
 $output = <$fh>;
 }
 close($fh);

my %format_key = $output;

 # Call hash (this is much later in the program)
    $item_format = $format_key{$fields[2]};

I'm completely stumped.  I suppose I can just manually enter all of my hash arguments into the script itself, but there will be lots of these and I would prefer to have them saved in a file for ease of updating down the road.

A: When you read from the file, you get a string (or multiple strings, if you read line-by-line). The Perl parser only parses source code passed to the Perl interpreter, not anything you read from files or elsewhere. You can use the eval function to evaluate arbitrary strings like this as perl code and return the result of the last expression (in this case, a list of strings), but string eval is dangerous because it can run any code; if you accidentally read a file containing system 'rm -rf ~/*' you have a problem.
A better option is to store your data in a known serialization format. A common format used for such things is JSON, because it maps neatly to Perl data structures, but you can also just store your strings as lines (without Perl syntax like quoting) for a simple case like this. There are any number of other options like YAML, or even XML, but they are harder to decode; and binary formats like Storable, Sereal, and CBOR, but they are not human-readable so can only be interacted with by your code.
use strict;
use warnings;
use JSON::MaybeXS;
# if you store it as JSON: {"SGBK":"PRINT","SGDVD":"VIDEO"}
my %format_key = %{decode_json($output)};
# or from an even-sized array: ["SGBK","PRINT","SGDVD","VIDEO"]
my %format_key = @{decode_json($output)};

# if you store it as one value per line
my %format_key = split /\n/, $output;


text:
Q: In a Qt application under Windows, the wrong button is selected by default I've been developing a desktop application using Qt Creator under Linux (Kubuntu).
Under linux, all is well, but under Windows, in a dialog box, the wrong button is selected by default when the window appears.
There are three buttons: Edit, Continue and Stop.
Continue is marked as 'AutoDefault' and 'Default'.
Stop is marked as 'AutoDefault', but not 'Deafault'.
Edit is marked as neither 'AutoDefault' nor 'Default', but when the dialog opens, it is selected, and pressing enter presses the Edit button.
The source for the program can be found at https://github.com/megamasha/FlashKard for anyone who wants to try it themselves. The window in question is generated from the 'resultswindow.ui' file.
Is this just me? Is this a bug? Just wondering if anyone can see any obvious reason why this doesn't work (or perhaps it just doesn't work on my Windows Vista system)

A: About QPushButton::default:

A button with this property set to true (i.e., the dialog's default
  button,) will automatically be pressed when the user presses enter,
  with one exception: if an autoDefault button currently has focus, the
  autoDefault button is pressed.

And more importantly:

Command buttons in dialogs are by default auto-default buttons, i.e.
  they become the default push button automatically when they receive
  the keyboard input focus.

Unless you explicitly set editButton's autoDefault to false, it is true. There might be some Windows specifics involved (without further hints, Windows focuses the control with the lowest ID, which is probably the case for editButton, since it's created first).
Try either setting autoDefault to false, or explicitly call continueButton.setFocus()


text:
Q: Ignore case sensitive for given word I have a search Query where I'm looking for values in my table. And I want to dynamically search for a value, for example, "AMAZON".
="select B, C, L, E, O, P, Q WHERE B >= date '"&TEXT(A2; "yyy-mm-dd")&"' and B <= date '"&TEXT(B2; "yyy-mm-dd")&"' and L matches '.*"&C2&".*' and E LIKE '%"&D2&"%'"

"C2" is my empty cell, for searching for a string. I, for example, input "amazon" into "C2"
My problem is that is doesn't return anything as in my table it's written "AMAZON" or probably "Amazon" so it won't find anything as I have a direct link to "C2"I couldn't figure out that way of phrasing the regular expression to ignore the case sensitive.
It would return anything as soon as I write "AMAZON" in "C2".
Goal:
I want to make it non case sensitive. Cause at the moment my formula won't print anything as soon as I don't write it in initial letters.

A: Please try lower in all cells you reference as well as all depending, returning columns.
So your formula would be:
="select B, C, L, E, O, P, Q WHERE B >= date '"&TEXT(A2; "yyy-mm-dd")&"' and B <= date '"&TEXT(B2; "yyy-mm-dd")&"' and lower(L) matches '.*"&lower(C2)&".*' and lower(E) LIKE '%"&lower(D2)&"%'"


text:
Q: What is the most robust archive format? I'd like to back up some old folders with documents I only very rarely need to access. For that, I'd like to put them all in one archive. As this will be a backup, the format should suit that purpose. So, bottom line:
Which one is the most reliable/robust archiving format in Ubuntu?

A: A tarball (.tar files) would be the way to go. Use the gzip compression format for less compression, but a good speed. bzip2 is much slower but provides a better compression ratio. For binary data, there is not a big different though.
The command for compressing a directory using the gzip compression:
tar czf /path/to/save/backup.tar.gz directory-to-backup

To extract a gzip-compressed tarball while preserving file permissions:
tar xzpf /path/to/save/backup.tar.gz

Replace z by j for the bzip2 compression and add v before v (e.g. czvf and xzpvf) to print the filenames as they're archived / extracted.

A: I choose 7zip (sudo apt-get install p7zip-full). It looks like an ideal compressing archiver from my point of view.
I don't like classic tarballs for their clumsiness as the whole tar file is to be decompressed (which may happen behind the scenes, but still happen) just to view the archive's table of contents.

A: Although not nearly as well known or widely used I'd be inclined to go with afio due to the way it compresses files individually thereby making recovery possible in case of corruption.  Install via aptitude or similar.

A: It depends. The two most popular options are tarballs and zip files, but they both are lacking:

*

*.tar tape archives are a very popular option for most Linux users. It preserves UNIX file permissions (which is important for a backup) and hard links. It's supported out-of-the box on every Linux distro I've tested, as well as some Windows programs like 7-zip. However, tar has several limitations and drawbacks for the back-up use-case, as explained by the Duplicity developers. It can be very slow: even to get a list of filenames stored in the archive, the entire archive must be read. It also doesn't handle detailed meta-data that some newer filesystems have.

*.zip zip files acts as both an archive and a compression format. For speed, you can disable compression completely. Zip files are better than tape archives in that they store a type of table of contents, allowing programs to quickly jump to the specific file they need to extract. It also stores checksums for the contents of each file, to allow for easy file corruption detection. Zip files are extremely popular, unfortunately, they are not suitable for Linux back-ups because they do not store simple file permissions.

Here are two more options that are, sadly, also lacking:

*

*.7z 7z compressed archives have some excellent features such as encryption and support for very large files. Unfortunately, it does not store UNIX file permissions, so it is not suitable for Linux back-ups.

*.ar classic UNIX archives are the predecessor to tar archives, and suffer from the same limitations as tar archives.

In my opinion, there is no completely robust back-up archive format for Linux back-ups, none that are sufficiently well-known to warrant my trust, any way.
One way to overcome the limitations of each of these formats is to combine them: for example, archive each file individually in a tar archive, and then archive all of these tarballs in one zip file.
If you want a really robust back-up, you should probably look into these solutions instead:

*

*back-up directly on to an external hard disk, with the same file system on both source and destination. This ensures that you will store each file's permissions and metadata exactly as intended. (As an aside, the owners and group owners of files are stored using their userid and groupid numbers, not their names.)

*Use full-disk imaging and cloning software, like CloneZilla. You can't retrieve one file from one of these back-ups, but you can be absolutely sure that you have saved everything you possibly can.
And remember, always remember: you can only be confident of your back-ups if you have attempted to restore them. If the worst came to worst and your source hard-drive was completely destroyed, could you restore everything you need to restore to a new hard-drive? Would it work as you expect? Try restoring your back-up to a new hard-disk and try running from that hard-disk for a couple of days. If you notice anything missing, you know your back-up wasn't thorough enough.
Also think about where you are keeping your back-ups. You need at least some back-ups that are not in same building as the source disks to protect yourself from theft or fire. Some options for this are the cloud, or a friend's house.

A: Gzipped tarball (.tar.gz, .tgz), Linux archiving standard. You can't go wrong with that.
Never in my life did I have a corrupted or even troublesome .tar.gz archive. At FlatmateRooms we use this to archive hundreds of thousands of images on the server and all backups.

A: In some cases this one is usefull for me.
tar -cJvf paquete.tar.lzma folder-to-backup/


text:
Q: Proof that $\|u+w\|^2 \geq \|u+w\|^2 - 2(\|v\|^2 - 1) + (\|v\|-1)^2 \geq 4 $ Let $E$ be a Banach Space and $u,v, w \in E$ such that $\|u\| = 1 \leq \|v\|$ and $w = \frac{v}{\|v\|}$.
I want to proof that $$\|u+w\|^2 \geq \|u+w\|^2 - 2(\|v\|^2 - 1) + (\|v\|-1)^2 \geq 4 $$
I got to proof only the first inequality:
since $\|v\|^2 - 1 = (\|v\| + 1)(\|v\|-1) \geq \|u+v\|\, (\|v\| - 1)$ and $\|w-v\| = \|v\| - 1$,
$$ \|u+w\|^2 - 2(\|v\|^2 - 1) + (\|v\|-1)^2 \leq \left ( \|u+v\| - \|w-v\| \right )^2$$
as $\|u+v\| \leq \|u+w\| + \|w-v\|$, follows that
$$ \left ( \|u+v\| - \|w-v\| \right )^2 \leq \|u+w\|^2 $$
and the first inequality holds.
However, I couldn't proof the second one. Help?

A: The second inequality does not hold with the stated conditions. For instance let $E=\mathbb C$, $u=1$, $v=-1$. Then $u+w=0$ and your second inequality is $0\geq 4$.


text:
Q: using DeleteLocalRef on references from jni's CallStaticObjectMethod I get that the NewStringUTF creates a local reference, but I can't seem to find a convincing source online that says otherwise about CallStaticObjectMethod etc. Do these need to be given the DeleteLocalRef treatment?
I mean, I saw that it's okay to just leave it until the native function returns to the java caller, but is it wrong to call DeleteLocalRef on these CallStaticObjectMethod return values?

A: Of course it creates a local reference.  If it didn't, how would the garbage collector know not to collect it while your JNI function is running?  However, unless you explicitly make an additional reference to it you don't need to delete it-  JNI will handle that.  Doing so for it is going to cause more problems than help.  The only time you should be calling the Delete function is if you previously had manually increased the reference count in order to store it for use in C outside of the function that created it.
Also, if you want to make your JNI memory management dead simple, just use PushLocalFrame and PopLocalFrame, and put all your code in between them.  It's the easiest way to be correct.


text:
Q: Dll issue while launching the application  I am using one dll in my application for including the functionality provided by that dll . This dll i am getting after  installing one msi .
But in my application i have  a requirement like if the user has not installed that msi then we have to show one warning message(e.g msi has not installed , code for this i have implemented in the main() of my application ) and have to exit from the application .
But the problem is if the user has not installed the msi , then while launching the application itself its showing one error message since its not able to get the dll  and this time  control not even coming to my main() where i have written the code for this msi checking  (through registry entry).
Is there any efficient way to resolve this issue ..

A: Consider delay-loading the DLL (Project -> Options -> Advanced Linker).
This will allow your app to load when the DLL is missing.


text:
Q: Handler and postDelayed doesn't work if milliseconds number is too high I am trying to execute a service in the background. This service is started on boot and its function is to execute something every 8 hours. In this case it sends a file by mail using JavaMail API and gmail account. This is my code:
private Handler mHandler;
private Runnable updateRunnable = new Runnable() {
    @Override public void run() {
        new MailSenderActivity.MailSender().execute();

        queueRunnable();
    }
};

private void queueRunnable() {

    mHandler.postDelayed(updateRunnable, 28800000);
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {

    mHandler = new Handler();
    queueRunnable();
}

@Override
public void onDestroy() {
    //code to execute when the service is shutting down
}
@Override
public void onStart (Intent intent, int startid) {
    //code to execute when the service is starting up
}

If xxxx in mHandler,postDelayed(updateRunnable, xxxx) is 600000 (10 minutes in milliseconds), it runs perfectly, but it doesn't if it is 28800000 (8 hours in milliseconds)
Any suggestions?
Thanks in advance

A:
I am trying to execute a service in the background. This service is started on boot and its function is to execute something every 8 hours.

Please don't do that. Please use AlarmManager to start an IntentService every 8 hours. That way, your service does not have to stay around in memory all that time.

If "xxxx" in "mHandler,postDelayed(updateRunnable, xxxx)" is 600000 (10 minutes in milliseconds), it runs perfectly, but it doesn't if it is 28800000 (8 hours in milliseconds)

Quite possibly, Android terminated your process. Again, this is not a problem if you use AlarmManager and an IntentService.


text:
Q: rails auto_complete plugin. how do i pass authenticity token? I tried the auto_complete text field in rails 2.3.3 and the server says it denied request because of no authenticity token. I can see that the helper doesn't automatically create a parameter for it.
How I can manually do this? And I do not want to disable forgery prevention for this autocomplete.

A: Honestly, disabling the forgery protection isn't a bad idea if you scope this to just JS.
def index
   respond_to |format| do
     format.html
     format.js do
       # your autocomplete code
     end
   end
end

Make your autocomplete call /things.js instead of /things.
As far as I understand it, forgery protection is not needed for JS responses, and ensuring your autocomplete uses a GET method should also solve your problem.  You're displaying a list, you're not modifying state, so use a GET and use the js response.

A: The forgery prevention is part of the form helper, not the field helper. If you use the full RoR form helper it should work. If it doesn't, please edit your question to include the form code and I'll try to help.

A: having had a similar problem I found just adding ":method => :get" to the "text_field_with_auto_complete" tag fixed it (as per Brian) - I didn't need to disable forgery protection


text:
Q: Silverlight/WPF: Retreiving the size of a UIElement once it has been rendered on screen I have the following simple piece of code:
            var canvas = new Canvas();

            foreach (var ztring in strings)
            {
                var textblock = new TextBlock();
                textblock.Text = ztring;

                panel.Children.Add(textblock);

                textblock.Measure(infiniteSize);
            }

At this point I would expect any of the size properties (Height/Width, ActualHeight/ActualWidth, DesiredSize, RenderSize) to give me the size of the textblock. None of them do.
ActualHeight always gives 16.0 no matter what size font. ActualWidth changes according to the text length but not the font size.
I change the font size on the parent container and not the TextBlock itself.
I feel like I am missing some basic element of understanding the manipulation of silverlight elements from within the codebehind.
The question is: how do I get the real actual pixel size of my TextBlock?

A: Below is a sample that adds a TextBlock to a Canvas using code behind and once the TextBlock is rendered, it displays its height in the title of the window. Is that what you are looking for?
XAML:
<Window x:Class="HeightTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <StackPanel TextBlock.FontSize="30">
        <Canvas Name="_canvas" Height="200"/>
    </StackPanel>
</Window>

Code behind:
using System.Windows;
using System.Windows.Controls;

namespace HeightTest
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            TextBlock textBlock = new TextBlock();
            textBlock.Text = "Hello";
            Canvas.SetLeft(textBlock, 25);
            textBlock.Loaded +=
                (sender, e) =>
                {
                    Title = textBlock.ActualHeight.ToString();
                };
            _canvas.Children.Add(textBlock);
        }
    }
}

A: Have you tried using a real container like a Grid instead of Canvas?
What if you try reading the ActualSize property after the Measure using a Dispatcher.BeginInvoke?


text:
Q: PUTTY: How do I cut & paste under Ubuntu? How does (where is) the the cut&paste function for PUTTY under Ubuntu ?
EDIT: source text is not in the PUTTY window.
EDIT: Found the problem:  the source text is in a Google Chrome tab which does not support "cutting" (at least for now).
EDIT: mea culpa: I realize now that SSH is preferred under Linux.

A: You can use the right mouse button to copy it, then click the middle mouse button (wheel) to paste.

A: I solved this issue using 2 methods:
1.  Using PuTTY Linux version:
Clicking both touchpad buttons, I simulated the middle button.
I needed to enable it manually, since the Linux Mint distro I'm using had not this middle button simulation activated. The latest version of evdev, version 2.5, changed the default for the middle mouse button emulation code. This change has disabled emulation of the middle mouse button by clicking the left and right mouse buttons.
To enable the middle mouse button emulation, add this to xorg.conf:
Section "InputClass"
Identifier "middle button emulation class"
MatchIsPointer "on"
Option "Emulate3Buttons" "on"
EndSection

2. Using PuTTY Windows version
I prefer that since I do not need to change distro settings like Xorg, only Wine settings in order to connect to console serial ports:
Since Wine handles com ports by having a link to the device (i.e. /dev/ttyUSB0), in the ~/.wine/dosdevices folder, this link would be created as follows, in order to update your wine profile configs:
ln -s /dev/ttyUSB0 ~/.wine/dosdevices/com1

I prefer this second method. Since copying and pasting always works, I do not need the middle button simulation and, the cherry on top of the cake, it NEVER hangs (occasionally PuTTY hangs on some Windows XP installations).
Otherwise, in case you do not need/want to install Wine, the first method is preferable.

A: In Ubuntu 12.04, I was able to paste using Ctrl + Shift + Insert after copying text from a Firefox window or text editor.

A: I replaced all occurences of GDK_SELECTION_PRIMARY with GDK_SELECTION_CLIPBOARD in unix/gtkwin.c and unix/gtkdlg.c in the sources, then recompiled. I also had to add
'#include "../proxy.h"' to unix/uxproxy.c to get it to recompile, but that's maybe because I'm on FreeBSD.
Anyway, the end result is that it recompiled, and works with the more-or-less expected behaviour.

A: One other thing to watch out for (which I just learned about) is that on desktop Linux there are often two different "clipboards" that text can be copied to: X/X11 clipboard and the Gnome/GTK clipboard. This threw me for a bit. I could paste text into some windows, but depending on where I copied it from I couldn't paste in to Putty.
Basically, some applications handle the multiple clipboards and some do not. A few solutions can be found here:
How can I merge the gnome clipboard and the X selection?
One of the most popular programs for syncing both clipboards is autocutsel.

A: Just highlight the text for copy and right click for paste.


text:
Q: Rename After Copy - Powershell I am trying to use powershell to copy one type of file (.xlsx) from one folder to another.
Once the copy is completed, I would like the extension on the original file to be changed. (.xlsx to .cmp)
I have the copy part down (below) but I am lost when it comes to the rename.  Can you guys please help.  I am a PS noob!  Thank you.
$src = "C:\Users\x\Documents\Test1"
$dst = "C:\Users\x\Documents\Test2"

Get-ChildItem $src -Filter "*.xlsx" | Move-Item -Destination $dst -Force

A: This should do it:
$src = "C:\Users\x\Documents\Test1"
$dst = "C:\Users\x\Documents\Test2"

Get-ChildItem $src -Filter "*.xlsx" | ForEach-Object {
    Copy-Item $_ -Destination $dst
    Rename-Item $_ -NewName ($_.Name -Replace '.xlsx','.cmp')
}

Uses a ForEach-Object loop to go through each item in the $src folder. Then for each item (represented inside the loop as $_) we use Copy-Item to copy it to the destination Then use Rename-Item with a -Replace to change the file extension.

A: As far as I know, you'll have to iterate over your files to be able to perform this rename.
# Set-up variables
$sourcePath = "C:\temp"
$sourceExtension = "txt"
$destinationPath = "C:\temp2"
$destinationExtension = "cmp"

# Grab the list of files
$files = Get-ChildItem -Path $sourcePath -Filter "*.$sourceExtension"

# Loop over the files
foreach ($file in $files) {
    # Construct the new file name
    $newFileName = (Join-Path -Path $destinationPath -ChildPath $file.BaseName) + ".$destinationExtension"

    Write-Output "New File Name = $newFileName"

    # Move the file to the new destination with its new name!
    Move-Item -Path $file.FullName -Destination $newFileName
}

Note: BaseName = filename without extension


text:
Q: not able to connect to cloud sql private IP via cloud run I am trying to connect to cloud sql(postgres) via simple python application code.. I am trying to run container locally using cloud shell.. getting below messages for a while and then finally a error.
vikrant@cloudshell:~/test/docker (test-project)$ docker run -ti --name=my-test-container test-docker-image
2022/06/12 03:56:09 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here.
2022/06/12 03:56:09 using credential file for authentication; email=service-gcf-transform@test-project.iam.gserviceaccount.com
2022/06/12 03:56:10 Listening on 127.0.0.1:5432 for test-project:europe-west1:test-uat-pgsql-65d01f80
2022/06/12 03:56:10 Ready for new connections
2022/06/12 03:56:11 Generated RSA key in 286.419278ms
connecting to postgres database
2022/06/12 03:56:19 New connection for "test-project:europe-west1:test-uat-pgsql-65d01f80"
2022/06/12 03:56:19 refreshing ephemeral certificate for instance test-projec:europe-west1:test-uat-pgsql-65d01f80
2022/06/12 03:56:22 Scheduling refresh of ephemeral certificate in 54m57s

  File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

below is sample code. I tried it with cloud sql IP also..
import sqlalchemy
import os

db_user='test-user'
db_pass='test-pswd'
db_name='test-database'

db_engine = None

host = '127.0.0.1'
port ='5432'

drivername='postgresql+psycopg2'

def _create_engine():

    return sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername=drivername,
            host=host,
            username=db_user,
            password=db_pass,
            database=db_name,
        )
    )

def get_engine():
    global db_engine
    if not db_engine:
        db_engine = _create_engine()
    return db_engine

def read_postgres(conn):
    sql = f"""
    select bucket_id,object_id from test_requests limit 5
    """
    result = conn.execute(sqlalchemy.text(sql)).fetchall()
    result_list=[]
    for r in result:
        d = dict(zip(r.keys(), r))
    result_list.append(d)

    return result_list

def connect_postgres():
    print('connecting to postgres database')
    with get_engine().connect() as conn:
        print('connected to postgres database')
        result = read_postgres(conn)
        result_list=[]
        for r in result:
            print(f"row data as:{r}")
            print(f"bucket name:{r['bucket_id']}")
            print(f"object name:{r['object_id']}")

connect_postgres()

gcloud run deploy run-postgres \
--image eu.gcr.io/test-project/test-docker-image \
--add-cloudsql-instances=test-project:europe-west1:test-uat-pgsql-65d01f80 \
--region=europe-west1 \
--service-account service-cce-transform@test-project.iam.gserviceaccount.com \
--vpc-connector test-uat-cf-connector

running it locally also not working
Dockerfile:
FROM python:3-alpine

WORKDIR usr/src/app
COPY main.py .
COPY requirements.txt .
COPY test_cf_SA_key.json .

ADD start.sh /
RUN chmod +x /start.sh

RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
RUN chmod +x cloud_sql_proxy

RUN cp ./cloud_sql_proxy /cloud_sql_proxy

RUN pip install --no-cache-dir -r requirements.txt

CMD ["/start.sh"]

running application code using start.sh to sort out the timing issue.. read over some stackoverflow link
#!/bin/sh

./cloud_sql_proxy -instances=test-project:europe-west1:test-uat-pgsql-65d01f80=tcp:5432 -credential_file=test_cf_SA_key.json &

chmod +x cloud_sql_proxy
sleep 10
python3 main.py

A: The main reason you can't connect to the Cloud SQL instance is the way you are using the Cloud SQL auth proxy. The proxy will not work for connecting to private instances if you run it from an environment not within the same VPC as the private SQL instance. Both your local machine and Cloud Shell are not part of the VPC where your SQL instance is.
An environment where you can test it, for example, would be a GCE instance located at the same VPC as your SQL instance. I tested a simplified version of your code and could query the instance from both GCE and a Cloud Run service. Below are the snippets I used.
However, using the auth proxy in a Cloud Run container to connect to a private CloudSQL instance is redundant. The official guide shows the recommended setup to query a private Cloud SQL instance from Cloud Run. The serverless VPC connector will allow your Cloud Run container to be in the same VPC as your SQL instance, and connect directly to it. Let me know if this was useful.
Dockerfile
FROM python:3-alpine

WORKDIR /app
COPY main.py .
COPY requirements.txt .
COPY test_service_acctkey.json .

COPY start.sh .
RUN chmod +x ./start.sh

RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
RUN chmod +x cloud_sql_proxy

RUN pip install --no-cache-dir -r requirements.txt

CMD ["./start.sh"]

start.sh
#!/bin/sh

./cloud_sql_proxy -instances=<INSTANCE_CONNECTION_NAME>=tcp:5432 -credential_file=<PATH_TO_SERVICE_ACCTKEY> -ip_address_types=PRIVATE &

chmod +x cloud_sql_proxy
sleep 10
gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 main:app

main.py
from flask import Flask
import sqlalchemy
import os

db_user='USER'
db_pass='PASS'
db_name='DATABASE'
db_engine = None

host = '127.0.0.1'
port ='5432'

drivername='postgresql+psycopg2'

app = Flask(__name__)

def _create_engine():

    return sqlalchemy.create_engine(
        sqlalchemy.engine.url.URL(
            drivername=drivername,
            host=host,
            username=db_user,
            password=db_pass,
            database=db_name,
        )
    )

def get_engine():
    global db_engine
    if not db_engine:
        db_engine = _create_engine()
    return db_engine

def read_postgres(conn):
    sql = f"""
    select * from testtable;
    """
    result = conn.execute(sqlalchemy.text(sql)).fetchall()
    return result

def connect_postgres():
    with get_engine().connect() as conn:
        result = read_postgres(conn)
        return result[0][1]

@app.route('/')
def entry():
    sql_data = connect_postgres()
    return f'TEST: {sql_data}'

if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

Deployment command (for testing)
gcloud run deploy SERVICE_NAME \
--source . \
--service-account=SERVICE_ACCT_ADDRESS \
--max-instances=3 \
--allow-unauthenticated \
--region=us-central1 \
--vpc-connector=SERVERLESS_CONNECTOR_NAME \
--no-cpu-throttling


text:
Q: What do operator //= and :: do? I am working on the Euler problems and found this code online for the third problem.
I used Python 3 to solve the third and fourth problems.
def lpf(c):  # largest_prime_factor
    i = 2
    while i * i <= c:
        if c % i:
            i += 1
        else:
            c //= i            # c // i returns the integer quotient of c/i
    return c

I know that the // returns the integer quotient of a division, but what is happening when an equal sign is put just after it?
c //= i --> Is the integer quotient of c/i affected to the variable c?
Also, I am working on palindromes for problem 4 and I found this operator ::.
For example, here is code using it:
> s = str(12321)

> print(s == s[::-1])

Output : True

(If the number is a palindrome, then output is True, else the output is False.)
Is the operator :: reading the string and changing it with an option? If so, how do you use it?

A: If you read an operator like ??= with ?? a special operator, that usually (not always), can be replaced by:
c ??= e
into:
c = c ?? e
So the operation is done inplace. So here you have written:
c = c // i    # equivalent to c //= i

Note that sometimes inplace operations differ from their non-inplace counterparts. For instance for a list la += lb is not equal to la = la + lb. Since numerical values are immutable however, there is not much we can optimize here, so for numbers the above will (probably) always hold.


text:
Q: Losing zone.js properties after using await command I'm using zone.js inside my AdonisJs project to create execution context. I have a piece of middleware that creates a zone as follows:
async handle ({ request, response }, next) {
    let token = jwtDecode( request.header('Authorization') )

    // Create a zone so we have execution context throughout the flow
    return Zone.current.fork({

        name: Math.random(),
        properties: {
            username: token.username,
            user_id: token.sub
        }
    }).run( async () => {

        // call next to advance the request
        await next()
    })
}

Inside my controller I can access my zone properties with
let username = Zone.current.get('username')

However, the moment I use the await command I lose access to the zone properties, all are undefined. For example:
WORKS
let username = Zone.current.get('username') // ALL OK
let order = await Order.find(params.id);

NOT WORK
let order = await Order.find(params.id);
let username = Zone.current.get('username') // UNDEFINED

Can anybody please advise?

A: This is a known issue, currently zone.js not support native async/await.


text:
Q: matlab: Solving coupled ODEs with time-varying parameters I am trying to solve a set of ODEs in matlab (I guess ODE45 is the right tool) that have time-varying parameters.
Here's an illustration:
x' = x/y+z*a(t)
y' = y*x+a(t)/y+b(t)
z' = x*y + c(t)/z + d

I have the data for a(t), b(t) and c(t) given in a lookup table prepared beforehand. d is something that has to be calculated from external data each itteration.
I;m dealing with solving the equations of motion of a system.
How do I do that?
Thanks!


text:
Q: Is it possible to create N variables in C with a simple macro? I've been studying VHDL and came in contact with the statement(not sure if this is the right word) "for generate", which allows me to instance N number of components, which lead me to think:
Is it possible to do something similar in C?
For example, you can do things like:
#define _VAR(x)  static int x##_data
#define STRUCT(x) {index##x, data##x, "Name " #x}

Probably the syntax above is wrong (I'm tired and have to wake up really early tomorrow), but you get the idea.
I am also 100% sure that this isn't possible (not from my research or what I've learned), but I still have to ask. Does a similar statement exist in C, other than creating an array:
#define NVARIABLES(name, x) static int ##name[x]

If not, do you think it would be useful (I do), could you see it in the next C revision ( C15?? :) ). Thank you for your help, and good night

A: For more information about this, and other things, check boost preprocessor.
Thank you everybody for you comments. You've been very helpful and pacient with a the sleep deprived version of me.
Thank you for pointing out all the information.


text:
Q: SeekBar setThumb(null) crashes NullPointerException So I have a SeekBar that fills up while a file is downloading. Once it is done downloading the filled SeekBar goes away. I run the method setThumb(null) to make it fill up instead of just showing a thumb icon go across. Well now with the newer OS this method crashes the program with a NullPointerException. I set it to an actual drawable but it fills up half the bar at start which I don't want. When I don't set a thumb at all it shows an ugly little thing go across. Any help would be nice. Thanks.

A: You can do two things:

*

*Use a ProgressBar, not a SeekBar

*Set the thumb drawable to be a transparent drawable (ColorDrawable or a transparent image)

A: So the way to solve this is turning it into a ProgressBar (thanks to Romain Guy and MH) and then to change style things about it. This website basically explains it and is very helpful: http://android-er.blogspot.com/2010/11/progressbar-running-in-asynctask.html


text:
Q: find resources that are never tagged in aws using boto3 Using this we can't find resources that are never tagged:
client = boto3.client('resourcegroupstaggingapi')

How to find resources that are never tagged in AWS using boto3?

A: We are using a tagging concept that requires 5 tags as mandatory, and we created a config rule that checks for these.
https://docs.aws.amazon.com/config/latest/developerguide/required-tags.html


text:
Q: How To Fix This Responsive Navigation Menu? I have added this navigation menu into My Web Site. But, there is a problem with responsive. When I minimize the web browser , it doesn't fit with the web browser size. And this navigation doesn't fit with mobile phones Or even I can't see a symbol which I can open the Navigation.

How can I fix this ?? Is there a problem in @media screen ?? or in JS ??

header
{
position:relative;
z-index:1;
width:100%;
background:#002248;
border-bottom: 3px solid yellow;
border-top: 3px solid yellow;
height:80px;
}

.logo{position:relative;z-index:123;padding:10px;font:18px verdana;color:#6DDB07;float:left;width:15%;margin-right:50px;}
.logo a{color:#6DDB07;}

nav
{

}

#cssmenu,#cssmenu ul,#cssmenu ul li,#cssmenu ul li a,#cssmenu #head-mobile
{

list-style:none;
line-height:1;
display:block;
background-color: #002248;
position:relative;

}

#cssmenu{font-family:sans-serif;background:#333}

#cssmenu > ul > li
{
float:left;
}

#cssmenu > ul > li > a
{
padding:20px;
font-size:12px;
letter-spacing:1px;
text-decoration:none;
color:#ddd;
font-weight:700;
border-right: 1px solid #969696;
}

#cssmenu > ul > li:hover >  a{border-bottom: 3px solid white;}

#cssmenu > ul > li.has-sub > a{padding-right:30px}

#cssmenu > ul > li.has-sub > a:after{position:absolute;top:22px;right:11px;width:8px;height:2px;display:block;background:#ddd;content:''}

#cssmenu > ul > li.has-sub > a:before{position:absolute;top:19px;right:14px;display:block;width:2px;height:8px;background:#ddd;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}

#cssmenu > ul > li.has-sub:hover > a:before{top:23px;height:0}

#cssmenu ul ul{position:absolute;left:-9999px}

#cssmenu ul ul li{height:0;-webkit-transition:all .25s ease;-ms-transition:all .25s ease;background:#002248;transition:all .25s ease}

#cssmenu ul ul li:hover{}

#cssmenu li:hover > ul{left:auto}

#cssmenu li:hover > ul > li{height:40px}

#cssmenu ul ul ul{margin-left:100%;top:0}

#cssmenu ul ul li a{border-bottom:1px solid rgba(150,150,150,0.15);padding:11px 15px;width:170px;font-size:12px;text-decoration:none;color:#ddd;font-weight:400;}

#cssmenu ul ul li:last-child > a,#cssmenu ul ul li.last-item > a{border-bottom:0}

#cssmenu ul ul li:hover > a,#cssmenu ul ul li a:hover{color:#fff}

#cssmenu ul ul li.has-sub > a:after{position:absolute;top:16px;right:11px;width:8px;height:2px;display:block;background:#ddd;content:''}

#cssmenu ul ul li.has-sub > a:before{position:absolute;top:13px;right:14px;display:block;width:2px;height:8px;background:#ddd;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}

#cssmenu ul ul > li.has-sub:hover > a:before{top:17px;height:0}

#cssmenu ul ul li.has-sub:hover,#cssmenu ul li.has-sub ul li.has-sub ul li:hover{background:#363636;}

#cssmenu ul ul ul li.active a{border-left:1px solid #333}

#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active> a{border-top:1px solid #333}

@media screen and (max-width:700px){
.logo{position:absolute;top:0;left: 0;width:100%;height:46px;text-align:center;padding:10px 0 0 0 ;float:none}
.logo2{display:none}
nav{width:100%;}
#cssmenu{width:100%}
#cssmenu ul{width:100%;display:none}
#cssmenu ul li{width:100%;border-top:1px solid #444}
#cssmenu ul li:hover{background:#363636;}
#cssmenu ul ul li,#cssmenu li:hover > ul > li{height:auto}
#cssmenu ul li a,#cssmenu ul ul li a{width:100%;border-bottom:0}
#cssmenu > ul > li{float:none}
#cssmenu ul ul li a{padding-left:25px}
#cssmenu ul ul li{background:#333!important;}
#cssmenu ul ul li:hover{background:#363636!important}
#cssmenu ul ul ul li a{padding-left:35px}
#cssmenu ul ul li a{color:#ddd;background:none}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li.active > a{color:#fff}
#cssmenu ul ul,#cssmenu ul ul ul{position:relative;left:0;width:100%;margin:0;text-align:left}
#cssmenu > ul > li.has-sub > a:after,#cssmenu > ul > li.has-sub > a:before,#cssmenu ul ul > li.has-sub > a:after,#cssmenu ul ul > li.has-sub > a:before{display:none}
#cssmenu #head-mobile{display:block;padding:23px;color:#ddd;font-size:12px;font-weight:700}
.button{width:55px;height:46px;position:absolute;right:0;top:0;cursor:pointer;z-index: 12399994;}
.button:after{position:absolute;top:22px;right:20px;display:block;height:4px;width:20px;border-top:2px solid #dddddd;border-bottom:2px solid #dddddd;content:''}
.button:before{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;position:absolute;top:16px;right:20px;display:block;height:2px;width:20px;background:#ddd;content:''}
.button.menu-opened:after{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;top:23px;border:0;height:2px;width:19px;background:#fff;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}
.button.menu-opened:before{top:23px;background:#fff;width:19px;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}
#cssmenu .submenu-button{position:absolute;z-index:99;right:0;top:0;display:block;border-left:1px solid #444;height:46px;width:46px;cursor:pointer}
#cssmenu .submenu-button.submenu-opened{background:#262626}
#cssmenu ul ul .submenu-button{height:34px;width:34px}
#cssmenu .submenu-button:after{position:absolute;top:22px;right:19px;width:8px;height:2px;display:block;background:#ddd;content:''}
#cssmenu ul ul .submenu-button:after{top:15px;right:13px}
#cssmenu .submenu-button.submenu-opened:after{background:#fff}
#cssmenu .submenu-button:before{position:absolute;top:19px;right:22px;display:block;width:2px;height:8px;background:#ddd;content:''}
#cssmenu ul ul .submenu-button:before{top:12px;right:16px}
#cssmenu .submenu-button.submenu-opened:before{display:none}
#cssmenu ul ul ul li.active a{border-left:none}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active > a{border-top:none}
}

HOME

ABOUT

PRODUCTS

Product 1

Sub Product

Sub Product

Product 2

Sub Product

Sub Product

BIO

VIDEO

GALLERY

CONTACT


text:
Q: Check format of user inputted time before passing to strtotime I'm working on an exercise in which I accept a user defined timestamp with day, month, year, hour, min, sec and then display said time with variations across several timezones while also considering every scenario including invalid input.
My question is, how do I compare the format of a string to time before converting it to time?  I first attempted to do it like so but learned that date() will not accept a string.
$format = 'd-m-Y h:i:s';
$queryTime = $_POST['day'] . "-" . $_POST['month'] . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
$checkInput = date($format, $queryTime) == $queryTime;

if (date($format,$queryTime) == $queryTime) {
    $now = strtotime($queryTime);
} elseif (date($format,$queryTime) !== $queryTime) {
    $prompt = "Your input is invalid datetime.  Try again.";
    echo '<script>alert('.$prompt.');</script>';
    exit;
}

A: The second parameter of date() must be a timestamp. Use strtotime() to convert your date into a timestamp:
if (date($format, strtotime($queryTime)) == $queryTime) {

} elseif (date($format,strtotime($queryTime)) !== $queryTime) {

The last line really could just an else statement.
if (date($format, strtotime($queryTime)) == $queryTime) {

} else {

}


text:
Q: Two consecutive greater-than signs How do I produce the output >> in a LaTeX Beamer presentation?
When I write >> or \textgreater\textgreater, I get this symbol, which I believe to be the guillemet(»):

I do not want this symbol. I want literally two greater-than symbols, in the context of

Use >> to append to a file, as in date >> dates

A: You can use the math mode \gg just for that symbol. If you think they are too close together, you could use >> (again in math mode) with some negative space \! between them to bring them together a bit.
\(\gg\)
\(>\!\!>\)

A: If you want to avoid the automatic combining of characters, separate them using an empty group >{}>:
\documentclass{article}
\usepackage[T1]{fontenc}
\begin{document}
>> >{}>
\end{document}


text:
Q: How do I get started reverse engineering z80 machine code? I have a .z80 memory dump. How do I reverse engineer it? What do I need to know? How can I minimize manual labour?

A: It depends on what operating system your in, there are a lot of good tools here:
http://www.z80.info/z80sdt.htm
The first program I ever wrote was in Z80 Assembly language.

A: Most powerful disassembler - IDA supports z80.
Also list of disassemblers published at "Software Development Tools for Z80 Family" page


text:
Q: php5-suhosin Broken Installation Hi i get the following error when trying to install, have you any idea how to fix?
apt-get install php5-suhosin
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php5-suhosin : Depends: phpapi-20090626
E: Unable to correct problems, you have held broken packages.

I get the following error in my apache2 error log
[Mon May 07 21:43:15 2012] [error] [client ip] PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20100525/suhosin.so' - /usr/lib/php5/20100525/suhosin.so: cannot open shared object file: No such file or directory in Unknown on line 0

A: php5-suhosin package is broken in Debian now. This is the bug report about suhosin problem:
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=668739


text:
Q: authority_cert_issuer and authority_cert_serial_number must both be present or both None I'm using Python 3.7.1 in Anaconda 2018.12 and trying to make get() with requests from within a corporate network with custom certificates, I have the .pem for the certificate and I am using like so:
response = requests.get('https://www.google.com', verify='ssl/rootCA.pem')
print(response)

When I run this I get the following error:
File "run.py", line 29, in <module>
response = requests.get('https://www.google.com', verify='ssl/rootCA.pem')
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 839, in _validate_conn
conn.connect()
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 355, in connect
cert = self.sock.getpeercert()
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py", line 360, in getpeercert
'subjectAltName': get_subj_alt_name(x509)
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py", line 210, in get_subj_alt_name
ext = cert.extensions.get_extension_for_class(
File "C:\ProgramData\Anaconda3\lib\site-packages\cryptography\utils.py", line 162, in inner
result = func(instance)
File "C:\ProgramData\Anaconda3\lib\site-packages\cryptography\hazmat\backends\openssl\x509.py", line 137, in extensions
self._backend, self._x509
File "C:\ProgramData\Anaconda3\lib\site-packages\cryptography\hazmat\backends\openssl\decode_asn1.py", line 252, in parse
value = handler(backend, ext_data)
File "C:\ProgramData\Anaconda3\lib\site-packages\cryptography\hazmat\backends\openssl\decode_asn1.py", line 376, in _decode_authority_key_identifier
key_identifier, authority_cert_issuer, authority_cert_serial_number
File "C:\ProgramData\Anaconda3\lib\site-packages\cryptography\x509\extensions.py", line 152, in __init__
"authority_cert_issuer and authority_cert_serial_number "

ValueError: authority_cert_issuer and authority_cert_serial_number must both be present or both None

My certificate is a pretty simple
-----BEGIN CERTIFICATE-----
... certificate in here ...
-----END CERTIFICATE-----

And I've used this method in the past with the same certificate (same .pem actually) before so I'm not sure what I must have done to cause this issue.

A: I resolved this issue by ditching Anaconda, just using Python and setting the REQUESTS_CA_BUNDLE path with:
set REQUESTS_CA_BUNDLE=C:\Users\User\workspaces\ssl\rootCA.pem


text:
Q: Redis Booksleeve, HGETALL and converting byte array to long I'm using Booksleeve to communicate with Redis from a C# code. The code first retrieves all the fields and values from a hash:
var vals = await Redis.Hashes.GetAll(0, redisKey);

The hash contains fields which have values of type long.
The call to Hashes.GetAll returns the field values as byte arrays. The question is, how can I convert this byte array to C# long?
For example, if I use Hashes.GetInt64 to retrieve the value, I get back 9684, which is correct. But I'm not able to convert the retrieved byte array to long so that it would match this value:
BitConverter.ToInt64(redisHashValue, 0) throws ArgumentException

BitConverter.ToInt32(redisHashValue, 0) returns 876099129

BitConverter.ToInt16(redisHashValue, 0) returns 13881

A: Well, converting the byte array first to string seems to do the trick:
long.Parse(Encoding.UTF8.GetString(redisHashValue));

But is there a better solution?


text:
Q: PIG load not giving correct output I have been trying to load the file from HDFS and check the output using Dump. But I am not getting the desire output. My input file ('/results') looks like this:
1   fail

2   fail

3   pass

4   pass

5   fail

6   pass

7   fail

8   pass

9   pass

10  pass

11  pass

12  fail

13  fail

14  fail

15  pass

16  pass

17  pass

18  pass

19  pass

20  fail

And this the pig command I am coding:
 A = LOAD '/results' using PigStorage() as (f1:int, f2:chararray);
 Dump A;

But I am getting the output as follows:
(1,fail)
(,)
(2,fail)
(,)
(3,pass)
(,)
(4,pass)
(,)
(5,fail)
(,)
(6,pass )
(,)
(7,fail)
(,)
(8,pass)
(,)
(9,pass)
(,)
(10,pass)
(,)
(11,pass)
(,)
(12,fail)
(,)
(13,fail)
(,)
(14,fail)
(,)
(15,pass)
(,)
(16,pass)
(,)
(17,pass)
(,)
(18,pass)
(,)
(19,pass)
(,)
(20,fail)

I really don't understand from where "(,)" has come between two tuples. Can someone help me out ?
Thanks.

A: You have to specify the delimiter between the columns in your input file in PigStorage.Assuming your columns are separated by a single space
A = LOAD '/results' USING PigStorage(' ') as (f1:int, f2:chararray);
DUMP A;

If it is a tab
A = LOAD '/results' USING PigStorage('\t') as (f1:int, f2:chararray);
DUMP A;

A: You have to specify correct delimiter in PigStorage() method in order to read the file contents correctly. You need to modify that method based on the delimiter you have in your input data like:
For single space:
INPUT = LOAD '/results' USING PigStorage(' ') AS (f1: int, f2:chararray);
DUMP INPUT

For tab delimited:
INPUT = LOAD '/results' USING PigStorage('\t') AS (f1:int, f2:chararray);
DUMP INPUT;

For the second part that you are getting (,) in the output, I see an empty line between each two lines in your input data.
Solution:
Logically filter out the null records (Considering delimiter is a tab):
INPUT = LOAD '/results' USING PigStorage('\t') AS (f1: int, f2: chararray);
INPUT = FILTER INPUT BY f2 IS NOT NULL;
DUMP INPUT;

Thank You.


text:
Q: Icon for content Page in Xamarin Forms I am trying to get page icons work. I created a blank application and added a icon to it. when I run the app the icon does not render.
What am I missing. This seems like it should be straight forward.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
         prism:ViewModelLocator.AutowireViewModel="True"
         x:Class="Sandbox.Views.MainPage"
         Title="MainPage" Icon="icon.png">
   <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
        <Label Text="{Binding Title}" />
   </StackLayout>
</ContentPage>

A: In your MainPage code-behind file (MainPage.xaml.cs), try using the SetTitleIcon method of the NavigationPage (assuming you're using a navigation page).
public MainPage()
{
    InitializeComponent();
    NavigationPage.SetTitleIcon(this, "icon.png");
}

A: In Android, that Icon should be set in MainActivity like [Icon = "@drawable/icon"].
But I think you can try another way, to do whatever you want in Navigation bar
https://forums.xamarin.com/discussion/92502/easier-way-to-create-popup-view-and-custom-navigation-bar#latest


text:
Q: importing audio file onto python-3 I am getting this error when I try to import audio file, how do i import this audio file?:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-13-ce3f03976f66> in <module>()
----> 1 Fs, oooh = wavfile.read('oooh.wav') #my vowel sound
      2 Audio(oooh, rate=Fs)

/anaconda/lib/python3.6/site-packages/scipy/io/wavfile.py in read(filename, mmap)
    231         mmap = False
    232     else:
--> 233         fid = open(filename, 'rb')
    234
    235     try:

FileNotFoundError: [Errno 2] No such file or directory: 'oooh.wav'

and this is the code I have written thus far:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.io import wavfile
import scipy.signal as sig
from scipy.fftpack import fft, ifft
from IPython.display import Audio
np.set_printoptions(precision=3, suppress=True)

Fs, oooh = wavfile.read('oooh.wav') #my vowel sound
Audio(oooh, rate=Fs)


text:
Q: Show a form from another form When I want to Display a form (C#) by clicking a button in another form I usually create an object from the form that I want to show and use the show method :
        Form2 f2 = new Form2();
        f2.Show();

or I work with the "Owner" :
        Form2 tempForm = new Form2();
        this.AddOwnedForm(tempForm);
        tempForm.Show();

the two ways generate the same results but what is the best and what are the differences between them?

A: Microsoft uses Form f = new Form(); f.Show(); by default when creating a new Windows Forms project to show the main form, and there is probably negligible difference (in performance) between such methods. Using the Show() method, instead of just setting f.Visible = true; is also more logical.
When you use AddOwnedForm() you essentially lock the forms together in such way that when one form is minimized, the other is also. The form is also always displayed on top of the owning form, similar to a modal dialog.

A: The only difference apart from the naming is that in the second you call AddOwnedForm, and in the first you do not. Looking at the documentation we see:

When a form is owned by another form, it is minimized and closed with the owner form. For example, if Form2 is owned by form Form1, if Form1  is closed or minimized, Form2 is also closed or minimized. Owned forms are also never displayed behind their owner form. You can use owned forms for windows such as find and replace windows, which should not be displayed behind the owner form when the owner form is selected.

So if you want this behavior of the forms being minimized together, and one always being shown above the other, use AddOwnedForm. If you don't want this behavior, don't use it.


text:
Q: db4o multiple store() and one close() doesn't work? Hi
I'm using db4o in an android application.
I want to store multiple objects in a database so I have a loop that adds my objects in the db but if I don't put the close() IN the loop (after each store()), all the objects won't persist the next time I open the db. How is this possible? And how can I put only one close() AFTER the loop without having that problem?
I want to do only one close() because this is expensive in IO and it slows down the application initialization on the phone.
Thanks!

A: First, is this related to DB4O close() wipe the DB? ?
This definitely works :)
Can you provide a sample android project that reproduces the problem? (you can email me directly: adriano db4o dot com)
Best


text:
Q: Need bindings equivalent of String.replaceAll(...) I need to create a binding that allows me to do the equivalent of String.replaceAll(...) but with bindings. I have a string, "${driver} driving ${name}", and I want the keys, "${driver}", etc. to be replaced with the specific property. I also want the returned property to be able to add listeners so when driverProperty or another changes, the returned property value will change without having to re-call getString().
public String getString(Derby derby) {
        String ret;
        if (driverProperty.get().equals("") && nameProperty.get().equals("") && numberProperty.get().equals("") && groupProperty.get().equals("")) {
            ret = "[blank]";
        } else {
            ret = (String) derby.getSettings().get("general.cardisplay").getValue();
            ret = ret.replace("${driver}", driverProperty.get());
            ret = ret.replace("${name}", nameProperty.get());
            ret = ret.replace("${number}", numberProperty.get());
            ret = ret.replace("${group}", groupProperty.get());
        }
        return ret;
    }

A: Use Bindings.createStringBinding(). This takes a function supplying the String and a list of values to observe; if any of those values change the binding is marked as invalid.
Your question isn't too clear to me, but I think you can do something like
StringBinding formattedString = Bindings.createStringBinding(
    () -> getString(derby),
    derby.settingsProperty(),
    nameProperty, numberProperty,
    driverProperty, groupProperty);

Now you can do things like
formattedString.addListener((obs, oldFormattedString, newFormattedString) -> {
    // invoked any time the formatted string changes...
});

or
Label label = new Label();
label.textProperty().bind(formattedString);


text:
Q: How to update a C++ string within a function? Suppose I want to write a C++ function foo() that updates the value of an input string. How do I do it? The code should probably look something like I have below but I don't know how to properly pass the string such that it is updated by the function.
void foo(String x) // Not sure if I should put an & or * before x
{
    x += " Goodbye";
}

void main()
{
    String x = "Hello World";
    cout << "x = " << x << endl;
    foo(x);  // Not sure if I should pass a pointer to x,
             // a reference to x or what?

    cout << "After foo (), x = " << x << endl;
}

(FYI, I'm writing this for an Arduino processor)

A: Pass by reference:
void foo(String& x)
{
    x += " Goodbye";
}

The & means the parameter is a reference to the String outside the function rather than a copy.

A: In order to update the string from within the function, you need to pass a reference to the string as input:
void foo(String& x)
{
    x += " Goodbye";
}

This SO post explains the difference between pass-by-reference and pass-by-value.
Regarding your confusion between using & or * in the function signature, you can either

*

*use & as described above OR

*you could define foo as void foo(String *x). However, in this case, when you call foo, you would need to call it as foo(&x);.

In the first case, you're passing the input as a reference variable while in the second case, you're passing it in as a pointer variable. The differences between them are explained in this post.

A: You can use either of the following methods: -

*

*void foo(String *x) in function header and foo(&x); in main().

or,

*void foo(String &x) in function header and foo(x); in main().


text:
Q: Issues in saving 'datetime' values in the database in rails I am working on a simple program where a customer can place many orders(i.e 'customer' has_many :orders & 'order' belongs_to :customer)
I have a form where it accepts customer name and order date:
new.html.erb

New order

<%= form_tag  orders_path, method: 'post' do %>

    <%= label_tag  'customer_name' %>

    <%= text_field_tag :customer_name,params[:customer_name] %>

    <%= label_tag 'order_date' %>

    <%= datetime_select :order_date, params[:order_date] %>

    <%= submit_tag "create" %>

 <% end %>

The corresponding method in the controller looks like this:
def create
@customer= Customer.find_by_name(params[:customer_name])
@order = @customer.orders.new(:order_date => params[:order_date])

respond_to do |format|
      if @order.save
format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render json: @order, status: :created, location: @order }
      else
        format.html { render action: "new" }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

My question is, the params[:order_date] is a hash, I want to send it to the database as a 'datetime' value. I tried some combinations by declaring another variable of type "DateTime"  and then passing it to the database but it simply wont work.What is the solution?
Thanks in advance:)

A: try this.
 date = DateTime.strptime("#{params['order_date']['(1i)']}-#{params['order_date']['(2i)']}-#{params['order_date']['(3i)']}T#{params['order_date']['(4i)']}:#{params['order_date']['(5i)']}", '%Y-%m-%dT%H:%M')


text:
Q: R: Extract multi-values attribute (without delimiter) For example, I have the following dataframe called person:
|name  |       hobbies       |
------------------------------
 Jeff  |  gamesbasketball
 Linda |  hikingtennisreading

I want to convert the above table into the following table (let's call it person_unwind):
|name  |  hobbies|
------------------
 Jeff  |  games
 Jeff  |  basketball
 Linda |  hiking
 Linda |  tennis
 Linda |  reading

Somehow, I knew all the values in hobbies are "enum"s. Specifically, I have another dataframe called all_hobbies:
| all_hobbies |
---------------
  games
  basketball
  hiking
  tennis
  reading

My initial thought was to insert , between distinct values in hobbies using regex (loop over the whole person table), and then I can use seperate_rows() in dplyr library to "unwind" the hobbies attribute.
Is there any other good way to convert person to person_unwind given all_hobbies? Thanks!

A: We can use the second dataset to extract all words into a list and then unnest the list column to expand the rows
library(dplyr)
library(tidyr)
library(stringr)
person %>%
   mutate(hobbies = str_extract_all(hobbies,
                str_c(all_hobbies$all_hobbies, collapse="|"))) %>%
   unnest(c(hobbies))

-output
# A tibble: 5 x 2
#  name  hobbies
#  <chr> <chr>
#1 Jeff  games
#2 Jeff  basketball
#3 Linda hiking
#4 Linda tennis
#5 Linda reading

data
person <- data.frame(name = c("Jeff", "Linda"),
   hobbies = c("gamesbasketball", "hikingtennisreading"))
all_hobbies <- data.frame(all_hobbies = c("games", "basketball",
         "hiking", "tennis", "reading"))