text:
Q: Tile Maps and vertexZ order for sprites Here is the setup. I have a orthogonal tile map made with Tiled. There are 5 layers. The bottom 4 comprise the background, while the top layer is the foreground that I will refer to as the "tree" layer. I have a hero sprite that I have added as a child of the tile map at the same node zorder as the tree layer.
The issue that invariably comes up with this scenario is that I want my hero to be in front of trees that he is "below", but behind those trees that he is "above". Below and above are determined by the Y coordinate of the hero versus the Y coordinate of any given tree.
The Cocos2d programming guide contains a section for tile maps, and in that section it specifically discusses how to achieve the affect I have described. This information can be found here.
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
The solution is pretty simple. Enable the depth buffer in my code. Add a cc_vertexz property with a value of -1000 to each layer that the hero will be above. Then add a cc_vertexz property to the tree layer with a value of "automatic" as well as a cc_alpha_func property with a value of .5. Then as your hero moves re-adjust its sprite's vertexz value based on its position within the map.
I did all this and it worked great. However, a problem appeared as soon as I added other "enemy" sprites to this map. As with the hero sprite these sprites were added to the map with the same node zorder as the tree layer, and they too have their vertexz values changed based on their Y coordinate within the map. It should be noted that the hero sprite is added after the enemy sprites. In addition, both the hero and enemy sprites are animated and their textures are not part of the tile map textures. Based on the Cocos2d documentation this should not matter.
The problem is this. If my hero is below an enemy sprite on the map then everything looks and works fine. However, if my hero is above an enemy sprite on the map then as the enemy passes over the hero sprite the background comes through rather than the hero sprite. The best way to describe it is to say that as soon as the enemy sprite begins to pass over the hero sprite, the transparent areas of the enemy sprite begin to fill with the background and the hero sprite is partially obscured until then enemy sprite moves off the hero. It is like the hero sprite is not there.
I know this is related to the order that the sprites are added to the map, because if I change this and have the hero sprite added to the map before the enemy sprites, then the effect reverses in that the background comes through the transparent areas of the hero sprite rather than the enemy sprites. It is almost like the vertexz property is not absolutely determining the order that things are drawn.
Looking into this it appears to be a blending issue and I found what seems to be the solution, which is to subclass the CCSprite class and override the draw method with the following:
-(void) draw {

glEnable(GL_ALPHA_TEST);

glAlphaFunc( GL_GREATER, 0 );

[super draw];

glDisable(GL_ALPHA_TEST);

}

The problem however is that this code is not applicable to the version of Cocos2d that I use, which is Cocos2d 2.1. In addition this appears to be handled by the CCTMXLayer drawing function if automatic vertexz is enabled. As such I do not know if subclassing CCSprite would just be redundant. See below for how CCTMXLayer handles this:
// CCTMXLayer drawing function -(void) draw

{

if( useAutomaticVertexZ_ ) {
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER, alphaFuncValue_);
}

[super draw];

if( useAutomaticVertexZ_ )
    glDisable(GL_ALPHA_TEST);
}

I am not new to Cocos2d, but I am very new to anything related to OpenGL. So in short, is the solution just to subclass CCSprite and find the Cocos2d 2.1 equivalent to the above code snippet, or am I simply doing something wrong? I suspect the latter.
Any help would be very much appreciated. Thanks!

A: This has been resolved.  The solution was to use the following on my sprites or sprite sheets as the case may be:
mySprite.shaderProgram = [[CCShaderCache sharedShaderCache]programForKey:kCCShader_PositionTextureColorAlphaTest];

This essentially takes the place of sub-classing CCSprite and overriding the draw method, which is the prescribed method for Cocos2d 1.x, whereas I am using Cocos2d 2.x.


text:
Q: unsafe struct Inaccessible error Structure Definition
[StructLayout(LayoutKind.Sequential, Pack = Compile.PackSize)]
  unsafe struct DB_PREPLIST
  {
    public TxnUnion txn;
    public fixed byte gid[DbConst.DB_XIDDATASIZE];
  }

Inaccessible error

Question
When I try to change the DB_PREPLIST as public  I get another error:
Pointers and Fixed size buffers may only be used in an unsafe context

A: All methods that need DB_PREPLIST as arguments need to be private in your code. Making DB_PREPLIST public would technically work, but is bad style, as you would need to mark all call sites unsafe. Better wrap all calls with another pure C# structure as argument and make your Delegate private. In this particular scenario, this will probably mean that you'll have to redirect the calls to the delegate through the wrapper, too.

A: This reply by Tony The Lion answers your question:
Basically, you need to wrap the code calling the unsafe struct in an 'unsafe' block, i.e.
unsafe
{
   //your code
}

(edit) you also need to add the public access modifier onto your struct, otherwise, unsafe or not, you won't be able to access it (unless it's nested in the class which calls it).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Contar ocorrencias de certos caracteres nos valores de uma coluna Bom, eu tenho um dataframe nesse estilo só que bem maior e as siglas de abreviação dos estados se repetem por toda a coluna, alterando apenas os valores em X, fazendo com que cada valor de uma linha seja único.

index
Numbers

0
XXMGXXXX

1
XXSPXXXX

2
XXDFXXXX

3
XXSPXXXX

O que eu preciso fazer é contar a frequência em que essas siglas de estado se repetem ao mesmo tempo que vou preenchendo outra coluna com esses valores, mais ou menos assim

index
Contador
Numbers

0
1
XXMGXXXX

1
1
XXSPXXXX

2
1
XXDFXXXX

3
2
XXSPXXXX

4
2
XXMGXXXX

5
1
XXRJXXXX

6
3
XXMGXXXX

Cada sigla tem sua própria contagem.Eu tentei utilizar o
df.groupby().count()

Porém esse método só faz a contagem da frequência dos valores em si, não sei como utilizar esse mesmo método para a contagem da frequência de um grupo de caracteres nos valores da coluna. Se for possível assim eu vou ter a frequência total em que cada sigla aparece, me permitindo utilizar o valor total para preencher a coluna 'Contador'.Se não for possível, alguém tem uma luz de alguma outra forma de fazer isso ?

A: Consegui resolver utilizando o pandas.core.groupby.GroupBy.cumcount, ficando assim
df.insert(0, 'Contador', '')
df['Contador'] = df.groupby(df['Numbers'].str[2:4]).cumcount() + 1

A primeira linha apenas adiciona a coluna 'Contador' ao dataframe, na posição zero, e sem nenhum vazia.
Na segunda, passamos para o groupby o critério que queremos para criar os grupos individuais, que no caso são as siglas dos estados contida na string de cada linha da coluna 'Numbers', e para realizar a contagem individual desses grupos, de forma que ela vá se acumulando por todo o dataframe utilizamos o cumcount(), o count() não acumula a contagem por isso não da certo, o +1 é apenas para começar a contagem em 1 e não em zero.


text:
Q: Can't connect to cassandra from Pyspark I'm trying to connect to cassandra from Pyspark and run some queries.
Here are all the steps I have done:
First I installed Spark:
wget http://www.apache.org/dyn/closer.lua/spark/spark-1.6.1/spark-1.6.1-bin-hadoop2.6.tgz

Then:
cd spark-2.1.0-bin-hadoop2.7/

Then I run this command:
./bin/pyspark

I got this:
16:48 $ ./bin/pyspark
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
17/05/02 16:50:33 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/05/02 16:50:33 WARN Utils: Your hostname, rleitao-H81M-HD3 resolves to a loopback address: 127.0.1.1; using 192.168.1.26 instead (on interface eth0)
17/05/02 16:50:33 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
17/05/02 16:50:36 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.1.0
      /_/

Using Python version 2.7.12 (default, Nov 19 2016 06:48:10)
SparkSession available as 'spark'.
>>>

Then:
from pyspark.sql import SQLContext
sql = SQLContext(sc)

Then:
df = sql.read.format("org.apache.spark.sql.cassandra").\
option("spark.cassandra.connection.host", "ec2-IPV4-Adress.REGION.compute.amazonaws.com").\
option("spark.cassandra.auth.username", "user"). \
option("spark.cassandra.auth.password", "pass"). \
option(keyspace="mykeyspace", table="mytable").load()

then Ops, I got this huge error:
    >>> df = sql.read.format("org.apache.spark.sql.cassandra").\
    ... option("spark.cassandra.connection.host", "ec2-IPV4-adress.REGION.compute.amazonaws.com").\
    ... option("spark.cassandra.auth.username", "user"). \
    ... option("spark.cassandra.auth.password", "pass"). \
    ... option(keyspace="mykeyspace", table="mytable").load()
    17/05/02 16:47:43 ERROR Schema: Failed initialising database.
    Unable to open a test connection to the given database. JDBC url = jdbc:derby:;databaseName=metastore_db;create=true, username = APP. Terminating connection pool (set lazyInit to true if you expect to start your database after your app). Original Exception: ------
    java.sql.SQLException: Failed to start database 'metastore_db' with class loader org.apache.spark.sql.hive.client.IsolatedClientLoader$$anon$1@fa39daf, see the next exception for details.
        at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
        at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
        at org.apache.derby.impl.jdbc.Util.seeNextException(Unknown Source)
        at org.apache.derby.impl.jdbc.EmbedConnection.bootDatabase(Unknown Source)
        at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
        at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
        at org.apache.derby.jdbc.InternalDriver$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
        at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
        at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
        at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:208)
ct.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at javax.jdo.JDOHelper$16.run(JDOHelper.java:1965)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.jdo.JDOHelper.invoke(JDOHelper.java:1960)
        at javax.jdo.JDOHelper.invokeGetPersistenceManagerFactoryOnImplementation(JDOHelper.java:1166)
        at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:808)
        at javax.jdo.JDOHelper.getPersistenceManagerFactory(JDOHelper.java:701)
        at org.apache.hadoop.hive.metastore.ObjectStore.getPMF(ObjectStore.java:365)
        at org.apache.hadoop.hive.metastore.ObjectStore.getPersistenceManager(ObjectStore.java:394)
        at org.apache.hadoop.hive.metastore.ObjectStore.initialize(ObjectStore.java:291)
        at org.apache.hadoop.hive.metastore.ObjectStore.setConf(ObjectStore.java:258)
        at org.apache.hadoop.util.ReflectionUtils.setConf(ReflectionUtils.java:76)
        at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:136)
        at org.apache.hadoop.hive.metastore.RawStoreProxy.<init>(RawStoreProxy.java:57)
        at org.apache.hadoop.hive.metastore.RawStoreProxy.getProxy(RawStoreProxy.java:66)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.newRawStore(HiveMetaStore.java:593)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.getMS(HiveMetaStore.java:571)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
        at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1521)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:86)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:132)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:104)
        at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3005)
        at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3024)
        at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1234)
        at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:174)
        at org.apache.hadoop.hive.ql.metadata.Hive.<clinit>(Hive.java:166)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:503)
        at org.apache.spark.sql.hive.client.HiveClientImpl.<init>(HiveClientImpl.scala:192)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        ... 108 more
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/souadmabrouk/Bureau/Souad/project/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/context.py", line 464, in read
        return DataFrameReader(self)
      File "/home/souadmabrouk/Bureau/Souad/project/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/readwriter.py", line 70, in __init__
        self._jreader = spark._ssql_ctx.read()
      File "/home/souadmabrouk/Bureau/Souad/project/spark-2.1.0-bin-hadoop2.7/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
      File "/home/souadmabrouk/Bureau/Souad/project/spark-2.1.0-bin-hadoop2.7/python/pyspark/sql/utils.py", line 79, in deco
        raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
    pyspark.sql.utils.IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionState':"
    >>>

How Can I use the cassandra connector? I could not find a clear documentation for that. and by the way,  cassandra cluster is on AWS.
Any help will be really appreaciated.

A: *

*run pyspark with:
./bin/pyspark --packages com.datastax.spark:spark-cassandra-connector_2.11:2.0.2

*In the code, create dict with connection config
hosts = {"spark.cassandra.connection.host": 'host_dns_or_ip_1,host_dns_or_ip_2,host_dns_or_ip_3'}

*In the code, Create Dataframe using connection config
data_frame = sqlContext.read.format("org.apache.spark.sql.cassandra").options(**hosts).load(keyspace="your_keyspace", table="your_table")

A: The following works for me:
./bin/pyspark --master local[*] --packages com.datastax.spark:spark-cassandra-connector_2.11:2.3.2 --conf spark.cassandra.connection.host=host.name --conf spark.cassandra.auth.username=cassandraname --conf spark.cassandra.auth.password=cassandrapwd

>>> df = spark.read.format("org.apache.spark.sql.cassandra")\
   .options(table="tablename", keyspace="keyspacename").load()

>>> df.show()


text:
Q: How can I line up the two containers in view? I am working on a web app. One of the views has been divided into different portions in order to display different information utilizing the whole view and make stuff more manageable. The problem is that the beginning of the information on placementContainerRight gets lined up with the last information from placementContainerLeft giving me a big free space on top of the placementContainerRight.
My html:

        <%--Start of left container --%>

            <%--This section will handle the three for the specific Enterprise --%>

                    All Agencies

                                    Number of Accounts
                                    Amount of Placement
                                    Percentage of Placement
                                    NeuPlacement Score

hmmm

        <%--End of left container --%>

        <%--Start of right container --%>

            <%--This section handles the Bar FusionChart --%>

This are the id's in my css:
#mainContainer
{
    width:900px;
    vertical-align: top;
    margin-left:20px;
    float:left;
}
#placementContainerLeft
{
    width:578px;
    margin-left:5px;
    clear:left;
}
#placementContainerRight
{
    width:267px;
    margin-left:628px;
    clear:right;
}

And this is the way it currently looks:

Does anybody know how to fix this problem?

A: This cheap and simple answer is to add "float: left" to your #placementContainerLeft #placementContainerRight.
There may be better ways to do this, but I think this is the simplest.
UPDATE: oh and remove that huge margin-left on your #placementContainerRight


text:
Q: How to output modelform errors in Django How do I trigger the opposite of is_valid()? This is how I have done it so far:
def post(self, request):
        user_form = self.form_class(request.POST)
        second_form = self.second_form_class(request.POST)

    if user_form.is_valid() and second_form.is_valid():
        user = user_form.save(commit=False)
        invite = second_form.save(commit=False)

        username = user_form.cleaned_data['username']
        password = user_form.cleaned_data['password']
        email = user_form.cleaned_data['email']
        code = second_form.cleaned_data['code']

        user.set_password(password)
        user.is_staff = True
        user.save()

        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                return redirect('main:welcome')

I want to check if this is true, but I don't know how to implement it in my generic view:
the_invite = Invites.objects.filter(code=code)

if the_invite.exists():
    the_invite.delete()
else:
    second_form.add_error()

I want to simply output like this error message with for example: "You entered the wrong code": enter link description here

A: When form is invalid, you need to send it to template and render:
{{ form.errors }}

A: "I want to simply output like this error message with for example: "You entered the wrong code""
Well, you can add errors to form like this:
form._errors = ErrorDict()
errors = form._errors.setdefault('[name of the field that failed verification]', ErrorList())
errors.append('[Your error message]')

And then return this form back to user.


text:
Q: R - adding columns together, depending on column name I have a dataframe (df1) that includes abundances of different species in each sample:
> SampleID   Sp1   Sp2   Sp3   Sp4   ... Spn
> asb-001      3     0     0    23         9
> asb-002      4    15    10    56        98
> asb-003      8    45     8   453         0
> asb-004      0     5     0     3         6
> asb-005    120    56     0     0         0
...

Each column represents a different species.
I have another dataframe (df2)
Sp     Fam
Sp1   Fam1
Sp2   Fam2
Sp3   Fam1
Sp4   Fam3
Sp5   Fam2
Sp6   Fam1
...

There are fewer Family names than there are Species names.
I would like to add columns together depending on the species name to get a total for the family (e.g. Sp1 + Sp3 + Sp6 = Fam1). I don't want to keep the original column with the species name.
If all goes according to plan, my new dataframe (df3) will look something like this:
> SampleID  Fam1  Fam2  Fam3
> asb-001     12     0     9
> asb-002     14    18   112
> asb-003     28    58    18
> asb-004     10    12    10
> asb-005    142    65     0
...

I could manually go through and add individual species together, but this seems tedious for a large dataset, and likely to produce errors. I have the feeling that I should melt df1, but I'm not confident in the details. Any advice would be appreciated!

A: Change your original data to be in the long format and join against the species-family mapping. You can then compute summation for each family using group_by. Finally, spread the data back out to be in wide format.
library( tidyverse )

df1 %>% gather( Sp, Value, -SampleID ) %>%     # Convert to long format
  inner_join( df2 ) %>%                        # Combine with family mapping
  group_by( SampleID, Fam ) %>%                # Work on each sample/family pair
  summarize( ValSum = sum(Value) ) %>%         # Compute the sum across species
  ungroup %>% spread( Fam, ValSum, fill=0 )    # Convert back to wide format

Depending on whether each sample is represented in each family, you may get NA after converting back to wide format. The optional parameter fill=0 takes care of converting these NA to 0.

A: Another way, using library(data.table):
setDT(df1); setDT(df2) # Convert data.frames into data.tables

x = df2[melt(df1, variable.name = 'Sp'), on = 'Sp'] # Join melted df1 to df2 on species
df3 = dcast(x, SampleID~Fam, fun.aggregate = sum) # cast to wide format by summing total values per family


text:
Q: kubernetes deploy with tar docker image I have a problem to deploy docker image via kubernetes.
One issue is that, we cannot use any docker image registry service e.g. docker hub or any cloud services. But, yes I have docker images as .tar file.
However, it always fails with following message
Warning  Failed     1s         kubelet, dell20

Failed to pull image "test:latest": rpc
error: code = Unknown
desc = failed to resolve image "docker.io/library/test:latest":
failed to do request: Head https://registry-1.docker.io/v2/library/test/manifests/latest: dial tcp i/o timeout

I also change deployment description with IfNotPresent or Never. In this case it will fail anyway with ErrImageNeverPull.
My guess is: kubernetes tries to use Docker Hub anyway, since it https://registry-1.docker.io in order to pull the image. I just want to use tar docker image in local disk, rather than pulling from some services.
And yes the image is in docker:
docker images
REPOSITORY  TAG    IMAGE ID      CREATED     SIZE
test        latest 9f4916a0780c  6 days ago  1.72GB

Can anyone give me any advices on this problem?

A: I was successful with using local image with Kubernetes cluster. I provided the explanation with example below:
The only prerequisite is that you need to make sure you have access to upload this image directly to nodes.
Create the image
Pull the default nginx image from docker registry with below command:
$ docker pull nginx:1.17.5
Nginx image is used only for demonstration purposes.
Tag this image with new name as nginx-local  with command:
$ docker tag nginx:1.17.5 nginx-local:1.17.5
Save this image as nginx-local.tar executing command:
$ docker save nginx-local:1.17.5 > nginx-local.tar
Link to documentation: docker save
File nginx-local.tar is used as your image.
Copy the image to all of the nodes
The problem with this technique is that you need to ensure all of the nodes have this image.
Lack of image will result in failed pod creation.
To copy it you can use scp. It's secure way to transer files between machines.
Example command for scp:
$ scp /path/to/your/file/nginx-local.tar user@ip_adddress:/where/you/want/it/nginx-local.tar

If image is already on the node, you will need to load it into local docker image repository with command:
$ docker load -i nginx-local.tar
To ensure that image is loaded invoke command
$ docker images | grep nginx-local
Link to documentation: docker load:
It should show something like that:
docker images | grep nginx
nginx-local                                           1.17.5              540a289bab6c        3 weeks ago         126MB

Creating deployment with local image
The last part is to create deployment with use of nginx-local image.
Please note that:

*

*The image version is explicitly typed inside yaml file.

*ImagePullPolicy is set to Never. ImagePullPolicy
Without this options the pod creation will fail.
Below is example deployment which uses exactly that image:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-local
  namespace: default
spec:
  selector:
    matchLabels:
      run: nginx-local
  replicas: 5
  template:
    metadata:
      labels:
        run: nginx-local
    spec:
      containers:
      - image: nginx-local:1.17.5
        imagePullPolicy: Never
        name: nginx-local
        ports:
        - containerPort: 80

Create this deployment with command:
$ kubectl create -f local-test.yaml
The result was that pods were created successfully as shown below:
NAME                           READY   STATUS    RESTARTS   AGE
nginx-local-84ddb99b55-7vpvd   1/1     Running   0          2m15s
nginx-local-84ddb99b55-fgb2n   1/1     Running   0          2m15s
nginx-local-84ddb99b55-jlpz8   1/1     Running   0          2m15s
nginx-local-84ddb99b55-kzgw5   1/1     Running   0          2m15s
nginx-local-84ddb99b55-mc7rw   1/1     Running   0          2m15s

This operation was successful but I would recommend you to use local docker repository. It will easier management process with images and will be inside your infrastructure.
Link to documentation about it:  Local Docker Registry


text:
Q: custom grouping of pd.df, calculate OHLC in vectorised fashion I would like to get Open/High/Low/Close for chunks of a dataframe where df.volume >= threshold.
Reproducible example:
df = pd.DataFrame(index=pd.date_range('2018-01-02', periods=10000, freq='ms'),
                  data=np.random.randint(0,100,size=(10000, 2)),
                  columns=['price', 'volume'])
df.head()
                       price volume
2018-01-02 00:00:00.000   19    4
2018-01-02 00:00:00.001   49    9
2018-01-02 00:00:00.002    2    5
2018-01-02 00:00:00.003   12   82
2018-01-02 00:00:00.004   42   32

I can achieve the desired result by iterating over iterrows() which is painfully slow:
threshold = 5000
vol = 0
count = 1
group = []
for idx, row in df.iterrows():
    vol += row['volume']
    if vol >= threshold:
        count +=1
        vol = 0
    group.append(count)
df['group'] = group

df.groupby('group').agg({'price': 'ohlc'})

I have 70 Dataframes with ~3mio rows each to process and the for loop takes ~2:30mins.
Hence I would appreciate a vectorised approach. Is there a way to replace the for loop with a vectorised solution?

A: This can be solved by using pandas groupby. First, create a new column to be used to group by. We can simply divide the cumsum column with the wanted granularity:
threshold = 5000
df['group'] = np.floor(df['cumsum'] / threshold)

np.floor is used here to make sure that the >= equality is kept, otherwise, just converting to int would work as well.
Now we can compute the aggregate values of each group. This can be done as follows:
df.groupby('group').agg({'price': 'ohlc'})


text:
Q: Implementing an "omnibar" like Google Chrome's... need method to determine query or URL Before I do this myself I thought I'd ask here and see if there are any quick solutions.
I don't need the history-lookup, autocomplete, or other fancy features of Chrome's omnibar; I just need to detect if a string looks like a valid URL (with valid TLDs and scheme/protocol) or ip-address (IPV4 and IPV6).
I'm not sure how to search chrome's code repository for a look at how they do it. So if you can find that for me that would be an acceptable answer (bonus points if you port it to javascript!).
Tagged as language-agnostic because I don't care what language it is in [well, please no Ook or LOLCODE]). Javascript will be the final implementation, though.

A: There's a regex provided in RFC2396 - Uniform Resource Identifiers (URI): Generic Syntax (see appendix B) :

The following line is the regular
  expression for breaking-down a URI
  reference into its components.
  ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
   12            3  4          5       6  7        8 9

The numbers in the second line
  above are only to assist readability;
  they indicate the reference points for
  each subexpression (i.e., each
  paired parenthesis).  We refer to the
  value matched for subexpression
  as $.  For example, matching the
  above expression to
  http://www.ics.uci.edu/pub/ietf/uri/#Related

results in the following
  subexpression matches:
  $1 = http:
  $2 = http
  $3 = //www.ics.uci.edu
  $4 = www.ics.uci.edu
  $5 = /pub/ietf/uri/
  $6 = <undefined>
  $7 = <undefined>
  $8 = #Related
  $9 = Related

I don't see a reason to not use regex in this case, especially if you're just checking if it's a URI or if it's a search.


text:
Q: Vue focusing input can't find input field I am trying to focus an input field but I get this error:

Error in nextTick: "TypeError: Cannot read property 'focus' of undefined"

Here is my code

<input
  v-show="employeeNumberEdit"
  ref="number"
>

toggleEdit: function(number){
    this.numberEdit = !number;
    if (this.numberEdit) {
      Vue.nextTick(() => {
        this.$refs.number.$el.focus();
      })
    }
}

What am I doing wrong here? Does he not know this in the callback?

A: Your input box is this way
<input
  v-show="employeeNumberEdit"
  ref="employeeNumber"
>

And to focus in on toggle please do it this way
toggleEdit: function(number){
    this.numberEdit = !number;
    if (this.numberEdit) {
       this.$refs.employeeNumber.focus();
    }
}

Below is the running code snippet, when you press toggle button, input box will be focused.

new Vue({
     el: '#app',
     methods:{
          toggleEdit: function(number){
            this.numberEdit = !number;
            this.$refs.employeeNumber.focus();
          }
     }
});

<input
  ref="employeeNumber"
>
<button @click="toggleEdit">Toggle</button>


text:
Q: How can i return a Varchar2 out of my stored procedure When I run my program I get this error in my catch

ORA-06550: line 1, column 7:
PLS-00905: object DBI304134.FINDFREEBARCODE is invalid
ORA-06550: line 1, column 7:

This is the c# code I use:
string freeBarcode = null;

    try
    {
        string connection = ConfigurationManager.ConnectionStrings["P4connection"].ConnectionString;
        using (OracleConnection con = new OracleConnection(connection))
        {
            OracleCommand cmd = new OracleCommand("FindfreeBarcode", con);
            cmd.CommandType = CommandType.StoredProcedure;

            OracleParameter outpuparameter = new OracleParameter("outpuparameter", OracleDbType.Varchar2,100);
            outpuparameter.ParameterName = "FREEBARCODE";
            outpuparameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(outpuparameter);

            con.Open();
            cmd.ExecuteNonQuery();

            freeBarcode = Convert.ToString(outpuparameter.Value.ToString());

            if (freeBarcode == null)
            {
                freeBarcode = null;
            }

            else
            {
                freeBarcode = Convert.ToString(outpuparameter.Value.ToString());
            }
        }

    }
    catch
    {
        freeBarcode = null;
    }

    return freeBarcode;

And this is the stored procedure i use:
create or replace procedure FindfreeBarcode
   (FREEBARCODE out VARCHAR2)
is
begin
   select b.BARCODE
    INTO FREEBARCODE
    from GAST g,BARCODECHECK b
    WHERE g.GASTID(+) = b.GASTID and b.GASTID is null and ROWNUM <= 1;
END FindfreeBarcode;

A: Find my answer on this page
Stored procedure output parameter returns @Value
had to change
freeBarcode = Convert.ToString(outpuparameter.Value.ToString());

to:
Convert.ToString(outpuparameter.Value);

A: Use the original version of your stored proc, and change
OracleCommand cmd = new OracleCommand("FindfreeBarcode", con);

to
OracleCommand cmd = new OracleCommand("FindfreeBarcode(:FREEBARCODE)", con);

Share and enjoy.


text:
Q: Regex to match word within a message I'm really new at regex and I'm trying to make a regex to find messages with only 1 word being the word "Hi" or some variations but exclude the message if the word "hi" is along with other words.
For example, I want the regex to match a message which includes only and only the word "hello" and set a flag to true, but if the message contains "hello I need help" the regex should not match and the flag should remain as false.
The regex should work with a list of words:
Hi
Hii
Hello
Hello sir
hi sir
hii sir
Hi sir/ma'am
Hello sir/ma'am
Hi there
Hello there

I tried this, trying to limit the number of characters but it didn't work [hi|hello|Hi sir]{0,10}

A: If you want to match lines that are exactly "hi", "hello" or "hi sir" with nothing else on the line (case insensitively matched):
(?i)^(hi|hello|hi sir)$


text:
Q: ImportError: libmpi.so.12: cannot open shared object file: No such file or directory I want to load a custom Python module dataloader, which utilizes the mpi4py library. My code raises ImportError: libmpi.so.12: cannot open shared object file: No such file or directory.
Traceback error:
> --------------------------------------------------------------------------- ImportError                               Traceback (most recent call
> last) /tmp/ipykernel_10920/2839973880.py in <module>

> ----> 6 from whole_slide_cnn.dataloader import WholeSlideDataloader, MILDataloader
>
> ~/CODEX/whole-slide-cnn/whole_slide_cnn/dataloader.py in <module>
> ----> 3 from mpi4py import MPI
>
> ImportError: libmpi.so.12: cannot open shared object file: No such
> file or directory

Jupyter notebook
! conda install -c conda-forge mpi4py
from whole_slide_cnn.dataloader import WholeSlideDataloader, MILDataloader

whole_slide_cnn.dataloader.py
from mpi4py import MPI

class WholeSlideDataloader(tf.keras.utils.Sequence):
    def __init__(
        self,
        dataset,
        augment,
        shuffle,
        num_classes,
        batch_size=1,
        snapshot_path=None,
        hvd=None,
    ):
        self.dataset = dataset
        self.augment = augment
        self.shuffle = shuffle
        self.num_classes = num_classes
        self.batch_size = batch_size
        self.snapshot_path = snapshot_path
        self.hvd = hvd

        self._reinit_shuffle_list()

    def __len__(self):
        num_workers = self.hvd.size() if self.hvd != None else 1
        return len(self.dataset) // self.batch_size // num_workers

    def __getitem__(self, idx):
        begin_idx = idx * self.batch_size
        end_idx = (idx + 1) * self.batch_size

        x_batch = []
        y_batch = []
        for shuffle_list_idx in range(begin_idx, end_idx):
            dataset_idx = self.shuffle_list[shuffle_list_idx]
            loaded = False
            while not loaded:
                try:
                    img, label = self.dataset[dataset_idx]
                    loaded = True
                except Exception as e:
                    print(traceback.format_exc())
                    print(
                        "Error occurs while loading {} . Retry after 5 seconds.".format(
                            self.dataset.get_slide_path(dataset_idx)
                        )
                    )
                    time.sleep(5)

            if self.augment:
                if img.size < 4 * 1024 * 1024 * 1024:
                    img = _get_augmentor().augment_image(img)
                else:
                    # If the image is too large, imgaug will fail on affine transformation. Use PIL instead.
                    img = _get_augmentor_wo_affine().augment_image(img)
                    img = Image.fromarray(img)
                    angle = np.random.uniform(0.0, 360.0)
                    translate = tuple(np.random.randint(-220, 220, size=[2]))
                    img = img.rotate(angle, resample=Image.NEAREST, translate=translate, fillcolor=(255, 255, 255))
                    img = np.array(img)

            if self.snapshot_path != None:
                os.makedirs(self.snapshot_path, exist_ok=True)
                img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
                cv2.imwrite(
                    os.path.join(self.snapshot_path, "dataloader_snapshot.tiff"),
                    img_bgr,
                )

            img = preprocess_input(img)
            y = np.zeros(shape=[self.num_classes])
            y[label] = 1.0

            x_batch.append(img)
            y_batch.append(y)

        return np.array(x_batch), np.array(y_batch)

    def on_epoch_end(self):
        self._reinit_shuffle_list()

    def get_slide_path(self, idx):
        dataset_idx = self.shuffle_list[idx]
        return self.dataset.get_slide_path(dataset_idx)

    def get_y_true(self, idx):
        dataset_idx = self.shuffle_list[idx]
        return self.dataset.get_y_true(dataset_idx)

    def get_dataset_idx(self, idx):
        return self.shuffle_list[idx]

    def _reinit_shuffle_list(self):
        self.shuffle_list = np.arange(len(self.dataset))
        if self.shuffle:
            np.random.shuffle(self.shuffle_list)
        if self.hvd != None:
            self.shuffle_list = MPI.COMM_WORLD.bcast(self.shuffle_list, root=0)

            num_workers = self.hvd.size()
            rank = self.hvd.rank()
            self.shuffle_list = [
                self.shuffle_list[idx * num_workers + rank]
                for idx in range(len(self))
            ]

class MILDataloader(WholeSlideDataloader):
    MIL_WHITE_THRESHOLD = 220
    MIL_EM_GAUSSIAN_KERNEL_SIZE = 3
    MIL_EM_P1 = 0.1
    MIL_EM_P2 = 0.05

    def __init__(
        self,
        dataset,
        augment,
        shuffle,
        num_classes,
        mil_model,
        batch_size=1,
        snapshot_path=None,
        hvd=None,
        mil_patch_size=[224, 224],
        mil_infer_batch_size=32,
        mil_use_em=False,
        mil_k=1,
        mil_skip_white=True,
    ):
        super(MILDataloader, self).__init__(
            dataset=dataset,
            augment=augment,
            shuffle=shuffle,
            num_classes=num_classes,
            batch_size=batch_size,
            snapshot_path=snapshot_path,
            hvd=hvd,
        )
        self.mil_model = mil_model
        self.mil_patch_size = mil_patch_size
        self.mil_infer_batch_size = mil_infer_batch_size
        self.mil_use_em = mil_use_em
        self.mil_k = mil_k
        self.mil_skip_white = mil_skip_white

    def __getitem__(self, idx):
        x_batch_wsi, y_batch_wsi = super(MILDataloader, self).__getitem__(idx)

        x_batch = []
        y_batch = []
        for i in range(self.batch_size):
            x = x_batch_wsi[i]
            y = y_batch_wsi[i]

            num_patch_y = x.shape[0] // self.mil_patch_size[1]
            num_patch_x = x.shape[1] // self.mil_patch_size[0]

            mil_infer_dataset = []
            coords = []
            for i in range(num_patch_y):
                for j in range(num_patch_x):
                    sliced_x = x[
                        i * self.mil_patch_size[1]: (i + 1) * self.mil_patch_size[1],
                        j * self.mil_patch_size[0]: (j + 1) * self.mil_patch_size[0],
                        :,
                    ]
                    if (
                        self.mil_skip_white and
                        np.min(sliced_x) > preprocess_input(self.MIL_WHITE_THRESHOLD)
                    ):
                        continue
                    mil_infer_dataset.append(sliced_x)
                    coords.append((j, i))
            mil_infer_dataset = np.array(mil_infer_dataset)

            mil_infer_res = []
            for begin_idx in range(0, len(mil_infer_dataset), self.mil_infer_batch_size):
                end_idx = np.minimum(len(mil_infer_dataset), begin_idx + self.mil_infer_batch_size)
                mil_infer_res.append(
                    self.mil_model.predict_on_batch(
                         mil_infer_dataset[begin_idx: end_idx]
                    )
                )
            mil_infer_res = np.concatenate(mil_infer_res, axis=0)
            benign_rate = mil_infer_res[:, 0]

            if not self.mil_use_em:
                top_k_indices = np.argsort(benign_rate)[0: self.mil_k]
                for index in top_k_indices:
                    x_batch.append(mil_infer_dataset[index])
                    y_batch.append(y)
            else:
                res_map = np.zeros([num_patch_y, num_patch_x, self.num_classes - 1]) # Excluding non-cancer
                for i in range(len(mil_infer_res)):
                    res = mil_infer_res[i]
                    coord = coords[i]
                    res_map[coord[1], coord[0], :] = res[1: ]

                res_map_blurred = cv2.GaussianBlur(
                    res_map,
                    (self.MIL_EM_GAUSSIAN_KERNEL_SIZE, self.MIL_EM_GAUSSIAN_KERNEL_SIZE),
                    0
                )

                mil_infer_res_blurred = []
                for i in range(len(mil_infer_res)):
                    coord = coords[i]
                    res_blurred = res_map_blurred[coord[1], coord[0], :]
                    mil_infer_res_blurred.append(res_blurred)
                mil_infer_res_blurred = np.array(mil_infer_res_blurred)

                thres_p1 = np.percentile(mil_infer_res_blurred, 100.0 - self.MIL_EM_P1)

                select = None
                for class_id in range(1, self.num_classes):
                    candidates = mil_infer_res_blurred[:, class_id - 1].tolist()
                    if self.hvd != None:
                        candidates = MPI.COMM_WORLD.gather(candidates, root=0)
                        candidates = MPI.COMM_WORLD.bcast(candidates, root=0)
                        flatten = []
                        for candidate in candidates:
                            flatten += candidate
                        candidates = flatten
                    candidates = np.array(candidates)

                    thres_p2 = np.percentile(candidates, 100.0 - self.MIL_EM_P2)
                    thres = np.minimum(thres_p1, thres_p2)

                    if select is None:
                        select = mil_infer_res_blurred[:, class_id - 1] > thres
                    else:
                        select = np.logical_or(select, mil_infer_res_blurred[:, class_id - 1] > thres)

                no_selected = True
                for i in range(len(mil_infer_res_blurred)):
                    is_select = select[i]
                    if is_select:
                        x_batch.append(mil_infer_dataset[i])
                        y_batch.append(y)
                        no_selected = False

                if no_selected:
                    x_batch.append(mil_infer_dataset[np.argmin(benign_rate)])
                    y_batch.append(y)

        x_batch = np.array(x_batch) # The batch dimension is large as (self.batch_size * self.mil_k).
        y_batch = np.array(y_batch)

        if self.snapshot_path != None:
            os.makedirs(self.snapshot_path, exist_ok=True)
            img = inverse_preprocess_input(x_batch[0])
            img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
            cv2.imwrite(
                os.path.join(self.snapshot_path, "mil_top_patch_snapshot.tiff"),
                img_bgr,
            )

        return x_batch, y_batch

A: Same problem here, in Anaconda 2021-11 and using mpi4py version  3.1.3 (installed via conda-forge) I get
Traceback (most recent call last):
  [...]
    from Utils.mpi import *
  [..]
    from mpi4py import MPI
ImportError: libmpi.so.12: cannot open shared object file: No such file or directory

but it used to work under an older Anaconda version. Seem that there is a mismatch between installed mpi library versions (libmpi.so.40) and the version wanted by mpi4py.
Looking for version 12 does not give me a hint of what to do
$ find / -iname 'libmpi.so.*' 2>/dev/null
find / -iname 'libmpi.so.*' 2>/dev/null
/usr/lib/x86_64-linux-gnu/openmpi/lib/libmpi.so.40.20.3
/usr/lib/x86_64-linux-gnu/libmpi.so.40
/usr/lib/x86_64-linux-gnu/libmpi.so.40.20.3
/home/xxx/.conda/pkgs/openmpi-4.0.2-hb1b8bf9_1/lib/libmpi.so.40
/home/xxx/.conda/envs/myy5/lib/libmpi.so.40
/home/xxx/.conda/envs/myy5/lib/libmpi.so.40.20.2
/opt/anaconda-2021.11/pkgs/mpich-3.3.2-hc856adb_0/lib/libmpi.so.12.1.8
/opt/anaconda-2021.11/pkgs/mpich-3.3.2-hc856adb_0/lib/libmpi.so.12

..that is, there is a libmpi.so.40, some in user installed conda paths (.conda/pkgs' and .conda/envs') and a correct version in the system path for my anaconda 2021-11 setup
/opt/anaconda-2021.11/pkgs/mpich-3.3.2-hc856adb_0/lib/libmpi.so.12
However, beforehand I tried both a pip and conda install of mpi4py (and conda install both systemwide and in the myy5 environment)...so conclusion is a bit tricky here.
The neede library libmpi.so.12 found in /opt/anaconda-2021.11/pkgs/mpich is still not found and loaded, when running Anaconda but a manual soft-link in
/opt/anaconda-2021.11/lib
as
$ cd /opt/anaconda-2021.11/lib
$ sudo ln -s /opt/anaconda-2021.11/pkgs/mpich-3.3.2-hc856adb_0/lib/libmpi.so.12

could be a temporary solution with the caveat, that the versions 12 and 40 may not be 100% compatible...
It used to work in my older setup , the version-12 error is new for me (or I forgot any hack applied earlier to make it work...)


text:
Q: How to post to a page using FB.ui()? I am trying to replicate the "share" functionality provided by the "share" link under a wall post: The dialog shows a dropdown box at the top allowing me to choose whether to post to my timeline, in a group, the wall of a page I manage (etc).
Ideally I'd like to able to do this without having to get extended permissions from the user. So I tried FB.ui() but could only get "Post to your wall" to post to the user's timeline. It doesn't have the same dropdown box at the top.
Accordiong to the doc I should be able to provide a page id as the "from" parameter to enable users to use the dialog to post to a page (assuming they are admins of the page). So I tried this but I always get the same "Post to your wall" dialog (even tho I'm admin of the page given).
The doc page contains a link How can I use the Feed Dialog to post on a Facebook Fan Page wall not liked by the user? but it's a dead link :-[
So can it be done using the dialog? Or do I have to get "manage_pages" permission and post to /pageId/feed (as here)?
Thanks!

A: Well it seems today I can do it using the feed dialog after all. I tried apage based on the example in the doc added my page id as the "from" parameter and it works.
I need to be logged on as a page admin, but I don't need to be "using Facebook as" the page.


text:
Q: C++ Game State System Okay: I'm fairly new to C++ and static languages on a whole. Coming from years of ruby (and other dynamic languages) I don't know if this is possible.
I've been making a game state system for... well a game. I want to make the system easy for me to cut and paste into other games without any (or very few) changes.
The two things I am wanting to improve are the way in which states switch and the way in which state pointers are held.
There could be any number of states, but there will always be at least 2 to 3 states active in memory.
Ugliness No 1.
Currently I have a state manager class with something like this in it:
void StateManager::changeState(StateID nextStateID)
{
    // UNFOCUS THE CURRENT STATE //
    if (currentState())
    {
        currentState()->onUnFocus();

        // DESTROY THE STATE IF IT WANTS IT //
        if(currentState()->isDestroyedOnUnFocus()) {
            destroyCurrentState();
        }
    }

    if (m_GameStates[nextStateID]) {
        // SWITCH TO NEXT STATE //
        setCurrentState(nextStateID);
    }
    else
    {
        // CREATE NEW STATE //
        switch (nextStateID)
        {
        case MainMenuStateID:
            m_GameStates[MainMenuStateID] = new MainMenuState;
            break;
        case GameStateID:
                        m_GameStates[MainMenuStateID] = new GameStates;
            break;
        };
        setCurrentState(nextStateID);
    }

    // FOCUS NEXT STATE //
    currentState()->onFocus();
}

This approach works but I don't feel it's very nice.
Is it possible to pass a type? And then call new on it?
new NextGameState;  // Whatever type that may be.

Can poloymophism help here? All States are derived from a class State.
Ugliness No 2.
Another thing I think needs some improvement is the way I've been storing the states.
State* m_GameStates[MaxNumberOfStates];

All the states are initialized to NULL, so I can test if a state is there, and if not it creates one when needed.
It works well as I can call the current state:
m_GameStates[m_CurrentState];

However, I don't like this for two reasons.  It seems a bit of a waste having an array full of NULL pointers when there will only be 2 or 3 pointers active at any one time. [Editor's note: what is the second reason?]
I thought about shifting this into a vector_ptr, but didn't as it would create extra complications with checking to see if a state exists. And the vector seems to reinforce Ugliness No 1. as I need to have a list to check each state.
Any advice or direction appreciated.
Thanks,
Phil.

A: Use a enum(eration) to define all possible states (its something like a list with constants).
Just create for one object one variable that holds the state and change the variable whenever you need to change it.

A: As soon as you say States, I think of the State pattern.
Basically, you can derive a bunch of objects from a State base class.  All actions related to a state occur against the current state maintained by the state manager.  States will move from state to state via the manager.
For instance, you can have a Paused and Unpaused state, each with a buttonPressed event.  When you press a button, the current state is delivered the event.  If it's in Paused, and the button was the pause button, move to Unpaused.  Vice versa for Unpaused.

A: void StateManager::changeState(StateID nextStateID)
{
     leaveState(actualState);
     enterState(nextStateID);
}

I really like this one - as easy as it could be. ;-)
What I want to tell you - I think doing creation/deleting your stats in the changeState Function is too much of logic in there - it just is supposed to change the state, right?
Edit:
To come to your 2 question - I don't think using this array is really a waste - you are talking about 3 fields, not 300 or so. So if you like using arrays - go for it. If you don't, the map would be my choose, it makes things easy if you want to check if there is a state created or not and you are not limited to a magic number "maxStates". You could possible check if there is enough ram and then create X states, not fixed 2-3.

A: For generating states you want a factory. That way the state id stays nice an generic.  For storing states I would go with a std::map

A: For your first problem, yes, you can pass in a type, with some caveats.
I've added a comment under your question, asking for a bit more information. Until we get that, I can't really say how it should be done, but read up on templates.
You can make a function template, which can be passed a type, for example like this:
template <typename T>
void Foo() {
  T* x = new T();
  ...
}

Foo<int>() // call Foo with the type T set to 'int'

There are some limitations to this, as the types have to be specified at compile-time, but it is a very powerful language feature.
Another option, which might work better since you seem to have an association between a variable (MainState) and a type (MainMenu), might be the use of traits classes. Again, I'm unsure of exactly how it'd be done in your case, since we haven't seen the entirety of the function (in particular, what type is MainState, and how/when is it created?)
It might also be possible to solve the problem through polymorphism, but again, I'd need to see a bit more of the context to suggest a solution.
For your second problem, you can use the standard library map:
#include <map>

// I'm not sure what type m_CurrentState is, so use its type instead of KeyType below
std::map<KeyType, State*> m_GameStates;

// and to perform a lookup in the map:
GameStates[m_CurrentState];

Finally, a really really important bit of advice:
Stop using pointers everywhere. Stop calling new to create new objects.
As a general rule, objects should be created on the stack (Instead of Foo* f = new Foo;, just do Foo f;
And instead of using pointers, you'll often want to just copy the object itself. Alternatively, create references instead of pointers.
And when you do need to use dynamic memory allocations, you still shouldn't use new directly. Instead, create a wrapper object, which internally allocates what it needs with new in its constructor, and frees it again in the destructor.
If you do this correctly, it pretty much solves all the headaches of memory management.
The general technique is called RAII.

A: Take a look at Boost Statechart Library


text:
Q: Jackson - deserialize json into generic type I have a model that looks like this:
@JsonIgnoreProperties(ignoreUnknown = true)
public class InputMessage<T> {

    @JsonProperty("UUID")
    private String UUID;

    @JsonProperty("MessageType")
    private String messageType;

    @JsonProperty("KeyData")
    private T keyData;

    ...

    getters/setters
}

This will be in a library that will be called from arbitrary clients, so the KeyData field has a generic type. If I try to make a call like the following from the client code, I get a ClassCastException java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class model.KeyData:

Edit :
Try with constructParametricType() advise but always an error.
ObjectMapper objectMapper = new ObjectMapper();
JavaType type = objectMapper.getTypeFactory().constructParametricType(InputMessage.class, KeyData.class);
KeyData keyData = objectMapper.readValue(inputMessage.getKeyData().toString(), type);

The json that I'm attempting to deserialize looks like this:
{
  UUID: 9bae9a6a-5553-4716-8a85-995f36df7732,
  KeyData: {
    CNSM_ID: 2,
    LGCY_SRC_ID: 123,
    PARTN_NBR: 1,
    PCD_EFF_DT: 2019-01-01,
    SRC_CD: AB
  },
  MessageType: provider_selection,
  Partition: 3,
  Rows: [
    {
      Type: l_cov_prdt_pcd_w_srch,
      SchemaID: 2,
      Value: base64encoded value
    }
  ]
}

The library I'm using to deserialize the json is com.fasterxml.jackson.core:jackson-databind:2.9.8
Any help with this would be greatly appreciated.

A: When you deserialize a JSON to a generic class, Jackson cannot guess the generic type used since that is not an information present in the JSON.
And when it doesn't know how to deserialize a field, it uses a java.util.LinkedHashMap as target.
What you want is a generic type such as :
InputMessage<KeyData> inputMessage = ...;
KeyData keyData = inputMessage.getKeyData();

An elegant way to solve that is defining a Jackson JavaType for the class by specifying the expected generic.
TypeFactory.constructParametricType(Class parametrized, Class... parameterClasses) allows that.
Supposing you want to deserialize to InputMessage<KeyData>, you can do :
JavaType type = mapper.getTypeFactory().constructParametricType(InputMessage.class, KeyData.class);
InputMessage<KeyData> keyData = mapper.readValue(json, type);

About your comment :

The library code with the generic type knows nothing about the
  KeyData class, so I assume it belongs in the client code?

The library doesn't need to know this class but clients should however pass the class to perform correctly the deserialization and to return a generic instance to the client and not a raw type.
For example, clients could use the library in this way :
InputMessage<KeyData> inputMessage = myJsonLibrary.readValue("someValueIfNeeded", KeyData.class);


text:
Q: Java RPi GPIO issue at runtime My Code Is This
package me.Andrew.Keypad.Listener;

import java.util.HashMap;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;

import me.Andrew.Keypad.Main;

public class ButtonInput {
    public boolean isRunning = false;
    public GpioController gpio = GpioFactory.getInstance();
    Main MA = Main.getInstance();

    public HashMap<String, GpioPinDigitalInput> ColPins = null;
    public HashMap<String, GpioPinDigitalOutput> RowPins = null;

    public void start() {
        isRunning = true;
        ButtonListener();
    }

    public void stop() {
        isRunning = false;
    }

    private int ScanRow(int row) {
        int Col = 0;
        RowPins.get(String.valueOf(row)).high();
        if (ColPins.get("1").isHigh()) {
            Col = 1;
        } else if (ColPins.get("2").isHigh()) {
            Col = 2;
        } else if (ColPins.get("3").isHigh()) {
            Col = 3;
        } else if (ColPins.get("4").isHigh()) {
            Col = 4;
        }
        return Col;
    }

    private void ButtonListener() {

        Main.GPIOMeths.setupPins();
        RowPins = Main.store.RowPins;
        ColPins = Main.store.ColPins;

        int Response = 0;

        while (isRunning == true) {
            if (isRunning) {
                Response = ScanRow(1);

                if (Response == 1) {
                    stop();
                    buttonPressEvent("1");
                    break;
                }else if (Response == 2) {
                    stop();
                    buttonPressEvent("2");
                    break;
                }else if (Response == 3) {
                    stop();
                    buttonPressEvent("3");
                    break;
                }else if (Response == 4) {
                    stop();
                    buttonPressEvent("A");
                    break;
                }

                int Responsee = ScanRow(2);
                if (Responsee != 0) {
                    stop();
                    String BP = Main.Meths.getButton(2, Responsee);
                    buttonPressEvent(BP);
                    break;
                }

                int Responseee = ScanRow(3);
                if (Responseee != 0) {
                    stop();
                    String BP = Main.Meths.getButton(3, Responseee);
                    buttonPressEvent(BP);
                    break;
                }

                int Responseeee = ScanRow(4);
                if (Responseeee != 0) {
                    stop();
                    String BP = Main.Meths.getButton(4, Responseeee);
                    buttonPressEvent(BP);
                    break;
                }
            }

        }
    }

    public void buttonPressEvent(String ButtonPressed) {
        // String ButtonPressed = Main.Meths.getButton(Row, Col);
        if (ButtonPressed.equalsIgnoreCase("*")) {
            System.out.println("Code Logging Started");
            Main.store.CodeMode = true;
            Main.store.CodeEntered = "";
        } else if (ButtonPressed.equalsIgnoreCase("#")) {
            System.out.println("Code Logging Ended");
            if (Main.Meths.CompareCodes()) {
                System.out.println("Code Correct");
            } else {
                System.out.println("Code Incorrect");
            }
            Main.store.CodeMode = false;
        } else {
            if (Main.store.CodeMode == false) {
                System.out.println("Code Logging Not Running: " + ButtonPressed);
            } else {
                Main.store.CodeEntered = Main.store.CodeEntered + ButtonPressed;
                System.out.println("Code Entered: " + Main.store.CodeEntered);
            }
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        } finally {
            start();
        }

    }
}

But when i run it and press 1,2,3,A All of the top row i get this response
root@raspberrypi:/home/pi# java -jar /home/pi/keypad.jar
Code Logging Not Running: 7
Code Logging Not Running: 0
Code Logging Not Running: 9
Code Logging Not Running: A
Code Logging Not Running: 7
Code Logging Not Running: 5
Code Logging Not Running: 3
Code Logging Not Running: A

A: Added
RowPins.get(String.valueOf(row)).low();

At the end of scan row


text:
Q: Expected a value of type 'ProductList', but got one of type '_Future' I am trying to consume a rest api data returning a list of maps each map contain product details, so i code classes for product as well as productList with fromJsom method implemented, then i am trying to dispaly thoes products in my flutter app with list.generate but got the error "Expected a value of type 'ProductList', but got one of type '_Future'"
here is the function responsible of api call, its return a Future of type ProductList:
Future<ProductList> loadProductsByIdService(_serviceid) async {

  var datamap = {'service_id': _serviceid};
  var data = json.encode(datamap);
  ProductList products;

  final response = await http.post(Uri.parse(PRODUCTS),
      headers: {
        "Accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
      },
      body: data,
      encoding: Encoding.getByName("utf-8"));

  if (response.body.isNotEmpty) {

    if (response.statusCode == 200) {
      products = ProductList.fromJson(json.decode(response.body));

    }

  } else {
    throw Exception('echec de chargement des produits');
  }

  return products;
}

and here the class responsible of displaying products
class PopularProducts extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var products = loadProductsByIdService(1) as ProductList;

    return Column(
      children: [
        Padding(
          padding:
              EdgeInsets.symmetric(horizontal: getPropotionalScreenWidth(20)),
          child: SectionTitle(title: "Produits à la Une", press: () {}),
        ),
        SizedBox(height: getPropotionalScreenWidth(20)),
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            children: [
              ...List.generate(
                products.products.length,
                (index) {
                  return ProductCard(product: products.products[index]);
                },
              ),
              SizedBox(width: getPropotionalScreenWidth(20)),
            ],
          ),
        )
      ],
    );
  }
}

also i am getting this error alongside:
"errors.dart:187 Uncaught (in promise) Error: FormatException: SyntaxError: Unexpected end of JSON input"

A: You are trying to paint the data before you get it.  You must wrap your column in a futureBuilder to wait for that data.
return FutureBuilder<ProductList>(
      future: loadProductsByIdService(1),
      builder: (context, snapShot) {
        if (snapshot.hasData) {
          return Column(
            children: [
              Padding(
                padding:
                    EdgeInsets.symmetric(horizontal: getPropotionalScreenWidth(20)),
                child: SectionTitle(title: "Produits à la Une", press: () {}),
              ),
              SizedBox(height: getPropotionalScreenWidth(20)),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    ...List.generate(
                      snapShot.products.length,
                      (index) {
                        return ProductCard(product: snapShot.products[index]);
                      },
                    ),
                    SizedBox(width: getPropotionalScreenWidth(20)),
                  ],
                ),
              )
            ],
          );
        } else {
          return SizedBox();
        }
      },
    );

A: Because, you have to await that data. Or, use FutureBuilder to get that data, which is the best option for me.


text:
Q: Login facebook with ParseFacebookUtil.login() return null user and exception invalid date I followed instruction to setup my android project with correct app_id, parse_app_id, parse_client_id. And even using ParseUI for Android to sign up a new account & logged-in. But facebook login just doesn't work!
Here's my settings(UPDATED to Parse-1.9.1 & Facebook v4.0.1):
In my app the build.gradle:
compile project(':ParseLoginUI')
compile 'com.facebook.android:facebook-android-sdk:4.0.1'

In the ParseLoginUI project its build.gradle(not change just copied from repo):
    dependencies {
        compile 'com.parse.bolts:bolts-android:1.2.0'
        compile 'com.android.support:support-v4:22.0.0'

        provided 'com.facebook.android:facebook-android-sdk:4.0.1'
        // This assumes that your app's project has a compile dependency on the Parse SDK JAR files.
        // Your project's build.gradle should say:
        //
        //     compile files('YOUR_PROJECT_LIBS_PATH/Parse-1.9.1.jar')
        //     compile files('YOUR_PROJECT_LIBS_PATH/ParseFacebookUtilsV4-1.9.1.jar')
        //
        // Since the dependency below is "provided" instead of "compile", your project's build.gradle
        // does not have to refer to the same Parse SDK instance that's in the ParseLoginUI/libs folder.
        provided files("$rootProject.projectDir/ParseLoginUI/libs/Parse-1.9.1.jar")
        provided files("$rootProject.projectDir/ParseLoginUI/libs/ParseFacebookUtilsV4-1.9.1.jar")
    }

Clicking login button will run:
facebookLoginButton = (Button) view.findViewById(R.id.fb_auth_button);
facebookLoginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        onLoadingListener.onLoadingStart(false); // Facebook login pop-up already has a spinner

        if (config.isFacebookLoginNeedPublishPermissions()) {
            ParseFacebookUtils.logInWithPublishPermissionsInBackground(getActivity(),
                    config.getFacebookLoginPermissions(), facebookLoginCallbackV4);
        } else {
            ParseFacebookUtils.logInWithReadPermissionsInBackground(getActivity(),
                    config.getFacebookLoginPermissions(), facebookLoginCallbackV4);
        }
    }
});

private LogInCallback facebookLoginCallbackV4 = new LogInCallback() {
    @Override
    public void done(ParseUser user, ParseException e) {
        if (isActivityDestroyed()) {
            return;
        }

        if (user == null) {
            //loadingFinish();
            if (e != null) {
                Logger.d(getString(com.parse.ui.R.string.com_parse_ui_login_warning_facebook_login_failed) +
                        e.toString());
            }
            UIUtils.getSoldaToast(
                    getActivity(),
                    getString(com.parse.ui.R.string.com_parse_ui_facebook_login_failed_toast),
                    Gravity.CENTER).show();
        } else if (user.isNew()) {
            GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject fbUser,
                                                GraphResponse response) {
              /*
                If we were able to successfully retrieve the Facebook
                user's name, let's set it on the fullName field.
              */
                            ParseUser parseUser = ParseUser.getCurrentUser();
                            if (fbUser != null && parseUser != null
                                    && fbUser.optString("name").length() > 0) {
                                parseUser.put(USER_OBJECT_NAME_FIELD, fbUser.optString("name"));
                                parseUser.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(ParseException e) {
                                        if (e != null) {
                                            Logger.d(getString(
                                                    com.parse.ui.R.string.com_parse_ui_login_warning_facebook_login_user_update_failed) +
                                                    e.toString());
                                        }
                                        loginSuccess();
                                    }
                                });
                            }
                            loginSuccess();
                        }
                    }
            ).executeAsync();
        } else {
            loginSuccess();
        }
    }
};

It always return null user & ParseException said invalid date:

checkout the doc but still don't know what I did wrong.
BTW, I'm sure I DO comment out Parse.enableLocalDatastore(this); to make it's not because of this bug. And the only facebook permission I request is email so the call would be
ParseFacebookUtils.logInWithReadPermissionsInBackground(
        getActivity(),
        config.getFacebookLoginPermissions(),
        facebookLoginCallbackV4
);

After update to latest version of ParseUI-android, the issue still occur.
Anyone experience this?

A: Finally I got this solved! Friend suggest me to delete the app from my facebook account to make sure starting fresh. And then uninstall the Android app to re-install again. BOOOM! it works! Thank you Faceboooook.
Hope this helps!


text:
Q: Why did only Red and Gold Squadrons return to Yavin IV? In Rogue One: A Star Wars Story, we see that Red and Gold Squadrons are present at the battle of Scarif (and thanks stock footage and digital editing, Gold Leader and another pilot or two are there).
However in A New Hope, we see Red and Gold Squadron are present to help at the Battle of Yavin, but not Blue Squadron or any of the capital ships (they are not in orbit above Yavin IV). Why didn't these return with Gold Squadron to Yavin IV?

A: It seems that almost[1] all the capital vessels were destroyed in the fight above Scarif except Profundity (one or two jumped to hyperspace in the movie shot). From Chapter 22 of Freed's official novelization:

The Profundity trembled under the onslaught of TIE fighters. Its shields burst, re-formed, and burst again as emerald volleys struck. Three decks had already been forced to evacuate due to radiation leakage. But the Profundity endured where other vessels had been torn apart; in geostationary orbit above the Scarif Citadel, it was the center of a storm of molten metal and rent ships.

And Profundity was disabled by Vader's Devastator

"The rebel flagship is disabled, my lord," the Devastator's captain reported crisply at Vader's side. Darth Vader did not turn to him as he spoke. "But it has received transmissions from the surface."

[1] - The film shows that 1 or two smaller ships - including a Corellian Corvette that technically is a capital ship - did escape. But....
However, it doesn't matter if any capital ships escaped Scarif - they wouldn't have been used in the battle of Yavin anyway.
From A New Hope script, the rebels clearly understood that capital ships were fully useless against Death Star:
                     DODONNA
                     The battle station is heavily shielded
                     and carries a firepower greater than
                     half the star fleet. It's defenses
                     are designed around a direct large-
                     scale assault. A small one-man fighter
                     should be able to penetrate the outer
                     defense.

There's no clear indication of what happened to Blue Squadron, but chances are it was largely destroyed, first trying to open the gate, then, during fighting, then in Death Star turbolaser, since it was under the shield, fighting.

"This is Admiral Raddus. Red and Gold Squadrons, engage those two Star Destroyers. Blue Squadron, get to the surface before they close that gate!"
"What about Profundity, Admiral?" the tactical officer called.
  "We cover Blue Squadron," Raddus said, and jutted a finger at the viewport. "We target the shield gate."
General Merrick, too, might have disagreed, but he had led Blue Squadron through the gate to Scarif, and now starfighter command fell to Raddus as well.


text:
Q: Android Java Socket. Can't send message to server Alright first off all, I'm fairly new to java and android coding. I'm working with socket.  Just want to know my client didn't send the message to server.I've already set permission to manifest like this.
<uses-permission android:name="android.permission.INTERNET" / >
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE"
/ >
This is the logcat error.
2021-06-22 21:36:23.635 3273-3273/com.example.charactercounter I/System.out: [socket]:check permission begin!

2021-06-22 21:36:23.635 3273-3273/com.example.charactercounter W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
2021-06-22 21:36:23.637 3273-3273/com.example.charactercounter I/System.out: [socket] e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaUtils

2021-06-22 21:36:23.638 3273-3273/com.example.charactercounter I/System.out: data error here

2021-06-22 21:36:23.638 3273-3273/com.example.charactercounter I/System.out: android.os.NetworkOnMainThreadException

2021-06-22 21:36:39.102 3273-3273/com.example.charactercounter I/Choreographer: Skipped 1 frames!  The application may be doing too much work on its main thread.

2021-06-22 21:36:39.103 3273-3414/com.example.charactercounter I/GED: ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 29, oppidx_max 29, oppidx_min 0

2021-06-22 21:36:43.643 3273-3414/com.example.charactercounter D/Surface: Surface::disconnect(this=0x7a8c40c000,api=1)

2021-06-22 21:36:43.663 3273-3273/com.example.charactercounter V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@28a3868, this = DecorView@5597d05[MainActivity]

2021-06-22 21:36:43.713 3273-3273/com.example.charactercounter I/Choreographer: Skipped 2 frames!  The application may be doing too much work on its main thread.

This is my server code !
            @Override
    protected Void doInBackground(Void... params) {
        Log.d("STATE", "onClick: This been clicked");
        TextView connection = findViewById(R.id.connection);
        TextView connection1 = findViewById(R.id.out_put_data);
        try {
            ServerSocket server_socket=new ServerSocket(7777);
            connection.setText("Server running on port:"+ server_socket.getLocalPort());

            Socket socket_name=server_socket.accept();//establishes connection
            DataInputStream dis=new DataInputStream(socket_name.getInputStream());
            String str= dis.readUTF();
            count_OccurrencesStr(str);
            server_socket.close();
        } catch (Exception e) {
            Log.d("Error", "onClick: Error on connecting server");
            System.out.println(e);
        }
        return null;
    }

And this is my client code
 public void submit(){
    TalkToServer tserver = new TalkToServer();
    tserver.execute();
    Button submit = findViewById(R.id.submit_btn);
    TextView text_output = findViewById(R.id.out_put_data);
    EditText editText = findViewById(R.id.data_field);

    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                System.out.println("data error here");
                Socket s = new Socket("127.0.0.1",7777);
                System.out.println("data error here1");
                DataOutputStream dout=new DataOutputStream(s.getOutputStream());
                String msg = "abbccc";
                dout.writeUTF(msg);
                dout.flush();
                dout.close();
                s.close();
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("data error here");
                System.out.println(e);
            }
        }
    });
}

A: All I just need is to put new Thread inside Onclick function like this
public void submit(){
        Button submit = findViewById(R.id.submit_btn);
        TextView text_output = findViewById(R.id.out_put_data);
        EditText editText = findViewById(R.id.data_field);

        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("data error here");
                            Socket s = new Socket("127.0.0.1",7777);
                            System.out.println("data error here1");
                            DataOutputStream dout=new DataOutputStream(s.getOutputStream());
                            String msg = "abbccc";
                            dout.writeUTF(msg);
                            dout.flush();
                            dout.close();
                            s.close();
                        } catch (Exception e) {
                            // TODO: handle exception
                            System.out.println("data error here");
                            System.out.println(e);
                        }
                    }
                }).start();

            }
        });
    }

Thanks to https://android-developers.googleblog.com/2009/05/painless-threading.html


text:
Q: Matplotlib / PyQT4: transparent figure I am using Python with PyQt4 and I want to embed a matplotlib figure in the GUI.
What's important to me, is that the background of the Figure matches the background color of the GUI. (no grey background around the actual plot)
My partial solution would be to make the Figure transparent with the following code:
...
fig.patch.set_alpha(0.5)
...

This works fine when plotting in pylab mode, but when embedding in PyQt4, the re-rendering doesn't clear the old figure, but adds it with on top with transparency I give. As seen in the sample below, which is the result of resizing the window:

The sample was produced using the code from the matplotlib website with adding the set_alpha(0.5) line in the __init__ statement of MyMplCanvas.

A: You have found an interesting bug in matplotlib.  The Qt4 backend does not clear the qImage it uses to display the figure before redrawing, hence the reason you see the shadows.  This is easily fixed by adding a few lines to matplotlib.backends.backed_qt4Agg.FigureCanvasQTAgg.paintEvent
def paintEvent(self, e):
    """
    Copy the image from the Agg canvas to the qt.drawable.
    In Qt, all drawing should be done inside of here when a widget is
    shown onscreen.
    """

    #FigureCanvasQT.paintEvent(self, e)
    if DEBUG:
        print('FigureCanvasQtAgg.paintEvent: ', self,
            self.get_width_height())

    if self.blitbox is None:
        # matplotlib is in rgba byte order.  QImage wants to put the bytes
        # into argb format and is in a 4 byte unsigned int.  Little endian
        # system is LSB first and expects the bytes in reverse order
        # (bgra).
        if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian:
            stringBuffer = self.renderer._renderer.tostring_bgra()
        else:
            stringBuffer = self.renderer._renderer.tostring_argb()

        refcnt = sys.getrefcount(stringBuffer)

        qImage = QtGui.QImage(stringBuffer, self.renderer.width,
                              self.renderer.height,
                              QtGui.QImage.Format_ARGB32)
        rect = qImage.rect()    ### <-- added this line
        p = QtGui.QPainter(self)
        p.eraseRect(rect)       ### <-- added this line
        p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage))

        # draw the zoom rectangle to the QPainter
        if self.drawRect:
            p.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.DotLine))
            p.drawRect(self.rect[0], self.rect[1],
                       self.rect[2], self.rect[3])
        p.end()

        # This works around a bug in PySide 1.1.2 on Python 3.x,
        # where the reference count of stringBuffer is incremented
        # but never decremented by QImage.
        # TODO: revert PR #1323 once the issue is fixed in PySide.
        del qImage
        if refcnt != sys.getrefcount(stringBuffer):
            _decref(stringBuffer)
    else:
        bbox = self.blitbox
        l, b, r, t = bbox.extents
        w = int(r) - int(l)
        h = int(t) - int(b)
        t = int(b) + h
        reg = self.copy_from_bbox(bbox)
        stringBuffer = reg.to_string_argb()
        qImage = QtGui.QImage(stringBuffer, w, h,
                              QtGui.QImage.Format_ARGB32)
        pixmap = QtGui.QPixmap.fromImage(qImage)
        p = QtGui.QPainter(self)
        p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap)
        p.end()
        self.blitbox = None
    self.drawRect = False

Changes in diff form:
diff --git a/lib/matplotlib/backends/backend_qt4agg.py b/lib/matplotlib/backends/backend_qt4agg.py
index 8433731..718d352 100644
--- a/lib/matplotlib/backends/backend_qt4agg.py
+++ b/lib/matplotlib/backends/backend_qt4agg.py
@@ -118,7 +118,9 @@ class FigureCanvasQTAgg(FigureCanvasQT, FigureCanvasAgg):
             qImage = QtGui.QImage(stringBuffer, self.renderer.width,
                                   self.renderer.height,
                                   QtGui.QImage.Format_ARGB32)
+            rect = qImage.rect()
             p = QtGui.QPainter(self)
+            p.eraseRect(rect)
             p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage))

             # draw the zoom rectangle to the QPainter

You can either modify your local installation or monkey patch it in your code.
PR #2449 which has been merged and will be in 1.3.1


text:
Q: Nodejs File Search from Array of Filenames I am attempting to do a file search based off array of file names and root directory.  I found some file search snips online that seem to work when I am finding just 1 single file, but it will not work when there is more than 1 file specified.  Below is the snippet:

const fs = require('fs');

const path = require('path');
var dir = '<SOME ROOT DIRECTORY>';
var file = 'Hello_World.txt'
var fileArr = ['Hello_World.txt', 'Hello_World2.txt', 'Hello_World3.txt'];

const findFile = function (dir, pattern) {
    var results = [];
    fs.readdirSync(dir).forEach(function (dirInner) {
        dirInner = path.resolve(dir, dirInner);
        var stat = fs.statSync(dirInner);
        if (stat.isDirectory()) {
            results = results.concat(findFile(dirInner, pattern));
        }
        if (stat.isFile() && dirInner.endsWith(pattern)) {
            results.push(dirInner);
        }
    });
    return results;
};

console.log(findFile(dir, file));

Any thoughts on how I can get this working with an array rather than just a single file string?
Doing the following seems to be working, but didn't know if there were other ways to do this which may be simpler:

newFileArr = [];

fileArr.forEach((file => {
    //findFile(dir, file).toString();
    console.log(findFile(dir, file).toString());
}));

A: The only thing that needs to change is the condition to determine if an individual filepath meets the search criteria. In the code you've posted, it looks like dirInner.endsWith(pattern), which says "does the filepath end with the given pattern?"
We want to change that to say "does the filepath end with any of the given patterns?" And closer to how the code will look, we can rephrase that as "Can we find a given pattern such that the filepath ends with that pattern?"
Let's rename pattern to patterns. Then we can simple replace dirInner.endsWith(patterns) with patterns.some(pattern => dirInner.endsWith(pattern))


text:
Q: How can I close an image shown to the user with the Python Imaging Library? I have several images which I would like to show the user with Python. The user should enter some description and then the next image should be shown.
This is my code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, glob
from PIL import Image

path = '/home/moose/my/path/'
for infile in glob.glob( os.path.join(path, '*.png') ):
    im = Image.open(infile)
    im.show()
    value = raw_input("Description: ")
    # store and do some other stuff. Now the image-window should get closed

It is working, but the user has to close the image himself. Could I get python to close the image after the description has been entered?
I don't need PIL. If you have another idea with another library / bash-program (with subprocess), it'll be also fine.

A: I've modified this recipe before to do some image work in Python.  It uses Tkinter, so it doesn't require any modules besides PIL.
'''This will simply go through each file in the current directory and
try to display it. If the file is not an image then it will be skipped.
Click on the image display window to go to the next image.

Noah Spurrier 2007'''
import os, sys
import Tkinter
import Image, ImageTk

def button_click_exit_mainloop (event):
    event.widget.quit() # this will cause mainloop to unblock.

root = Tkinter.Tk()
root.bind("<Button>", button_click_exit_mainloop)
root.geometry('+%d+%d' % (100,100))
dirlist = os.listdir('.')
old_label_image = None
for f in dirlist:
    try:
        image1 = Image.open(f)
        root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
        tkpi = ImageTk.PhotoImage(image1)
        label_image = Tkinter.Label(root, image=tkpi)
        label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
        root.title(f)
        if old_label_image is not None:
            old_label_image.destroy()
        old_label_image = label_image
        root.mainloop() # wait until user clicks the window
    except Exception, e:
        # This is used to skip anything not an image.
        # Warning, this will hide other errors as well.
        pass

A: psutil can get the pid of the display process created by im.show() and kill the process with that pid on every operating system:
import time

import psutil
from PIL import Image

# open and show image
im = Image.open('myImageFile.jpg')
im.show()

# display image for 10 seconds
time.sleep(10)

# hide image
for proc in psutil.process_iter():
    if proc.name() == "display":
        proc.kill()

A: The show method "is mainly intended for debugging purposes" and spawns an external process for which you don't get a handle, so you can't kill it in a proper way.
With PIL, you may want to use one of its GUI modules , such as ImageTk, ImageQt  or ImageWin.
Otherwise, just manually spawn an image viewer from Python with the subprocess module:
for infile in glob.glob( os.path.join(path, '*.png')):
    viewer = subprocess.Popen(['some_viewer', infile])
    viewer.terminate()
    viewer.kill()  # make sure the viewer is gone; not needed on Windows


text:
Q: Не корректно отображaется цвет фона html&css
Верхняя часть. Вставлена фоновая фотография и также прописан цвет  черный
background:#000 url("") no-repeat.
Но фоновая фотография заканчивается, а цвет не отображается. Не понимаю почему?
Вот код — но в нем нет фотографии поэтому выглядит все корректно.
Но на оригинальном сайте фон не отображается
body {
    margin:0;
    padding:0;
    min-width:960px;
    max-height:1800px;
    text-transform:uppercase;
    font-size:14px;
    font-weight:bold;
    font-family:'PT Sans', 'sans-serif';
    color:white;
    background:#000 url("../img/bg.jpg") no-repeat 50% 0%;
    max-width:1800px;
}

A:
Если наряду с фоновыми изображениями требуется задать цвет фона
  элемента, он указывается в последнюю очередь после перечисления.

Источник на русском языке и на английском Mozilla.
В этом случае используйте указание цвета фона в конце:
background: url("../img/bg.jpg") no-repeat 50% 0% #000;


text:
Q: React-leaflet custom components, how to extend Polyline from Leaflet? I'm trying to extend a react-leaflet component so I can add custom variables to it.
I need to add an "id" to a Polyline (so when a user clicks on it, I can retrieve the id and make a server call behind to gather data on it). I had to do the same for the markers and found this workaround:
markers = nextProps.buses.map((bus, i) => {
  let iconCustom = new L.Icon.Default({internalId: bus.internalId});
  this.markersDirectAccess[bus.internalId] = {
    ...bus
  };

  return {
    lat: bus.latitude,
    lng: bus.longitude,
    popup: bus.busId,
    options: {icon: iconCustom}
  }
});

I'm not entirely sure if it's the right way to do it. But I'm stuck when it comes to the Polyline component.
I've found this answer and I'd like to apply it to react-leaflet but I don't know how to do it. This is the current state of my extended component :
import L from 'leaflet'
import { Polyline } from 'react-leaflet'
import PropTypes from 'prop-types';

export default class PolylineCustomId extends Polyline {
  static propTypes = {
    positions:  PropTypes.array,
  }

  createLeafletElement (props: Object): Object {
    return L.Polyline(props)
  }
}

A: I don't think you need a custom component for this.  You can simply add a click handler for each polyline that will return it's id.  See this example:
render () {
  const position = [this.state.lat, this.state.lng]
  return (
    <Map center={position} zoom={this.state.zoom}>
      <TileLayer
        attribution='© OpenStreetMap contributors'
        url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
      />
      {this.state.polylines.map(polyline =>
          <Polyline
            key={polyline.id}
            positions={polyline.coords}
            onClick={() => alert('clicked ' + polyline.id)}
            />
        )
      }
    </Map>
  )
}

And here is a jsfiddle with a working example: https://jsfiddle.net/31euue73/1/


text:
Q: nodejs why its chaning timezone of date automatically Here is my node.js code
var app = http.createServer(function(req,res){
        var queryData = url.parse(req.url, true).query;
        res.setHeader('Content-Type', 'application/json');

        var start = new Date(parseInt(queryData.start));
        var end = new Date(parseInt(queryData.end));

        console.log(start);
        console.log(end);
        ....
});
app.listen(3000);
console.log('Server running at 3000');

I am requesting url mywebapp:3000/?start=1391230800000&end=1396324800000
On nodejs console I am getting
Server running at 3000
Sat Feb 01 2014 08:00:00 GMT+0300 (MSK)
Tue Apr 01 2014 08:00:00 GMT+0400 (MSD)
Invalid Date
Invalid Date

Also its looking that console is out putting 4 times, why is that?

A: Node.js is not changing timezone. Your operating system does.

Also its looking that console is out putting 4 times, why is that?

2nd request is for favicon.ico, that's what browsers do

A: You probably have outdated system, since it assumes that in March the clock will advance 1 hour (MSD stands for Moscow Daylight Time). It's actually not an issue, unless you want yo use result of toString directly


text:
Q: How to get Eclipse intro to export correctly? I have an RCP application with an welcome page implementing org.eclipse.ui.intro.config in one of the plugins within a product.  This welcome page works correctly when run from the IDE but fails with a file not found error when running from a PDE export.
java.io.FileNotFoundException: C:\app\introContent.xml (The system cannot find the file specified)
If I copy the introContent.xml to the app directory the error changes to all of the referenced pages.
How can I get an exported RCP app to run the intro?

A: The answer (like most export issues) is to ensure that you have selected the items for export in the build.properties.


text:
Q: gridView definitions for Column headings with mouse hover I have a gridView:-
<asp:GridView ID="gvwAccums" runat="server"
        AutoGenerateColumns="false"
        CssClass="GridView"
        HeaderStyle-CssClass="GridViewHeaderRowStyle"
        RowStyle-CssClass="GridViewRowStyle"
        AlternatingRowStyle-CssClass="GridViewAlternatingRowStyle"
        EmptyDataRowStyle-CssClass="GridEmptyDataRowStyle"
        >
            <Columns>
                <asp:BoundField HeaderText="Start Date" DataField="Beg_PlanYr" />
                <asp:BoundField HeaderText="Paid" DataField="indTotPaid" DataFormatString="{0:F}" HeaderStyle-HorizontalAlign="Right"
                    ItemStyle-HorizontalAlign="Right" />
                <asp:BoundField HeaderText="Copay" DataField="indTotCopay" DataFormatString="{0:F}" HeaderStyle-HorizontalAlign="Right"
                    ItemStyle-HorizontalAlign="Right" />
                <asp:BoundField HeaderText="Deductible" DataField="indTotDed" DataFormatString="{0:F}" HeaderStyle-HorizontalAlign="Right"
                    ItemStyle-HorizontalAlign="Right" />
                <asp:BoundField HeaderText="Out of Pocket" DataField="indTotOop" DataFormatString="{0:F}" HeaderStyle-HorizontalAlign="Right"
                    ItemStyle-HorizontalAlign="Right" />
            </Columns>
            <EmptyDataTemplate>

                    No Accumulated Totals found.

            </EmptyDataTemplate>
        </asp:GridView>

and I am trying to add definition text to its column headers on the server side:-
protected void gvwAccums_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow row = e.Row;
        bool isDataRow = row.RowType == DataControlRowType.DataRow;
        TableCellCollection cells = e.Row.Cells;
        string allCells = string.Empty;
        string content = "";
        int lastCol = cells.Count - 1;

        content = cells[lastCol].Text.Trim();

        // Only do this to the header row, ignore data and footer rows. Adding definition to the label of each column on the Gridview of claims.
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].ToolTip = "xxxxx ";
            e.Row.Cells[1].ToolTip = "yyyyy ";
            e.Row.Cells[2].ToolTip = "zzzzz ";
            e.Row.Cells[3].ToolTip = "fffff ";
            e.Row.Cells[4].ToolTip = "vvvvv ";
        }

    }

However I don't see any text when I hover over with the mouse pointer. The gridview itself works fine.
Can anyone help?

A: Your code work for me - tooltip displays when mouse hovers on Header text.
If still doesn't work, you can try with Attributes.Add
e.Row.Cells[0].Attributes.Add("title", "xxxxx ");

Here is how I test your code

public class Test
{
    public int Beg_PlanYr { get; set; }
    public decimal indTotPaid { get; set; }
    public decimal indTotCopay { get; set; }
    public decimal indTotDed { get; set; }
    public decimal indTotOop { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvwAccums.DataSource = new List<Test>()
        {
            new Test {Beg_PlanYr = 1, indTotPaid = 1, indTotCopay = 1, indTotDed = 1, indTotOop = 1},
            new Test {Beg_PlanYr = 2, indTotPaid = 2, indTotCopay = 2, indTotDed = 2, indTotOop = 2},
            new Test {Beg_PlanYr = 3, indTotPaid = 3, indTotCopay = 3, indTotDed = 3, indTotOop = 3},
        };
        gvwAccums.DataBind();
    }
}

protected void gvwAccums_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].ToolTip = "xxxxx ";
        e.Row.Cells[1].ToolTip = "yyyyy ";
        e.Row.Cells[2].ToolTip = "zzzzz ";
        e.Row.Cells[3].ToolTip = "fffff ";
        e.Row.Cells[4].ToolTip = "vvvvv ";
    }
}


text:
Q: Issue related to horizontal scroll in react-native-snap-carousel I am using carousel from react-native-snap-carousel module to scroll images horizontally from remote urls. it is working fine in android but in case of iOS sometimes the image is getting scrolled, most of the times not.
It is detecting my slide action but the image is not getting scrolled.
I have tried on iOS 13.1.3, react-native 0.59.8, react-native-snap-carousel 3.8.2
Following code is for Carousel
   <Carousel
            borderTopRightRadius={2}
            borderTopLeftRadius={2}
            ref={c => (this._ref = c)}
            data={images}
            renderItem={item => this.renderItem(item)}
            onSnapToItem={index => {
              this.setState({ currentImage: index });
              onSliderMove(index);
            }}
            layout={"default"}
            sliderWidth={parentWidth || width}
            itemWidth={parentWidth || width}
            loop={circleLoop || false}
            contentContainerCustomStyle={{}}
            scrollEnabled={scrollable}
            onStartShouldSetResponderCapture={() => {
              return scrollable;
            }}
            onMoveShouldSetResponderCapture={() => {
              return scrollable;
            }}
            layoutCardOffset={20}
          />

I am using a custom component to load an image.
     renderItem = ({ item, index }) => {
      return (
        <View style={{ width, height }}>
          <LoadableImage
            url={item}
            index={index}
          />
        </View>
       )
      }

Expected results: Horizontal scrolling should work on iOS smoothly.
Actual results: Horizontal scrolling is not working most of the time.
Help me solve this issue

A: I was also facing an issue in scroll with this carousel. I looked into the library and tried the below attributes. You can try after adding the given attributes, they make the scroll smooth. I am not facing any issue after using the below attributes.
Try the last two attributes.
<Carousel
      ref={isCarousel}
      data={options}
      renderItem={renderItem}
      sliderWidth={SLIDER_WIDTH}
      itemWidth={itemWidth || ITEM_WIDTH}
      useScrollView
      activeSlideAlignment="start"
      inactiveSlideScale={1}
      inactiveSlideOpacity={1}
     onSnapToItem={(index) => {console.log(index); setIndex(index)}}
     *enableMomentum={true}
     decelerationRate={0.9}*
   />