text:
Q: Instagram Signup using python requests I am trying to create a instagram account using python and requests, when i send the last request to confirm the account creation it return : {"account_created": false, "errors": {"ip": ["L\u2019adresse IP que vous utilisez a \u00e9t\u00e9 signal\u00e9e comme un proxy ouvert. Si vous pensez qu\u2019il s\u2019agit d\u2019une erreur, rendez-vous sur http://help.instagram.com/"]}, "status": "ok", "error_type": "signup_block"}, the error is in french and mean: "The ip you are using has been flagged has an open proxy"
After doing some research on internet i found out that the error code showing is because instagram ip banned me so i tried with multiple different ip which i am sure are not compromised nor banned by default.
So i concluded that the requests i send may flag instagram antibot/antiproxy system. After 2 hours of trials and error i couldnt figure out how i could bypass it.
The code i wrote :
Code deleted

Code explanation:
Stage 1 : Generate data used for registration
Stage 2 : Ask tempmail.io for a new email and extract the email and email token from the response
Stage 3 : try to extract csrf token from the cookie (fail everytime idk why)
Stage 4 : send manifest (instagram always respond with code 401)
Stage 5 : send signup request to instagram (response : 200)
Stage 6 : send signup data generated in Stage 1 and 2 (response : 200)
Stage 7 : send birthdate (response : 200)
Stage 8 : ask instagram for email verification with the email generated in Stage 2 (response: 200)
Stage 9 : loop to check for email from instagram
Stage 10 : extract verification code from email
Stage 11 : send requests to delete email
Stage 12 : send verification code to instagram and extract signup code from response (response : 200)
Stage 13 : send signup attempt requests and try to complete registration (response : 200 but answer to the request with {"account_created": false, "errors": {"ip": ["L\u2019adresse IP que vous utilisez a \u00e9t\u00e9 signal\u00e9e comme un proxy ouvert. Si vous pensez qu\u2019il s\u2019agit d\u2019une erreur, rendez-vous sur http://help.instagram.com/"]}, "status": "ok", "error_type": "signup_block"})
All the requests i send are the one from a normal signup attempt from a webbrowser. The whole information in headers including CSRF token, deviceID... are from normal registration attempt using a webbrowser and coverted using https://curlconverter.com/ and are sent in the right order. I didnt sent some requests like falco and logging_client_events as i dont think they are needed for signup.
Any answers are well appreciated :)

A: I fixed the error by extracting csrf token from the cookie by using ''session.cookies.get_dict()'' and by passing the cookie to other requests now the account is created successfully.


text:
Q: Trouble separating MySqlConnection, MySqlCommand, etc. into another class because of query strings public void addEmployee(string fname, string lname)
{
    string addQuery = "INSERT INTO emp_table (emp_fname, emp_lname) VALUES (@fname, @lname)";

    MySqlConnection connection = new MySqlConnection(ConfigurationManager.AppSettings["connectionString"]);
    MySqlCommand cmd = new MySqlCommand(addQuery, connection);

    cmd.Parameters.AddWithValue("@fname", fname);
    cmd.Parameters.AddWithValue("@lname", lname);

    connection.Open();
    cmd.ExecuteNonQuery();
    connection.Close();
}

I want to put the lines MySqlConnection and MySqlCommand to the Connection class but the MySqlCommand has "addQuery" parameter. the reason i want it to avoid repeating the initialization of connection and command. so i dont have to call connection and cmd repeatedly.

A: You should always have a distinct connection and command for each query.  However, you can achieve some re-usability: I'd recommend creating a database service class that takes a query and a collection of parameters and executes the query.  In fact, you could combine the function of a query that doesn't return rows with one that does, because you will just get an empty dataset for the former:
internal static class MySqlDataManager
{
    internal static System.Data.DataSet GetMySqlDataSet(string usingQuery,
         string usingConnectionString, params MySqlParameter[] withParameters)
    {
        using (var conn = new MySqlConnection(usingConnectionString))
        using (var command = new MySqlCommand(usingQuery, conn))
        {
            command.Parameters.AddRange(withParameters);
            var ds = new System.Data.DataSet();
            using (var adapter = new MySqlDataAdapter(command)) adapter.Fill(ds);
            return ds;
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not remove all files from Trash in OS X I am try to empty the Trash, which takes forever. Most of the files have been removed, but I am left with several that will not delete, and I now get the following message:

The operation can't be completed because you don't have permission to access some of the items.

The folders and files that remain in Trash cannot be 'Put Back'. How can I remove these files from Trash?
In Terminal, I have typed in cd ~/.Trash then rm -rf ~/.Trash/* but nothing happens. How do you execute a command in Terminal? Do you hit Enter?
I am new to OS X and have never used Terminal before, so I am very wary of how best to proceed. I would appreciate any help you can give me.
I now know that if I 'Move To Trash' individual files and empty folders, the are removable from Trash. However I still need to remove the ones already there.

A: There's actually a number of causes of this so the solution varies. Often simply logging out and back in does the trick. If that doesn't work try repairing permissions through the menu. If that doesn't have an effect try Cmd +Option + Shift + Backspace.
As a last resort you can also type this into the terminal
sudo rm -rf /.Trash ~/.Trash

A:
The operation can't be completed because you don't have permission to access some of the items.

That's indicative of you not having administrator access to the machine. Does the system ask for your password when you initiate an Empty Trash action from the trash can icon in the Dock? Do you know if you're an administrator on the machine?

How do you execute a command in Terminal? Do you hit Enter?

Yes, you hit Enter to execute what ever you've typed at the prompt. But this is dangerous stuff to be doing if you've never used the command line before.
If you really want to go down this route, you need to prefix your rm call with sudo. Like so:
sudo rm -rf ~/.Trash/*

Be very, very careful with those commands. You can quickly render your machine inoperable with a poorly thought out, sudo'ed, rm call.

A: If you're not experienced with the command line you may want to try out BatChmod. It has a handy Force Empty Trash command that does the trick.
http://www.macchampion.com/arbysoft/BatchMod/Download.html


text:
Q: What is the proper way to check for more derived types in a generic collection? I am writing a dialog module for my XNA game as a learning project. I have been using the accepted answer here as a guide.
Every ILink contains an ICollection<ICondition>, which is used to determine whether or not all conditions have been met in order to make a particular dialog link appear as an option:
public interface INode
{
    int ID { get; set; }
    ICollection<ILink> Links { get; set; }
}

public interface ILink
{
    INode Target { get; set; }
    IScript Script { get; set; }
    ICollection<string> Text { get; set; }
    ICollection<ICondition> Conditions { get; set; }
}

public interface IScript { void Execute(); }
public interface ICondition { bool Evaluate(); }

Based on this, it was apparent that each type of comparison I wanted to make would have to be its own class:
public class EntityHasItem : ICondition
{
    public IEntity Entity { get; set; }
    public IItem Item { get; set; }
    public bool Evaluate() { return Entity.Inventory.Contains(Item); }
}

Or
public class QuestHasFlag : ICondition
{
    public IQuest Quest { get; set; }
    public IFlag Flag { get; set; }
    public bool Evaluate() { return Quest.Flags.Contains(Flag); }
}

How can I check what type each element of INode.Conditions is? I might make an editor, or provide feedback, for example. Because of the generic collection, it will always return with ICondition (which is the most common derived type), but it only exposes Evaluate(), which isn't much help here.
My first thought was to use reflection to get a list of types that were derived from ICondition, then compare that list against every element of the collection, but that seems like overkill. Is there a better way?

A: You shouldn't need to do this, violation of an interface (by downcasting) should only be done with great care and good reason.
There are two use cases you mentioned for wanting to do this, viewing and editing.
For viewing, the solution is simple. Either override .ToString() to get the information you need, or if you need "pretty" output, create an interface function DrawInfo to do this display for you (passing parameters as necessary, like an area of the screen to draw to).
For editing, you'll want a DrawDialog function. Like the DrawInfo function, this could take an "area" parameter. Assuming this dialog can manage its own UI controls (buttons and the like) you're done. This, by the way, would be analogous to having a class return a UserControl in WPF/Winforms to do the same thing.
Having these in the interface ensures that every derived class has it (invoking a method via reflection is not safe or fun!) and you don't need to worry about the types at runtime, polymorphism takes care of everything for you.

A: you can call the GetType() method on any .NET object.  This will return the actual type of the object (EntityHasItem, QuestHasFlag, etc).
http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx
for example:
foreach(var condition in type.Conditions)
{
   Debug.WriteLine(condition.GetType().FullName);
}


text:
Q: Root took over account in 18.04 I had a login loop on one my accounts. The other ones appear to work. When I use Ctrl+Alt+F3 to open the terminal, log into my normal account and type sudo xstart, I seem to be logging into root user with my normal home directory. How do I fix this so I can log in properly again?
Second Edit: startx without sudo gives a timeout from Xauthority then gives an xinit server error
First Edit: This is the .xsession-errors
dbus-update-activation-environment: systemd --user not found, ignoring --systemd argument
dbus-update-activation-environment: setting DISPLAY=:1
dbus-update-activation-environment: setting XAUTHORITY=/home/standard/.Xauthority
localuser:root being added to access control list
dbus-update-activation-environment: systemd --user not found, ignoring --systemd argument
dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
dbus-update-activation-environment: systemd --user not found, ignoring --systemd argument
dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
dbus-update-activation-environment: systemd --user not found, ignoring --systemd argument
dbus-update-activation-environment: setting SUDO_GID=1000
dbus-update-activation-environment: setting MAIL=/var/mail/root
dbus-update-activation-environment: setting USER=root
dbus-update-activation-environment: setting HOME=/home/standard
dbus-update-activation-environment: setting QT4_IM_MODULE=xim
dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
dbus-update-activation-environment: setting DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-mNX4Ha4s9l,guid=624789917a86589ef80a2eef5e389cc7
dbus-update-activation-environment: setting SUDO_UID=1000
dbus-update-activation-environment: setting IM_CONFIG_PHASE=1
dbus-update-activation-environment: setting LOGNAME=root
dbus-update-activation-environment: setting GTK_IM_MODULE=ibus
dbus-update-activation-environment: setting TERM=linux
dbus-update-activation-environment: setting USERNAME=root
dbus-update-activation-environment: setting WINDOWPATH=3
dbus-update-activation-environment: setting PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
dbus-update-activation-environment: setting DISPLAY=:1
dbus-update-activation-environment: setting LANG=en_US.UTF-8
dbus-update-activation-environment: setting LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
dbus-update-activation-environment: setting XAUTHORITY=/home/standard/.Xauthority
dbus-update-activation-environment: setting XMODIFIERS=@im=ibus
dbus-update-activation-environment: setting SUDO_COMMAND=/usr/bin/startx
dbus-update-activation-environment: setting SHELL=/bin/bash
dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
dbus-update-activation-environment: setting SUDO_USER=standard
dbus-update-activation-environment: setting GPG_AGENT_INFO=/home/standard/.gnupg/S.gpg-agent:0:1
dbus-update-activation-environment: setting QT_IM_MODULE=ibus
dbus-update-activation-environment: setting PWD=/home/standard
dbus-update-activation-environment: setting XDG_DATA_DIRS=/usr/share/gnome:/home/standard/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share
dbus-update-activation-environment: setting CLUTTER_IM_MODULE=xim

A: I fixed it.
ls -lA gave the following on "standard":
-rw-r--r--  1 root root   38 Feb  4 00:30 .bash_aliases
-rw-------  1 root root  501 Feb  4 00:31 .bash_history
-rw-r--r--  1 root root  220 Feb  4 00:07 .bash_logout
-rw-r--r--  1 root root 3771 Feb  4 00:07 .bashrc
drwx------ 14 root root 4096 Feb  4 00:11 .cache
drwx------ 12 root ....

The solution was to run sudo chown -R standard . && sudo chgrp -R standard . to recursively change ownership and group to standard. Afterward ls -lA looks like
-rw-r--r--  1 standard standard   38 Feb  4 00:30 .bash_aliases
-rw-------  1 standard standard  501 Feb  4 00:31 .bash_history
-rw-r--r--  1 standard standard  220 Feb  4 00:07 .bash_logout
-rw-r--r--  1 standard standard 3771 Feb  4 00:07 .bashrc
drwx------ 14 standard ....

Now "standard" can log in properly and no longer gives a login loop.
Note: It took way to long to realize that root actually owned everything


text:
Q: linker command failed with exit code 1 I am getting some errors and warnings when I build my IOS project
ld: warning: directory not found for option '-L/Users/parikshitpatel/Documents/IphoneDevelopment/FH/funkiorangemobile_iphonehealthadviceapp/Social'
ld: warning: directory not found for option '-LMedia/Twitter/Twitter'
ld: warning: directory not found for option '-LLibrary/Libraries'
ld: warning: directory not found for option '-L/Users/parikshitpatel/Documents/IphoneDevelopment/FH/funkiorangemobile_iphonehealthadviceapp0/Social'
ld: warning: directory not found for option '-L&'
ld: warning: directory not found for option '-LHeaders'
ld: warning: directory not found for option '-LMedia/Twitter'
ld: library not found for -lOAuth
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am not getting how to fix this error can some one help?

A: It looks like your Library path is incorrect.
Try to go to:   Targets - Build Phases - Link Binary with Libraries
 and add your Twitter Library/Framework

A: In your Folder path there are blank spaces between them. for example:
/Users/parikshitpatel/Documents/IphoneDevelopment/FH/funkiorangemobile_iphonehealthadviceapp/Social Media

In your Library dependencies write Social\ Media instead.
Do the same for other library.

A: For me I was opening the .xcodeproj Xcode project instead of the .xcworkspace workspace.  I'm pretty new to iOS development, but this feels similar to opening the wrong gradle file in Android Studio


text:
Q: How to find $f(x)$ in weird integral equation $ \int _ 0 ^ 1 f ( x ) c ^ x \ \mathrm d x = c $ Working on a problem and have reduced it to finding $ f ( x ) $ such that
$$ \int _ 0 ^ 1 f ( x ) c ^ x \ \mathrm d x = c \text . $$
However, here's where it gets interesting. The function should satisfy this equation for all values of $ c $ in $ ( 0 , 1 ) $.
How would I solve this? I thought about Mellin transform, but I don't know if that would work.

A: You can show that there is no such integrable function $ f : [ 0 , 1 ] \to \mathbb R $. If you want to consider the case of generalized functions (like measures or distributions), then you can see that $ f $ must be Dirac's delta concentrated at $ 1 $.
One way of looking at the problem is using Laplace transform. Define $ s = - \log c $, and the given equation becomes
$$ \int _ 0 ^ 1 f ( x ) \exp ( - s x ) \ \mathrm d x = \exp ( - s ) $$
for all $ s \in ( 0 , + \infty ) $. Extending the domain of $ f $ to be $ [ 0 , + \infty ) $ with $ f ( x ) = 0 $ for $ x > 1 $ (so that we deal with Laplace transform in the more traditional sense), the equation is in fact equivalent to
$$ \mathcal L \{ f \} = \mathcal L \{ g \} \text , $$
where $ g ( x ) = \delta ( x - 1 ) $. So $ f $ must be equal to $ g $ (in the sense of almost everywhere extended to the realm of generalized functions), as Laplace transform is invertible.
You can also try to solve the problem directly like this:
$$ \int _ 0 ^ 1 f ( x ) \exp ( - s x ) \ \mathrm d x = \int _ 0 ^ 1 f ( x ) \sum _ { n = 0 } ^ \infty \frac { ( - 1 ) ^ n x ^ n s ^ n } { n ! } \ \mathrm d x = \sum _ { n = 0 } ^ \infty \left( \frac { ( - 1 ) ^ n } { n ! } \int _ 0 ^ 1 f ( x ) x ^ n \ \mathrm d x \right) s ^ n $$
$$ \exp ( - s ) = \sum _ { n = 0 } ^ \infty \frac { ( - 1 ) ^ n } { n ! } s ^ n $$
Therefore, for every nonnegative integer $ n $, the coefficients of $ s ^ n $ in the two above series must be equal; i.e. we must have $ \int _ 0 ^ 1 f ( x ) x ^ n \ \mathrm d x = 1 $. This shows that in the sense of integrable functions, there is no solution, as
$$ 1 = \lim _ { n \to \infty } \int _ 0 ^ 1 f ( x ) x ^ n \ \mathrm d x = \int _ 0 ^ 1 f ( x ) \left( \lim _ { n \to \infty } x ^ n \right) \ \mathrm d x = 0 \text , $$
which is a contradiction. In the case of generalized functions, the above limit under the integral will be equal to $ g ( x ) $ mentioned before. The justification of validity of some of the above steps (like interchanging sum and integral and interchanging limit and integral) will be different in cases of integrable functions and generalized functions, but are rather standard and straightforward to check.


text:
Q: GA tracking with additional URL parameters Something I cannot find information about in the GA tracking documentation of branch.io is how to attach parameters other than the default GA ones to a link?
For example on top of UTM tracking our company uses custom URL parameters like ?acc=amex in order to provide special access pages on web that triggers certain things. Since in Branch we only have "Channel" "Campaign" and "tags" then I'm wondering would branch pass those custom link parameters and how?

A: We do pass custom link parameters to Google Analytics and this requires a custom webhook implementation. As this requires more information from your end, I would request you to send an email to integrations@branch.io to take this forward.


text:
Q: How run a silverlight application in another PC out of VS2010 with IIS I created a silverlight application with .net framework 4.0. I'm using a WCF with Linq to SQL for calling stored procedures from SQL server 2008.
My application works well in VS 2010 in local way but how can I install my application in another pc using IIS? I configured my WCF service in the other PC in IIS and work well the service but the application is not calling well.
The service doesnt show any errors and any data. My question is how my application can use that service or how can I install my silverlight application in another PC out of VS2010?
I try to use IIS in the client pc for install my silverlight application my WCF is run with any problems in client pc but the application doesn't show any data.

A: In my own opinion you have to disable the firewall of the machine you are going to connect.

A: Here's my guess:
When you add a reference to a web service in a Silverlight (version 3 and 4 at least) it creates a .clientconfig file. This file is similar to an app.config or web.config files you may already be familiar with. In it will be a hardcoded URI to the web service at the time you added the initial reference. My guess is that this path is still pointing to your dev machine. One option would be to change this URI to match the deployed location. I think the idea is that you'd unzip the XAP file, manually change the address, and re-zip (when you deploy/install the system).
You can alternatively programatically choose a different URI than the one in clientconfig. You pass a Uri object (or something like that) in the constructor of the generated service proxy class. I've often create a Uri this way that is relative to the path of the page the Silverlight app is hosted in. This makes deploying easy. But this relative path thing can make debugging difficult, you may want to consider a way to override this behavior. (we use a aspx code to alter the  tag to include a named parameter to override the relative path thing)

A: Here are few possibilities:
-It may be related to Silverlight client access policy, just make sure that you can do cross-domain calls to the host that hosts the SL if you are calling from a different domain.
-Your references may not have been updated, still pointing to old addresses (like an IP maybe)
-Your IIS dev server gets a dynamic port and it has changed and the server doesn't run on the port that was specified in service definition anymore.


text:
Q: Should the dimension of WORK array on xGEHRD and xHSEQR routines be equal on eigenvalue calculation? I'm calculating the eigenvalues of a dense non symmetric matrix A. For that purpose I use xGEHRD and xHSEQR Lapack routines in order to calculate first the upper Hessenberg form of A and then to calculate the only the eigenvalues of the obtained matrix.
Both routines require the parameter LWORK and both provide a mechanism to calculate its optimal value. I believe that this parameter is related to an internal blocking of buffer technique, but I don't know how it is determined.
Using the query mechanism to obtain the optimal value of LWORK the workflow should be like:
int LWORK = -1;
float* OPT_LWORK = (float*) malloc( sizeof(float));

sgehrd_ (..., OPT_LWORK ,&LWORK, ...) // query optimal value for sgehrd

LWORK = (int) OPT_WORK
float* WORK = (float*) malloc( (int) sizeof(float) * LWORK );

sgehrd_ (..., WORK ,&LWORK, ...) // calculate Hessenberg

int LWORK = -1;
shseqr_ (..., OPT_LWORK ,&LWORK, ...) // query optimal value for shseqr

LWORK = (int) OPT_WORK
float* WORK = // possibly realloc with the new LWORK value

shseqr_ (..., WORK ,&LWORK, ...) // finally obtain eigenvalues

I've done some testing, obtaining always the same optimal values for the dimension of WORK array. If the values were the same, I could simplify my code a lot (no need for realloc and only one call to determine the value of LWORK, less error checking...).
My question is, for the same matrix and the same values of ILO and IHI, can I assume that the values   are going to be equal the both routines?

A: Looking at sgehrd.f, it seems that the optimal size of WORK for routine sgehrd() is N*NB, where NB is
NB = MIN( NBMAX, ILAENV( 1, 'SGEHRD', ' ', N, ILO, IHI, -1 ) )

where NBMAX=64. Hence, the optimal LWORK depends on N, ILO and IHI.
Looking at shseqr.f, the computation of the optimal length LWORK is more complex : the routine slaqr0() is called... But the documentation in the file states :

If LWORK = -1, then SHSEQR does a workspace query.
    In this case, SHSEQR checks the input parameters and
    estimates the optimal workspace size for the given
    values of N, ILO and IHI.  The estimate is returned
    in WORK(1).  No error message related to LWORK is
    issued by XERBLA.  Neither H nor Z are accessed.

The optimal length of WORK may be different for sgehrd() and shseqr(). Here is an example :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

extern void sgehrd_(int *n,int* ilo, int* ihi, float* a,int* lda,float* tau,float* work, int* lwork,int* info);

extern void shseqr_(char* job,char* compz,int *n,int* ilo, int* ihi,float* h,int* ldh,float* wr,float* wi,float* z,int* ldz,float* work, int* lwork,int* info);

int main()
{
    int n=10;
    int ilo=n;
    int ihi=n;
    float* a=malloc(sizeof(float)*n*n);
    int lda=n;
    float* tau=malloc(sizeof(float)*(n-1));
    int info;

    char job='S';
    char compz='I';
    float* h=malloc(sizeof(float)*n*n);
    int ldh=n;
    float* wr=malloc(sizeof(float)*(n));
    float* wi=malloc(sizeof(float)*(n));
    float* z=malloc(sizeof(float)*n*n);
    int ldz=n;

    int LWORK = -1;
    float* OPT_LWORK =(float*) malloc( sizeof(float));

    sgehrd_ (&n,&ilo, &ihi, a,&lda,tau,OPT_LWORK ,&LWORK,&info); // query optimal value for sgehrd
    if(info!=0){printf("sgehrd lwork=-1 : failed\n");}

    LWORK = (int) OPT_LWORK[0];
    printf("sgehrd,length of optimal work : %d \n",LWORK);

    float* WORK = (float*) malloc( (int) sizeof(float) * LWORK );

    sgehrd_ (&n,&ilo, &ihi, a,&lda,tau,WORK ,&LWORK,&info);// calculate Hessenberg
    if(info!=0){printf("sgehrd execution : failed\n");}

    LWORK = -1;
    shseqr_ (&job,&compz,&n,&ilo, &ihi, h,&ldh, wr, wi,z,&ldz, OPT_LWORK ,&LWORK, &info); // query optimal value for shseqr
    if(info!=0){printf("shgeqr lwork=-1 : failed\n");}

    LWORK = (int) OPT_LWORK[0];
    printf("shseqr,length of optimal work : %d \n",LWORK);

    WORK = realloc(WORK,(int) sizeof(float) * LWORK );// possibly realloc with the new LWORK value

    shseqr_ (&job,&compz,&n,&ilo, &ihi, h,&ldh, wr, wi,z,&ldz, WORK ,&LWORK, &info);  // finally obtain eigenvalues
    if(info!=0){printf("shgeqr execution : failed\n");}

    free(OPT_LWORK);
    free(WORK);

    free(a);
    free(tau);
    free(h);
    free(wr);
    free(wi);
    free(z);

}

Compile by gcc main.c -o main -llapack -lblas
My output is :
sgehrd,length of optimal work : 320
shseqr,length of optimal work : 10


text:
Q: Prove that there is no integrable function $f(x)$ such that $\lim_{n \to \infty} \int^{1}_{0}[f(x)]^ndx=2$ Prove that there is no integrable function $f(x) $ such that $$\lim_{n \to \infty} \int^{1}_{0}[f(x)]^ndx=2 \ \ \ \ (*)$$.
My Attempt
$[0,1]=E_1 \sqcup E_2 \sqcup E_3$ Where $E_1=\{ x \in [0,1] \ | \ f(x)>1 \}$, $E_2=\{ x \in [0,1] \ | \ f(x)<1 \}$ and $E_3=\{ x \in [0,1] \ | \ f(x)=1 \}$. then $$\lim_{n \to \infty} \int^{1}_{0}[f(x)]^ndx= \lim_{n \to \infty} \left( \int_{E_1}[f(x)]^ndx + \int_{E_2}[f(x)]^ndx + \int_{E_3}[f(x)]^ndx \right)$$
Define $G_n=[f(x)]^n$, on $E_1$ the sequence $\{G_n\}$ is increasing and therefore we can use the Monotone Convergence Theorem. On $E_2$ the seguence $\{f_1-G_n\}$ is an increasing sequence of non-negative functions, so again we're allowed to use MCT. Hence,$$\lim_{n \to \infty} \int^{1}_{0}[f(x)]^ndx= \lim_{n \to \infty} \left( \int_{E_1}[f(x)]^ndx  -\int_{E_2}(f_1-[f(x)]^n-f_1 )dx + \int_{E_3}1 dx \right)= \left( \int_{E_1} \lim_{n \to \infty} [f(x)]^ndx  -\int_{E_2} \lim_{n \to \infty} (f_1-[f(x)]^n dx - \int_{E_2} f_1 dx + m_{E_3}\right) \ \ \ (**)$$ On $E_2$ we have that $\lim_{n \to \infty} [f(x)]^n = 0$ but on $E_1$ the limit blows up , therefore for $(*)$ to hold we must have that $mE_1=0$, So in $(**)$ everything vanishes except $mE_3$ But $$mE_3 \leq m[0,1]=1<2$$ Which means that there is no such function.
Is my reasoning correct ?
If we replace $f\in L^{\infty}[0,1]$ instead of $f\in L^1[0,1]$, does a similar argument work again?
Thank you in advance

A: If you assume $f$ to be nonnegative, then your answer is correct. However, you need to specify what $f_1$ is, as this is not clear. You could take $f_1(x) = 1$.
Now you just need to reduce to the case of nonnegative $f$.
Your argument holds up in any case for nonnegative $f$, because the monotone convergence theorem is valid for measurable functions with values in $[0,+\infty]$.


text:
Q: Vim displays json file without any quotes I have a validated json file that will display without any quotes in Vim. The only time it displays the json file correctly is under Visual mode.
I have tried disabling eslint, jshint, youcompleteme
OS X
MacVim 7.4
Vim 7.4 in Terminal

A: The built-in $VIMRUNTIME/syntax/json.vim uses Vim's conceal feature to hide the quotes, presumably to remove unnecessary clutter.
You must have enabled concealing by setting the 'conceallevel' option to 2 or 3; the default is 0 (off). Likewise, you see the quotes in visual mode because of your 'concealcursor' setting.
Inside a JSON file, check where the conceal options got set:
:verbose set conceallevel? concealcursor?

Then, you can adapt your settings to suit your preferences.

A: Adding to the currently accepted answer, you can disable that behavior specifically for JSON by setting the following option in you .vimrc:
" Disable quote concealing in JSON files
let g:vim_json_conceal=0

That way, you don't have to set conceallevel to 0 (disabled), which would also make useful plugins like indentLine (which was mentioned in a comment above) not work anymore.

A: Like already mentioned, one can check which plugin caused the increased conceal level:
:verbose set conceallevel?

If the conceal level is caused by the vim-json Plugin:
let g:vim_json_syntax_conceal = 0

If conceal is caused by the indentLine Plugin:
let g:indentLine_setConceal = 0

In vimrc, You can add both options for json files:
autocmd Filetype json
  \ let g:indentLine_setConceal = 0 |
  \ let g:vim_json_syntax_conceal = 0

A: I find this annoying because the lines 'jump' as quotes are hidden and unhidden.
Setting conceallevel=1 replaces the " with space (rather than hiding them) which stops the jumping while still making json more readable.


text:
Q: Populate input fields with values when option is selected in php mysql I have a form that i would like to submit details when an option is selected from the database.
The mysql database table :-
USERS contains fields like [email],[age],[name].
I want to be able to populate the other input fields values when one field is selected from the menu.
        <form>
        User
        <select name="user" id="user">
          <option>-- Select User --</option>
          <option value="Mark">Mark</option>
          <option value="Paul">Paul</option>
          <option value="Hannah">Hannah</option>
        </select>

          Age
          <input type="text" name="age" id="age">

          Email
          <input type="text" name="email" id="email">

        </form>

How do i acheive this using jquery or javascript.

A: Please Try this,
on your HTML page:
write this to your html page,

in getUser.php:
getUser.php
<?php

$link = mysqli_connect("localhost", "user", "pass","mydb");

$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT age,email FROM userstable WHERE name = '".$user."' ");
$row = mysqli_fetch_array($sql);

json_encode($row);die;


text:
Q: file_get_contents() on network fails. Php - windows 7 I've been searching the internet for the solution but I still can't find the answer on copying through file network using php.
Please see my sample code ang its output:
<?php
$source = ("file://///server/path/file.txt");
$destination = 'sample.txt';
$data = file_get_contents($source);
$handle = fopen($destination, "w");
if(fwrite($handle, $data)){
echo "success";
fclose($handle);
}
else
{
echo"failed";
fclose($handle);
}
?>

Web output:
failed
destination folder output:
sample.txt with blank contents.
I granted permission to access the file and is available to access using my network. and is using Windows 7 platform
it is very much easy copying a file from your local drive.
what must I do to be able to copy the file from the server?
I even tried \\(computername/ipaddress)\path\file.txt but not worth it. I just make use of google for that said code.
Thanks in advance


text:
Q: Using Oracle Data Integrator 12c with Snowflake We successfully connected Oracle Data Integrator 12c from Oracle Cloud Infrastructure to Snowflake but when we run mappings which make use of the ODI Knowledge Modules, we are seeing batches of data being sent in small chunks via separate SQLIDs.  Does anyone have experience with using Oracle Data Integrator with Snowflake, cross cloud?  Any tips on how to process more records at once other than writing the records to a file first and loading the files?  That sort of defeats the purpose, I think.

A: I'm not sure how the Oracle Data Integrator works, but for most connectors to Snowflake, the connector SHOULD be creating files and loading them...usually behind the scenes.  Using a COPY INTO command or Snowpipe (both from blob storage) is the BEST way to get data into Snowflake.


text:
Q: obout gridview postback databind Hello i am working with visual studio , asp.net vb.net and using obout gridview
my problem is that it aint updating after inserting new data ( it does only after reloading the page )
i am using the asp.net sql control for selection and insertion
so after something like :
Protected Sub createCategoryBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles createCategoryBtn.Click
.
.
.
 sql1.insert()
 sql1.databind()
 grid1.databind()
.
.
.
END SUB

i still cant see the new row ( only after reloading the page )
i noticed obout grid got rebind option on click in which u can open sql connection and probebly data bind the grid, but i was wondering if i can avoid doing that? ( if thats even the right way to do so with obout gridview )

A: You need grid1.datasource = sql1 before grid1.databind()


text:
Q: Heckman selection model in R manually I would like to calculate a Heckman selection model manually in R.
My problem is that the standard errors are biased. Is there a way to correct these manually as well?
Below my (sample) code from the sampleSelection model (correct SEs), and the manual code (correct Estimates, wrong SEs)
 require(sampleSelection)

data( Mroz87 )
Mroz87$kids <- ( Mroz87$kids5 + Mroz87$kids618 > 0 )

Using sampleSelection
heckman <- selection(selection = lfp ~ age + I(age^2) + faminc + kids + educ, outcome = wage ~ exper + I(exper^2) + educ + city,
                                data = Mroz87, method = "2step")
summary(heckman)

Manually
seleqn1 <- glm(lfp ~ age + I(age^2) + faminc + kids + educ, family=binomial(link="probit"), data=Mroz87)
summary(seleqn1)

# Calculate inverse Mills ratio by hand ##
Mroz87$IMR <- dnorm(seleqn1$linear.predictors)/pnorm(seleqn1$linear.predictors)

# Outcome equation correcting for selection ## ==> correct estimates, wrong SEs
outeqn1 <- lm(wage ~ exper + I(exper^2) + educ + city + IMR, data=Mroz87, subset=(lfp==1))
summary(outeqn1)

A: myprobit    <- probit(lfp ~ age + I(age^2) + faminc + kids + educ - 1, x = TRUE,
                           iterlim = 30, data=Mroz87)

imrData     <- invMillsRatio(myprobit) # same as yours in this particular case
Mroz87$IMR1 <- imrData$IMR1

outeqn1     <- lm(wage ~ -1 + exper + I(exper^2) + educ + city + IMR1,
                  data=Mroz87, subset=(lfp==1))

The main thing was that you use intercept models instead of no-intercept.


text:
Q: asp.net imageurl uses physical path for testing I know that we can't use physical path when the webpage is deployed.
But here is my problem: I'm developing an Application for C# winform and Asp.net webform, the Data folder for the app is huge and I need to put that folder separately from the projects' folders cause it would be convenient to backup my projects to Google drive. The C# winform is easy to link the physical path, but the asp.net webform forces me to put the Data folder inside the project.
My current solution is: putting the Data folder inside the asp.net webform project and link that folder to the C# winform. But it wouldn't be convenient to backup the webform.
But is there any way I can use physical path with asp.net webform just for testing?
Thanks for reading.

A: You can put the folder external to web app folder, then place the path in Web.Config Under AppSettings as
<appSettings>
     <add name="Data_Folder_Path" value="C:\Path\to\Data\Folder" />
 </appSettings>

Then in code behind or elsewheere you need the data path you use Configuration class to read the path value:
var dataFolderPath = System.Configuration.ConfigurationManager.AppSettings["Data_Folder_Path"]

A: You can make use of server.mappath as shown below
Server.MapPath("~/" + folderName + nameOfFile)
to get the location of the files.
You may save the names of the files on your database and retrieve them when needed.


text:
Q: How can I replace icons of an application's executable? I have an application whose executable contains some default icon. Now, I know I can use a shortcut with whatever icon I want, but what I'm looking to do is change the icon without the executable itself. How can I do this?
Notes:

*

*Using Windows 7 64bit, but I'm interested in 32-bit executables as well, which will perhaps run on Win XP etc.

*Keeping the same filesize is a plus, but not necessary.

A: Sounds like a job for Resource Hacker
It allows to change the resources within exe files - including images.
Alternatively, since Resource Hacker is no longer being developed, there is another tool with similar capabilities - Resource Editor.
Edit:
This one as well: reseditor
Edit2: There's more. Resedit

A: Try this :
Right click on your .exe
Property


text:
Q: New Ubuntu install, now reboot startup screen shows ethernet controller for 1 minute I just installed Ubuntu 16.04 on an older computer that I had recently upgraded with a SSD and new graphics card.
The install worked, however when I reboot I get the following screen for about 1 minute.

After about a minute I see this and then ubuntu boots normally 2-3 seconds later

How can I avoid or eliminate this ?

A: In your BIOS setting you have boot order. In the boot order you have 'network' over 'harddisk'. Move 'network' down and it will work.


text:
Q: How to output parts of a string onto a new line in a listbox C# I am having trouble figuring out how to split a concatenated string onto new lines. Am pretty new to c#/coding in general, and am looking for a relatively easy method to show this.
I am not trying to just get an answer, have spent a lot of time researching different split methods online, but most I have seen don't show splitting a concatenated string.
This is my current code:
private string SearchbyPayRate(string term, List<string> PeopleList)

    {try
        {
            string result = "not found"; //initial value of search result

            //prepare for the search item from parameter

            int employeeid = int.Parse(term);

            for (int i = 0; i < PeopleList.Count; i++) //The list is search through one by one
            {   //In order to separate employee id from other items in a line, each line is split into 3 items (fields) by ","
                string[]vals = PeopleList[i].Split(',');
                int id = int.Parse(vals[0]); //Employment id is at the first item
                if (id == employeeid) //Found
                {
                    decimal hours = decimal.Parse(tbxwageworkinghrs.Text);
                    decimal payrate = decimal.Parse(vals[2]);
                    decimal wage = hours * payrate;

                    result = "Employee " + vals[0] + " Wage Details:" + "Pay rate is $" + vals[2] + " Working hours is " + hours + "Wage is $" + wage;

                }
            }
            return result; //Send a single result string back to the main program which calls this method
        }
    catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return null;
        }
   }

    private void btngrosspay_Click(object sender, EventArgs e)
    {try

        {//Saved data file needs to be loaded before the search
            if (People == null)
            {
                MessageBox.Show("No data is loaded from saved file!", "Click button \"Load File\""); }
                //Display special symbol, \ is used
                else
            {   //A single variable is used to receive only one search result by calling a SearchbyPayRate method
                //This method has two parameters, employee id from textbox and a list of loaded people data from the daved file
                string eidResult = SearchbyPayRate(tbxwageempid.Text, People);
                //Output the single result
                lbxwagedetails.Items.Clear();
                lbxwagedetails.Items.Add(eidResult);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Currently the listbox output is all on one line like this:
Employee 1 Wage Details: Pay rate is $20 Working hours is 25 Wage is $500.00
I want the listbox output to look like this:
Employee 1 Wage Details:
Pay rate is $20
Working hours is 25
Wage is $500.00
Any suggestions/ideas would be greatly appreciated.
Thanks

A: I suggest parsing into out parameters referring to a BindingList<String>.
You could alternatively use an ArrayList<String> (or possibly some other class or struct?) and return that instead of a string. After all, the idea of extracting your strings from CSV format was to turn them into multiple strings, right? Recombining them is just a step backwards.
You'll then want btngrosspay_Click to iterate on the multiple items in the List (whichever one you used; they both iterate the same way), to add each item to the list as a separate list entry... or if you're using a class or struct, you'll want to individually add each member as an item to the list.

A: you need to set Return result string with comma separate, add comma where ever you want break line like string eidResult = "Result : 10%,Marks :5". Now when you add in ListBox with Using ListBox.AddRange(eidResult.Split(',').ToArray()), I Hope you'll get your solution
      private string SearchbyPayRate(string term, List<string> PeopleList)

     {try
         {
          string result = "not found"; //initial value of search result

        //prepare for the search item from parameter

        int employeeid = int.Parse(term);

        for (int i = 0; i < PeopleList.Count; i++) //The list is search through one by one
        {   //In order to separate employee id from other items in a line, each line is split into 3 items (fields) by ","
            string[]vals = PeopleList[i].Split(',');
            int id = int.Parse(vals[0]); //Employment id is at the first item
            if (id == employeeid) //Found
            {
                decimal hours = decimal.Parse(tbxwageworkinghrs.Text);
                decimal payrate = decimal.Parse(vals[2]);
                decimal wage = hours * payrate;

                result = "Employee " + vals[0] + " Wage Details:" + ",Pay rate is $" + vals[2] + ",Working hours is " + hours + ",Wage is $" + wage;

            }
        }
        return result; //Send a single result string back to the main program which calls this method
    }
catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null;
    }
    }

private void btngrosspay_Click(object sender, EventArgs e)
{try

    {//Saved data file needs to be loaded before the search
        if (People == null)
        {
            MessageBox.Show("No data is loaded from saved file!", "Click button \"Load File\""); }
            //Display special symbol, \ is used
            else
        {   //A single variable is used to receive only one search result by calling a SearchbyPayRate method
            //This method has two parameters, employee id from textbox and a list of loaded people data from the daved file
            string eidResult = SearchbyPayRate(tbxwageempid.Text, People);
            //Output the single result
            lbxwagedetails.Items.Clear();
            lbxwagedetails.Items.AddRange(eidResult.Split(',').ToArray());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}


text:
Q: Control.Slider is not a constructor New Extension Problem 1.9.2.4 I have just paid $150 for an extension from MageStore (Reward Points Plus) and it is not working.
The error I am getting is:
prototype.js:828 Uncaught TypeError: Control.Slider is not a constructor

In the extension JS the code is:
    var RewardPointsSlider = Class.create();
RewardPointsSlider.prototype = {
    initialize: function (pointEl, trackEl, handleEl, zoomOutEl, zoomInEl, pointLbl) {
        this.pointEl = $(pointEl);
        this.trackEl = $(trackEl);
        this.handleEl = $(handleEl);
        this.pointLbl = $(pointLbl);

        this.minPoints = 0;
        this.maxPoints = 1;
        this.pointStep = 1;

        this.slider = new Control.Slider(this.handleEl, this.trackEl, {
            axis: 'horizontal',
            range: $R(this.minPoints, this.maxPoints),
            values: this.availableValue(),
            onSlide: this.changePoint.bind(this),
            onChange: this.changePoint.bind(this)
        });
        this.changePointCallback = function (v) {
        };

        Event.observe($(zoomOutEl), 'click', this.zoomOut.bind(this));
        Event.observe($(zoomInEl), 'click', this.zoomIn.bind(this));
    },
    availableValue: function () {
        var values = [];
        for (var i = this.minPoints; i <= this.maxPoints; i += this.pointStep) {
            values.push(i);
        }
        return values;
    },
    applyOptions: function (options) {
        this.minPoints = options.minPoints || this.minPoints;
        this.maxPoints = options.maxPoints || this.maxPoints;
        this.pointStep = options.pointStep || this.pointStep;

        this.slider.range = $R(this.minPoints, this.maxPoints);
        this.slider.allowedValues = this.availableValue();

        this.manualChange(this.slider.value);
    },
    changePoint: function (points) {
        this.pointEl.value = points;
        if (this.pointLbl) {
            this.pointLbl.innerHTML = points;
        }
        if (typeof this.changePointCallback == 'function') {
            this.changePointCallback(points);
        }
    },
    zoomOut: function () {
        var curVal = this.slider.value - this.pointStep;
        if (curVal >= this.minPoints) {
            this.slider.value = curVal;
            this.slider.setValue(curVal);
            this.changePoint(curVal);
        }
    },
    zoomIn: function () {
        var curVal = this.slider.value + this.pointStep;
        if (curVal <= this.maxPoints) {
            this.slider.value = curVal;
            this.slider.setValue(curVal);
            this.changePoint(curVal);
        }
    },
    manualChange: function (points) {
        points = this.slider.getNearestValue(parseInt(points));
        this.slider.value = points;
        this.slider.setValue(points);
        this.changePoint(points);
    },
    changeUseMaxpoint: function (event) {
        var checkEl = event.element();
        if (checkEl.checked) {
            this.manualChange(this.maxPoints);
        } else {
            this.manualChange(0);
        }
    },
    changeUseMaxpointEvent: function (checkEl) {
        Event.observe($(checkEl), 'click', this.changeUseMaxpoint.bind(this));
    },
    manualChangePoint: function (event) {
        var changeEl = event.element();
        this.manualChange(changeEl.value);
    },
    manualChangePointEvent: function (changeEl) {
        Event.observe($(changeEl), 'change', this.manualChangePoint.bind(this));
    }
}

This controls the slider to add discount to the order.
I have contacted Magestore who are not willing to help me until next week as they are on holiday.


text:
Q: How to run oracle 12c report in excel want to run oracle 12 c report in excel
i want to run oracle 12 c report to excel,but not finding the way,i have posted code below please help me

Declare
   pl_id paramlist;
   v_rep_server varchar2(100);
 v_path varchar2(100);

 v_rep varchar2(100);

begin

 v_rep := 'SAMPLE_DETAIL_f.rdf';

 v_rep_server := pckg_erp.f_get_report_server_name(NULL,'192.168.0.231',null,null,null);
 v_path := pckg_erp.f_get_object_path(NULL ,v_rep,'R',null,35,'192.168.0.231',null,null,null);

 WEB_REPORT.SETREPORTSSERVER(v_rep_server);
   WEB_REPORT.setDesformat('xls');

   pl_id:=get_parameter_list('temp');

   if not id_null(pl_id) then
       destroy_parameter_list(pl_id);
   end if;

   pl_id := Create_Parameter_List('temp');

   add_parameter(pl_id,'PARAMFORM',text_parameter,'NO');
   add_parameter (pl_id,'DESTYPE',TEXT_PARAMETER,'LOCALFILE');
   add_parameter (pl_id,'DESFORMAT',TEXT_PARAMETER,'ENHANSEDSPREADSHEET');
   add_parameter(pl_id,'MAXIMIZE',text_parameter,'YES');
WEB_REPORT.RUN_REPORT(reports,v_path||v_rep,synchronous,runtime,filesystem,pl_id,null);

end;


text:
Q: OwlCarousel and bootstrap slide use in website I'm new.when I'm using bootstrap slide show and owl-carousel then bootstrap slide show take owl-carousel CSS how to use that.
carousel item.

bootstrap slide show

A: Well, maybe it depends in what order you are calling your steelsheets. Whithout any code it will be hard to help you.
In my projects I proceed this way
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="web/lib/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="web/lib/owlcarousel/css/owl.carousel.css">
    <link rel="stylesheet" type="text/css" href="web/lib/owlcarousel/css/owl.theme.css">


text:
Q: Sending Mail through G Suite with PHPMailer I'm trying to send email through an email account managed by G Suite. I keep getting a connection error. I've tried changing various setting and using either tls or ssl, but it doesn't seem to make any difference. I have verified the login credentials, so I know those are not the issue. The emails being sent through this account are working properly, so the MX records are also configured correctly.
require "PHPMailer-master/PHPMailerAutoload.php";
include "info/user.inc";

$name = trim(htmlspecialchars($_POST['name']));
$email = trim(htmlspecialchars($_POST['email']));
$subject = trim(htmlspecialchars($_POST['subject']));
$phone = trim(htmlspecialchars($_POST['phone']));
$extension = "Ext. ".trim(htmlspecialchars($_POST['extension']))."";
if($etension == null) {
    $extension = "";
}

$message = nl2br(trim(htmlspecialchars($_POST["message"])));

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; //ssl or tls
$mail->Host = "smtp.gmail.com";
$mail->Port = "587"; //465 or 587
$mail->Username = $user;
$mail->Password = $pass;

$mail->SetFrom($email, $name);
$mail->AddAddress($address);
$mail->AddReplyTo($email);

$mail->WordWrap = 50;
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = $message;

if(!$mail->Send()) {
    echo "Message could not be sent. Please try again later.";
    echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
    header("Location: ../success.html");
}

With debugging set to 2, I get the following error:
2017-12-04 01:24:36 SERVER -> CLIENT: 220-a2ss55.a2hosting.com ESMTP Exim 4.89 #1 Sun, 03 Dec 2017 20:24:36 -0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2017-12-04 01:24:36 CLIENT -> SERVER: EHLO www.tigertorch.ca
2017-12-04 01:24:36 SERVER -> CLIENT: 250-a2ss55.a2hosting.com Hello www.tigertorch.ca [68.66.216.5] 250-SIZE 52428800 250-8BITMIME 250-PIPELINING 250-AUTH PLAIN LOGIN 250-STARTTLS 250 HELP
2017-12-04 01:24:36 CLIENT -> SERVER: STARTTLS
2017-12-04 01:24:36 SERVER -> CLIENT: 220 TLS go ahead
2017-12-04 01:24:36 SMTP Error: Could not connect to SMTP host.
2017-12-04 01:24:36 CLIENT -> SERVER: QUIT
2017-12-04 01:24:36 SERVER -> CLIENT: 221 a2ss55.a2hosting.com closing connection
2017-12-04 01:24:36 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent. Please try again later.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting


text:
Q: How to substitute rows value by condition I want to replace the values of some rows for particular column in the dataframe.
These should be the rows that contain the text that start from ABC. So, the thing is that there are rows with different values besides ABC, e.g. ABC1234, ABC2376, etc. I want to substitute all of them by CDA. How can I do it?

A: gsub can make sed like regex substitution (note that ^ means search at the beginning of the string):
df$column <- gsub("^ABC", "CDA", df$column)


text:
Q: Find the Jordan canonical form $N$ is a nilpotent $15\times15$ matrix over $\mathbb{R}$ such that $$\dim(\ker N) = 5, \quad \dim (\ker{N^2}) =8, \quad \dim(\ker{N^3})= 11,$$ $$\dim (\ker{N^4}) = 13, \quad \dim(\ker{N^5}) =15$$ Find the Jordan form.

A: Since $\dim\text{Ker}(N^4)= 13$ and $\dim\text{Ker}(N^5)= 15$ the maximal Jordan block is of size 5, and you have exactly two Jordan blocks $J_1$ and $J_2$ of size 5, indeed, if there are no such blocks the $N^4=0$ otherwise if there is just one such  block then $\dim\text{Ker}(N^4)= 14$. So it remains to calculate other blocks. Since $\dim\text{Ker}(N)= 5$ and the blocks $J_1$ and $J_2$ give you 2 vector of the kernel, then the other block must have in total 3 vector of the kernel, so the third jordan block cannot be of size 5 neither 4. Assume that $J_3$ has size 3 hence it gives you one vector of the kernel, and so the only other possibility are $J_4=J_5=0$ the $1\times 1$ $0-$matrix. Actually in this case you have $\dim\text{Ker}(N)= 5$ $\dim\text{Ker}(N^2)= 2+2+2+1+1=8$,$\dim\text{Ker}(N^3)= 3+3+3+1+1= 11$ and $\dim\text{Ker}(N^4)= 4+4+3+1+1=13$.
Moreover it is easy to check that other combinations do not satisfie all condition.


text:
Q: Building a Tree Widget in GWT I am trying to build a Tree Structure in GWT which gets to be scrollable when the number of items are large, the Tree structure will permanently reside on the WestRegion of my Application DockLayout Panel.
The Main code:
<!-- The west side has a panel with complex dynamic tree list to be implemented -->
    <g:west size='14'>
        <app:Mainlist ui:field='mainlist'/>
    </g:west>

The Mainlist:
  <g:VerticalPanel>
    <g:ScrollPanel>
        <g:HTMLPanel width='100%' >
            <div class='{style.contentColumn}'>
                <g:Tree ui:field='citytree'>
                    <g:TreeItem text='Delhi/NCR'/>
            </g:Tree>
            </div>
        </g:HTMLPanel>
    </g:ScrollPanel>
  </g:VerticalPanel>
</ui:UiBinder>

However I dont see anything in the west region. Can anyone point out what am I doing wrong?
Moreover:
In the corresponding "Mainlist.java" file I cannot say @UiField Tree citytree(Gives Exception) . This seems to be because of the nesting involved. How do I access my Tree instance?
The GWT showcase has Tree built without using UiBinder. Moreover I could not find any sample code to build a Tree structure with UiBinder. Any resources?

A: After searching and exploring more. I did it. I think theere is no example code online so this post might be helpfull for learners like me.
<ui:with field='res' type='myth.social.zomato.client.Mainlist.Images' />

    <ui:style src="resources/GlobalStyles.css">

    </ui:style>

        <g:Tree ui:field='tree' resources='{res}'>
            <g:TreeItem text='Cities' >
                <g:TreeItem text='Ahemadabad'/>
                <g:TreeItem text='Banglore'/>
                <g:TreeItem text='Chennai' />
                <g:TreeItem text='Delhi/NCR' />
                <g:TreeItem text='Hyderabad' />
                <g:TreeItem text='Jaipur' />
                <g:TreeItem text='Kolkata'/>
                <g:TreeItem text='Mumbai'/>
                <g:TreeItem text='Pune' />
            </g:TreeItem>

            <g:TreeItem text='SalesPerson'>
                <g:TreeItem text='Sales1' />
                <g:TreeItem text='Sales2' />
            </g:TreeItem>

        </g:Tree>


text:
Q: Function to Convert Square Matrix to Upper Hessenberg with Similarity Transformations I am attempting to translate a MATLAB function to Python from Timothy Sauer,
Numerical Analysis Second Edition, page 546, Program 12.8.  The original function
receives a square matrix and returns a matrix with the same eigenvalues but in
Upper Hessenberg form.  The original function creates Householder reflectors to produce zeros in the
offdiagonals of the matrix and performs similarity transformations on the original matrix to
get it to upper hessenberg form.
My Python translation succeeds only in obtaining the eigenvalues for 3x3 matrices
but not for 4x4 matrices.  Would anyone know the cause of the error?  I pasted my code with success and failing cases below.  Thank you.

import numpy as np
import math

norm = lambda v:math.sqrt(np.sum(v**2))

def upper_hessenberg(A):
    '''
    Translated from Timothy Sauer, Numerical Analysis Second Edition, page 546, Program 12.8
    Input:  Square Matrix, A
    Output: B, a Similar Matrix with Same Eigenvalues as A except in Upper Hessenberg form
            V, a matrix containing the reflectors used to produce zeros in the off diagonals
    '''
    rows, columns   = A.shape
    B               = A[:,:].astype(np.float)                    #will store the similar matrix
    V               = np.zeros(shape=(rows,columns),dtype=float) #will store the reflectors

    for column in range(columns-2): #start from the 1st column end at the third to last column
        row                 = column
        x                   = B[row+1: ,column] #decapitate the column
        reflection_of_x     = np.zeros(len(x))  #first entry is the norm, followed by 0s
        if abs(norm(x)) <= np.finfo(float).eps: #if there are already 0s inthe offdiagonals skip this column
            continue
        reflection_of_x[0]  = norm(x)

        v   = reflection_of_x - x # v, (the difference vector) represents the line connecting the original column to the reflection of the column (see Timothy Sauer Num Analysis 2nd Edition Figure 4.11 Householder reflector)
        v   = v/norm(v) #normalize to length of 1 (unit vector)
        V[:len(v), column]    = v #save the reflector in an upper triangular matrix called V
        #verify with x-2*(x @ v * v) should equal a vector with all zeros except the leading entry

        column_projections   =  np.outer(v , v @ B[row+1:, column:])    #project each col onto difference vector
        B[row+1:, column:]   = B[row+1:, column:] - (2 * column_projections)
        row_projections      = np.outer(v, B[row:, column + 1:] @ v).T  #project each row onto difference vector
        B[row:, column + 1:] = B[row:, column + 1:] - (2 * row_projections)
    return V, B

# Algorithm succeeds only with 3x3 matrices
eigvectors = np.array([
    [1,3,2],
    [4,5,6],
    [7,8,9],
])
eigvalues = np.array([
    [4,0,0],
    [0,3,0],
    [0,0,2]
])
M = eigvectors @ eigvalues @ np.linalg.inv(eigvectors)
print("The expected eigvals :", np.linalg.eigvals(M))
V,B = upper_hessenberg(M)
print("For 3x3 matrices, The function successfully produces these eigvals",np.linalg.eigvals(B))

#But with 4x4 matrices it fails
eigvectors = np.array([
    [1,3,2,4],
    [4,5,6,2],
    [7,8,9,5],
    [5,2,7,8]
])
eigvalues = np.array([
    [4,0,0,0],
    [0,3,0,0],
    [0,0,2,0],
    [0,0,0,1]
])
M = eigvectors @ eigvalues @ np.linalg.inv(eigvectors)
print("The expected eigvals :", np.linalg.eigvals(M))
V,B = upper_hessenberg(M)
print("For 4x4 matrices, The function fails to obtain correct eigvals",np.linalg.eigvals(B))

A: Your error is that you try to be too efficient. While the last rows are indeed increasingly reduced with leading zeros, this is not the case for the last columns. So in row_projections you need to remove the limiter row:, change to B[:, column + 1:].

You are using the unstable variant of the "improved" Householder reflector. The older version would use the larger of x_refl - x and x_refl + x by setting reflection_of_x[0]  = -np.sign(x[0])*norm(x) (or remove all minus signs there).
The stable variant of the improved reflector would use the binomial trick in the normalization of x_refl - x if this difference becomes too small.
x_refl - x = [ norm(x) - x[0], - x[1:] ]
           = [ norm(x[1:])^2/(norm(x) + x[0]), - x[1:] ]

(x_refl - x)/norm(x_refl - x)

              [ norm(x[1:]), - (norm(x)+x[0])*(x[1:]/norm(x[1:])) ]
           = -----------------------------------------------------
                     sqrt(2*norm(x)*(norm(x)+x[0]))

While the parts may have wildly different scales, no catastrophic cancellation happens for x[0]>0.
See the discussion about the same algorithm from Golub/van Loan 4th ed. in for further details and opinions and the code from that book.


text:
Q: Ionic typeerror: 'null' is not an object (evaluating 'content.offsetx') When i run my ionic / angular mobile app on my iphone 4 with ios 7 i get this error when i click a navigation link in the side menu, and it blocks the rest of the app from running
typeerror: 'null' is not an object (evaluating 'content.offsetx')
anyone ever get this before?
heres some code but I'm not sure if it will help

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic',  'starter.controllers', 'arvak.forms', 'angular-locker', 'ngSlider', 'arvak.configs', 'widgets.camera', 'widgets.signature', 'ngCordova', 'widgets.barcodeScanner' ])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
    //iOS 8 bug
    //http://forum.ionicframework.com/t/click-a-input-field-whole-app-jumps-down-and-back-to-the-original-place/10876/15
    if(window.cordova && window.cordova.plugins.Keyboard) {
       window.cordova.plugins.Keyboard.disableScroll(true);
    }

  });
})

.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
  //$locationProvider.html5Mode(true);

    //$urlRouterProvider.when('', '/');

  $stateProvider

      .state('index', {
        url: '/',
        templateUrl: 'index.html'
      })

      .state('app', {
        url: "/app",
        abstract: true,
        templateUrl: "templates/menu.html",
        controller: 'AppCtrl'
      })

      .state('app.search', {
        url: "/search",
        views: {
          'menuContent': {
            templateUrl: "templates/search.html",
            controller: 'SearchController'
          }
        }
      })
      .state('app.form', {
        url: "/forms",
        views: {
          'menuContent': {
            templateUrl: "js/forms/templates/forms/formWrapper.html",
            controller: 'FormsController'
          }
        }
      })

      .state('app.browse', {
        url: "/browse",
        views: {
          'menuContent': {
            templateUrl: "templates/browse.html",
            controller: 'BrowseController'
          }
        }
      })
        .state('app.playlists', {
          url: "/playlists",
          views: {
            'menuContent': {
              templateUrl: "templates/playlists.html",
              controller: 'PlaylistsCtrl'
            }
          }
        })

      .state('app.single', {
        url: "/playlists/:playlistId",
        views: {
          'menuContent': {
            templateUrl: "templates/playlist.html",
            controller: 'PlaylistCtrl'
          }
        }
      })
      .state('app.camera', {
          url: "/camera",
          views: {
              'menuContent': {
                  templateUrl: "templates/camera.html"
                  //controller: 'CameraControler'
              }
          }
      })

        .state('app.signature', {
            url: "/signature",
            views: {
                'menuContent': {
                    templateUrl: "templates/signature.html"
                    //controller: 'CameraControler'
                }
            }
        })

      .state('app.barcode', {
          url: "/barcode",
          views: {
              'menuContent': {
                  templateUrl: "templates/barcode.html"
                  //controller: 'CameraControler'
              }
          }
      });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/forms');
});
<ion-side-menus enable-menu-with-back-views="false">
  <ion-side-menu-content>
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>

      <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="menuContent"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="left">
    <ion-header-bar class="bar-stable">

Left

    </ion-header-bar>
    <ion-content>
      <ion-list>
        <ion-item nav-clear menu-close ng-click="login()">
          Login
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/search">
          Search
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/forms">
          Form
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/playlists">
          Tasks
        </ion-item>
          <ion-item nav-clear menu-close href="#/app/camera">
              Camera
          </ion-item>
          <ion-item nav-clear menu-close href="#/app/signature">
              signature
          </ion-item>
          <ion-item nav-clear menu-close href="#/app/barcode">
              barcode scanner
          </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="lib/ng-slider/css/ng-slider.min.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

     <ion-nav-view class="slide-left-right"></ion-nav-view>


text:
Q: Isn't inline premature optimization?
Possible Duplicate:
Inline functions in C++

Modern compilers are better than programmers at deciding what should be inlined and what should not. Just like, register, shouldn't inlining functions be a job for the compiler only, and be considered premature optimization ?

A: inline has a double meaning that some are unaware of - it allows a function to be defined in more than one translation unit (i.e. if you define an unbound function in a header and include it from within various translation units, you are forced to declare it inline or the linker would complain about doubly defined symbols).
The second meaning is a hint to the compiler that this function may profit from inlining its machine code at the caller site. You're right, modern compilers/optimizers should be able to figure this out on his own.
My advice is to use inline only when it is needed (first case) and never to pass an optimization hint to the compiler. This way, this crazy double meaning is resolved in your source code.

A: inline is only tangentially related to optimization.
You should choose to apply inline to a function if you need the exceptions to the one definition rule that it gives you, and leave it out if you don't. Most of the time you can rely on the compiler to perform the appropriate optimizations independent of whether a function is declared inline or not.

A: Check out this answer: Inlining this function or not?
Essentially, yes, inlining is a task of the compiler at this point. Inlining was initially created to indicate to the compiler that it should try. The keyword is indicate - The compiler has the choice as to whether or not it inlines the function or not.


text:
Q: Some menu items wont budge add_action('admin_menu', 'remove_admin_menu_links');
        function remove_admin_menu_links(){
            $user = wp_get_current_user();
            if( $user && isset($user->user_email) && 'email@address.com' == $user->user_email ) {

                remove_menu_page('upload.php'); // Media - works(remove)

                remove_menu_page( 'gf_edit_forms' ); //Forms - doesn't work(visibile)

                remove_menu_page('edit.php?post_type=page'); // Pages - works(removed)

                remove_menu_page('wpseo_dashboard'); // SEO  - works(remove)
                remove_menu_page('admin.php?page=wpseo_dashboard'); // SEO  - works(remove)

                remove_menu_page('envanto-market'); // Envanto Market  - doesn't work(visibile)
                remove_menu_page('admin.php?page=envanto-market'); // Envanto Market - doesn't work(visibile)

                remove_menu_page('gadwp_settings'); // Google Analytics - doesn't work(visibile)
                remove_menu_page('admin.php?page=gadwp_settings'); // Google Analytics - doesn't work(visibile)
        }
    }

add_action( 'admin_menu', 'remove_admin_menus_links' , 9999 );

Outlined above shows the action added to remove menu items from a specific admin users menu items.
I cant seem to be able to remove Forms, Envanto Market or Google Analytics. The rest of the menu items have been removed, bit I cant figure out why these few don't appear to moving.
If anyone can see why these menu items are still available?
Also, there is a full list of these menu items still available in the admin_bar_menu, new_Post option at the top of the page. If Anyone can point me in the right direction to remove these too?
I've tried adding to functions.php:
// admin_bar_menu hook
add_action('admin_bar_menu', 'update_adminbar', 999);

and in the /plugins/admin_bar.php :
<?php
// update toolbar
function update_adminbar($wp_adminbar) {

  // remove unnecessary items
  $wp_adminbar->remove_node('wp-logo');
  $wp_adminbar->remove_node('customize');
  $wp_adminbar->remove_node('comments');
  $wp_adminbar->remove_node('post-new');

}
?>

A: There's a typo on your callback function name.
add_action( 'admin_menu', 'remove_admin_menus_links' , 9999 );

should be:
add_action( 'admin_menu', 'remove_admin_menu_links' , 9999 );

If you correct that, the action will get fired later and the GADWP menu link will get removed.

A: The admin bar is hooked incorrectly.It should be hooked to wp_before_admin_bar_render.
This is what I use (and works):
function alter_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu( 'customize' );
    $wp_admin_bar->remove_menu( 'ddw-gravityforms-toolbar' );
    $wp_admin_bar->remove_menu( 'members-new-role' );
    $wp_admin_bar->remove_menu( 'new-media' );
    $wp_admin_bar->remove_menu( 'new-post' );
    $wp_admin_bar->remove_menu( 'new-user' );
    $wp_admin_bar->remove_menu( 'wp-logo' );
}
add_action( 'wp_before_admin_bar_render', 'alter_admin_bar' );

Regarding the side menu I don't know. My first guess would be that you're using incorrect identifiers.


text:
Q: How to co-author Word documents? I am trying to understand how to edit Word documents concurrently with other users in my team at work.
Currently if someone open the document for editing, then the others can only open it in read only mode.
I tried to search Google about this issue and got confused.
Some of the results mention SkyDrive as a must have to be able to use this functionality. As far as I understand, SkyDrive is Microsoft server to share documents through the web. This is not necessary since the people I need to share my documents work in the next room in the same office.
In other results they say that you need Sharepoint to allow this functionality, others have said that it's build-in behavior of Word 2010.
So which of these is the truth?
Another thing that I need to figure out is how online synchronization can be achieved?
Can I get the latest changes from my colleagues whenever I press save to save my changes?

A: If you don't care about integrity of your data, and locking for changes, then you can do it with Skydrive or Dropbox.
On the other hand, if you actually want to do it properly, then you'll have to use something like Sharepoint, or Google Docs - which actually have decent multi-user editing capabilities.
Microsoft are now doing some kind of hosted sharepoint type SaaS thing, I think it's Office365 or something.

A: To collaborate you have to save the document to OneDrive or SharePoint Online.
Then invite people to edit it with you. They can open the document in Word 2016, Word Online and Word Android and you'll see each other's changes.
From: https://support.office.com/en-us/article/Collaborate-on-Word-documents-with-real-time-co-authoring-7dd3040c-3f30-4fdd-bab0-8586492a1f1d#ID0EABAAA=Windows


text:
Q: awk select line with variable, cannot open no such file I'm struggling with a basic awk command.
File 1 :
AB253828.1
AB253829.1
AB253830.1
AB253831.1

File 2 :
accession   accession.version   taxid   gi
A00001  A00001.1    10641   58418
A00002  A00002.1    9913    2
A00003  A00003.1    9913    3
A00004  A00004.1    32630   57971
A00005  A00005.1    32630   57972
A00006  A00006.1    32630   57973
A00008  A00008.1    32630   57974
A00009  A00009.1    32630   57975
A00010  A00010.1    32630   57976

both file have >1 000 000 lines
I would like to print columns 2 and 3 of file 2 if column 2 corresponds to the patterns of file 1
I tried a lot of possibilities but none work...
for ACC in $(cat file1.txt)
do
    #ACC1=$(echo "\"$ACC\"")
    awk -v OFS='\t'-v z="$ACC" '{ if($2 == z) { print $2,$3 } }' file2.txt
done

I got

awk: cannot open { if($2 == z) { print $2,$3 } } file2.txt (No such file or directory)

I checked, file2 is there. I suppose, my problem is the variable z but I can't find the solution.

A: The immediate problem is that you are missing a space before the second -v option. (Look closely: you are setting the OFS to \t-v and then Awk thinks z="$ACC" is your actual Awk script, and looks for - and complains about the lack of - a file named ... your Awk script's contents.) But really, you want to overhaul this more thoroughly.
awk -v OFS='\t' 'NR==FNR { z[$1]++; next }
    $2 in z { print $2,$3 }' file1.txt file2.txt

This uses a common Awk idiom for reading the first file into memory, then printing out the records from the second whose second field existed as an entry in the first file.  This should be orders of magnitude faster, as well as of course trivially fix the reading lines with for antipattern.
If the first file is too large to fit into memory at once, maybe partition it into smaller pieces (say 500,000 lines each?) and run this on each of those separately.  It should be easy to see when Awk consumes so much memory that your system starts thrashing; at least during the first few runs, keep an eye on top or some similar monitoring tool and kill the process if it misbehaves.


text:
Q: relatively prime ideals $p_1\cap p_2+p_3=(1)$ when $p_1,p_2$ and $p_3$ are relatively prime Let $R$ be a ring. If $p_1,p_2,p_3$ are three pairwise relatively prime ideals, then $p_1\cap p_2+p_3=(1)$.
I just want to confirm my method is correct.
Since $p_1+p_3=(1)$ and $p_2+p_3=(1)$, $(p_1+p_3)(p_2+p_3)=(1)$. $LHS=p_1p_2+p_3^2+p_3(p_1+p_2)=p_1p_2+p_3^2+p_3=p_1p_2+p_3$ as $p_3^2\subset p_3$. So we obtain equality by $p_1,p_2$ relatively prime.

A: Your proof is correct, but it can be shortened.
Let $1=a+b=c+d$, where $a\in p_1$, $c\in p_2$, $b,d\in p_3$; then
$$
1=(a+b)(c+d)=ac+(bc+ad+bd)\in p_1p_2+p_3
$$
Since $p_1p_2\subseteq p_1\cap p_2$, we are done.
Note that the hypothesis that $p_1$ and $p_2$ are coprime is not needed.


text:
Q: Return the date of the day under an if formula with Excel or VBA I have two columns A and B and many lines with some specific tasks to be done. In column B, I have a drop-down list with the name of people who are scheduled for the task . And in column A, I want the date of the day the person signed off the task.
What should I do in VBA or in Excel so that, for example, when somebody signs off a task in the cell B11, A11 returns me the date of the day.
I have used the formula below in A11
=if (B11<>"", today(),"") but everytime i open the file the date is updated. So it doesn't allow me to keep track of everybody's work.
I tried with vba but couldn't write a function that gives me the right answer.
i'm pretty new at vba so i'm sorry if my question sounds stupid

A: I spent 5min playing around with the below macro that I found here:
Private Sub Worksheet_Change(ByVal Target As Range)
  Range("S" & Target.Row) = Date
End Sub

It will put the current Date in Column S, anytime anything in the selected row is changed.  It might be possible to adjust the macro to look for changes in a particular cell or column.


text:
Q: Capturing the error message downloading file with nodejs I am download a file from nodejs.
When there is an error in backend, I need to send a message to front end.
My problem is that I am unable to capture that message.
I know there is some problem related to use blob and json, on back end.
But I didn´t solve it.
My code in line:
console.log(error.response.data.message)

allways returns "undefined"
//front end
    try{
        let response = await axios.post('/generateLoteXMLZIPConsulta');
        let blob = await new Blob([response.data], {
          type: "application/zip",
        });
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = window.URL.createObjectURL(blob);
        const fileName = response.headers["content-disposition"].match(
          /filename=(.*)/
        )[1];
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }catch(error){
      console.log(error.response.data.message)
    }
         //backend nodejs
         router.post("/generateLoteXMLZIPConsulta", async (req, res) => {
            ....
            ....
            try
               res.download(
                    path.resolve(__dirname, "../../file.zip"),
                    "xmlFile.zip"
            );
            catch (error){
               res.removeHeader("Content-disposition");
               res.status(400).json({ message: "You got an error" });
            }
        })

A: First of all, there are a few mistakes in your code:
...
  try {
    // you have to tell axios how to handle response with `responseType`
    let response = await axios.post('/generateLoteXMLZIPConsulta');

    // no need to use await here
    let blob = await new Blob([response.data], {
      type: "application/zip",
    });

    const link = document.createElement("a");

    // no need since you didn't append this element into DOM
    link.style.display = "none";

    link.href = window.URL.createObjectURL(blob);
    const fileName = response.headers["content-disposition"].match(
      /filename=(.*)/
    )[1];
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  } catch (error) {
    console.log(error.response.data.message)
  }
...

This is my reproduce code:
// backend

app.post('/foo', async (req, res) => {
  try {
    // throw 'Something went wrong'
    res.download(path.resolve('bar.zip'))
  } catch {
    res.status(400).json({ message: 'You got an error' })
  }
})

// frontend

;(async function () {
  try {
    // with blob response you have no need to wrap response data to create blob again
    // {} is required otherwise axios will treat { responseType } as data
    let response = await axios.post('/foo', {}, { responseType: 'blob' })
    let blob = response.data
    console.log(window.URL.createObjectURL(blob))
  } catch (error) {
    console.log(error.response.data)
  }
})()

This is working so far except when backend throw an error, axios will treat the response as blob as we set. So we have to convert it back to json.
axios.interceptors.response.use(null, async error => {
  if (error.response.request.responseType === 'blob') {
    // you may need to add an error handler if the response is not JSON
    error.response.data = await new Promise(resolve => {
      let reader = new FileReader()
      reader.addEventListener('load', () => {
        resolve(JSON.parse(reader.result))
      })
      reader.readAsText(error.response.data)
    })
  }
  throw error
});

This is related Github issue.


text:
Q: Unity3D: NullReferenceException: Object reference not set to an instance of an object I want to access Hero.class variable "aspect" from laserController.class, but I receive an error message : NullReferenceException: Object reference not set to an instance of an object.
Hero.class
using UnityEngine;
using System.Collections;

public class Hero : MonoBehaviour {

public float aspect = 0.1f;
void Update () {

    }
}

laserController.class
using UnityEngine;
using System.Collections;

public class laserController : MonoBehaviour {

public float health = 0f;
//public float aspect = 0.1f;

void OnCollisionEnter(Collision collision) {
    if(collision.gameObject.tag == "enemy"){
        Destroy(gameObject);
        Destroy(collision.gameObject);
    }
 }

void Update () {

    Hero direction = gameObject.GetComponent<Hero>();

    //LaserHealth
    health += Time.deltaTime;

    if(health > 7f){
        Destroy(gameObject);
    }
    //problem in here
    transform.Translate(Vector3.up * -direction.aspect);

    }
}

A: I guess your Hero component isn't attached to the same GameObject where laserController is attached to.
If you want to force that condition you can use a RequireComponentAttribute:
[RequireComponent(typeof(Hero))]
public class laserController : MonoBehaviour

Some other unrelated consideration:

*

*Defining a empty Update method is useless and has performances overhead

*Try to follow consistence naming conventions for classes (camel case: laserController -> LaserController)


text:
Q: Need help on sorting my file alphabetically, with a simple code f = ("name list.txt","r")
f.sort()
for lines in f:
   print(f)

This brings an error message saying

"tuple" object has no attribute f.sort()

A: Assuming this is python,
f = ("name list.txt","r")

is not what you want.  The parentheses here create a tuple of two strings.  I believe you intended to do:
f = open("name list.txt","r")

This won't fix your problem, because a file object does not have a sort method either, but it's a step in the right direction.  You might be looking for lines = f.readlines(); lines.sort()

A: Short version
You should open the file, then use the sorted function to do a non-in-place sort, then store that to a variable:
with open("name list.txt","r") as fobj:
    res = sorted(fobj)

res will be what you want, a sorted list of strings.
More detailed explanation
sorted automatically goes through each line in the file, extracts the text from that line, then sorts all the lines.  This is because, in Python, files are considered iterables, you can loop over them line-by-line (like for line in fobj), and sorted accepts iterables.
with is used because it will safely close the file when everything is over, even if there is an exception.  fobj = open("name list.txt","r") requires you to remember to close it afterwards, and may close if there is an exception.  with takes cares of that all for you.
If you don't want newlines at the end of each line, do this:
with open("name list.txt","r") as fobj:
    res = sorted(line.strip('\n') for line in fobj)

This is basically the same as above, except it goes through each  line and strips the newline character before sorting.

A: This is the simplest way I can think of to do what you want:
with open("name list.txt", "r") as f:
    for line in sorted(f.read().splitlines()):
       print(line)


text:
Q: How to filter on two values in an array of objects in Jsonata? In the array there are 5 unique objects, but the objects have some values that are duplicated. Is there a way to filter the objects based on two of the values? In this case how would I return four objects, removing the object that has duplicated "num":"999" and "name":"thing A"? Either the first object or the fourth can be removed.
{
  "array":[
    {
      "id":"1",
      "num":"999",
      "name":"thing A"
    },
    {
      "id":"2",
      "num":"888",
      "name":"thing A"
    },
    {
      "id":"3",
      "num":"777",
      "name":"thing B"
    },
    {
      "id":"4",
      "num":"999",
      "name":"thing A"
    },
    {
      "id":"5",
      "num":"999",
      "name":"thing B"
    }
  ]
}

Results can be
Either:
{
  "array":[
    {
      "id":"2",
      "num":"888",
      "name":"thing A"
    },
    {
      "id":"3",
      "num":"777",
      "name":"thing B"
    },
    {
      "id":"4",
      "num":"999",
      "name":"thing A"
    },
    {
      "id":"5",
      "num":"999",
      "name":"thing B"
    }
  ]
}

Or:
{
  "array":[
    {
      "id":"1",
      "num":"999",
      "name":"thing A"
    },
    {
      "id":"2",
      "num":"888",
      "name":"thing A"
    },
    {
      "id":"3",
      "num":"777",
      "name":"thing B"
    },
    {
      "id":"5",
      "num":"999",
      "name":"thing B"
    }
  ]
}

A: You can use the $reduce function to filter out duplicates:
{
  "array": $reduce(array, function ($acc, $item) {(
    $alreadyExistsInAcc := $acc[num = $item.num and name = $item.name];
    $alreadyExistsInAcc ? $acc : $append($acc, $item)
  )}, [])
}

Check it out on the playground: https://stedi.link/5CNdBAZ


text:
Q: How do we mutate a string in Javascript I have a string t2 and I want to mutate this string based on the below if condition . I tried .replace but it doesnt work.
t2 = "
"+tp_info.elements["info"].cdatas.join.strip+"
"

if (tp_info.attributes["ITcoded"]== "true")
                t2= t2.replace(t2,"
"+tp_info.elements["info"].cdatas.join.strip+"
");
                end

Thanks!

A: There's no need to use .replace() to substitute the entire string:
t2 = t2.replace(t2, ...);

At that point, you can just assign the replacement directly:
t2 = "
"+tp_info.elements["info"].cdatas.join.strip+"
";

Though, since the difference between them is in the class names, you might consider trying to determine those ahead of time and build the markup string afterwards.
var t2_class = ['coded_true'];

if (tp_info.attributes["ITcoded"] == "true") {
    t2_class.push('ITcoded_true');
}

var t2 = "
"+tp_info.elements["info"].cdatas.join.strip+"
"

A: Did you mean to do t2.replace(t2, ... ?  This should always replace the entire string by the definition of the replace function because your search term is the string itself:
http://www.w3schools.com/jsref/jsref_replace.asp


text:
Q: How do I add data labels to a ggplot histogram with a log(x) axis? I am wondering how to add data labels to a ggplot showing the true value of the data points when the x-axis is in log scale.
I have this data:
date <- c("4/3/2021", "4/7/2021","4/10/2021","4/12/2021","4/13/2021","4/13/2021")
amount <- c(105.00, 96.32, 89.00, 80.84, 121.82, 159.38)
address <- c("A","B","C","D","E","F")

df <- data.frame(date, amount, address)

And I plot it in ggplot2:
plot <- ggplot(df, aes(x = log(amount))) +
      geom_histogram(binwidth = 1)

plot + theme_minimal() + geom_text(label = amount)

... but I get the error

"Error: geom_text requires the following missing aesthetics: y"

I have 2 questions as a result:

*

*Why am I getting this error with geom_histogram? Shouldn't it assume to use count as the y value?

*Will this successfully show the true values of the data points from the 'amount' column despite the plot's log scale x-axis?

A: Perhaps like this?
ggplot(df, aes(x = log(amount), y = ..count.., label = ..count..)) +
  geom_histogram(binwidth = 1) +
  stat_bin(geom = "text", binwidth = 1, vjust = -0.5) +
  theme_minimal()

ggplot2 layers do not (at least in any situations I can think of) take the summary calculations of other layers, so I think the simplest thing would be to replicate the calculation using stat_bin(geom = "text"...

Or perhaps simpler, you could pre-calculate the numbers:
library(dplyr)
df %>%
  count(log_amt = round(log(amount))) %>%
  ggplot(aes(log_amt, n, label = n)) +
  geom_col(width = 1) +
  geom_text(vjust = -0.5)

EDIT -- to show buckets without the log transform we could use:
df %>%
  count(log_amt = round(log(amount))) %>%
  ggplot(aes(log_amt, n, label = n)) +
  geom_col(width = 0.5) +
  geom_text(vjust = -0.5) +
  scale_x_continuous(labels = ~scales::comma(10^.),
                     minor_breaks = NULL)


text:
Q: Ignore duplicates when using INSERT in a Database with Symfony and Doctrine I have a table
CREATE TABLE `sob_tags_articles` (
  `tag_id` int(11) NOT NULL,
  `article_id` int(11) NOT NULL,
  `id` int(11) NOT NULL auto_increment,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=112

And triing to save an object with Doctrine:
$sbTagsArticles = new SobTagsArticles();
$sbTagsArticles->article_id = $pubId;
$sbTagsArticles->tag_id = $tagId;
$sbTagsArticles->save();

But if record exists with the same $pubId and $tagId new record will be insertet with new PK.
How to do INSERT IGNORE into table with symfony?
$sbTagsArticles->isNew();

returns 1.
Thnx.

A: This is the actual code to be used
try
{
    $record->save();
}
catch(Doctrine_Connection_Exception $e)
{
    if($e->getPortableCode() != Doctrine::ERR_ALREADY_EXISTS)
    {
        /**
         * if its not the error code for a duplicate key
         * value then rethrow the exception
         */
        throw $e;
    }
    /**
     * you might want to fetch the real record here instead
     * so yure working with the persisted copy
     */
}

A: try
{
    $record->save();
}
catch(Doctrine_Exception $e)
{
    if($e->getErrorCode() !== $duplicateKeyCode)
    {
        /**
         * if its not the error code for a duplicate key
         * value then rethrow the exception
         */
        throw $e;
    }

    /**
     * you might want to fetch the real record here instead
     * so yure working with the persisted copy
     */
}

You should be ensuring that the same record doesnt exist on the application side not the SQL side. If you dont ever want the same article/tag combo to exist then add a unique index to (article_id, tag_id). That should generate a mysql error which will in turn generate a doctrine exception that you can catch. There isnt an ignore flag for saves... You might be able to use one operating at a lower level of the DBAL (Doctrine_Query, Doctrine_Connection, etc..) but not directl from the ORM layer.
Doctrine_Record::isNew() will always return true if you have instantiated record asopposed to pulling it from the db otherwise it has way it has no way to know that the record is/isnt new.
Also why are you using the MyISAM storage engine? Im pretty sure this will actually result in more overhead when using Doctrine since it then needs to emulate constraints on the php side. Normally your schema would look something like this:
CREATE TABLE `sob_tags_articles` (
  `tag_id` int(11) NOT NULL,
  `article_id` int(11) NOT NULL,
  `id` int(11) NOT NULL auto_increment,
  PRIMARY KEY  (`id`),
  CONSTRAINT `some_unique_constraint_name_1`
      FOREIGN KEY `article_id`
      REFERENCES `article` (`id`)
      ON DELETE CASCADE,
  CONSTRAINT `some_unique_constraint_name_2`
      FOREIGN KEY `tag_id`
      REFERENCES `tag` (`id`)
      ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=112

A: You could extend the SobTagsArticles object with a new save method, and check if the record already exists:
public function exists() {
  $q = Doctrine_Query::create()
    ->from('sobtagsarticles ta')
    ->where('ta.tag_id = ? and ta.article_id = ?', array($this->getTagId(), $this->getArticleId()));

  if (!$result = $q->execute())
  {
    parent::save();
  }
}

This way the object will be saved only if it doesn't exist.
You could also set an unique index to your table like so:
UNIQUE INDEX `sb_tags_articles_unique` (`tag_id` ASC, `article_id` ASC)

Your schema would look like this:
CREATE TABLE `sob_tags_articles` (
  `tag_id` int(11) NOT NULL,
  `article_id` int(11) NOT NULL,
  `id` int(11) NOT NULL auto_increment,
  PRIMARY KEY  (`id`),
  UNIQUE INDEX `sb_tags_articles_unique` (`tag_id` ASC, `article_id` ASC),
  CONSTRAINT `some_unique_constraint_name_1`
      FOREIGN KEY `article_id`
      REFERENCES `article` (`id`)
      ON DELETE CASCADE,
  CONSTRAINT `some_unique_constraint_name_2`
      FOREIGN KEY `tag_id`
      REFERENCES `tag` (`id`)
      ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=112


text:
Q: Double CD4017 leds driver 555 clock
The very cool circuit is from here:
http://engmousaalkaabi.blogspot.com/2016/01/81-led-chaser-using-double-ic-4017.html
Here are my few questions regarding it.
1, It has 18 transistors. are they really required for lighting up some small LEDs? I think 9 transistors should work.
2, It's about the 4017. When powering on and without a clock signal from 14, does Pin 3 (first output) goes HIGH or LOW? (according to this circuit, Pin 3 much go HIGH for it to work.)
3, what is 3.3k doing in this circuit?
4, last and my main question will be. Can I replace a 555 ic without a micro-controller such as a small attiny 95 and turn this array of leds into a clock? will the CD4017 fast enough for that? according to the datasheet, it has 2.5mhz clock input.

A: 1) indeed, if you run the LEDs on a small current such that the ratings of the left 4017 are not exceeded, you could remove those 9 emitter followers.
2) according to the datasheet (the one from Texas Instruments) output 0 (pin 3) is high even when in reset. Only after a clock will it go low.
Look at the timing diagram in the datasheet and all will be clear (I hope).
3) it is in series with a input (RESET, pin 15) and as this is CMOS logic and I see no capacitor that could lift a voltage above the supply (near this pin) I would say: you don't need the 3.3 k resistor.
4) Yes you can use almost any oscillator or clock generator instead of the 555. The 4017 will indeed be capable to keep up up to a few MHz. But the LEDs would blink so fast that they would all light up. The idea is that the clock is only a couple of Hz which you can easily do with any micro.

A: I made this circuit about 1 month ago, in first I was thinking as you and I removed the 9 transistors that connected to positive line, but the circuit did not work. I was thinking my IC burned so change it, but did not work again.
So I was forced to use all 18 transistors.
I don't know why but you have to use all 18 transistor, that not because of power consumption.
The resistor 3.3k reset the first IC. When I remove it, circuit stopped working. You can use any other IC for clock pulse generation, I've used 4060.

A: You could use 74HC4017s instead of CD4017s, which can easily drive 5mA directly and get rid of the 9 of the transistors. You could replace the bottom 9 transistors with a couple ULN2003A drivers. Recalculate the 100 ohm resistor values to something a bit higher (probably a few hundred ohms).
There is no way to tell what output 0 does at power-up since this circuit has no reset circuit.
The 3.3K does nothing (short it and the behavior will be similar). Probably it was intended to connect a reset circuit to that pin.
Yes you can drive the clock input (and reset inputs) with a microcontroller. For the reset input drive the output high to reset the counters and high-Z (make it an input) after reset. You'll need to use two outputs and add another resistor to reset the second counter.
Or (and I would recommend) use a better circuit such as two OR gates (eg. 74HC02 with two gates connected as inverters) and then you don't need the resistors and can use a single output from the micro (active high, low for normal operation) to reset both counters. Like this:

simulate this circuit – Schematic created using CircuitLab
Net effect is a reduction by ~26 parts (use networks for the resistors and knock another 7 or 8 off), improved functionality (proper reset) and lower overall cost. Engineering- booyah!


text:
Q: How to change the name of the rows of a dataframe? I have a dataframe something like this:

But I don't want the dates to appear there. I prefer the usual names like 1,2,....56.
How can I solve this?
Help please

A: If you are using python and pandas, you can try:
df.reset_index(drop=True)