text:
Q: Setting Azure Blob Index tags with parenthesis - works in Browser but not in REST API I have been trying to set some blob tags and receiving a horrible error:

Response: HTTP/1.1 400 The tags specified are invalid. It contains characters that are not permitted.

I can set the tags with the same value in container browser without any issue, but via REST api it always fails with parenthesis, I have tried encoding in several ways, but the only way to success is to omit the patenthesis (which I am currently doing).
Successful payload:

<Tags>
    <TagSet>
        <Tag>
            <Key>FileID</Key>
            <Value>307145362</Value>
        </Tag>
        <Tag>
            <Key>FileName</Key>
            <Value>/omit/gkcs2022-11-15 14.49.12.log</Value>
        </Tag>
         <Tag>
            <Key>FileType</Key>
            <Value>GKCS Log File</Value>
        </Tag>
         <Tag>
            <Key>DeviceID</Key>
            <Value>151283</Value>
        </Tag>
         <Tag>
            <Key>Timestamp</Key>
            <Value>2023-01-20T144920.192Z</Value>
        </Tag>
         <Tag>
            <Key>DOWNLOADEDTO_GBMSVINTELLIFS</Key>
            <Value>False</Value>
        </Tag>
    </TagSet>
</Tags>

Failing Payloads:
Raw:

<Tags>
    <TagSet>
        <Tag>
            <Key>FileID</Key>
            <Value>307145362</Value>
        </Tag>
        <Tag>
            <Key>FileName</Key>
            <Value>/omitted/gkcs(2022-11-15 14.49.12).log</Value>
        </Tag>
         <Tag>
            <Key>FileType</Key>
            <Value>GKCS Log File</Value>
        </Tag>
         <Tag>
            <Key>DeviceID</Key>
            <Value>151283</Value>
        </Tag>
         <Tag>
            <Key>Timestamp</Key>
            <Value>2023-01-20T144920.192Z</Value>
        </Tag>
         <Tag>
            <Key>DOWNLOADEDTO_GBMSVINTELLIFS</Key>
            <Value>False</Value>
        </Tag>
    </TagSet>
</Tags>

URL Encoding:

<Tags>
    <TagSet>
        <Tag>
            <Key>FileID</Key>
            <Value>307145362</Value>
        </Tag>
        <Tag>
            <Key>FileName</Key>
            <Value>/omit/gkcs%282022-11-15 14.49.12%29.log</Value>
        </Tag>
         <Tag>
            <Key>FileType</Key>
            <Value>GKCS Log File</Value>
        </Tag>
         <Tag>
            <Key>DeviceID</Key>
            <Value>151283</Value>
        </Tag>
         <Tag>
            <Key>Timestamp</Key>
            <Value>2023-01-20T144920.192Z</Value>
        </Tag>
         <Tag>
            <Key>DOWNLOADEDTO_GBMSVINTELLIFS</Key>
            <Value>False</Value>
        </Tag>
    </TagSet>
</Tags>

Escape Character:

<Tags>
    <TagSet>
        <Tag>
            <Key>FileID</Key>
            <Value>307145362</Value>
        </Tag>
        <Tag>
            <Key>FileName</Key>
            <Value>/omit/gkcs\(2022-11-15 14.49.12\(.log</Value>
        </Tag>
         <Tag>
            <Key>FileType</Key>
            <Value>GKCS Log File</Value>
        </Tag>
         <Tag>
            <Key>DeviceID</Key>
            <Value>151283</Value>
        </Tag>
         <Tag>
            <Key>Timestamp</Key>
            <Value>2023-01-20T144920.192Z</Value>
        </Tag>
         <Tag>
            <Key>DOWNLOADEDTO_GBMSVINTELLIFS</Key>
            <Value>False</Value>
        </Tag>
    </TagSet>
</Tags>

A: As per Azure Storage documentation, only the following characters can be used in valid tag keys and values:

*

*Lowercase and uppercase letters (a-z, A-Z)

*Digits (0-9)

*A space ( )

*Plus (+), minus (-), period (.), solidus (/), colon (:), equals (=), and underscore (_)

Unfortunately, parenthesis characters are not currently supported by the Set Blob Tags REST API request.


text:
Q: How should I handle records not found when dealing with a json method I am using the following web method to get data for a driver my question is however. My question is what is the best way when your returning json to handle an error if data is not found is their a specific error code like page not found i no is 404 that i should send back in my webmethod
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public motorista GetDriverInformation(int driverId)
{

        motorista _wsmoristita = new motorista();
        _wsmoristita = _dal.GetDriverInformation(driverId);
        return _wsmoristita;

}

A: I suppose you are using jquery ajax. You can throw custom exception in the WebMethod with specific message, and after that in error function which you define in the ajax call you will show this message.
Part of $.ajax({});
    success: OnSuccess,
    error: OnErrorCall

Your OnErrorCall function will look like this
 function OnErrorCall(response) {

     alert(response.responseText);
  }

You can even show the message in some textbox, so if you throw an exception with text Record is not found or something like that, you can show it in label,alert or etc.
Here is an example of custom exception. You can read MSDN Article if you want
public class EmployeeListNotFoundException: Exception
{
    public EmployeeListNotFoundException()
    {
    }

    public EmployeeListNotFoundException(string message)
        : base(message)
    {
    }

    public EmployeeListNotFoundException(string message, Exception inner)
        : base(message, inner)
    {
    }
}

A: I ended up using something like below but I persume its not the best way as its to genral and wouldnt idnetify the column causing the fault to the web developer.
if (_wsHistory.id_terminal == 0)
 {

            Context.Response.Status = "404 Terminal table Not Found";
            //the next line is untested - thanks to strider for this line
            Context.Response.StatusCode = 404;
            //the next line can result in a ThreadAbortException
            //Context.Response.End();
            Context.ApplicationInstance.CompleteRequest();
            return null;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using field names containing the "@" (@timestamp) in elasticsearch-dsl I have a feeling that my question must have a trivial answer but several
hours of googling and searching python tutorials and I am still stuck.
My Field names often contain the "@" character (i.e @timestamp)
and the "@" is used by python for decorator functions.
How do you reference these field names in elasticsearch-dsl?
(I am using python 3.6.2)
resp = s.execute()

for hit in resp:
    print(hit.response_code)
    print(hit.@timestamp)

Of course I tried escaping and quoting.

A: you can always use hit['@timestamp'] or getattr(hit, '@timestamp')


text:
Q: Azure SAS | Error | Make sure the value of Authorization header is formed correctly including the signature I have got details to send data to Azure SAS.
Storage Account Name: acountname123
Blob Container Name - containername123
SAS URI:
https://acountname123.blob.core.windows.net/containername123?sv=2019-12-12&si=xxinboundpolicy&sr=c&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I tried to call this from soapui however its giving error related to authorization header.
Can you pl help me with what I need to pass in authorization header.
I followed below links
https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob
https://learn.microsoft.com/en-us/azure/storage/common/storage-sas-overview?toc=%2fazure%2fstorage%2fblobs%2ftoc.json

Thanks
Yatan


text:
Q: Angular Material Datepicker not keeps local timezone I have such code:
<mat-form-field class="example-full-width">
                <input
                  [matDatepicker]="picker"
                  formControlName="from"
                  matInput
                />
                <mat-datepicker-toggle [for]="picker" matSuffix></mat-datepicker-toggle>
                <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

{{element.get('from').value.toISOString()}}

{{element.get('from').value}}

this._formBuilder.group({
        from: [moment(source.from).local()]
})

I want that user will work with local timezone, but on server I want to send zero UTC offset.
Initially, it shows the correct date

But when I choose a different date from datepicker, it clears timezone from date for some reason. I don't need it.
Why it can be happening?

A: That was because of moment.tz.setDefault


text:
Q: Meteor: Using setInterval() To Run Function Once Per Day I am trying to run a function that will search for certain parameters and will email users only once a day.
I am finding many ways that can be done. It seems that setInterval() can be a way to do that.
 setInterval(function () {
    var date = new Date();
    if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
        alert("Surprise!!")
    }
}, 1000)

For example the above would trigger every day at 10 am.
I also found there is a package that runs cron jobs.
https://github.com/percolatestudio/meteor-synced-cron
It seems that I could set a cron job to send email every day. I have never used cron jobs so I think this option would be much more difficult for me at this moment.
Lastly, I also found this way to do it:
Call function once on day change
With just a regular function.
It seems that perhaps setTimeout() is the easiest way to get it done. But are there any setbacks? I don't want to miss emails, or worse email users many times. My site is live and growing so I would hate to find out the hard way.
Any help is appreciated.

A: I think you'll have to use Meteor.setInterval() rather than setInterval() to get it to work correctly on the server. However, I use this for functions I need to run every second; for longer periods any sort of cron job package would also work fine, such as synced-cron.

A: So, to finish the  subject and maybe help anyone in the same situation. This is how I did it. I added the package 'percolate:synced-cron'. Then on the server side I created a file 'cron.js'. And this is the code I used. I removed the rest of my action part of function for privacy, but the important parts are here. The parser.text makes it really easy to pick a time. 'every 5 seconds' (does action every 5 seconds).. or ('at 10 am') will take action every day at 10 am. Keep in mind mongo is set in UTC time as standard so you have to do the conversion.
    if (Meteor.isServer) {
  // optionally set the collection's name that synced cron will use
  SyncedCron.config({
    collectionName: 'somethingDifferent'
  });

  SyncedCron.add({
    name: 'Crunch some important numbers for the marketing department',
    schedule: function(parser) {
      // parser is a later.parse object
      // return parser.text('every 5 seconds');

      return parser.text('at 3:00 am');
      // midnight is at 5pm LA time ... 10 am LA time is 3 am UTC
    },
    job: function(intendedAt) {
      var today = new Date();
      var yesterday = new Date()
      var dayBeforeYesterday = new Date()
      yesterday.setDate(today.getDate() - 1)
      dayBeforeYesterday.setDate(today.getDate() - 2)

      var todaysUsers = Meteor.users.find({   createdAt: {    $lt: (yesterday), $gt: dayBeforeYesterday   } }).fetch()
      //rest of function here

      }
    }
  });

  Meteor.startup(function () {
    // code to run on server at startup
    SyncedCron.start();

    // Stop jobs after 15 seconds
    // Meteor.setTimeout(function() { SyncedCron.stop(); }, 7 * 1000);
  });
}

A: I would recommend using a package such as percolate:synced-cron to achieve this.


text:
Q: Extracting path element to make a string in bash I'd like to synthesize a string from a directory name in bash. I need to extract the last two path names to make a string.
For example, with an input /a/b/c, I want to make "b_c_HELLO".
How can I do that with bash?

A: Use basename and dirname:
parent=$(dirname "$input")
output=$(basename "$parent")_$(basename "$input")_HELLO

A: echo $PATH|awk -F"/" '{print $(NF-1)"_"$NF"_HELLO";}'

A: A pure bash implementation leveraging Parameter Expansion:
input="a/b/c"
tmp="${input%%/*/*}"
tmp="${tmp#$tmp/}"
output="${tmp/\//_}_HELLO"

Also, see http://mywiki.wooledge.org/BashFAQ/100


text:
Q: How to see $x^3-17$ has a degree 2 irreducible factor in $Q_{3}[x]$? Consider $Q_3$ field which is rational number $Q$ completed at $p=3$.(In other words, $Q_3$ is $3-$adic rational numbers.) Let $f=x^3-17\in Q_3[x]$. Let $O$ be the complete DVR associated to $Q_3$.
Clearly $f\in O[x]$. From Gauss lemma by $O$ PID, I see that if $f=gh,g,h\in Q_3[x]$,then $g,h\in O[x]$. Therefore, I can perform $3-$reduction by considering $\frac{O}{3}[x]$.
Now $\bar{f}\in Z_3[x]$ has $x^3+1=(x+1)^3\in Z_3[x]$. So I cannot apply hensel lemma here to determine factor of $f$ in $Q_3[x]$. The book says it has a degree 2 irreducible factor in $Q_3[x]$.
The other version of Hensel uses $f'(x)=3x^2$. And $x=-1$ yields $3^2\vert f(-1)$ and $3^2\not\vert f'(x)$ but $2=1+1$. The absolute value requires $|f(-1)|<|f'(-1)|^2$ where $|x|$ is the $\frac{1}{3^{v_3(x)}}$ and $v_3(x)$ is $3-$adic valuation of $x\in Q_3$. Both sides yields $\frac{1}{9}$ for absolute value. So I cannot apply this hensel lifting.
$\textbf{Q:}$ Can someone kindly provide hints to methods to determine reducibility for local fields? If I am lucky, I can proceed by hensel lemma but it requires factors after prime reduction being coprime. Have I done something wrong above?

A: Here's a method of using Strong Hensel, which you seem to know:
The cubic $X^3-17=f(X)$ has a root if and only if $f(X-1)=X^3-3X^2+3X-18$ has a root. Three-adically, the Newton polygon has a vertex at $(1,1)$, which already tells you that there's a factorization.
If you're not comfortable with Newton , go one step further, and substitute $3X$ for $X$, to get $f(3X-1)=27X^3-27X^2+9X-18=9\left(3X^3-3X^2+X-2\right)$. Modulo $3$, we get $3X^3-3X^2+X-2\equiv X-2\pmod3$, and this has the nice factorization $(X-2)\cdot1$ into two relatively prime factors. You can lift one of them to characteristic zero, by Strong Hensel, preserving its degree. Of course you choose the $X-1$. And there you have it.
In case you're nervous about using $1$ as one of the factors, let me reassure you. This freedom comes in handy surprisingly often.
EDIT: Addendum
You asked about the factorization of $f(X)=X^3-17$ modulo $3$ and why that didn't tell the splitting of $(3)$ in $\Bbb Q(w)$, where $\text{Irr}(w,\Bbb Q[X])=X^3-17=f(X)$. The theorem should read that the splitting of the irreducible modulo $p$ tells the splitting of $(p)$ only when the root $r$ generates the integers of $\Bbb Q(r)$ over $\Bbb Z$. And of course $r=w$ doesn't do that.


text:
Q: Tengo una variable con dos valores, como los sumo? Mi consulta es la siguiente, tengo una variable:
var tdElem = document.getElementById(product-${j + 1}-subtotal).innerText;

Que obtiene los valores almacenados en un td, dichos valores se obtienen desde un bucle. Tengo que imprimir en pantalla lo que seria un subtotal
sub.innerHTML +=  $ ${(tdElem)}

Entonces tengo que sumar esos dos valores, (los valores que me retorna son: 200 y 500000, o se que tendría que imprimir en pantalla 500200) ya extraje solo los números con lo siguiente:
tdElem = tdElem.replace(/\D/g,'');

El tema es que están contenidos en una misma variable y no se como sumarlos. No se si me explico, les dejo el código JavaScript.
for (let j = 0; j < carrito.articles.length; j++) {
  let cart = carrito.articles[j];

  let disminuirBtn = document.getElementById(`disminuir-${j + 1}`);
  let aumentarBtn = document.getElementById(`aumentar-${j + 1}`);
  let cantidad = document.getElementById(`cantidad-${j + 1}`);
  let subtotal = document.getElementById(`product-${j + 1}-subtotal`);
  let del = document.getElementById(`product-${j + 1}`)
  let trash = document.getElementById(`delete-${j + 1}`);
  trash.addEventListener("click", () => {
    del.innerHTML = "";
  })

  // Se llama a la funcion para que cargue los costos que ya vienen en el json.
  actualizarSubtotal(subtotal, cart.unitCost, cantidad.value, cart.currency);
  sub = document.getElementById("subtotal");
  var tdElem = document.getElementById(`product-${j + 1}-subtotal`).innerText;
  console.log(tdElem);
  tdElem = tdElem.replace(/\D/g,'');
  sub.innerHTML += `<td class="subtotal" id="subtotal"> $ ${(tdElem)} </td>`

  // Se le pasan los paramentros que consisten en cantidad (input), costo por unidad, elemento subtotal y la moneda.
  disminuirBtn.addEventListener('click', () => disminuir(cantidad, cart.unitCost, subtotal, cart.currency));
  aumentarBtn.addEventListener('click', () => aumentar(cantidad, cart.unitCost, subtotal, cart.currency));
}
})

A: Agrego ejemplo donde se suman los valores de la columna y se coloca al final el total. Basado en la estructura de la tabla de ejemplo.

function actualizarSubTotales() {
  // actualizar los subtotales
  for (i = 1; i <= 2; i++) {
    document.getElementById(`a${i}`).innerHTML = `${Math.round(
      Math.random() * 1000,
      0
    )}`;
  }

  // luego de actualizar llamar la función sumar
  // para actualizar el total
  sumar();
}

function sumar() {
  let total = 0;

  // recorrer todos los td
  for (i = 1; i <= 2; i++) {
    let tdElem = document.getElementById(`a${i}`).innerHTML;
    // dejar solo los digitos y multiplicar por 1 para convertirlo
    // en tipo number
    tdElem = tdElem.replace(/\D/g, "") * 1;

    total += tdElem;

    // agregar nuevo subtotal
    document.getElementById(`subtotal`).innerHTML = `$${total}`;
  }
}
// suma inicial
sumar();
<button onclick="actualizarSubTotales()">Actualizar sub totales</button>

      $200

      $500000

      0


text:
Q: Accept boolean and String Type in Netbeans I am a little stumped at the moment. How do I write a method in a sub-class which overrides an abstract method and accepts only String and boolean values?

A: All derived abstract Methods must have the same signature. Meaning the name and number of parameters as the method declared in superclass. So if your abstract class have String and boolean prameters you can do that by coping the signature in your subclass and adding your own definition.
Here is an example:
public void myMethod(String myString, Boolean b)

If you want to have different signature, then it doesn't make sense to extend the abstract class.
Also checkout this tutorial about abstract classes and methods in Java
http://beginnersbook.com/2013/05/java-abstract-class-method/


text:
Q: Formula to dynamically create column of values, excluding some by criteria Say I have a column with these values on Sheet1:
IDs
1
2
3
4
5
6

Then a column with these values on Sheet2:
Used IDs
2
3
6

Is there a clever way I can write a formula on Sheet3 that shows only the IDs that are visible on Sheet1 but NOT on sheet2?  Like this:
Unused IDs
1
4
5

I need something that would update dynamically as move values are added to the
Used IDs' column on Sheet2.  I can make something work that simply omits the used IDs (retaining their rows as NULL), like this:
Unused IDs
1

4
5

However, I need something without the blank rows.

A: put this in A1 in Sheet3 and copy down till blanks:
  =IFERROR(INDEX(Sheet1!A:A,AGGREGATE(15,6,ROW(Sheet1!$A$1:$A$6)/(NOT(ISNUMBER(MATCH(Sheet1!$A$1:$A$6,Sheet2!A:A,0)))),ROW(1:1))),"")


text:
Q: Error creating new migration in Entity Framework We've got an odd issue that I'm hoping someone can explain. We are using EF migrations (4.3.1) and when we run an update-database and it returns that there are no pending migrations however if we then make some changes and run an add-migration it says it can't create it as there The model backing the 'XXXDatabaseContext' context has changed since the database was created.
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending explicit migrations.
PM> add-migration Foo
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The model backing the 'EntityFrameworkDatabaseContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
   at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)

However setting the initializer to null sorts it
static MyDbContext() {
    Database.SetInitializer<MyDbContext>(null);
}

Can anyone explain what's going on?


text:
Q: How to read value with get readable and insert into another table with set writeable in the same function I need to read value with get readable and insert into another table with set writeable in the same function.
public void Check(String msg){

    //getdata from database
    String query="SELECT "+ CUL_ID +" FROM  " + STUDENT_TABLE + " WHERE "+ CUL_QRCODE +" like "+ msg +" ";
    SQLiteDatabase db1=this.getReadableDatabase();
    db1.execSQL(query);
    db1.close();
// I need to return this query in string variable value and put it into the queryString

    String value = "";
    String queryString ="INSERT INTO " + TABLE_PRESENCE_TABLE + " VALUES (" + value + " ,( SELECT count( "+CUL_ID_PRESENCE+" ) FROM  " + TABLE_PRESENCE_TABLE + " WHERE "+ CUL_ID_PRESENCE+ " = ( SELECT "+ CUL_ID +" FROM "+ STUDENT_TABLE +" WHERE "+ CUL_QRCODE + " = "+ msg +"))+"+1+" , datetime('now'));";
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(queryString);
    db.close();

}

A:
I need to read value with get readable and insert into another table with set writeable in the same function.

You don't need to. As much as you have used/coded a subquery for the 2nd column as per :-
( SELECT count( "+CUL_ID_PRESENCE+" ) FROM  " + TABLE_PRESENCE_TABLE + " WHERE "+ CUL_ID_PRESENCE+ " = ( SELECT "+ CUL_ID +" FROM "+ STUDENT_TABLE +" WHERE "+ CUL_QRCODE + " = "+ msg +"))+"+1+"

You can code a subquery for the 1st value i.e. replace value with the query that obtained the value.
e.g. you could have a single insert without the preceding query, along the lines of :-
INSERT INTO presence VALUES
    (
        coalesce((SELECT cul_id FROM student WHERE cul_qrcode = 'message'),-99),
        (SELECT count(cul_id_presence) FROM  presence WHERE CUL_ID_PRESENCE = (SELECT CUL_ID FROM STUDENT WHERE CUL_QRCODE = 'message')+1),
        datetime('now')
    )
;

*

*note that the coalesce function will convert a NULL (if there is no cul_qrcode LIKE msg) to another value (-99 in the case of the above).

*table and column names have been guessed so they may not match what you actually have.

*Otherwise to actually receive the result of the query you capture the result in a Cursor BUT you do not use execSQL, you use rawQuery or the query convenience method.

*

execSQL  Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

How can i Receive the value of getReadableDatabase() in variable string that's it

To use the query followed by the insert you would have something like :-
Cursor csr = db1.rawQuery(query,null);
String value = "-99"; /* assume that if nothing is returned then use -99 */
if(csr.moveToFirst) {
    value = csr.getString(0);
}
csr.close(); /* SHOULD ALWAYS CLOSE CURSORS WHEN FINISHED WITH THEM */

However, it is BAD practice to concatenate parameters to SQL as this is considered a potential for SQL injection. Instead you should bind parameters (which will over come a MAJOR flaw as you appear to probably NOT be enclosing the msg in single quotes, binding a parameter will enclose the parameter in single quotes). So the above should be :-
public void Check(String msg){

    //getdata from database
    String query="SELECT "+ CUL_ID +" FROM  " + STUDENT_TABLE + " WHERE "+ CUL_QRCODE +" like ?"; //<<<<< use ? to allow bind of msg
    SQLiteDatabase db1=this.getReadableDatabase();
    Cursor csr = db1.rawQuery(query,new String[]{msg});
    String value = "-99"; /* assume that if nothing is returned then use -99 */
    if(csr.moveToFirst) {
        value = csr.getString(0);
    }
    csr.close(); /* SHOULD ALWAYS CLOSE CURSORS WHEN FINISHED WITH THEM */
    ....

Furthermore
There is no need to close the database and and then reopen it to apparently switch between readable and writable. That is getReadableDatabase will if it's possible return a writeable database except if there is some reason why the database cannot be opened as writable. If a read only database is returned then the subsequent getWritableDatabase would very likely fail unless somehow the underlying issue is fixed.
as per:-

Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call to getWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.

*

*https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper#getReadableDatabase()


text:
Q: How to create a time series dataframe from a 1D numpy array I have the following numpy array S ( actual array is bigger) :
 S = np.array([200,210,230, 250, 270, 290, 300, 350,400])

with sample interval of 40 µs, i want to create the following dataframe where i have a time ( in seconds) column and value column as below:
 time    value
 0        200
 0.00004  210
 0.00008  230
 0.00012  250
 0.00016  270
 0.00020  290
 0.00024  300
    .
    .
    .

A: Create yout time vector (with numpy.arange for example), then use it as the time column of your pandas DataFrame.
import pandas as pd
import numpy as np

S = np.array([200,210,230, 250, 270, 290, 300, 350,400])

dt = 0.00004

d = {
    'time' : np.arange(0, len(S)*dt, dt),
    'value' : S
}

print(pd.DataFrame(d))

output
      time  value
0  0.00000    200
1  0.00004    210
2  0.00008    230
3  0.00012    250
4  0.00016    270
5  0.00020    290
6  0.00024    300
7  0.00028    350
8  0.00032    400

Personally, I really like to use the Dataframe() constructor that takes a dictionary as argument. It is clean and clear.


text:
Q: Get-AzDataFactoryV2Pipeline : Unable to deserialize the response I am trying to fetch the Data Factory Pipeline Information with the help of following simple command:
Get-AzDataFactoryV2Pipeline -ResourceGroupName $resourceGroupName -DataFactoryName $dataFactoryName

However, I am getting this Error. I have also update my Az.Data Factory module to the latest one.
Get-AzDataFactoryV2Pipeline : Unable to deserialize the response.
At line:1 char:1
+ Get-AzDataFactoryV2Pipeline -ResourceGroupName $resourceGroupName -Da ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzDataFactoryV2Pipeline], SerializationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.DataFactoryV2.GetAzureDataFactoryPipelineCommand

Please give your valuable suggestions to fix this ?

A: This command works for me with the Az.DataFactory 1.11.0, please open a new powershell session to try again.


text:
Q: When does $x^{x^{x^{...}}}$ converge? Provided that $x$ is positive, when does the following converge? $$x^{x^{x^{x^{...}}}}$$

 I just had a talk with my friend who is taking a calculus class and he is dealing a lot with divergence and convergence stuff. His TA said that if anyone could answer this and write a proof, he or she doesn't have to come to the recitation class anymore. This drives me a lot.

So here is my work, but I don't really know if this is correct. Could anyone shed some light on this?

I haven't done any real analysis before so I'm trying to make use of
  whatever I can use, and my plan is to find the critical points of $y'$
  and look at the graph of $y=f(x)$. First let
  $f(x)=x^{x^{x^{x^{...}}}}=y=x^y$, then I have $$ \ln{y}=y\ln{x} $$ $$
 \frac{d(\frac{\ln{y}}{y})}{dx} = \frac{d\ln{x}}{dx} $$ $$
 \frac{1-\ln{y}}{y^2} \frac{dy}{dx} = \frac{1}{x}$$ $$ y'=
 \frac{f^2(x)}{x(1-\ln{f(x)})} $$ Now I noticed that the critical
  points are $x=0$ and $f(x)=0$ or $f(x)=e$. Since
  $f(x)=x^{x^{x^{x^{...}}}}$ is an increasing function, the graph of
  $y=f(x)$ would go up vertically at some point as $x$ increases, and that
  is when the function diverges. From these 3 critical points, $f(x)=e$
  seems to make most sense. By plugging $f(x)=e$ back into $y=x^y$, it's
  not hard to see that $f(x)=e$ occurs at $x=e^{\frac{1}{e}}$. So the
  function converges when $x\in (0, e^{\frac{1}{e}})$

Edit: I just noticed something strange in my proof:
$$ y'= \frac{f^2(x)}{x(1-\ln{f(x)})} $$
When $f(x)>e$, the denominator on the right hand side is negative. But since $f(x)$ is an increasing function, therefore, shouldn't $y'$ be positive? Now it seems to deep for me to perceive...


text:
Q: Horizontalscrollview initial offset value How to set HorizontalScrollView's initial offset value? I used smoothScrolTo() but it is not working.
Please help.

A: You can not call smoothScrolTo() during onCreate, onStart or onResume. try to give a small delay like this:
public void onResume() {
    super.onResume();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            HorizontalScrollView sv = (HorizontalScrollView)findViewById(R.id.ScrollView01);
            sv.smoothScrollTo(1000, 0);
        }
    }, 100);
}

This works for me, but dose anyone know a better time(e.g. in a listener) for calling smoothScrollTo?

A: Another way to solve this is via xml.
The trick is add "Spaces views" as childs of the HorizontalScrollView and set the width of them to the offset you want to have.
Example:
<!--BUTTONS ON HORIZONAL SCROLL -->
    <HorizontalScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/scroll_view_child_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <!-- This View does the trick! -->
            <Space
                android:layout_width="16dp"
                android:layout_height="match_parent" />

            <Button
                android:id="@+id/btn_1"
                style="@style/HorizontalScrollButtons"
                android:text="Btn1" />

            <Button
                android:id="@+id/btn_2"
                style="@style/HorizontalScrollButtons"
                android:text="Btn1" />

            <!-- Keep adding buttons... -->

            <!-- This View does the trick too! -->
            <Space
                android:layout_width="16dp"
                android:layout_height="match_parent" />

        </LinearLayout>

    </HorizontalScrollView>

In the example I want a 16dp "margin" so I give the Space View a width of 16dp.
It will give this...

...instead of this...

...as starting view.

A: Use View.getViewTreeObserver.addOnGlobalLayoutListener to add listener for knowing when scrollview is laid. In the callback you can set scroll.
Use removeGlobalOnLayoutListener(this) in the callback to unregister for further events.
scroll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
   @Override
   public void onGlobalLayout(){
      scroll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
      scroll.scrollTo(x, y);
   }
});


text:
Q: How to style the items inside a ComboBox in JavaFX Is it possible to change the color of the items inside a ComboBox in JavaFX?
I want to change the background color of each item to black and its text to white, and to green and white when hovering.
@FXML
private ComboBox<String> govs;

public void initialize() {
    ObservableList<String> options = FXCollections.observableArrayList(
         "Ariana",
         "Beja",
         "Ben Arous",
         "Bizerte",
         "Gabès"
    );
    govs.setItems(options);
}

A: Since this cannot be done by applying CSS rules to the node, you have to supply your own cell factory implementation to the combobox.
comboBox.setCellFactory(param -> new ComboBoxListCell<String>() {{
    setTextFill(Color.WHITE);

    Background blackBackground = new Background(new BackgroundFill(Color.BLACK, null, null));
    Background greenBackground = new Background(new BackgroundFill(Color.GREEN, null, null));

    setBackground(blackBackground);
    setOnMouseEntered(event -> {
        setBackground(greenBackground);
    });
    setOnMouseExited(event -> {
        setBackground(blackBackground);
    });
}});


text:
Q: Getting OSM maps in Equirectangular Projection via osm2pgsql I'm trying to import some OSM data into psql as equirectangular projection using osm2pgsql with the following command:
osm2pgsql -c -d osm -S /usr/local/share/osm2pgsql/default.style -l /OPENSTREETMAP/south-america-latest.osm.pbf

However, it fails with this error:
Projection code failed to initialise

I have installed the latest version of the PROJ framework from here.
What am I doing wrong?
EDIT 1:
Running 'select * from spatial_ref_sys where srid=4326;' on the database produces this:
 srid | auth_name | auth_srid |                                                                                srtext                                                                                |              proj4text
------+-----------+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------
 4326 | EPSG      |      4326 | GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]] | +proj=longlat +datum=WGS84 +no_defs
(1 row)

A: Make sure that your version of osm2pgsql is built for the version of postgis you have.
There were some major changes in postgis 2.0.
It might help to run the legacy.sql to add the old functions again, see
https://postgis.net/docs/PostGIS_FAQ.html#legacy_faq

EDIT
Second choice:
https://help.openstreetmap.org/questions/16175/nominatim-installation-problem-projection-code-failed
https://www.mail-archive.com/dev@openstreetmap.org/msg09334.html
comes with the same error, because the proj lib can not be found. This was a Windows system, but make sure osm2pgsql can find the proj lib.

A: AFAIK the most OSM tools rely on a 4326 projection, so it's not a wise idea to change the DB schema to a different one. Instead you could write a small wrapper or use e.g. Geoserver to reproject the geometries per request.


text:
Q: Including two Ruby mixins with the same method name What's going on with this:
module Sounds
  def dog
    "bark"
  end
end

module Noises
  def dog
    "woof"
  end
end

class Animals
  include Sounds
  include Noises
end

x = Animals.new
x.dog # Returns "woof", as I expected

class Animals
  include Sounds
end

x.dog # Still returns "woof" for some reason -- shouldn't it be bark?

y = Animals.new
y.dog # Also returns "woof" for some reason -- shouldn't it be bark?

A: Once you've included a module, I'm not sure it will be included again. It will probably be listed as already included so the duplicate operation is ignored.
If you need to do this, which would be very strange indeed, you probably need to fake out Ruby by making a module, even a temporary one, that includes your target module, then include that one instead.


text:
Q: Ng-include doesn't work I have simple angular.js application. Also i have index.html as a front page of my web application, now i want to create footer.html and include it with ng-include directive to my index.html.
I have root controller:
function RootController ($scope) {
    $scope.templates = [{name : 'footer.html', url : 'views/footer.html'}];

    $scope.getFooter = function(){
        return $scope.templates[0];
    }
}

And my index.html template:

  ....

footer.html has a simple html:
Test Test Test

But when i open index.html i don't see footer. Why? How can include it correctly?
UPD
Problem solved. Maybe someone be useful my solution:
It works with:

Thank you.

A: Use either
ng-include="getFooter().url"

or
return $scope.templates[0].url;


text:
Q: How to get LastPass to detect angularjs material inputs after page change I have a login page for my angularjs site and I'm using the angularjs material library's inputs.
On first page load LastPass detects the email and password inputs and auto fills them. The problem is if I leave the page and navigate back to the login page (without a full browser refresh), LastPass won't detect the inputs.
My mark up is as follows:
<form class="inputs-form" name="login" layout="column">

Sign In

{{errorMessage}}

                <md-input-container flex="100" class="signin-input-container">
                    Email
                    <input class="username" ng-model="email" type="text" />
                </md-input-container>

                <md-input-container flex="100" class="signin-input-container">
                    Password
                    <input class="password" ng-model="password" type="password" />
                </md-input-container>

            <button ng-click='login()' class='t3Btn_primary'>Sign In</button>

</form>

I've tried setting the id, name and class of the inputs to password and username like I've seen others suggest in other questions but that doesn't work in this case.
It would be great if someone knew how I could get LastPass to detect the inputs everytime the page is rendered and not just when a full browser refresh occurs.
Thanks.


text:
Q: Variable value not showing in Win Batch I am writing a batch to automate the installation of a a number of settings, INI files and APKs on a multitude of devices. I am getting errors in the batch due to the variables in showing NULL.
I have checked that the config.ini and ADBCommands.ini and adb+.bat are in the correct location.
Can you help?
::Global
@echo off
cd C:\

::INI Locations
set mypath=%~dp0
set config=%mypath%config.ini
set Commands=%mypath%ADBCommands.ini
set multi=%mypath%adb+.bat
@pause

::Set Varialbes
@for /f "tokens=1,2 delims==" %%a in (%config%) do (
if %%a==Build set Build=%%b
if %%a==Version set Version=%%b
if %%a==Creator set Creator=%%b
if %%a==DateModified set DateModified=%%b
if %%a==ScreenTimeout set ScreenTimeout=%%b
if %%a==UnknownSources set UnknownSources=%%b
if %%a==ScreenBrightness set ScreenBrightness=%%b
)

@for /f "tokens=1,2 delims==" %%d in (%Commands%) do (
if %%d==ScreenTimeoutCommand set ScreenTimeoutCommand=%%e
if %%d==UnknownSourcesCommand set UnknownSourcesCommand=%%e
if %%d==ScreenBrightnessCommand set ScreenBrightnessCommand=%%e
if %%d==OpenSOTICommand set OpenSOTICommand=%%e
)

::Build information
cls
@echo.
@echo.
@echo      BUILD:              %Build%
@echo      VERSION:            %Version%
@echo      BUILD CREATOR:      %Creator%
@echo      LAST UPDATED:       %DateModified%
@echo.
@echo.
@pause

Contents the ini files
config.ini
Build=XCover 3
Version=1.0.0
Creator=James B
DateModified=20/02/2017
ScreenTimeout=300000
UnknownSources=1
ScreenBrightness=225

Contents the ini files
ADBCommands.ini
ScreenTimeoutCommand=shell settings put system screen_off_timeout
UnknownSourcesCommand=shell settings put system install_non_market_apps
OpenSOTICommand=shell am start -n net.soti.mobicontrol.elm.samsung/net.soti.mobicontrol.startup.SplashActivity

A: Because your path has spaces you need to enclose the path with quotes. But when you do this, you need to tell the FOR /F command that you are still parsing a file and not a variable.  So you need to use the USEBACKQ option.
@for /f "usebackq tokens=1,2 delims==" %%a in ("%config%") do (

AND
@for /f "usebackq tokens=1,2 delims==" %%d in ("%Commands%") do (


text:
Q: Removing land based cells from sea surface temperature grid by using shoreline shapefile? I am a second year Geo student.
I was tasked with creating a sea surface temperature grid from a colour profile, which I have completed, but I am required to drop the land based cells through the use of a shoreline shapefile.
I have dissolved the shoreline (which I am hoping is the right move), but can't seem to find a way to move forward.


text:
Q: How to open a 2017 Cordova project in Visual Studio 2019 I have a Visual Studio project written using Visual Studio 2017 Tools for Apache Cordova, and I am unable to open it in Visual Studio 2019 (Message: incompatible) and there is no available Cordova project types. What's the best way to be able to open/edit/redeploy a Tools for Apache Cordova project?

A: You can't open it from visual 2019, because Microsoft stop supporting Cordova.
The best way is to install visual 2017 for Apache Cordova projects only (to be lite in usage) and install latest version of Cordova globally.


text:
Q: UIView Subview Does not autoresize on orientation change In my iPhone app, I have a view controller with two views (essentially, a front & back view). The front view is the main UIView, and the back view is a secondary UIView which is added as a subview using [self.view addSubview:backView] when showing the back and [backView removeFromSuperview] when hiding it. However, when the orientation changes, I have the following issue: the main UIView (frontView) rotates & all of its elements resize properly, but the secondary/subview UIView (backView) does not rotate & all of its elements do not resize properly. Does anyone have suggestions on how to make the secondary UIView autoresize properly according to the rules I have set in Interface Builder?

A: In the end, the solution I found was simply to separate my UIViews into separate UIViewControllers, and make sure that any views that I wanted to be able to rotate only had one UIView.

A: If I understand correctly, at the time of rotation 'backView' has been removed from it's superview, yeah?  If so, that's the cause of the problem.  The autoresize property determines how the view resizes relative to it's superview.  If it doesn't have a superview it won't resize.
Perhaps using [backView setHidden:YES] instead of [backView removeFromSuperview] will be sufficient for your needs.

A: I had the same problem, here is how I fixed it based on imaginaryboy's
suggestions (thanks!)
Add the backview to the viewcontroller at viewDidLoad and hide it at the same time. Show it when needed, Hide it again. Set the resizing of the backview to UIViewAutoresizingFlexibleWidth in IB (or code I guess, I used IB)

A: Not that this is the same problem, but I found a similar problem when adding 2 subviews in my application:didFinishLaunchingWithOptions method.  Since your reference above is using [self.view addSubview:view], I would understand that to mean that self is not your UIWindow.  When adding an additional view controller to your App Delegate window (UIWindow), the second view controller will NOT receive any rotation events and will never rotate.  Only the first view controller added to UIWindow will rotate.  See:Technical Q&A QA1688  I believe this also affects views added after the first view where the first view is later removed from the superview.
I ended up following the suggestion I read elsewhere to use separate views for each orientation, thereby eliminating the need to worry about resizing behavior.  As always, YMMV.

A: Or; if you want to avoid an additional controller, you can achieve the same effect by setting view.frame in willRotateToInterfaceOrientation:: like so
    if(UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) ;//set stubborn view.frame for landscape orientation

    else ; //set stubborn view.frame for portrait orientation

Although it feels like a hack; it's simple.


text:
Q: How to move a number of columns in a matrix to the right most in matlab Suppose I have an mxn matrix A. Suppose I have a list (or a vector) P of i elements where each element of P indicates the number of a column in A. I need to move all the columns indicated by P to the right most of A; for instance the the columns indicated in the first and the i'th elements in P will become the (n-i)'th and the n'th column of A respectively.
Hope my statement is clear, let me know if there is any ambiguity.
thanks.

A: To get the columns 3,5,7 to the right, first c is constructed which indicates the new order of columns. Then the columns are indexed using c which reorders them.
>> M=magic(10);
>> c=[3,5,7];
>> c=[setdiff(1:size(M,2),c),c]

c =

  Columns 1 through 9

     1     2     4     6     8     9    10     3     5

  Column 10

     7

>> M=M(:,c);


text:
Q: Oracle SQL: loop count overlaps between values in the the same column I have a table which look like the one below:
Form_ID   Values
1            a
1            b
1            c
1            d
2            a
2            d
2            e
3            d
3            e
3            f

I have more than 200 forms and 10,000+ values from these forms. So I want to do a loop using SQL to count overlapped distinct value between each form. For example, the distinct count between form1 and form2 is 2. The result table should look like:
Form1    Form2   Overlap_Count
1         2           2
2         3           2

Thanks!
Sophia

A: You can do this with a self-join and aggregation:
select t1.id, t2.id, count(*) as NumOverlaps
from t t1 join
     t t2
     on t1.id < t2.id and t1.value = t2.value
group by t1.id, t2.id;

A: try this:
Select t1.form_Id form1, t2.Form_Id form2,
       count(*) overLAPS
From table t1
   join table t2
      on t2.Form_ID > t1.form_Id
         and t2.[Values] = t1.[Values]
group by t1.form_Id, t2.Form_Id


text:
Q: Microsoft Edge Configuration Export Is there a way to export all the Microsoft Edge configuration to a file? Registry tree? Folder?
One thing that annoys me is the lost of Edge's configuration. I like some particular configuration I've done. Every time there is an update o Edge, it resets the whole configuration and I have to reconfigure it all again.
Thanks.

A: Have you considered configuring a local or domain GPO for Edge and leaving that for persistence or exporting for future use?
Available policies for Microsoft Edge
Alternatively, if you're looking for the setup for the Favorites and Favorites bar, these can be exported by HTML or via LocalAppData: see here


text:
Q: Beaglebone Black update IP Address and subnet for USB0 I'm looking for some guidance regarding updating the IP address for the BBB.  I have a BBB that I need to place remotely on my network. It's a custom BBB with no connections on it what so ever, other than the USB port. It has neither the Ethernet port or Wifi. The board boots via the emmc, not the sdcard. So I'm looking to find a way to use a USB-Ethernet adapter and connect it to the USB port.
So I need to update the IP address from 192.168.6.2, but more importantly I need to update the subnet so I'll be able to access it on my network.
It's obvious that I can update the information in the interfaces file, I've done this before with a Raspberry Pi. However what I'm concerned that if I go about making changes it's going to disable access completely and that's a risk I don't want to take. I just ordered a new board. I'll do some experimenting with the SD card, so I'll avoid bricking issues.
However, I was hoping to gain some insight as to what steps I should take. I've read that there are init scripts running at boot that setup and configure the USB0 as well.
Does anyone have any insight as to what steps I should take?
Michael


text:
Q: .htaccess - Add prefix string to beginning of URLs I'm migrating a website over to a new server and on the old server the website existed in the document root (/var/www/html/). The new server will contain multiple websites and so I put it in it's own directory (/var/www/html/dev.newsite.com).
The problem is that all of the links on the website were built based on the old document root. I'd like to not have to change the document root in the httpd.conf file. How can I prepend 'dev.newsite.com' to the beginning of all the URLs on my site using the .htaccess file? Thank you!


text:
Q: ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None Hello this is my code for Implementing CNN with Keras backend with tensor flow, for classifying image
I don't know what part i am doing wrong.
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

img_width, img_height = 224, 224

train_data_dir = '/Users/CK/data/train'
validation_data_dir = '/Users/CK/data/validation'

nb_train_samples = 47000
nb_validation_samples = 47000
epochs = 50
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(12,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(12,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='categorical_crossentropy', optimizer = 'adam', metrics=['accuracy'])

train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True
        )

test_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(train_data_dir, target_size = (img_width, img_height),
                                                    batch_size=batch_size, class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(validation_data_dir,target_size=(img_width, img_height),
                                                        batch_size=batch_size, class_mode='categorical')

model.fit_generator(train_generator,
                    steps_per_epoch=nb_train_samples// batch_size, epochs=epochs,
                    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

But then I got an error
runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')
Found 46827 images belonging to 9 classes.
Found 46827 images belonging to 9 classes.
Epoch 1/50
Exception in thread Thread-7:
Traceback (most recent call last):
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 612, in data_generator_task
    generator_output = next(self._generator)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 727, in __next__
    return self.next(*args, **kwargs)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 960, in next
    target_size=self.target_size)
  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/preprocessing/image.py", line 318, in load_img
    raise ImportError('Could not import PIL.Image. '
ImportError: Could not import PIL.Image. The use of `array_to_img` requires PIL.

Traceback (most recent call last):

  File "<ipython-input-13-15de1a62b9cf>", line 1, in <module>
    runfile('/Users/CK/Desktop/test.py', wdir='/Users/CK/Desktop')

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/CK/Desktop/test.py", line 66, in <module>
    validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/models.py", line 1110, in fit_generator
    initial_epoch=initial_epoch)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)

  File "/Users/CK/anaconda/envs/tensorflow/lib/python3.5/site-packages/keras/engine/training.py", line 1865, in fit_generator
    str(generator_output))

ValueError: output of generator should be a tuple `(x, y, sample_weight)` or `(x, y)`. Found: None

How do i fix problem? I appreciate if you guys help to fix the code with details. thx

A: There are two errors here

*

*ImportError for PIL

*ValueError
and I think your second one is depended on the first. Why?
because the image data got corrupted as it might be none because of the absence of required library and making validation with this data might be causing the generator to return weird values.
To resolve first you will need to install PIL by the following command
  # sudo does not require if you are using virtualenv
  $ sudo pip install Pillow

Hopefully, your second issue will also get resolved.

A: You must make file into train_data_dir,validation_data_dir and next you must carry images into this file.


text:
Q: After scoped `no autodie` the program dies at `*STDOUT` This program
use warnings;
use strict;
use feature qw(say);

{
    #use autodie;   # all good when this is uncommented
    no autodie;
}

open my $OLDSTD, '>&', *STDOUT;        #--> line 10 (program fails)
open *STDOUT, '>', 'stdout.out';

say "$$ done";

aborts with

Undefined subroutine called at problem_no_autodie.pl line 10.

To restate the comment in code: if there is a use autodie; statement first then all is well. (All is well with only use autodie; as well.) Curiously, in the same scope with no autodie statement I see no such problems either; only code outside of its scope fails! Kinda anti-scoping, eh?
If this scoped no autodie comes after the use of *STDOUT then it's all good again. Further use of *STDOUT, after (the scoped) no autodie, fails the program.
There is a Gotcha mentioned in docs that involves barewords (which I don't fully understand), and the program indeed fails with STDOUT -- but I have it as *STDOUT.
So it appears that *STDOUT is treated as a user's sub, but I don't understand that nor how the scope of autodie gets defeated.  (Scope leakage is mentioned as a bug in some versions but in a seemingly unrelated way.)  And there is a practical problem with this.
I don't use autodie in my code. But consider this sub, which I do use
sub isatty {
    no autodie;
    state $isatty = open(my $tty, '+<', '/dev/tty');
    return $isatty;
}

It is legitimate for that open to fail, so we have to disable autodie in that scope in case the user of the sub has it on. Then is the described behavior going to hurt? Under what circumstances?
I am puzzled by this effect of no autodie and by its leakage out of its scope, and by all their strange details. But the real concern is that I am not sure how to protect the code that uses a library like the one above against that behavior, since I don't understand it. Any ideas?
I see this under 5.16.3 (system), 5.26.2 and 5.30.0 (perlbrew) on CentOS 7.8
I do not see this behavior on 5.32.0; no failure there.

The ... or die $! check with open didn't make any difference so it's not shown for simplicity.

A: This bug was introduced in autodie 2.24 and fixed in autodie 2.30.
$ ( cd ./autodie-2.23; perl Makefile.PL >&3; make >&3; perl -Mblib ../a.pl && echo ok ) 3>/dev/null
ok

$ ( cd ./autodie-2.24; perl Makefile.PL >&3; make >&3; perl -Mblib ../a.pl && echo ok ) 3>/dev/null
Undefined subroutine called at ../a.pl line 10.

$ ( cd ./autodie-2.29; perl Makefile.PL >&3; make >&3; perl -Mblib ../a.pl && echo ok ) 3>/dev/null
Undefined subroutine called at ../a.pl line 10.

$ ( cd ./autodie-2.30; perl Makefile.PL >&3; make >&3; perl -Mblib ../a.pl && echo ok ) 3>/dev/null
ok

$ ( cd ./autodie-2.31; perl Makefile.PL >&3; make >&3; perl -Mblib ../a.pl && echo ok ) 3>/dev/null
ok

(2.30 is not found on CPAN.)
To protect against this issue, add a dependency on autodie 2.30 or higher.


text:
Q: Decorator that prints function call details (argument names and values)? I want to make a function that being a decorator to another function will print that function call details - parameters names and effective values. My current implementation is this.
def describeFuncCall(func):
    """
    Decorator to print function call details.

    parameters names and effective values.
    """

    def wrapper(*func_args, **func_kwargs):
        print "func_code.co_varnames =", func.func_code.co_varnames
        print "func_code.co_argcount =", func.func_code.co_argcount
        print "func_args =", func_args
        print "func_kwargs =", func_kwargs
        params = []
        for argNo in range(func.func_code.co_argcount):
            argName = func.func_code.co_varnames[argNo]
            argValue = (
                func_args[argNo]
                if argNo < len(func_args)
                else func.func_defaults[argNo - func.func_code.co_argcount]
            )
            params.append((argName, argValue))
        for argName, argValue in func_kwargs.items():
            params.append((argName, argValue))
        params = [argName + " = " + repr(argValue)
                  for argName, argValue in params]
        print (func.__name__ + " ( " + ", ".join(params) + " )")
        return func(*func_args, **func_kwargs)

    return wrapper

@describeFuncCall
def test(a, b=4, c="blah-blah", *args, **kwargs):
    pass

test(1)
# test(1, 3)
# test(1, d = 5)
test(1, 2, 3, 4, 5, d=6, g=12.9)

Kinda works, but with some bugs:
For call
test(1, 2, 3, 4, 5, d = 6, g = 12.9)
it prints
test ( a = 1, b = 2, c = 3, d = 6, g = 12.9 ).
The expected result is
test ( a = 1, b = 2, c = 3, args = [4, 5], kwargs = {'d': 6, 'g': 12.9} )
I got stuck here. Can you help me to find the right solution?

A: Here's how I solved it in Python 3, based on aliteralmind's answer, put more cleanly (PEP8) if I may say so.
Majority of the inspiration for the cleanup came from the (currently) accepted answer by Robert King.
Code (test.py):
#!/usr/bin/env python3

import functools
import inspect
import logging
import time

class CustomFormatter(logging.Formatter):
    """
    Custom formatter, overrides funcName with value of name_override if it exists

    Inspired by; https://stackoverflow.com/a/7004565/1503549
    """
    def format(self, record):
        if hasattr(record, 'func_name'):
            record.funcName = record.func_name
        return super(CustomFormatter, self).format(record)

def log_function_entry_and_exit(decorated_function):
    """
    Function decorator logging entry + exit and parameters of functions.

    Entry and exit as logging.info, parameters as logging.DEBUG.
    """

    @functools.wraps(decorated_function)
    def wrapper(*dec_fn_args, **dec_fn_kwargs):
        # Log function entry
        func_name = decorated_function.__name__
        name_dict = dict(func_name=func_name)
        logging.info(f"Entering {func_name}()...", extra=name_dict)

        # Log function params (args and kwargs)
        func_args = inspect.signature(decorated_function).bind(*dec_fn_args, **dec_fn_kwargs).arguments
        func_args_str = ', '.join(
            f"{var_name} = {var_value}"
            for var_name, var_value
            in func_args.items()
        )
        logging.debug(f"\t{func_args_str}", extra=name_dict)

        # Execute wrapped (decorated) function:
        out = decorated_function(*dec_fn_args, **dec_fn_kwargs)

        time.sleep(1)   # Test to ensure timestamp is real
        logging.info(f"Done running {func_name}()!", extra=name_dict)

        return out
    return wrapper

@log_function_entry_and_exit
def func2(*args, **kwargs):
    print('\t\thello')

@log_function_entry_and_exit
def func1(a, b, c):
    func2(1, 2, 3, 4, b=5)
    print('Hello2!')

if __name__ == '__main__':
    log = logging.getLogger()

    # Must get handler to set format
    handler = logging.StreamHandler()   # Get default root logger
    handler.setFormatter(
        CustomFormatter(
            (
                '[%(asctime)s]'
                ' %(levelname)s:%(funcName)s():%(lineno)s>'
                ' %(message)s'
            ),
            datefmt='%Y-%m-%dT%H:%M:%S',
        )
    )

    # Set logLevel
    log.setLevel(logging.DEBUG)
    handler.setLevel(logging.DEBUG)

    # Combine the two again
    log.addHandler(handler)

    log.info('yolo!', extra=dict(func_name='__main__'))

    func1(2, b="y", c={'z': 4})

Output:
[2020-06-11 22:22:15] 0 x10an14@x10-desktop:~/Desktop/testy
-> $ python3 test.py
[2020-06-11T22:22:53] INFO:__main__():88> yolo!
[2020-06-11T22:22:53] INFO:func1():33> Entering func1()...
[2020-06-11T22:22:53] DEBUG:func1():42>     a = 2, b = y, c = {'z': 4}
[2020-06-11T22:22:53] INFO:func2():33> Entering func2()...
[2020-06-11T22:22:53] DEBUG:func2():42>     args = (1, 2, 3, 4), kwargs = {'b': 5}
        hello
[2020-06-11T22:22:54] INFO:func2():48> Done running func2()!
Hello2!
[2020-06-11T22:22:55] INFO:func1():48> Done running func1()!
[2020-06-11 22:22:55] 0 x10an14@x10-desktop:~/Desktop/testy
-> $

When I get the magical resources known as "time and energy", I'm interested in playing around with LOG_FORMAT, and figure out how I can replace the wrapper substring with say filename and line number of function invocation =)
EDIT(2020-06-11): Fixed wrapper issue after prompt from @Gahan's comment (dated 2020-06-10).
It seems to be impossible (ref. https://stackoverflow.com/a/8339710/1503549) to have a wrapper report (via the logging module) the line-number of the wrapped / decorated function. Maybe wrapt could be leveraged for this purpose?

A: @warvariuc's answer, upgraded to Python 3:
def dumpArgs(func):
    '''Decorator to print function call details - parameters names and effective values'''
    def wrapper(*func_args, **func_kwargs):
        arg_names = func.__code__.co_varnames[:func.__code__.co_argcount]
        args = func_args[:len(arg_names)]
        defaults = func.__defaults__ or ()
        args = args + defaults[len(defaults) - (func.__code__.co_argcount - len(args)):]
        params = list(zip(arg_names, args))
        args = func_args[len(arg_names):]
        if args: params.append(('args', args))
        if func_kwargs: params.append(('kwargs', func_kwargs))
        print(func.__name__ + ' (' + ', '.join('%s = %r' % p for p in params) + ' )')
        return func(*func_args, **func_kwargs)
    return wrapper

@dumpArgs
def test(a, b = 4, c = 'blah-blah', *args, **kwargs):
    pass

test(1)
test(1, 3)
test(1, d = 5)
test(1, 2, 3, 4, 5, d = 6, g = 12.9)

A: Here is the updated version for Python 3.6+
import inspect

def dump_args(func):
    """
    Decorator to print function call details.

    This includes parameters names and effective values.
    """

    def wrapper(*args, **kwargs):
        func_args = inspect.signature(func).bind(*args, **kwargs).arguments
        func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items()))
        print(f"{func.__module__}.{func.__qualname__} ( {func_args_str} )")
        return func(*args, **kwargs)

    return wrapper

@dump_args
def test(a, b=4, c="blah-blah", *args, **kwargs):
    pass

test(1)
test(1, 3)
test(1, d=5)
test(1, 2, 3, 4, 5, d=6, g=12.9)

Old version

Working version with default values:
def dumpArgs(func):
    '''Decorator to print function call details - parameters names and effective values'''
    def wrapper(*func_args, **func_kwargs):
        arg_names = func.func_code.co_varnames[:func.func_code.co_argcount]
        args = func_args[:len(arg_names)]
        defaults = func.func_defaults or ()
        args = args + defaults[len(defaults) - (func.func_code.co_argcount - len(args)):]
        params = zip(arg_names, args)
        args = func_args[len(arg_names):]
        if args: params.append(('args', args))
        if func_kwargs: params.append(('kwargs', func_kwargs))
        print func.func_name + ' (' + ', '.join('%s = %r' % p for p in params) + ' )'
        return func(*func_args, **func_kwargs)
    return wrapper

@dumpArgs
def test(a, b = 4, c = 'blah-blah', *args, **kwargs):
    pass

test(1)
test(1, 3)
test(1, d = 5)
test(1, 2, 3, 4, 5, d = 6, g = 12.9)

Result:
>>> test  (  a = 1, b = 4, c = 'blah-blah' )
test  (  a = 1, b = 3, c = 'blah-blah' )
test  (  a = 1, b = 4, c = 'blah-blah', kwargs = {'d': 5} )
test  (  a = 1, b = 2, c = 3, args = (4, 5), kwargs = {'d': 6, 'g': 12.9} )

A: Sorry its a bit messy. I modified some code from Easy Dump of Function Arguments in the PythonDecoratorLibrary.
def dump_args(func):
    "This decorator dumps out the arguments passed to a function before calling it"
    argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
    fname = func.func_name
    def echo_func(*args,**kwargs):
        print fname, "(", ', '.join(
            '%s=%r' % entry
            for entry in zip(argnames,args[:len(argnames)])+[("args",list(args[len(argnames):]))]+[("kwargs",kwargs)]) +")"
    return echo_func

@dump_args
def test(a, b = 4, c = 'blah-blah', *args, **kwargs):
    pass

test(1, 2, 3, 4, 5, d = 6, g = 12.9)

Output:
test ( a=1, b=2, c=3, args=[4, 5], kwargs={'d': 6, 'g': 12.9})

A: Here is a version that also works for native functions (python 3 only)
import logging
import inspect

def dump_args(func):
    """
    Decorator to print function call details.
    This includes parameters names and effective values.
    """
    def wrapper(*args, **kwargs):
        try:
            # For standard functions, inspect the signature
            signature = inspect.signature(func)
            func_args = signature.bind(*args, **kwargs).arguments
            func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items()))
            msg =  f"{func.__module__}.{func.__qualname__} ( {func_args_str} )"
        except ValueError:
            # For native functions, the signature cannot be inspected
            args_strs = map(lambda arg: f"arg_{arg[0]} = {arg[1]}", enumerate(args) )
            kwargs_strs = map(lambda kwarg: f"{kwarg[0]} = {kwarg[1]}", kwargs )
            func_args_str = ", ".join(list(args_strs) + list(kwargs_strs))
            msg =  f"{func.__module__}.{func.__name__} ( {func_args_str} )"
        logging.debug(msg)
        return func(*args, **kwargs)
    return wrapper

And I can activate it at module level like this:
__init__.py
_DEBUG_MY_MODULE = True

if _DEBUG_MY_MODULE:
    from .decorators import dump_args
    SDL_CreateWindow = dump_args(SDL_CreateWindow)

And I get outputs like this:
DEBUG:root:ctypes.SDL_CreateWindow ( arg_0 = b'', arg_1 = 863, arg_2 = 548, arg_3 = 150, arg_4 = 150, arg_5 = 8226 )

For a more complete version, that include return values, output parameters and fancy output, see this gist

A: Its a bit old post but wanted to add my bit.
Solution given by warvariuc does not work in all cases. If a method have default values as well as we send named arguments while calling, it does not give proper output. e.g. we get two values of b.
test(1, b = 5)
test (a = 1, b = 4, c = 'blah-blah', kwargs = {'b': 5} )

Adding my modified code.
def print_args(func):
    """
    Function to print all args of decorated function
    """

    def wrapper(*func_args, **func_kwargs):
        arg_names = func.__code__.co_varnames[:func.__code__.co_argcount]
        args = func_args[:len(arg_names)]
        defaults = func.__defaults__ or ()
        args = args + defaults[len(defaults) - (func.__code__.co_argcount - len(args)):]
        params = zip(arg_names, args)
        new_arg_list = [list(i) for i in params]
        for key in func_kwargs:
            for param in new_arg_list:
                if key == param[0]:
                    param[1] = func_kwargs[key]
        new_arg_list = [tuple(i) for i in new_arg_list]
        result = func(*func_args, **func_kwargs)
        print(f'{func.__name__} (' + ', '.join('%s = %r' % p for p in new_arg_list) + f'): {result}')

        return result

    return wrapper

@print_args
def test_params(a=7,b=5):
    pass

test_params(a=3)

Output
test_params (a = 3, b = 5)


text:
Q: Git Restkit submodule .xcodeproj modified all the time I am not doing changes to the submodule and it keeps making problems every time I am merging or committing.
Is there a way to ignore that ?

A: I am not an expert with XCode projects; But to my understanding this folder holds important files (see here https://stackoverflow.com/a/6120152/1031900).

*

*But if you know what you're doing, and you'd like to ignore changes to RestKit.xcodeproj, do this
git update-index --assume-unchanged $(git ls-files RestKit.xcodeproj | tr '\n' ' ')
Better explained here

*You could also just add the folder to .gitignore, but when commiting don't use -a switch. Adding the folder to .gitignore file (in the base git folder, if it doesn't exist create it) is done with this line:
RestKit.xcodeproj/

*If you'd like to completely stop tracking the folder, do this:
git rm -r RestKit.xcodeproj
Then, add the folder to .gitignore file as explained above.
You can probably fine some usefull information in Git ignore file for Xcode projects
Hope I helped.


text:
Q: Cygwin shell is overriding my Windows shell I'm not sure what I did, but I've somehow got Cygwin installed in such a way that even when I try to run an ordinary windows shell, Cygwin is interfering. I have batch scripts that I want to run in the default windows way that Cygwin complains about. I can't change them; I need to run them in the felaut shell. Is there any way to get my cmd shell back without completely uninstalling cygwin?
I did try renaming cygwin1.dll to something else, and the shell seems to work just fine until foo.bat tries to run the exe. Then I get a complaint that cygwin1.dll has moved, so it looks like cygwin is being invoked by the windows shell? I have the typical windows prompt in the cmd shell. I've even tried the powershell with the same results.
Interestingly, if I run the batch file directly from Win-R, using cmd /c, it works. So I'm pretty confused.

A: move the Cygwin path entry to the end of the path statement.


text:
Q: How to refer to instance methods in documentation? How can I refer to an instance field when writing documentation?
Consider this code:
object Foo {
  val foo = 42
}

class Foo {
  val foo = 42
}

In Java, one would use Foo.foo for the "static" method and Foo#foo for the instance method.
But in Scala # is already taken for path-dependent types and
class Foo {
  class foo
  def foo = 42
}

is legal code, so I can't refer to it unambiguously.
Is there some convention how this should look like?

A: Tough. Maybe English-like, as in Foo's foo? I had missed the ambiguity of #. That is still my preferred choice, though, because the ambiguity only exists in the absence of context. When referring to a type, # has one meaning. When referring to a value or method, # has another.
Since types and methods/values do not share the namespace, I don't see the ambiguity being of relevance here.


text:
Q: How to curry function with two parameters in Haskell I have a function buckets with type Integral a => [a] -> Int -> Int -> [[a]] and I want use it in foldl in this way:
basketsort lst = foldl (f) lst [1..3]
f lst = reverse . concat . (flip buckets 9) lst

The function f works, and has a type Integral a => [a] -> Int -> [a], but if I reduce lst parameter, compilation fails.
Is it possible to reduce more than one parameter by currying and use f's body in foldl without declaration of f? Something like this:
basketsort lst = foldl (reverse . concat . (flip buckets 9)) lst [1..3]

A: If you expand the second application of the dot operator:
    f lst = reverse . concat . (flip buckets 9) lst
==> f lst = (.) (reverse . concat) ((flip buckets 9) lst)

then the eta-reduction becomes obvious:
    f = (.) (reverse . concat) . (flip buckets 9)

But come on, do you really want to do that? Not a very nice present for whoever is going to maintain your code after you're gone.

A: First: I recommend not to use flip just to apply a function partially to its second argument; this can be done better with an infix section. (Or, perhaps the arguments of bucket should be the other way around in the first place?)
So, you want to make
f lst = reverse . concat . (`buckets`9) lst

pointfree. The problem is that you need to pass two arguments to the rightmost element in the composition chain. One way to do this is to use uncurried form (because then those two arguments come in just a single value):
f = curry $ reverse . concat . uncurry (`buckets`9)

An alternative is to use specialised combinators. The pointless-fun package has this:
f = reverse . concat .: (`buckets`9)

A more standard, though IMO rather ugly alternative is to use the function-functor: you can map over a function, which corresponds to composing after it:
f = fmap (reverse . concat) . (`buckets`9)

The best alternative frankly is to keep that parameter named:
basketsort lst = foldl (\l -> reverse . concat . buckets l 9) lst [1..3]


text:
Q: Android app not updating content I used the Android app to edit an answer that I had previously posted on Stack Overflow for this question. But the app is not displaying the updated content, even though I can see it OK on the Stack Overflow website.
I tried pulling down the screen page to refresh it, I tried stopping and restarting the app, but the old content is still being displayed.
Update: eventually, the app finally caught up with the new content on that page. But this is the first time I've seen it not update when I asked it to.


text:
Q: how to add class to the wordpress primary dropdown menu I want to add class name to the primary sub-menu in wordpress. Please any one help me to do this. thanks in advance.
for example menu structure like this

 home

About us

submenu1

submenu2

submenu3

i want to add another class in the sub-menu ul

A: This will work , just add this code to your functions.php
function your_submenu_class($menu) {

$menu = preg_replace('/ class="sub-menu"/','/ class="sub-menu yourclass" /',$menu);

return $menu;

}

add_filter('wp_nav_menu','your_submenu_class');

A: Use 'menu_class' argument of wp_nav_menu() function in .php template:
  <?php
    wp_nav_menu( array(
      'theme_location' => 'main-menu',
      'menu_id'        => 'primary-menu',
      'menu_class'      => 'menu  primary-menu-top'
    ) );
  ?>


text:
Q: Trying to setup unit stats based off a class in another script using objects name as a filter. (Unity) I'm new to coding games, so my logic may not be right for creating stats.
Quick intro: I'm creating a game that spawns units at the players command that go fight other units. To store all the different units stats I am creating a statsheet then (trying) to search that stat sheet in the units entity script that defines everything about that unit. I have an entity prefab that has all the scripts that apply to all units (such as move and damage). Then after the GameManager spawns the entity prefab, it builds another prefab (which is the actual unit) and moves it as a child inside the entity prefab.
I'm trying to add stats to each unit so I built a statsheet that holds non-MonoBehaviour classes with the different unit stats. The entity script then takes the name of the child(which is the unit name) and subtracts "(clone)" from it, then I want it to search for that class inside the statsheet based on that unit name and then assign the stats based of the preset stats in the statsheet. I don't know if this is the best way, or even a possible way at all. But so far logically it's the best I can come up with. I'm open to any suggestions if this won't work, however, the issue I'm running into with my current method is I can't search a class in another script based off a string. I've been searching the web for about 2 hours now and can't find anything.
entity script snippet:
public class Entity : MonoBehaviour
{
    public Movement movement;
    public int health;
    public int damage;
    public int attackSpeed;
    public int range;
    public int moveSpeed;
    public bool flying;
    public int cost;
    private void Start()
    {
        movement = GetComponent<Movement>();
        string unitName = transform.GetChild(0).name;
        unitName = unitName.Remove(unitName.Length-7);

        //unitName for this example returns "Pen1"

        health = unitName.health;
    }

here is my statsheet snippet:
public class Pen1
{
    public int health = 50;
    public int damage= 5;
    public int attackSpeed = 1;
    public int range = 1;
    public int moveSpeed = 1;
    public bool flying = false;
    public int cost = 50;

}

A: Searching by class name does not make sense because your class name may not have a health attribute. Then it will error the compiler. You need another logic. If you want to have different entities in the game, all you have to do is inherit them from the Entity class and then customize the variables. Finally prefab them and you can Instantiate whenever you want. You also do not need a clone.
public class Pen1 : Entity
{
    // setup variable in Inspector then prefab it.

    public void Write() // special method in pen that other entities doesn't have
    {
        // do something
    }
}

Now you can do the following to find pen classes that have their own properties. Remember that class definitions actually cover types, not just definitions of different instances. So even pens that have the same method properties and fields do not need to define another class.
var pens = FindObjectsOfType<Pen1>(); // it returns a list of pens

foreach (var p in pens)
{
    p.Write();
    Debug.Log(p.health);
}


text:
Q: Can you reach to embedded tags variable from outside? I need to get the index of a th:each to outsider scope.
   <div th:object="userList">
        <form th:action="@{/api/v1/product/saveProductToUser/{username}/{productName}(username=${userList.get(iterstatus).getUserName()},productName=${productList.get(${iterstatus2})})}" th:object="productList"   id="register" class="input-group" method="post">

          <select class="input-opt">
            <option th:each="a,iterStatus : ${productList}" th:text="${a.productName}" th:value="${a.productName}" th:with="iterstatus2=${iterStatus}" id="opt2">Choose a Product</option>
          </select >

          <select  class="input-opt">
            <option th:each="a,iterStatus : ${userList}" th:text="${a.userName}" th:value="${a.userName}"  th:with="iterstatus=${iterStatus}" id="opt2">Choose a Product</option>
          </select >

          <a th:href="@{/api/v1/product/showAllProducts}" type="submit" class="submit-btn">Save</a>

Can I get the index of this iteration to my form? Or any alternative solutions?


text:
Q: How does python use paths when a script is called using eval() from a php script and when the same function is called from a bash script? I have an executable python script which archives data from mysql server using the pymysql library.  The script works well from the command line.
I call this script from a php script using escapeshellcmd function and I've gotten it to work.
I also have created a bash script that I intend to use from crontab to archive the information as well. I can make this script work as well, by making changes outlined below.
Somehow I have gotten into python versions and path problems.
if I include
#!/home/tim/anaconda3/bin/python

as the first line of the python script it works when called by the php script (using www-data as the user, I believe).  It doesn't work from the bash script or the command line, giving the following error:
  File "./signal_archive.py", line 22, in <module>
    import pymysql
ModuleNotFoundError: No module named 'pymysql'

However, if the first line of the python script is as follows:
#!/usr/bin/python3

the script works from the bash script and the command line but not from the php script.  It gives the following error:
  File "/home/tim/python/commodities_related/signal_archive.py", line 23, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'

Both packages are installed on my system.  Thinking pointing the script to the path would help, I added the following to the python script but no luck so far.
sys.path.append('/usr/lib/python3/dist-packages:')
sys.path.append('/usr/local/lib/python3.5/dist-packages:')

There is obviously something I'm missing;  I think it is that php script is called by www-user and I don't know the default path.  The bash file is called by my user with the path specified in the .bashrc file.  However, I may need to point the apache or php (www-user) to use a specific installation of python.
EDIT-
To be more clear, a php script (phpfile1.php) calls the python script.  When I call phpfile1.php from another php script (phpfile2.php) running on apache2 I everything works using the
#!/home/tim/anaconda3/bin/python

When I call the same file (phpfile1.php) from a different php script (phpfile3.php) from a bash script it fails.
Additionally, if I run the file in place using the following
./signal_archive.py

I get the error but if I run it using the following command it works:
python signal_archive.py

Any ideas if this is right or how to do it?  Thanks.

A: I fixed this in 2 steps:
It turns out that I needed to add the path to anaconda3 to my .bash_profile file.
export PATH="/home/tim/anaconda3/bin:$PATH"

When anaconda3 is installed it modifies the .bashrc file with the previous code snippet.  However .bash_profile made the difference in this case.
I also modified the top of the python file to use the anaconda path for execution, as well as add the path for the specific python packages.
#!/home/tim/anaconda3/bin/python
import sys
sys.path.insert(1, '/usr/local/lib/python3.5/dist-packages')


text:
Q: How I write to the file from datagridview Am trying to write from the datagridview with a goal of saving the input to the xml file, but am not getting it correctly. My code:
XDocument doc = XDocument.Load(outputFilePath);
doc.Save(outputFilePath);
oDataSet = new DataSet();

foreach (DataGridViewRow _rows in Gridview_Output.Rows)
{
    DataRow oDatarow = oDataTable.NewRow();
    for (int i = 0; i < Gridview_Output.ColumnCount; i++)
    {
        oDataTable.Rows.Add(oDatarow.ItemArray);
    }
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(outputFilePath);
doc.Save(outputFilePath);

I want to write to this empty tags:
<data name="Exit_Button" xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp][Comment][/Comment]</comment>
</data>

A: Hmm try this to create a datatable from gridview:
private DataTable GetDataTableFromDGV(DataGridView dgv) {

    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }
    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
            dt.Rows.Add(cellValues);
    }
    return dt;
}

Then you can do:
DataTable dT = GetDataTableFromDGV(DataGridView1);
DataSet dS = new DataSet();
dS.Tables.Add(dT);
dS.WriteXml(File.OpenWrite("xml.xml"));


text:
Q: Token extension versus matcher versus phrase matcher vs entity ruler in spaCy I am trying to figure out the best way (fast) to extract entities, e.g. a month. I have come up with 5 different approaches using spaCy.
Initial setup
For each solution I start with an initial setup
import spacy.lang.en
nlp = spacy.lang.en.English()
text = 'I am trying to extract January as efficient as possible. But what is the best solution?'

Solution: using extension attributes (limited to single token matching)
import spacy.tokens
NORM_EXCEPTIONS = {
    'jan': 'MONTH', 'january': 'MONTH'
}
spacy.tokens.Token.set_extension('norm', getter=lambda t: NORM_EXCEPTIONS.get(t.text.lower(), t.norm_))
def time_this():
    doc = nlp(text)
    assert [t for t in doc if t._.norm == 'MONTH'] == [doc[5]]

%timeit time_this()

76.4 µs ± 169 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Solution: using phrase matcher via entity ruler
import spacy.pipeline
ruler = spacy.pipeline.EntityRuler(nlp)
ruler.phrase_matcher = spacy.matcher.PhraseMatcher(nlp.vocab, attr="LOWER")
ruler.add_patterns([{'label': 'MONTH', 'pattern': 'jan'}, {'label': 'MONTH', 'pattern': 'january'}])
nlp.add_pipe(ruler)
def time_this():
    doc = nlp(text)
    assert [t for t in doc.ents] == [doc[5:6]]
%timeit time_this()

131 µs ± 579 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Solution: using token matcher via entity ruler
import spacy.pipeline
ruler = spacy.pipeline.EntityRuler(nlp)
ruler.add_patterns([{'label': 'MONTH', 'pattern': [{'lower': {'IN': ['jan', 'january']}}]}])
nlp.add_pipe(ruler)
def time_this():
    doc = nlp(text)
    assert [t for t in doc.ents] == [doc[5:6]]
%timeit time_this()

72.6 µs ± 76.7 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Solution: using phrase matcher directly
import spacy.matcher
phrase_matcher = spacy.matcher.PhraseMatcher(nlp.vocab, attr="LOWER")
phrase_matcher.add('MONTH', None, nlp('jan'), nlp('january'))
def time_this():
    doc = nlp(text)
    matches = [m for m in filter(lambda x: x[0] == doc.vocab.strings['MONTH'], phrase_matcher(doc))]
    assert [doc[m[1]:m[2]] for m in matches] == [doc[5:6]]
%timeit time_this()

115 µs ± 537 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Solution: using token matcher directly
import spacy.matcher
matcher = spacy.matcher.Matcher(nlp.vocab)
matcher.add('MONTH', None, [{'lower': {'IN': ['jan', 'january']}}])
def time_this():
    doc = nlp(text)
    matches = [m for m in filter(lambda x: x[0] == doc.vocab.strings['MONTH'], matcher(doc))]
    assert [doc[m[1]:m[2]] for m in matches] == [doc[5:6]]
%timeit time_this()

55.5 µs ± 459 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Conclusion
The custom attributes with is limited to single token matching and the token matcher seems to be faster so that seems to be preferable. The EntityRuler seems to be the slowest which isn't surprising since it is changing the Doc.ents. It is however quite convenient that you have your matches in Doc.ents so you might want to consider this method still.
I was quite surprised that the token matcher outperforms the phrase matcher. I thought it would be opposite:

If you need to match large terminology lists, you can also use the PhraseMatcher and create Doc objects instead of token patterns, which is much more efficient overall

Question
Am I missing something important here or can I trust this analysis on a larger scale?

A: I think ultimately, it all comes down to finding the optimal tradeoff between speed, maintainability of the code and the way this piece of logic fits into the larger picture of your application. Finding a few strings in a text is unlikely to be the end goal of what you're trying to do – otherwise, you probably wouldn't be using spaCy and would stick to regular expressions. How your application needs to "consume" the result of the matching and what the matches mean in the larger context should motivate the approach you choose.
As you mention in the conclusion, if your matches are "named entities" by definition, adding them to the doc.ents makes a lot of sense and will even give you an easy way to combine your logic with statistical predictions. Even if it adds slightly more overhead, it'll likely still outperform any scaffolding you'd otherwise have to write around it yourself.

For each solution I start with an initial setup

If you're running the experiments in the same session, e.g. in a notebook, you may want to include the creation of the Doc object in your initial setup. Otherwise, the caching of the vocabulary entries could theoretically mean that the very first call of nlp(text) is slower than the subsequent calls. It's likely insignificant, though.

I was quite surprised that the token matcher outperforms the phrase matcher. I thought it would be opposite

One potential explanation is that you're profiling the approaches on a very small scale and on single-token patterns where the phrase matcher engine doesn't really have an advantage over the regular token matcher. Another factor could be that matching on a different attribute (e.g. LOWER instead of TEXT/ORTH) requires creating a new Doc during matching that reflects the values of the matched attribute. This should be inexpensive, but it's still one extra object that gets created. So a test Doc "extract January" will actually become "extract january" (when matching on LOWER) or even "VERB PROPN" when matching on POS. That's the trick that makes matching on other attributes work.
Some background on how the PhraseMatcher works and why its mechanism is typically faster: When you add Doc objects to the PhraseMatcher, it sets flags on the tokens included in the patterns, indicating that they're matching a given pattern. It then calls into the regular Matcher and adds token-based patterns using the previously set flags. When you're matching, spaCy will only have to check the flags and not retrieve any token attributes – that's what should make the matching itself significantly faster at scale.
This actually brings up another approach you could be profiling for comparison: Using Vocab.add_flag to set a boolean flag on the respective lexeme (entry in the vocab, so not the context-sensitive token). Vocab entries are cached, so you should only have to compute the flag once for a lexeme like "january". However, this approach only really makes sense for single tokens, so it's relatively limiting.

Am I missing something important here or can I trust this analysis on a larger scale?

If you want to get any meanigful insights, you should be benchmarking on at least a medium-sized scale. You don't want to be looping over the same small example 10000 times and instead, benchmark on a dataset that you'll only be processing once per test. For instance, a few hundred documents similar to the data you're actually working with. There are caching effects (both within spaCy, but also your CPU), differences in memory allocation and so on that can all have an impact.
Finally, using spaCy's Cython API directly will always be the fastest. So if speed is your number one concern and all you want to optimise for, Cython would be the way to go.


text:
Q: Using ipcRenderer in angular 2; trigger change detection I am building an electron app with angular 2 in the renderer process. My main process talks to a socket server. Whenever the user is connected to this server or disconnected, I wish to show the user's status in the view.
For this, I use electron's ipc to send a message from the main to the renderer process, like this
socket.on('connect', function() {
  mainWindow.webContents.send('socket-connection-status', true);
});
socket.on('disconnect', function() {
  mainWindow.webContents.send('socket-connection-status', false);
});

In my view, I then have a (simplified) angular component, like this
const ipc = require('electron').ipcRenderer;
@Component({
  selector: 'status-bar',
  template: '{{status}}'
})
export class StatusBarComponent {
  private status: string = "offline";
  constructor() {
    ipc.on('socket-connection-status', function(event, status) {
      if (status===true) {
        this.status = 'online';
      } else {
        this.status = 'offline';
      }
      console.log(status);  // Successfully logs true|false
      console.log(this.status);  // Successfully logs online|offline
    })
  }
}

I successfully log the messages from main process.
The problem is that angular 2 does not 'know' electron's ipc, so change detection is not triggered for status. I have seen several people struggling with this issue, but haven't come across a 'true' solution.
I have tried to solve it with injecting ApplicationRef, ChangeDetectorRef and ngZone (ref: Triggering Angular2 change detection manually), but none of the methods provided (tick(), detectChanges(), run() respectively) happened to provide a solution.
Apparently, 'within' ipc.on I cannot reference my class' properties/methods/injectables as I run into errors: For instance, this (https://github.com/JGantner/angular2_change_detection_issue/blob/master/browser/security-level-indicator-component.ts) solution (which I find not very elegant) results in Uncaught TypeError: Cannot read property 'markForCheck' of undefined.
Could somebody please help me out with how to make change detection work in my case?

Edit (hack):
One way I have found in which I at least get the functionality that I need/want:
status-bar.component.ts:
const ipc = require('electron').ipcRenderer;
import { SocketStatusService } from '../services/socket-status.service';
@Component({
  selector: 'status-bar',
  template: '{{status}}'
})
export class StatusBarComponent {
  private status: string = "offline";
  status$: Subscription;
  constructor(private socketStatusService: SocketStatusService, private ref: ApplicationRef) {
  ipc.on('socket-connection-status', function(evt, status) {
    if (status===true) {
      this.service.updateSocketStatus('online');
    } else {
      this.service.updateSocketStatus('offline');
    }
  }.bind({service: socketStatusService}))

  this.status$ = this.socketStatusService.socket_status$.subscribe(
    status => {
      this.status = status;
      this.ref.tick();
    }
  )
}

socket-status.service.ts:
@Injectable()
export class SocketStatusService {
  private socket_status = new BehaviorSubject<string>("offline");
  socket_status$ = this.socket_status.asObservable();

  updateSocketStatus(status: string) {
    this.socket_status.next(status);
  }
}

Although this works, I have the feeling there must be a more elegant way to achieve this behavior.
Best case scenario though would be a means to set the component's class properties directly in the ipc callback and trigger change detection... So far I have not been able to get that to work, so any help would be appreciated.
(p.s. Also, I am not sure why I have to manually trigger this.ref.tick(), which is not something I remember having had to do to trigger change detection from streams in earlier beta versions of angular 2...)

A: this.status is set on wrong object, and markForCheck doesn't work because of this too. Event handler should be an arrow in order for proper context to be provided.
With proper this context any known way to trigger change detection should work.
For example
ipc.on('...', (evt, status) => {
  ...
  this.changeDetectorRef.detectChanges();
});

Or
ipc.on('...', (evt, status) => {
  setTimeout(() => {
    ...
  });
});


text:
Q: read and decrypt cakephp cookies in javascript Is there any way to read and decrypy the cakephp cookies in javascript? i can read out the encrypted value, but it's not of much help.
Thank you in advance!

A: Those values are encrypted with a secret key. To decrypt them, you'd need to make the key available to Javascript, which means making it available to anyone out there who's looking at your site. It's not impossible to do it, but I'd seriously question how wise it is to do so.


text:
Q: Where does one hold service instances in a react/redux application? Suppose I am writing an application in Redux and I am tasked to add logging using a 3rd party library. Its API is as follows:
function createLogger(token) {
    // the logger has internal state!
    let logCount = 0;

    return {
        log(payload) {
            logCount++;            // modify local state

            fetch('/someapi', {    // ship payload to some API
                method: 'POST',
                body: payload
            });
        }
    };
}

I would then use the library something like this:
let logger = createLogger('xyz');
logger.log('foobar');

I definitely want to create the logger instance just once during application init. But then the question is: where do I store the logger instance?
First instict is to put it somewhere in the store. But is that a good idea? As I have demonstrated in the code the logger object is stateful, it stores a counter in the closure. I do not get a new instance like I would with an immutable object. As we know, state should only be modified via pure reducer functions.
Other possibilities are to create the instance somewhere in a redux middleware closure or just create a global variable, which is obviously evil in terms of testability.
Is there a best practice for this (I would think) rather common scenario?

A: Since you are using ES6 modules I would setup your logger as a module, export it, and import it wherever you plan to use it. I think logging from the actions is a solid plan, since it keeps the components unaware, and doesn't pollute the store with side-effects.
function createLogger(token) {
    // the logger has internal state!
    let logCount = 0;

    return {
        log(payload) {
            logCount++;            // modify local state

            fetch('/someapi', {    // ship payload to some API
                method: 'POST',
                body: payload
            });
        }
    };
}

export default const logger = createLogger('xyz');

Your action creators
import logger from 'logger-module';

//
logger.log('somestuff');

Testing is still easily achievable by importing the logger and placing whatever spy/stub on its methods that you need to intercept.

A: From the Redux documentation:
/**
 * Sends crash reports as state is updated and listeners are notified.
 */
const crashReporter = store => next => action => {
  try {
    return next(action)
  } catch (err) {
    console.error('Caught an exception!', err)
    Raven.captureException(err, {
      extra: {
        action,
        state: store.getState()
      }
    })
    throw err
  }
}

Raven being a third-party library.
If the library has its own state then it shouldn't be an issue using it in middleware (the state belongs in the library and not your app). If you're creating a state for it, for some reason, then that state should belong in the Redux store, probably under store.logger or something.