text:
Q: Open file and create new frame I want to open .py file - that i have found out - and than from opened file run new frame. This is code in file MenuWindow:
def OnNewGame(self,event):
    play = False
    nameofplr = wx.GetTextFromUser('Enter your name:', 'NEW GAME')
    subor=open("Save/savegame.txt","a")
    subor.write( "\n" + nameofplr)
    subor.close()
    savegame=open("Save/" + nameofplr + ".prjct", "w+")
    savegame.close()
    play = True
    if (play == True):
        sys.path.insert(0, './bin')
        import game
        new = GameFrame(parent=None, id=-1)
        new.Show()
        self.Close()

And This is code from game.py:
    print "game.py opened"

import wx
class GameFrame(wx.Frame):
def __init__(self,parent,id):

    wx.Frame.__init__(self, parent, id, "Project", size=(860, 640))
    wx.Frame.CenterOnScreen(self)

Output prints game.py opened so it open the file, but why it doesn´t create new frame?
This is output:

game.py opened
  Traceback (most recent call last):
   File "D:\Python\Python Projects\Project\MenuWindow.py", line 48, in OnNewGame
     new = GameFrame(parent=None, id=-1)
  NameError: global name 'GameFrame' is not defined

A: You import game, and GameFrame is a part of game, so you should type
new = game.GameFrame(parent=None, id=-1)

A: I was searching on internet for about 2 or 3 hours and nothing worked, then i write question here and tried modify code of my own and i have fixed it! So if somebody will have the same problem here is the code for def OnNewGame:
    def OnNewGame(self,event):
    play = False
    nameofplr = wx.GetTextFromUser('Enter your name:', 'NEW GAME')
    subor=open("Save/savegame.txt","a")
    subor.write( "\n" + nameofplr)
    subor.close()
    savegame=open("Save/" + nameofplr + ".prjct", "w+")
    savegame.close()
    play = True
    if (play == True):
        sys.path.insert(0, './bin')
        from game import GameFrame
        new = GameFrame(parent=None, id=-1)
        new.Show()
        self.Close()

An that´s all it works!!!


text:
Q: Why a tensor object gets a new memory location after repeating the already executed operation? I'm performing a simple addition operation using two tensors.

In the above screenshots, it has been shown that even after performing the same operation twice different memory locations have been allocated to the same result every time, however, this is not the case with plain python code:

So, is it happening because in TensorFlow for every operation it actually generates the computational graph and it doesn't really persist the results which means even when the same operation is executed twice it gives birth to two computational graphs which eventually results in two different memory locations?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to put method in Backgroundworker I have made a method and i wanted it to put it on Backgroundworker with a progressbar in it. this is the first that im working on a Background worker.
here is my Code:
    public void WorkLoad()
    {
        string conStr, sheetName;
        conStr = string.Empty;
        //Get the name of the First Sheet.

        using (OleDbConnection kuneksyon = new OleDbConnection(Excel07ConString))
        {
            using (OleDbCommand utos = new OleDbCommand())
            {
                using (OleDbDataAdapter oda = new OleDbDataAdapter())
                {
                    utos.Connection = kuneksyon;
                    kuneksyon.Open();
                    DataTable dtExcelSchema = kuneksyon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                    kuneksyon.Close();
                    DataTable dt = new DataTable();
                    utos.Connection = kuneksyon;
                    utos.CommandText = "SELECT [Engineer],[SITEID],[SITE NAME],[2G TX Status],[3G TX Status],[WO Status-LTE]  From [" + sheetName + "]";
                    kuneksyon.Open();
                    oda.SelectCommand = utos;
                    oda.Fill(dt);
                    kuneksyon.Close();
                    //Populate DataGridView.
                    ForIssuanceView.DataSource = dt;
                    ForIssuanceView.Columns.Add(" ", " ");
                }
            }
        }
    }

A: Let's assume you have your background worker as a class member:
private BackgroundWorker bw;

When you are going to use it, you create and initialize it:
        bw = new BackgroundWorker();
        bw.WorkerReportsProgress = true;
        bw.ProgressChanged += ProgressChanged;
        bw.DoWork += DoWork;

Then you start it:
        bw.RunWorkerAsync();

You should provide a method to do actual work:
    private static void DoWork(object sender, DoWorkEventArgs e)
    {
        // do your actual work and report percentage whenever you find appropriate
        for (var p = 0; p < 100; p++)
        {
            bw.ReportProgress(p);
        }
    }

You might also provide a method to handle percentage change. It will be called automatically whenever you do ReportProgress on your background worker. Be careful, it gets launched in its own thread, not on your UI thread as you might expect:
    private static void ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // inform the UI that the percentage has been changed
    }


text:
Q: VM disk on ESXi 6.7 is taking more space than actual max size I'm having an issue on my ESXi 6.7, I have few VM on which the disk is taking more space on the host than the actually maximum size I provided to the disk, here is what I see on esx :
Disk on esx and here is what I see when the vm is turned off : Disk vm off and this is inside the VM : Disk space in VM.
As you can see, I create a disk for this vm that have a maximum capacity of 64GB but the disk is currently taking more than 71GB on my host even though the disk is not full, how is this posible? I tried to consolidate my disk and I deleted all the snapshots I had.
The problem is that the disk is growing every day and after a while the disk space on my host will be full. I'm currently at 97% even though I designed all my disks to not saturate my host disk space even if all my vm are taking 100% of the disk space.
If anyone could help me, I would be very grateful, my disk is almost full.
Thank you


text:
Q: Werid PHP behaviour when comparing types I have following code:
var_dump($attr['value']);
if ($attr['value'] != 0 && $attr['value'] != null) {
    echo $attr['value'];
    $i++;
}

The problem is that dump tells me the $attr['value'] is 8 characters long string but the if condition fails and the code doesn't show me the value of $attr['value'] inside the if block. Is the condition wrong? I don't want to check the length of the string cause sometimes it can be also 1 character long string.

A: This condition :
if ($attr['value'] != 0)

Verifies if $attr['value'] CONTAINS 0, this is NOT the length of the string.
If you want to verify the string length, modify your code to this :
var_dump($attr['value']);
if (strlen($attr['value']) != 0 && $attr['value'] != null)
{
    echo $attr['value'];
    $i++;
}

strlen($variable) will verify the length of the string :
http://php.net/manual/fr/function.strlen.php
It seems that you are simply checking if the variable is set, in that case, you could simplify your code to this :
var_dump($attr['value']);
if ($attr['value'])
{
    echo $attr['value'];
    $i++;
}

A: try
if(!empty($attr['value'])){

A: Note that any non-numeric string will be converted to 0 when compared to integer unless you use the === operator.
Try this:
var_dump('a' == 0);   // true
var_dump('a' === 0);  // false

The solution you are searching for is:
if(isset($attr['value']) && !empty($attr['value'])) ...


text:
Q: Can Java comments be seen by decompiling? I was wondering if I put comments in my code and when someone tried to decompile it, if they could read the comments that I put?

A: No, comments are never included as part of the compilation process. They are typically removed in some sort of pre-processing, or first-pass stage.

A: Nope, comments are discarded by the compiler.

A: No. And you can verify this by using DJ Java Decompiler, for example. If you also refer to the Java Class File Format, you'll see there's no construct for storing comments.

A: Comments aren't included in the .class files, so a decompiler won't be able to produce them.


text:
Q: org.hibernate.exception.GenericJDBCException @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ICCID", length=100,unique=true, nullable=false)
private String ICCID;
.....

create table DUMMY_DATA(
    ICCID VARCHAR(255) NOT NULL ,
   IMSI  VARCHAR(255) NOT NULL,
   PRIMARY KEY (ICCID)
);

2015-10-29 13:13:09,883  WARN [SqlExceptionHelper] (SqlExceptionHelper.java:145) - SQL Error: 1364, SQLState: HY000
2015-10-29 13:13:09,883 ERROR [SqlExceptionHelper] (SqlExceptionHelper.java:147) - Field 'ICCID' doesn't have a default value
Oct 29, 2015 1:13:09 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/globeconnect] threw exception [Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'ICCID' doesn't have a default value

I am getting the following exception.
i am reading the content from the file and saving in the data base.
ICCID value will be given from file.
Actually I am setting the file content value to ICCID,can u help me out with where i am going wrong.

A: You must configure the hbm2ddl.auto in the hibernate configuration file :
<property name="hbm2ddl.auto">create</property>

after run 1 time the app .
and change it to update , like this :
<property name="hbm2ddl.auto">update</property>

The problem is you have some old values inserted in the table and when you want to change the schema , there is no default value for those old values .


text:
Q: "gunicorn/finish 127. exec: gunicorn: not found" when updating local azure ml deployment in docker Yesterday I was following along a tutorial provided by Azure in deploying machine learning models to endpoints:
https://learn.microsoft.com/en-us/azure/machine-learning/how-to-deploy-online-endpoints?tabs=azure-cli
In this tutorial I ended up successfully deploying a simple linear regression model to a local endpoint with a docker container. However any time I try to update the deployment (i.e. by adding a simple python package dependency in the conda yaml file) and subsequently running:
az ml online-deployment update --local -n blue --endpoint $ENDPOINT_NAME -f endpoints/online/managed/sample/blue-deployment.yml

The container containing model goes into a failed state and logs that exec: gunicorn cannot be found. Using the same command as above works fine for updating the deployment that is actually deployed to azure online (with removing --local). However I would like to develop locally, and redeploying my container for each time my environment changes feels silly. For context the relevant yaml files are provided below, strangely enough in the tutorial I do not touch a docker file. Any thoughts or comments on how to proceed are appreciated!
blue-deployment.yml

$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineDeployment.schema.json
name: blue
endpoint_name: my-endpoint
model:
  path: ../../model-1/model/
code_configuration:
  code: ../../model-1/onlinescoring/
  scoring_script: score.py
environment:
  conda_file: ../../model-1/environment/conda.yml
  image: mcr.microsoft.com/azureml/openmpi4.1.0-ubuntu20.04:latest
instance_type: Standard_DS2_v2
instance_count: 1

conda.yml
name: model-env
channels:
  - conda-forge
dependencies:
  - python=3.8
  - numpy=1.21.2
  - pip=21.2.4
  - scikit-learn=0.24.2
  - scipy=1.7.1
  - pyodbc=4.0.34
  - pip:
    - azureml-defaults==1.47.0
    - inference-schema[numpy-support]==1.5
    - joblib==1.0.1

endpoint.yml
$schema: https://azuremlschemas.azureedge.net/latest/managedOnlineEndpoint.schema.json
name: my-endpoint
auth_mode: key

I tried to update an existing local docker container that contained a sklearn regression model which was originally deployed through Azure cli. I expected the containers environment to be updated with a new dependency such that I could use newly added python packages in my code. However, the container goes into a failed state and cannot be restarted as it fails to find gunicorn. I also tried adding gunicorn as a dependency in the conda.yml but to no avail.


text:
Q: How to return MultipleParams to Javascript using in ios? Hi i want to return image AS Base64sting and Float value's to Javascript using cordova
 ,How to achieve it?
using Json object i am getting
type error:Undefind is not an object and memory exception
After which application just crashes
please help

A: Use your string in the below code and use this code in native to call js function.
NSString * jsCallBack = [NSString stringWithFormat:@"fetchedNativeValues()];
[self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];
Here fetchedNativeValues() is the js function which we are calling from native.
now goto javascript file where fetchedNativeValues(param1,param2) is declared
and fetch the string value and convert that string again into image.
function fetchedNativeValues(param1,param2){
       //you can get these parameters from native like this
}


text:
Q: Instanciar um objeto relacionado a outro objeto C#? Eu tenho duas classes: Categoria e Subcategoria
public class Categoria
{
    public string Nome { get; set; }
    public List<Subcategoria> Subcategoria { get; set; }
}

e a classe sub:
public class Subcategoria
{
    public string Nome { get; set; }
}

Consigo instanciar um objeto de categoria, mas e como eu faço para criar um de subcategoria? Que será dependente de categoria.
E caso eu cadastre mais de um, como faço para percorre-los?
Supondo que eu tenha uma lista de categorias:
List<Categoria> categorias = new List<Categoria>();
categorias.Add(new Categoria { Nome = "FILMES", Subcategoria = })

Observação: não consegui desenvolver para preencher o "subcategoria" e  não sei qual termo utilizar para pesquisar, pois, falando em "relacionamento" de classes, só vem sobre Entity Framework, mas gostaria entender dessa forma, que é a mais simples.

A: Tem várias formas de vc preencher a subcategoria:
Uma delas é:
List<Categoria> categorias = new List<Categoria>();
categorias.Add(new Categoria
{
    Nome = "FILMES",
    Subcategoria = new List<Subcategoria>()
    {
        new Subcategoria() { Nome = "nome1" },
        new Subcategoria() { Nome = "nome2" },
        new Subcategoria() { Nome = "nome3" },
        new Subcategoria() { Nome = "nome4" },
        new Subcategoria() { Nome = "nome5" },
        new Subcategoria() { Nome = "nome6" },
    }
});

A: Existe uma forma simples que uso e sempre dar certo é transforma os objetos em lista e ir adicionando outros objetos;
/No Model ou objeto da classe Filme deve estar +/- dessa forma/
public virtual <List> Caterogias { get; set; }
public string TituloFilme {get; set;}
public string Autor {get; set;}

/Lista de Objetos/
List<Filmes> ListaFilme = new List<Filmes>();
List<Caterogias> ListaCategoria = new List<Categorias>();

/Criar objetos para popular a lista de objetos/
Categorias ObjCategoria = new Categorias
{
   TipoFilme = "Terro",
   DuracaoMinutos = 120,
};

ListaCategoria.add(ObjCategoria);

Filmes objFilme = new Filmes
{
   Titulo = "Crepusculo",
   Autor = "Desconhecido",
   Categoria = ListaCategoria,
};

ListaFilme.add(objFilme);

Dessa forma você consegue de forma organizada a preencher as listas de catergorias e as do Filme, e quando for instanciar se não tiver muitos você mesmo pode criar uma consulta de filmes dentro do código dessa forma. ListaFilme[0].Titulo == "Crepusculo" && ListaFilme[0].Categoria[0].TipoFilme == "Terro".
Espero pode ter ajudado!


text:
Q: Problen add dependency android studio I posted my library in Artifactory
https://imagizer.imageshack.us/v2/806x253q90/631/kkK1Yn.png
this is my Gradle
buildscript {
repositories {
    jcenter()
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0'
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle',
    version: '3.0.1')
    }
}

repositories {
    jcenter()
    mavenCentral()
    mavenLocal()
    maven {
       url 'http://myartifactory:8081/artifactory/gradle-local'
    }
}

apply plugin: 'com.jfrog.artifactory'
apply plugin: 'com.android.library'
apply plugin: 'android-apt'
def AAVersion = '3.2'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

defaultConfig {
    minSdkVersion 14
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

sourceSets {
    main {
    }

}

dependencies {
   compile fileTree(include: ['*.jar', '*.so'], dir: 'libs')
   compile 'com.android.support:recyclerview-v7:21.0.+'
   compile 'com.android.support:appcompat-v7:21.0.+'
   compile 'com.android.support:support-v4:21.0.+'
   compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
   compile 'de.greenrobot:eventbus:2.4.0'
   compile 'com.github.chrisbanes.photoview:library:1.2.3'
   compile 'it.sephiroth.android.exif:library:+'
   compile 'com.joanzapata.android:android-iconify:1.0.8'
   compile 'com.android.support:cardview-v7:21.0.+'
   compile 'com.afollestad:material-dialogs:0.6.0'
   compile 'com.github.lzyzsd:circleprogress:1.0.1@aar'
   apt "org.androidannotations:androidannotations:$AAVersion"
   compile "org.androidannotations:androidannotations-api:$AAVersion"
   compile(group: 'com.mylibrary.android.common', name: 'android.common', version: '1.0.0', ext: 'aar')
}
apt {
   arguments {
      androidManifestFile variant.outputs[0].processResources.manifestFile

      resourcePackageName 'com.mypackage.library'

   }
}

I get this error
https://imagizer.imageshack.us/v2/519x72q90/540/8ojerK.png
Gradle I found that running the route using the url wrong use "/" instead of "."
Try to find
...8081/artifactory/repo/com/mypackage/android/common/android.common/1.0.0/android.common-1.0.0.aar
but should be
...8081/artifactory/repo/com.mypackage.android.common/android.common/1.0.0/android.common-1.0.0.aar
I'm doing wrong, wrong as was published in the artefactory

A: Your artifact is not complaint to the standard Maven layout, in which the groupId should be separated by /, not by ..
It's not a big deal, Gradle can handle it easly, you just can't declare the repository as maven, but as ivy instead.
Actually, it will be easier to use the artifactory plugin for resolution, it also supports both Maven and Ivy layouts.
Also, please remember to set the repository in Artifactory to be with correct layout (not Maven2, probably Ivy).
And frankly, I think maybe it worth redeploying the artifact under Maven layout, it will make your life easier.


text:
Q: highslide.js - how to hide image filename I have phpBB forum installed, and recently I installed highslide image viewer for phpBB. The problem is that when an image doesn't have an alt text then in stead image filename is displayed when the image is clicked (enlarged).
To be more specific, it looks like this:

So, any ideas how can I get rid of it?


text:
Q: Change the font type of a template In this template, I want to change the font type to be the default latex font type. How can I do that?
Thank you

A: Edit: (I have to after 3 votes)
Such problems are easy solved by a search inside the text of the appropriate files. Appropriate file for the font, is always the main file but this doesn't means that can not be done in the cls file.(It is not recommended though).
The specific search will probably result font sizes etc and also the problem is that the change can be done without the word font inside the command (like below) but we then hope that the template maintainer or creator commented the inclusion of the package that changes the font.
In some cases, it we can find font changes that using the command \sfdefault
and it is a step before go to the last chance that follows.
If we are not lucky and the command that changes the font is not commented or a usual command like the above sfdefault, we have to search all the preamble (including the files that are been include) for packages that may change the font.
For more about packages and commands that can change the font see tha answer of @cfr here : https://tex.stackexchange.com/a/411081/120578
In XeLaTeX the usual commands can be found with search for \selectfont, or "fontfamily" or \setsansfont, \setmainfont and generally (in the most of the cases) search just for "font"
Old Answer with 3! votes not really deserved :P
Comment out line 44 of the file main.tex:
%\usepackage{mathpazo} % Use the Palatino font by default

Output (in order to not be marked my answer for close):


text:
Q: Maven Versions Plugin - Exclude Major Version With Suffix I am implementing the Maven versions plugin to manage our dependencies, but am having trouble excluding the next Spring major release due to the ".RELEASE" suffix.
Here's a snippet of my pom.xml:
<properties>
     <spring.version>4.2.0.RELEASE</spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>[${spring.version},5.0.0.RELEASE)]</version>
    <dependency>
</dependencies>

What I am trying to do is update to the latest 4.X.X (4.3.something) WITHOUT allowing the 5.0 series which could introduce breaking changes. Unfortunately, due to the suffix, it ignores the ")" which is supposed to ignore the 5.0.0 releases.
I do not currently have an externalized rules XML file (getting to it).
Can anyone assist?
Edit: I am using the following command to update:
mvn versions:use-latest-releases

Edit 2: Below is my configuration for the maven plugin:
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <allowIncrementalUpdates>true</allowIncrementalUpdates>
                    <allowMinorUpdates>true</allowMinorUpdates>
                    <allowMajorUpdates>false</allowMajorUpdates>
                    <allowSnapshots>false</allowSnapshots>
                </configuration>
            </plugin>


text:
Q: If $A\subseteq X$ is contractible, is $X\simeq X/A$? Let $$F: (X,A,*)\times [0,1]\to (X,A,*)$$ be a homotopy such that $F_0$ is the identity and $F_1$ maps $A$ to the point $*$. Does it imply that $X$ is homotopy equivalent to $X/A$? If it helps, we may assume that all spaces are $CW$ complexes or simplicial sets.
I tried to analyze the maps $\tilde{F_1}: X/A\to X$ induced by $F_1: (X,A)\to (X,*)$ and possible homotopy inverse $q: X\to X/A$ but am not able to prove that they induce homotopy equivalence.

A: No, it's not always true that $X/A \simeq X$ when $A$ is contractible. It is true if the pair $(X,A)$ has the homotopy extension property, as proven in Hatcher's book as Proposition 0.17.
Here is a counterexample. Let $X = S^1$ be the circle, let $x \in X$ be an arbitrary point, and let $A = S^1 \setminus \{x\}$. Then $X/A$ has exactly two elements, say $x$ and $y = [A]$, and its open sets are $\varnothing$, $\{y\}$ and $X/A = \{x,y\}$. This is a contractible space and hence not homotopy equivalent to $X = S^1$.


text:
Q: Generate randomly placed squares with javaFX I am trying to figure out how I can generate randomly placed squares using javaFX.  I have the following code started, however it does not function properly.
The loop appears to run only one time, as the stage is called.  I can't wrap my head around how to run the loop, and then call the stage.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.shape.*;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;

public class Testing extends Application{
   public void start(Stage primaryStage) {

       for(int i=0; i<=30;i++) {
           float x = (float)(Math.random()*513);
           float y = (float)(Math.random()*513);

           Rectangle r = new Rectangle(x,y,40,40);
           Group root = new Group(r);
           Scene scene = new Scene(root, 512, 512, Color.WHITE);
           primaryStage.setTitle("Assignment 5, a QR Code");
           primaryStage.setScene(scene);
           primaryStage.show();
       }

       //Group root = new Group(r);
       //Scene scene = new Scene(root, 512, 512, Color.WHITE);

       //primaryStage.setTitle("Assignment 5, a QR Code");
       //primaryStage.setScene(scene);
       //primaryStage.show();
   }
   public static void main (String[] args) {
       launch(args);
   }
}

A: Like @James_D said you got the Scene, Group, and Stage in the loop. Move them out. Update: Also, like @James_D pointed out the List is not really needed. Just add the Rectangles to the Group.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication42 extends Application {
    @Override
    public void start(Stage primaryStage) {
        Group root = new Group();
        for(int i=0; i<=30;i++)
        {
           float x = (float)(Math.random()*513);
           float y = (float)(Math.random()*513);

           Rectangle r = new Rectangle(x,y,40,40);
           root.getChildren().add(r);//Add each rectangle to the Group.
        }

        Scene scene = new Scene(root, 512, 512, Color.WHITE);
        primaryStage.setTitle("Assignment 5, a QR Code");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Generic way of handling concatenated table key If I have a tabkey value, e.g., DATA(lv_tabkey) = '1000041508773180000013000'., which is the concatenated value of all table keys for an entry and I know the name of the corresponding table:
How I can get the table entry for it without splitting tabkey manually and therefore having to write the order and length of each key field?
Full example:
" The first 3 chars always belong to the 'mandt' field
" which can't be filtered in the SELECT, therefore
" I ignore it and start with key2
DATA(lv_tabkey) = '1000041508773180000013000'.

"ToDo - how to make this generic? - START
DATA(lv_key2) = lv_tabkey+3(12).
DATA(lv_key3) = lv_tabkey+15(3).
DATA(lv_key4) = lv_tabkey+18(4).
DATA(lv_key5) = lv_tabkey+22(3).
DATA(lv_where) =      'key2 = ' && lv_key2 &&
                 ' AND key3 = ' && lv_key3 &&
                 ' AND key4 = ' && lv_key4 &&
                 ' AND key5 = ' && lv_key5.
"ToDo - how to make this generic? - END

SELECT *
  FROM table_x
  INTO TABLE DATA(lt_results)
  WHERE (lv_where).

I think I have to somehow iterate over the table fields, find out the keys and their length - but I don't know how to do this.

A: The statement you are seeking is:

ASSIGN tabkey TO < structure> CASTING TYPE HANDLE r_type_struct.

Knowing type handle for the (table key) structure you can fill it with values in a generic way and query the table using the structure. Here is how:
DATA: handle      TYPE REF TO data,
      lref_struct TYPE REF TO cl_abap_structdescr.

FIELD-SYMBOLS: <key_fld> TYPE abap_componentdescr.

SELECT * UP TO 5000 ROWS
  FROM cdpos
  INTO TABLE @DATA(t_cdpos)
  WHERE tabname NOT LIKE '/%'.

LOOP AT t_cdpos ASSIGNING FIELD-SYMBOL(<fs_cdpos>).
  lref_struct ?= cl_abap_structdescr=>describe_by_name( <fs_cdpos>-tabname ).

* get key fields
  DATA(key_fields) = VALUE ddfields( FOR line IN lref_struct->get_ddic_field_list( ) WHERE ( keyflag NE space ) ( line ) ).

* filling key field components
  DATA(key_table) = VALUE abap_component_tab( FOR ls_key IN key_fields
                                              ( name = ls_key-fieldname
                                                type = CAST #( cl_abap_datadescr=>describe_by_name( ls_key-domname ) )
                                               )
                                            ).
* create key fields type handle
  TRY.
      DATA(r_type_struct) = cl_abap_structdescr=>create( key_table ).
    CATCH cx_sy_struct_creation .
  ENDTRY.

* create key type
  CHECK r_type_struct IS NOT INITIAL.
  CREATE DATA handle TYPE HANDLE r_type_struct.
  ASSIGN handle->* TO FIELD-SYMBOL(<structure>).

* assigning final key structure
  ASSIGN <fs_cdpos>-tabkey TO <structure> CASTING TYPE HANDLE r_type_struct.

* filling values
  LOOP AT key_table ASSIGNING <key_fld>.
    ASSIGN COMPONENT <key_fld>-name OF STRUCTURE <structure> TO FIELD-SYMBOL(<val>).
    CHECK sy-subrc = 0.
    <key_fld>-suffix = <val>.
  ENDLOOP.

  DATA(where_cond) = REDUCE string( INIT where = ` ` FOR <field> IN key_table WHERE ( name <> 'MANDT' ) NEXT where = where && <field>-name && ` = '` && <field>-suffix && `' AND ` ).
  where_cond = substring( val = where_cond off = 0 len = strlen( where_cond ) - 4 ).

  IF <fs_cdpos>-tabname = 'BNKA'.
    SELECT *
    INTO TABLE @DATA(lt_bnka)
    FROM bnka
    WHERE (where_cond).
  ENDIF.

ENDLOOP.

Here I built the sample on table CDPOS that contain table names and additionally concatenated key values in field tabkey, in other words exactly what you are trying to use.
In a loop it detects table types, builds the key and make SQL query in a generic way. Here I used table BNKA for simplicity, but SQL SELECT can be generized as well via field-symbol. Also I made a trick by filling values into the same tab that contains structure components, in SUFFIX field.
P.S. Before passing where condition into query make proper data type validation to avoid such errors as SAPSQL_DATA_LOSS, because with new syntax it makes a strict check.

A: your use case reminds me that how I deal with Change Document key.(CDHDR/CDPOS).
Hope it helps!
DATA:
  lv_tabkey  TYPE char50,
  ls_table   TYPE table_x.
FIELD-SYMBOLS:
  <ls_src_x> TYPE x,
  <ls_tgt_x> TYPE x.

"Add Client info the Table key if your table is Client dependent.
CONCATENATE sy-mandt lv_tabkey INTO lv_tabkey.

ASSIGN lv_tab_key TO <ls_src_x> CASTING.
ASSIGN ls_table TO <ls_tgt_x> CASTING.
<ls_tgt_x> = <ls_src_x>.

"Now ls_table has the key info filled including MANDT if you have the MANDT in table key.

SELECT *
  FROM table_x
    INTO TABLE DATA(lt_results)
    WHERE key2 = ls_table-key2 AND key3 = ls_table-key3
          AND key4 = ls_table-key4 AND key5 = ls_table_key5.


text:
Q: Cannot find the declaration of element 'beans'. Error while loading xml Below is the xml code, I am getting this error
cvc-elt.1: Cannot find the declaration of element 'beans'.
I am using ClassPathXmlApplicationContext for loading this xml and I have all the jars in manifest.mf
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Enable Annotation based Declarative Transaction Management -->
    <tx:annotation-driven proxy-target-class="true"
        transaction-manager="transactionManager" />

    <!-- Creating TransactionManager Bean, since JDBC we are creating of type
        DataSourceTransactionManager -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Oracle DB DataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />
        <property name="username" value="IDCSITCORE" />
        <property name="password" value="IDCSITCORE" />
    </bean>

    <bean id="CommonTranMan" class="panacea.boot.tranman.CommonTranMan">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

--update
This is the error which I get
Caused by: org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 101; cvc-elt.1: Cannot find the declaration of element 'beans'.

I have this as a fat jar inside an ear deployed in jboss eap 6.4.
I have no problem when I run it as a standalone application but when deployed in jboss, I am facing this problem
Class1.java
public void method1()  {
        try {

        ApplicationContext   ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        CommonTranMan c = ctx.getBean(CommonTranMan.class);

            returnDto = c.callUpdateValues(_dtoobject);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I will call this method1 from some other java class in different project.
Class1 c = new Class1();
c.method1();

pom.xml for building fat jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>panacea</groupId>
    <artifactId>springapp3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springapp</name>
    <description>New app</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.2.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <!-- get all project dependencies -->
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <!-- MainClass in mainfest make a executable jar -->
                    <archive>
                      <manifest>
                        <mainClass>panacea.boot.Class1</mainClass>
                      </manifest>
                    </archive>

                </configuration>
                <executions>
                  <execution>
                    <id>make-assembly</id>
                                        <!-- bind to the packaging phase -->
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                  </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

</project>


text:
Q: How do I label values for cycle numbers in python pandas I have a columns, iterate 1 to 3. I need a cycle number, which presents in the mid column. How do I use pandas to get the second column number please?
here is the table:
column  | I need   |Note
-----------------------------------------------------------------------
2       | 1        |first cycle although not starting from 1
3       | 1        |first cycle although not starting from 1
-----------------------------------------------------------------------
1       | 2        |second cycle
2       | 2        |second cycle
3       | 2        |second cycle
-----------------------------------------------------------------------
1       | 3        |
2       | 3        |
3       | 3        |
-----------------------------------------------------------------------
1       | 4        |
2       | 4        |
3       | 4        |
-----------------------------------------------------------------------
1       | 5        |
2       | 5        |
3       | 5        |
-----------------------------------------------------------------------
1       | 6        |
2       | 6        |
3       | 6        |
-----------------------------------------------------------------------
1       | 7        |7th cycle and does have to end in 3
2       | 7        |

A: With your sample data working first difference by Series.diff, compare less like 0 and last cumulative sum by Series.cumsum:
df['new'] = df['column'].diff().lt(0).cumsum() + 1

If values are strings is possible encoding to numeric by Series.map with dictionary:
df['new'] = df['column'].map({'1':0, '2':2, '3':3}).diff().lt(0).cumsum() + 1

print (df)
    column  I need  new
0        2       1    1
1        3       1    1
2        1       2    2
3        2       2    2
4        3       2    2
5        1       3    3
6        2       3    3
7        3       3    3
8        1       4    4
9        2       4    4
10       3       4    4
11       1       5    5
12       2       5    5
13       3       5    5
14       1       6    6
15       2       6    6
16       3       6    6
17       1       7    7
18       2       7    7

EDIT: You can create dictioanry for map by all value in one group with enumerate:
d = {v:k for k, v in enumerate(['1','2','3'])}
#if possible create groups by all unique values - check order before
#print (df.columns.unique())
#d = {v:k for k, v in enumerate(df.columns.unique()}
df['new'] = df['column'].map(d).diff().lt(0).cumsum() + 1

A: I think this is the most simple solution, as you just need to define the value/string that starts the interval:
start_val = 1 # the value / string which starts the cycle
df['new'] = ((df['column'] == start_val) | pd.isna(df['column'].shift())).cumsum()

If you have nan's in df['column'] than add .fillna(0 / '') before the .shift()


text:
Q: What does it mean (Class *)? Example:
- (Subclass *)field:(NSArray *)fields
{
    // code
    return (Subclass *)[self field:fields];
}

I've seen more than once where it is used (Class *). So, what does it mean?

A: The first example says that the method returns pointer to an instance of class Subclass.
The second one is casting, it's just telling the compiler that  [self field:fields] is Subclass type (pointer an instance of class Subclass).


text:
Q: Centos: Could not retrieve the mirrorlist I am not able to install any service by using the yum command.
When I try to install httpd by typing
[root@kstest /]# yum install httpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=os error was
14: PYCURL ERROR 7 - "Failed to connect to 2a02:2498:1:3d:5054:ff:fed3:e91a: Network is unreachable"
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=extras error was
14: PYCURL ERROR 7 - "Failed to connect to 2a02:2498:1:3d:5054:ff:fed3:e91a: Network is unreachable"
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=updates error was
14: PYCURL ERROR 7 - "Failed to connect to 2a02:2498:1:3d:5054:ff:fed3:e91a: Network is unreachable"
 * base: centos.aol.in
 * extras: centos-hn.viettelidc.com.vn
 * updates: centos.aol.in
http://centos.aol.in/6.5/os/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://centos.aol.in/6.5/os/x86_64/repodata/repomd.xml: (28, 'connect() timed out!')
Trying other mirror.

After that when I try to use yum command it says
Existing lock /var/run/yum.pid: another copy is running as pid 2063.
Another app is currently holding the yum lock; waiting for it to exit...
  The other application is: yum
    Memory :  22 M RSS (219 MB VSZ)
    Started: Mon Jul 21 05:09:53 2014 - 01:09 ago
    State  : Traced/Stopped, pid: 2063

to unlock that I entered
ps aux | grep yum
kill -9 <pid number>

When I tried to update yum by typing
yum update -y

I am getting the following
[root@kstest etc]# yum update -y
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: centos.aol.in
 * extras: centos-hn.viettelidc.com.vn
 * updates: centos.aol.in
http://centos.aol.in/6.5/os/x86_64/repodata/repomd.xml: [Errno 12] Timeout on http://centos.aol.in/6.5/os/x86_64/repodata/repomd.xml: (28, 'connect() timed out!')
Trying other mirror.

How do I resolve this issue ?
How can I install httpd?
My yum.repos.d file present in etc/ is empty. and my yum.conf file is
[main]
proxy=http://proxy.com:8000
cachedir=/var/cache/yum/$basearch/$releasever
keepcache=0
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1
gpgcheck=1
plugins=1
installonly_limit=5
bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum
distroverpkg=centos-release

the proxy I have added it. it was not there from before.

A: I've been having this same issue since 6.4, I remain shocked that there isn't an easy to find solution. The quick workaround is to comment out all mirrorlist lines and uncomment all baseurl ones, but according to some people in some forums that's not a good thing to do.

A: This issue can be resolved by fixing your network setup. IPv6 mirrors don't work in all setups. What I do using Ansible is disabling IPv6 and also use Google's public resolver. The playbook assumes SELinux is disabled.
---
- hosts: all
  user: vagrant
  sudo: True
  tasks:

  - name: "disable ipv6"
    shell: echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6

  - name: "disable ipv6"
    shell: echo 1 > /proc/sys/net/ipv6/conf/default/disable_ipv6

  - name: "restart network"
    service: name=network state=restarted

  - name: "add public resolver"
    lineinfile: dest=/etc/resolv.conf regexp='^nameserver'
              line='nameserver 8.8.8.8' state=present

  - name: "clean yum"
    shell: yum clean all

  - name: "warmup Yum"
    shell: yum search libselinux-python

  - name: "use Yum"
    yum: name={{ item }} state=installed
    with_items:
      - libselinux-python

  - name: "Enable SELinux"
    selinux: policy=targeted state=permissive

A: If you define a proxy server in /etc/yum.conf, all users connect to the proxy server with those details when using yum. To enable all yum operations to use a proxy server, specify the proxy server details in /etc/yum.conf.
Add entry like below in /etc/yum.conf, to enable yum to use the proxy (here proxy server: abc.mydomain.com, connecting to port 8080)
proxy=http://abc.mydomain.com:8080


text:
Q: Flink Job ID From within the Streaming Application We are running a Flink session cluster and there are a lot of jobs running. I would like to add the jobID as a suffix to any error logs so we can identify which job failed and get notified of the same.
Is there a way to get the jobID of a flink job from within the application? Also, any ideas on how we can write a custom logger to perform the suffix operation?


text:
Q: Nested property in ResourceBundleMessageSource I wanted help if its possible to auto resolve by Spring the nested property. I am using Spring 4.2.4, Java 8 and the property file looks like-
# messages.properties
company.name=XYZ
welcome.message=Dear Customers of ${company.name}
about.company=${company.name} is blah blah

We have a custom localization implementation to get the String from Resource bundle for i18 as defined below-
public String get(Locale locale, String key, Object... arguments) {
String pattern = this.getString(locale, key);
MessageFormat formatter = new MessageFormat(pattern, locale);
StringBuffer buffer = new StringBuffer();
formatter.format(arguments, buffer, null);
return buffer.toString();
}

I want to be able to use this method like get(locale, "welcome.message") and expect to render it as Dear Customers of XYZ.
Currently its not working failing in MessageFormat. Is there a way to allow spring auto resolve this.

A: You can now use curly braces (without symbol $).
It work for Spring 5 (tested for 5.3.6 and 5.3.7):
# messages.properties
company.name=XYZ
welcome.message=Dear Customers of {company.name}
about.company={company.name} is blah blah

A: I do this with MessageSource in my Controller like this
@Inject
private MessageSource message;

protected String getMessage(String key, Object[] arguments) {
    return message.getMessage(key, arguments, LocaleContextHolder.getLocale());
}


text:
Q: How do I get the following page layout using CSS? I want my layout to be like the image below

This is the code that I have tried:
CSS
body {
    margin: 0;
    padding: 0;
    background-color: #faf8f6;
    font-family:'Segoe UI', Verdana, Arial;
    font-size: 13px;
    color: #2c2c2c;
}
img, img a, img a:hover {
    border: none;
}
p {
    margin: 0;
    padding: 0;
}
#main-wrapper {
    margin: 0;
    padding: 0;
    width: 100%;
    min-height: 100%;
    position: fixed;
}
#header {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100px;
    background-color: #faf8f6;
}
#left-logo {
    margin: 38px 0 26px 35px;
    width: 300px;
    height: 36px;
    float: left;
}
#left-logo p {
    font-size: 32px;
    color: #000000;
    text-align: left;
    line-height: 26px;
}
#left-logo p span {
    color: #d4102b;
    font-weight: bold;
}
#right-logo {
    margin: 15px 35px 15px 0;
    width: 217px;
    height: 70px;
    float: right;
}
#menu-wrapper {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 28px;
    background-color: #948e8a;
    border-top: 1px solid #5a4736;
    border-bottom: 1px solid #5a4736;
}
#body-wrapper {
    top: 130px;
    bottom: 25px;
    width: 100%;
    position: fixed;
}
#left-menu-wrapper {
    width: 199px;
    height: 100%;
    float: left;
    background-color: #948e8a;
    border-right: 1px solid #5a4736;
}
#content-wrapper {
    width: calc(100%-200px);
    margin: 0 0 0 200px;
    height: 100%;
}
#footer {
    bottom: 0;
    height: 24px;
    width: 100%;
    background-color: #948e8a;
    border-top: 1px solid #5a4736;
    position: fixed;
}
#footer p {
    margin: 0 35px 0 0;
    text-align: right;
    line-height: 24px;
    color: #ffffff;
    font-size: 12px;
}

HTML

    <form id="form1" runat="server">

123 India

© 2013. 123India. All rights reserved.

    </form>

And here's a live demonstration on JS Fiddle.

A: The best way to go about this imo, is fixed divs for the headers, sidebar and footer. Then one main div which pushes the body to make it scrollable. You (at least I do) want native scrolling and should avoid scrollable divs with set heights.
Benefits over pushing the body instead of using a scrollable content div:

*

*the entire document is scrollable, instead of just the content div

*you won't have issues with -webkit-overflow-scrolling: touch and any hardware acceleration issues that come along with it (e.g. relatively positioned elements on a scrollpane, image tearing, ...)

Here's how I solved it:

head

head2

side

    1st that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!
that's a lotta stuff!

foot

And for the css:
body, html{
    margin: 0
}

#header, #header2, #sidebar, #footer{
    border: 1px solid black;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    position: fixed;
    left: 0
}

#header, #header2, #footer{ right: 0 }

#header {
    background-color: lightblue;
    height: 100px
}

#header2 {
    background-color: lightyellow;
    border-top-width: 0;
    height: 30px;
    top: 100px
}

#sidebar {
    background-color: lightgreen;
    border-top-width: 0;
    border-bottom-width: 0;
    top: 130px;
    width: 200px;
    bottom: 30px
}

#content {
    padding-left: 200px;
    padding-top: 130px;
    padding-bottom: 30px
}

#footer {
    background-color: lightgrey;
    bottom: 0;
    height: 30px
}

Working example:
http://jsfiddle.net/kevinsmets/d5bpL/


text:
Q: Android Dynamic Feature INSTALL_FAILED_INVALID_APK I am trying to add some functionality to an existing application. The app's build.gradle contains several productFlavors and a couple of buildTypes. I have tried to replicate that as best I can in my dynamic-feature module, but I cannot seem to get it to install properly from Android Studio.
I followed the example from: https://github.com/googlearchive/android-dynamic-features to set up my feature module, so my project is structured like
app
features/module/build.gradle
build.gradle

I added a buildType and flavor to  the app build.gradle
defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
 }
dynamicFeatures = [":features:module"]
buildTypes{
    myBuildType {
        debuggable true
        multiDexEnabled true
    }
}

flavorDimensions "blah"
productFlavors{
        arm64 {
            ndk {
                abiFilters "arm64-v8a"
            }
            ext {
                abiVersionCode = 5
            }
            matchingFallbacks = ['defaultFlavor']
        }
}

and in the module build.gradle, I have attempted to match that with:
defaultConfig {
    minSdkVersion 24
    targetSdkVersion 28
    }
buildTypes {

    dynamic {
        multiDexEnabled true
        debuggable true
    }
}

flavorDimensions "blah"
productFlavors {
    arm64 {
        ext {
            abiVersionCode = 5
        }
    }
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':app')
}

In my Run->Edit Configuration screen, I have put a checkbox next to both the base app and the module under the dynamic features to deploy section. I am trying to test this on a Nokia 6, with Android 9.0 running on it. The only output I get from the build is:
01/12 22:39:25: Launching 'app' on HMD Global TA-1025.
Installation did not succeed.
The application could not be installed: INSTALL_FAILED_INVALID_APK
The APKs are invalid.

A: It just happened to me.
Turns out I was setting different flavors for different modules.
Try selecting the same variants under View > Tool Windows > Build Variants.

A: Please check those things
1) making sure that the AndroidManifest.xml package name was the same as the
   build.grade applicationId
2) check package name in your Androidmanifest.xml see whether started with one empty
   space character. like "  com.example.test" instead of "com.example.test"
   and make sure contain at least one dot in your package name
   like "com.exampletest" instead of "comexampletest"
   https://code.google.com/p/android/issues/detail?id=55841

3)"Build" > "Clean Project"
4)reboot the android system

A: Try Edit Configurations > Installations Options > Deploy APK from app bundle

A: I found a solution that resolved my problem. Make sure your libraries and class paths are up to date. I had a class for firebase plugins that were out of date. This problem occurred when using the new graddle. After updating the classpath, everything looks fine.
In my case. I changed this
classpath 'com.google.firebase:firebase-plugins:1.1.0'
to this
classpath 'com.google.firebase:perf-plugin:1.3.1'

A: I had same problem when I used Flavors (Build variants) in my app.
The solution for me was select another build variant in Build Variants tab (for example, release instead of debug flavor), then select the correct build variant, and then Clean, Rebuild.
I found this solution here: https://stackoverflow.com/a/65630971/6543967


text:
Q: How to suppress all initialization errors When I have a simple test-class
public final class InitTest {

    private String field;

    public InitTest() {
        init();
    }

    private void init() {
        field = "";
    }
}

The initialization checker of the checker-framework correctly reports the issues:
InitTest.java:7: error: [initialization.fields.uninitialized] the constructor does not initialize fields: field
        public InitTest() {
               ^
InitTest.java:8: error: [method.invocation.invalid] call to init() not allowed on the given receiver.
                init();
                    ^
  found   : @UnderInitialization(java.lang.Object.class) @NonNull InitTest
  required: @Initialized @NonNull InitTest
2 errors

According to the docs of the Initialization Checker, it should be able to disable the initialization checker via a command line argument:

To disable initialization checking, supply the command-line argument
-AsuppressWarnings=uninitialized

When we use this argument (in checker-framework 2.2.1) we still get an initialization error:
InitTest.java:8: error: [method.invocation.invalid] call to init() not allowed on the given receiver.
                init();
                    ^
  found   : @UnderInitialization(java.lang.Object.class) @NonNull InitTest
  required: @Initialized @NonNull InitTest
1 error

Am I missing something or is this a bug?
Note: when we use -AsuppressWarnings=initialization then no error is shown anymore - but this would also suppress the nullness-related issues: see this SO discussion.

A: -AsuppressWarnings=uninitialized suppresses all warnings related to initialization itself.  It lets you write a constructor that does not initialize all its fields, for example.
However, that does not currently disable all other checks in the Checker Framework.  The Checker Framework implementation treats the error that you showed as a method call error (that's how it is printed, for example).
Another way of saying this is that the -AsuppressWarnings=uninitialized affects messages that are printed as initialization errors but not errors that are printed as other types.  This behavior is consistent, but it isn't what a user such as you desires.  I would call this behavior a Checker Framework bug and report it at the issue tracker.


text:
Q: excel vba - add table column with date based on adjacent cell that includes date and time I have an excel table ("Table1") with 4 total columns. The 3rd and 4th column contain 'clock in' and 'clock out' information formatted to show date and time. For example :
 6/3/2016 10:54:52 AM

I would like to do two things here...first, I want to create a new, 3rd column that just reads the date, formatted "d-mmm". This should match the date found in what would now be column 4.
The second thing I would like to do is take the date portion of text out of what would now be columns 4 and 5. So at the end, an example row of data might read as follows (columns 3:5):
    C,           D,          E
7-Jun, 10:54:52 AM, 4:59:44 AM

Here is what I have so far for code:
Sub test()

Dim currentSht As Worksheet
Dim lst As ListObject

Set curretnSht = ActiveWorkbook.Sheets(1)
Set lst = currentSht.ListObjects("Table1")

lst.ListColumns.Add Position:=3
'Not really sure how to do the rest
End Sub

A: That's not the Excel way.  Dates are numbers 0 represents 1/1/1900. Add 1 to it and you get the next day the value of an hour is 1/24 .
The biggest problem of your approach is Excel you stop editing the cell Excel evaluate the cells value.  It'll still look like 7 - Jun but Excel changes the cells format and the cells value to be 7 - Jun of this your 6/7/216.  It's best to have all the cells equal the same date.  Just change the cells formatting to display the results that you want.  If  you need to calculate the Month use the a WorkSheet Function to do so. =Month(A1)

A: Try this:
Sub Demo()
    Range("C1").EntireColumn.Insert               '-->insert column
    Range("D:D").Copy Destination:=Range("C1")    '-->copy column 4 to column 3
    Range("C:C").NumberFormat = "d-mmm"           '-->format column 3
    Range("D:E").NumberFormat = "h:mm:ss AM/PM"   '-->format column 4 and 5
End Sub

Even this will work:
Sub Demo()
    Dim currentSht As Worksheet
    Dim lastRow As Long
    Set currentSht = ActiveWorkbook.Sheets("Sheet1")
    lastRow = currentSht.Cells(Rows.Count, "C").End(xlUp).Row          '-->get last row with data
    currentSht.Range("C1").EntireColumn.Insert                         '-->insert column
    currentSht.Range("C1:C" & lastRow) = currentSht.Range("D1:D" & lastRow).Value '-->copy column 4 to column 3
    currentSht.Range("C1:C" & lastRow).NumberFormat = "d-mmm"          '-->format column 3
    currentSht.Range("D1:E" & lastRow).NumberFormat = "h:mm:ss AM/PM"  '-->format column 4 and 5
End Sub

A: This meets your specs:
Sub InsertColumnAndFormatDates()
    Columns("C:C").Copy
    Selection.Insert Shift:=xlToRight
    Application.CutCopyMode = False
    Columns("C").NumberFormat = "d-mmm"
    Columns("D:E").NumberFormat = "h:mm:ss AM/PM"
End Sub


text:
Q: Looping through Array to set viewmodel properties. What if index doesn't exist? I'm looping through an array of items nested within another array of items.
Almost always, the inner array contains 5 indexes, but there is an off chance that the feed I'm consuming will only have 4 indexes in it.
When I add the indexes to my ViewModel, if the fifth index is missing, everything blows up.
How can I prevent "Index is outside the bounds of the array" errors in this specific scenario?
private List<ImageViewModel> ConvertSmugMugModel(SmugMugGallery smugMugGallery)
{
    return smugMugGallery.Channel.Items.Select(i => new ImageViewModel
        {
            TinyImage = i.Group.Contents[0].Url,
            ThumbnailUrl = i.Group.Contents[1].Url,
            SmallImageUrl = i.Group.Contents[2].Url,
            MediumImageUrl = i.Group.Contents[3].Url,
            LargeImageUrl = i.Group.Contents[4].Url
        }).ToList();
}

*note: I'm not opposed to moving to an iCollection or some other object if using an array is not the best fit. I just didn't want to add bloat if I didn't need to.

Edit
Kal asked what the the model looks like in a comment below.
[XmlRoot("rss")]
public class SmugMugGallery
{
    [XmlElement("channel")]
    public m_Channel Channel { get; set; }
    public class m_Channel
    {
        [XmlElement("item")]
        public Item[] Items { get; set; }
        public class Item
        {
            [XmlElement("group", Namespace = "http://search.yahoo.com/mrss/")]
            public m_Group Group { get; set; }
            public class m_Group
            {
                [XmlElement("content", Namespace = "http://search.yahoo.com/mrss/")]
                public Content[] Contents { get; set; }
                public class Content
                {
                    [XmlAttribute("url")]
                    public string Url { get; set; }
                }
            }
        }
    }
}

A: My first thought is just use the ? operator, like so:
    private List<ImageViewModel> ConvertSmugMugModel(SmugMugModel smugMugGallery)
    {
        return smugMugGallery.Channel.Items.Select(i => new ImageViewModel
        {
            TinyImage = i.Group.Contents[0].Url,
            ThumbnailUrl = i.Group.Contents[1].Url,
            SmallImageUrl = i.Group.Contents[2].Url,
            MediumImageUrl = i.Group.Contents[3].Url,
            LargeImageUrl = i.Group.Contents.Count() > 4 ? i.Group.Contents[4].Url:new Url("blank")
        }).ToList();
    }

You may also want to put that check into the rest of them also, unless you're 101% sure you won't run into less than 4 elements.  Thusly:
    private List<ImageViewModel> ConvertSmugMugModel(SmugMugModel smugMugGallery)
    {
        return smugMugGallery.Channel.Items.Select(i => new ImageViewModel
        {
            TinyImage = i.Group.Contents.Count() > 0 ? i.Group.Contents[0].Url:new Url("blank"),
            ThumbnailUrl = i.Group.Contents.Count() > 1 ? i.Group.Contents[1].Url:new Url("blank"),
            SmallImageUrl = i.Group.Contents.Count() > 2 ? i.Group.Contents[2].Url:new Url("blank"),
            MediumImageUrl = i.Group.Contents.Count() > 3 ? i.Group.Contents[3].Url:new Url("blank"),
            LargeImageUrl = i.Group.Contents.Count() > 4 ? i.Group.Contents[4].Url:new Url("blank")
        }).ToList();
    }


text:
Q: Saving URLs in Woocommerce product attributes I'm trying to get Woocommerce to save an URL as a product attribute. Problem is that URL contains some URL-encoded data like "%25" which Woocommerce doesn't save.
I tried a more simple example of creating a new attribute, called it "MyTestAttribute" and added a value of "Test value 123%456".
What Woocommerce saved was "Test value 1236", without %45.
Any ideas?
Thanks!


text:
Q: MVC scaffolding does not support Entity Framework 6 I'm trying to add a controller with read/write actions and views, using Entity Framework.
But when I try so, VS2012 tells me that "MVC scaffolding does not support Entity Framework 6 or later".
I've read http://support.microsoft.com/kb/2816241 and tried to uninstall EntityFramework 6 and install 5 in Nuget Manager Console:

PM> Uninstall-package EntityFramework -force
  Removing 'EntityFramework 6.0.2' from OnlinebookingAdministrator.
  Successfully removed 'EntityFramework 6.0.2' from OnlinebookingAdministrator.
  Uninstalling 'EntityFramework 6.0.2'.
  Successfully uninstalled 'EntityFramework 6.0.2'.
PM> Install-Package EntityFramework -version 5.0.0
  'EntityFramework 5.0.0' already installed.
  Adding 'EntityFramework 5.0.0' to OnlinebookingAdministrator.
  Successfully added 'EntityFramework 5.0.0' to OnlinebookingAdministrator.

But the error keeps showing up when I try to add the controller. Is there a solution to this?

A: I'm afraid I don't have a perfect solution to your problem, however I think I've got a pretty decent workaround:
I've had many arguments with the default MVC Scaffold-er of late, I'd recommend installing MVCScaffolding via NuGet and using the console to create anything you require.
Steps to Fix:

*

*Install MVCScaffolding using NuGet
PM> Install-Package MvcScaffolding

*Run the following command via Package Manager Console replacing ModelName with the name of the model you wish to generate Controllers/Views for.
PM> Scaffold Controller ModelName

*Learn the basic MVCScaffolding commands
MvcScaffolding: Standard Usage

A: Have you tried http://go.microsoft.com/fwlink/?LinkId=276833?

You must manually scaffold your views or use Entity Framework 5 for scaffolding. Once you scaffold your application, you can use Entity Framework 6.
Note This is a "FAST PUBLISH" article created directly from within the Microsoft support organization. The information contained herein is provided as-is in response to emerging issues. As a result of the speed in making it available, the materials may include typographical errors and may be revised at any time without notice. See Terms of Use for other considerations.


text:
Q: How to get elements by class name only from one part of the document in javascript? I have two grids on page and both of them have "_status" class. I want to get elements only from the second grid.
If I use this:
var allVariants = document.getElementsByClassName("_status");

I will get elements from both grids. Both of my grids have different class "grid1" and "grid2". Is there any chance to get my elements using something like:
var allVariants = document.Find("grid2").getElementsByClassName("_status");

?
In my javascript method I want to add/remove some classes and add/remove some InnerText. When I click on radioButton on some row in my second grid, I send rowNumber and length (number of all rows) to this javascript method. Here is my javascript method:
function changeRowCheckedStatus(rowNumber, length) {
$('.radioButtonSelectColumn .radioButton :checked').attr('checked', true);
var allVariants = document.getElementsByClassName("_status");
allVariants[rowNumber - 1].innerText = "Changed";

for (i = 1; i <= length; i++) {
    if (i !== rowNumber) {
        var variant = "variant" + i;
        $('input[variant=' + variant + ']').removeAttr('checked');
        allVariants[i - 1].innerText = "NotChanged";
    }
}

}
So I want to add class "selected" and add InnerText = "Changed" to this row, and I want to remove class "selected" and add InnerText = "NotChanged" to all other rows. The problem is because var allVariants get all rows, and I want only rows from second grid.

A: You can use querySelectorAll():
var allVariants = document.querySelectorAll("._status.grid2")[1];

A: you can use querySelectorAll to point to grid2:
var allVariants = document.querySelectorAll('.grid2 ._status');

A: I can add id to both of my grids, and after that I can do this:
 var allVariants = document.getElementById("grid2").getElementsByClassName("_status");

Now it will be as HTML Collection.


text:
Q: Imprimir día por día de una semana con PHP necesito puedan colaborarme con una solución a mi consulta.
Resulta que tengo una semana que siempre será Domingo a Sábado para una agenda de forma horizontal. Pero necesito imprimir el día según la semana. actual.
Ya tengo el código de semana actual el cual es:
    if(date('D')!='Mon'){
        $staticstart = date('d/m/Y',strtotime('last Sunday'));
    }else{
        $staticstart = date('d/m/Y');
    }
    if(date('D') != 'Sun') {
        $staticfinish = date('d/m/Y',strtotime('next Saturday'));
    }else{
        $staticfinish = date('d/m/Y');
    }

Ahora bien, cómo imprimo de forma horizontal el día según el rango. Adjunto imagen de referencia.

A: A ver si entendí bien. ¿Quieres imprimir el rango de días de la semana, de domingo a sábado de una fecha en particular?
Si es así, esta función te puede servir, ayudándonos del constructor DateTime, el cual permite hacer muchas operaciones con fechas. El código es sencillo y en él está documentado lo que hace.
<?php
function date_week($u_date) {
    $date_obj = new DateTime($u_date); // Crear un objeto de fecha
    $num_day = $date_obj->format('w'); // 0-dom, 1-lun, ... 6-sab
    $date_obj->modify("-$num_day day"); // Posicionar el objeto en domingo
    $wdays = array();
    for($i=0; $i<7; $i++) {
        $wdays[] = $date_obj->format('Y-m-d');
        $date_obj->modify('+1 day'); // Incrementar el objeto 1 dia
    }
    return $wdays;
}

Ejemplos de salida:
print_r(date_week('2020-04-03'));
// array('2020-03-29', '2020-03-30', '2020-03-31', '2020-04-01', '2020-04-02', '2020-04-03', '2020-04-04')
print_r(date_week('2020-12-30'));
// array('2020-12-27', '2020-12-28', '2020-12-29', '2020-12-30', '2020-12-31', '2021-12-01', '2021-12-02')

El array de salida puedes recorrerlo con un ciclo y aplicarle los formatos HTML correspondientes.
[ Edit ] Modifiqué el formato de salida a completo Y-m-d por si quieres hacer otras cosas con esa fecha, como especificar el mes o el año si cambia. En caso de querer imprimir solo el día, pues solo basta con substr($array[$i], -2); a cada elemento, o también da lo mismo:  date('d', strtotime($array[$i]));
Función Date y Formatos | Constructor DateTime

A: Cuando DateTime no esta disponible, con el viejo fiel mktime tienes la semana en dos líneas:
$semana = array(); // Arreglo de timestamps
for($d=0; $d<7 ; $d++)
  $semana[] = mktime(0, 0, 0, date('n'), date('d')-date('w')+$d, date('Y'));

foreach($semana as $dia)
  echo date('d/m/Y',$dia).PHP_EOL;

A: Recuerda aplicar la función
date_default_timezone_set ( string $timezone_identifier )

[1]: https://www.php.net/manual/es/function.date-default-timezone-set.php para establecer la zona horaria desde la que trabajas, siempre que trabajemos con fechas en php.


text:
Q: How to load Observable array property as Angular Material Table data source? I have an Observable array property with the value fetched from Rest API.
Currently I am using ngFor to show the data in the standard html table.
Now I want to switch into Angular Material Table (MatTableDataSource). How do I load the [dataSource] with the data I have from the Observables?

A: Just [dataSource]="Observable<ReadOnlyArray>" works. The commit feat(table): allow data input to be array, stream (#9489) seems at Angular 5.2 . For now, allowed types are DataSource<T> | Observable<ReadonlyArray<T> | T[]> | ReadonlyArray<T> | T[].

A: Here you go.  Hack away at this.  I have the observable in a service I call processor.service and it uses the same code is used to populate all my tables. The vars are in the component and are passed through to the service:
component
private dbTable = 'members';  // The table name where the data is.
private dataSource = new MatTableDataSource();

private displayedColumns = [
    'firstName',
    'lastName',
...]

ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
 }

// ------ GET ALL -----

  private getAllRecords() {
    return this.mainProcessorService.getAllRecords(
      this.dbTable,
      this.dataSource,
      this.paginator,
      );
  }

processor.service
  getAllRecords(dbTable, dataSource, paginator) {

    dataSource.paginator = paginator;

    // Populate the Material2 DataTable.
    Observable.merge(paginator.page)
      .startWith(null)  // Delete this and no data is downloaded.
      .switchMap(() => {
        return this.httpService.getRecords(dbTable,
          paginator.pageIndex);
      })
      .map(data => data.resource)  // Get data objects in the Postgres resource JSON object through model.

      .subscribe(data => {
          this.dataLength = data.length;
          dataSource.data = data;
        },
        (err: HttpErrorResponse) => {
          console.log(err.error);
          console.log(err.message);
          this.messagesService.openDialog('Error', 'Database not available.');
        }
      );
  }

My html isn't ngFor but should be useful.  The results create a long table that requires pagination and probably accomplishes what you want.
<mat-table #table [dataSource]="dataSource" matSort>

        <ng-container matColumnDef="firstName">
          <mat-header-cell fxFlex="10%" *matHeaderCellDef> First Name </mat-header-cell>
          <mat-cell fxFlex="10%" *matCellDef="let row"> {{row.first_name}} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="lastName">
          <mat-header-cell fxFlex="10%" *matHeaderCellDef mat-sort-header> Last Name </mat-header-cell>
          <mat-cell fxFlex="10%" *matCellDef="let row">  {{row.last_name}} </mat-cell>
        </ng-container>
...

A: You either need to create a custom DataSource or use the MatTableDataSource.
See here


text:
Q: Custom JSP Tag processor is caching a dated property, so the page shows old data and don't update, how to avoid this? I made a custom jsp tag that search a historical value on a database an render it on the page. The attributes that the tag requires are the variable name and the date.
The problem is that the 'date' property changes according clock move on ('date' points always to the last hour), but the JSP Tag processor's (jasper2) pooling system don't update the 'date' property anymore (calling to the setDate), and the page stays freezed on a point in time.
I don't want to disable the pooling system because it gives performance to the web, but i need to tell it somehow that 'date' property must be setted always.
There is a trick o a procedure to force this?
Thanks a lot.

A: I am not sure what pooling you are talking about.
Part of the JSP specification that all containers implement is the distinction between attributes evaluated at runtime and those evaluated when the page is compiled.
In the TLD, you must declare the date attribute's <rtexprvalue/> to be true.


text:
Q: jVectorMap change color with click for 2 areas max Can someone help me with jVectorMap for selecting 2 regions max. There are 2 options available for region color, they could be green or they could be red. Only one region can be green at the time and the same for the red region. So, one region green and one region red.
If I click in the green region it should become the normal region color for example(#ccc) as all the other regions, the same happen when I click in the red region.
If I click in any #ccc region while exists red and green region nothing should happen. But if I click in a #ccc region while no green or no red regions the clicked region must become or green or red.
Here is an example of the function that I want to add to jVectorMap, you can just copy and paste in your html to check.

This is just an example, pretend that each block is a country in jVectorMap. What I want is to do the same logic as this for the world map

A: The built-in jVectorMap selection cannot be used for this task, because regions and markers are JavaScript objects (not arrays) , so the selection sequence is not guaranteed to be the correct one. It will be much simpler to set a custom selection inside the click handler.
So, You need to implement Your own selection array. To do that, simply add two custom parameters containing Your data. The logic behind the selection criterias will be also very simple to implement, if You store that selection sequence.
Here is an example:

$(function() {

  function setSelection(code) {
    var a = 'fill', p = this.params,
      colors = p.selectedColors, regions = p.travelRegions,
      initial = p.regionStyle.initial[a];
    var e = this.series.regions[0].elements[code].element,
      shape = e.shape, status = e.config.style.selected;

    var i = colors.indexOf(status[a]);
    switch(i) {
      case 0:
      case 1:
        regions[i] = ''; status[a] = initial;
        break;
      default:
        switch(true) {
          case regions[0] == '' && regions[1] == '':
          case regions[0] == '' && regions[1] != '':
            regions[0] = code; status[a] = colors[0];
            break;
          case regions[0] != '' && regions[1] == '':
            regions[1] = code; status[a] = colors[1];
            break;
          default:; /* departure & arrival already selected */
        }
    }
    shape.updateStyle();
    for(var n=0; n<regions.length; n++) {
      if(regions[n] != '') this.setSelectedRegions(regions[n]);
    }
  }

  var worldMap = new jvm.Map({
    map: 'world_mill_en',
    container: $('#world-map'),
    zoomOnScroll: true,
    backgroundColor: 'aliceblue',
    travelRegions: ['',''],
    selectedColors: ['#ff0000', '#00ff00'],
    series: {regions: [{values: {}}]},
    onRegionClick: function(e, code) {
      setSelection.call(worldMap, code);
    }
  });

});
<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jvectormap@2.0.4/jquery-jvectormap.min.css" type="text/css">


text:
Q: Using templated member function pointer as template parameter I have this class:
#include <assert.h>

template <typename DeclaringType, typename HandlerType>
using SubscribeMethodType = void (DeclaringType::*)(HandlerType* handler);

template <typename DeclaringType>
using UnsubscribeMethodType = void (DeclaringType::*)();

template <SubscribeMethodType<???_1, ???_2> subscribeMethod, UnsubscribeMethodType<???_1> unsubscribeMethod>
class EventHandler
{
private:
    template <typename T>
    struct ExtractDeclaringAndHandlerTypes
    {
    };

    template <typename DeclaringType, typename HandlerType>
    struct ExtractDeclaringAndHandlerTypes<void (DeclaringType::*)(HandlerType*)>
    {
        typedef DeclaringType DeclaringType;
        typedef HandlerType HandlerType;
    };

    typedef typename ExtractDeclaringAndHandlerTypes<decltype(subscribeMethod)>::DeclaringType DeclaringType;
    typedef typename ExtractDeclaringAndHandlerTypes<decltype(subscribeMethod)>::HandlerType HandlerType;

public:
    EventHandler() { }
    ~EventHandler()
    {
        Unsubscribe();
    }

    void Subscribe(DeclaringType* eventOwner, HandlerType* handler)
    {
        assert(!m_IsSubscribed);

        m_EventOwner = eventOwner;
        (eventOwner->*subscribeMethod)(handler);
        m_IsSubscribed = true;
    }

    void Unsubscribe()
    {
        if (m_IsSubscribed)
        {
            (m_EventOwner->*unsubscribeMethod)();
            m_IsSubscribed = false;
        }
    }

private:
    DeclaringType* m_EventOwner;
    bool m_IsSubscribed;
};

Example usage:
class IEventConsumer
{
};

class ExampleEventOwner
{
public:
    void Subscribe(IEventConsumer* consumer) {}
    void Unsubscribe() {}
};

int main()
{
    ExampleEventOwner owner;
    IEventConsumer consumer;

    EventHandler<&ExampleEventOwner::Subscribe, &ExampleEventOwner::Unsubscribe> handler;
    handler.Subscribe(&owner, &consumer);
    handler.Unsubscribe();

    return 0;
}

Is it possible to specify something instead of "???_1" and "???_2" to allow them to be any type? The goal is to avoid the consumer of this class having to specify DeclaringType and HandlerType explicitly, since they can easily be inferred from subscribeMethod and unsubscribeMethod.
Note: I cannot use C++17.

A:
Is it possible to specify something instead of "???_1" and "???_2" to allow them to be any type?

Not before C++17, no. What you're asking for is a template non-type parameter that can deduce its type from the provided value - which is exactly what the new C++17 language feature template auto does.
Before C++17, the only way to do such a thing is to provide the type first:
template <class T, T Value> struct X;

So you have to write:
EventHandler<decltype(&ExampleEventOwner::Subscribe), &ExampleEventOwner::Subscribe,
    decltype(&ExampleEventOwner::Unsubscribe), &ExampleEventOwner::Unsubscribe
> handler;

which, admittedly, sucks. Alternatively, you could change the design to make the template parameters be the class type and handler type. This would allow you to write:
EventHandler<ExampleEventOwner, IEventConsumer> handler(
    &ExampleEventOwner::Subscribe, &ExampleEventOwner::Unsubscribe);

which in turn would let you write a factory function:
template <class T, class H>
EventHandler<void (T::*)(H*), void(T::*)()> makeEventHandler(
    void (T::*subscribe)(H*), void (T::*unsubscribe)());

auto handler = makeEventHandler(&ExampleEventOwner::Subscribe,
    &ExampleEventOwner::Unsubscribe);

And that is decidedly non-terrible.


text:
Q: Commands not working on Git Bash Hi i am willing to use Git Bash for app dev, however whenever i start it, it gives me couple of 'bash :export:' lines and not even the clear/clrscr commands work.
I am using a Windows 8.1 machine (6.00 gb ram, 1 TB - just so you know). I have tried the following:

*

*uninstalling-reinstalling git

*Using Git as CMD prompt

Below is the screenshot of the Terminal window:

Output of echo $PATH

This is my current PATH env variable:
C:\Users\Madhukar Jain.npm-global\node_modules\express;C:\Users\Madhukar Jain\AppData\Roaming\npm;%APPDATA%\Roaming\npm\node_modules.bin\;C:\Program Files\MongoDB\Server\3.2\bin;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Program Files\Git\bin;C:\Program Files\Git\cmd;

A: Looks like the PATH is completely messed up. Are you using custom profile/rc file such as ~/.bashrc , ~/.bash_profile , ~/.bash_login or ~/.profile ? If yes you need to check whether the contents are syntactically correct. From the errors I feel that there are few issues with special characters such as spaces. You may have to use double quotes properly to clearly differentiate the directories in the PATH.

A: Try this and check
export PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin


text:
Q: How to get all values for a certain field in django ORM? I have a table called user_info. I want to get names of all the users. So the table has a field called name. So in sql I do something like
SELECT distinct(name) from user_info

But I am not able to figure out how to do the same in django. Usually if I already have certain value known, then I can do something like below.
user_info.objects.filter(name='Alex')

And then get the information for that particular user.
But in this case for the given table, I want to get all the name values using django ORM just like I do in sql.
Here is my django model
class user_info(models.Model):
    name = models.CharField(max_length=255)
    priority = models.CharField(max_length=1)
    org = models.CharField(max_length=20)

How can I do this in django?

A: You can use values_list() as given in Daniel's answer, which will provide you your data in a list containing the values in the field. Or you can also use, values() like this:
user_info.object.values('name')

which will return you a queryset containing a dictionary. values_list() and values() are used to select the columns in a table.

A: You can use values_list.
user_info.objects.values_list('name', flat=True).distinct()

Note, in Python classes are usually defined in InitialCaps: your model should be UserInfo.

A: Adding on to the accepted answer, if the field is a foreign key the id values(numerical) are returned in the queryset. Hence if you are expecting other kinds of values defined in the model of which the foreign key is part then you have to modify the query like this:
    `Post.objects.values_list('author__username')`

Post is a model class having author as a foreign key field which in turn has its username field:
Here, "author" field was appended with double undersocre followed by the field "name", otherwise primary key of the model will be returned in queryset. I assume this was @Carlo's doubt in accepted answer.


text:
Q: Recovering from OOM on DirectByteBuffer allocation on a WebFlux Web Server I'm not sure if this makes sense so please comment if I need to provide more info:
My webserver is used to upload files (receives files as Multipart/form-data and uploads them to another service). Using WebFlux, the controller defines the argument as a @RequestPart(name = "payload") final Part payload which wraps the header and Flux.
Reactor / Netty uses DirectByteBuffers to accomodate the payload. If the request handler cannot get enough direct memory to handle the request, it's gonna fail on an OOM and return 500. So this is normal / expected.
However, what's supposed to happen after?
I'm running load tests by sending multiple requests at the same time (either lots of requests with small files or less requests with bigger files). Once I get the first 500 due to an OOM, the system becomes unstable. Some requests will go through, and other fails with OOM (even requests with very small payload can fail).
This behaviour leds me to believe the allocated Pooled buffers are not shared between IO Channels? However this seems weird, it makes the system very easy to DDOS?
From the tests I did, I get the same behaviour using unpooled databuffers, although for a different reason. I do see the memory being unallocated when doing jcmd <PID> VM.native_memory but they aren't released to the OS according to metrics & htop. For instance, the reserved memory shown by jcmd goes back down but htop still reports the previous-high amount and it eventually OOM.
So Question :
Is that totally expected or am I missing a config value somewhere?
Setup :
Spring-boot 2.5.5 on openjdk11:jdk-11.0.10_9
Netty config :
-Dio.netty.allocator.type=pooled -Dio.netty.leakDetectionLevel=paranoid -Djdk.nio.maxCachedBufferSize=262144 -XX:MaxDirectMemorySize=1g -Dio.netty.maxDirectMemory=0


text:
Q: Merge Datarows using sql i have a table like this:
Datatable
and i need to modify it like this:-
Required Table
i have to merge operation name which have same operation type, machine and attachment and then sum up the [sam] of merged operations.
i tried this but getting errors
SELECT [operation_type],
       [operation_name],
       [machine_type],
       [attachment],
       Stuff((SELECT '+' + t2.operation_name
          FROM   ob
          WHERE  [operation_type] = t2.[operation_type]
                 AND [machine_type] = t2.[machine_type]
                 AND [attachment] = t2.[attachment]
          FOR xml path ('')), 1, 1, '') AS NAME
FROM   ob AS t2
GROUP  BY operation_type

A: SELECT
    operation_type,
    STUFF((SELECT '+' + ob.operation_name
           FROM ob
           WHERE
               operation_type = t2.operation_type
               AND machine_type = t2.machine_type
               AND attachment = t2.attachment
           FOR XML PATH ('')), 1, 1, '') AS 'Operation_Name' ,
    machine_type,
    attachment,
    SUM(SAM) AS 'SAM'
FROM
    ob AS t2
GROUP BY
    t2.operation_type, t2.machine_type, t2.attachment

Thank you!


text:
Q: Is Possible to update live data from from socket server to display data in client We want to send live data from the server which will automatically update on the client side. They Perform only display the data for the first time. If we have some changes in that data they do not perform well. After refresh page changed data will be displayed on the page. How to automatically update page using socket.io.
Server-side code:
io.on('connection', function(socket){
    console.log('A user connected %s',socket.id);

    //Send a message after a timeout of 4seconds
    setTimeout(function(){
        //socket.send('Sent a message 4seconds after connection!');
        socket.emit('testEvent', { description: ' A custom event from server named testEvent after 4 seconds!'} );
    }, 4000);
});

client-side code

socket.on('testEvent', function(data){
    document.write(data.description);
});


text:
Q: Email validation regexp I'm new to pegexp and I want to write a short one which validates emails.
Here is my regexp:
^[a-zA-Z0-9_.-]+@[_a-zA-Z0-9-]+\.[_a-zA-Z0-9-.]+$

The valid email consists of part1@part2. Where part1 consists of 1 or more words, divided by '.' and part2 consists of 2 or more words, divided by '.' Each word consists of a-z or A-Z or 0-9 or - or _
These emails are NOT correct:
smth...smth@smth.smth...
...@a...
I don't know how to fix my regexp and exclude theese examples.

A: Solved this myself:
/^[a-zA-Z0-9\-_]+(\.([a-zA-Z0-9\-_])+)*@[a-zA-Z0-9\-_]+\.[a-zA-Z0-9\-_]+(\.([a-zA-Z0-9\-_])+)*$/


text:
Q: How to fix ubuntu boot alongside windows 7 In the beginning I had only Ubuntu on my pc.
After I installed Win 7 in another partition.
Then Ubuntu boot doesn't starts anymore?
I need dual boot: how can I fix it?

A: You should be able to add Ubuntu to your Windows boot menu with a boot manager like EasyBCD (freeware), or you can boot from an Ubuntu Live CD and re-install grub, which will recognise both W7 and Ubuntu.


text:
Q: Pandas Dataframe column getting implicitly converted to Nan after merge Below are small samples of my 2 pandas dataframe:
    In [65]: df1
 Out[65]:
          Send_Agent  Send_Amount Country_Code
 0     AWD120279        85.99          KW
 1     API185805        22.98          PH
 2     ANO080012       490.00          NO
 3     AUK359401       616.16          GB
 4     ACL000105       193.78          CL

 In [44]: df2
Out[44]:
Country_Code  Rating
0         KW Medium
1         PH Higher
2         NO Lower
3         GB Lower
4         CL Lower

In [97]: df4 = df1[df1['Send_Agent']=='AWD120279']

In [98]: df4
Out[98]:
 Send_Agent  Send_Amount Country_Code
0     AWD120279        85.99          KW
3359  AWD120279       200.00          KW
3878  AWD120279       203.03          KW

In [102]: df5 =  df2[df2['Country_Code']=='KW']
In [104]: df5
 Out[104]:
           Country_Code  Rating
  15           KW         Medium

    In [105]: pd.merge(df4,df5,on='Country_Code',how='left')
Out[105]:
Send_Agent  Send_Amount Country_Code Rating
0  AWD120279        85.99          KW     NaN
1  AWD120279       200.00          KW     NaN
2  AWD120279       203.03          KW     NaN

I am not able to figure out why the 'Rating' column getting converted to Nan after the merge. Every Country_Code has a rating associated with it. So , it should never be Nan.


text:
Q: Exclude class from jar with gradle I've seen these:
Gradle - Exclude file from being packaged with jar
Exclude one class file in gradle Android Studio
and am wondering what path or name I should use with exclude.  This is in a gradle.kts file:
group = "kaldrn.core"

jar {
    exclude("kaldrn/CliKt.class")
}

That's my best guess, since it's the filepath in the jar.  I've also tried using the source file, which doesn't work. I've tried using just basenames without path, no luck.  The significance of the group declaration in this context, if any, is lost on me (I was never a big java user pre kotlin).
The class is defined in cli.kt, in package kaldrn.
How do I determine what to use here?

Perhaps ironically the path above turns out to be the correct one -- see my comments on the accepted answer about a very nasty caveat that affects gradle and jar { exclude ...}, at least for version 6.7.

A: The exclude path should contain the full path to the target file from the source route (eg, from main).
In your case:
jar {
    exclude("kaldrn/cli/CliKt.class")
}

If you are unsure in the path, look for your file under build/classes/kotlin/main


text:
Q: Setting CF while cmp The flag CF is set when we compare two digits and one number is less than another:
mov eax,1
cmp eax,2
jb truWay

In binary form:
1=00000001
2=00000010=11111101+1(add. code)=11111110и
00000001+11111110=11111111(no carry)

Why does instruction cmp eax,2 set the CF flag? There was no carry, or  I'm wrong.

A: You can refer to these slides to understand how subtraction is performed in an ALU.
While it is true that A - B = A + (-B) and that in two's complement this is A + ¬B + 1, this consideration accounts for the result only.
A subtracter implemented with half-adders takes the form

Note that the CarryOut bit is inverted.
You can check that this is necessary and correct by taking your example (limiting the size to 4 bits):
1 - 2 = 1 + (-2) = 0001b + 1110b = 0|1111b since ¬0 = 1 we have a borrow
while for 2 - 1 one has
2 - 1 = 2 + (-1) = 0010b + 1111b = 1|0001b since ¬1 = 0 we have no borrow
So in your example, there is a borrow, and thus CF is set, exactly because 0001b + 1110b produces no carry.
For a more formal proof of the correctness of the inverted carry out flag, once can use induction on the number of bits.
Base case
n = 1
This can be proven with a truth table
a  b   a-b (a+¬b+1)  ¬carryOut  Expected borrow
0  0   0+1+1 = 1|0       0           0
0  1   0+0+1 = 0|1       1           1
1  0   1+1+1 = 1|1       0           0
1  1   1+0+1 = 1|0       0           0

Induction case
When subtracting two n-bit numbers A = an an-1 ... a0 and B = bn bn-1 ... b0 we can have A > B, A < B or A = B.
In the first case there is a k such that ak < bk and aj = bj for all j > k up to n.
The condition ak < bk implies ak = 0 and bk = 1.
Thus A and ¬B are equal down to the k-1-th bit so only this many bits influence the carry out.
But by the induction hypothesis, the carry out is correct, so it is correct in this case too.
The same process goes for the case A > B.
The case A = B is easier as the whole operation is reduced to A + ¬A + 1 which reduces to 111...1 + 1 that always produces a carry out and thus no borrow.

A: There is borrow out indeed. CF is set by the cmp instruction if there is borrow out.
Your instruction cmp performs the following subtraction:
  1 = 0001
- 2 = 0010
--------------
      1111

For the the first rightmost column there is nothing special: 1 - 0 = 1.
For the second rightmost column there is a borrow (i.e.: a 1 is "borrowed" from one of the next columns). The borrow is needed because 0 < 1. The result of this column is then 10 - 1 = 1.
Note however, that for the first operand there is not a single column on the left with a 1 to borrow from, therefore a borrow out occurs: a borrow is coming out for the most significant bit, which actually sets CF.
Your subtraction operation would actually be like setting CF (i.e.: "borrowing" or "getting" a 1 for the MSB of the first operand) and performing the following subtraction:
  10001
-  0010
-------
   1111

Note that the first operand has a 1 on the left side of its true MSB. This 1 was not there before and it represents the borrow.

A: First:
The result of a-b is the same as the result of a+(-b).
However the flags set by the operation a-b are NOT (at least not always) the same flags as the flags set by the operation a+(-b)!
This can be seen by comparing different CPU types (e.g. a modern x86 CPU and the historic 6502):
The values of the flags after the operation a+b are the same on the x86 and the 6502 while the "carry flag" has exactly the opposite meaning on both CPUs after the operation a-b.
This means that the "carry flag" has the same value after the operation a+(-b) on both CPUs while the value after a-b always differs on both CPUs.
Second:
On the x86 the "carry flag" is defined as "borrow out" for subtractions. You could emulate this by

*

*extending both numbers to a number with more bits - for example 9 instead of 8 bits

*then making the "extended" number negative

*then doing the addition

*ignoring the carry in the addition

*instead using the highest bit of the result as carry

Example:
1 = 00000001 (8 bit) = 0 00000001 (9 bit)
2 = 00000010 (8 bit) = 0 00000010 (9 bit)
3 = 00000011 (8 bit) = 0 00000011 (9 bit)
=> -2 = 1 11111110 (9 bit!)

Do the addition:
3 + (-2) = 1000000001 (9 bit plus carry)
1 + (-2) =  111111111 (9 bit)

Ignore carry:
3 + (-2) = 000000001 (9 bit)
1 + (-2) = 111111111 (9 bit)

Use the highest bit as carry:
3 + (-2) =  000000001 = 0 00000001 = (no carry) 00000001
1 + (-2) =  111111111 = 1 11111111 = (carry)    11111111


text:
Q: Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException:Error communicating with the remote browser. It may have died I try to execute this script:
public class BuyMenShirt {

    public static void main(String[] args) throws InterruptedException
    {
        //Firefox driver setup

        String driverPath = "C:\\Users\\RW\\geckodriver-master\\";
        System.setProperty("webdriver.gecko.driver", driverPath + "geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("http://www.gap.com");

        WebElement menlink = driver.findElement(By.id("division5063"));
        menlink.click();

        WebElement shirtlink = driver.findElement(By.cssSelector("a.sidebar-navigation--category--link[href=/browse/category.do?cid=15043]"));
        shirtlink.click();
    }
}

However, I got this error:
Nov 01, 2016 2:10:13 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
JavaScript error: http://www.gap.com/, line 20471: TypeError: personalizationService.model.personalizationData.personalizationInfoV1.featureSelections is null
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700'
System info: host: 'RW-PC', ip: '192.168.0.105', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_112'
Driver info: driver.version: RemoteWebDriver
Capabilities [{rotatable=false, raisesAccessibilityExceptions=false, marionette=true, firefoxOptions={args=[], prefs={}}, appBuildId=20161019084923, version=, platform=XP, proxy={}, command_id=1, specificationLevel=0, acceptSslCerts=false, processId=1692, browserVersion=49.0.2, platformVersion=10.0, XULappId={ec8030f7-c20a-464f-9b0e-13a3a9e97384}, browserName=firefox, takesScreenshot=true, takesElementScreenshot=true, platformName=windows_nt, device=desktop}]
Session ID: 9c166d1b-3391-4ed9-8fac-3afe6d09b13f
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:622)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:465)
    at org.openqa.selenium.By$ByCssSelector.findElement(By.java:430)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at BuyMenShirt.main(BuyMenShirt.java:27)
Caused by: java.lang.IllegalArgumentException: expected one element but was: <org.openqa.selenium.remote.ErrorCodes$KnownError@cd2dae5, org.openqa.selenium.remote.ErrorCodes$KnownError@4973813a>
    at com.google.common.collect.Iterators.getOnlyElement(Iterators.java:322)
    at com.google.common.collect.Iterables.getOnlyElement(Iterables.java:284)
    at org.openqa.selenium.remote.ErrorCodes.toStatus(ErrorCodes.java:138)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:92)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:42)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    ... 5 more

Did I do something wrong? I notice I got some JavaScript error right before UnreachableBrowserException. Does it matter?