text:
Q: Unable to start Spark-standalone in ubuntu I'm having trouble while starting spark standalone in my local computer. I'm following this manual, which is pretty straightforward but i'm still missing something
When i run start-master.sh, it show the following errors:
couto@ubuntu:~/Downloads/spark-1.6.2-bin-hadoop2.4/sbin$ sh start-master.sh
start-master.sh: 31: start-master.sh: [[: not found
start-master.sh: 31: start-master.sh: [[: not found
start-master.sh: 45: start-master.sh: 0: not found
start-master.sh: 52: /home/couto/Downloads/spark-1.6.2-bin-hadoop2.4/bin/load-spark-env.sh: [[: not found
starting org.apache.spark.deploy.master.Master, logging to /home/couto/Downloads/spark-1.6.2-bin-hadoop2.4/logs/spark-couto-org.apache.spark.deploy.master.Master-1-ubuntu.out
start-master.sh: 78: [: false: unexpected operator

Nevertheless, the master seems to run right:

However, once I try to start a slave, it shows the following errors and no slave is included in the spark console.
couto@ubuntu:~/Downloads/spark-1.6.2-bin-hadoop2.4/sbin$ sh start-slave.sh spark://localhost:7077
start-slave.sh: 42: start-slave.sh: [[: not found
start-slave.sh: 42: start-slave.sh: [[: not found
start-slave.sh: 42: start-slave.sh: [[: not found
start-slave.sh: 52: /home/couto/Downloads/spark-1.6.2-bin-hadoop2.4/bin/load-spark-env.sh: [[: not found
start-slave.sh: 68: start-slave.sh: function: not found
start-slave.sh: 70: shift: can't shift that many

I'm using jdk 1.8.0_91
Spark: spark-1.6.2-bin-hadoop2.4 (i also tried with the prebuilt version for hadoop2.6)
Using start-all.sh as suggested in the first comment:
couto@ubuntu:~/Downloads/spark-1.6.2-bin-hadoop2.4/sbin$ sh start-all.sh
start-all.sh: 30: start-all.sh: 0: not found
starting org.apache.spark.deploy.master.Master, logging to /home/couto/Downloads/spark-1.6.2-bin-hadoop2.4/logs/spark-couto-org.apache.spark.deploy.master.Master-1-ubuntu.out
localhost: ssh: connect to host localhost port 22: Connection refused

Can you please give me some indications?

A: Add sbin path in .bashrc
export SPARK_HOME=/usr/local/spark
export PATH=$PATH:$SPARK_HOME/bin
export PATH=$PATH:$SPARK_HOME/sbin

then run .bashrc
source `.bashrc`

A: Running as follows it worked fine
bash start-master.sh
bash start-slave.sh spark://localhost:7077

Kind regards

A: All the scripts provided by Spark are Bash script and use some Bash-specific syntax. You're trying to run it in using a sh interpreter, which causes the error. You should just execute them directly.
chmod +x start-all.sh
./start-all.sh


text:
Q: Problem with custom ContextProvider state when using custom hook for fetching data in multiple tables in React I have multiple tables, of small size, and I want to be able to write / read / update my components when the corresponding table has been updated by the app (we can consider it's a single user app for the moment).
I've been inspired by this question to write a custom Provider and associated hook for data fetching (and eventually posting) in my app: React useReducer async data fetch
I came up with this:
import React from "react";
import { useContext, useState, useEffect } from "react";
import axios from "axios";

const MetadataContext = React.createContext();

function MetadataContextProvider(props) {
  let [metadata, setMetadata] = useState({});

  async function loadMetadata(url) {
    let response = await axios.get(url);
    // here when I console.log the value of metadata I get {} all the time
    setMetadata({ ...metadata, [url]: response.data });
  }

  async function postNewItem(url, payload) {
    await axios.post(url, payload);
    let response = await axios.get(url);
    setMetadata({ ...metadata, [url]: response.data });
  }

  return (
    <MetadataContext.Provider value={{ metadata, loadMetadata, postNewItem }}>
      {props.children}
    </MetadataContext.Provider>
  );
}

function useMetadataTable(url) {
  // this hook's goal is to allow loading data in the context provider
  // when required by some component
  const context = useContext(MetadataContext);

  useEffect(() => {
    context.loadMetadata(url);
  }, []);

  return [
    context.metadata[url],
    () => context.loadMetadata(url),
    (payload) => context.postNewItem(url, payload),
  ];
}

function TestComponent({ url }) {
  const [metadata, loadMetadata, postNewItem] = useMetadataTable(url);
  // not using loadMetadata and postNewItem here

  return (
    <>
      <p> {JSON.stringify(metadata)} </p>
    </>
  );
}

function App() {
  return (
    <MetadataContextProvider>
      <TestComponent url="/api/capteur" />
      <br />
      <TestComponent url="/api/observation" />
    </MetadataContextProvider>
  );
}

export default App;

(the code should run in CRA context, both apis can be replaced with almost any API)
When I run it, a request is fired on both endpoints (/api/capteur and /api/observation), but where I'm expecting the metadata object in the MetadataContextProvider to have 2 keys: "/api/capteur" and "/api/observation", only the content of the last request made appears.
When I console.log metadata in the loadMetadata function, metadata always has the initial state hook value, that is {}.
I'm fairly new to React, I tried hard and I'm really not figuring out what's going on here. Can anyone help?

A: Your problem is how you update the metadata object with setMetadata.
The operation of updating the metadata object via loadMetadata in your context is done by two "instances" respectively: TestComponent #1 and TestComponent #2.
They both have access to the metadata object in your context, but they're not instantly synchronized, as useState's setter function works asynchronously.
The easy solution for your problem is called functional updates.
useState's setter does also provide a callback function, which will then use (I'm oversimplifying here) the "latest" state.
In your context provider:
async function loadMetadata(url) {
  let response = await axios.get(url);
  setMetadata((existingData) => ({ ...existingData, [url]: response.data }));
  // instead of
  // setMetadata({ ...metadata, [url]: response.data });
}

Here is a working CodeSandbox:   https://codesandbox.io/s/elegant-mclean-syiol?file=/src/App.js
Look at the console to see the order of execution.

I highly recommend to fully read React hooks documentation, especially the "Hooks API Reference". There are also other problems with your code (for example missing dependencies in the useEffect hook, do you have ESLint enabled?).
If you want to have a better overview on how to use React's context I can recommend Kent C. Dodds' blog:
https://kentcdodds.com/blog/application-state-management-with-react
https://kentcdodds.com/blog/how-to-use-react-context-effectively

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'Sequence contains more than one element' (InvalidOperationException) thrown by external System.Core call when using Linq2Sql firstly let me explain that I fully understand why this InvalidOperationException has been thrown and that I am simply looking for a way to avoid it from being thrown. There is a call to System.Linq.Enumerable.SingleOrDefault() that I can see in the Visual Studio 2010 Call Stack window. However, the call is in external Linq2Sql code, so I have no access to change it.

(Sorry, you may need to zoom in to see this image properly)
The last internal code call before execution goes external is found in the application dbml.designer.cs file which I do have access to, but still cannot edit because it updates automatically and loses custom changes. It is in a (Linq2Sql) property setter for one of the database tables used in the application and it appears that the problem is caused by the call to the _DbAudioTrackContributors.Entity object:
public DbAudioTrackContributor DbAudioTrackContributors
{
    get
    {
        return this._DbAudioTrackContributors.Entity;
    }
    set
    {
        // This is the last internal line before the Exception
        DbAudioTrackContributor previousValue = this._DbAudioTrackContributors.Entity;

        // Execution never reaches here
        if (((previousValue != value) ||
        (this._DbAudioTrackContributors.HasLoadedOrAssignedValue == false)))
        {
            this.SendPropertyChanging();
            if ((previousValue != null))
            {
                this._DbAudioTrackContributors.Entity = null;
                previousValue.DbAudioTrack = null;
            }
            this._DbAudioTrackContributors.Entity = value;
            if ((value != null))
            {
                value.DbAudioTrack = this;
            }
            this.SendPropertyChanged("DbAudioTrackContributors");
        }
    }
}

If anyone has a way to provide me with the internal code for the EntityRef<TEntity> struct (or even just the Entity property), this could possibly help me to work out what is causing the problem.
The last line of my own code before the InvalidOperationException is thrown is a call to dataContext.SubmitChanges():
public int UpdateAudioTrack(AudioTrack audioTrack)
{
    using (TransactionScope transactionScope = new TransactionScope())
    {
        using (MidasDataContext dataContext = DataContext)
        {
            DbAudioTrack dbAudioTrack = dataContext.DbAudioTracks.Where(
                g => g.Id == audioTrack.Id).FirstOrDefault();
            if (dbAudioTrack == null) return -1;
            CopyToDbAudioTrack(audioTrack, dbAudioTrack);
            UpdateAudioTrackContributors(dataContext, audioTrack);

            // This is the last line of my code before the Exception
            dataContext.SubmitChanges(ConflictMode.FailOnFirstConflict);

            // Execution never reaches here
            transactionScope.Complete();
            return 0;
        }
    }
}

The CopyToDbAudioTrack method simply copies all of the property values from the AudioTrack object to the Linq2Sql generated DbAudioTrack object and the UpdateAudioTrackContributors method is shown below.
private void UpdateAudioTrackContributors(MidasDataContext dataContext, AudioTrack audioTrack)
{
    DataList<Label> labels = new DataList<Label>(
        audioTrack.Labels.Except(audioTrack.OriginalState.Labels));
    if (labels.Count > 0) AddAudioTrackContributors(dataContext, audioTrack, labels);
    labels = new DataList<Label>(audioTrack.OriginalState.Labels.Except(audioTrack.Labels));
    if (labels.Count > 0) DeleteAudioTrackContributors(dataContext, audioTrack, labels);
}

This method simply finds the Label objects that have changed and either adds or deletes them in the AudioTrackContributors database table. This table seems to be the root of the problem as it disappears if this code is commented out. However, this method correctly selects the objects to add or delete, so I am still confused. The AddAudioTrackContributors method basically calls the code shown below and the DeleteAudioTrackContributors code is shown below that:
List<DbAudioTrackContributor> dbAudioTrackContributors = new List<DbAudioTrackContributor>();
foreach (T dataListEntry in dataList)
{
    DbAudioTrackContributor dbAudioTrackContributor = new DbAudioTrackContributor();
    CopyToDbAudioTrackContributor(audioTrack, dataListEntry, dbAudioTrackContributor, contributorType);
    dbAudioTrackContributors.Add(dbAudioTrackContributor);
}
dataContext.DbAudioTrackContributors.InsertAllOnSubmit(dbAudioTrackContributors);

DeleteAudioTrackContributors:
List<DbAudioTrackContributor> dbAudioTrackContributors = new List<DbAudioTrackContributor>();
foreach (T dataListEntry in dataList)
{
    DbAudioTrackContributor dbAudioTrackContributor = dataContext.DbAudioTrackContributors.Where(d => d.DataListId == dataListEntry.Id && d.AudioTrackId == audioTrack.Id).FirstOrDefault();
    if (dbAudioTrackContributor != null) dbAudioTrackContributors.Add(dbAudioTrackContributor);
}
dataContext.DbAudioTrackContributors.DeleteAllOnSubmit(dbAudioTrackContributors);

Again, stepping through the code during execution shows that the above code also correctly selects the right objects to delete. As I can't see any problems in my code, I don't know where to look next.
If anyone has any ideas on how to proceed, I would be very glad to hear them. Many thanks in advance.

A: Ok, so this was a hideous problem with no clear clues as to the actual cause. It turned out to be the definition of the DbAudioTrackContributor table in the Linq2Sql dbml file.
Luckily, I also had a DbMasterTrackContributor table which did not suffer from the same error. After comparing all of my code that related to the two tables and this update, I could find no differences. Then, I decided to look at the Linq2Sql generated designer code and noticed a difference between the two table definitions.
The DbAudioTrackContributor table was registered as an EntityRef<DbAudioTrackContributor> whereas the working DbMasterTrackContributor table was registered as an EntitySet<DbMasterTrackContributor>.
After looking online at the differences between them, it turned out that EntityRef<T> is used for one to one relationships and EntitySet<T> is used for one to many and many to many relationships. I therefore suspected that they should both have been declared as EntitySet<T>, so I deleted the table from the dbml file and then re-added it.
After doing this, it began to work again! So I learnt a valuable lesson: If I have a dbml related error, first try removing and re-adding the suspect table(s) from the dbml file.


text:
Q: How to break  inbetween multiple ? I have the below html.

     Category
      Test
     Format
     Test 1

I want the output to be like below.
Category Format
Test     Test1

Note that the 2nd  and the 4th  are in a new line.
How do I achieve this using css?

A: You do not need to use CSS for this table all you need is HTML. For the table headers, you have to put a  tag inside a
 tag  so it goes something like this:

    Category
    Format

     Test
    Test 1

A: display:grid is ideal for this.

tr {
  display: grid;
  grid-template-columns: auto auto;
  column-gap: 0.5em;
}
td.break {
  grid-row: 2;
}

     Category
      Test
     Format
     Test 1


text:
Q: How to get Http Status Code and Vourbose logs by Curl function We try to check the API connection and response by several curl commands as follows, we have two issue though.
-- function
function exec_cmd() {
cmd=$@
echo "curl command:" ${cmd}
response=$(${cmd} --max-time ${timeout_sec} -o ${LogFile} -w '%{http_code}\n' -S)
echo statud_code:${response}
}

-- curl command#1 ...
exec_cmd curl -v -x put <LBFrontIP/ApiEndpoint1> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '{"SystemId":"XXXX", "AppNo":"99999999999"}'

-- curl command#2
exec_cmd curl -v -x put <LBFrontIP/ApiEndpoint2> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '{"sbSystemId":"XXXX", "email":"XXX@example.com",
"PhoneNo":"99999999999"}'

-- curl command#3
exec_cmd curl -v -x put <LBFrontIP/ApiEndpoint3> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '
{
    "ID1": "XXXXX",
    "ID2": "1q2w3e4r5t",
    "applyNo": "00db182faef74e779ca958681127bcec", ...
    "docLiveScore": "0.1391"
}'

Issue #1 : cmd=$@ can get the curl command but if that curl command contains @ or return code, it can't work as expected.
curl command#1 is working fine, but curl command#2 and #3 is not, since bash misunderstands @ and return code in data option as terminate of the command line. Curl command can work by itself though.
Also tried cmd=$* or cmd="$@" but not working so far.
Issue #2 : We'd like to get status_code for our quick check, but on the same time, we'd like to get the detail response in the log.
Is there any better way to get both of status_code and verbose log by appropriate function?
Above commands over write the verbose logs...

A: Given the complexity of the commands involved, I am tempted to say that you should avoid command parsing and read the command lines from a job configuration file.
#!/bin/bash

START=`pwd`
echo ${START}
BASE=`basename "$0" ".sh" `
ThisDATE=`date '+%Y%m%d_%H%M%S' `

LogPrefix="${START}/${BASE}.${ThisDATE}"        ; rm -f "${LogPrefix}"*
BatchFile="${START}/${BASE}.${ThisDATE}.config"     ; rm -f "${BatchFile}"

cat >$BatchFile <<-!EnDoFbAtCh
curl -v -x put <LBFrontIP/ApiEndpoint1> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '{"SystemId":"XXXX", "AppNo":"99999999999"}'
curl -v -x put <LBFrontIP/ApiEndpoint2> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '{"sbSystemId":"XXXX", "email":"XXX@example.com", "PhoneNo":"99999999999"}'
curl -v -x put <LBFrontIP/ApiEndpoint3> -H 'Content-Type:application/json; charset=utf-8' -H 'Host:<HostName>' -d '{ "ID1": "XXXXX", "ID2": "1q2w3e4r5t", "applyNo": "00db182faef74e779ca958681127bcec", ...  "docLiveScore": "0.1391" }'
!EnDoFbAtCh

function exec_cmd() {
    echo "curl command: ${cmd}"
    ${cmd} --max-time ${timeout_sec} -o ${LogFile} -w '%{http_code}\n' -S
    RC=$?
    echo "statud_code:${RC}"
}

index=1
while read cmd
do
    if [ -z "${cmd}" ] ; then  break ; fi

    LogFile="${LogPrefix}.${index}.log"

    exec_cmd

    index=`expr ${index} + 1 `
done < "${BatchFile}"


text:
Q: How much do mathematicians know? How much does a good mathematicians know about math? I mean, do mathematicians know the details of every branch of mathematics or they just specialize on a specific branch/topic? And what are the branches and minimum requirements that every mathematicians have to know in order to be one?

A: In general, the majority of mathematicians have a bit of exposure to a wide variety of topics so that if they needed a certain idea/tool from some other branch they can  find the material and relevant information relatively fast.
This is similar to your question.


text:
Q: Squid log rotation and sarg report creation errors 1) My Squid usually was creating 2 files: access.log and cache.log .
Some days ago it started creating many files like:
access.log.1
access.log.2  ... until access.log.9
cache.log.1 ... until cache.log.9

I could not find solution to this. Could anyone help me?
I want it to create only 2 files: access.log and cache.log
2) My Sarg was generating Squid's report once a day according to crontab.
Some days ago it started to generate reports twice like:
2017Jun25-2017Jun25
2017Jun25-2017Jun25.1

Why?
My crontab's content:
0 0 * * * /usr/sbin/squid -k rotate
10 1 * * * /etc/webmin/sarg/generate.pl

A: You need to check the settings of your system's log rotation script. It rotates system logs and deletes the oldest ones so that the hard disk isn't filled with log files.


text:
Q: P: TDA | PUNTEROS y MEMORIA alguien sabe como puedo solucionar este error que tengo? básicamente no me carga los "cartones"/matrices bien, adjunto los archivos .c y .h.
en resumen lo que tengo que hacer es cargar 3 matrices pero primero tengo que acceder a la estructura Jugador para posteriormente acceder a cartonJugador que es un puntero que apunta a una estructura llamada Carton que vendría a ser donde se encuentra la matriz.
PD: lo que tengo hasta ahora compila 2 matrices pero la segunda es pura basura, solo compila bien la primera matriz y luego se queda cargando como si estuviera en un bucle infinito
¿Alguien sabe como puedo solucionar este big error? pd estoy aprendiendo
pd: en el main solo compilo algo();
//prueba.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "prueba.h"
#include "cartonnn.h"

struct Jugador {

    Carton cartonJugador[3];
    Carton cartonMaquina[3];

};
datos algo(){
    datos player = malloc(sizeof(struct Jugador));

for(int i=0;i<3;i++){
player->cartonJugador[3] = cargarMatrizManual();

}
for(int i=0;i<3;i++){
mostrarMatriz(getCartonJugador(player->cartonJugador,i));
}

}
int getCartonJugador(datos x,int i){
return getBingo(x->cartonJugador[i]);
}

//prueba.h
struct Jugador;

typedef struct Jugador *datos;

datos algo();
int getCartonJugador(datos x,int i);

//cartonnn.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "prueba.h"
#include "cartonnn.h"

struct CartonEstructura{

    int carton[RENGLONES][COLUMNAS];

};

int *getBingo(Carton x){
return x->carton;
}

Carton cargarMatrizManual(){
  Carton x = malloc(sizeof(struct CartonEstructura));

    for (int r = 0; r < RENGLONES; r++){
        for (int c=0; c < COLUMNAS; c++){
            x->carton[r][c] = rand()% 9;
        }
    }
    return x;
}

void mostrarMatriz(Carton x){
    printf("\n");

    for(int r=0;r<RENGLONES;r++){
        for(int c=0;c<COLUMNAS;c++){
            printf("[% .2d]",x->carton[r][c]);
        }
        printf("\n");
    }
}

//cartonnn.h

#define RENGLONES 3
#define COLUMNAS 5

struct CartonEstructura;
typedef struct CartonEstructura *Carton;

int *getBingo(Carton x);
void mostrarMatriz(Carton x);
Carton cargarMatrizManual();


text: Q: mingw grep does not find matched results grep -rn "bg.tool" "pom.xml"  does not find any result in pom.xml. However, many pom.xml in the current directory or its subdirectories contain that string. Is it a MINGW thing, or is it wrong gramma?


text:
Q: looping a command to varying number of files in subdirectories I am trying to find a way to write a script that executes a command on varying number of files in subdirectories. I have 72 subdirectories each with varying number of sample files (fastq.gz files) with the one containing the most having 20 sample files. I used the following command but it gives me alot of empty folders and files when the number of files is less than 20 in a subdirectory.
#!/bin/sh
TOPHAT_BINARY=/home/alex/tools/tophat-2.1.0.Linux_x86_64/tophat2
GENE_REFERENCE=/home/alex/toxo/ref/genes/ToxoDB-27_TgondiiME49.gff
BOWTIE_INDEX=/home/alex/toxo/ref/bwt/ToxoDB-27_TgondiiME49_Genome
P=10 #use 10 threads
for FILE_ID in {001..072}
do
 for SAMPLE_ID in {001..020}
 do
 $TOPHAT_BINARY -G $GENE_REFERENCE -p $P -o /home/alex/toxo/alignments/Nishi_${FILE_ID}/sample_${SAMPLE_ID} $BOWTIE_INDEX /home/junya/bioinfo/NGS/original/Nishikawa.cell/rename_and_link/Nishi_${FILE_ID}/*_${SAMPLE_ID}.fastq.gz &
 mv /home/alex/toxo/alignments/Nishi_${FILE_ID}/sample_${SAMPLE_ID}/accepted_hits.bam /home/alex/toxo/alignments/Nishi_${FILE_ID}/sample_${SAMPLE_ID}.bam
 done
done

how do i edit the script
for SAMPLE_ID in {001..020}

so that the command only applies to the specific number of files in a particular subdirectory without outputting empty files?
Some of the subdirectories contain 2, 3, 10, 16 etc number of files so I just did 20 so if a subdirectory has 2 sample files then the output will contain 18 empty files....I added a command to remove all empty files at the end and it worked but Is there any other way to specify only the files contained in multiple subdirectories?
## secure and fast version ###
find /home/alex/toxo/alignments/Nishi_${FILE_ID} -type f -empty -print0 | xargs -0 -I {} /bin/rm "{}"

A: right after second do line, insert a new line and type
if [ -a /home/alex/toxo/alignments/Nishi_${FILE_ID}/sample_${SAMPLE_ID} ] ; then

and right before the first done line, again, insert a new line and type
fi

this will check the existence of the file before trying to process it. If it doesn't exist, it will skip over that SAMPLE_ID value.

A: It looks like Mel's answer has solved your problem; here's another variation. Instead of looping over a large range of SAMPLE_ID's (and what if you eventually end up with more than your expected 20?), I changed the loop so that it uses bash's filename expansion to loop over all and only the sample_* files that actually exist in /home/alex/toxo/alignments/Nishi_${FILE_ID}. In order to get your original value of SAMPLE_ID back, I use Parameter Expansion to retrieve the last three charcters from the SAMPLE_ID filename. Note that this breaks if you end up with more than 999 sample_* files!
I also changed your she-bang header line to explicitly call bash (via env) because if called as /bin/sh, bash will try to emulate Bourne shell, and lose features of the Bourne Again SHell (like fancy Parameter Expansion!).
As a side bonus, using SAMPLE_FILE in this way makes the commands a little bit shorter & easier to read!
#!/usr/bin/env bash
TOPHAT_BINARY=/home/alex/tools/tophat-2.1.0.Linux_x86_64/tophat2
GENE_REFERENCE=/home/alex/toxo/ref/genes/ToxoDB-27_TgondiiME49.gff
BOWTIE_INDEX=/home/alex/toxo/ref/bwt/ToxoDB-27_TgondiiME49_Genome
P=10 #use 10 threads
for FILE_ID in {001..003}
do
  for SAMPLE_FILE in /home/alex/toxo/alignments/Nishi_${FILE_ID}/sample_*
  do
    SAMPLE_ID=${SAMPLE_FILE: -3}
    $TOPHAT_BINARY -G $GENE_REFERENCE -p $P -o $SAMPLE_FILE $BOWTIE_INDEX /home/junya/bioinfo/NGS/original/Nishikawa.cell/rename_and_link/Nishi_${FILE_ID}/*_${SAMPLE_ID}.fastq.gz
    mv ${SAMPLE_FILE}/accepted_hits.bam ${SAMPLE_FILE}/sample_${SAMPLE_ID}.bam
    echo
  done
done


text:
Q: Octave: Loaded package is not recognized I have installed package image via pkg install -forge image and after tons of warnings (I am using clang as a C compiler, yeah, I know...) it finished installing.
I then loaded the package with ordinary pkg load image and Octave did not complain. But when I typed help viscircles to get some help on the function, Octave behaved like there was no package image, meaning it returned
>> help viscircles
error: help: the 'viscircles' function belongs to the image package
from Octave Forge but has not yet been implemented.

Please read <http://www.octave.org/missing.html> to learn how you can
contribute missing functionality.

Now I executed the pkg list to see if the package was indeed installed and loaded and yes, it was (there was an asterisk next to image package, which indicates that the certain package is loaded).
I decided to unload all packages and so I did. Now, before loading image again, I executed help viscircles again, but this time I got the next error:
>> help viscircles
error: help: the 'viscircles' function belongs to the image package
from Octave Forge which you have installed but not loaded.  To load the
package, run 'pkg load image' from the Octave prompt.

Interesting... I loaded the package again and same problem as before. I also downloaded the package manually and reinstalled it, same problems.
And yes, I have Octave 4.0.2, the requirements for image 2.6.2 is version 4.0.0+.

A: The function viscircles is on development versions of the image package only. It is not part of the current release, version 2.6.2 which you have installed.
The error message:
>> help viscircles
error: help: the 'viscircles' function belongs to the image package
from Octave Forge which you have installed but not loaded.  To load the
package, run 'pkg load image' from the Octave prompt.

means that the function is not part of Octave and if it is to exist at all, it will be on the image package. It doesn't mean that the image package will actually have it, only that it belongs to it.  The error message you get after loading the package:
>> help viscircles
error: help: the 'viscircles' function belongs to the image package
from Octave Forge but has not yet been implemented.

Please read <http://www.octave.org/missing.html> to learn how you can
contribute missing functionality.

tells you the issue.  The function viscircles is not implemented on that version of the package.
You can get it from the mercurial repository of the image package though at 75df28049249. Not sure if it will work on Octave 4.0 though.


text:
Q: Evaluation of a nested sum Given
$\sum_{i=1}^5 \sum_{j=i}^{12} {(2j-7)}$
My questions are :
(1)when $(j=i)$ what that actually means ?
(2) I tackled the inner sum
$\sum_{j=i}^{12}{(2j-7)}$ = 2$\sum_{j=i}^{12} {(j)}$ - $\sum_{j=i}^{12} {(7)} $
I know how to evaluate $\sum_{j=i}^{12} {(7)} $=$-7(13-i)$
I tried to use same logic with 2$\sum_{j=i}^{12}{(j)}$ it didn't work and the solution of the textbook says that the sum of this, is the sum of the first 12 integers minus the sum of the first i-1 integers.
I have no idea what that means and how so.
Any clarifications please ?
Thanks in advance.

A: $$S=\sum_{i=1}^{5} \sum_{j=i}^{12}(2j-7)=\sum_{i=1}^{5} \left[\sum_{j=1}^{12}(2j-7)-\sum_{j=1}^{i-1}(2j-7)\right].$$
$$S=\sum_{i=1}^{5}\left[ (12.13-7.12)-(i(i-1)-7(i-1)\right]=72.5-\sum_{i=1}^{5}(i^2-8i+7)$$ $$=360-55+8.5.3-7.5=390$$
We have used $\sum_{k=1}^{n}=\frac{1}{2}n(n+1), \sum_{k=1}^n k^2=\frac{1}{6}n(n+1)(2n+1)$


text:
Q: Google Chrome running super slow Today I started my computer as usual. And opened the Google Chrome browser and found that I was running SUPER slow.
What steps will reproduce the problem?
(1) Create a new browser window
(2) Choose File -> New Tab
What is the expected output?
The NTP page should display instantaneously
What do you see instead?
The NTP takes a full 1 second to appear. By "appear" I mean the new tab appears with blan content instantly, but then you wait 1s for the NTP page contents to finally show up.
Attached is a trace - see pid 47093. It shows two NTP loads, one at 5.5s and the second at 8.5s. It shows the page taking about 200ms to load, followed by a CSS animation that runs for 1.1s (according to the red boxes along the top).

I'm using:

*

*Windows 10 (64-bit)

*Google Chrome v49.0.2623.112 m (64-bit) (last version)

*

*Extensions: ad-block

*PC:

*

*CPU AMD FX-8320 (3.5GHz)

*RAM 8GB

Edit
Is a bug.

*

*https://bugs.chromium.org/p/chromium/issues/detail?id=599872

*https://bugs.chromium.org/p/chromium/issues/detail?id=599212


text:
Q: Android SQLite - "if" SQLite table column null then execute I want to write code which checks the table if the column value is null and then execute the insert function. If not, run the code.
Cursor sumw = dbObject.rawQuery(
        "SELECT COMAMOUNT FROM COMMISION",
        null);
sumw.moveToFirst();
int e = sumw.getInt(0);
if(e != 0){
    alerts();
}

This is how I tried. I know it must be wrong, because it always sends the alert to insert.

*

*Table name : COMMISION - DB_COMMISION

*Table column : COMAMOUNT - handle.COM_AMOUNT

A: Please try this
Cursor sumw = dbObject.rawQuery(
                "SELECT COMAMOUNT FROM COMMISION",
                null);

if(sumw.moveToNext()){
   String no = sumw.getString(0);
   if( no != null ) {
      alerts();
   }
}


text:
Q: PHP: What is a good way to upload multiple large files? What is a good way to upload multiple large files in PHP?
Note: in my case I don't really need very large files, I need something like 40-50 or maybe 100 MB upload. My purpose and goal is mainly about documents upload in websites, these documents (pdf, doc, etc.) can sometimes be 20-30 MB and rarely 100+MB, where normally the php MAX_UPLOAD_FILESIZE is 10-20 MB. I think that having a large MAX_UPLOAD_FILESIZE is very bad and anyway allowing large file uploads in PHP (like 1GB+) is really a bad idea.
I have been reading, even here on SO, different solutions like plupload and some others (HTTP Upload, bigUpload, etc.) and I am not sure which way is better to consider.
As a principle, I'd like to find something with mantained code (not an abandoned library) and possibly following coding standards (PSR).
I think that writing all from scratch would be a huge work, but maybe I am wrong, if someone did that I would like to hear your experience. Of course if I can't find something that gives me what I need, I'll have to edit existing libraries or write one on my own.
I will give a try to plupload but my biggest concern is that it might not be well mantained. There is a v3 release but the stable is still the v2. If I understand correctly, the last updates of this library on GitHub were made in 2017 and this doesn't really reassure me. PHP but everything in general changes really quickly.
Problem 1: Server knows the size of the file only when the upload is finished
I think this is the first problem. I can't be sure about the file size until the upload is completed. If I have to give an error in PHP because the file is too big, I'd need to upload the file before. I could guess the size in javascript but I think that would be too hackable. Same thing for HTML5. All client-side checks could be "hacked" or manipulated even if it requires work, it is still doable
Problem 2: File chunking, is it the best solution?
I have read about file chunking, which is very interesting, but that is only client-side, right? Because to chunk a file on server-side, you go back to problem 1, you need to upload the whole file before chunking it. Is client-side chunking safe? Are there known vulnerabilities about it? (an example, could I exploit something out while the file is being uploaded?). I will read more about this later.
Also what about the time required to upload? Let's say you are using your phone in 4G to upload two PDFs or JPGs on a form, you have to upload 20-30 MB with a bad signal in that moment, let's say you take 30 seconds or 1 minute to upload them. Will the server stop listening after a while?
In any case, with file chunking, do I need to have a large MAX_FILESIZE_UPLOAD? Is usually the request sent (as a POST) with the entire file, which could return an error because the size exceeds the PHP limit? I would like to keep a normal PHP file size limit.
Problem 3: stopping file upload and deleting interrupted upload
What happens if I stop or I want to stop my upload? I guess that the server will find itself with a temporary file which is only partially uploaded.
Then, in general, is the best way to have a cron checking the /tmp (or whatever) folder and deleting uncompleted files?
Problem 4: overwriting interrupted uploads
What if the user uploads a new file that should overwrite the old one, but the old one was not completed? Let's say, user uploads a 10MB document but realizes it's the wrong one. He will probably reload the page or maybe click "Browse" again and upload the new one. So, all the temporary files should have a unique name. If I remember correctly, PHP already gives them a random name in /tmp/. Is this enough? Would it be better to manually give them a random name, maybe based on a timestamp?
In code words, something like:
$fileName = time() . '-' . uniqid() . '.tmp';

Problem 5: what about multiple files upload?
Let's say the user uploads 3 documents, 10 MB each one. Should the server receive them all at the same time or one by one? Or maybe is it the same? At a first look, I might think that multiple uploads at the same time could give more problems with server load. Maybe this is not that important though.
Problem 6: accessibility
Would all this be easily accessible? Do you think that a user using a screen-reader would be able to upload multiple (and possibly large) files without problems?
Conclusion
In conclusion I will take a look at existing libraries and test a bit if I can find a good solution for my needs. In general I would like to read comments or experiences that could  help me understand possible difficulties and problems that I could encounter.

A: I will try to help you in your questions:
Problem 1: Server knows the size of the file only when the upload is finished
You need to configure upload_max_filesize and post_max_size to allow the maximum file upload you want to be able to receive in a single request.
And yes, you will know the size once the file has been uploaded, as your script will be executed once the file is completely uploaded.
You can have some kind of checking in your javascript to improve your UI to the customer.
Also if the file exceeds the maximum size, the file will not be available in your server script.
Problem 2: File chunking, is it the best solution?
I don't think this would be any better than uploading the whole file.
The speed will not be increased, so although you can paralelize the upload, the upload speed will be determined by the client speed, you will end up uploading 1 file at 10Mb/s or 10 files at 1Mb/s, at the end will be the same.
Also you will have a very complex code at the client and at the server to handle it, and you will have to handle new error scenarios.
It is not worth it.
Problem 3: stopping file upload and deleting interrupted upload
If the client stops the upload, your server code will not be executed as the request has not been completed.
Also you won't have any troubles with duplicated tmp files, the file is removed from tmp folder when you move it using move_uploaded_file and if you don't move the file will be deleted when your script has finished.
https://www.php.net/manual/en/features.file-upload.post-method.php
Problem 5: what about multiple files upload?
With multiple file uploads, i prefer to use diferent requests via javascript for each file, then you can paralelize or start uploading files one by one and show the user the upload process.
With javascript you can see the upload percent of each request, and it is very useful when uploading big files to give the user the feedback that the application is working properly.
Problem 6: accessibility
You will handle the same accessibility issues than uploading a small file.
Conclusion
The server side coding is independent of the file size you are trying to upload, as it just does some checks and moves the file to the proper location.
You will have to code some javascript to improve the ui to show the progress to the customer, and if you want to add the ability to cancel the upload, it is very easy as it is just an http request with a listener that updates the progress (https://stackoverflow.com/a/47638378/1445024)


text:
Q: Project cant't find DynamicComponent : Blazor SOLVED: solution at the end
I am trying to use the DynamicComponent but it says,

if "Ctrl + ." it suggests me to create a razor component.
Here what I have or tried so far:

*

*VS 2022 version 17.0.0 Preview 2.1

*Blazor WASM Project Property "Target framework" set to .NET 6.0

Package Manager:
dotnet --version
6.0.100-preview.6.21355.2

*

*deleted bin, obj folders

*rebuild project and solution

Any Idea what am I missing?
Best Alex
EDIT::
dotnet --info

EDIT2::
Code-snippet: Tabs.razor
@page "/tab"

Tabs

@using Microsoft.AspNetCore.Components.Web

Loan application

<select @onchange="OnChange" class="form-control">
  <option value="@nameof(Tabs)">Select a value</option>
  <option value="@nameof(HundeVersicherung)">Hunde</option>
  <option value="@nameof(ReiseVersicherung)">Reise</option>
</select>

start

<DynamicComponent Type="selectedType" />

@code {
    Type selectedType = typeof(Tabs);

    public void OnChange(ChangeEventArgs changeEventArgs)
    {
        selectedType = Type.GetType($"InsuranceProductsUI.Pages.{changeEventArgs.Value}");
        Console.WriteLine("");
    }
}

Code-snippet: Hundeversicherung.razor
@page "/hunde"
@using InsuranceProductsUI.Components

        <Search OnSearchChanged="SearchChanged" />

    <HundeVersicherungTable ProductAs="ProductAsList" />

        <Pagination MetaData="MetaData" Spread="2" SelectedPage="SelectedPage" />

Project page screenshot:

Namespace screenshot:

Even though it doesn't recommend me for an update in .net6.0. I manually had to update the Microsoft packages and the Automapper.

before (not working):
  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="10.1.1" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.8" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.8" PrivateAssets="all" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.2" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
    <PackageReference Include="MimeKit" Version="2.13.0" />
    <PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
  </ItemGroup>

after (working):
  <ItemGroup>
      <PackageReference Include="AutoMapper" Version="10.1.1" />
      <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
      <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.0-preview.6.21355.2" />
      <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.0-preview.6.21355.2" PrivateAssets="all" />
      <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0-preview.6.21352.12" />
      <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0-preview.6.21352.12" />
      <PackageReference Include="MimeKit" Version="2.14.0" />
      <PackageReference Include="System.Net.Http.Json" Version="6.0.0-preview.6.21352.12" />
  </ItemGroup>


text:
Q: Strange C++ Builder Linker error DATA.BIND.OBJECTSCOPE.OBJ So I recompiled a perfectly fine and working project and suddenly all I get is this linker error:
[ilink32 Error] Fatal: Unable to open file 'DATA.BIND.OBJECTSCOPE.OBJ'

The project is a C++ console application with VCL enabled and I have no idea where the DATA.BIND.OBJECTSCOPE.OBJ comes from.
These are the headers I'm using.
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <vector>
#include <vcl.h>
#include <System.hpp>
#include <System.IOUtils.hpp>
#include <System.Zip.hpp>
#include <System.Classes.hpp>
#include <System.IniFiles.hpp>

I tried to do a complete disc clean, removing all temp files etc... No change...
This project was compiling fine yesterday.

A: I found this solution on Embarcadero bug tracker:
Add the followind to one of your source files
#if defined(_WIN32) && !defined(_WIN64)

#pragma link "Data.Bind.ObjectScope.obj"

#endif

The original solution ha been provided here.
https://plus.google.com/103589122222763968447/posts/gSwPfUZLPEH

A: I'll add this here if someone else stumbles upon this highly frustrating issue.
I had this exact problem. It occurred when I included REST.Client.hpp in an Embarcadero RAD Studio project which uses C++ Builder. After some wasted hours I ended up dropping the REST Client component onto a GUI designer form. Boom. Works. It was this site that lead me onto the right track.
It says that #pragma link entries are included in source files automatically when you put a component onto a form.

A: In my experience, this is caused when a library or control that your project uses decides that it needs DATA.BIND.OBJECTSCOPE (e.g., due to a uses clause in Delphi code or a #pragma link in C++Builder code).
A quick but not at all elegant fix:

*

*Determine which .lib file includes this .obj file.  (You can do this by going to the libraries directories for RAD Studio and for any third-party libraries you're using and grepping for the .obj filename, or the TLIB command can list the .obj files in a .lib.)

*Edit your .cbproj file in a text editor to add that library to the LinkPackageStatics and AllPackageLibs sections.

Depending on your project settings (whether or not you're using runtime packages, whether you're linking statically or dynamically), you may be able to go under Project Options, Packages and under Project Options, Packages, Runtime Packages and edit package lists there, instead of editing the .cbproj directly.

A: Adding to the answers, as none of the above answers fixed my project, having the same linker error.
Including the Vcl.Bind.Consts.hpp header, i.e.
#include "Vcl.Bind.Consts.hpp"

fixed the issue.


text:
Q: Weblogic installer reads from incorrect file I am trying to install Weblogic 12c.
I placed the Weblogic jar files in my C drive.
To compile and run the jar file, I typed the following command
java -jar fmw_12.2.1.0.0_wls_quick.jar

I have ensured that
1) Command prompt is run in administration mode
2) Environmental variable JAVA_HOME = C:\Program Files\Java\jdk1.7.0_79
However I get the following error
This installer must be executed using JDK but C:\Program Files\Java\jre7 is not a valid JDK

It appears that the installer is reading from C:\Program Files\Java\jre7 instead of C:\Program Files\Java\jdk1.7.0_79
How do i change the installer setting to correct the changes??

A: you still use jre java
"%JAVA_HOME%\bin\java" -jar fmw_12.2.1.0.0_wls_quick.jar


text:
Q: How to non-interactively add a Splunk forwarder? I wish to create a script for setting up forwarding to a splunk server. Here's what I have so far:
./splunk add forward-server SPLUNK-IP-ADDRESS:SPLUNK-PORT
However, it asks for my credentials. How can I non-interactively pass credentials to splunk and setup the forwarder?

A: You can use the splunk login command to pass your credentials to the Splunk server:
./splunk login -auth 'admin:mypassword'
./splunk add forward-server SPLUNK-IP-ADDRESS:SPLUNK-PORT


text:
Q: SVN Error: post-commit hook failed with locked file message I get the following SVN error (using TortoiseSVN) when i am trying to tag trunk.
Error: post-commit hook failed (exit code 1) with output:
Error: svn: Working copy '.' locked
Error: svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)

The tag still seems to have been created ...
I have no post-commit hooks added ...
I have tried the following:

*

*update + cleanup

*search for 'lock' files in .svn dir

*fresh checkout

I am not sure what is going on, any help would be appreciated?

A: Earlier I changed "svnserve.conf" realm = [new-realm] which caused user/pass re-prompts for checkouts/updates. On the SVN server there is a post-commit hook which does an svn update, because of the realm change, the hook was dying because creds needed to be reset.
Moral of the story is: changing realm will cause creds to be invalidated (which may break your automated scripts)


text:
Q: About the non-trivial zeros of the Riemann zeta function. We define the function $N(T)$ is the number of non-trivial zeros $ρ$ of the Riemann zeta function which
$0<\Im (ρ) <T$ .
Then
$$ N(T+1)-N(T)=O(\log(T)) \quad (T\to \infty) $$
I understood this property.
But I couldn't understand following claim.
For arbitrarily large T>O and all non-trivial zeros $ρ=β+iγ$ ,We get
$$\frac{1}{\log (T)}=O(|T-γ|)$$
This property is used for the proof of the explicit fomula.
Please tell me about this.


text:
Q: Matching parts of lines in a file (python) I currently have a list of genes in a file. Each line has a chromosome with it's information. Such an entry appears as:
NM_198212  chr7  +  115926679 115935830  115927071  11593344  2  115926679,'115933260',  115927221,'115935830',
The sequence for the chromosome starts at base 115926679 and continues up to(but not including) base 115935830
If we want the spliced sequence, we use the exons.The first extends from
115926679 to 155927221, and the second goes from '115933260' to '115935830'
However, I have run across a problem when on a complementary sequence such as:
NM_001005286 chr1 - 245941755 245942680 245941755 245942680 1 245941755,  '245942680'
Since column 3 is a '-', these coordinates are in reference to the anti-sense strand (the complement to the strand). The first base (in bold) matches the last base on the sense strand (in italics). Since the file only has the sense stand, I need to try to translate coordinates on the anti-sense strand to the sense strand, pick out the right sequence and then reverse-complement it.
That said, I have only been programming for about half a year and and not sure how to starts going about doing this.
I have written a regular expression:
'(NM_\d+)\s+(chr\d+)([(\+)|(-)])\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+),(\d+),s+(\d+),(\d+),'

but am now unsure as to how to start this function...
If anyone can help me get started at all on this, perhaps making me see how to do this, I would very much appreciate it.
OK: suppose this is chromosome 25:
AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG
(there are 10 of each character).
Now: if I am looking for an unspliced gene on: chr25 + 10 20
Then the gene starts on position 10 (starting from 0), and goes up to but not including position 20. So its:
CCCCCCCCCC
This is easy. It matches python string slicing really well.
Its more confusing if I give you:
chr25 - 10 20
What you have is the positive strand. But this gene is on the negative (complementary) strand. Remember what the chromosome looks like as a double-strand:
AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG
TTTTTTTTTTGGGGGGGGGGAAAAAAAAAACCCCCCCCCC
We are looking for the gene on the bottom strand. Meaning we count from 0 starting on the right. Number the top strand from the left, and the bottom strand from the right. So what I want here is AAAAAAAAAA.
The catch is that I'm only giving you the top strand. I'm not giving you the bottom strand. (You could generate yourself from the top strand — but given how large it is, I advise against that.)
So you need to convert coordinates. On the bottom strand, base 0 (the right-most C) is opposed to base 39 on the top strand. Base 1 is against base 38. Base 2 is against case 37. (Important point: notice what happens when you add these two numbers up — every time.) So base 10 is against base 29, and base 19 is against base 20.
So: if I want to find base 10-20 on the bottom strand, I can look at base 20-29 on the top (and then reverse-complement it).
I need to figure out how to translate to coordinates on the bottom strand to the equivalent coordinates on the bottom strand. Yes: it is very confusing
I have tried weronika's original answer:
fields = line.split(' \t')
geneID, chr, strand = fields[:2]
start = int(fields[3])
end = int(fields[4])
if strand == '-':
    start,end = -(start + 1), -(end + 1) # this part was changed from original answer.

which is on the right track, but it's not enough. This would take the 10 and 20, and turn it into a 20 and 10.
And I know I can reverse complement the string by doing this:
r = s[::-1]
bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
l = list(r)
o = [bc[base] for base in l]
     return ''.join(o)

Edited! Does this look correct?!
fp2 = open('chr22.fa', 'r')
fp = open('chr22.fa', 'r')
for line in fp2:
    newstring = ''
    z = line.strip()
    newstring += z
for line in fp:
    fields = line.split('\t')
    gene_ID, chr, strand = fields[:2]
    start = int(fields[3])
    end = int(fields[4])
    bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'a': 't', 't': 'a', 'c':'g', 'g':'c', 'N':'N', 'n':'n'}
    l = list(newstring)
    if strand == '+':
        geneseq = ''.join([bc[base] for base in l[start:end]])
    if strand == '-':
        newstart, newend = -(start + 1), -(end + 1)
        genseq = ''.join([bc[base] for base in l[newstart:newend]])

A: I didn't understand the domain problem, but it looks like you're trying to cram too much into one regex.  Try to break it down into simpler subproblems, like the following (in pseudocode):
if third column is a '+'
    parseRegularSequence()
else
    parseComplementarySequence()

A: As noted in my comment to the question, this seems like a very odd file format, thus my original confusion.
Note: if this is one of the standard biology file formats, you would probably be better off using Biopython or something similar to parse it.
If you want to do your own parsing, regular expressions still seem like the wrong way to go - difficult to read and unnecessary with a simple space/tab separated file.
I'm assuming you have parsed your chromosome fasta file and have the sequences of all the chromosomes as a chrom_sequences name:seq dictionary, and also that you have a reverse_complement function (both of those things are easily implemented by hand but probably better done with biopython).
fields = line.split(' ')  # or '\t' instead of ' ' if the file is tab-separated
gene_ID, chr, strand = fields[:2]
start, end = [int(x) for x in fields[3:5])
this_chromosome_seq = chrom_sequences[chr]
# if strand is +, just take the sequence based on the start-end position
if strand == '+':
  # be careful about off-by-one errors here - some formats give you a 1-based position,
  #  other formats make it 0-based, and they can also be end-inclusive or end-exclusive
  gene_sequence = this_chromosome_seq[start:end]
# if your coordinates really are given as antisense strand coordinates when strand is -,
#  you just need to subtract them from the chromosome length to get sense-strand coordinates,
#  (switching start and end so they're still in smaller-to-larger order),
#  and then reverse-complement the resulting sequence.
if strand == '-':
  chrom_length = len(this_chromosome_seq)
  # again, be careful about off-by-one errors here!
  new_start,new_end = chrom_length-end, chrom_length-start
  gene_sequence = reverse_complement(this_chromosome_seq[new_start:new_end])

Original answer, didn't actually do what was asked:
If you just want to get the start/end positions, do something like this:
fields = line.split(' ')  # or '\t' instead of ' ' if the file is tab-separated
gene_ID, chr, strand = fields[:2]
start = int(fields[3])
end = int(fields[4])
if strand == '-':
  start,end = end,start

Then you'll have to parse your fasta file to actually get the sequence for these start-end coordinates, and reverse-complement it if strand=='-'.  Again, I think Biopython can do most of that for you.
Another note - Biostar is a good StackExchange-type site specifically for bioinformatics, you may get better answers there.

A: If you slice a string with a negative number, Python counts backward from the end.
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
s = "AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG"
"".join(complement[c] for c in s[-20:-10])

EDIT:
Your edit looks about right to me, yes. I am very bad at checking for fencepost errors, but you're better placed to see those than I am anyway!
I've rewritten your code to be more Pythonic, but not changed anything substantial.
bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'}

f = open('chr22.fa')
l = ''.join(line.strip() for line in f)
f.seek(0)

for line in f:
    fields = line.split('\t')
    gene_ID, chr, strand = fields[:2]

    start = int(fields[3])
    end = int(fields[4])

    if strand == '-':
        start, end = -(start + 1), -(end + 1)

    geneseq = ''.join(bc[base.upper()] for base in l[start:end])

A: I imagine (especially since your files are large) that it would be MUCH easier to read and write directly from the file buffer.
Let's say you've already parsed your header file. The line that you parsed looks like so:
line = "NM_001005286 chr1 - 245941755 245942680 245941755 245942680 1"

you then determine what the start/end positions are (in antisense coords):
name, chromosome, direction, start, end = line[:5]

Then, do the following:
#Open up the file `chr1.txt`.
f = open("chr1.txt", "r")

#Determine the read length.
read_len = end - start

#Seek to the appropriate position (notice the second argument, 2 -- this means
#seek from the end of the file)
f.seek(-end, 2)

#Read the data
sense_seq = f.read(read_len)

After that it's just a matter of converting the sequence to antisense.
Easy :)


text:
Q: Getting Value using Linq to Xml I have the following Xml structure:
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <sitemap>
  <loc>http://www.example.com/</loc>
  <lastmod>2011-11-27T08:34:46+00:00</lastmod>
 </sitemap>
 <sitemap>
  <loc>http://www.example.com/123</loc>
  <lastmod>2011-11-27T08:34:46+00:00</lastmod>
 </sitemap>
</sitemapindex>

I want to get the links along with their modification date. e.g. the result should look like:
loc: http://www.example.com/ - lastmod: 2011-11-27T08:34:46+00:00
loc: http://www.example.com/123 - lastmod: 011-11-27T08:34:46+00:00
I've used the following code but nothing seems to work:
XElement root = XElement.Load("data.xml");
var results = from el in root.Elements("sitemap")
              select new
              {
                  loc = (string) el.Element("loc"),
                  lastmod = (string) el.Element("lastmod")
              };

foreach (var result in results)
{
    Console.WriteLine("loc:" + result.loc + " - lastmod:" + result.lastmod);
}

even this query doesn't return anything:
var results = from el in root.Elements("sitemap")
              select el;

I am new to Linq to Xml, Please help.

A: The problem is you're trying to select elements without namespaces. Try this instead:
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
var results = from el in root.Elements(ns + "sitemap")
              select new
              {
                  loc = (string) el.Element(ns + "loc"),
                  lastmod = (string) el.Element(ns + "lastmod")
              };


text:
Q: Why is true && false equal to 1 in C++? I was playing around with booleans and ended up with this line of code:
std::cout << true && false;
which, for some reason, produces 1. How is this possible, if && requires both sides to be true, in order to produce 1?

A: Due to operator precedence, the true is printed and then the return of the operator<< (the std::cout) is && with the false.
(std::cout << true) && false; // Equivalent

A: Because operator<< has higher precedence than operator&&, std::cout << true && false; is just same as (std::cout << true) && false; (i.e. print out true firstly, then the returned std::cout is converted to bool, which is used as operand with false for the operator&&, the result is discarded at last).
Note that std::cout could be converted to bool via operator bool, which could be used in contextual conversions (including as operand of built-in operator&&) even it's marked as explicit.

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

You might specify precedence by adding parentheses.
std::cout << (true && false);


text:
Q: Should I emphasize the hyphen, here? I need to emphasize one part of a combined word containing a hyphen (cis-Golgi). What would be correct? Including or excluding the hyphen / minus in \emph{}? Does it make a difference?

A: Semantically, the emphasis should be on cis only. The cis is italicised because it's a latin abbreviation. You are using the hyphen to indicate a compound name, and the hyphen is not part of the latin word, so it should not be emphasised.


text:
Q: Azure Function Managed Identity to Azure Sql - Login failed for user '' I have a C# dotnet core 3.1 Azure Function App (named func-utrngen-dev-001) that I'd like to configure to authenticate to a Sql Azure database via managed identity.
Steps Taken:

*

*Created the AAD admin for sql server account

*Used that account to open a connection to the sql server

*Ran the following to created a "contained user" of the same name as the azure function app
CREATE USER [func-utrngen-dev-001] FROM EXTERNAL PROVIDER
ALTER ROLE db_datareader ADD MEMBER [func-utrngen-dev-001]
ALTER ROLE db_datawriter ADD MEMBER [func-utrngen-dev-001]

*Ensured that "Allow Azure services and resources to access this server" is set to "Yes" from the Azure Portal under the Sql Server\Security\Firewalls and virtual networks blas

*Ensured that System assigned\Status is set to "On" on the function app's Identity blade
When the function app attempts to authenticate, I get the following error:

Login failed for user '<token-identified principal>'

So I installed Microsoft's "MSI Validator" tool and ran through the steps described here.
I ran the following from the Powershell window of a Kudu session:

./msi-validator.exe test-connection -r sql -e "Data Source=sql-utrngen-dev-001.database.windows.net;Initial Catalog=utrngen;"

It successfully obtained a token but then failed with the same error as my function app:

Unable to connect to SQL. Exception : Login failed for user
'<token-identified principal>'

*I ran select * FROM sys.fn_get_audit_file(path to tsql audit blob) but the results only showed activity from my account logged into SSMS

What should I try next?

A: The fix was to give the correct name for the database ♂. More haste less speed


text:
Q: A question about writing data to a custom section? below is my class thanks to the article found at:
URL: Derik Whittaker
My Code:
public class FavsSection : ConfigurationSection
    {
        public override bool IsReadOnly()
        {
            return base.IsReadOnly();
        }

        public FavsSection() // default Constructor.
        { }

        [ConfigurationProperty("Items", IsRequired=true)]
        public FavouritesCollection FavsItems
        {
            get
            {
                return (FavouritesCollection)(base ["Items"]);
            }
        }
    }

    [ConfigurationCollection(typeof(FavouriteElement))]
    public class FavouritesCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new FavouriteElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((FavouriteElement)(element)).ItemType;
        }

        public FavouriteElement this[int idx]
        {
            get
            {
                return (FavouriteElement)BaseGet(idx);
            }
        }

        public override bool IsReadOnly()
        {
            return base.IsReadOnly();
        }
    }

    public class FavouriteElement : ConfigurationElement
    {
        [ConfigurationProperty("id", DefaultValue = "", IsKey = true, IsRequired = true)]
        public string ID
        {
            get
            {
                return ((string)(base["id"]));
            }
            set
            {
                base["id"] = value;
            }
        }

        [ConfigurationProperty("path", DefaultValue = "", IsKey = false, IsRequired = false)]
        public string Path
        {
            get
            {
                return ((string)(base["path"]));
            }
            set
            {
                base["path"] = value;
            }
        }
    }

My config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="FavouritesMenu" type="MyFileExplorer.FavsSection, MyFileExplorer" />
  </configSections>
  <FavouritesMenu>
    <Items>
      <add id="1" path="c:\foo" />
      <add id="2" path="C:\foo1" />
    </Items>
  </FavouritesMenu>
</configuration>

As you can see I am trying to write data into my custom section called 'Favourites Menu'. I think I have got the basic gist of the idea but I don;t see how to make my next step ... something got do with the 'IsReadOnly' method? Can someone please help me fill in the blanks? Feel free to rename things to make it easier to read? I thought I would make a half decent effort before I asked for help ...
RESEARCH: StackOverFlow - SAME QUESTION!
---------- Got lost on Pike65's comment ... cannot write to collection because it is set to read only.
I presume the collection needs setting to IsReadOnly false and some helper methods are needed to add data into the collection? This part is all alittle hazy to me ...
Thanks for reading,
Ibrar

A: I have been doing some basic testing and to 'NO' surprise ... the above actually works. You just need to make sure that when you want to pass data to your config section, then by default they are read only. So you will need to override the 'isReadOnly()' method inorder for the above code to work.
So the solution is that the above peice of code, does work ... you just need to override an extra method to allow you to access the collection responsible for holding your element data and manipulate its contents via the properties you define in the class that extends or inherits from the Configuration Element class.
UPDATE:
The above code sample I pasted in allows you to edit what already exists in the config file inside your custom section. In order to add a new item for example like the following:
            FavsSection favconfig = (FavsSection)config.GetSection("FavouritesMenu");

            ToolStripMenuItem menu = (ToolStripMenuItem)returnMenuComponents("favouritesToolStripMenuItem", form);

            ToolStripItemCollection items = menu.DropDownItems;

            for (int i = 0; i < items.Count; i++)
            {
                //favconfig.FavsItems[i].ID = i.ToString();
                //favconfig.FavsItems[i].Path = items[i].Text;

                favconfig.FavsItems[i] = new FavouriteElement()
                {
                    ID = i.ToString(),
                    Path = items[i].Text
                };
            }

As you can see above, I am physically adding a new 'FavouriteElement' object into the collection returned by the property 'favconfig.FavItems'. In order to to do this, one property needs extending to support this.
public FavouriteElement this[int idx]
{
    get
    {
        return (FavouriteElement)BaseGet(idx);
    }
    set
    {
      base.BaseAdd(value);
    }
}

This indexer or paramterful property as 'Jeffrey Richter' calls them needs to have it's 'Set' accessor implemented as shown above in the code snippet. I have pasted it in here as it did not take long to figure out and most of the code is changed using a template I have used from Derik Whittaker's Article. Hopefully this will alow other coders to implement something similar.
Another solution would be to simply rather than 'getting' the collection all the time that 'lassoes' together all my 'FavouriteElements', you could implement the 'set' accessor for the related property. I have not tested this but I might be worth trying out.


text:
Q: Android studio, open a file , continuously write and then close I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.
I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file
  String data= reading1","+reading2+","+time +"/n";
        try {
            FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
            out.write(data.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();

I would prefer to have the file open when the start button is clicked.
if ( v.getId() == R.id.start ){
                // checks which button is clicked
                Log.d("dennis", "Scan working"); //logs the text
                // open a file
                try {
                    FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

but when it comes to closing the file, no options for .close() appear when out is typed
if ( v.getId() == R.id.stop ){
                // checks which button is clicked

                out. // no valid options appear
                messageValue.setText(R.string.stopButtonText);// changes the hallo world text
                readNoRead=false;

            }

Does all the open/write/close need to be together or is it possible to
***open file***
-----
Cycle through all the data
-----
***Close file***

A: It is definitely possible to open, process and close a file all in one block without closing the file.
Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);

to
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);

and then add FileOutputStream out; to a line above the first if statement (outside of the block).
You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.

A: You should store a link to your FileOutputStream on top level in your class.
Example to your code:
FileOutputStream out;

void clickStart() {
    if (v.getId() == R.id.start){
        // checks which button is clicked
        Log.d("dennis", "Scan working"); //logs the text
        // open a file
        try {
            out = openFileOutput("data.csv", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
}

void writeData() {
    String data= reading1+","+reading2+","+time +"/n";
    try {
        out.write(data.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

void clickStop() {
    if (v.getId() == R.id.stop) {
        try {
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
        messageValue.setText(R.string.stopButtonText);// changes the hello world text
            readNoRead=false;
        }
}


text:
Q: Join two table and then search for the match I have two table named security_questions and login. Columns in login tables are:
Username, Security_QA_ID, Security_Answer, Security_Attempts,Last_Login,Password_Attempts

where security_questions have:
ID, Name

where Security_QA_ID is referenced with ID
CREATE DEFINER=`satish`@`%` PROCEDURE `p_chkAnswer`(
IN sq VARCHAR(75),
IN sa VARCHAR(20) ,
IN uname VARCHAR(15) ,
out msg INT
)
BEGIN
select (COUNT(*) > 0) INTO @result from login join security_questions on Security_QA_ID = ID where User_Name=uname and Name=sq and Security_Answer=sa;
set msg = @result;
if @result = 1 Then
UPDATE login SET  Last_Login=now(),Password_Attempts=0 where User_Name=uname;
else
UPDATE login SET  Security_Attempts=Security_Attempts+1 where User_Name=uname;
End if;

END

but in every time only else part get executes. thanks in advance

A: Your code is quite confusing and hard to read (for me at least), I simplified your statement into a single SELECT so that I can check if your select is correct, and it appears to be correct:
CREATE TABLE `login`
 ( User_Name text,
   Security_QA_ID int(11),
   Security_Answer text,
   Security_Attempts datetime,
   Last_Login datetime,
   Password_Attempts int(11)
 );

CREATE TABLE `security_questions`
 (ID int(11),
  Name text
  );

INSERT INTO login SET
 User_name = 'a',
 Security_QA_ID = 1,
 Security_Answer = 'c',
 Security_Attempts = NOW(),
 Last_Login = NOW(),
 Password_Attempts = 0;

INSERT INTO security_questions SET
 ID = 1,
 Name = 'b';

And the select
SELECT IF(COUNT(*) > 0, 1, 0) AS Authenticated
from (login)
LEFT join security_questions on Security_QA_ID = ID
where User_Name='a' and Name='b' and Security_Answer='c'

Do you have to use this DEFINER? wouldn't it be easier to write PHP/Perl/etc code to check for Authenticated as being non-zero?


text:
Q: Is heating plasma the only way to initiate fusion? I was looking at why fusion reactors need to get so hot and the internet said that it needed the momentum to overcome the repulsive forces of two atoms. Is heating the atoms the only way to give it enough momentum? Could we spin the two atoms In opposite directions instead and bring them close to let the angular momentum smash the two atoms into each other?

A:
Is heating the atoms the only way to give it enough momentum?

Oh no, in fact, this is among the hardest ways.
The very first fusion reactions were produced in a simple particle accelerator that fit in a small lab at Cambridge. This shot deuterium ions into a metal foil that had been infused with deuterium gas. Every once in a while one of the D's from the accelerator would hit one of the D's in the foil, and presto, fusion. This was way back in 1932.
Unfortunately, its trivially easy to demonstrate that the number of missed collisions is many orders of magnitude greater than the number of collisions, and the energy you spent accelerating those ions is thus orders of magnitude higher than what you get back out. In spite of several very clever attempts to get around this, no one's come close to a working accelerator-driven reactor.
Next, lets consider the H-bomb. These work through a combination of factors, but the main one is that they compress a tiny rod of plutonium in the core of the fusion fuel, the "spark plug" to ridiculous pressures. What was once sub-critical immediately goes super-mega-critical and the resulting blip of fission gives off a burst of neutrons.
These neutrons fly off in all directions through the surrounding fusion fuel. This is normally a dry fuel of lithium deuteride. When a neutron hits the lithium ions in the fuel, they turn into tritium. In the super-condensed state of the fuel, the chance that will impact a nearby deuteron is so high that they fuse, release another neutron, and so on.
So right off the bat, one way to get around the heating side is to simply compress the fuel. That heats it too, the fuel in the bomb is the equivalent of millions of degrees (ideal gas law here, nothing more) but it's the compression that's key. What you're trying to do is ensure that everything is so dense that various bits like neutrons and alphas don't have a chance to escape off the surface and carry away your energy. This is non-trivial.
Around 1960 Nuckolls suggested one could do this with a laser instead of a bomb. If you shine lasers all over the outside of a sphere, the "blowoff" compresses the interior, hopefully to the point where you get reactions. 60 years later we have NIF, and while it "works" in that it does indeed create fusion reactions without directly heating the fuel, it failed to reach the magic number called "ignition" that is required (in this design) to output net power.
Which brings us to heating. Recall that the idea behind the bomb is to keep everything inside the fuel. This is called the "confinement time" (which you might see confused with the amount of time a fuel keeps in the reactor, not the same thing at all). As density goes up, energy confinement improves and you need less outright heating to reach your magic number. As density goes down, its not like confinement suddenly disappears, but you do have to add more external heat to make up for the losses.
So something like ITER is at one end of a scale - it has VERY low density, "a very good vacume", and makes up for the constant energy loss through external heaters. On the other end of the scale is NIF, which has no external heating and lots of compressions (100 times the density of lead - think about that). There are any number of designs that live between those two extremes, like MAGLIF.


text:
Q: Restore default Windows 7 key bindings I recently inherited a work laptop from a previous employee. Unfortunately, the person changed all of the key bindings and most of the built-in bindings no longer work. How do I reset/restore the original bindings?

A: You can probably use SharpKeys to extract the required registry key from a Windows 7 installation which has not been messed around with and then import it to the one which has been customised.

A: This might be a different keyboard layout.
Go to Control Panel, Regional and Language Options, Keyboards, and check.


text: Q: How to make a last day column for each month when date is not given in power BI? I want to make a date column. For that I have a month and year column but not the day column. How do I make it in power BI?


text:
Q: Change row mouseover color of the GWT Grid when selected When a button is pressed, i change the background of a few rows in a Grid component, I've achieved it so far, but, when the user mouses over the selected row, it does not show the color that is set, how to change the color of the mouse over item to match the selected item color? Code here so far.
for(int i=0;i<grid.getStore().getCount();i++){
    Element row = (Element) grid.getView().getRow(i);
    row.getStyle().setProperty("backgroundColor", "#FFFFFF");
}
for(int item:items){
    Element row = (Element) grid.getView().getRow(item);
    row.getStyle().setProperty("backgroundColor", "#DFE8F6");
}

Changed as per the answer.
for(int i=0;i<grid.getStore().getCount();i++){
    Element row = (Element) grid.getView().getRow(i);
    row.getStyle().setProperty("backgroundColor", "#FFFFFF");
    row.removeClassName("ps-grid-selected-row");
}
Element row = (Element) grid.getView().getRow(indexItem);
row.getStyle().setProperty("backgroundColor", "#DFE8F6");
//              row.getStyle().setProperty("hover", "#DFE8F6");
row.addClassName("ps-grid-selected-row");

A: The easiest way to add a mouse over color to the row is through CSS.  In your CSS file, add an entry like this:
.selected-row:hover {
  background-color: #DFE8F6;
}

And back in your code, instead of setting the background color just add the CSS class:
for(int i=0;i<grid.getStore().getCount();i++){
  Element row = (Element) grid.getView().getRow(i);
  row.removeClassName( "selected-row" );
}
for(int item:items){
  Element row = (Element) grid.getView().getRow(item);
  row.addClassName( "selected-row" );
}

When you select the row, just add the selected-row classname and when it's not selected just remove the classname.  The CSS specifies that when the user hovers over the class selected-row, it will use the #DFE8F6 background color.


text:
Q: kafka-configs.sh + what is the configuration after retention.ms deletion on topic On the following kafka topic syntax
kafka-topics.sh  --zookeeper zookeeper:2181 --describe --topics-with-overrides

we get :
Topic: __consumer_offsets       PartitionCount: 50      ReplicationFactor: 3    Configs: compression.type=producer,cleanup.policy=compact,min.insync.replicas=3,segment.bytes=104857600,retention.ms=7200000

We can see that retention.ms=18000000   ( its means that retention in mili second is 5 hours )
now we removed the retention.ms configuration by the following kafka cli
kafka-configs.sh --zookeeper zookeeper:2181 --alter --entity-type topics --entity-name __consumer_offsets       --delete-config retention.ms

and therefore we get
kafka-topics.sh  --zookeeper zookeeper:2181 --describe --topics-with-overrides

Topic: __consumer_offsets       PartitionCount: 50      ReplicationFactor: 3    Configs: compression.type=producer,cleanup.policy=compact,min.insync.replicas=3,segment.bytes=104857600

As we can see above retention.ms was removed
Now my Question is

*

*After we removed the retention.ms , what should be the new retention ?  , is it means that kafka is looking now on kafka configuration file as - server.properties ?

*Second , what is the risks when we perform the kafka cli - kafka-configs.sh --zookeeper zookeeper:2181 --alter --entity-type topics --entity-name __consumer_offsets       --delete-config retention.ms

A: All topics have a retention, so there is no risk of removing the topic-override.
If the override is removed, then yes, it'll take the default, global retention from the broker server.properties
Note that you may see different values if you use --describe --bootstrap-servers kafka:9092


text:
Q: NgRx Call dispatch Action in Angular router guard will execute infinite loop Story:
Hi everyone. I am a newbies in use NgRx library. In my angular project I use router guard to prevent unauthenticated user to unauthenticated website.
My ideal is call an rest api to verify local storage token content. When rest api result is "success", before return of(true), do "store.dispatch(LoginSuccess)" to update login auth information in Store.
Problem:
When do dispatch action. The "LoginSuccess" action always execute infinite loop even setting { dispatch: false } in @Effect(). After try and search by google solution for it. This problem always in my project.
Hope some friends on stackoverflow can give me some help.~ thank you.
part of codes:

auth.guard.ts

.....
....
canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    const authData: {email: string, token: string} = JSON.parse(
          String(localStorage.getItem('User')));

    const authToken = authData && authData.token;

    // loginServ is a REST API for verify token
    return this.loginServ.VerifyToken(authToken).pipe(
      concatMap((res: AuthResult) => {
        if (res.result === 'success') {

          this.store.dispatch(LoginSuccess({
            isAuthenticated: true,
            email: authData && authData.email,
            token: authToken,
            result: 'success',
            message: 'success'
          }));  // <-- execute action infinite.

          return of(true);
        } else {

          this.store.dispatch(LoginFailed({
            isAuthenticated: false,
            email: authData && authData.email,
            token: authToken,
            result: 'failed',
            message: 'token illegal'
          }));

          localStorage.removeItem('User');
          this.router.navigate(['']);
          return of(false);
        }
      })
    );
...
...

action.ts:

...
export const LoginSuccess = createAction(
  '[auth] Login Success',
  props<{
    isAuthenticated: boolean,
    email: string,
    token: string,
    result: string,
    message: string,
  }>()
);
....
...

reducer.ts

....
....
export const loginReducer = createReducer(
  defaultState,

  on(Login),

  on(LoginSuccess, (state, userInfo) => {
    console.log(state);     // <-- for debug.
    console.log(userInfo);  // <-- for debug.
    return {
      ...state,
      ...userInfo
    };
  }),

  on(LoginFailed, (state, result) => {
    return {
      ...state,
      ...result
    };
  }),
....
...

effect.ts

....
...
loginSuccess = createEffect(() => this.actions$
  .pipe(
    ofType(LoginSuccess),
    map((user: any) => {

      console.log(user);
      const beStoreInfo = {
        email: user.email,
        token: user.token,
      };

      localStorage.setItem(
        'User',
        JSON.stringify(beStoreInfo));
        return {
          type: '[auth] Login Success',
          isAuthenticated: true,
          email: user.email,
          token: user.token,
          result: user.result,
          message: user.message
        };
    }),
  ), {dispatch: false});
....
...

service_overview-routing.module.ts

....
// using lazy loading module
const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    component: ServiceOverviewComponent},
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class ServiceOverviewRoutingModule { }
....

app-routing.module.ts

Using lazy load module.
....
...
const routes: Routes = [
  { path: 'login', loadChildren: () => import('./login/login.module')
    .then(m => m.LoginModule)},
  { path: 'register', loadChildren: () => import('./register/register.module')
    .then(m => m.RegisterModule)},
  { path: 'service_overview', loadChildren: () => import('./service-overview/service-overview.module')
    .then(m => m.ServiceOverviewModule)},
  { path: '', redirectTo: 'login', pathMatch: 'full' }
];
....

Environment:
Angular Cli: 8.0.3
NgRx Store/Effect: 8.0.1
OS: Ubuntu 18.04
..Thanks

A: Your login success effect returns another login success action resulting into infinite loop.
loginSuccess = createEffect(() => this.actions$
  .pipe(
    ofType(LoginSuccess),
    map((user: any) => {

      console.log(user);
      const beStoreInfo = {
        email: user.email,
        token: user.token,
      };

      localStorage.setItem(
        'User',
        JSON.stringify(beStoreInfo));
        // remove this ⬇
        return {
          type: '[auth] Login Success',
          isAuthenticated: true,
          email: user.email,
          token: user.token,
          result: user.result,
          message: user.message
        };
        // end remove this ⬆
    }),
  ), {dispatch: false});


text:
Q: Error:unresolved external symbol _popen Why does using popen result in Error: Failed to close command stream under windows?

A: You actually have to use: _popen and _pclose  (yes WITH the silly underscore) under Windows.
See MSDN Entry on it; it has a nice example
Now as for _popening "ps" you know whether or not you have a ps on your system.


text:
Q: Need to synchronize stepper motors am using two A4988 drivers to control two NEMA 17 stepper motors with 1.8 degree full step resolution on Rpi 2b. I am using them as wheels. The motors are initially given ramp signal using PGPIO wave_chain function and then a steady PWM signal using the SET_PWM function in PGPIO library.
The ramp and pwm are defined each wheel and are called together but the problem is the wheels turn one after the other and not synchronously.
pWhich wheel turns first depends on which wheels function is executed first. Please help me to resolve the issue

A: It is known that whichever wheel function is called first, moves first. This implies a delay in returning from the execution of the wheel function.
Either

*

*try to remove delay from the code.

*Write a forward function which activates each one at a time

*Use a separate own signal tied to both stepper controllers.

Do you need complete independent control of both wheels?
Thinking one own for driving both and one for driving one for steering.

A: If it is possible to drive both motors from the same driver with adequate current limit, they will stay in sync.  I have done that successfully with an XY gantry with two X motors on belts at high speeds and optical home recal only needed on one side each for XY over 1m square gantry that can race around all corners in a couple seconds and end up in same home position. Using an Uno with gcode file and CNC shield with Gcode Panel (Win) to USB on Uno).
Ramping step rate depends on available excess torque so drag and inertia will define your max. acceleration and braking constant.

A: The problem is that a Raspberry runs a kernel (linux) and you do not have direct access to the IO nor have full CPU process.
This results to a undefined, variable random delay to your IO access and is not easy to solve on a Raspberry.
If your raspberry has several CPU Core, you can reserve one core to a specific task, so you won't have kernel task switch over and you can then control your timings. You probably also would need some kernel level drivers to access the IO directly from your separate core, if that is possible. All this is not an easy feat.
The easier method would be to control your PWM with an Arduino, and connect the arduino to the raspberry through SPI/I2C, this approach will be much simpler and you will be able to accurately control and synchronize your PWM and the motor.
Here a link for motor drive system with arduino.


text:
Q: How to simulate blocking dialog on Android? First of all: I'd like to point out that I understand that is fundamentally against Androids design to use blocking dialogs but I have to do this thing and I don't know how to. And what it really comes down to is "simulating" a blocking dialog.
My program needs to fire a chain of events (essentially call one or more of a group of functions) that in certain conditions will require user input and cannot complete the function call util it gets the user choice. It may require it anywhere from 1 to N times. Or, as I said, not at all. This is a game, just so you know, and instructions on what the program needs to do (and consequently if the user needs to make a decision or not) are obtained by parsing a sequence of strings which are different commands.
With blocking dialogs this would be trivial. Hoewever I have no idea how to accomplish this behaviour in Android. Can any one give me any clues as to how to do this?
Thank you very much for any answers.

A: First, there are better UI designs than this, such as a wizard with 1-N pages, where you skip the wizard in cases where it is not needed. This will be much more natural for the user, make it easier to move backwards and forwards through the series of steps, etc. It will also be easier to code than a series of 1-N dialogs, given existing wizard frameworks.
But, let's assume for the moment that an evil supervillian is holding the citizen of Major City hostage, unless you implement a series of 1-N dialogs.
Implementing this chain of dialogs does not require blocking dialogs. Show the next (or previous) dialog based upon the accept/cancel events from the current dialog, using an object to maintain your ongoing state.

in certain conditions will require user input and cannot complete the function call util it gets the user choice

That is not generally possible. Event-driven programming has been around for a couple of decades; the Android framework assumes that developers know how to implement event-driven programming.

Hoewever I have no idea how to accomplish this behaviour in Android

Android does not support blocking dialogs, as you have discovered.

However as I am simply doing an application on my free time as a hobbie, it will be difficult to do as you suggested

You do not have much of a choice in the matter.


text:
Q: General purpose diode between 2 power rails I am looking at a schematic where there is a general purpose diode connected between the positive side of a 5V DC rail to the positive side of a 12 V DC rail.
The circuit is powered by a power supply that provides 12 & 5 V DC and these two input voltages are connected to a choke. The other side of the choke is where the diode connects the 5V to the 12V rail as seen in the picture.
What's the function of this diode?

A: It is there to protect IC's that require the 12V at all times that the 5V is present (possibly older memory ICs). If the 12V drops faster than the 5V supply on power down, you could have 5V still when the 12V bias is gone. This insures that if the 12V drops faster, it will not 'over-run' the 5V as they approach 0V. Some chips can be destroyed if the 12V is not turned on first or simultaneously with the 5V, and at power down, the 12V must stay above the 5V supply at all times. I assume the difference due to the .7V diode loss will not hurt the ICs.

A: there's probably a part in there there that will be broken if the 12V input is significantly less than the 5V input. the diode prevents this.


text:
Q: My pygame window displays a black screen everytime I run my project I wrote this code below and just get a black screen on my pygame window everytime I run my project on pycharm
I copied this code through a tutorial step by step and checked it but the teacher didn't seem to have this problem when running the code
import pygame
width = 500
height = 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")

clientNumber = 0

class Player():
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = (x, y, width, height)
        self.vel = 3

    def draw(self, win):
        pygame.draw.rect(win, self.color, self.rect)

    def move(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.x -= self.vel

        if keys[pygame.K_RIGHT]:
            self.x += self.vel

        if keys[pygame.K_UP]:
            self.y -= self.vel

        if keys[pygame.K_DOWN]:
            self.y += self.vel

        self.rect = (self.x, self.y, self.width, self.height)

def redrawWindow(win, player):
    win.fill((255, 255, 255))
    player.draw(win)
    pygame.display.update()

def main():
    run = True
    p = Player(50, 50, 100, 100, (0, 255, 0))
    clock = pygame.time.Clock()

    while run:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
    p.move()
    redrawWindow(win, p)

main()

A: Press tab before p.move() and redrawWindow(win, p) so they look like this
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            pygame.quit()
    p.move()
    redrawWindow(win, p)

They should be indented under while loop.


text:
Q: Is it possible to run my following code by parallel? Actually the following code is doing the gaussian elimination for a matrix. And my job is to try some java concurrency technique to let it be a parallel program.
However, the problem is that each external loop has the data dependency which comes from the previous loop. And I have try that it is too costly to use the parallel technique inside the external loop. Can someone help me with it? How to let the following code run by parallel? Is there any technique in java concurrency technique can handle with this condition?
    for (int i = 0; i <1; i++) {

        int max = i;
        for (int j = i + 1; j < N; j++) {
            if (Math.abs(matrix[j][i]) > Math.abs(matrix[max][i])) {
                max = j;
            }
        }

        double[] temp = matrix[i];
        matrix[i] = matrix[max];
        matrix[max] = temp;

        for (int k = i + 1; k < N; k++)
        {
            double alpha = matrix[k][i] / matrix[i][i];
            for (int j = i; j < N; j++)
            {
                matrix[k][j] -= alpha * matrix[i][j];
            }
        }
    }

A: The work done by the k loop can be made parallel, since the modified data is non-overlapping.
Simply delegate the work done by the body of the loop to a thread.
Easiest way is to use a Java 8 parallel stream, i.e. replace the k loop with:
final int ii = i; // since 'i' is not effectively-final
IntStream.range(ii + 1, N).parallel().forEach(k -> {
    double alpha = matrix[k][ii] / matrix[ii][ii];
    for (int j = ii; j < N; j++) {
        matrix[k][j] -= alpha * matrix[ii][j];
    }
});


text:
Q: pic versus macro in TikZ Consider this code in the TikZ - PGF manual, which uses a macro
% Main code from
% The TikZ - PGF manual
%   Author: Till Tantau et al
%   Version 3.1.3, released May 9, 2019
%   Page 40
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
    \def\rectanglepath{-- ++(1cm,0cm) -- ++(0cm,1cm) -- ++(-1cm,0cm) -- cycle}
    \draw (0,0) \rectanglepath;
    \draw (1.5,0) \rectanglepath;
\end{tikzpicture}
\end{document}

and this one written by me, which uses pic
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
[rectanglepath/.pic={\draw (0,0)--++(1cm,0cm)--++(0cm,1cm)--++(-1cm,0cm)--cycle;}]
    \pic at (0,0) {rectanglepath};
    \pic at (1.5,0) {rectanglepath};
\end{tikzpicture}
\end{document}

Both give us the same output

Observation
Both give the same output. I prefer the latter one, as it is more "TikZ-ish". However, we can always change a code from pic to macro and vice versa, as above (am I wrong – is there a case in which we can't convert?), or draw the same figure using two different codes (this and this for example).
Also, I can't see any aspects in which macros are better than pic. Even arguments: we can also have pic with up to nine arguments with any pattern using /.style args.
In the PGF manual, sometimes I see pic is used, but sometimes a macro is used (it is even used in the title page!). From those examples, I can't figure out in what case I should use a macro and in what case I should use a pic.
Question
It may be quite clear by now.

If I have to draw the same "sub-"picture many times in a TikZ picture, should I use a pic or a macro? And why? Is there any cases in which I must use this one and not the other?

Thanks in advance.

Edit
As for @marmot's nice codes, I have written myself some code (against it) which uses macros
\documentclass{article}
\usepackage{tikz}
\begin{document}
\subsection*{Macros can have more complicated constructions}

\begin{tikzpicture}%[rectanglepath/.pic={\draw (-0.5,-0.5) rectangle ++(1,1);
%\draw[red] (-0.5,0.5) -- (0.5,-0.5);}]
\newcommand\rectanglepath[2][]{\scope[shift={(#2)},#1]\draw (-0.5,-0.5) rectangle ++(1,1);
                                \draw[red] (-0.5,0.5) -- (0.5,-0.5);\endscope}
%\path (0,0) pic{rectanglepath} (2,0) pic[dashed]{rectanglepath};
\rectanglepath{0,0}
\rectanglepath[dashed]{2,0}
\end{tikzpicture}

\subsection*{Macros can have names}

\begin{tikzpicture}%[rectanglepath/.pic={\draw (-0.5,-0.5) rectangle ++(1,1);
%\draw[red] (-0.5,0.5) coordinate(-tl)  -- (0.5,-0.5) coordinate(-br) ;}]
\newcommand\rectanglepath[3][]{\scope[shift={(#2)},#1]\draw (-0.5,-0.5) rectangle ++(1,1);
                                \draw[red] (-0.5,0.5) coordinate (#3-tl)
                                    -- (0.5,-0.5) coordinate (#3-br);\endscope}
%\path (0,0) pic (A) {rectanglepath} (2,0) pic[dashed] (B) {rectanglepath};
\rectanglepath{0,0}{A}
\rectanglepath[dashed]{2,0}{B}
\draw (A-tl) to[out=30,in=150] (B-tl) (A-br) to[out=-30,in=-150] (B-br);
\end{tikzpicture}

\subsection*{Transformations are much more intuitive on macros}

\begin{tikzpicture}[rectanglepath/.pic={\draw (-0.5,-0.5) rectangle ++(1,1);}]
\newcommand\rectanglepath[2][]
    {\scope[shift={(#2)},#1]\draw (-0.5,-0.5) rectangle ++(1,1);\endscope}
%\path (0,0) pic[rotate=45]{rectanglepath} (2,0) pic[dashed,rotate=-30]{rectanglepath}
%(4,0) pic[thick,xscale=0.5]{rectanglepath};
\rectanglepath[rotate=45]{0,0}
\rectanglepath[rotate=-30,dashed]{2,0}
\rectanglepath[thick,xscale=0.5]{4,0}
\end{tikzpicture}
\end{document}

A: Here are threefour examples of things that are much harder to achieve in the macro approach. The first three examples have been translated to macros in the revised question.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\subsection*{Pics can have more complicated constructions}
\tikzset{rectanglepath/.pic={\draw (-0.5,-0.5) rectangle ++(1,1);
\draw[red] (-0.5,0.5) coordinate(-tl)  -- (0.5,-0.5) coordinate(-br) ;}}

\begin{tikzpicture}
\path (0,0) pic{rectanglepath} (2,0) pic[dashed]{rectanglepath};
\end{tikzpicture}

\subsection*{Pics can have names}

\begin{tikzpicture}
\path (0,0) pic (A) {rectanglepath} (2,0) pic[dashed] (B) {rectanglepath};
\draw (A-tl) to[out=30,in=150] (B-tl) (A-br) to[out=-30,in=-150] (B-br);
\end{tikzpicture}

\subsection*{Transformations are much more intuitive on pics}

\begin{tikzpicture}
\path (0,0) pic[rotate=45]{rectanglepath} (2,0) pic[dashed,rotate=-30]{rectanglepath}
(4,0) pic[thick,xscale=0.5]{rectanglepath};
\end{tikzpicture}

\subsection*{You can insert pics in paths}

\begin{tikzpicture}[xboard/.style={insert path={
(0,0) grid (#1,#1)
foreach \X in {1,...,#1}
{(\X-0.5,\X-0.5) pic{rectanglepath} (\X-0.5,#1-\X+0.5) pic[rotate=90]{rectanglepath}}}}]
\draw[xboard=1,xshift=2cm,xboard=3,xshift=4cm,xboard=5];
\end{tikzpicture}

\end{document}

My personal take: pics win, at least in the above-described scenarios. IMHO the translated macros in the revised question substantiate this.
Notice that "behind the scenes" pics are macros at some level. So you will always be able to reproduce the outcome of a pic with a macro. However, the effort will be more substantial. And yes, if you are in the mood to do some unnecessary extra work, you can use macros instead of pics. So, yes, the choice can depend on the mood of the day.
Let me also stress that there are scenarios in which pics perform worse. An example of this type may be a life wheel.
BTW, there is also the insert path option that is sometimes preferable over pics IMO.