text:
Q: C# Delete File from Google Shared Drive API v.3 I'm successfully able to upload a file to a Google Drive Shared Drive (not the "My Drive" folder which is different) using a service account.  But when I try to delete the file, I'm getting a The user does not have sufficient permissions for this file. [403]
Note that in my code I have the request.SupportsAllDrives = true; flag set to allow it access to shared drives.
I've done a check on the service account's permission ID and also the file's permission ID and unsurprisingly, they are the same since the service account is the one who put the file up there to begin with.
Any ideas of what is going wrong?
/// <summary>
/// Permanently delete a file, skipping the trash.
/// </summary>
/// <param name="service">Drive API service instance.</param>
/// <param name="fileId">ID of the file to delete.</param>
public async Task<string> DeleteDriveFile(DriveService service, string fileId)
{
    // get the user's permission id from Drive
    var getRequest = service.About.Get();
    getRequest.Fields = "*";
    var getResponse = await getRequest.ExecuteAsync().ConfigureAwait(true);

    string userPermissionId = getResponse.User.PermissionId;
    Debug.Print($"UserPermissionID: {userPermissionId}");

    var responseFile = service.Permissions.Get(fileId, userPermissionId);
    Debug.Print($"FilePermissionID: {responseFile.PermissionId}");

    string response = "";
    try
    {
        var request = service.Files.Delete(fileId);
        request.SupportsAllDrives = true;
        response = await request.ExecuteAsync().ConfigureAwait(false);
    }
    catch (Exception e)
    {
        Debug.WriteLine("Delete File Error: " + e.Message);
    }

    return response;
}

What gets written to the output console:
UserPermissionID: 0243088xxxxxx3009857
FilePermissionID: 0243088xxxxxx3009857
The thread 0x1398 has exited with code 0 (0x0).
Exception thrown: 'Google.GoogleApiException' in System.Private.CoreLib.dll
Delete File Error: Google.Apis.Requests.RequestError
The user does not have sufficient permissions for this file. [403]
Errors [
    Message[The user does not have sufficient permissions for this file.] Location[ - ] Reason[insufficientFilePermissions] Domain[global]
]

A: The currently authenticated user must own the file or be an organizer on the parent for shared drive files.
So in summary, you cannot delete a file if it has not been created by you (i.e. the user authenticated to the API)


text:
Q: How to center 90º rotated text in SVG Working with D3, I want to have a Y axis label which is rotated -90º and centered on the Y axis.  I thought this would be a piece of cake, and wrote the following:
// Y Axis Label
svg.append('svg:text')
    .attr('class', 'y label')
    .attr('text-anchor', 'middle')
    .attr('y', 0)
    .attr('width', height)
    .attr('transform', 'translate(-' + yAxisSpacing + ',' + height + ') rotate(-90)')
    .text('Y Axis Label')

height in this case is the height of the chart (the vertical area occupied by svg).  The above code will render a <text> element to the bottom left of the chart, then center the text relative to that bottom left point.  The width does not change and thus instead of being centered it runs off the bottom left hand corner of the svg.
I had guessed that if the width was equal to the height of the chart, then the text within it would become vertically centered.  That doesn't seem to be the case -OR- there is some magic display:block type property I need to set in SVG in order for width to work on the <text> element.
How should this be done?

Based on the responses, I went with a javascript route and modified the above line to be (height/2)...
.attr('transform', 'translate(-' + yAxisSpacing + ',' + height / 2 + ') rotate(-90)')

A: A width attribute has no effect on <text> in SVG 1.1. The text will be centered (due to text-anchor=middle) around the x,y position defined by the x and y attributes (they default to 0 if you don't specify them). After that the transform attribute is applied.

A: You could do this with CSS transform. Add this to your CSS (via http://css3please.com):
-webkit-transform: rotate(90deg);
   -moz-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
     -o-transform: rotate(90deg);
        transform: rotate(90deg);
           filter: progid:DXImageTransform.Microsoft.Matrix(/* IE6–IE9 */
                 M11=6.123031769111886e-17, M12=-1, M21=1, M22=6.123031769111886e-17, sizingMethod='auto expand');
             zoom: 1;

Working example here - look in the 'css' tab: http://livecoding.io/3492918

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove that if $\sup S = \infty$ then for every $N > 0$ there exists an element $s$ of $S$ such that $s > N$ How would I prove this? Would I use upper bounds or lower bounds or would I do a proof by contradiction?

A: $\sup=\infty$, i.e $S$ is not upper bounded. and this means that for any $N$ there exists $s\in S$ such that $s>N$. since otherwise it is upper bounded.
more percisely if there exists $N$ s.t. $s\leq N$ for all $s\in S$ then $\sup S\leq N<\infty$. which is a contradiction.

A: "$\sup S=\infty$" means $S$ has no upper bound. That means that, for every $N$, $N$ is not an upper bound. In other words, $N$ isn't $\ge$ than everything in $S$. That is to say, there are things in $S$ bigger than $N$.
Compare that with what you wanted to prove.


text:
Q: Time Service is not working.On Running it shows "Unfortunately Stopped" Please Help ...I m new to android and I am doing my 1st project in Eclipse Juno.
I have a Reminder module with Alarm service.Reminder Time and date are stored in Sqlite database with table name reminder_tb.
Saving of these values are done in ReminderActivity.java and AlarmService is done creating a new java page TimeService.java and this page is called(intent) from my main page ie LoginActivity.java
At first run my app worked without any errors.Next day when I run again its show:UNFORTUNATELY STOPPED
Here is my ReminderActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reminder);
    //open sqlite and fetch id from xpence and pass to php page
    SQLiteDatabase db = openOrCreateDatabase("xpence", MODE_PRIVATE, null);
final   Cursor cur=db.rawQuery("select * from login",null);
     //save details on click

    Save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            AmountString=Amount.getText().toString().trim();
            DateString=Date.getText().toString().trim();
            TimeString=Time.getText().toString().trim();
            DescString=Desc.getText().toString().trim();

            if (cur.moveToFirst())
            {
                id = cur.getString(0).toString();
                doSaveRem(AmountString,DateString,TimeString,DescString,id);

            }

        }

    });
}

public void doSaveRem(final String AmountString,final String DateString,final String TimeString,final String DescString,final String id)
{

    //Toast.makeText(getApplicationContext(), "Loaded"+AmountString+DateString+TimeString+DescString+id,Toast.LENGTH_SHORT).show();

    db=openOrCreateDatabase("xpence", MODE_PRIVATE, null);

    //TABLE FOR SMS AND NOTIFY
    //Insert to SMSNOTIFY
        db.execSQL("create table if not exists reminder_tb(amount varchar,date varchar,time varchar,desc varchar,id,active_flag INTEGER DEFAULT 0)");
        db.execSQL("insert into reminder_tb(amount,date,time,desc,id) values('"+AmountString+"','"+DateString+"','"+TimeString+"','"+ DescString+"','"+id+"')");
        Cursor   c = db.rawQuery("SELECT * FROM reminder_tb", null);
        c.moveToFirst();
        if(c.getCount()>0)
         {

            Toast.makeText(getApplicationContext(),"Saved!",Toast.LENGTH_LONG).show();
            Amount.setText("");
            Date.setText("");
            Time.setText("");
            Desc.setText("");

         }
         db.close();
         finish();
}

////  - Here is TimeService.java
     public class TimerService extends Service
                    {
                        String dateString;
                         String timeString;
                         private int year;
                         private int month;
                         private int day;
                         private int hour;
                         private int minute;
                         private String date;
                       // private Cursor c;
                        private  SQLiteDatabase db;
                         // constant
                        public long  NOTIFY_INTERVAL = 1000;
                        // run on another Thread to avoid crash
                        private Handler mHandler = new Handler();
                        // timer handling
                        private Timer mTimer = null;
                        @Override
                        public IBinder onBind(Intent intent)
                        {
                            return null;
                        }
                        @Override
                        public void onCreate()
                        {
                        // cancel if already existed
                            if (mTimer != null)
                            {
                                mTimer.cancel();
                            }
                            else
                            {
                                // recreate new
                                mTimer = new Timer();
                            }
                            // schedule task
                            mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
                           }
                    class TimeDisplayTimerTask extends TimerTask
                        {
                           @Override
                            public void run()
                            {
                                // run on another thread
                                mHandler.post(new Runnable()
                                {
                                   @Override
                                    public void run()
                                    {
                                        AlarmService();

                                    }

                                });
                            }
                        }
                    private void AlarmService()
                        {
                          //for date
                             final Calendar ca = Calendar.getInstance();
                             year  = ca.get(Calendar.YEAR);
                             month = ca.get(Calendar.MONTH)+1;
                             day   = ca.get(Calendar.DAY_OF_MONTH);
                             date =year+"-"+month+"-"+day;
                             final Calendar c1 = Calendar.getInstance();
                             hour = c1.get(Calendar.HOUR_OF_DAY);
                            minute = c1.get(Calendar.MINUTE);
                              String timeSet = "";
                             if (hour > 12)
                             {
                                 hour -= 12;
                                 timeSet = "PM";
                             } else if (hour == 0)
                             {
                                 hour += 12;
                                 timeSet = "AM";
                             }
                     else if (hour == 12)
                                 timeSet = "PM";
                             else
                                 timeSet = "AM";
                      String minutes = "";
                             if (minute < 10)
                                 minutes = "0" + minute;
                             else
                                 minutes = String.valueOf(minute);
                      String TimeString = new StringBuilder().append(hour).append(':').append(minutes).append(" ").append(timeSet).toString();
                      db = openOrCreateDatabase("xpence", Context.MODE_PRIVATE, null);
                             String tableName="reminder_tb";
                             Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
                             Cursor   c = db.rawQuery("SELECT * FROM reminder_tb",null);
                             c.moveToFirst();
                            if( cursor!=null)
                             {
                                 if(cursor.getCount()>0)
                                    {
                                      cursor.close();
                                       c = db.rawQuery("SELECT * FROM reminder_tb where date='"+date+"' and time='"+TimeString+"' and active_flag=0" , null);
                                      c.moveToFirst();
                                      if(c.getCount()>0)
                                       {
                                        Toast.makeText(getApplicationContext(), "REMINDER: " + c.getString(3) + "Amount:"+c.getString(0)+" On "+date+","+TimeString, Toast.LENGTH_LONG).show();
                                        db.execSQL("update reminder_tb SET active_flag=1 WHERE date='"+date+"' and time='"+TimeString+"'");

                                        }
                                    c.close();
                                 }
                                cursor.close();
                             }
                             db.close();
                         }
                    }

///- LoginActivity.java
Intent serviceIntent = new Intent(LoginActivity.this, TimerService.class);
    LoginActivity.this.startService(serviceIntent);

*

*Here is the LogCat

03-08 15:50:20.481: E/Trace(1799): error opening trace file: No such
  file or directory (2) 03-08 15:50:21.121: D/dalvikvm(1799):
  GC_CONCURRENT freed 44K, 4% free 2768K/2876K, paused 7ms+2ms, total
  52ms 03-08 15:50:21.461: D/dalvikvm(1799): GC_FOR_ALLOC freed 8K, 3%
  free 2829K/2912K, paused 36ms, total 48ms 03-08 15:50:21.561:
  I/dalvikvm-heap(1799): Grow heap (frag case) to 7.820MB for
  5242892-byte allocation 03-08 15:50:21.581: D/dalvikvm(1799):
  GC_FOR_ALLOC freed <1K, 2% free 7949K/8036K, paused 25ms, total 25ms
  03-08 15:50:21.641: D/dalvikvm(1799): GC_CONCURRENT freed <1K, 2% free
  7948K/8036K, paused 13ms+2ms, total 58ms 03-08 15:50:22.912:
  E/SQLiteLog(1799): (1) no such table: reminder_tb 03-08 15:50:22.931:
  D/AndroidRuntime(1799): Shutting down VM 03-08 15:50:22.931:
  W/dalvikvm(1799): threadid=1: thread exiting with uncaught exception
  (group=0xb2d0a908) 03-08 15:50:22.912: E/SQLiteLog(1799): (1) no such
  table: reminder_tb 03-08 15:50:22.931: D/AndroidRuntime(1799):
  Shutting down VM 03-08 15:50:22.931: W/dalvikvm(1799): threadid=1:
  thread exiting with uncaught exception (group=0xb2d0a908) 03-08
  15:50:22.951: E/AndroidRuntime(1799): FATAL EXCEPTION: main 03-08
  15:50:22.951: E/AndroidRuntime(1799):
  android.database.sqlite.SQLiteException: no such table: reminder_tb
  (code 1): , while compiling: SELECT * FROM reminder_tb 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method) 03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  com.ANSAR.xpence.TimerService.AlarmService(TimerService.java:149)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  com.ANSAR.xpence.TimerService.access$1(TimerService.java:91) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  com.ANSAR.xpence.TimerService$TimeDisplayTimerTask$1.run(TimerService.java:81)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  android.os.Handler.handleCallback(Handler.java:725) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  android.os.Handler.dispatchMessage(Handler.java:92) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  android.os.Looper.loop(Looper.java:137) 03-08 15:50:22.951:
  E/AndroidRuntime(1799):    at
  android.app.ActivityThread.main(ActivityThread.java:5041) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  java.lang.reflect.Method.invokeNative(Native Method) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  java.lang.reflect.Method.invoke(Method.java:511) 03-08 15:50:22.951:
  E/AndroidRuntime(1799):    at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  03-08 15:50:22.951: E/AndroidRuntime(1799):    at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 03-08
  15:50:22.951: E/AndroidRuntime(1799):  at
  dalvik.system.NativeStart.main(Native Method)*


text:
Q: Filtering Multiple input on a single json I have a json file with object
obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar"
},{fname:"abhi",age:5,class:"ten",lanme:"kumar"
},{fname:"abhi",age:5,class:"ten",lanme:"kumar"
},{fname:"abhi",age:5,class:"ten",lanme:"kumar"
}]

which I display in the following table
enter image description here
i am trying to build a filter for the above table but I am not able to filter it out
Can anyone please help me on this
Note: Second Row each Column is a Filter for only that column that is Class searches only class  column not everything
And that search should populate in that table
Can anyone please help I am stuck here from ages on this specially with useState Hook
Stack Used : React & Javascript no third party library
Currently my filter is something like this
const [value, setValue] = useState({
    lastname: '',
    class: '',
    firstname: '',
  });
  const handleSubmit = e => {
    const searchValue = {
      ...value,
      [e.target.name]: e.target.value
    };
    setValue(searchValue);
    setCopyList(
      copyList.filter(item => item[e.target.name].includes(e.target.value))
    );
  };

currently what is happening is as soon as I search on each individual column it refreshes the search on the present values

A: first You make a generic function and then implement every input text
field. This solution is especially in react js and js.
 const searchByName = (name) => {
if (name !== "") {
  console.log(name);
  const res = data.filter((sd) => {
    return (
      sd.firstName.toString().toLowerCase().includes(search) ||
      sd.email.toString().toLowerCase().includes(search)
    );
  });
  console.log(res);
  setData(res);
} else {
  setData(dataFilter);
}

};


text:
Q: The Euclidean vector momentum operator in spherical coordinates I am having some trouble with the notion that the different components of a vector operator can be hermitian in one coordinate system but non-hermitian in another. I have seen e.g. Bra-ket notation in a 3 dimensional system says a euclidean vector operator acting on a state should be thought of as an operator that has euclidean vectors for its eigenvalues. So if we were in an eigenstate of momentum then:
$$
\hat{\underline{p}}|\underline{p}\rangle = \underline{p}|\underline{p}\rangle.
$$
My first question is to ask is it ok to think of this as being three copies of the state vector with different scalar eigenvalues in front of each:
$$
\hat{\underline{p}}|\underline{p}\rangle = p_x|\underline{p}\rangle\underline{e}_x + p_y|\underline{p}\rangle\underline{e}_y + p_z|\underline{p}\rangle\underline{e}_z.
$$
My main question is about when and how the operator can be decomposed into component terms. It seems that it is acceptable in cartesian coordinates here to say:
$$
\hat{\underline{p}}|\underline{p}\rangle = \hat{p}_x|\underline{p}\rangle\underline{e}_x + \hat{p}_y|\underline{p}\rangle\underline{e}_y + \hat{p}_z|\underline{p}\rangle\underline{e}_z
$$
and that I write
$$\hat{\underline{p}} = \hat{p}_x\underline{e}_x + \hat{p}_y\underline{e}_y + \hat{p}_z\underline{e}_z.$$
But this unravels for coordinate systems with non-unity Jacobians. Specifically the spherical polar coordinates (Jacobian = $r^2\sin\theta$) I understand that the "radial component" of the euclidean vector operator is not hermitian (nor is the $\theta$ component but the $\phi$ component is hermitian - it all being connected to whether that coordinate appears in the Jacobian or not).
But the vector operator is still hermitian, so it seems reasonable to me to believe that I could have:
$$
\hat{\underline{p}}|\underline{p}\rangle = p_r|\underline{p}\rangle\underline{e}_r + p_\theta|\underline{p}\rangle\underline{e}_\theta + p_\phi|\underline{p}\rangle\underline{e}_\phi
$$
where all those eigenvalues are real-valued. But if I try to write $$\hat{\underline{p}} = \hat{p}_r\underline{e}_r + \hat{p}_\theta\underline{e}_\theta + \hat{p}_\phi\underline{e}_\phi$$ I dont think I can equate, e.g. $\hat{p}_r$ to the hermitian operator that returns the radial momentum component (which is not the same operator as the non-hermitian operator that is the radial component of the euclidean momentum operator).
If I call the hermitian operators that correspond to the coordinates of momentum $\hat{p}'_r,\hat{p}'_\theta,\hat{p}'_\phi$ then I'm happy that e.g. $\hat{p}'_r|\underline{p}\rangle=p_r|\underline{p}\rangle$ but I do not believe that $$\hat{\underline{p}} = \hat{p}'_r\underline{e}_r + \hat{p}'_\theta\underline{e}_\theta + \hat{p}'_\phi\underline{e}_\phi.$$ Specifically, when I try to calculate the angular momentum operators from this definition of $\hat{\underline{p}}$ and a definition of $\hat{\underline{r}} = \hat{r}\underline{e}_r$ (i.e. I try to say $\hat{\underline{L}} = \hat{\underline{r}}\times\hat{\underline{p}}$ it doesn't give the answers I expect).
So the question is, what is the right way to write the euclidean momentum operator in spherical polar coordinates and relate it to the operators corresponding to the respective components of momentum?


text:
Q: Access SVN server over HTTP in Windows I have installed VisualSVN Server in a windows machine. And TortoiseSVN client in another server. I want to access the data of VisualSVN server through TortoiseSVN over http or https. How can I do that?
Please help

A: Just tell TortoiseSVN the URL of your repo:

*

*Open VisualSVN Server Manager. Under repositories, select your repository, right click > Copy URL to clipboard.

*Go to other machine, rigth click on folder where you want to checkout the code > SVN Checkout..., paste the above value in the field URL of the repository (TortoiseSVN might even pre-populate this for you from clipboard). Click OK.

That's all.


text:
Q: How to authenticate with a private repo on DockerHub through the Docker.Dotnet client? I am currently writing a microservice in .NET Standard that writes a Dockerfile, builds the Docker image associated with that Dockerfile (which implicitly causes a pull image), and pushes the image to a private Docker registry. Those Docker operations are all performed using the Docker.Dotnet library that MSFT maintains. I believe that this is mostly just a wrapper around calls to the Docker Remote API. The execution context of this microservice is in a K8s cluster hosted on AWS, or internally on bare-metal, depending on the deployment.
Previously our Docker registry has just been a private registry hosted on Artifactory internally, but we are migrating to a private DockerHub registry/repository/. With this migration have come some authentication problems.
We authenticate all of the pull and push operations with an AuthConfig that consists of the username and password for the account associated with the registry. The AuthConfig is either added to a Parameters object and then passed to the call:
imageBuildParameters.AuthConfigs = new Dictionary<string,
AuthConfig>() { { DockerEnvVariables.DockerRegistry, authConfig } };

…
using (var responseStream = _dockerClient.Images.BuildImageFromDockerfileAsync(tarball, imageBuildParameters).GetAwaiter().GetResult())

Or it's (strangely, to me) both passed in a parameter and separately to the call:
ImagePushParameters imagePushParameters = new ImagePushParameters() { ImageID = image.Id, RegistryAuth = authConfig, Tag = "latest" };
_dockerClient.Images.PushImageAsync(RepoImage(image.Id), imagePushParameters, authConfig, this).GetAwaiter().GetResult();

We are currently getting auth errors for any of the various Docker registries I've tried for DockerHub, as such (where I've redacted the organzation/namespace and image:
{"message":"pull access denied for registry-1.docker.io//, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"},"error":"pull access denied for registry-1.docker.io//, repository does not exist or may require 'docker login': denied: requested access to the resource is denied"
The list of DockerHub urls that I've tried is following, all with either the error above or a different "Invalid reference format" error:

*

*Hub.docker.io

*Hub.docker.io/v1/

*Docker.io

*Docker.io/v1/

*Index.docker.io

*Index.docker.io/v1/

*Registry.hub.docker.com

*registry-1.docker.io

Strangely enough, if I run it locally on my Windows system, the bolded URL's actually work. However, they all fail when deployed to the cluster (different method of interacting with the Docker socket/npipe?).
Does anyone know the correct URL I need to set to properly authenticate and interact with DockerHub? Or if my current implementation and usage of the Docker.Dotnet library is incorrect in some way? Again, it works just fine with a private Docker registry on Artifactory, and also with DockerHub when run on my local Windows system. Any help would be greatly appreciated. I can provide any more information that is necessary, be it code or configuration.


text:
Q: How best to run through a series of elements {a,1,i}, {b,2,ii}, etc I am rewriting a package I wrote for XeLaTeX to handle unicode blocks. This means dealing with setting up character classes for all characters from block "BlockName" starting at codepoint 1234 and ending at codepoint 5678.
Right now I have a macro that takes three inputs, and transforms them as:
\newcounter{glyphcounter}
\newcommand{\@defineUnicodeClass}[3]{
 \newXeTeXintercharclass#1
 \forloop{glyphcounter}{#2}{\value{glyphcounter}<#3}\XeTeXcharclass\value{glyphcounter}=#1}
 \XeTeXcharclass#3=#1}

This then gets called many, many times:
\@defineUnicodeClass{\AegeanNumbersClass}{65792}{65855}
\@defineUnicodeClass{\AlphabeticPresentationFormsClass}{64256}{64335}
\@defineUnicodeClass{\AncientGreekMusicalNotationClass}{119296}{119375}
...

I'd like to compact this in such a way that I can simply define the list of blocks, a la {{AegeanNumbers,65792,65855},{AlphabeticPresentationForms,64256,64335},{AncientGreekMusicalNotation,119296,119375},...} and then run through this list to generate everything for each block.
I was thinking about writing the data definition as {AegeanNumbers,65792,65855,AlphabeticPresentationForms,64256,64335,AncientGreekMusicalNotation,119296,119375,...}, so just a concatenated string in which every first%3 term is a new block definition, then having a macro that checks whether the input is empty, and if not takes the first three terms in that list, deals with them, then recurses with the list "tail", but I'm having a hard time implementing this in TeX.
If this is the best way to go about it, how do I do so? If not, what's a better way to run through this kind of data?
I had a look at http://maraist.org/comma-separated-lists-in-latex_08-2009 to figure out how to get the head/tail splitting to happen, but I am not having much luck getting this to work in XeLaTeX. I tried
\def\myTestCommand#1,#2{#1}

just to see whether it would do something, but calling it with "\myTestCommand{a,b,c,d}" just leads to a "runaway argument?" error.
I also had a look at the \forcsvlist command from the etoolbox package, but from what I can tell this only understands a comma separated list in which every element is the same kind of thing, and has no concept of tuples. I could write a switching macro with two state variable macros to effect an "if states empty, fill first var, if one filled, fill second var, if both filled, call the following macro and empty both vars" but if someone has a cleaner approach, that would be much preferred.

A: Here are two ways to handle the definition of the commands as well as the iteration. Both require the definition of  a macro that can define the commands:
\def\CommandFactory#1#2#3{%
      \expandafter\gdef\csname#1\endcsname{#1 class}
      \expandafter\gdef\csname#1start\endcsname{#2}
      \expandafter\gdef\csname#1end\endcsname{#3}
 }

This can be viewed as a utility to define objects or struct. In the above three commands are defined for example aegean, aegeanstart and aegeanend. If you use a dot or an @ the structure is more obvious, aegean@start, aegean@end.
Now back to iteration, the first method uses \@elt, which is a short for element and a Lisp relic found in LaTeX.
\def\@elt#1,#2,#3,{\CommandFactory{#1}{#2}{#3}}
\def\unicoderange{\@elt test,1,2,\@elt testi,2,3,\@elt testii,4,5,}

this is Knuth's way of handling lists (he uses \\ rather than \@elt).
The second way to handle iteration is to use LaTeX's @for with an example shown in the minimal below. I have used \i to make it more intuitive so be aware to run the code through a group or save and restore its definition otherwise the dotless i will disappear!
\documentclass{article}
\begin{document}

\def\CommandFactory#1#2#3{%
  \expandafter\gdef\csname#1\endcsname{#1 class}
  \expandafter\gdef\csname#1start\endcsname{#2}
  \expandafter\gdef\csname#1end\endcsname{#3}
}

\def\unicodeClasses{aegean,musical,alphabetic}

\CommandFactory{aegean}{65792}{65855}
\CommandFactory{musical}{119296}{119375}
\CommandFactory{alphabetic}{64256}{64335}

\makeatletter
\@for \i:=\unicodeClasses \do{
   \csname\i\endcsname,
   \csname\i start\endcsname-%
   \csname\i end\endcsname,
}

%% another way to iterate using @elt
\def\@elt#1,#2,#3,{\CommandFactory{#1}{#2}{#3}}
\def\unicoderange{\@elt test,1,2,\@elt testi,2,3,\@elt testii,4,5,}

\unicoderange

\testi
\makeatother

\end{document}

A: I don't know the looping macros for LaTeX, but this is how you can process a nested comma list in ConTeXt
\def\definecharacterlist
    {\dosingleargument\dodefinecharacterlist}

\def\dodefinecharacterlist[#1]%
    {\processcommalist[#1]\defineUnicodeCharacter}

\def\defineUnicodeCharacter#1%
    {\dostartdefineUnicodeCharacter#1\dostopdefineUnicodeCharacter}

\def\dostartdefineUnicodeCharacter#1,#2,#3\dostopdefineUnicodeCharacter
    {\writestatus{DEBUG}{1: #1; 2: #2; 3: #3}}

\definecharacterlist[{AegeanNumbers,65792,65855},{AlphabeticPresentationForms,64256,64335},{AncientGreekMusicalNotation,119296,119375}]

The \dosingleargument is just ConTeXt's way of doing optional arguments. You can replace \processcommalist by the equivalent LaTeX looping macro, and replace \writestatus by any macro that you want.

A: Would a syntax such as
\@defineUnicodeclasses{AegeanNumbers/65792/65855,
  AlphabeticPresentationForms/64256/64335,
  AncientGreekMusicalNotation/119296/119375}

be good? I think so. Then
\def\@defineUnicodeclasses#1{%
  \def\@Unicodeclasseslist{#1}%
  \@for\next:=\@Unicodeclasseslist\do
    {\expandafter\do@Unicodeclasslist\next\@nil}}
\def\do@Unicodeclasslist#1/#2/#3\@nil{%
  \count@=\numexpr#2-1\relax
  \expandafter\newXeTeXintercharclass\csname#1\endcsname
  \loop\ifnum\count@<#3\relax
    \advance\count@\@ne
    \XeTeXcharclass\count@=\csname#1\endcsname
  \repeat}

should be what you need. But I don't see much advantage over multiple \@defineUnicodeclass declarations.


text:
Q: Change Is Identity to yes on existing column In SSMS on my development DB, I set IsIdentity to true on an int field, and after a short wait the changes complete and all seems to work.  The column is currently populated with values that cannot change.
On production however, with ~1mm rows, SSMS seems to freeze and not apply the change successfully.
Adding a new column, dropping the old one, renaming them etc isn't an option as there are too many relationships.
Often I find on the production DB, running the query explicitly as supposed to using the SSMS interface does seem to work a lot better.
Is there a simple alter query that will change the IsIdentity to true?


text:
Q: Android OpenCV: update camera frames while executing AsyncTask I have created an AsyncTask for processing a number of camera frames after calling onClick(), but the camera freezes until the AsyncTask has finished its execution.
Is there a way of avoiding this behavior? I mean, is it possible to keep updating the camera frames during the execution of the AsyncTask?
AsyncTask code:
private class ReadCodeTask extends AsyncTask<Mat[], List<Mat>, List<Bitmap>> {

    protected Mat[] onPreExecute(List<Mat> frames){
        Mat[] output = new Mat[4];;
        for(int i=0; i<frames.size(); i++){
            mH = new Mat();
            List<Mat> channels = new ArrayList<Mat>(3);
            // convert inputFrame to HSV for segmentation
            Mat hsvFrame = new Mat(frames.get(i).height(), frames.get(i).width(), CvType.CV_8UC3, new Scalar(4));
            Imgproc.cvtColor(frames.get(i), hsvFrame, Imgproc.COLOR_RGB2HSV, 0);

            Core.split(hsvFrame, channels);

            // get H channel of the input image
            mH = channels.get(0);

            if(mH!=null){
                double meanH = 0;
                double size = mH.rows()*mH.cols();
                // average saturation in frame
                for(int k=0; k<mH.rows(); k++){
                    for(int j=0; j<mH.cols(); j++){
                        meanH += mH.get(k, j)[0]/size;
                    }
                }
                if(meanH<=0.2*180){ // if WHITE BACKGROUND
                    output[i] = frames.get(i);
                    continue;
                }
            }else{
                Log.e("ERR", "Error converting to HSV");
            }
            gray = new Mat(frames.get(i).height(), frames.get(i).width(), CvType.CV_8UC1, new Scalar(4));
            Imgproc.cvtColor(frames.get(i), gray, Imgproc.COLOR_RGB2GRAY, 0);
            Mat grayBin = new Mat();
            Scalar lowG = new Scalar(0.9*255);
            Scalar highG = new Scalar(1*255);
            Core.inRange(gray, lowG, highG, grayBin);
            Imgproc.findContours(grayBin, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
            for(int c=0; c<contours.size(); c++){
                if(couldItBeASquare(contours.get(c))){
                    boundingRect = Imgproc.boundingRect(contours.get(c));
                }
            }
            Mat qrSubIm = new Mat();
            try{
                qrSubIm = frames.get(i).submat(boundingRect);
            }catch(NullPointerException e){
                //          Log.e("ERR", e.getMessage());
            }
            if(qrSubIm != null){
                output[i] = qrSubIm;
            }else{
                output[i] = frames.get(i);
            }
        }
        return output;
    }

    @Override
    protected List<Bitmap> doInBackground(Mat[]... params) {
        List<Bitmap> bmp = new ArrayList<Bitmap>();

        for(int i=0; i<params.length; i++){
            Mat mRgb = params[0][i];
            qr = new Mat();
            mQrFinder.qrFindJNI(mRgb.getNativeObjAddr(), qr.getNativeObjAddr());
            Bitmap aux = null;
            if(qr.cols()!=0 || qr.rows()!=0){
                try {
                    aux = Bitmap.createBitmap(qr.cols(), qr.rows(), Bitmap.Config.ARGB_8888);
                    Utils.matToBitmap(qr, aux);
                    bmp.add(aux);
                }catch (CvException e){
                    Log.e("Exception",e.getMessage());
                }
            }
        }
        return bmp;
    }

    @Override
    protected void onPostExecute(List<Bitmap> bmp) {
        List<String> results = new ArrayList<String>(bmp.size());
        for(int i=0; i<bmp.size(); i++){
            try {
                String aux = readQRCode(bmp.get(i));
                results.add(aux);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        for(int i=0; i<results.size(); i++){
            if(!results.get(i).contentEquals("NOTHING")){
                Toast toast = Toast.makeText(mContext, results.get(i), android.widget.Toast.LENGTH_SHORT);
                toast.show();
            }
        }
        return;
    }
}

Notice that the onPreExecute() method is not overridden, I have to manually call it like so:
ReadCodeTask task = new ReadCodeTask();
task.execute(task.onPreExecute(frames));

For completion, the following piece of code corresponds to the camera listener I am using for retrieving the frames:
camListener = new CvCameraViewListener2() {

        @Override
        public void onCameraViewStopped() {
            // TODO Auto-generated method stub
        }

        @Override
        public void onCameraViewStarted(int width, int height) {
            //
        }

        @Override
        public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
            rgb = inputFrame.rgba();
            if(frames != null){
                if(frames.size()<4){
                    frames.add(rgb);
                }
                if(frames.size()==4){
                    List<Mat> aux = frames;
                    for (int k = 0; k<aux.size()-1; k++){
                        frames.set(k, aux.get(k+1));
                    }
                    frames.set(aux.size()-1, rgb);
                }
            }
            return rgb;
        }
    };

A: I meant something like this. Be aware of the mContext, you should pass a context, or if your asynctask is a private class in a class that extends Activiti then you could pass '.this' to the toast.
private class ReadCodeTask extends AsyncTask<List<Mat>, Void, List<Bitmap>> {

    @Override
    protected List<Bitmap> doInBackground(List<Mat>... frames) {

         Mat[] output = new Mat[4];;
         for(int i=0; i<frames.length; i++){
             mH = new Mat();
             List<Mat> channels = new ArrayList<Mat>(3);
             // convert inputFrame to HSV for segmentation
             Mat hsvFrame = new Mat(frames[0].get(i).height(), frames[0].get(i).width(), CvType.CV_8UC3, new Scalar(4));
             Imgproc.cvtColor(frames[0].get(i), hsvFrame, Imgproc.COLOR_RGB2HSV, 0);

             Core.split(hsvFrame, channels);

             // get H channel of the input image
             mH = channels.get(0);

             if(mH!=null){
                 double meanH = 0;
                 double size = mH.rows()*mH.cols();
                 // average saturation in frame
                 for(int k=0; k<mH.rows(); k++){
                     for(int j=0; j<mH.cols(); j++){
                         meanH += mH.get(k, j)[0]/size;
                     }
                 }
                 if(meanH<=0.2*180){ // if WHITE BACKGROUND
                     output[i] = frames[0].get(i);
                     continue;
                 }
             }else{
                 Log.e("ERR", "Error converting to HSV");
             }
             gray = new Mat(frames[0].get(i).height(), frames[0].get(i).width(), CvType.CV_8UC1, new Scalar(4));
             Imgproc.cvtColor(frames[0].get(i), gray, Imgproc.COLOR_RGB2GRAY, 0);
             Mat grayBin = new Mat();
             Scalar lowG = new Scalar(0.9*255);
             Scalar highG = new Scalar(1*255);
             Core.inRange(gray, lowG, highG, grayBin);
             Imgproc.findContours(grayBin, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
             for(int c=0; c<contours.size(); c++){
                 if(couldItBeASquare(contours.get(c))){
                     boundingRect = Imgproc.boundingRect(contours.get(c));
                 }
             }
             Mat qrSubIm = new Mat();
             try{
                 qrSubIm = frames[0].get(i).submat(boundingRect);
             }catch(NullPointerException e){
                 //          Log.e("ERR", e.getMessage());
             }
             if(qrSubIm != null){
                 output[i] = qrSubIm;
             }else{
                 output[i] = frames[0].get(i);
             }
         }

        List<Bitmap> bmp = new ArrayList<Bitmap>();

        for(int i=0; output.length; i++){
            Mat mRgb = output[i];
            qr = new Mat();
            mQrFinder.qrFindJNI(mRgb.getNativeObjAddr(), qr.getNativeObjAddr());
            Bitmap aux = null;
            if(qr.cols()!=0 || qr.rows()!=0){
                try {
                    aux = Bitmap.createBitmap(qr.cols(), qr.rows(), Bitmap.Config.ARGB_8888);
                    Utils.matToBitmap(qr, aux);
                    bmp.add(aux);
                }catch (CvException e){
                    Log.e("Exception",e.getMessage());
                }
            }
        }
        return bmp;
    }

    @Override
    protected void onPostExecute(List<Bitmap> bmp) {
        List<String> results = new ArrayList<String>(bmp.size());
        for(int i=0; i<bmp.size(); i++){
            try {
                String aux = readQRCode(bmp.get(i));
                results.add(aux);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        for(int i=0; i<results.size(); i++){
            if(!results.get(i).contentEquals("NOTHING")){
                Toast toast = Toast.makeText(mContext, results.get(i), android.widget.Toast.LENGTH_SHORT);
                toast.show();
            }
        }
        return;
    }
}

I'm not sure If I mispelled something. Why like this? Normally the onPreExceute has the type void, so maybe when you overloaded this method the UI gets blocked. I would give it a try anyways.
Remember that onPreExecute method is run in the UI thread. See documentation: http://developer.android.com/reference/android/os/AsyncTask.html#onPreExecute()


text:
Q: How to get the Values of HTML Dynamic user inputs using Javascript I have these Dynamic user inputs with following types:

*

*Costs: <selection>The user will choose 1 option

*Money Input: user input some text.I got after help.

I want Theses 2 values given above.
I want to get the Values of these  Dynamic user inputs using JavaScript.
Here the Code given below : Update:solved

<!DOCTYPE html>

      <form  action="payroll.php" method="post">

               Costs
               Money Input

                  <select class="mySelect" name="DESCR" >
                     <option  disabled="" selected="">Select</option>
                     <option value="BASIC PAY">BASIC PAY</option>
                     <option  value="GAS BILL">GAS BILL</option>
                     <option  value="CLUB">CLUB</option>
                     <option  value="MEDICINE">MEDICINE</option>
                     <option  value="BANK LOAN">BANK LOAN</option>
                  </select>

                <input type="text" name="ALAMT">

      </form>

      <button onclick="addMore()">Add More</button>
      <button onclick="removeLast()">Remove</button>
      <button onclick="myFunction()">Try it</button>

Using this code every  i get errors.But i want the <option> value that is only chosen by the user, instead off all.
Please suggest me how can i do this or more better alternatives to do it.
please let me know for any further information.Thanks

A: You get the HTMLTableCellElement object since you don't specify what you want to get from the cells[0], should add .textContent to if you want to get the text inside the column :
document.getElementById("myTable").rows[1].cells[0].textContent

Or .innerHTML if you want to get the HTML inside the column :
document.getElementById("myTable").rows[1].cells[0].innerHTML

If you want to get the selected option form the select by the user in 'Costs' select, i suggest to use classes .mySelect instead id="mySelect" since the id should be unique in same document, and use querySelector e.g :
var costs = document.querySelector('#myTable tr:nth-child(2) td:nth-child(1) .mySelect option:checked').value;
var money = document.querySelector('#myTable tr:nth-child(2) td:nth-child(2) input").value;

Hope this helps.

function addMore() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(-1);
  var cell1 = row.insertCell(-1);
  var cell2 = row.insertCell(-1);

  var x = document.getElementById("myTable").rows[1].cells;

  cell1.innerHTML =  x[0].innerHTML;
  cell2.innerHTML = x[1].innerHTML;
}

function removeLast() {
  document.getElementById("myTable").deleteRow(-1);
}

function myFunction() {
  var costs = document.querySelector('#myTable tr:nth-child(2) td:nth-child(1) .mySelect option:checked').value;
  var money = document.querySelector('#myTable tr:nth-child(2) td:nth-child(2) input').value;

  document.getElementById('result').textContent = costs+' - '+money;
}
table, th, td {
  border-collapse: collapse;
}
<form action="payroll.php" method="post">

      Costs
      Money Input

        <select class="mySelect" name="DESCR" >
          <option  disabled="" selected="">Select</option>
          <option value="BASIC PAY">BASIC PAY</option>
          <option  value="GAS BILL">GAS BILL</option>
          <option  value="CLUB">CLUB</option>
          <option  value="MEDICINE">MEDICINE</option>
          <option  value="BANK LOAN">BANK LOAN</option>
        </select>

       <input type="text" name="ALAMT">

</form>

<button onclick="addMore()">Add More</button>
<button onclick="removeLast()">Remove</button>
<button onclick="myFunction()">Try it</button>

A:   var select = document.getElementById("myTable").rows[1].cells[0].firstElementChild;
  var selectValue = select.options[select.selectedIndex].value;
  var ocell = document.getElementById("myTable").rows[1].cells[1];
  alert("Selected Index: "+selectValue+"\nInput value: "+ocell.firstElementChild.value);


text:
Q: Will disparity in image format/quality between binary classifications affect training of Convolutional Neural Network? I have an image dataset containing two classes. One of the classes has many images and they are all JPG images with the following format:
Horizontal/Vertical Resolution: 96 dpi
Bit depth: 24
Size: ~217 KB

The other class contains images which I (for the most part) have had to create myself. There are a few that are from the original dataset but the rest are created outside of it. These images have a format like so:
Horizontal/Vertical Resolution: 120 dpi
Bit depth: 32
Size: ~2.75 MB

Both image classifications are of type .jpg and have the same height x width dimensions
During training, all of these files will be reduced in size and converted to a Python numpy array using the following code:
import numpy as np
from skimage.io import imread
from skimage.transform import resize

np.array([resize(imread(str(fileName)), (width, height, channels)) for fileName in list_of_filenames])

This gives me one batch of images that have been read from a directory, reduces their size to the specified height/width, and puts them into a numpy array.
My question is, with the disparity in image size, bit depth, and dpi will my image classifier simply become a classifier for the image format itself rather than the content of the image? And how would the differences in the images affect the resize function?


text:
Q: Angular Modal Service I'm trying to get modals working in my Angular application. I tried using Bootstrap and Angular Material modals but I could not make them work. I decided to try with Angular Modal Service, however I'm getting the same error. Whenever I call the function ModalService.showModal I get the following error:
angular.js:12416 TypeError: Cannot read property 'showModal' of undefined
at Scope.$scope.show (AboutController.js:4)
at fn (eval at <anonymous> (angular.js:13231), <anonymous>:4:203)
at callback (angular.js:23371)
at Scope.$eval (angular.js:15878)
at Scope.$apply (angular.js:15978)
at HTMLAnchorElement.<anonymous> (angular.js:23376)
at HTMLAnchorElement.n.event.dispatch (jquery-2.2.3.min.js:3)
at HTMLAnchorElement.r.handle (jquery-2.2.3.min.js:3)

The service im using:
https://github.com/dwmkerr/angular-modal-service

The JS Fiddle example that I used:
http://jsfiddle.net/dwmkerr/8MVLJ/?utm_source=website&utm_medium=embed&utm_campaign=8MVLJ

Include:

About.html:

Comentarios

Show a Modal

App.module.js:
var Tiendiia = angular.module('Tiendiia', ['ui.router', 'ngMaterial', 'ui.bootstrap', 'ngCookies', 'angularModalService',]);

Tiendiia.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('yellow')
.accentPalette('orange')
.warnPalette('amber')
.backgroundPalette('grey');
});

AboutController.js
Tiendiia.controller('AboutController', ['$scope',  function($scope, ModalService) {

$scope.show = function() {
    ModalService.showModal({
        templateUrl: 'modal.html',
        controller: "ModalController"
    }).then(function(modal) {
        modal.element.modal();
        modal.close.then(function(result) {
            $scope.message = "You said " + result;
        });
    });
};

}]);

ModalController.js
Tiendiia.controller('ModalController', function($scope, close) {

 $scope.close = function(result) {
close(result, 500); // close, but give 500ms for bootstrap to animate
};

});

I have looked everywhere I could, but I can't find why it's not working.
Thanks!

A: On angular material it is called dialog what you need. Sometimes angular material uses John Papa style that is recommended but sometimes difficult to understand for beginners. If you understand this guide then you really understand angular.
Link To styleguide
Try to use modal of ui.bootstrap and do not add unnecessary libraries with functionality that you already have on ui bootstrap. Anyways I think your error might be here:
It seems that on about controller
['$scope',  function($scope, ModalService)
you need to add ModalService
['$scope', 'ModalService',  function($scope, ModalService)


text:
Q: C++ virtual "file" stream I have an object that writes binary data to a file. Sometimes it needs to seek to the beginning and re-write some data, to update a header of instance. I now need to avoid file i/o, so I am looking for something equivalent to a "virtual" file stream that I could seek around with.
Right now I am using a vector, but I switched from a file to improve performance as much as absolutely possible in the first place. I am also having logical problems trying to imitate fseek with a vector.
Is there a better object to use in C++? My use case is
MyVirtualStream vs;
vs.Write(somebytes);
vs.Write(somebytes);
vs.Seek(0);
vs.Read(&somestruct);
somestruct.data = 555;
vs.Write(struct);
vs.Seek(0 + sizeof(somestruct));

A: You could use std::stringstream:
NOTE: Read and write position seekg and seekp is independent for std:stringstream, but are interchangeable for file streams. In other words, there is only one pointer maintained for files.
#include <sstream>
#include <iostream>

struct Header
{
    int flag1;
    char flag2;
};

// Also you can provide an overload for `std::ostream::operator<<` like

std::ostream& operator<<(std::ostream& out, Header& h)
{
    out.write(reinterpret_cast<char*>(&h), sizeof(Header));
    return out;
}

std::istream& operator>>(std::istream& in, Header& h)
{
    Header header;
    in.read( reinterpret_cast<char*>(&header), sizeof(Header) );
    h = std::move(header);
    return in;
}

int main(int argc, char *argv[])
{

    std::stringstream ss;
    Header h {0x30303030, 0x31};
    Header h2 {0x32323232, 0x33};
    std::string str = "Hello, world";
    ss << str;
    ss.seekp(0);  // move write position.
    ss.write("Buy  ", 5);
    std::cout << ss.str() << std::endl;
    ss.write(reinterpret_cast<char*>(&h), sizeof(Header));
    ss.seekg(5); // move read position
    ss.read(reinterpret_cast<char*>(&h2), sizeof(Header));
    return 0;
}

A: You're looking for a stringstream.
It's a stream, backed by a string (instead of a file or other thing).


text:
Q: is there an efficient way to run multiple BFt-tests on multiple vectors? i have a dataframe with a dozen columns,
and i want to run the function "ttestBF" on 5 of them.
each row is a subject.
and i want to compare inside each column between 2 conditions (male/female).
what i did looks like this:
 ttestBF(df$sheker[df$sex == "f"],
         df$sheker[df$sex == "m"])

five times for each column.
i have tried looking in the history of similar questions but they were quite different.
is there a way to do this more efficiently?


text:
Q: Translate as you type in Mobile App using Flutter I am looking to build a functionality wherein as user type in English in a text box, there is a corresponding text box which starts to display the text in other language(lets say Hindi).
Then I want user to change the text in Hindi according to their need and that makes change in English text box.
are there any API's available to perform a function like this?
Secondly I am looking to use them in my mobile app which is to be built using Flutter.
I have looked at Google Translate, however I could not find an option where I can translate as one type.
Any help would be really appreciated.


text:
Q: How do I override nested dependencies with `yarn`? If my package has these dependencies
{ "name": "my-package",
  "dependencies": { "foobar":"~1.0.3", "baz":"2.0.9" }

And the foobar package has these dependencies
{ "name": "foobar",
  "dependencies": { "baz":"^2.0.0" }

and the most recently released version of baz is 2.1.0, the first run of yarn will install baz@2.1.0 in foobar/node_modules.
How do I force yarn to use the baz@2.0.9 package for foobar?
My understanding is that this would be possible using npm shrinkwrap (a la this question).

The summary of my question probably is: Yarn creates repeatable, deterministic installations, but how do I customize that installation?

A: This is now possible with yarn's selective version resolution feature.
In your project's package.json, use resolutions:
  "resolutions": {
    "foobar/**/baz": "2.0.9"
  }

This overrides package foobar's (and any other packages under it) version of baz, forcing it to be version 2.0.9.

A: If you do in fact have a sub-dependency that is overly restrictive in what versions it will accept, you can override them using yarn.
UPDATED EDIT: Yarn now, as of 1.0, officially supports the "resolutions" block. So the way to override resolutions is to just add a block like this to package.json:
"resolutions": {
      "package-a": "2.0.0",
      "package-b": "5.0.0",
      "package-c": "1.5.2"
}

You'll get warnings for "incompatible" versions sometimes, but I find that some packages (like socket.io) are overly restrictive in what version they accept, and so I'll happily select the latest version when it doesn't actually break things.
Original but outdated answer below.
It sounds like the original question wasn't exactly correct, but the original question was in fact the one I wanted answered, and I found an answer, so here it is for posterity:
I'm using the socket.io library, and it has component-emitter as a dependency. But it has a pair of versions that it requires. This is what the yarn.lock file looked like before I changed anything:
component-emitter@1.1.2:
  version "1.1.2"
  resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.1.2.tgz#296594f2753daa63996d2af08d15a95116c9aec3"

component-emitter@1.2.0:
  version "1.2.0"
  resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.2.0.tgz#ccd113a86388d06482d03de3fc7df98526ba8efe"

So it was including two copies of the component emitter in my client code. I looked, and there didn't appear to be any breaking changes between 1.1.2 and 1.2.0 (or 1.2.1, which was current). I first tried just changing the yarn.lock file:
component-emitter@1.2.1, component-emitter@^1.2.1, component-emitter@1.1.2:
  version "1.2.1"
  resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.2.1.tgz#137918d6d78283f7df7a6b7c5a63e140e69425e6"

This worked, but the file has warnings about it being autogenerated, meaning that every single update or new package I add will stomp on this change. A bit of searching found the yarn --flat option, which will force yarn to choose no more than one of each package in the entire project. That seems like overkill to me, since I'm sure there are actual cases of incompatibility between older and newer packages. I just wanted to eliminate a redundant package from my client code, to make the download smaller; I still want the development packages to all work correctly.
But in the docs to yarn --flat I found a reference to a "resolutions" block that can go in package.json:
"resolutions": {
  "package-a": "2.0.0",
  "package-b": "5.0.0",
  "package-c": "1.5.2"
}

So I tried putting "component-emitter" : "1.2.1" in a new "resolutions" block in my package.json, and it in fact flattened component-emitter to 1.2.1 for all places that required it, and now I have only one copy in my client code.
(And now the resolutions block is completely supported in yarn, so you don't even need to use --flat.)

A: EDIT: This is now deprecated, please read this answer instead:
https://stackoverflow.com/a/46615878/2398593

@SomeCallMeTime's answer is great and we've been doing that for month at work.
Unfortunately, this is not possible anymore since the v0.24.x (see that comment).
There's an opened PR on Github with an RFC proposal to have a simple way of handling that use case without having to keep an eye on the generated lockfile.


text:
Q: How to map an int to a tuple and access the tuple in scala I have an input map from an integer to a tuple of Int and Double as follow.
def doSomething(x: Seq[Map[Int, (Int, Double)]]): Int = {.....}

Now, I want to access each element of the tuple in x as follows inside doSomething.
val res = x.map({ (input, weight) => }).unzip

Then I do some computation on the input which is an Int and weight which is a double for all keys of the map. But this does not work. How can I access the tuple values from the map?

A: You need to perform two map operation in order to access your Map values (input,weight)
x.map(_.map { case (key, (input, weight)) => /*do something with (input,weight)*/})

A: so x.map requires a function as parameter of form Map[Int,(Int,Double)] => B in your case so to get to the input and weight (assuming that's the tuple) you'll have to
x.map(
    kvMap => kvMap.map(
      kv => {
          val tuple = kv._2
          val input = tuple._1
          val weight = tuple._2
      }
    )
)

A: You can do it using collect
scala> val seqMap :Seq[Map[Int, (Int, Double)]] = List(Map(1->(1,1.0), 2-> (2,2.0)),Map(3->(3,3.0), 4-> (4,4.0)))
seqMap: Seq[Map[Int,(Int, Double)]] = List(Map(1 -> (1,1.0), 2 -> (2,2.0)), Map(3 -> (3,3.0), 4 -> (4,4.0)))

scala>val result = seqMap.collect{
  case e => e.values.map( ele => ele._1 -> ele._2)
}.flatten
result :  Seq[(Int, Double)] = List((1,1.0), (2,2.0), (3,3.0), (4,4.0))


text:
Q: error trying to use GridSearhCV with XGBClassifier I am trying to use GridSearchCV with XGBoost in order to train and fit using the best prams quite a large dataset (> 500MB). But I'm getting an error which I am unable to resolve. I have a laptop with 32GB ram and the Python memory consumption did not exceed 10gb once I left it running so I don't think it is a memory-related issue although I am not sure.
I do not even know if can get through these kinds of errors by using a different model or something else. Maybe it is a problem with grid search but not sure how to get over this without using it.
Here is the code:
parameters = {'learning_rate': [0.03,0.04,0.05,0.06,0.07],
              'max_depth': [3,5,7,9,11],
              'min_child_weight': [2,4,6,8,10],
              'subsample': [0.9,0.8,0.7,0.6,0.5],
              'colsample_bytree': [0.9,0.8,0.7,0.6,0.5]}

xgb_model = XGBClassifier(objective = 'multi:softprob', nthread = 4, n_estimators= 1000, seed = 1337, silent = 0)

clf = GridSearchCV(estimator=xgb_model,param_grid=parameters,n_jobs=-1,verbose = 5)
clf.fit(orders_prior1[['user_id','order_number','order_dow','order_hour_of_day','days_since_prior_order']]\
                       ,orders_prior1['product_id'], orders_prior1['user_order'])

Here is the Error:
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\sklearn\externals\joblib\_parallel_backends.py", line 344, in __call__
    return self.func(*args, **kwargs)
  File "C:\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 131, in __call__
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "C:\Anaconda3\lib\site-packages\sklearn\externals\joblib\parallel.py", line 131, in <listcomp>
    return [func(*args, **kwargs) for func, args, kwargs in self.items]
  File "C:\Anaconda3\lib\site-packages\sklearn\model_selection\_validation.py", line 238, in _fit_and_score
    estimator.fit(X_train, y_train, **fit_params)
  File "C:\Anaconda3\lib\site-packages\xgboost\sklearn.py", line 445, in fit
    verbose_eval=verbose)
  File "C:\Anaconda3\lib\site-packages\xgboost\training.py", line 205, in train
    xgb_model=xgb_model, callbacks=callbacks)
  File "C:\Anaconda3\lib\site-packages\xgboost\training.py", line 76, in _train_internal
    bst.update(dtrain, i, obj)
  File "C:\Anaconda3\lib\site-packages\xgboost\core.py", line 806, in update
    _check_call(_LIB.XGBoosterUpdateOneIter(self.handle, iteration, dtrain.handle))
OSError: [WinError -529697949] Windows Error 0xe06d7363

I posted quite a similar question to this (except using a neural network classifier) a few days ago but still, did not get any positive answer. Any ideas on why this kind of error happens and how to resolve this kind of error? Maybe try a different language? Although Python became a key language for dealing with data-science problems, I am up to using a different language to get over this problem. Thanks in advance.


text:
Q: How do I get my TileSheet to wrap? I load the map from a level file which are just numbers corresponding to a tile in the tilesheet.
Here is the level file
[Map]
0 1 0 0 0 0 0 0
0 0 20 0 0 0 0 0
0 0 0 40 0 0 0 0
0 0 0 0 63 0 0 0
0 0 0 0 0 79 0 0
0 0 0 0 0 0 0 0

And here is the code that interprets it
void LoadMap(const char *filename, std::vector< std::vector <int> > &map)
{
    std::ifstream openfile(filename);
    if(openfile.is_open())
    {
        std::string line, value;
        int space;

        while(!openfile.eof())
        {
            std::getline(openfile, line);

            if(line.find("[TileSet]") != std::string::npos)
            {
                state = TileSet;
                continue;
            }
            else if (line.find("[Map]") != std::string::npos)
            {
                state = Map;
                continue;
          }

            switch(state)
            {
            case TileSet:
                if(line.length() > 0)
                    tileSet = al_load_bitmap(line.c_str());
                break;
            case Map:

                std::stringstream str(line);
                std::vector<int> tempVector;

                while(!str.eof())
                {
                    std::getline(str, value, ' ');
                    if(value.length() > 0)
                        tempVector.push_back(atoi(value.c_str()));
                }
                map.push_back(tempVector);
                break;
            }
        }
    }
    else
    {
  }
  }

And this is how it looks
http://i.imgur.com/6W49eWf.jpg
Ok so my Tilesheet is 1000 by 200 and it looks like this http://i.imgur.com/Y83zBxj.png
How would I make it wrap around to 20 or 40 when putting in 20 or 40 in the map file?
void DrawMap(std::vector <std::vector <int> > map)
{
    for(int i, j = 0; i < map.size(); i ++)
    {
        for(j = 0; j < map[i].size(); j ++)
        {
          al_draw_bitmap_region(tileSet, map[i][j] * TileSizeX, 0, TileSizeX, TileSizeY, j   * TileSizeX, i * TileSizeX, NULL);
        }
    }
}

Also the TileSizeX and TileSizeY is 50

A: You need to calculate what cell of the tileset your target tile sits. You have the tileset index. Use a little math, based on the dimensions of the tileset, to determine the col and row of that tile.
//This is how many columns your tileset can have.
//You could even dynamically calculate this if you wanted.
static const int TILESET_COLCOUNT = 20;

void DrawMap(std::vector<std::vector<int> > map)
{
    int mapRowCount = map.size();

    for (int i = 0; i < mapRowCount; ++i)
    {
        int mapColCount = map[i].size();

        for (int j = 0; j < mapColCount; ++j)
        {
            //This is your tileset index in your level map.
            int tilesetIndex = map[i][j];

            //The tileset row can be calculated by dividing the tileset index by the number of columns in a tileset row.
            int tilesetRow = floor(tilesetIndex / TILESET_COLCOUNT);

            //The tileset column can be calculated by retrieving the remainder of the modulus operation on the total number of columns in a row.
            int tilesetCol = tilesetIndex % TILESET_COLCOUNT;

            al_draw_bitmap_region(
                tileSet, //The tileset
                tilesetCol * TileSizeX, //multiply the tileset column by the size of a tile to get the source x
                tilesetRow * TileSizeY, //multiply the tileset row by the size of a tile to get the source y
                TileSizeX, //width
                TileSizeY, //height
                j * TileSizeX, //destination x
                i * TileSizeX, //destination y
                NULL //flags
            );
        }
    }
}


text:
Q: Keyboard Freezes with Wireless Use on HP Pavillion dm1
Possible Duplicate:
What should I do when Ubuntu freezes?

I recently bought an HP Pavillion DM1 laptop for everyday use. To get the wireless card working, I had to install the proprietary Broadcom drivers.
However, this has created a problem: from time to time, the keyboard and touchpad freeze. The system is not frozen, and whatever was running keeps on running. If I connect an external keyboard/mouse to the system they work fine, and if I run
sudo modprobe -r psmouse
sudo modprobe psmouse

from a terminal, then the laptop's keyboard and touchpad regain their functionality.
If I switch of the wireless, this problem does not happen any more.
Similar problems have been posted elsewhere, but the solutions given have not worked for me. These normally include blacklisting modules in /etc/modprobe.d/blacklist.conf.
Any help will be appreciated.

A: This is clearly a bug, file an issue with launchpad using apport, specify that this is a kernel issue so it gathers all the necessary details. Thanks.
https://help.ubuntu.com/community/ReportingBugs#Filing_bugs_when_off-line

apport-cli -f -p linux-generic --save bug.crash
ubuntu-bug -c bug.crash


text:
Q: What is the reasoning behind saying the magnetic field is non conservative I remember hearing this and believing it but I cant seem to show it. If i consider a positive test charge moving around in a uniform magnetic field, then the field always seems to do no work. How can I go about reasoning that the work done in a magnetic field is path dependant and consequently there is no unique magnetic potential at a point?

A: A vector field $\mathbf F$ is called conservative if there exists some scalar field $\psi$ such that $$\mathbf F = \nabla \psi$$
If $\mathbf F$ is conservative, then the fact that it is irrotational, i.e. $\nabla \times \mathbf F = \nabla \times (\nabla \psi) = 0$, follows immediately from the fact that the curl of a gradient always vanishes.  Equivalently, if the curl of a vector field $\mathbf F$ is not zero, then $\mathbf F$ is not conservative.
According to Faraday's law, though,
$$\nabla \times \mathbf B = \mu_0 \mathbf J + \epsilon_0 \mu_0 \frac{\partial \mathbf E}{\partial t}$$
so if the right hand side does not vanish, then $\mathbf B$ is not conservative.

It's also important to note that the converse holds only if the domain in question is simply connected.  That is, the fact that $\nabla \times \mathbf B \neq 0$ does not generally imply that $\mathbf B$ is conservative.


text:
Q: Phrase for "able to concentrate for long periods of time" I am looking for a word or phrase that describes someone who is able to concentrate and work for long periods of time without taking a break. An example would be a computer programmer who can sit in front of the computer and write code for hours without getting distracted or needing to take a break.
Edited to clarify:
I am looking for a word/phrase that describes the positive attribute of someone who is able to do this (along the lines of "diligent" or "assiduous"), not a phrase that describes someone who is actually doing it.
Example: "John is responsible, diligent, and ___. "

A: Focused

Directing a great deal of attention, interest, or activity towards a particular aim:
Darren knows what he wants and he's very focused.
He seems to be very focused on the new challenge.
The need for more focused research

Oxford Dictionary of English

A: How about persevering

to persist in a state, enterprise, or undertaking in spite of counterinfluences, opposition, or discouragement


text:
Q: Can't Load URL: The domain of this URL isn't included in the app's domains - Facebook Login I'm trying to get access token from user
string response_script = "<script>top.location.href='https://www.facebook.com/v2.4/dialog/oauth?response_type=token&client_id=[APPLICATION ID]&redirect_uri=https://www.facebook.com/[APPLICATION URL]/?sk=app_[PAGE ID]&scope='; </script>";

But I'm getting an error:

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

That code works well. So I think that needs to add my url to

Valid OAuth redirect URIs

But It doesn't exists in advanced section anymore. facebook changed it's design and now it looks like this. It's too big image and because I have it in out of stackoverflow
What can I do?

A: I had the same issue as you, I figured it out. Facebook now roles some features as plugins. In the left hand side select Products and add product. Then select Facbook Login. Pretty straight forward from there, you'll see all the Oauth options show up.

A: Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.
I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

A: Adding my localhost on Valid OAuth redirect URIs
at https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/ solved the problem!
And pay attention for one detail here:
In this case http://localhost:3000 is not the same of http://0.0.0.0:3000 or http://127.0.0.1:3000
Make sure you are using exactly the running url of you sandbox server.
I spend some time to discover that...

A: I  had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/

A: If you are using AWS, go to Facebook Developers console - https://developers.facebook.com/
You need to add the URL from User Pools > App Integration > Amazon Cognito domain, and add /oauth2/idpresponse to it, for example:
https://myappxxxxx-xxxx-dev.auth.us-east-2.amazoncognito.com/oauth2/idpresponse


text:
Q: Prevent javascript access to DOM elements of widget If I develop a Javascript widget that others can embed directly into their page without using an iFrame, is it somehow possible to prevent Javascript access to DOM-elements of the widget from the embedding page?
Suppose the widget is an image gallery and the embedding website selects all images via Javascript and changes both CSS attributes and any click handlers. How can I prevent the functionality or appearance of the widget from being changed without using an iFrame? I imagine this as a kind of firewall that allows/blocks Javascript access by DOM-source and destination.

A: The perfect solution is Shadow Dom


text:
Q: I am using selenium(python) to open youtube. But when it opens chrome, I am not signed in When selenium opens youtube, I am not signed in and when I try to sign in, it says the following:
"This browser or app may not be secure. Learn more
Try using a different browser. If you're already using a supported browser, you can refresh your screen and try again to sign in."
Is there any way to sign in
This is the code:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver

browser = webdriver.Chrome("C:\\Users\\Pranav Sandeep\\Downloads\\chromedriver.exe")

browser.get('https://www.youtube.com')

SearchBar = browser.find_element_by_name("search_query").send_keys("Selenium", Keys.ENTER)

Video = browser.find_element_by_id("video-title")
Video.click()

A: You need to first sign in to google and then you can go to youtube. Use this code below.
Use Seleniumwire with undetected browser v2

Note: put chromedriver in your sys path.

from seleniumwire.undetected_chromedriver.v2 import Chrome, ChromeOptions
import time

options = {}
chrome_options = ChromeOptions()
chrome_options.add_argument('--user-data-dir=hash')
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--incognito")
chrome_options.add_argument("--disable-dev-shm-usage")
# chrome_options.add_argument("--headless")
browser = Chrome(seleniumwire_options=options, options=chrome_options)

browser.get('https://gmail.com')
browser.find_element_by_xpath('//*[@id="identifierId"]').send_keys('your-email')
browser.find_element_by_xpath('//*[@id="identifierNext"]/div/button').click()
time.sleep(5)
browser.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys('you-password')
browser.find_element_by_xpath('//*[@id="passwordNext"]/div/button').click()
time.sleep(5)
browser.get('https://www.youtube.com')

In addition to this, selenium wire has many awesome features, check out Github repository


text:
Q: Piping between several processes in C I'm writing a shell in C and am trying to implement multiple pipes. I've done this by creating a two dimensional array with pipes and using a separate pipe everytime. All commands in between pipes are separated by a parsing function and put into a struct. Every command line in-between pipes gets it's own process. And for all commands in the middle I'm trying to read from the previous process and write to the next one. Somewhere here the problem starts. It works fine for one pipe, however when I trying more than one pipe I don't get any output and the program gets stuck. In GDB I get a failed message from the execvp after forking the second process. What can this be due to?

int create_pipe(int* fd)
{
  int pipe_id = pipe(fd);
  if (pipe_id == -1)
  {
    return -1;

  }
  return 0;
}

void write_pipe(int* fd)
{
  close(fd[READ]);
  if ((dup2(fd[WRITE], STDOUT_FILENO)) < -1)
  {
    fork_error();
  }
  close(fd[WRITE]);

}

void read_pipe(int *fd)
{
  close(fd[WRITE]);
  if (dup2(fd[READ], STDIN_FILENO) < 0)
  {
    fork_error();
  }
  close(fd[READ]);

}

void need_to_pipe (int i, int (*fd)[2])
{

  if (commands[i].pos == first)
  {
    write_pipe(fd[i * 2]);
  }
  else if (commands[i].pos == last)
  {
    read_pipe(fd[(i-1) *2]);
  }
  else //if (commands[i].pos == middle)
  {

      dup2(fd[(i-1)*2][READ], STDIN_FILENO);
      close(fd[(i-1)*2][READ]);
      close(fd[(i-1)*2][WRITE]);
      //close(fd[(i)*2][READ]);
      //close(fd[(i)*2][WRITE]);
      close(fd[(i)*2][READ]);
      dup2(fd[i*2][WRITE], STDOUT_FILENO);
      close(fd[(i)*2][WRITE]);
  }

}

void fork_cmd(int i, int (*fd)[2]) {

  pid_t pid;
  switch (pid = fork()) {
    case -1:
      fork_error();
    case 0:
      if (!(commands[i].pos == single))
      {
        need_to_pipe(i, fd);
      }
      if (execvp(commands[i].argv[0], commands[i].argv)<0)
      {

        exit(EXIT_FAILURE);
      }
  }
}

void fork_cmds(int n, int (*fd)[2])
{
  for (int i = 0; i < n; i++)
  {
    fork_cmd(i, fd);
  }
}

void wait_once ()
{
  wait(NULL);
}

void wait_for_all_cmds(int n)
{
  for (int i = 0; i < n; i++)
  {
      wait_once();
     //wait for number of child processes.
  }

}

int main() {
  int n;
  size_t size = 256;
  char line[size];

  while(true) {

    get_line(line, size);

    n = parse_cmds(line, commands);

    int fd[(n-1)][2];
    for(int i =0;i<n-1;i++)
    {
      int pipe_id = pipe(fd[i*2]);

      if (pipe_id == -1)
      {
        return -1;

      }
    }

    fork_cmds(n, fd);

    for(int i =0;i<n-1;i++)
    {
      int *fdclose= fd[i*2];

      close (fdclose[READ]);
      close (fdclose[WRITE]);
    }

    wait_for_all_cmds(n);

  }

  exit(EXIT_SUCCESS);
}

A: You [probably] have too many processes keeping pipe ends open (that do not belong to the given child) because your loop opens all pipes before any forking.
This places an undue burden on each child because it has to close many pipe ends to prevent it from holding open a pipe end, preventing other children from seeing an EOF on their input pipes.

To see this, for debug purposes in your present code, the child could do (just before the exec* call) (e.g.):
fprintf(stderr,"child: %d\n",getpid());
fflush(stderr);
system("ls -l /proc/self/fd 1>&2");

Each child should only have three open streams on stdin, stdout, and stderr (e.g. 0, 1, 2).
I think you'd find that there are many extraneous/detrimental streams open on the various children.

You only need two pipe arrays (e.g.): int pipeinp[2]; int pipeout[2]; Initially, pipeinp is all -1.
Roughly ...
Parent should do a single pipe call at the top of fork_cmd [before the fork] to pipeout.
The child dups (and closes) the read end of pipeinp [if not -1] to stdin.
Child dups/closes the write end of pipeout to stdout.
It closes the read end of pipeout.
After that, the parent should copy pipeout to pipeinp and close the write end of pipeinp
This should be repeated for all pipe stages.
No pipe to pipeout should be done for the last command. And, the [last] child should not change stdout.

For a working example, see my answer: fd leak, custom Shell


text:
Q: bat file doesn't proceed after mvn clean install I've put below lines in a .bat file

cd D:\code\MML\
cd D:\code\MML\com
svn update
mvn clean install -Dmaven.test.skip=true
cd D:\code\MML\m14_6
svn update
mvn clean install -Dmaven.test.skip=true

When I run this it can successfully change directories i.e. cd D:\code\MML\  and cd D:\code\MML\com get executed. However after maven clean install mvn clean install -Dmaven.test.skip=true(takes about 5 minutes to execute), it doesn't proceed further to execute cd D:\code\MML\m14_6
How can I fix this(tried to search, but keywords put in by me is not fetching the answer I need) ?
Thanks in advance :)

A: To execute a command file from a running command file you need to CALL it, if not the current running command file will not resume. Try :
call mvn clean install -Dmaven.test.skip=true


text: Q: Can we display a html tag from a background page in a Chrome Extension? I want to display a custom made prompt box when we open the browser. If we use the content script it will only display the prompt on a specific tab. I want to display a custom prompt from the background page so that the user will be able to access the browser features after answering the prompt.


text:
Q: Search Method not working Basically i have a hashmap and the search method is missing a keyboard.next which should allow the user to input the name they want to search for.  There are no errors.  The output does not allow an opportunity for the user to enter the name they want to search.  The weird thing is i can use the userInput method and it works perfectly.  Here is my code:
Store declaration
//Imports.
import java.util.Scanner;
//********************************************************************
public class MainApp
{
    //The Scanner is declared here for use throughout the whole MainApp.
    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args)
    {
        new MainApp().start();

    }
    public void start()
    {
//Create a Store named Store and add Employee's to the Store.
        EmployeeStore Store = new EmployeeStore();
        Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));

        Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));

        Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
//********************************************************************

/*Test Code.
        Store.searchByName("James O' Carroll");
        Store.print();
        Store.searchByEmail("gmail.com");
        Employee andy = Store.searchByEmail("hotmail.com");
        System.out.println(andy);
        Employee employee = Store.searchByName("James O' Carroll");
        if (employee != null)
        {
            employee.setEmployeeName("Joe");
            employee.setEmployeeId(1);
            employee.setEmployeeEmail("webmail.com");
           Store.edit(employee);
           Store.print();
        }*/
//********************************************************************

        int choice ;
        System.out.println("Welcome to the Company Database.");
        do
        {
         choice = MenuMethods.getMenuChoice(
                "1.\tView All" +
                "\n2.\tAdd" +
                "\n3.\tDelete" +
                "\n4.\tDelete All " +
                "\n5.\tEdit" +
                "\n6.\tSearch" +
                "\n7.\tPrint"+
                "\n8.\tExit", 8, "Please enter your choice:", "Error [1,8] Only");
         //String temp = keyboard.nextLine();  This prevented entering the choice.
        switch (choice)
        {
            case 1:
                 System.out.println("View All");
                Store.print();

                break;

        case 2:
             System.out.println("Add");
                Employee employee = MenuMethods.userInput();
                Store.add(employee);

                break;

        case 3:
             System.out.println("Delete");
                //Store.delete();

                break;

        case 4:
                System.out.println("Delete All");
                Store.clear();

                break;
        case 5:
           System.out.println("Edit");
           Employee employee2 = MenuMethods.userInput();
           Store.searchByName(employee2.getEmployeeName());
         if (employee2 != null)
        {
            employee2.setEmployeeName("Joe");
            employee2.setEmployeeId(1);
            employee2.setEmployeeEmail("webmail.com");
           Store.edit(employee2);
           Store.print();
        }

            break;
        case 6:
             System.out.println("Search");
             Employee employee1 = MenuMethods.userInputByName();
             Store.searchByName(employee1.getEmployeeName());

            break;
        case 7:
             System.out.println("Print");
            Store.print();

            break;
        case 8:
             System.out.println("Exit");

            break;
        }

        } while (choice != 8);

     }
}

//Imports
import java.util.Scanner;
//********************************************************************

public class MenuMethods
{
    private static Scanner keyboard = new Scanner(System.in);

    //Methods for the Company Application menu.
    //Method for validating the choice.
         public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
         {
                System.out.println(menuString);
                int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
                return choice;
         }
    //********************************************************************
    //This method is used in the getMenuChoice method.
            public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage)
            {
                int number;
                boolean valid;
                do {
                    System.out.print(prompt);
                    number = keyboard.nextInt();
                    valid = number <= max && number >= min;
                    if (!valid) {
                        System.out.println(errorMessage);
                    }
                } while (!valid);
                return number;
            }
    //********************************************************************
    public static Employee userInput()
    {
         String temp = keyboard.nextLine();
         Employee e = null;
         System.out.println("Please enter the Employee Name:");
         String employeeName = keyboard.nextLine();
         System.out.println("Please enter the Employee ID:");
         int employeeId = keyboard.nextInt();
         temp = keyboard.nextLine();
         System.out.println("Please enter the Employee E-mail address:");
         String employeeEmail  = keyboard.nextLine();
         return e = new Employee(employeeName , employeeId, employeeEmail);

    }
    //********************************************************************
    public static Employee userInputByName()
    {

         Employee e = null;
         System.out.println("Please enter the Employee Name:");
         String employeeName = keyboard.nextLine();
         System.out.println("Please enter the Employee Name:");

         return e =  new Employee(employeeName);

    }
    //********************************************************************

}

Search Method in the mainApp
case 6:
             System.out.println("Search");
             Employee employee1 = MenuMethods.userInputByName();
             Store.searchByName(employee1.getEmployeeName());

            break;

The actual Search method.
public Employee searchByName(String employeeName)
    {
        Employee employee = map.get(employeeName);
        System.out.println(employee);
        return employee;
    }
//********************************************************************

The userInputByName method.  This is where the problem seems to lie.
 public static Employee userInput()
    {
         String temp = keyboard.nextLine();
         Employee e = null;
         System.out.println("Please enter the Employee Name:");
         String employeeName = keyboard.nextLine();
         System.out.println("Please enter the Employee ID:");
         int employeeId = keyboard.nextInt();
         temp = keyboard.nextLine();
         System.out.println("Please enter the Employee E-mail address:");
         String employeeEmail  = keyboard.nextLine();
         return e = new Employee(employeeName , employeeId, employeeEmail);

    }
    //********************************************************************
    public static Employee userInputByName()
    {

         Employee e = null;
         System.out.println("Please enter the Employee Name:");
         String employeeName = keyboard.nextLine();
         System.out.println("Please enter the Employee Name:");

         return e =  new Employee(employeeName);

    }
    //********************************************************************

A: Let me try my best.
First of all, why is there two println statements in your userInputByName()?
 public static Employee userInputByName()
    {
         Employee e = null;
         System.out.println("Please enter the Employee Name:");
         String employeeName = keyboard.nextLine();
         System.out.println("Please enter the Employee Name:"); //!???

         return e =  new Employee(employeeName);
    }

Then, in the case 6, you just call the method searchByName and does not check if the search is successful or not. I suggest:
case 6:
    System.out.println("Search");
    Employee employee1 = MenuMethods.userInputByName();
    Employee foundEmployee = Store.searchByName(employee1.getEmployeeName());

    if (foundEmployee != null) {
        System.out.println("Found employee!");
    } else {
        System.out.println("Not Found!");
    }

    break;


text:
Q: Include object issue while geting async list In asp.net core, I can get list if I don't include object. But can't get list of data if I include a object with it.
I have tried both code first and database first approach. Results are same.
public partial class BloodGroups
{
    public BloodGroups()
    {
        Donors = new HashSet<Donors>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Donors> Donors { get; set; }
}

public partial class Donors
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? BloodGroup { get; set; }
    public virtual BloodGroups BloodGroupNavigation { get; set; }
}

public async Task<ActionResult<IEnumerable<Donors>>> GetDonors()
{
    return await _context.Donors.Include(d => d.BloodGroupNavigation).ToListAsync();
}

I have created a web API project using asp.net core in visual studio 2019. I have created two model with one to many relationship. Then I had created a async call to get all donors list. It gives me all data. But if I include BloodGroups object with it, It shows first data, then the object of BloodGroup with incomplete donors list.
This is the result:
[{"id":1,"name":"Robiul","bloodGroup":2,"bloodGroupNavigation":
{"id":2,"name":"B+","donors":[


text:
Q: Max height - change when window is resized? I have a block grid in foundation, this has loads of images in it.
I would like set a max-height of the grid so that images after a certain height are not shown. I wish to show 2 rows and then hide the rest.
HTML:

CSS
.my-grid{

    min-height: 300px;
    overflow: hidden;

The above works and anything below 300px is hidden. I get into trouble though when the window is resized, 300px is no longer the desired height for 2 rows of images as the images are smaller for different media queries, my question is, how can I keep the max-height in relation to 2 rows of images?

A:
...the images are smaller for different media queries...

In that case, all you have to do is creating very similar media queries for the grid height. If your CSS to format images depending on screen height is something along these lines (assuming a li element wraps the image in its entirety):
@media (max-height: 900px) {
    .my-grid li {
        height: 150px;
    }
}

@media (max-height: 700px) {
    .my-grid li {
        height: 120px;
    }
}

@media (max-height: 500px) {
    .my-grid li {
        height: 100px;
    }
}

... then we know exactly what condition is met when the image is downscaled. We can use that to also scale the grid itself:
@media (max-height: 900px) {
    .my-grid {
        height: 300px; /* 2*150 = two rows of images */
    }
}

@media (max-height: 700px) {
    .my-grid {
        height: 240px; /* 2*120 = two rows of images */
    }
}

@media (max-height: 500px) {
    .my-grid {
        height: 200px; /* 2*100 = two rows of images */
    }
}


text:
Q: Multiple python commands does not run from bash I have a bash script that launches wsgi for python and celery as well. The pythib project launes nicely though celery does not work. Below i incluse two ways of invoking the wsgi project and celery and none works as expected.
Way No1
...
echo "the PWD of project now is : ${PWD}"
exec    gunicorn project.wsgi:application \
        --name audit_tool \
        --bind 0.0.0.0:8000 \
        --timeout 1000 \
        --workers 4 \
        --log-level=$level \
        --env DEBUG=${DEBUG} \
        --log-config tmp.conf \
        --preload &&
echo "Gunicorn started"
exec celery -A project worker -Q celery --loglevel=info --concurrency=1 --max-memory-per-child=25000 &&
sleep 2.5
ps aux | grep celery ;
echo 'done'

...
read -r -d '' cmd << end
    gunicorn project.wsgi:application \
        --name audit_tool \
        --bind 0.0.0.0:8000 \
        --timeout 1000 \
        --workers 6 \
        --log-level=$level \
        --env DEBUG=${DEBUG} \
        --log-config tmp.conf \
        --preload
end
echo Starting Gunicorn.
($cmd)
read -r -d '' cmd2 << end
    celery \
        -A project \
            worker \
        -Q celery \
        --loglevel=info \
        --concurrency=1 \
        --max-memory-per-child=25000
end
echo "Starting celery."
($cmd2)

Any help would be appreciated !!
I tried the two above ways and expectation was to launch the wsgi project and celery as well.

A: It depends how you want it to work...
If you want to do thing1, wait till it finishes, then thing2, use:
thing1
thing2

If you want to do thing1 and at the same time thing2, use:
thing1 &
thing2

If thing1 is actually 2 things, thing1A and thing1B, then you can combine them (Do not omit spaces ever. You may omit the semi-colons if the commands are spread across multiple lines):
{ thing1A ; thing1B ; }

So, in answer to your question:
You can do it like this:
{ gunicorn project.wsgi:application \
        --name audit_tool \
        --bind 0.0.0.0:8000 \
        --timeout 1000 \
        --workers 4 \
        --log-level=$level \
        --env DEBUG=${DEBUG} \
        --log-config tmp.conf \
        --preload &&
echo "Gunicorn started" } &

{ celery -A project worker -Q celery --loglevel=info --concurrency=1 --max-memory-per-child=25000 &&
sleep 2.5
ps aux | grep celery } &

So that starts gunicorn and your echo command in the background, and while that is still running, it starts celery, sleep and ps as another group of commands running in parallel with gunicorn.


text:
Q: Output Resistance of a High-Swing Cascode Current Mirror I am wondering how to calculate the output resistance of a High-Swing Cascode Current Mirror from small-signal parameters, see question High-Swing Cascode Current Mirror for the circuit.
First I transformed the output stage of that circuit to a small-signal representative, see circuit below (only considering gm and gds, since they have by far the highest impact). Since the output resistance is measured by shorting the inputs, the voltage controlled current sources deliver actually zero current and play no further role in the analysis. Therefore, the output resistance should be R_DS4 + R_DS2.
I simulated the High-Swing Cascode Current Mirror and got the following small-signal parameters (bias voltage and output voltage of 1V):
\$
gm_4=297.8uS \\
gds_4=3.118uS \\
gm_2=290.8uS \\
gds_2=2.267uS
\$
If I calculate now the output resistance as above, I get:
\$
1/gds4 + 1/gds2 = 320718.4\Omega + 441111.6\Omega = 761830\Omega
\$
But that seems totally different than what the simulation says, which is \$ 50M\Omega \$! I calculated this output resistance in cadence by typing 1/deriv(I_D4) in the calculator (Plotting I_D4 over V_OUT).
What am I doing wrong?

simulate this circuit – Schematic created using CircuitLab

A: When you want to measure the output resistance, you replace the \$i_{in}\$ current source on the left with an open circuit, and you put a \$v_s\$ signal generator at the output and measure the \$i_{s}\$ that is drawn out of it.
If you do this, the gates of \$M_2\$ and \$M_4\$ do not move and are small signal grounds.
Since the source of \$M_2\$ is also a signal ground, \$v_{gs2}\$ (small signal) is always zero.
This means that \$M_2\$ behaves like a resistor of value \$r_{ds2}\$. Let's call this \$R\$.
So you have a simple transistor with its source connected to ground through a resistance and its gate at signal ground, and you want the output resistance.
\$i_s\$ come in from the output and will be flowing down \$R\$, thus the source of M4 will be at a voltage of $$ v_{s4} = i_s R $$
This means that $$v_{gs4} = 0 - v_{s4} = - i_s  R$$ and thus that you have a downwards current in the transistor of $$i_{d4} = g_{m4}  v_{gs4} = - g_{m4}  i_s  R$$
You also have a current in \$r_{ds4}\$, which in the downward direction is $$i_{r_{ds4}}=(v_s - v_{s4})/r_{ds4}$$
These two currents, summed, are equal to \$i_s\$.
$$i_s = - g_{m4}  i_s  R + v_s/r_{ds4} - i_s  R/r_{ds4} $$
$$i_s  (1 + g_{m4}  R + R/r_{ds4}) = v_s  1/r_{ds4}$$
$$R_{out} = v_s/i_s = r_{ds4} + g_{m4}  R  r_{ds4} + R = r_{ds4} + g_{m4}  r_{ds2}  r_{ds4} + r_{ds2} \approx g_{m4} r_{ds2} r_{ds4}$$
With your data I'm getting \$43M\Omega\$ with the exact formula.
I think what you did wrong is to think in the wrong way about what is an input. The input is the generator of the current that gets mirrored, but instead you shorted the gates and sources of all transistors, despite there not being any input voltage source linking them, and thus having no reason to do so.