text:
Q: How to create a continuous stream of Python's concurrent.futures.ProcessPoolExecutor.submits()? I am able to submit batches of concurrent.futures.ProcessPoolExecutor.submits() where each batch may contain several submit(). However, I noticed that if each batch of submits consumes a significant about of RAM, there can be quite a bit of RAM usage inefficiencies; need to wait for all futures in the batch to be completed before another batch of submit() can be submitted.
How does one create a continuous stream of Python's concurrent.futures.ProcessPoolExecutor.submit() until some condition is satisfied?
Test Script:
#!/usr/bin/env python3

import numpy as np
from numpy.random import default_rng, SeedSequence
import concurrent.futures as cf
from itertools import count

def dojob( process, iterations, samples, rg ):
    # Do some tasks
    result = []
    for i in range( iterations ):
        a = rg.standard_normal( samples )
        b = rg.integers( -3, 3, samples )
        mean = np.mean( a + b )
        result.append( ( i, mean ) )
        return { process : result }

if __name__ == '__main__':

    cpus = 2
    iterations = 10000
    samples = 1000

    # Setup NumPy Random Generator
    ss = SeedSequence( 1234567890 )
    child_seeds = ss.spawn( cpus )
    rg_streams = [ default_rng(s) for s in child_seeds ]

    # Peform concurrent analysis by batches
    counter = count( start=0, step=1 )

    # Serial Run of dojob
    process = next( counter )
    for cpu in range( cpus ):
        process = next( counter )
        rg = rg_streams[ cpu ]
        rdict = dojob( process, iterations, samples, rg )
    print( 'rdict', rdict )

    # Concurrent Run of dojob
    futures = []
    results = []
    with cf.ProcessPoolExecutor( max_workers=cpus ) as executor:

        while True:

            for cpu in range( cpus ):
                process = next( counter )
                rg = rg_streams[ cpu ]
                futures.append( executor.submit( dojob, process, iterations, samples, rg ) )

            for future in cf.as_completed( futures ):
                # Do some post processing
                r = future.result()
                for k, v in r.items():
                    if len( results ) < 5000:
                        results.append( np.std( v ) )
                        print( k, len(results) )

            if len(results) <= 100: #Put a huge number to simulate continuous streaming
                futures = []
                child_seeds = child_seeds[0].spawn( cpus )
                rg_streams = [ default_rng(s) for s in child_seeds ]
            else:
                break

    print( '\n*** Concurrent Analyses Ended ***' )

A: To expand on my comment, how about something like this, using the completion callback and a threading.Condition? I took the liberty of adding a progress indicator too.
EDIT: I refactored this into a neat function you pass your desired concurrency and queue depth, as well as a function that generates new jobs, and another function that processes a result and lets the executor know whether you've had enough.
import concurrent.futures as cf
import threading
import time
from itertools import count

import numpy as np
from numpy.random import SeedSequence, default_rng

def dojob(process, iterations, samples, rg):
    # Do some tasks
    result = []
    for i in range(iterations):
        a = rg.standard_normal(samples)
        b = rg.integers(-3, 3, samples)
        mean = np.mean(a + b)
        result.append((i, mean))
    return {process: result}

def execute_concurrently(cpus, max_queue_length, get_job_fn, process_result_fn):
    running_futures = set()
    jobs_complete = 0
    job_cond = threading.Condition()
    all_complete_event = threading.Event()

    def on_complete(future):
        nonlocal jobs_complete
        if process_result_fn(future.result()):
            all_complete_event.set()
        running_futures.discard(future)
        jobs_complete += 1
        with job_cond:
            job_cond.notify_all()

    time_since_last_status = 0
    start_time = time.time()
    with cf.ProcessPoolExecutor(cpus) as executor:
        while True:
            while len(running_futures) < max_queue_length:
                fn, args = get_job_fn()
                fut = executor.submit(fn, *args)
                fut.add_done_callback(on_complete)
                running_futures.add(fut)

            with job_cond:
                job_cond.wait()

            if all_complete_event.is_set():
                break

            if time.time() - time_since_last_status > 1.0:
                rps = jobs_complete / (time.time() - start_time)
                print(
                    f"{len(running_futures)} running futures on {cpus} CPUs, "
                    f"{jobs_complete} complete. RPS: {rps:.2f}"
                )
                time_since_last_status = time.time()

def main():
    ss = SeedSequence(1234567890)
    counter = count(start=0, step=1)
    iterations = 10000
    samples = 1000
    results = []

    def get_job():
        seed = ss.spawn(1)[0]
        rg = default_rng(seed)
        process = next(counter)
        return dojob, (process, iterations, samples, rg)

    def process_result(result):
        for k, v in result.items():
            results.append(np.std(v))
        if len(results) >= 10000:
            return True  # signal we're complete

    execute_concurrently(
        cpus=16,
        max_queue_length=20,
        get_job_fn=get_job,
        process_result_fn=process_result,
    )

if __name__ == "__main__":
    main()

A: The Answer posted by @AKX works. Kudos to him. After testing it, I would like to recommend two amendments that I believe are worth considering and implementing.
Amendment 1: To prematurely cancel the execution of the python script, Ctrl+C has to be used. Unfortunately, doing that would not terminate the concurrent.futures.ProcessPoolExecutor() processes that are executing the function dojob(). This issue becomes more pronounced when the time is taken to complete dojob() is long; this situation can be simulated by making the sample size in the script to be large (e.g. samples = 100000). This issue can be seen when the terminal command ps -ef | grep python is executed. Also, if dojob() consumes a significant amount of RAM, the memory used by these concurrent processes do not get released until the concurrent processes are manually killed (e.g. kill -9 [PID]). To address these issues, the following amendment is needed.
with job_cond:
    job_cond.wait()

should be changed to:
try:
    with job_cond:
        job_cond.wait()
except KeyboardInterrupt:
    # Cancel running futures
    for future in running_futures:
        _ = future.cancel()
    # Ensure concurrent.futures.executor jobs really do finish.
    _ = cf.wait(running_futures, timeout=None)

So when Ctrl+C has to be used, you just have to press it once first. Next, give some time for the futures in running_futures to be cancelled. This could take a few seconds to several seconds to complete; it depends on the resource requirements of dojob(). You can see the CPUs activity in your task manager or system monitor drops to zero or hear the high revving sound from your cpu cooling fan reduce. Note, the RAM used would not be released yet. Thereafter, press Ctrl+C again and that should allow a clean exit of all the concurrent processes whereby the used RAM are also released.
Amendment 2: Presently, the inner while-loop dictates that jobs must be submitted continuously as fast as the cpu "mainThread" can allow. Realistically, there is no benefit to be able to submit more jobs than there are available cpus in the cpus pool. Doing so only unnecessarily consumes cpu resources from the "MainThread" of the main processor. To regulate the continuous job submission, a new submit_job threading.Event() object can be used.
Firstly, define such an object and set its value to True with:
submit_job = threading.Event()
submit_job.set()

Next, at the end of the inner while-loop add this condition and .wait() method:
with cf.ProcessPoolExecutor(cpus) as executor:
    while True:
        while len(running_futures) < max_queue_length:
            fn, args = get_job_fn()
            fut = executor.submit(fn, *args)
            fut.add_done_callback(on_complete)
            running_futures.add(fut)
            if len(running_futures) >= cpus: # Add this line
                submit_job.clear()           # Add this line
            submit_job.wait()                # Add this line

Finally change the on_complete(future) callback  to:
def on_complete(future):
    nonlocal jobs_complete
    if process_result_fn(future.result()):
        all_complete_event.set()
    running_futures.discard(future)
    if len(running_futures) < cpus: # add this conditional setting
        submit_job.set()            # add this conditional setting
    jobs_complete += 1
    with job_cond:
        job_cond.notify_all()

A: There is a library called Pypeln that does this beautifully. It allows for streaming tasks between stages, and each stage can be run in a process, thread, or asyncio pool, depending on what is optimum for your use case.
Sample code:
import pypeln as pl
import time
from random import random

def slow_add1(x):
    time.sleep(random()) # <= some slow computation
    return x + 1

def slow_gt3(x):
    time.sleep(random()) # <= some slow computation
    return x > 3

data = range(10) # [0, 1, 2, ..., 9]

stage = pl.process.map(slow_add1, data, workers=3, maxsize=4)
stage = pl.process.filter(slow_gt3, stage, workers=2)

data = list(stage) # e.g. [5, 6, 9, 4, 8, 10, 7]


text:
Q: Eu não consigo compilar meu programa pois, estou com um erro que diz "NullPointerException" Estou tentando montar um projeto em Java segundo os conceitos de programação orientada objetos.
No entanto o compilador(ECLIPSE) acusa um erro na linha da minha função liigar. Ele diz que tem um erro de NullPointerException. Pesquisando na internet vi que isso é quando a variável é "não inicialiazada". Chequei meu programa e tenho um valor default que eu coloco para a varável como um "false". Gostaria de poder entender porque o eclipse está acusando este erro.
Nesta classe eu coloquei a main:
public class TestaCarro {

public static void main(String[] args){

    Carro meuCarro = new Carro();

        meuCarro.setCor("Azul");

        meuCarro.setModelo("Gol");
        // ligando o carro
        meuCarro.ligar();
        // Acelerando o carro
        meuCarro.acelerar(80);
        // Obtendo a marcha atual
        int marchaAtual = meuCarro.obtemMarcha();

        // Imprimindo informações sobre o carro e o estado dos atributos
        System.out.print("Meu " + meuCarro.getModelo() + " " + meuCarro.getCor() + " ");
        System.out.print("Está andando na marcha " + marchaAtual + " a ");
        System.out.print(meuCarro.getVelocidadeAtual() + " Km/h!!!");

        // Parando o carro
        meuCarro.parar();

        // Acelerando o carro novamente
        meuCarro.acelerar(20);
        // Obtendo a marcha atual novmente
        marchaAtual = meuCarro.obtemMarcha();

        // Imprimindo(novamente) informações sobre o carr e o estado dos atributos
        System.out.print("Agora, meu " + meuCarro.getModelo() + " " + meuCarro.getCor() + " ");
        System.out.print(" está andando na marcha " + marchaAtual + " a ");
        System.out.println(meuCarro.getVelocidadeAtual() + " Km/h!!!");

        // Parando o carro
        meuCarro.parar();

        // Desligando o carro
        meuCarro.desligar();
    }
}

Nesta classe tenho a primeira função ligar:
public class Carro {
    private String cor, modelo;// get e set
    private int velocidadeAtual;// Apenas get
    private double velocidadeMaxima = 140;// Definido por default + get
    private Motor motor; // get e set

    // Método para ligar o carro
    public void ligar() {
        if (this.motor.ligar())
            System.out.println("O carro está sendo ligado...");
    }

    // Método para parar o carro
    public void parar() {
        System.out.println("Parando o carro...");
        this.velocidadeAtual = 0;
    }

    // Método para desligar o carro
    public void desligar() {
        if (this.motor.desligar()) {
            System.out.println("O carro está sendo desligado...");
        } else {
            System.out.println("Não há como desligar um carro em movimento.");
        }
    }

    // Métodos get, set, acelerar, obterMarcha...
    public String getCor() {
        return cor;
    }

    public void setCor(String cor) {
        this.cor = cor;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public Motor getMotor() {
        return motor;
    }

    public void setMotor(Motor motor) {
        this.motor = motor;
    }

    public double getVelocidadeAtual() {
        return velocidadeAtual;
    }

    public double getVelocidadeMaxima() {
        return velocidadeMaxima;
    }
    //Método qued devolve a marcha em que o carro está.
    public void acelerar(double velocidade){
        this.velocidadeAtual+=velocidade;
    }
// Método que devolve a marcha em que o carro está

        public int obtemMarcha() {

         if(this.velocidadeAtual<=0) {
            return -1;
        }
        else {
              if(this.velocidadeAtual<=20) {
                return 1;
        }
        else {
              if(this.velocidadeAtual<=40) {
                return 2;
            }
            else {
                  if(this.velocidadeAtual<=60) {
                    return 3;
                }
                else {
                      if(this.velocidadeAtual<=80) {
                            return 4;
                        }
                         else {
                            return 5;
                         }

                }
            }
        }
    }
}

}

Agora eu inicializo nesta outra class a função ligar:
public class Motor {

    private double potencia;// get e set
    private String tipoDeCombustivel;// get set
    private boolean ligado = false;// is e set

    public boolean ligar() {
        this.ligado = true;
        System.out.println("Ligando o motor...");
        return true;
    }

    public boolean desligar() {
        this.ligado = false;
        System.out.println("Desligando o motor..");
        return true;
    }

    public double getPotencia() {
        return potencia;
    }

    public void setPotencia(double potencia) {
        this.potencia = potencia;
    }

    public String getTipoDeCombustivel() {
        return tipoDeCombustivel;
    }

    public void setTipoDeCombustivel(String tipoDeCombustivel) {
        this.tipoDeCombustivel = tipoDeCombustivel;
    }

    public boolean isLigado() {
        return ligado;
    }

    public void setLigado(boolean ligado) {
        this.ligado = ligado;
    }

}

A: Se está dando erro de NullPointer no método ligar e este encontra-se na classe Motor, o mais provável é que você não criou um objeto de Motor.
Na sua classe Carro tem uma variável do tipo Motor, certo? Chamar um método da classe motor causa erro de NullPointer porque ela é apenas uma variável, e não um objeto.
Faça o seguinte, dentro do seu construtor da classe Carro, instancie o objeto Motor da seguinte forma:
motor = new Motor();

Agora motor é um objeto e será possível chamar os métodos que ele possui.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linking Modules into Small Footprint Assemby According to http://blogs.msdn.com/b/junfeng/archive/2005/02/12/371683.aspx I should be able to create a single .exe file build from some source code and a .netmodule file. However, after looking at http://msdn.microsoft.com/en-us/library/92b5ab4h.aspx and http://msdn.microsoft.com/en-us/library/k669k83h.aspx I cannot seem to make this happen. Whenever I run my .exe it is looking for the .netmodule externally.
Does anyone know of any example showing which options I have to pass to csc to make this do what I want?
For example I have, common.netmodule and program.cs, and I want a single file program.exe that has common.netmodule in the assembly.

A: After rethinking things, I decided to solve the problem at the source code level. Instead of compiling a common.netmodule file, I just have Maven copy my common.cs file into the project specific directories, and then compile. It works, it's simple, and I cannot believe I wasted so much time trying to figure out the abstruse details of .Net assemblies.


text:
Q: The Microsoft Jet database engine could not find the object 'Sheet1$_' I am reading data from an Excel file. when I read the normal Excel file,It works fine but when I read an excel file which has columns like shown below it does not find the work sheet and gives an exception-

The Microsoft Jet database engine could not find the object 'Sheet1$_'.  Make sure the object exists and that you spell its name and the path name correctly.

My Code to read the excel is-
  private static DataTable getExcelData(string ExcelPath)
    {
        OleDbConnection con;
        string connectionString;
        string[] pathArray = ExcelPath.Split('.');
        var Extention = pathArray[pathArray.Length - 1];
        if (Extention == "xlsx")
            //read a 2007 file
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                ExcelPath + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
        else
            //read a 97-2003 file
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                ExcelPath + ";Extended Properties=Excel 8.0;";

        con = new OleDbConnection(connectionString);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        DataTable dbSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null);
        var firstSheetName = dbSchema.Rows[0]["TABLE_NAME"];
        OleDbDataAdapter cmd = new OleDbDataAdapter("select * from [" + firstSheetName + "] Where NOT [Event Code]=''", con);
        DataSet ds = new DataSet();
        cmd.Fill(ds);
        con.Close();
        return ds.Tables[0];
    }

}

I have to get all the columns inside Mon,Tues etc.

A: GetOleDbSchemaTable also returns hidden tables in your Excel file: usually a name like Sheet1$_ indicates an hidden table created when you apply a filter on Sheet1$.
You need to change your code: search for table that ends with $ to set firstSheetName.
Please note that OLEDB does not preserve the sheet order as they were in Excel.
Also note that you need to do this to read an excel file with multirow titles:

*

*set HDR=No in EXTENDED PROPERTIES of your connection string

*specify column name and select range in your OleDbCommand in order to skip the first two rows

For example:
SELECT [F1] AS Location,
    [F2] AS EmpId,
    [F3] AS EmpName,
    [F4] AS MondayShift,
    [F5] AS Monday15Min,
    [F6] AS Monday30Min,
    [F7] AS Monday15Min2
FROM [Sheet1$A3:G]


text:
Q: Error on map reduce example of Hadoop 2.2.0 I am new to hadoop and after installing Hadoop 2.2.0 I tried to follow example  http://www.srccodes.com/p/article/45/run-hadoop-wordcount-mapreduce-example-windows to try a simple map reduce job.
However whenever I try to do the map reduce job over the txt file I created, I keep getting failures with this message
c:\hadoop>bin\yarn jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.2.0.ja
r wordcount /input output
14/03/26 14:20:48 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0
:8032
14/03/26 14:20:50 INFO input.FileInputFormat: Total input paths to process : 1
14/03/26 14:20:51 INFO mapreduce.JobSubmitter: number of splits:1
14/03/26 14:20:51 INFO Configuration.deprecation: user.name is deprecated. Inste
ad, use mapreduce.job.user.name
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.jar is deprecated. Inst
ead, use mapreduce.job.jar
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.output.value.class is d
eprecated. Instead, use mapreduce.job.output.value.class
14/03/26 14:20:51 INFO Configuration.deprecation: mapreduce.combine.class is dep
recated. Instead, use mapreduce.job.combine.class
14/03/26 14:20:51 INFO Configuration.deprecation: mapreduce.map.class is depreca
ted. Instead, use mapreduce.job.map.class
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.job.name is deprecated.
 Instead, use mapreduce.job.name
14/03/26 14:20:51 INFO Configuration.deprecation: mapreduce.reduce.class is depr
ecated. Instead, use mapreduce.job.reduce.class
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.input.dir is deprecated
. Instead, use mapreduce.input.fileinputformat.inputdir
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.output.dir is deprecate
d. Instead, use mapreduce.output.fileoutputformat.outputdir
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.map.tasks is deprecated
. Instead, use mapreduce.job.maps
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.output.key.class is dep
recated. Instead, use mapreduce.job.output.key.class
14/03/26 14:20:51 INFO Configuration.deprecation: mapred.working.dir is deprecat
ed. Instead, use mapreduce.job.working.dir
14/03/26 14:20:51 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_13
95833928952_0004
14/03/26 14:20:52 INFO impl.YarnClientImpl: Submitted application application_13
95833928952_0004 to ResourceManager at /0.0.0.0:8032
14/03/26 14:20:52 INFO mapreduce.Job: The url to track the job: http://GoncaloPe
reira:8088/proxy/application_1395833928952_0004/
14/03/26 14:20:52 INFO mapreduce.Job: Running job: job_1395833928952_0004
14/03/26 14:21:08 INFO mapreduce.Job: Job job_1395833928952_0004 running in uber
 mode : false
14/03/26 14:21:08 INFO mapreduce.Job:  map 0% reduce 0%
14/03/26 14:21:20 INFO mapreduce.Job: Task Id : attempt_1395833928952_0004_m_000
000_0, Status : FAILED
Error: java.lang.ClassCastException: org.apache.hadoop.mapreduce.lib.input.FileS
plit cannot be cast to org.apache.hadoop.mapred.InputSplit
        at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:402)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:162)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInforma
tion.java:1491)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:157)
14/03/26 14:21:33 INFO mapreduce.Job: Task Id : attempt_1395833928952_0004_m_000
000_1, Status : FAILED
Error: java.lang.ClassCastException: org.apache.hadoop.mapreduce.lib.input.FileS
plit cannot be cast to org.apache.hadoop.mapred.InputSplit
        at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:402)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:162)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInforma
tion.java:1491)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:157)
14/03/26 14:21:48 INFO mapreduce.Job: Task Id : attempt_1395833928952_0004_m_000
000_2, Status : FAILED
Error: java.lang.ClassCastException: org.apache.hadoop.mapreduce.lib.input.FileS
plit cannot be cast to org.apache.hadoop.mapred.InputSplit
        at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:402)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
        at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:162)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInforma
tion.java:1491)
        at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:157)
14/03/26 14:22:04 INFO mapreduce.Job:  map 100% reduce 100%
14/03/26 14:22:10 INFO mapreduce.Job: Job job_1395833928952_0004 failed with sta
te FAILED due to: Task failed task_1395833928952_0004_m_000000
Job failed as tasks failed. failedMaps:1 failedReduces:0
14/03/26 14:22:10 INFO mapreduce.Job: Counters: 6
        Job Counters
                Failed map tasks=4
                Launched map tasks=4
                Other local map tasks=3
                Data-local map tasks=1
                Total time spent by all maps in occupied slots (ms)=48786
                Total time spent by all reduces in occupied slots (ms)=0

Since I followed everything with no issues step by step I have no idea why this might be, does anyone know?
Edit: Tried adopt 2.3.0 same issue happens with the example jar given, and the code bellow I tried compile, no idea what the issue is
import java.io.IOException;
import java.util.*;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class teste {

   public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
      private final static IntWritable one = new IntWritable(1);
      private Text word = new Text();

      public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
         String line = value.toString();
         StringTokenizer tokenizer = new StringTokenizer(line);
         while (tokenizer.hasMoreTokens()) {
            word.set(tokenizer.nextToken());
            context.write(word, one);
         }
      }
   }

   public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {

      public void reduce(Text key, Iterable<IntWritable> values, Context context)
         throws IOException, InterruptedException {
         int sum = 0;
         for (IntWritable val : values) {
            sum += val.get();
         }
         context.write(key, new IntWritable(sum));
      }
   }

   public static void main(String[] args) throws Exception {
      Configuration conf = new Configuration();

      Job job = new Job(conf, "wordcount");

      job.setJarByClass(teste.class);
      job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(IntWritable.class);

      job.setMapperClass(Map.class);
      job.setReducerClass(Reduce.class);

      job.setInputFormatClass(TextInputFormat.class);
      job.setOutputFormatClass(TextOutputFormat.class);

      FileInputFormat.addInputPath(job, new Path(args[0]));
      FileOutputFormat.setOutputPath(job, new Path(args[1]));

      job.waitForCompletion(true);
   }

}

A: I had the same issue (java.lang.ClassCastException) and was able to solve it by running Hadoop with admin privileges. The problem seems to be the creation of symbolic links which by default is not possible for non-admin Windows users. Open a console as administrator and then proceed as described in the example from your link.

A: link you provided has input perameter as input NOT /input...try with this syntax...
C:\hadoop>bin\yarn jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.2.0.jar wordcount input output

if this doesn't work than see this - Link  and modify the mapper class.


text:
Q: How to set fixed size mask in android image cropping? I am trying to crop an image from Gallery. When I tried to crop it, a mask is appeared and then I can re-size the mask width and height. But I want the mask can't be re-sizable. User will just have to move the mask only but not able to re-size the mask or rectangle size. So I want the mask size will be fixed. I tried many solution but did not work. Here is the sample code
intent.putExtra("crop", "true");
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 4);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);

Sample problem. How can I solve the problem?


text:
Q: Trackpad gesture to select text Ok, it should be very easy one to figure out but I can't do it, so I'm asking experts. I want to know which one is accurate trackpad gesture for selecting text. Is it "three finger swipe right" or "one finger fixed with two fingers swipe down" or "three fingers swipe down" or any other ??
This is the  context in which I'm asking this question.
I'm trying to automate my text selection to get highlighted in preview and to get copied to clipboard in web browser. Two different things , but selecting text & assigning gesture is common.
The way I select text in browser is by "three fingers drag right & down simultaneously".
This is how automatic highlighting worked in preview: selected text by "three finger swipe right" -  assigned action "^ command H" to this gesture using bettertouchtool app & selected text is highlighted. But can't use same technique in web browser to automatically copy my text with trackpad gesture.
When I use "three fingers swipe right" gesture in browser it only selects few words or one line & not the entire set of lines/para like in preview. So what will be right trackpad gesture to select text in browser. I hope its clear now.

A: I think this link may help you out. "Three Fingers Drag" is not in Trackpad Preferences. It's in Accessibility.
http://www.idownloadblog.com/2015/06/25/three-finger-drag-gesture-os-x-el-capitan/
Admin please pardon me for pasting links.
James
From Vietnam.

A: You can enable a three-finger-drag in system preferences, under touchpad/trackpad. Then, you can use three fingers to select text.
(Assuming that is what you're asking, it is not very clear to me.)


text:
Q: Where and How Event watcher run in Async, Await I am going through Async programming and I understand that there is an
EventTable, Event Queue and Event loop.
In my understanding every-time compiler sees await in call-stack it registers an entry in Event Table. Whenever the result of async comes, entry from the event table is removed and put to Event queue.
let's say we are making an http call in async function. so I believe an entry will be made in Event Table and whenever response is returned from the http call particular code will be put in EventQueue to run. And Event loop will take care of running the code. But My question is who makes the http call and who is tracking the response from the api similarly in the case of setTimeout() who is running the clock and checking the entires in Event Table?
If some other process is keeping a track, that means on a single core machine 3 processes are running

*

*event loop

*actual function (whenever event loops pulls something out from event queue)

*cron like job who keeps track of time, async response etc etc?
Extension of the above question is what classifies to be run as async.
Can we run a = b + c as async? (IMO, no since b+c will need to be calculated on machine only, hence does not make sense to do a = b + c in an async function)
If yes
who will take care of calculating b + c?
If not what is the rule for a function to be truly async


text:
Q: How can I stop a JavaScript from executing if an element exists? I have a Firefox addon that injects/executes a jQuery script on every page at sub.example.com. The script doesn't work on one page of the site, because of bad design. Is there any way to stop the script from being executed if a certain element is located on the page?
EDIT: The script I am using has to be executed before the DOM loads. Is there any way to access the HTML file itself and find out if the element exists?

A: Since jQuery collections are just beefed up arrays, they each have a length property, which tells you how many elements it has matched:
jQuery(document).ready(function($)
{
    if ( $('#someElement').length ) return;
    // All of your code should go here...
});

A: Since you're using jQuery, I assume your script is wrapped in a $(document).ready callback, if so:
$(document).ready(function() {
    if ($('#breakOnThisElem').length) {
       return;
    }
});

If your code isn't wrapped in a function like this: change it! :)


text:
Q: Как авторизизоваться и загрузить фото профиля мой мир[mail.ru]? Хочу сделать авторизацию сессиями(requests) python в сервисе мой мир
и далее загрузить фото профиля.
Естественно селениумом я уже все сделал, но если что-то поменяется, то весь скрипт полетит, например банер появится.
Пожалуйста помогите, уже 3 дня не могу сделать. Я пробовал повторять запросы через Burp Suite, смотрел как браузер шлет запросы, это не помогло. У mail есть свое апи, но чтобы зарегать приложение обязательно нужно делать это руками или селениумом + мой мир там не поддерживается те методы, которые мне нужны.
Вот что выдает burp suite

Так же я не смог найти куда я должен писать логин и пароль чтобы авторизовать. В дате находятся какие-то странны значения, которые нигде не взять.
При загрузки фотографии появились так же неприятности, даже если я вписывал кукисы браузера.
Вообще не ясно что писать в дате чтобы запрос обработался.
Все что пока что получилось сделать, это авторизацию в light mail ru, но в мой мир нужны другие куки
кукисы поменял, так что не пробуйте их использовать
Код который я пытался использовать для загрузки картинки

import requests
cookies = {
    '$act': 'a83d04d4d54840d9adca40ced24262c6',
    'mrcu': 'CB44619E6BB71E86F4999B6CEC6D',
    'p': 'AHMAABb/VgAA',
    'tmr_lvid': 'd12c1003ee8804c32ef6ec0a88c2e284',
    'tmr_lvidTS': '1620995001627',
    't': 'obLD1AAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAACAAAkB0AcA',
    's': 'octavius=1',
    'Mpop': '1620995011:465c517d057b54581905000017031f051c054f6c5150445e05190401041d0309000750575e5d5d51595e595b145c555e551f4243:2001angelahill@mail.ru:',
    'sdcs': 'SZfKeBy4GAu3jXcd',
    'hses': '1',
    'searchuid': '7146720301620995113',
    'VID': '2C2TgT0spz2200000U0yD4o2:::5b8c4e7-0-0-5b8c479:CAASED9cbdpJckH17mJp6cbZzXQaYBveTHgwffXN__f8EjhxqjjJ1tRo5ahnoO5M0QzUy5iGzpX3dea5vHhLU74XxH_UNvLChywNBRTH2X0fS7oeBBt2oAq49-O-r5exhY3nJORAMwu1bi78YJPbyTyweZhYSA',
    '_showsc_1921420075': '1',
    'c': 'MGyeYAEAEHsTAAAUAQAACQDgmVbIAQAA',
    'b': 'SEkCAJCp1/0AJwnWhgAAAAIA',
    'tmr_reqNum': '38',
}

headers = {
    'Host': 'upload-12.my.mail.ru',
    'Connection': 'close',
    'Content-Length': '51232',
    'sec-ch-ua': '\\"Chromium\\";v=\\"89\\", \\";Not A Brand\\";v=\\"99\\"',
    'Accept': '*/*',
    'sec-ch-ua-mobile': '?0',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
    'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryhOu76ALnKJYjALeM',
    'Origin': 'https://my.mail.ru',
    'Sec-Fetch-Site': 'same-site',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'https://my.mail.ru/',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
}

with open('/home/depocode/Downloads/images/image_1', 'rb') as file:
    content = file.read()
response = requests.post('https://upload-12.my.mail.ru/uploadphoto', headers=headers, cookies=cookies, data={'file': content})

пытался залогиниться
resp = s.post('https://auth.mail.ru/cgi-bin/auth', data={
    'username': '2001angelahill@mail.ru',
    'password': '_53uJpe%$y'}
              )

пытался залогиниться v.2
import requests
cookies = {
    'p': '1gACOM/9BwAA',
    'searchuid': '692413531621243871',
    'mrcu': '50D360A237E002DA059A9B6CEC6D',
    'tmr_lvid': '7a77320aa5f463ec54e25a81bdad2707',
    'tmr_lvidTS': '1631243873831',
    'act': '5d695f26353c4bfc8906987b7765169d',
    't': 'obLD1AAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAACAAAkB0AcA',
    'b': 'S0kBAJC6tnQA30EShRMAAEA4rxVdBwAA',
    'c': 'jTiiYAEAEHsTAAAUAQAACQDgfVbIAQAA',
    'i': 'AQCNoKJgAQDJAAUCAQA=',
    'Mpop': '1618475646:5f4e64655474517c1905000017031f051c054f6c5150445e05190401041d0309000750575e5d5d51595e595b145c555e551f4243:2001afgelahill@mail.ru:',
    'tmr_reqNum': '13',
    'VID': '1rQ6E70909Y200000U0yD4o2:::5bc9148-0-0-5bc90a2:CAASENmXgK9GeWpGuARl3u_XPEUaYJqljFU1XFnUgFGp78kic3ZKPJXSgD3AQZ6Ey9bs4gIN4_6AaBHWQjaVHghf-X9rpqugX1Ea2WQJX5vvYv-kORPZ5OxuW95_EKiPZRTv0jz2Bq0efIsSDiYcl8TRfCazrA',
}

headers = {
    'Host': 'account.mail.ru',
    'Connection': 'close',
    'Content-Length': '164',
    'sec-ch-ua': '\\"Chromium\\";v=\\"89\\", \\";Not A Brand\\";v=\\"99\\"',
    'sec-ch-ua-mobile': '?0',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
    'Content-Type': 'text/plain;charset=UTF-8',
    'Accept': '*/*',
    'Origin': 'https://account.mail.ru',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'https://account.mail.ru/login/?mode=simple&v=2.8.1&account_host=account.mail.ru&type=login&modal=1&allow_external=1&success_redirect=https%3A%2F%2Fmy.mail.ru%2F&opener=mail.login&noinnerscroll=1&wide=1&rebranding2018=1&parent_url=https%3A%2F%2Fe.mail.ru%2Fcgi-bin%2Flogin%3Flang%3Den_US%26page%3Dhttps%3A%2F%2Fmy.mail.ru%2F',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.9',
}

params = (
    ('p', 'login'),
    ('split', 's10273.b1s'),
    ('r', 'https://e.mail.ru/'),
    ('pgid', 'koseulnr.pds'),
)

data = 'batch=%5B%7B%22v%22%3A%221%22%2C%22skipdwh%22%3A%22false%22%2C%22i%22%3A%22form_submit%3A1%22%2C%22t%22%3A%22mail-login_ref_mymailru%22%2C%22uid%22%3A%2257%22%7D%5D'

response = requests.post('https://account.mail.ru/api/v1/utils/xray/batch', headers=headers, params=params, cookies=cookies, data=data)

upd. нашел мобайл версию и логинюсь так, только теперь надо другую штуку обойти
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'https://m.my.mail.ru',
    'Connection': 'keep-alive',
    'Referer': 'https://m.my.mail.ru/',
    'Upgrade-Insecure-Requests': '1',
    'Sec-GPC': '1',
}
data = {
  'Login': '1998christoaherwatkins@mail.ru',
  'Domain': 'mail.ru',
  'Password': '+9C5U2cfCO',
  'page': 'https://m.my.mail.ru/',
  'FailPage': 'https://m.my.mail.ru/cgi-bin/login?infomessage=bad_password&page=https://m.my.mail.ru/'
}
s = requests.session()
response = s.post('https://auth.mail.ru/cgi-bin/auth?rand=2777947971', headers=headers, data=data)

upd 2.
эту штуку я тоже уже обошел, но теперь кукисы не подходят для обычной версии сайта они очень сильно поломались

код как я обошел подтверждение номера
        resp = s.post('https://account.mail.ru/api/v1/user/copper',
                  json={'fields': {"phone": phone}, 'htmlencoded': False})
    resp.raise_for_status()
    if resp.json().get('body'):
        url = resp.json()['body']['url']
        response = s.get(url)
        response.raise_for_status()

Буду рад любой помощи, всем добра.


text:
Q: Left outer join with extra conditions in django I have problems to do this SQL with django queryset+Q objects.
How can I do that without raw query?
SELECT *
FROM Table1 T1
LEFT OUTER JOIN Table2 T2 ON T1.id == T2.fk_id AND (T2.VALUE = 'val1' OR T2.VALUE IS NULL)

A: I think you might have been looking for the Prefetch object, but that likely didn't exist 5 years ago. Any way this is one way to implement it now.
You need the filter in both locations to make sure you're getting the appropriate T1 and T2 instances. Then the Prefetch will actually do an additional query to pull all the related T2 instances. The distinct is so that if there are multiple T2 instances, there aren't duplicate T1 instances returned.
from django.db.models import Prefetch
t2_filter = Q(t2_set__value__isnull=True) | Q(t2_set__value='val1')
T1.objects.filter(
    t2_filter,
    t2_set__isnull=False,
).prefetch_related(
    Prefetch(
        't2_set',
        T2.objects.filter(t2_filter),
        to_attr='filtered_t2_set',
    )
).distinct()


text:
Q: gearmand: Could not open log file "/usr/local/var/log/gearmand.log" I'm trying to install gearman in my Ubuntu 12.04.
Actually installation is successful. But when I start the daemon, I'm getting this error.
gearmand: Could not open log file "/usr/local/var/log/gearmand.log" from xxxx switching to stderr. (No such file or directory)
Am I missing anything here? I tried installing various versions of gearman, still the result is same.
Any help please...

A: /usr/local/var/log/gearmand.log is default value of --log-file option.
See gearmand --help
  -l [ --log-file ] arg (=/usr/local/var/log/gearmand.log)
                                        Log file to write errors and
                                        information to. If the log-file
                                        parameter is specified as 'stderr',
                                        then output will go to stderr. If
                                        'none', then no logfile will be
                                        generated.


text:
Q: Generics to return a struct of asked Type I'm having a function like this:
func someFunction<T: Codable>(x: Double, y: Double, outputClass: T, completionBlock: CompletionBlock)

the completionblock is:
enum Result {
    case success(Codable)
    case failure(String?)
}

typealias CompletionBlock = (Result) -> Void

What I want to achieve is that when you call the function for example like this:
someFunction(x: 12, y: 12, outputClass: Foo.self) { (result) in
   switch result {
   case .success(let result):
}

That my let result in the success case is of type Foo.
I have a Foo struct:
struct Foo: Codable {
    let content: String
}

Now when I try to call the function xCode tells me:
Argument type 'Foo.Type' does not conform to expected type 'Encodable'

But the struct conforms to the type Codable and that is encodable & decodable.
Can someone explain me what I'm doing wrong?

A: I think you need to wrap your function inside a generic class, and put the enum inside the class as well. This way, you can use the generic parameter T of the class instead of the T in the function. You also don't need the outputType parameter.
class SomeClass<T: Codeable> {
    class func someFunction(x: Double, y: Double, completionBlock: CompletionBlock) {

    }

    enum Result {
        case success(T)
        case failure(String?)
    }

    typealias CompletionBlock = (Result) -> Void
}

struct Foo: Codeable {

}

// usage
SomeClass<Foo>.someFunction(x: 0, y: 0) { (x) in
    switch x {
    case .success(let result):
        // result is now of type Foo
    case .failure:
        break
    }
}


text:
Q: driver.refresh() cant get driver.get() to work for certain url I was trying to verify the URL of a certain online store. Here is the code demo
ser = Service(r"C:\\Users\\user\\Downloads\\chromedriver.exe")
driver = webdriver.Chrome(service=ser)

def valid(url):

    driver.get(url)
    get_source = driver.page_source

    search_text = "Sorry, this page"

    if search_text in get_source:
        get_url=0
    else:
        get_url = driver.current_url

    driver.refresh()

    return get_url

my_list=[valid('https://www.google.com'),
       valid('https://www.farfetch.com/hk/shopping/women/guucci/items.aspx')
       valid('https://www.farfetch.com/hk/shopping/women/gucci/items.aspx'),
       valid('https://www.yahoo.com')
      ]

print(lists)

The result I got is as follow
WebDriverException                        Traceback (most recent call last)
Input In [25], in <cell line: 22>()
     17     driver.refresh()
     19     return get_url
     22 lists=[valid('https://www.google.com'),
     23        valid('https://www.farfetch.com/hk/shopping/women/gucci/items.aspx'),
---> 24        valid('https://www.yahoo.com')
     25       ]
     28 print(lists)

Input In [25], in valid(url)
      5 def valid(url):
----> 7     driver.get(url)
      8     get_source = driver.page_source
     10     search_text = "Sorry, this page"

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\webdriver.py:447, in WebDriver.get(self, url)
    443 def get(self, url: str) -> None:
    444     """
    445     Loads a web page in the current browser session.
    446     """
--> 447     self.execute(Command.GET, {'url': url})

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\webdriver.py:435, in WebDriver.execute(self, driver_command, params)
    433 response = self.command_executor.execute(driver_command, params)
    434 if response:
--> 435     self.error_handler.check_response(response)
    436     response['value'] = self._unwrap_value(
    437         response.get('value', None))
    438     return response

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\selenium\webdriver\remote\errorhandler.py:247, in ErrorHandler.check_response(self, response)
    245         alert_text = value['alert'].get('text')
    246     raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 247 raise exception_class(message, screen, stacktrace)

WebDriverException: Message: unknown error: unexpected command response
  (Session info: chrome=103.0.5060.114)
Stacktrace:
Backtrace:
    Ordinal0 [0x00DF6463+2188387]
    Ordinal0 [0x00D8E461+1762401]
    Ordinal0 [0x00CA3D78+802168]
    Ordinal0 [0x00C97210+750096]
    Ordinal0 [0x00C9675A+747354]
    Ordinal0 [0x00C95D3F+744767]
    Ordinal0 [0x00C9557C+742780]
    Ordinal0 [0x00CA9BF3+826355]
    Ordinal0 [0x00CFCB47+1166151]
    Ordinal0 [0x00CEC5F6+1099254]
    Ordinal0 [0x00CC6BE0+945120]
    Ordinal0 [0x00CC7AD6+948950]
    GetHandleVerifier [0x010971F2+2712546]
    GetHandleVerifier [0x0108886D+2652765]
    GetHandleVerifier [0x00E8002A+520730]
    GetHandleVerifier [0x00E7EE06+516086]
    Ordinal0 [0x00D9468B+1787531]
    Ordinal0 [0x00D98E88+1805960]
    Ordinal0 [0x00D98F75+1806197]
    Ordinal0 [0x00DA1DF1+1842673]
    BaseThreadInitThunk [0x773FFA29+25]
    RtlGetAppContainerNamedObjectPath [0x77A27A7E+286]
    RtlGetAppContainerNamedObjectPath [0x77A27A4E+238]

Where the driver.refresh() can't enable driver.get() for another new url after implementing
valid('https://www.farfetch.com/hk/shopping/women/gucci/items.aspx')

where this URL is actually the one that can direct the user to the desired online store.
But then if I try some other case
my_list=[valid('https://www.google.com','Sorry, we can\'t find'),
       valid('https://www.net-a-porter.com/en-hk/shop/designer/Acne-Studios','Sorry, we can\'t find'),
       valid('https://www.net-a-porter.com/en-hk/shop/designer/AcneStudios','Sorry, we can\'t find'),
       valid('https://www.yahoo.com')
      ]

and this
my_list=[valid('https://www.google.com','Sorry, we can\'t find'),
           valid('https://www.net-a-porter.com/en-hk/shop/designer/AcneStudios','Sorry, we can\'t find'),
           valid('https://www.net-a-porter.com/en-hk/shop/designer/Acne-Studios','Sorry, we can\'t find'),
           valid('https://www.yahoo.com')
          ]

Both of the lists (where I interchanged the original 2nd (correct URL) and 3rd (does not exist)) return me an error at the 3rd implementation of the function valid().
Summing up: the wanted URL would crash the program. Does anyone have some ideas on fixing it?


text:
Q: Change posts list Breadcrumb I have a custom page set in Settings > Read > Articles Page (page named "Blog").
It's not my homepage, but NavXT breadcrumbs show only "Home". I'd like it to show the page title : "Home > Blog".
How can I achieve this?

A: It seems that you have a misunderstanding about a static front page and a blogpage and the returned result from the conditional tags. Here is a short explanation
STATIC FRONT PAGE
The general misconception is that your static front page is your home page, which it is not. The static front page is just a cover page, if you wish, something like the cover of a book. It serves the purpose of introducing someone to what the site/author/etc is all about
The static front page is in most cases used as an introductary/portfolio page with important info about the site/author/business/etc. The content on this page is static and usually only change if there are some changes to the site/author/business itself
The conditional tag is_home() returns false on this page, because as said, this is not the home page, but something like a cover page. The conditional tag is_front_page() should be used to test this page
BLOG PAGE
Popular misbelieve is that this is like a normal page on the site, while in fact this is the true home page of the site. This page is exactly the same as your normal homepage when no static front page is set. This page displays all your blog posts as normal
is_home() will return true on this page, as I said, because this is the actual homepage of the site. This is why you see the behavior as you have stated in your question.
GENERALISING
Plugin specific question is off topic here, so you should contact the plugin author for assistance with implementing this.
On a general note, you can also write yor own breadcrumb to modify the behavior of the output on your blogpage
If you need something like Home > Blog to display on your blog page, you can do the following conditional check inside your breadcrumb
if( is_home() && 'page' == get_option( 'show_on_front' ) ) {
    echo 'Home > Blog';
}elseif( is_home() && 'posts' == get_option( 'show_on_front' ) ) {
    echo 'Home';
}

Additional resources: Creating a Static Frontpage


text:
Q: Accessing parameters passed in make command My first day with makefile and gulp and here i need to pass couple of parameters in my make command from the terminal and use those params later on elsewhere.
Presently my make command would be "make xyz". Need it to be something like "make xyz --paramOne=abc" and use this "abc" elsewhere in the framework.
Completely at loss here! I have been using grunt and aware of how  grunt works. Any help or leads would be of immense help.
Thanks!

A: Use environment variables.
paramOne=abc make xyz

You can access the inherited environment variables in your code. For example, in Node.js,
console.log(process.env.paramOne);
// => abc


text:
Q: For enumerate Iteration for v in enumerate (["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"])
    folder = "/Users/Name/Desktop/Datas/" + v
    csvFiles = glob.glob (os.path.join (folder, "*.csv"))
    df = (pd.read_csv(i) for i in csvFiles)
    df = pd.concat (df, ignore_index=True)

I´m iterating over the subfolders A,B,C,D,E,F,G,H,I,J,K.
This code works good, but how can I avoid writing all the string ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"] in the for sentence?

A: If you're working based on the number, you can do like so:
import string
letters = [string.ascii_uppercase[i] for i in range(11)]

A: If you are using consecutive alphabets, you can use:
for v in range(ord('A'), ord('K')+1):
    print(chr(v))

A: Strings are iterables too :)
    Python 2.7.14+ (default, Dec  5 2017, 15:17:02)
    [GCC 7.2.0] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> for x in enumerate('ABC'):
    ...     print x
    ...
    (0, 'A')
    (1, 'B')
    (2, 'C')

And you can compare strings :
    >>> 'A' < 'V'
    True
    >>> 'E' < 'V'
    True
    >>> 'E' < 'D'
    False
    >>> 'A' < 'C' < 'K'
    True


text:
Q: How to generate an array with month ranges in Ruby? I am new to Ruby and managed to generate year_ranges (please correct me if there's a better term for this) from an array of years:
class User < ActiveRecord::Base

  def years
    [2013, 2012, 2011, 2010, 2009]
  end

  def year_ranges
    years.map { |y| "#{y}-01-01_#{y}-12-31" }
  end

end

@user.year_ranges

# =>
[
  "2013-01-01_2013-12-31",
  "2012-01-01_2012-12-31",
  "2011-01-01_2011-12-31",
  "2010-01-01_2010-12-31",
  "2009-01-01_2009-12-31"
]

Now how can I create a method month_ranges, so I get an array like this?
[
  "2013-01-01_2013-01-31",
  "2012-02-01_2012-02-31",
  "2011-03-01_2011-03-31",
  "2010-04-01_2010-04-31",
  "2009-05-01_2009-05-31",
  .....
]

Thanks to anybody who can help.

A: I suspect you want one such entry for every month in each year.

*

*Date.new(year, month, 1) returns the first day of the given year and month

*Date.new(year, month, -1) returns the last day of the given year and month

This should work:
require 'date'

years = [2013, 2012, 2011, 2010, 2009]

years.flat_map { |y|
  12.downto(1).map { |m| "#{Date.new(y, m, 1)}_#{Date.new(y, m, -1)}" }
}
#=> ["2013-12-01_2013-12-31", "2013-11-01_2013-11-30", "2013-10-01_2013-10-31", "2013-09-01_2013-09-30", "2013-08-01_2013-08-31", "2013-07-01_2013-07-31", "2013-06-01_2013-06-30", "2013-05-01_2013-05-31", "2013-04-01_2013-04-30", "2013-03-01_2013-03-31", "2013-02-01_2013-02-28", "2013-01-01_2013-01-31", "2012-12-01_2012-12-31", "2012-11-01_2012-11-30", "2012-10-01_2012-10-31", "2012-09-01_2012-09-30", "2012-08-01_2012-08-31", "2012-07-01_2012-07-31", "2012-06-01_2012-06-30", "2012-05-01_2012-05-31", "2012-04-01_2012-04-30", "2012-03-01_2012-03-31", "2012-02-01_2012-02-29", "2012-01-01_2012-01-31", "2011-12-01_2011-12-31", "2011-11-01_2011-11-30", "2011-10-01_2011-10-31", "2011-09-01_2011-09-30", "2011-08-01_2011-08-31", "2011-07-01_2011-07-31", "2011-06-01_2011-06-30", "2011-05-01_2011-05-31", "2011-04-01_2011-04-30", "2011-03-01_2011-03-31", "2011-02-01_2011-02-28", "2011-01-01_2011-01-31", "2010-12-01_2010-12-31", "2010-11-01_2010-11-30", "2010-10-01_2010-10-31", "2010-09-01_2010-09-30", "2010-08-01_2010-08-31", "2010-07-01_2010-07-31", "2010-06-01_2010-06-30", "2010-05-01_2010-05-31", "2010-04-01_2010-04-30", "2010-03-01_2010-03-31", "2010-02-01_2010-02-28", "2010-01-01_2010-01-31", "2009-12-01_2009-12-31", "2009-11-01_2009-11-30", "2009-10-01_2009-10-31", "2009-09-01_2009-09-30", "2009-08-01_2009-08-31", "2009-07-01_2009-07-31", "2009-06-01_2009-06-30", "2009-05-01_2009-05-31", "2009-04-01_2009-04-30", "2009-03-01_2009-03-31", "2009-02-01_2009-02-28", "2009-01-01_2009-01-31"]


text:
Q: Synaptics stole Alt+Shft+L -- how can I reclaim it? When I updated to Windows 10 it installed the latest Synaptics touchpad driver on my Lenovo W520. I tried to remove the driver but Windows brought it back with the next round of updates.
This particular driver registers a global keyboard hook on Alt+Shift+L to generate and show its log file. However, as long time user of Resharper, I was already using that keyboard shortcut regularly while running Visual Studio.
I don't want to see the Synaptics log file, ever. I don't even use the touchpad. I tried disabling it in the "Device Manager." Does anyone know how to kill the Synaptics global keyboard hook?

A: From here:
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\SynTP\Parameters\Debug /v DumpKernel /d 00000000 /t REG_DWORD /f

Then reboot the computer.

A: *

*I tried with uninstallation of synaptics driver uninstall completely

*then restarted my device

*installed driver taken from official website of my laptop.

woww... issue gone .


text:
Q: Using C++ as scripting language Am wondering if there is any "successful" attempts to create a complete set of templates in C++, so, C++ can be used as a scripting language. In other words, get the results at compile time (computation, loop,...) without running the exe.
Think one can calculate recursive items through templates, but having a complete set of functionnality (for, while, and double calculation), I could not find it.

A:
"... get the results at compile time (computation, loop,...) without running the exe."

Nope, there's no way.
Even if everything is computed at compile time, you'll need to run the executable to retrieve the result.
Retrieving the result is not available as a compile time feature.


text:
Q: Error when eval a for-loop I am writing a script which accepts two arguments:
#! /bin/bash

eval  for i in {$1..$2}; do echo $i;  done

I run it like:
$ ./myscript 0002 0010
 syntax error near unexpected token `do'

Why is the error?
I though it might be because the looping should be grouped. But by replacing eval  for i in {$1..$2}; do echo $i;  done with eval { for i in {$1..$2}; do echo $i;  done; }, the error remains.
Note:
I hope to perform parameter expansion before brace expansion by using eval.
The desired output of my example is 0002 0003 0004 0005 0006 0007 0008 0009 0010. (See Perform parameter expansion before brace expansion?)

A: That's because the shell evaluated ;, so eval didn't see it.
You have to escape any shell special character to delay its evaluation and pass is literally to eval:
eval for i in \{"$1".."$2"\}\; do echo \"\$i\"\;  done

A: That line breaks at the first metacharacter, which is ; (in this example).
The line:
eval for i in {$1..$2}; do echo $i;  done

Is divided into this three commands:
eval for i in {$1..$2};
do echo $i;
done

Trying to execute a do without having a previous for, while, until can not work. It will raise an error condition:

syntax error near unexpected token `do'

That happens because the previous for is hidden as an argument in the command eval.
One possible workaround is to quote everything and leave out only what you want to be expanded, which I believe you want the variables $1 and $2:
eval 'for i in {'$1'..'$2'}; do echo $i;  done'

It does work:
$ ./myscript 0002 0010
0002
0003
0004
0005
0006
0007
0008
0009
0010

However, this script is evaluating external input, a highly insecure practice.
Correct Solution
A safer script which sanitize $1 and $2 and properly quote the vars, is this:
#!/bin/bash
a=${1//[^0-9]/}          ### select only numbers from first parameter.
b=${2//[^0-9]/}          ### select only numbers from second parameter.
eval  'for i in {'"$a"'..'"$b"'}; do echo $i;  done'


text:
Q: Bit width calculation I'm trying to understand "bit overflow" so I made a simple example.
As I understand, hex value 'hFF can convert to 7'b11111111
So I implement to check with $display("%b" , {7'hff});
But, I got the below warning message.
$display("%b" , {7'hff});
                         |
xmvlog: *W,INTOVF (testbench.sv,18|25): bit overflow during conversion from text [2.5(IEEE)] (7 bits).

How do I calculate the bit width, and why does the bit overflow warning message happen?

A: The "bit overflow" message happens because you specified 7 as the bit width, but your numeric literal (ff) requires 8 bits.

As I understand, hex value 'hFF can convert to 7'b11111111

No, 'hFF converts to 8'b11111111.  If you count the number of 1's, you have 8.
Verilog syntax supports the underline character as a visual separator to make it easier to understand numeric literals with several digits.  For example, you could write the number as 'b1111_1111.  That makes it easier to see that there are 8 1's.
To avoid the warning, use 8'hff.
The maximum 7-bit hex value is 7'h7f.


text:
Q: How do I create a Moodle calculated multiple choice question from a tex file? To create a multiple choice question I have been using the environment
\begin{multi}
...
\end{multi}

What is the environment to use to generate a calculated multiple choice question, that is one with a variable in it?

A: This github project demonstrates how you can use python code within your LaTeX file to generate something that pretty much mimics the effect of calculated questions: you generate a pool of questions out of a prototype.
To push things a bit more, in a development version of the moodle package, I introduced support for moodle tags. This way, when building a quiz in Moodle, you can ask to pick up randomly a question among those that share a specific tag.
I also observed that with LuaTeX's internal scripting capabilities, you can do the same as what can be done using python.
Here is an example code:
% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{moodle} % development version 0.8
\begin{document}
\begin{quiz}[tags={calculated}]{Example Quiz}
\directlua{
function clozenum_print(pair,op,result)
  tex.print("\\begin{numerical}$"..pair[1].." "..op.." "..pair[2].." =$".."\\item ",result,"\\end{numerical}")
end
function cloze_print(pair,points)
  tex.print("\\begin{cloze}[points="..points.."]{Arithmetic Quiz ("..pair[1]..", "..pair[2]..")}Solve the following tasks!\\\\")
  clozenum_print(pair,"+",pair[1]+pair[2])
  clozenum_print(pair,"-",pair[1]-pair[2])
  clozenum_print(pair,"*",pair[1]*pair[2])
  if pair[1]/pair[2]==math.floor(pair[1]/pair[2]) then
    clozenum_print(pair,":",math.floor(pair[1]/pair[2]))
  end
  tex.print("\\end{cloze}")
end
for x = 2,4 do
  for y = 2,4 do
    if x>y then
      if x/y==math.floor(x/y) then points=4 else points=3 end
      cloze_print({x,y},points)
    end
  end
end
}
\end{quiz}
\end{document}

the resulting PDF is rendered like this

and the resulting XML file is
<?xml version="1.0" encoding="UTF-8"?>

<quiz>

<question type="category">
  <category>
    <text>$course$/top/Example Quiz</text>
  </category>
</question>

<question type="cloze">
  <name format="html">
    <text><![CDATA[Arithmetic Quiz (3, 2)]]></text>
  </name>
  <questiontext format="html">
    <text><![CDATA[
Solve the following tasks!
 \(3 + 2 =\){1:NUMERICAL:=5:0}\(3 - 2 =\){1:NUMERICAL:=1:0}
]]></text>
  </questiontext>
  <defaultgrade>3</defaultgrade>
  <generalfeedback format="html"><text/></generalfeedback>
  <penalty>0.10</penalty>
  <hidden>0</hidden>
  <tags>
    <tag><text><![CDATA[calculated]]></text></tag>
  </tags>
</question>
<question type="cloze">
  <name format="html">
    <text><![CDATA[Arithmetic Quiz (4, 2)]]></text>
  </name>
  <questiontext format="html">
    <text><![CDATA[
Solve the following tasks!
 \(4 + 2 =\){1:NUMERICAL:=6:0}\(4 - 2 =\){1:NUMERICAL:=2:0}\(4 : 2 =\){1:NUMERICAL:=2:0}
]]></text>
  </questiontext>
  <defaultgrade>4</defaultgrade>
  <generalfeedback format="html"><text/></generalfeedback>
  <penalty>0.10</penalty>
  <hidden>0</hidden>
  <tags>
    <tag><text><![CDATA[calculated]]></text></tag>
  </tags>
</question>
<question type="cloze">
  <name format="html">
    <text><![CDATA[Arithmetic Quiz (4, 3)]]></text>
  </name>
  <questiontext format="html">
    <text><![CDATA[
Solve the following tasks!
 \(4 + 3 =\){1:NUMERICAL:=7:0}\(4 - 3 =\){1:NUMERICAL:=1:0}
]]></text>
  </questiontext>
  <defaultgrade>3</defaultgrade>
  <generalfeedback format="html"><text/></generalfeedback>
  <penalty>0.10</penalty>
  <hidden>0</hidden>
  <tags>
    <tag><text><![CDATA[calculated]]></text></tag>
  </tags>
</question>

</quiz>

Once the questions are imported in the question bank of your Moodle course, you can add edit a quiz to populate it with questions taken randomly from the question bank

A: If you look at the manual (texdoc moodle in your TeXLive installation, or on CTAN), there is no such thing implemented.
The available questions are just

*

*cloze

*matching

*essay

*short answer

*numerical (no variables)

*multi


text:
Q: ForeignKey to 'self' in sub-application throws error on makemigrations in Django project I'm currently working on an large Django project (version 1.10.7) and am running into an error with a model field in a sub-application. Here's what the basic structure looks like:
project/
    app_one/
        __init__.py
        apps.py
        models.py
        urls.py
        views.py
        app_two/
            __init__.py
            apps.py
            models.py
            urls.py
            views.py

The model and field in question looks like this (project/app_one/app_two/models.py):
class SampleModel(model.Model):
    parent = models.ForeignKey('self', null=True, blank=True, related_name='members')

When I run python manage.py makemigrations app_one.app_two in the root folder I get this error message:

File .../django/db/models/utils.py", line 23, in make_model_tuple
      "must be of the form 'app_label.ModelName'." % model ValueError: Invalid model reference 'app_one.app_two.SampleModel'. String model
  references must be of the form 'app_label.ModelName'.

Here is code from other files that are relevant:
project/settings.py:
INSTALLED_APPS = filter(None, (
    ...
    'app_one',
    'app_one.app_two',
    ...
)

project/app_one/app_two/apps.py:
from __future__ import unicode_literals

from django.apps import AppConfig

class AppOneAppTwoConfig(AppConfig):
    name = 'app_one.app_two'
    label = 'app_one.app_two'

project/app_one/app_two/__init__.py:
default_app_config = 'app_one.app_two.apps.AppOneAppTwoConfig'

I believe the error here is that Django is only looking for one . in the full model name (app_one.app_two.SampleModel) to separate the app label from the model name in django/db/models/utils.py, and since there are two in this case, it fails.
My question is: This seems like a weird for Django not to account for...is there anyway to retain the dot notation of the app label and still have a self-referencing ForeignKey in a sub-application?

A: As you mention, it seems to be a lookup error when the project is trying to locate your app due to the nested apps. This can be solved by specifying the app name with an app_label in the models internal meta class:
class SampleModel(models.Model):
    ...
    class Meta:
        app_label = 'app_two'

A: I was able to solve this by changing the app_label to 'app_one_app_two' in apps.py. Because django references this when registering the related models, it doesn't break. All migrations are then registered under that label as well.


text:
Q: What is the point of having $this and self:: in PHP? Why does PHP require you to explicitly write $this? I would understand if you had to use $this here:
function foo($bar) {
   $this->bar = $bar;
}

But you must write it explicitly in verbose code that looks like this:
$this->var3 = globalFun($this->var, $this->var2[$this->anotherVar], $this->method());

as opposed to:
$var3 = globaFun($var, $var2[$anotherVar], method());

So what is the point of $this?
Additional Bonus Question:
Why do we have to differentiate static references and instances? Why do we need:
static function getValue() {
   return self::value;
}

Can't PHP find out at runtime if the variable/method in question is static? Now if I want to change a method from static to non-static, I have to replace all those self:: with $this-> (and vice-versa).
Wouldn't it be better if we had a $this that behaves like it does in Java?

A: PHP was not OOP.
Now it is, but with side effects.

A: Since this was re-opened, I'll post here my answer, as promised.
TL;DR version If it were not required to qualify a member access, there would be not only performance penalties, but the same line of code could simultaneously signify a field access and a local variable access, depending on the code path.
Full version
In PHP, there's always one symbol table active at the table. This is either the global symbol table or a function/method local symbol table (which by the way, are lazily built). Superglobals and optimizations like compiled variables aside, when a variable $var is requested, it is looked up in the current symbol table. Since the object properties live not on the symbol tables, but instead on either in the objects (the instance properties) or the structure associated the class (the static properties), a lookup for $var can never return a property.
To bring a given variable to the function scope, you must explicitly signal your intention by creating a reference. Examples:
$myglobal = 7;
class A {
    private $prop;
    public function meth() {
        global $myglobal; //bring a global to the current scope
        $prop =& $this->prop; //brings a property to the current scope
        $local = 4;
        $lambda = function () use (&$local) { };
    }
}

Obviously, this is just a more sophisticated way to phrase what currently happens. The question is why this behavior?
After all, in Java we only have to type this.prop when there's a local variable called prop hiding the property. Why is this not a good option for PHP?
I can think of several reasons.
The object properties are determined at runtime
PHP has something called "dynamic properties". You can assign new properties to objects at runtime. In fact given two objects of the same class, one can have a given property $a and while the other doesn't. Example:
$obj1 = new stdClass();
$obj2 = new stdClass();
$obj1->a = 7;

In PHP, the defined local variables are determined at runtime
Variables do not have to be declared; consequently, depending on the code path, at some point a variable may or may not be defined. To add insult to the injury, we also have the monster called "variable variables". Example:
class A {
    private $g = 3;
    public function func($varname) {
        if (rand(1,2) == 1) {
            $g = 4; //no block scope; the scope is the function's
        }
        $$varname = 5; //god knows what's happening here
        //if local variables hid properties, we'd have trouble
    }
}

In Java, a given identifier may also represent, inside the same function, a local variable and a property, but:

*

*Not within the same block (in PHP, all blocks in a function share exactly the same scope).

*You get a warning if you're hiding a property.

*Crucially, in any given occurrence of an identifier, it's either a property or a local variable, it can't sometimes be one and other times the other.

Consequences
Owing to these facts, it would be impossible to determine at compile time if $var referred to a local variable or to a property. Consequently:

*

*At runtime, every time a variable occurred, it would have to looked up first in the local symbol table, then in the instance properties table, and finally in the static properties list, or any other order (since there can't be an instance and a static property with the same name and static properties need to be declared, there would be some optimization potential here, but the point stands). This means a symbol would have, in the worst case, would have to be looked up in three different places. This is bad from a performance perspective.

*A given symbol occurrence could mean different things on different occasions. This is a recipe for disaster.

A: Okay, so let's remove the need for writing $this everywhere. Take a look at this situation:
class Foo {
    public function setBar($value) {
        $bar = $value;
    }
}
$foo = new Foo();
$foo->setBar('some value');

Is $bar a local variable or a member of $foo?
There has to be some differentiation. They could have allowed declaration of local variables with the var keyword, but that would not have been backwards-compatible and would have been very confusing to people upgrading from older versions of PHP.
Same thing applies to self::. How does the interpreter know whether the function you wanted to call is global or specific to the class?

A: Actually, I know people who use this. in Java even where unnecessary because they feel it creates clearer code ;) I don't have a really definite answer, but I guess that, internally, getting $var would always have to be translated to $this->var. So it's not like someone intentionally made things more complicated by forcing us to do $this->var, but just decided to not implement the $var shortcut. If that helps in any way, I don't know ;)


text:
Q: WebView does not show KOLIBRI log in page Hi I'm new in Android Studio. I'm developing an app that uses the WebView to open a http url. This http url is used to access learning materials in my school that I'm working. The webview is working properly in other websites and also it can access my routers settings. I can't make it work in http://192.168.100.73:8080. The webview only displays the icon but it works when I remove the line  myWebView.setWebViewClient((new WebViewClient())); which I don't want to do. I can't search similar problem in google.
My manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.gves.studentresources">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.StudentResources"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.StudentResources.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

the fragment layout
<WebView
    android:id="@+id/webview1"
    android:layout_width="409dp"
    android:layout_height="729dp"
    android:layout_marginStart="1dp"
    android:layout_marginTop="1dp"
    android:layout_marginEnd="1dp"
    android:layout_marginBottom="1dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

the fragment java class
    binding = FragmentHomeBinding.inflate(inflater, container, false);
    View root = binding.getRoot();

    WebView myWebView = root.findViewById(R.id.webview1);
    myWebView.getSettings().setJavaScriptEnabled(true);
    //myWebView.setWebViewClient((new WebViewClient()));
    myWebView.loadUrl("http://192.168.100.73:8080");

    return root;
}

Screenshot while the app is running. The webview shows the icon but nothing happens.
with new webview code
Screenshot when I remove the myWebView.setWebViewClient((new WebViewClient())); line code
without new webview code
I'm using Android Studio's default navigation drawer template. I hope you could help me with this.

A: I solve my problem by adding this line.
myWebView.getSettings().setDomStorageEnabled(true);
but I have another problem. The download resource button in Webview is missing. google chrome in bluestaks compared to android studio emulator


text:
Q: No echo for expect send command Got a license agreement which I want to process in expect.
I have the following code
{
  /usr/bin/expect << EOD
  log_user 0
  set timeout 20
  spawn -noecho "${filename}" > /dev/null 2>&1

  stty -echo;
  expect {
      "Press Enter to view the End User License Agreement" {
          send "\r"
          exp_continue
      }
      "More" {
          send " "
          exp_continue
      }
      "Do you accept the End User License Agreement?" {
          log_user 0
          send "y\r"
          log_user 0
      }
  }
  interact
  expect eof
EOD
}

Running this I get the following output:
y

It is working fine, but I want to get no output from the expect at all.
My goal is to not echo the send command.
As you can see I have already tried to use the log_user and stty to get this done, but with no luck.
Before using this extra bits in the code, I could see the whole license text on screen. With log_user 0 this is now not showing anymore.
But I still got the y from the last send command, which I'm not able to not echo on screen.
Any advise?
Thanks

A: With stty -echo itself sufficient to hide the output. But, I am not sure what's wrong with that.
Anyway, try this.
"Do you accept the End User License Agreement?" {
    send "y\r"
    log_user 0
    expect *
}
log_user 1
send \r; # This is optional
interact


text:
Q: addPostFrameCallback runs constantly when I only want it to run once In my application I have a few values that on startup I want to be able to refresh and reload from SharedPreferences, and make some adjustments to in the process if necessary. I'm currently facing the issue of actually grabbing these values consistently on startup however. Originally I had all these functions in my initState() function thinking this would make the values always reload on boot, but this behaviour doesn't seem to be consistent.

My get functions are all based on a variation of this:

Then I tried using addPostFrameCallback where I did the following:

This last implementation seems to run constantly every half second for some reason, and I can't exactly figure out why this is happening. Is there any solution to this, or any other solution I could try?

A: as you are calling setState inside build method, so build method is rendering again and again in infinite loop. if you need to do setState after screen open you can override didChangeDependencies method like below -
@override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance?.addPostFrameCallback((_) async {
      setState(() {
        // Write your code here
      });
    });
  }


text:
Q: Why can terms of a spacetime metric only have 2 differential factors? In my general relativity textbook, the following equation is given:
$$ds^2 = g_{\alpha \beta}(x)dx^{\alpha}dx^{\beta}$$
Which describes the line element $ds^2$ for a metric. $g_{\alpha \beta}$ is a matrix that is the metric itself. This equation implies that a given term of the equation for a line element can only have two differential factors. Either two different linear variables (For example: $dtdr$) or one variable squared (For example: $d\theta^2$).
Intuitively, this makes some sense. Our line element is $ds^2$, so that exponent of 2 could explain why, when you multiply things out, you can only get two differential factors per term, just like squaring any polynomial.
But this doesn't really make sense to me from a more formal perspective. I suppose the issue is that I don't really understand what the exponent of 2 is actually doing. So what is it doing? And what is the exact reason that we can only have two differential factors per term?
(Reading back this question, I'm not sure if everything is clear, so let me know if I can clarify anything or otherwise improve this question).

A: The expression for the line element is a generalization of the Pythagorean Theorem of 2D Euclidean space,
$$c^2=a^2+b^2,$$
to 4D curved spacetime, on an infinitesimal scale. So the squares shouldn't be surprising.
In 3D Euclidean space, you have probably seen that infinitesimal arc length along a curve is just
$$ds^2=dx^2+dy^2+dz^2.$$
In the flat (Minkowskian) spacetime of Special Relativity it is just
$$ds^2=-dt^2+dx^2+dy^2+dz^2.$$
For a general 4D curved spacetime, your expression, written out in $txyz$ coordinates, is
$$\begin{align}ds^2&=g_{tt}(t,x,y,z)\,dt^2+g_{xx}(t,x,y,z)\,dx^2+g_{yy}(t,x,y,z)\,dy^2+g_{zz}(t,x,y,z)\,dz^2 \\
&+2g_{tx}(t,x,y,z)\,dt\,dx+2g_{ty}(t,x,y,z)\,dt\,dy+2g_{tz}(t,x,y,z)\,dt\,dz\\
&+2g_{xy}(t,x,y,z)\,dx\,dy+2g_{xz}(t,x,y,z)\,dx\,dz+2g_{yz}(t,x,y,z)\,dy\,dz.
\end{align}$$
The essential idea is that curved space(time) should be, over sufficiently small regions, very similar to flat space(time), in the same way a small patch of the Earth's spherical surface seems like a plane. This means that you can't have something weird with different powers like
$$ds^2=-A dt^3+B dx^4+C dy^5+D dz^6.$$


text:
Q: the name is not a valid identifier error in function      Create FUNCTION [dbo].[fngetname]
    (
       @OrganisationID int=null,
       @UserID int=null,
       @ClientTypeID int

    )
    RETURNS  varchar(500)
    BEGIN
    DECLARE @Name VARCHAR(500)

     DECLARE @dbName VARCHAR(500)
    set @dbName=(select ClientDataBase from dbo.ClientType where ClientTypeID=@ClientTypeID)

    begin

   set @Name='select UserName from ['+ @dbName+'].dbo.Users where UserID='+convert(varchar,@UserID)
    exec @Name
    end

       return @Name
    end

A: There are two issues here, first if you want to execute dynamic sql, you need to encapsulate your statement variable in parenthesises:
you need to add parenthesises to the exec @Name in your function declaration.
The function gets written but cannot execute it stops at the exec
replace that exec @Name with exec (@Name)
you can easily reproduce this error by just trying two simple lines (ofc replace the table and db-name with something you have ;)):
DECLARE @statement VARCHAR(MAX) = 'SELECT * FROM [nana].dbo.Fruits'
exec @statement

This should throw the exact same error.
Then add () around the @statement and it will work.
The second issue is, that you cannot use dynamic sql in a function, because they have to be deterministic (look here).
To get around this, rewrite that function behaviour into a stored procedure and then it should work ;).
One way to rewrite your function into a procedure might look like this(untested, because I do not have your database structure set up):
CREATE PROCEDURE spGetName @OrganisationID INT = NULL, @UserID INT = NULL, @ClientTypeID INT
AS
BEGIN
    DECLARE @Name VARCHAR(500)
    DECLARE @dbName VARCHAR(500)
    SET @dbName = (SELECT ClientDataBase FROM dbo.ClientType WHERE ClientTypeID = @ClientTypeID)

    SET @Name = 'select UserName from [' + @dbName + '].dbo.Users where UserID=' + CONVERT(VARCHAR, @UserID)
    exec(@Name)
END
GO

A: Try using
exec sp_executesql @statement


text:
Q: Using Mac as wifi hotspot for android devices? Can anyone tell me why my android device can't see my wifi network, while my ipad can?
Is there something I need to configure in the Mac Network settings to get Android and OSX to play nicely together?

A: It sounds like you may have a dual band set up or the wifi chip in either device is creating a network that the other chip is unable to communicate with. If it is not visible at all it is likely a hardware limitation.
Mac's and Ipad's both support the 5GHz range I believe and if that is the case, and you android device doesn't, then this is why your network is not visible to your android device.
5GHz was originally used for 802.11a (before b, g, and n) which supported 54MBps and has more recently need adopted to be usable for 802.11n at 150MBps+. If your n capable device doesn't also support a then it won't be able to see the 5GHz band (this may have changed more so recently since a is outdated and some n's could simply have been adapted for use with 5GHz).

A: I think android does not display ad hoc connections natively, this was the case with me. So the network you created in your Mac probably was ad hoc.


text:
Q: php how to find all child nodes of a given node My XML input is like this:
<Configuaration>
    <Allowances>
        <payhead>
            123
            <name_en>Basic</name_en>
            <source>anything</source>
        </payhead>
    </Allowances>
    <Deductions>
        <payhead>
            444
            <name_en>House Rent</name_en>
            <source>anything</source>
        </payhead>
    </Deductions>
</Configuaration>

What I want is like, in my php function I will give 2 parameters. 1st one is the input xml and 2nd one is the searchTag (all child nodes under this tag should return).
my php function:
<?php
class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $childs = $dom->getElementsByTagName($searchTag);
        foreach ($childs as $child) {
            echo '<'.$child->nodeName.'>'.$child->nodeValue.'</'.$child->nodeName.'>'.PHP_EOL;
        }
    }
}
?>

so if i put the_xml_string and 'payhead' as the function parameter then it should return
<payhead>
    123
    <name_en>Basic</name_en>
    <source>anything</source>
</payhead>
<payhead>
    123
    <name_en>Basic</name_en>
    <source>anything</source>
</payhead>

but instead i get
<payhead>123Basicanything</payhead>
<payhead>444House Rentanything</payhead>

I dont understand it. Can anybody help? If there is something wrong in my code then how can I achieve it? TIA.

A: It looks like you need this function:
class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $foundElements = $dom->getElementsByTagName($searchTag);
        foreach ($foundElements as $foundElement) {
            echo $foundElement->ownerDocument->saveXML($foundElement);
        }
    }
}

You can run locally this code:
<?php
$xml = <<<EOF
<Configuaration>
<Allowances>
    <payhead>
        123
        <name_en>Basic</name_en>
        <source>anything</source>
    </payhead>
</Allowances>
<Deductions>
    <payhead>
        444
        <name_en>House Rent</name_en>
        <source>anything</source>
    </payhead>
</Deductions>
</Configuaration>
EOF;
class myXMLUtil
{
    public static function getValue($inputXML, $searchTag)
    {
        $dom = new DOMDocument;
        $dom->loadXML($inputXML);
        $foundElements = $dom->getElementsByTagName($searchTag);
                foreach ($foundElements as $foundElement) {
                        echo $foundElement->ownerDocument->saveXML($foundElement);
                }
    }
}
myXMLUtil::getValue($xml, 'payhead');
?>

And it will return
<payhead>
    123
    <name_en>Basic</name_en>
    <source>anything</source>
</payhead><payhead>
    444
    <name_en>House Rent</name_en>
    <source>anything</source>
</payhead>


text:
Q: How to take webpage screenshots using QWebEngineView without opening window I'm looking for a way to take website screenshots with QWebEngineView.  The main goal is to develop a headless screencapture application that runs in the background.
I've managed to get a minimal working example to work (see this for example).  However, these examples require that the QWebEngineView widget is made visible, either with calls to QWebEngineView::show(), QWebEngineView::showMinimized() or even QWebEngineView::setVisible(true), to be able to take a screen capture of a website.  As this results in opening a series of windows, this solution is less than perfect.
Does anyone know of a way to use QWebEngineView to take screenshots of websites without having windows popping open?

A: The solution is rather easy: configure the QWebEngineView widget to not show onscreen by setting the Qt::WA_DontShowOnScreen attribute through a call to QWidget::setAttribute(Qt::WA_DontShowOnScreen).
http://doc.qt.io/qt-5/qt.html#WidgetAttribute-enum


text:
Q: Is it possible to output a relative line number in flagderiv? I am trying to output a number relative to the current step of my proof instead of being hard coded. I'll try and explain what I mean with this proof:
\documentclass[11pt]{article}
    \usepackage[a4paper,total={6in,8in},textwidth=496pt]{geometry}
    \usepackage{amsmath}
    \usepackage{amstext}
    \usepackage{flagderiv}
    \usepackage{calc}
    \usepackage[nomessages]{fp}

\begin{document}

\begin{flagderiv}
\step{}{P}{}
\step{}{P\implies Q}{}
\conclude{}{Q}{1\&2}
\end{flagderiv}

\end{document}

Instead of having to write 1\&2 in the conclusion section I would like to find some way of using the step counter to get just say the line above this one.
I know that flagderiv has a \thestepcounter variable but that gives me the number in this format: (n). I was also thinking of using fp (which I found in this answer) to do the maths in some way like this: \FPeval{\result}{clip(\thestepcounter-1)}. I have yet to find a variation of this that works though.
This feels possible, but I'm quite new to latex and manipulating variables in this way is beyond me. After reading parts of the Implementation section in this pdf I think \thefd@stepcount might be the variable I'm looking for, but it seems to be internal and I don't know how to access it.
Any help is much appreciated. Thank you in advance!

A: The first argument to \step (which you are leaving empty) is a label, which can be referenced by standard methods.
\documentclass[11pt]{article}

\usepackage{flagderiv}
\usepackage{amsmath}

\begin{document}

\begin{flagderiv}
\step{foo}{P}{}
\step{bar}{P\implies Q}{}
\conclude{}{Q}{\ref{foo} \& \ref{bar}}
\end{flagderiv}

\end{document}

A: Here a new command \relativeRef{<num>} is provided (you can surely use a shorter macro name). For example in line 3, \relativeRef{2} will give 1 (3 minus 2). Note that the underneath counter is named fd@stepcount.
\documentclass{article}
\usepackage{amsmath}
\usepackage{flagderiv}

\makeatletter
\newcommand{\relativeRef}[1]{%
  \the\numexpr\c@fd@stepcount-#1\relax
}
\makeatother

\begin{document}
\begin{flagderiv}
  \step{}{P}{}
  \step{}{P\implies Q}{}
  \conclude{}{Q}{\relativeRef{2} \& \relativeRef{1}}
\end{flagderiv}
\end{document}


text:
Q: What's wrong with upgrading kernel in this case? I always upgrade packages by dist-upgrade including kernel. Recently I discovered that  current kernel version is 4.4.0-34-generic which is old. The last time when I upgrade kernel, it was 4.4.0-79. I checked the lists in GRUB customizer:

As you can see in the picture, new kernels are listed. But they aren't shown when I press Shift button to enter the grub menu while booting.
I even specifically run the command uname -r that showed:
4.4.0-34-generic

I also run sudo update-grub which showed:
Searching for GRUB installation directory... found: /boot/grub
Searching for default file... found: /boot/grub/default
Testing for an existing GRUB menu.lst file... /boot/grub/menu.lst
Searching for splash image... none found, skipping...
Found kernel: /boot/vmlinuz-4.4.0-79-generic
Found kernel: /boot/vmlinuz-4.4.0-78-generic
Found kernel: /boot/vmlinuz-4.4.0-72-generic
Found kernel: /boot/vmlinuz-4.4.0-34-generic
Found kernel: /boot/memtest86+.bin
Found kernel: /boot/vmlinuz-4.4.0-79-generic
Found kernel: /boot/vmlinuz-4.4.0-78-generic
Found kernel: /boot/vmlinuz-4.4.0-72-generic
Found kernel: /boot/vmlinuz-4.4.0-34-generic
Found kernel: /boot/memtest86+.bin
Updating /boot/grub/menu.lst .. done

I looked around in /boot/grub/grub.cfg and there were no new kernels but 4.4.0-34.
Ubuntu's version is 16.04.2 LTS amd64. I want to upgrade the kernel as my computer's stopping to respond after 2-3 minutes after logging in.
What am I supposed to upgrade my kernel in the right way? What did I do wrong to upgrade it?

A: I figured out the problem. It turned out that my grub version was 0.97 which is quite old. I upgraded it and everything's become ok now


text:
Q: THREE.BufferGeometry error with stemkoski Particle Engine I was trying to use stemkoski's particle engine in my own project (his example of using the particle engine can be found here ). I have received an error of three.min.js:474 THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead. After tracking down the source, I noticed that it is the version of threejs he used in his library that is different from mine. Whereas I used http://threejs.org/build/three.min.js, he used a different version (looking into the file, I believe it's version 60 )
What I have tried so far:

*

*Used the three.min.js from threejs.org/build but change the following in the ParticleEngine.js
this.particleGeometry = new THREE.Geometry();

to
this.particleGeometry = new THREE.BufferGeometry();

This pretty much gives me the same errors

*Used his version of three.js instead, says renderer.setPixelRatio and geometry.scale they are not functions (Because I used these two functions in my own project)

A: I solved this by using the squarefeet/ShaderParticleEngine instead of the stemkoski and it works well. I gave anoter piece of information in a previous answer but it was deleted by Brad as considered as not helpful. I believe it was as it says that updating three.js to r79 was not a solution.


text:
Q: lateinit property has not been initialized I can not find a way to Initialize it I have lateinit property in my Kotlin activity, this is simplified version of that:
class CreateNewListOfQuestions : AppCompatActivity() {
    lateinit var questionAnswerListOfObjects: ArrayList<QuestionAnswerObject>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_create_new_list_of_questions)

        save.setOnClickListener {
            questionAnswerListOfObjects.add(0, QuestionAnswerObject("question", "answer", 1))
        }
    }
}

The main problem is that when I generate mobile app and press "Save" button app stops working.
Logcat shows this error: "lateinit property questionAnswerListOfObjects has not been initialized"
I was trying many ways to initialize it but these ways did not help to me. How should I properly initialize it?
I am plining to add to ArrayList many objects of this class:
class QuestionAnswerObject(var question: String, var answer: String, var probability: Int=100) {}

A: It depends what you want.
For example if everything you need is using ArrayList<QuestionAnswerObject> you dont need lateinit at all:
var questionAnswerListOfObjects = ArrayList<QuestionAnswerObject>()

would be enough
If you want to get from Bundle or from something else - you must initialize it before using.
Basically lateinit keyword is used only to say "hey, compiler, I have a variable, it is not initialized yet, but I promise it will be initialized before I use it, so please mark it as not nullable field".
So if you really want to use lateinit, just init that property earlier, for example add after setContentView
questionAnswerListOfObjects = ArrayList<QuestionAnswerObject>()


text:
Q: show programmatic storyboard view changes I'm new to iOS dev, and coming from a Windows background, I was able to see any programmatic changes made to ui elements reflected on the designer. If I wanted to, say, round the corners of a button (programmatically is the only way  have found), but see the changes reflected on the storyboard, is this possible?

A: Storyboards are very useful for building simple framework for apps, however it falls somewhat short when displaying custom interfaces.
The advantage of using storyboards is to have everything one one clear, concise page, with view controllers and transitions, rather than using XIBs. It eliminates a good amount of code that is needed in order for your app to run (for certain transitions between views, for example,) and also changes the required boilerplate code that is needed for certain classes like
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

I believe a lot of advanced iOS applications have custom views or some special ways of presenting content, however storyboards are very often used as well.
edit: it seems that a new feature is in Xcode 6 that I didn't know about! Found a very nice tutorial on how to show some of the features you would like.
https://www.weheartswift.com/make-awesome-ui-components-ios-8-using-swift-xcode-6/
(credit to the commenter on your post for linking to another IBInspectable tutorial)


text:
Q: Does $f_n(x)=n(x^{\frac{1}{n}}-1)$ converge uniformly in $(0,\infty)$ and in $[0,10]$? I'd like your help with the deciding whether the following function uniformly converges in two intervals.
$$f_n(x)=n \left(x^{\frac{1}{n}}-1 \right) .$$
In $(0,10]$, with l'Hôpital, I showed that for every $x$ the limit of the function is $\ln x$, so with a help from Dini's theorem, I am able that the function is monotone and the limit is continuous so the function uniformly converges.
I'm not sure what should I do with the other interval. I tried to evaluate the limit of $|f_n(x)-f(x)|$, I didn't come to any smart conclusion.

A: The sequence does converge uniformly to $\ln x$ on any compact subset of $(0,\infty)$, but the convergence is not uniform in $(0,a\,]$ for any $a>0$. If the convergence were uniform, there would exist an $n_0$ such that for all $n\ge n_0$
$$
|f_n(x)-\ln x|\le1\quad\forall x\in(0,a\,].
$$
But
$$
|f_n(2^{-n})-\ln(2^{-n})|=\Bigl(\ln2-\frac12\Bigr)n
$$
is not bounded.
Observe that $(0,a\,]$ is not compact and Dini's theorem does not apply.

A: As pointed out by Julian, the sequence does not converge uniformly on $(0,a]$ for any $a>0$; but it does converge uniformly on any compact subset of $\Bbb R$.
For sets of the form $[a,\infty)$:
Using L'Hopital, you can show the pointwise limit is $f(x)=\ln x$ on $[a,\infty)$.
Now take $x_n=2^n$. Then
$$
|f_n(x_n)-\ln(x_n)|= |n(2-1) -  n\ln 2|=n(1-\ln2)\quad
\buildrel{n\rightarrow\infty}\over\longrightarrow\quad\infty.
$$
Thus, there is no $N$ so that $|f_n(x)-\ln x|<1$ for all $n\ge N$ and all $x\in [a,\infty)$.
Thus, the convergence is not uniform on $[a,\infty)$.


text:
Q: What's the difference between assignment and initializer list in c++? class a
{
private:
    const int anInt;
public:
    a() : anInt(10) {}
};

vs
class a
{
private:
    const int anInt = 10;
public:
    a() {}
};

What's the difference between these two? When I compile it doesn't seem to have any problem and produce the same results.

A: it's quite different.
The Initializer List is used to initialize a class's data members. At some time after the variable is created, 'Assignment' gives that variable a value.

A: There could be other differences, but the first and main difference between the two is that initialization gives a variable an initial value at the time it is created. On the other hand, assignment gives a variable a value at some point after the variable is created.


text:
Q: Query for group by values from multiple column I have a table like:
ID key familyname  street     pin
1   1    xxx          abc      11
2   1    xxx          acf      13
3   1    xxx1         acf      13
4   1    xxx1         bcf      12
5   2    yyy          abc      11
6   2    yyy          abc      11
7   2    yyy1         bcj      13
8   2    yyy1         bck      14
9   2    yyy2         btj      15
10  2    yyy2         byj      16

Now I want to group street and pin based on columnn "familyname" for each individual key. For example I would expect the output for the above table to be
ID key familyname  street     pin
1   1    xxx        abc,acf    11,13

3   1    xxx1       acf,bcf    13,12

5   2    yyy        abc,abc    11,11

7   2    yyy1       bcj,bck    13,14

9   2    yyy2       btj,byj    15,16

It would be of great help if I can get some suggesion regarding the design  of the grouping query which could give me the result in a fashion as shown above
thanks a lot

A: MySQL has built-in functionality to concatenate rows for every group called GROUP_CONCAT().
SELECT  MIN(ID) ID,
        `key`,
        familyName,
        GROUP_CONCAT(street) street,
        GROUP_CONCAT(pin) pin
FROM    TableName
GROUP   BY `key`, familyName

*

*SQLFiddle Demo

*MySQL GROUP_CONCAT()
OUTPUT
╔════╦═════╦════════════╦═════════╦═══════╗
║ ID ║ KEY ║ FAMILYNAME ║ STREET  ║  PIN  ║
╠════╬═════╬════════════╬═════════╬═══════╣
║  1 ║   1 ║ xxx        ║ abc,acf ║ 11,13 ║
║  3 ║   1 ║ xxx1       ║ acf,bcf ║ 13,12 ║
║  5 ║   2 ║ yyy        ║ abc,abc ║ 11,11 ║
║  7 ║   2 ║ yyy1       ║ bcj,bck ║ 13,14 ║
║  9 ║   2 ║ yyy2       ║ btj,byj ║ 15,16 ║
╚════╩═════╩════════════╩═════════╩═══════╝