text:
Q: Arrays and global variables I'm trying to handle a global variable (matrix[]).
My first question is: What is an array with two indexes ([x][x]) called?
My second question is: In initialize(); I am trying to assign every element in matrix[] to a 'O', but it doesn't seem to work.
#include <stdio.h>

char matrix[4][10];

void initialize()
{
    matrix[4][10] = {{'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                     {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                     {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                     {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'}};

}

int main(void)
{

}

This code gives me the following error:
error: cannot convert '<brace-enclosed initializer list>' to 'char' in assignment

A: It's called 2 dimensional array.
You can use = {...}; initialisation only in the same line where you declare an array. So
char matrix[4][10] = {{....}};

will work, but
char matrix[4][10];
matrix = {{...}};

will not.
You should use loops if you want to fill your array in some function:
for (int i = 0; i < 4; i++)
    for (int j = 0; j < 10; j++)
        matrix[i][j] = 0;

And you left main function empty so initialise function will be never called.

A: No need for initialize here, just initialize the variable at the point of definition:
char matrix[4][10] = {{'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                      {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                      {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'},
                      {'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O'}};

A: *

*call function Initialize() from main.

*matrix[4][10] is a single character. you can't initialize as like what you did in your function.
Either do it by using loop and memset()
or
Use two loops.

A: You can try below code to initialize variable size matrix M x N at runtime,
int **Create(int M , int N) // `M` & `N` are dimensions of the matrix
{
    int **a, i, j;
    a = (int **)malloc(M * sizeof(int *));   // Create array of pointers

    for (i = 0; i <= M-1; i++) // Create `M` rows, there addresses are stored in array
         a[i] = (int *)malloc(N * sizeof(int));
    return a; // return address of the matrix
 }

Once matrix is created we can initialize the elements as below,
for(i = 0; i <= row - 1; i++)
  for(j = 0; j <= col - 1; j++)
     scanf("%d", &a[i][j]);   // Read a[i][j]


text:
Q: Set Variables like current_user in Application Controller I have the following Base Controller for Brands Scope
class Brand::ApplicationController < ApplicationController
  before_action :authenticate_brands_member!
  before_action :current_company
  helper_method :current_company

  private

  def current_company
    current_brands_member? current_brands_member.company : nil
  end

end

The variable current_brands_member is the device model for authentication for members. Each Member belongs to a Company
members(id, name, company_id,...)
companies(id, name, ....)
brands(id, name, company_id,...)

Since i will be traversing through members to companies to brands i want to set a common variable current_company which will have the content of the member's company when required in the controllers and views.
When i try to access the same in the controller like this
class Brands::MembersController < Brand::ApplicationController
  def index
    puts current_company.inspect
  end
end

Am getting the following error
undefined local variable or method `current_company' for #<Brands::MembersController:0x007f90c34a8138>

A: You can't access private methods from outside the class itself. Remove the private instruction or move the method outside of it.

A: Hmm, it looks perfectly ok to me.
But there is one thing. In your code in Brand::AppController you have a syntax error:
def current_company
  # mind the missing space before question mark
  current_brands_member? current_brands_member.company : nil

  # it should be:
  # current_brands_member ? current_brands_member.company : nil

  # or even simpler
  # current_brands_member.try(:company)
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Applying a dependency to a service in icinga2 We are using icinga2 for monitoring. We have a lot service checks which are applied dynamically through apply rules.  Additionally, these are services applied to a hashmap of database instances which are on various hosts.  The long and the short of it is that our service names are determined dynamically so one might be, for example HOST!DBNAME-svcvheck.
So the scenario is that most of these services depend on a database is up, e.g., `HOST!DBNAME-tnsping".  Unfortunately, the documentation examples are fairly simple and don't include dynamically creating a parent service reference.  What I think I want to do is something like this:
apply Dependency "db-connectivity" to Service {
  parent_service_name = "$host.name$!$service.vars.envname$-tnsping"
  # also tried variants of this, e.g.
  # parent_service_name = host.name + "!" + service.vars.envname + "-tnsping"
  child_service_name = service.name
  child_host_name = host.name
  disable_checks = true
  assign where "oracle-db-svc" in service.templates
}

The host doesn't really matter in my case because the dependencies are only the services but the child_host_name is a required field.
No matter what I do I can't seem to get it to recognize the parent service.  For example:
Error: Dependency 'scan-szepdb041x.myhost.org!UAT2-beqfilelast!db-connectivity' references a parent host/service which doesn't exist.

The rules for referencing other object variables while applying a Dependency seem a bit different from applying a Service.
Does anyone have any ideas or examples of dynamically apply service dependencies to services which were generated dynamically?

A: you probably have to loop over existing hosts and see if they match. Then you define dependency inside of a loop.
I had a similar example for dynamically generating disk checks. If i find it, i'll post it here in a few days.
Not sure if that is possible with dependencies, but I'll see.
edit: see if somethig like that will be enough to get you started:
for (server in get_objects(Host)) {
        if (match("somename*", server.name)) {
                apply Dependency "db-connectivity" + server.name to Service use (server) {
                        parent_service_name = server.name + service.vars.envvname + "-tnsping"
                        child_service_name = service.name
                        child_host_name = host.name
                        disable_checks = true
                        assign where "oracle-db-svc" in service.templates
                }
        }

}


text:
Q: OpenCL's enqueueWriteBuffer causes __memcpy_sse2_unaligned segmentation fault I have the following OpenCL code, using the C++ Wrapper and Intel's OpenCL toolkit:
#include <Eigen/StdVector>

...

typedef Sample_t float
typedef std::vector<Sample_t, Eigen::aligned_allocator<Sample_t> > SampleArray;

...

SampleArray data(ns * nt);

...

mdata = cl::Buffer(context, CL_MEM_READ_ONLY, sizeof(Sample_t) * data.size());
queue.enqueueWriteBuffer(mdata, CL_FALSE, 0, sizeof(Sample_t) * data.size(), &data[0]);

When it is compiled with -O3, march=native and mtune=native flag, it causes the following segmentation fault coming from TBB code:

__memcpy_sse2_unaligned() at memcpy-sse2-unaligned.S:116 0x7ffff6e64ba4

Without any optimizations, the program runs fine.
I traced the problem to the queue.enqueueWriteBuffer call, without it I have no problems whatsoever.
I have tried to comment out portions of the code that modify the variable "data", in case I was accessing invalid memory positions, but the problem persists.
If I remove the aligned_allocator from the std::vector, the build without optimizations also starts to break.
In total I have 70MB that I'm trying to store in this buffer, far less than the 3.8GB reported by CL_DEVICE_MAX_MEM_ALLOC_SIZE. But if I reduce the size of the array, the problem stops. The size that I tried in this later case was 5.
I also decided to print the address allocated by the vector and it is 0x7f21b797f010, so it is aligned to at least 16 bytes.
EDIT: Regarding multithreading, the creation of the array, as well as the OpenCL operations happen in the same method, and in the main thread. The command queue was not created with asynchonous flags, and there is a flush() operation after the buffer write.
What could be the problem?
Thank you

A: As confirmed in the conversation in comments, the problem here is that the enqueueWriteBuffer() operation is non-blocking (CL_FALSE passed as the blocking argument) and that the source buffer (SampleArray vector) goes out of scope before the underlying copy operation is guaranteed to have completed.
There are at least 4 possible solutions:

*

*Use the blocking form of enqueueWriteBuffer(). As the documentation indicates, the source buffer will not be accessed once the function returns in that case.

*Capture the returned event and call clWaitForEvents() or call clFinish() before the SampleArray() goes out of scope. This is only really preferable to the blocking variant if your program is doing anything substantial in the interim.

*Keep the source data around for long enough.

*Don't use the copying form of enqueueWriteBuffer(): create a buffer with a NULL source, map it into your application's memory space, write the data to it, then unmap it. This potentially avoids copying altogether, at least on integrated GPUs/APUs)

These are roughly in increasing order of parallelism/efficiency.


text:
Q: issues with executing cablint-ct part of certlint tool I am attempting to run the tool certlint, specifically the module called cablint-ct but when we try we get errors. There are three modules, certlint, cablint and cablint-ct -- all of which work except for cablint-ct.
Here is the command I am running in ruby:
ruby -I "/certlint-master/lib" "/certlint-master/bin/cablint-ct" "cert.der"

Here is the error I receive:
/certlint-master/lib/certlint/ct.rb:149:in `initialize': undefined method `+' for nil:NilClass (NoMethodError)
from /certlint-master/bin/cablint-ct:39:in `new'
from /certlint-master/bin/cablint-ct:39:in `<main>'

Here is the referring block of code in ct.rb (line 39):
30      def initialize(tbs_der)
31        asn = OpenSSL::ASN1.decode(tbs_der)
32        # tbsCertificate.version is optional, so we don't have a fixed
33        # offset. Check if the first item is a pure ASN1Data, which
34        # is a strong hint that it is an EXPLICIT wrapper for the first
35        # element in the struct.  If so, this is the version, so everything
36        # is offset by one.
37        skip = asn.value[0].instance_of?(OpenSSL::ASN1::ASN1Data) ? 1 : 0
38        sig_alg_der = asn.value[1 + skip].to_der
39        @raw = OpenSSL::ASN1::Sequence.new([tbs_der, sig_alg_der, DER_SIG]).to_der
40        super(@raw)
41      end
42    end

and ct.rb (line 149)
148    def initialize(log)
149      @log = URI.parse(log + '/').normalize
150    end

I've opened an issue #37 on github with the owner of the tool but have not seen a response as of yet.
Will be grateful if someone can see if i am doing something wrong with my command or is there a coding issue somewhere?

UPDATE 1
I have figured that I need to be passing a URL into the command rather then a cert file. For example:
ruby -I "/certlint-master/lib" "/certlint-master/bin/cablint-ct" "https://ct.ws.symantec.com/ct/v1/get-entries?start=932966&end=932966"

I believe the code expect a JSON response from this URL and this link returns a file with JSON data, however, I get the following error:
/usr/share/ruby/json/common.rb:155:in `initialize': A JSON text must at least contain two octets! (JSON::ParserError)
    from /usr/share/ruby/json/common.rb:155:in `new'
    from /usr/share/ruby/json/common.rb:155:in `parse'
    from /certlint-master/lib/certlint/ct.rb:184:in `_call'
    from /certlint-master/lib/certlint/ct.rb:160:in `get_entries'
    from /certlint-master/bin/cablint-ct:40:in `<main>'

Any ideas?

A: resolved, the command expects a known ct log url and index id e.g.
ruby -I "/certlint-master/lib" "/certlint-master/bin/cablint-ct" "https://ct.ws.symantec.com" 173977
or
ruby -I "/certlint-master/lib" "/certlint-master/bin/cablint-ct" "symantec" 173977


text:
Q: Как передать что-то в конструктор в middleware Есть middleware в конструктор которого хочу передать определенный параметр, что бы явно внедрять зависимость и не делать что-то типо того:
public function __construct()
    {
        $this->default_ref = config('TEST_CONFIG', 'http://test');
    }

а выполнить что-то типо того
public function __construct($default_ref)
{
    $this->default_ref = $default_ref;
}

Буду благодарен за подсказку как я это могу сделать

A: Как бы это правильно пояснить...
При вызове посредников (middleware) выполняется метод handle (если его не переопределять). Посредники явно не создаются, поэтому конструктор по сути не задействуется. Но в него можно включать зависимости и они заинжектятся (это чтобы в handle не писать new SomeClass())
А теперь о возможности передачи параметров. Из документации. Их можно передать в метод hadle. Делается это через : и разделяются параметры запятыми
Route::put('/post/{id}', function ($id) {
    //
})->middleware('role:editor');

и в самом посреднике
public function handle($request, Closure $next, $role)
{
    if (! $request->user()->hasRole($role)) {
        // Redirect...
    }

    return $next($request);
}

Если смотреть на Ваш вопрос, то вы можете передать параметр (главное, чтобы это была строка, которая не содержит запятых)
Route::put('/post/{id}', function ($id) {
    //
})->middleware('redirect:' . $default_ref);


text:
Q: Drawing horizontal lines parallel to x axis using highcharts.js Below is the fiddle for a Pareto chart. I want to draw a horizontal line parallel to the x-axis which spans from left to right and ends at the 80% mark on the y-axis. I want to do this always while plotting a Pareto chart.
Can you let me know if there's a way to do this dynamically?

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column',
        borderWidth:1,
        borderColor:'#ccc',
        marginLeft:110,
        marginRight:50,
        //backgroundColor:'#eee',
        //plotBackgroundColor:'#fff',
    },
    title:{
        text:'Pareto Test 1'
    },
    legend:{

    },
    tooltip:{
        formatter:function(){
                if(this.series.name == 'Line'){
                    var pcnt = Highcharts.numberFormat((this.y / 415 * 100),0,'.');
                    return pcnt + '%';
                }
                return this.y;
            }
    },
    plotOptions: {
        series: {
            shadow:false,
        }
    },
    xAxis:{
        categories:['A','B','C','D','E','F','G','H'],
        lineColor:'#999',
        lineWidth:1,
        tickColor:'#666',
        tickLength:3,
        title:{
            text:'X Axis Title',
            style:{
                color:'#000'
            }

        }
    },
    yAxis:[{
        min:0,
        //endOnTick:false,
        //lineColor:'#999',
        lineWidth:1,
        //tickColor:'#666',
        //tickWidth:1,
        //tickLength:3,
        //gridLineColor:'#ddd',
       /* title:{
            text:'Y Axis Title',
            rotation:0,
            margin:50,
            style:{
                color:'#000'
            }
        }*/
    },{
        title:{text:''},
        //alignTicks:false,
        gridLineWidth:0,
        lineColor:'#999',
        lineWidth:1,
        tickColor:'#666',
        tickWidth:1,
        tickLength:3,
        tickInterval:415 / 20,
        endOnTick:false,
        opposite:true,
        linkedTo:0,
        labels:{
            formatter:function(){
                var pcnt = Highcharts.numberFormat((this.value / 415 * 100),0,'.');
                return pcnt + '%';
            }
        }
    }],
    series: [{
        //yAxis:0,
        data: [115,75,60,55,45,30,20,15],
    },{
        type:'line',
        name:'Line',
        //yAxis:0,
        data: [115,190,250,305,350,380,400,415],
    }]
});

A: What you want to look at is a plot line:
http://api.highcharts.com/highcharts#yAxis.plotLines
{{EDIT:
Also, look here for slightly improved way of getting the data sum dynamically:
Highcharts percentage of total for simple bar chart

A: You can set this up the same way you calculated what 80% is. See the Fiddle below. Here is some sample code to add plotLines:
plotLines: [{
            color: '#FF0000',
            width: 2,
            value: .80 * 415 // Need to set this probably as a var.
        }]

var chart = new Highcharts.Chart({
  chart: {
    renderTo: 'container',
    defaultSeriesType: 'column',
    borderWidth: 1,
    borderColor: '#ccc',
    marginLeft: 110,
    marginRight: 50,
    //backgroundColor:'#eee',
    //plotBackgroundColor:'#fff',
  },
  title: {
    text: 'Pareto Test 1'
  },
  legend: {

  },
  tooltip: {
    formatter: function() {
      if (this.series.name == 'Line') {
        var pcnt = Highcharts.numberFormat((this.y / 415 * 100), 0, '.');
        return pcnt + '%';
      }
      return this.y;
    }
  },
  plotOptions: {
    series: {
      shadow: false,
    }
  },
  xAxis: {
    categories: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
    lineColor: '#999',
    lineWidth: 1,
    tickColor: '#666',
    tickLength: 3,
    title: {
      text: 'X Axis Title',
      style: {
        color: '#000'
      }

    }
  },
  yAxis: [{
    min: 0,
    //endOnTick:false,
    //lineColor:'#999',
    lineWidth: 1
      //tickColor:'#666',
      //tickWidth:1,
      //tickLength:3,
      //gridLineColor:'#ddd',
      /* title:{
          text:'Y Axis Title',
          rotation:0,
          margin:50,
          style:{
              color:'#000'
          }
      }*/
  }, {
    title: {
      text: ''
    },
    //alignTicks:false,
    gridLineWidth: 0,
    lineColor: '#999',
    lineWidth: 1,
    tickColor: '#666',
    tickWidth: 1,
    tickLength: 3,
    tickInterval: 415 / 20,
    endOnTick: false,
    opposite: true,
    linkedTo: 0,
    labels: {
      formatter: function() {
        var pcnt = Highcharts.numberFormat((this.value / 415 * 100), 0, '.');
        return pcnt + '%';
      }
    },
    plotLines: [{
      color: '#FF0000',
      width: 2,
      value: .80 * 415 // Need to set this probably as a var.
    }]
  }],
  series: [{
    //yAxis:0,
    data: [115, 75, 60, 55, 45, 30, 20, 15]
  }, {
    type: 'line',
    name: 'Line',
    //yAxis:0,
    data: [115, 190, 250, 305, 350, 380, 400, 415]
  }]
});


text:
Q: How to select all from table where concat is user ids I want to select all from specific rows usin concat but my syntax fails without an error.
Here's what's I've done.
mysqli($con, "SELECT *
              FROM table
              WHERE uid = CONCAT (8, '', 7, '', 1)")
              or die(mysqli_error($con));.

How do I select only from those ids with concat?

A: *

*what is mysqli? It should be variable $mysqli

*you don´t call query, so $mysqli->query

*I think you´re looking for IN instead of CONCAT, so ... WHERE uid IN (8, 7, 1)

A: mysqli_query($conn, "SELECT * FROM table WHERE uid IN (8,7,1)");

A: CONCAT can take only two parameters as input. in your SQL 5 parameters are passed as arguments to CONCAT try using the below query it may work
SELECT * FROM table WHERE    uid = CONCAT(CONCAT(CONCAT(CONCAT (8, ''), 7), ''), 1)


text:
Q: Load a local Json file and store it in a variable using Javascript I created a small app that saves me data in a JSON file! Since it's all local I don't need node.js and backend technologies. After a series of functions, a JSON file is saved locally with Blob.
How do I create an event that will import this file by choosing it from the filesystem of the computer?
If I write at the top of the listing import data from './data.json'; it works! I'd rather rather have the option of being able to upload the file from anywhere on the filesystem.
this allows me to save the file where I want:
 let file = new Blob([fileJSON], {type: 'application/json'});
     let a = document.createElement("a");
     a.href = URL.createObjectURL(file);
     a.download = file;
     a.click();

how do I load it by going to choose the path every time?
loadDatas=()=>{
  const dataJ = //something that allows me to go and choose the json file from my computer wherever it is

const parseIt = $.parseJSON(dataJ);
    // do something
}

A: You could try codes below:
constructor(props){
    super(props)
    this.state={
         file:null
    }
    this.inputRef = React.createRef()
}

openFileLoadingDialog = () => {
    this.inputRef.current.click()
}

readURL=(e)=>{
    let file = URL.createObjectURL(e.target.files[0])
    if(this.state.file !== file)
    {
        this.setState({
            file : file
        })
    }
}

render(){

     return(
         <div>
             <input type="file" style={{display:"none"}} ref={this.inputRef} onChange={this.readURL}/>
             <input type="button" value="open file" onClick={this.openFileLoadingDialog} />
         </div>
     )
}


text:
Q: Breadcrumb trail shows incorrect trail? Why the following code would cause my breadcrumb trail to show the same post link in the breadcrumbs no matter what page you are on in the site?
I have been stuck on this issue for ages now and just cannot figure it out...
See what I mean here.

    <?php
        global $post;
            $category_id = get_cat_ID('stories');
            $args = array( 'numberposts' => 9, 'offset'=> 0, 'category'=> $category_id );
            $myposts = get_posts( $args );
        foreach( $myposts as $post ) : setup_postdata($post); ?>

                      <?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
                    <a href="<?php the_permalink(); ?>">
                    <?php the_post_thumbnail(array(64,64)); // Declare pixel size you need inside the array ?>
                <?php endif; ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endforeach; ?>

A: Try to reset the postdata, like in this example from the Codex:

<?php
global $post;
$args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :
  setup_postdata($post); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endforeach;
wp_reset_postdata(); ?>


text:
Q: Add wilc3000 driver to Yocto raspberry pi I want to build my own yocto image for a raspberry (cm3). I use the meta-raspberry (dunfell) layer and poky dunfell-23.0.0.
For installing the microchip wilc3000 module I have to modify the kernel following this guide. In that way, I change the kernel conf (Kconfig) to add the mchp driver in the menu and later selecting it.
I have generated a patch to the kernel using this guide (Patch-based workflow). After generating the patch, I have modified and generated a new kernel config (defconfig). All the changes are applied in my own layer with this recipe (linux-raspberrypi_%.bbappend):
FILESEXTRAPATHS_prepend := "${THISDIR}/patchs:"

SRC_URI += "file://0001-Add-wilc3000-driver.patch \
            file://defconfig_my \
            "
PACKAGE_ARCH = "${MACHINE_ARCH}"

# PR="r2"

INTREE_DEFCONFIG_pn-linux-ti = "defconfig_my"

kmoddir = "/lib/modules/${KERNEL_VERSION}/kernel/drivers/net/wireless/mchp"

# do_configure_append() {
#     cat ${WORKDIR}/*.cfg >> ${B}/.config
# }

do_install_append() {
  install -d ${D}${kmoddir}
  install -m 0755 ${WORKDIR}/wilc-spi.ko ${D}${kmoddir}
}

FILES_${PN}_append += " \
  ${kmoddir}/wilc-spi.ko \
"

The patchs folder contains the patch for the kernel and the new kernel configuration generated
When I generate the image:
bitbake -v core-image-base

The generation fails in do_install task when it tries to copy wilc-spi.ko, which is not generated.
Which is the way to compile and deploy the kernel with my own configuration? if I download and compile the kernel in a separate folder, it successfully generates the wilc-spi.ko, but inside build folder in yocto there is no trace of the file generation.
Please, help me to add this driver to the kernel, Thanks a lot.

A: As @qschulz pointed out, the solution was to change defconfig_my to defconfig and remove all the extra code. Finally, the code looks like this:
FILESEXTRAPATHS_prepend := "${THISDIR}/patchs:"

SRC_URI += "file://0001-Add-wilc3000-driver.patch \
            file://defconfig \
            "
PACKAGE_ARCH = "${MACHINE_ARCH}"

PR="r3"

FILES_${PN}_append += " \
  ${kmoddir}/wilc-spi.ko \
"

KERNEL_MODULE_AUTOLOAD += "wilc-spi.ko"

And add in the layer.conf the instruction to load the module:
MACHINE_EXTRA_RDEPENDS += " kernel-module-wilc-spi "


text:
Q: Relations between the spin of representations of Lorentz group and Poincare group It is known that

*

*Finite dimensional irreducible representations of Lorentz group can be indexed by two half integers $(s_1,s_2)$ and the sum $s_1+s_2$ is called the spin.

*Infinite dimensional unitary irreducible representations of (the universal cover of) Poincare group can be indexed by two numbers $m$ and $s$, while the $s$ is also called spin.

*We can construct representations of Poincare group from those of Lorentz group.

My question is:

*

*Are all infinite-dimensional unitary irrps of Poincare group are constructed from finite-dimensional irreps of Lorentz group?

*Does the spin $s$ of the representation of Poincare group equal to $s_1+s_2$ if it is constructed from a $(s_1,s_2)$ irrp of Lorentz group?

For example:

*

*left-handed electron is a $(1/2,0)$ Lorentz representation. Does it induces a spin $1/2$ Poincare representation?

*Is a $(1/2,1/2)$ Lorentz representation induces a spin 1 Poincare representation?

A: First, note that while you can induce unitary representations of the Poincaré group from representations of the Lorentz group, they are not in general irreducible (although sometimes they are), and the various physical field equations (Dirac equation, Lorentz gauge condition) actually serve as projectors onto the irreps.
The irreducible unitary representations are actually constructed via Wigner's little group method. The construction is rather technical; you can read the full details in Figueroa O'Farril's (incomplete) notes which you can find here, which require familiarity with principal bundles. So to answer your questions:

*

*In the notes, it is stated on page 18 without proof that all unitary irreps are constructed in this manner. I unfortunately do not know the proof.

*First note that to obtain half-integer spin representations, you have to consider the double cover of the Poincaré group $\mathbb{R}^{(1,3)}\rtimes \text{SL}(2,\mathbb{C})$. The constructed representations will also be representations of $\text{SL}(2,\mathbb{C})$ as it is contained as a subgroup, so yes, the definition of spin will be the same. (What I'm saying is that the $(\frac{1}{2},0)$ representation is not actually an honest-to-goodness representation of the Lorentz group, but rather a projective one; but it is a representation of its double cover. This is the same situation as in the non-relativistic case with $\text{SU}(2)$ and $\text{SO}(3)$). A few comments:

*

*The $(0,0)$, $\left(\frac{1}{2},0\right)$ and $\left(0,\frac{1}{2}\right)$ representations induced by (the double cover of) the Lorentz group are irreducible, that is to say, they are also induced by the little group method.

*The spin $1$  massive $\left(\frac{1}{2},\frac{1}{2}\right)$ induced representation decomposes as a $3$-dimensional vector irrep $\oplus$ $1$-dimensional scalar irrep, both constructed under the little group method; the Lorentz gauge-like condition $\partial_\mu A^\mu=0$ serves as the projector onto the first one, while the second is just the $(0,0)$ irrep. The massless "spin" $1$ particles (i.e. photons) cannot be embedded in this representation (see below).

*The $\left(0,\frac{1}{2}\right)\oplus\left(\frac{1}{2},0\right)$ representation is obviously reducible by projecting onto the chiral subspaces, but it can also be shown that the Dirac equation is actually also projector onto a spin $\frac{1}{2}$ irrep that mixes both chiralities.

One further thing to note, however, is the mass $m$ that you mentioned, which also determines the representation; in the massless case it will not be appropriate to speak of "spin".
When the mass is nonzero, the little group in question is $\text{SU}(2)$, and the little group method consists of taking unitary finite-dimensional representations of it, so we can speak of spin as usual. It can also be seen that the mass induces the mass-shell condition upon choosing a rest frame for the representation, which acts as the Klein-Gordon equation (which is why it occurs in all massive field theories). The fact that in this case the double cover of $\text{SO}_3$ is the little group is no coincidence; it is exactly the group of symmetries of the rest frame.
However, in the massless case, the little group is given by $\mathbb{R}^2\rtimes\text{Spin}_2$, the double cover of the Euclidean group. So its finite-dimensional representations are more accurately labeled by the name helicity. There is no rest frame for the particle, so its symmetry group is given by rotations around its axis of motion*: (the double cover of) $\text{SO}(2)$. The presence of the $\text{Spin}_2$ group severely restricts the possible Lorentz representations it can be embedded in; we cannot, for example, describe a particle of helicity $\pm1$ with the $\left(\frac{1}{2},\frac{1}{2}\right)$ representation, and we must resort to $(0,1)$ and/or $(1,0)$ (the self-dual and anti-self-dual fields respectively).
* The plane part $\mathbb{R}^2$ acts trivially, as we look for finite-dimensional unitary representations of the little group and $\mathbb{R}^2$ is non-compact.


text:
Q: Socket hang up error not caught in try catch block In the production environment, I'm using node 16.14.2. The pods are failing due to a Socket hang-up error. Although the socket hang-up error is not that frequent, I need better error handling for this error.
There is a try-catch block in place for error handling, but it still won't catch socket hang-up errors.
export const keepAlive = () => {
  const keepAliveSettings = {
    keepAlive: true,
    maxSockets: config.MAX_SOCKETS,
    maxFreeSockets: config.MAX_FREE_SOCKETS,
    timeout: config.SOCKETS_KEEPALIVE,
    keepAliveTimeout: config.SOCKETS_KEEPALIVE_TTL,
  };
  const httpAgent = new Agent(keepAliveAgentSettings);

  // for SSL
  keepAliveAgentSettings.rejectUnauthorized = false;
  const httpsAgent = new Agent.HttpsAgent(keepAliveAgentSettings);
  return {
       httpsAgent,
       httpAgent,
  };
};

// Axios instance with AgentKeepAlive setup.
   export const getAxiosInstance = () => {
     const webAgent = keepAlive();
     return axios.create({
       httpAgent: webAgent.httpAgent,
       httpsAgent: webAgent.httpsAgent,
     });
   };

// Inside the function
    try {
      response = await axiosInstance.get(`${url}${xt}${param}`, { httpsAgent: getHttpsAgent() });
    } catch (error) {
      console.log("error.message")
    }

Error Logs:
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20)
at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  errno: -104,
  code: 'ECONNRESET',
  syscall: 'read'
} [message]: undefined


text:
Q: .htaccess URL rewrite works, but address bar then shows 'dirty' URL
*

*User clicks link (from their email): http://www.site.com/edit/wih293f73y

*Browser window opens and gets them to the correct page.

*But now the browser's address bar shows: http://www.site.com/editor.php?editCode=wih293f73y
Extra info:

*

*My rewrite rule is:RewriteRule    ^edit/([A-Za-z0-9-]+)/?$    editor.php?editCode=$1    [NC,L]

*This problem ONLY occurs when the user has clicked a link. It works perfectly when you just type the pretty url into the address bar.

*This problem ONLY occurs for links that include the www. - the link http://site.com/edit/wih293f73y works like a charm.

*My .htaccess file includes the following code (from HTML5 boilerplate, which I wasn't aware of previously):

# Rewrite www.example.com → example.com
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

If it's important, this occurs after my other rewrite rules.

A: I just took a look and it is apparent that your www rules is causing this. Question is do you want it be fixed? If you do then move this rule on top of all other rules and your problem should be fixed.
Move this to top of all other rules
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

A: You can use use the redirect directive

redirect 301 ^edit/([A-Za-z0-9-]+)/?$ editor.php?editCode=$1

There are some pros and cons to this strategy. The pros being;

*

*It's super fast. You don't even need to load up your application for this to work.

*It's minimal code.

*Redirects are an intrinsic part of Apache (or any http server) and aren't going anywhere soon.

The cons being;

*

*It's not part of your application proper. Should you decide to change logic or URLs, you'll have to change this, too.

*It's slower, as you need to invoke php, as opposed to just having Apache issue the redirect.


text: Q: Communication between android tablet using USB I want to make simple app to transfer 100 MP file from one android tablet to another tablet. Both has ice-cream sandwich and USB host port. How to perform this operation? I can't file simple code to send file from one Tab to another Tab.


text:
Q: How to reliably obtain a folder's view state property bag I'm trying to implement a feature that allows the user to save a given Explorer folder view layout, and then apply that same view to other folders as desired.
After digging around and experimenting, it seems like the way to obtain and save a folder view would be to call SHGetViewStatePropertyBag.  But as far as I can tell, that function requires you to know a folder-type GUID.  The call has to look something like this:
SHGetViewStatePropertyBag(  pidlFolder,
                            L"Shell\\{5C4F28B5-F869-4E84-8E60-F11DB97C5CC7}",
                            SHGVSPB_FOLDERNODEFAULTS,
                            IID_PPV_ARGS(&pPropBag) );

As a practical matter, that GUID is probably FOLDERTYPEID_Generic, FOLDERTYPEID_Documents, FOLDERTYPEID_Videos, FOLDERTYPEID_Pictures, or FOLDERTYPEID_Music, but that doesn't seem to be a given.
Furthermore, I'm not sure all folders have a folder type specified under the "Shell" key.
So is there a reliable or better way of obtaining a folder's view state property bag?


text:
Q: Error reporting is blocked on parse errors I will start by writing that I did see similar questions, and I did try the suggested solutions.
I am running a cli, when I purposely put a parse error in the php file, I get no error in stdOut.
I am using the below configurations:
22527 for error_reporting is
ini_set('error_reporting', E_ALL|E_STRICT);
PHP 5.5.20 (cli) (built: Jan  9 2015 11:20:56)
php -i | grep error
display_errors => STDOUT => STDOUT
display_startup_errors => Off => Off
error_append_string => no value => no value
error_log => no value => no value
error_prepend_string => no value => no value
error_reporting => 22527 => 22527
html_errors => Off => Off
ignore_repeated_errors => Off => Off
log_errors => Off => Off
log_errors_max_len => 1024 => 1024
track_errors => Off => Off
xmlrpc_error_number => 0 => 0
xmlrpc_errors => Off => Off

ADDITION: If I add my own fatal handler:
    function fatal_handler() {
        $error = error_get_last();
        if ($error !== null) {
            echo ("\n\nERROR occured!\nFile [{$error['file']}].\nLine: [{$error['line']}].\nMessage: [{$error['message']}]\n\n");
        }
        exit(1);
    }
register_shutdown_function("fatal_handler");

I do get to see the error in stdio.
Below is an example to a code (with parse error) that does not produce errors for me
class A{
   const AAA = 'aaa';
   static public function Result(A::AAA){

   }
}

A: The error_reporting => 22527 => 22527 is equivalent to E_ALL & ~E_DEPRECATED & ~E_STRICT.
Use -1 or E_ALL error level (E_ALL | E_STRICT in PHP 5.4) to show all errors.
Set it in the ini file php.ini.
error_reporting = -1

The following won't work, because the code contains a parse error so the ini_set() never gets called.
<?php

ini_set('error_reporting', -1)

class A
{
    const AAA = 'aaa';

    static public function Result(A::AAA)
    {
    }
}


text:
Q: Animate size of UITextField when pressed I have a text field that I want to change the width and image of when I touch inside it. The image changes without any issues but the width remains the same. The issue somehow lies in the action triggered when touching the text field because when I create a simple button the animation works. So my question is how to get the animation working when touching the text field.
The animation doesn't work here:
- (void)textFieldDidBeginEditing:(UITextField *)textField{

        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationCurveEaseOut
                         animations:^{

                         self.textFieldSearchStore.background = [UIImage imageNamed:@"text-field-small.png"];
                         self.textFieldSearchStore.frame = CGRectMake(textFieldSearchStore.frame.origin.x, textFieldSearchStore.frame.origin.y, 248.0f, textFieldSearchStore.frame.size.height);

                     }
                     completion:^(BOOL finished){}
     ];

}

The animation works here:
- (IBAction)test:(id)sender {

    [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationCurveEaseOut
                     animations:^{

                         self.textFieldSearchStore.background = [UIImage imageNamed:@"text-field-small.png"];
                         self.textFieldSearchStore.frame = CGRectMake(textFieldSearchStore.frame.origin.x, textFieldSearchStore.frame.origin.y, 248.0f, textFieldSearchStore.frame.size.height);

                     }
                     completion:^(BOOL finished){}
     ];

}

A: Are you touching the frame of self.textFieldSearchStore in any other method like
– textFieldShouldBeginEditing:
– textFieldDidBeginEditing:
– textField:shouldChangeCharactersInRange:replacementString:

or methods that listen to the following notifications:
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification

or any of these methods
– canBecomeFirstResponder
– becomeFirstResponder
– touchesBegan:withEvent:

If so I would set a breakpoint on these methods to see if they are being called after the method above. Let me know if it's helpful.

A: Problem solved. The issue was that I was using a Table View Controller. Changed to a regular View Controller and now it's working!


text:
Q: Add multiple users in XMPP roster How can I add multiple users in my roster? Right now I can add a single user at a time. But now I have to sync device contact with XMPP. Using backend API I can filter out the contacts which are registered with the application. Now adding them one by one to the roster is taking too much time.
So is there any quicker way to add multiple contacts to the roster?
I have already gone through many questions like this, but they are no help.
And is filtering device contact with backend API a good approach, or should I be doing something else?

A: XMPP is a complete XML based protocol, even through library doesn't have some methods, we can extend the library as per our need. So as you said that you want to add multiple rosters there are two approaches to achieve it:
1.  Add some method into your XMPP client library or in your application and add multiple roster items as below:
- (void)addUsers:(NSArray<XMPPJID *> *)jids withNickname:(NSArray<NSString *> *)optionalNames groups:(NSArray *)groups {

if (jids == nil) return;
XMPPJID *myJID = xmppStream.myJID;

// Add the buddy to our roster
//
// <iq type="set">
//   <query xmlns="jabber:iq:roster">
//     <item jid="bareJID" name="optionalName">
//      <group>family</group>
//     </item>
//   </query>
// </iq>

XMPPIQ *iq = [XMPPIQ iqWithType:@"set"];

for (int i = 0; i < jids.count; i++) {

    XMPPJID *jid = jids[0];
    if ([myJID isEqualToJID:jid options:XMPPJIDCompareBare])
    {
        // You don't need to add yourself to the roster.
        // XMPP will automatically send you presence from all resources signed in under your username.
        //
        // E.g. If you sign in with robbiehanson@deusty.com/home you'll automatically
        //    receive presence from robbiehanson@deusty.com/work

        XMPPLogInfo(@"%@: %@ - Ignoring request to add myself to my own roster", [self class], THIS_METHOD);
        continue;
    }
    NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
    [item addAttributeWithName:@"jid" stringValue:[jid bare]];
    NSString *optionalName = optionalNames[i];
    if(optionalName)
    {
        [item addAttributeWithName:@"name" stringValue:optionalName];
    }

    for (NSString *group in groups) {
        NSXMLElement *groupElement = [NSXMLElement elementWithName:@"group"];
        [groupElement setStringValue:group];
        [item addChild:groupElement];
    }

    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
    [query addChild:item];
    [iq addChild:query];
}

[xmppStream sendElement:iq];

}

*Write some service api with some rabbitmq service at server side and it will insert multiple roster for a users and XMPP server will update you regarding roster update. I hope this answer will help you.

A: I tried sending this stanza :
<iq type="set" id="15-47" to="940588870@localhost">
    <query xmlns="jabber:iq:roster" ver="1116247190">
        <item jid="1234@localhost" name="user1" subscription="both">
            <group>acceptance</group>
        </item>
        <item jid="7663@localhost" name="user2" subscription="both">
            <group>acceptance</group>
        </item>
        <item jid="9876@localhost" name="user3" subscription="both">
            <group>acceptance</group>
        </item>
        <item jid="1111@localhost" name="user4" subscription="both">
            <group>acceptance</group>
        </item>
    </query>
</iq>

I received
this error : 00:32:03.163 [Smack Cached Executor] WARN  org.jivesoftware.smack.roster.Roster.handleIQRequest(1739) -  - Ignoring roster push with not exactly one entry. size=4

On checking this further, XMPP guidelines say that it considers the packet with namespace "jabber:IQ:roster" and more than 1 item element inside the query element as an error case.


text:
Q: set visible on others selectors without parent and children I can use children() and parent() but what if inputs not are children and parent?

    <input type="checkbox" class="check">
    <select style="display: none"><option>1</option><option>2</option></select>
    <select style="display: none"><option>1</option><option>2</option></select>
    <input type="text" style="display: none">

    <input type="checkbox" class="check">
    <select style="display: none"><option>1</option><option>2</option></select>
    <select style="display: none"><option>1</option><option>2</option></select>
    <input type="text" style="display: none">

    <input type="checkbox" class="check">
    <select style="display: none"><option>1</option><option>2</option></select>
    <select style="display: none"><option>1</option><option>2</option></select>
    <input type="text" style="display: none">

    <input type="checkbox" class="check">
    <select style="display: none"><option>1</option><option>2</option></select>
    <select style="display: none"><option>1</option><option>2</option></select>
    <input type="text" style="display: none">

if i check checkbox with class check then 2 select and input should be visible. How can i make with jQuery?
FIDDLE: http://jsfiddle.net/ykyNq/1/

A: Depending on your situation you can use a few different selectors to find siblings.  In this case you can use siblings()
$('.check').click(function(){
    $(this).siblings("select, input").toggle()
})

http://jsfiddle.net/ykyNq/3/

A: You can use siblings to select all it's siblings(elements at the same level under the same parent)
$('.check').click(function(){
    $(this).siblings().toggle();
})

http://jsfiddle.net/ykyNq/4/


text: Q: new user/login GUI missing in SSMS 2017 I'm new to azure and I've created a new SQL DB and I want to create a read-only user for my DB (so I can use it in my web app) but when I go to create a new login/user (right click security folder >  select new login/user) I get a query tab instead of the GUI that I see in all the examples for creating a user. Did MS do away with the new user/login GUI or are there some settings that are not on that control whether or not that GUI screen shows?


text:
Q: How to add "async" to a route with a custom middleware? I need to use await inside a route on Express, therefore it must be async. However, when I try to add async to the route, it does not work because I use a middleware.
api.get('/users/yop', CORS(CORSOPT), async, checkauth, (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

Middleware looks like this:
function checkauth(req, res, next) {
 ...
 next();
}

If async and checkout are separed by commas like in the code I posted, I get this error:
await is only valid in async function
If they are not separated by commas, my code editor marks it as syntax error:

How to fix this?

A: The syntax you're trying is not valid. async always goes with the function definition.
api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

should work. If checkauth too contains await statements, mark the definition of checkauth as async.

A: You need to declare the arrow function as async directly using the keyword.
api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
    await GETDATA.getUsers(db.collection('users'));
    res.json(users[req.user]);
});

A: Put the "async" directly in-front of the function you are passing in, not the references to the other functions. If those needed async, they can have their own declarations when those functions are defined themselves.
api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

A: You can add async to the callback function:
api.get('/users/yop', CORS(CORSOPT), checkauth, async (req, res) => {
  await GETDATA.getUsers(db.collection('users'));
  res.json(users[req.user]);
})

Also if you want checkauth to return a promise for any reason, this is where you put the async:
async function checkauth(req, res, next) {
 ...
 next();
}


text:
Q: Javascript optional parameters for callbacks I want to do something like $.ajax() success and error callbacks.
This is what I have so far:
var FileManager = {
            LoadRequiredFiles: function (onLoadingCallback, onCompleteCallback) {
                //Not sure what to do here
                this.OnLoading = onLoadingCallback;
                this.OnCompleteCallback = onCompleteCallback;

                this.OnLoading();
                this.OnComplete();
            },
            OnLoading: function () {
                //empty by default
            }
            OnComplete: function () {
                //empty by default
            }

};
//I want to do something like this:
FileManager.LoadRequiredFiles({OnLoading: function() {
            alert('loading');
       }
});

How do I fix this up properly? I'm using FileManager as my namespace.

A: You can check if the functions are defined:
var FileManager = {
    LoadRequiredFiles: function (config) {
        config = config || {};
        this.OnLoading = config.onLoadingCallback;
        this.OnCompleteCallback = config.onCompleteCallback;

        if(typeof this.OnLoading =='function') {
            this.OnLoading();
        }

        //Or use the shortcut:
        if(this.OnComplete) {
            this.OnComplete();
        }
    }
};

FileManager.LoadRequiredFiles(
    {
        onLoadingCallback: function() {
            alert('loading');
       }
    }
);


text:
Q: What's a good way to calculate agreement between examiners when the measure is binary? I want to assess ability to identify tumor types in humans vs. a computers. There are 7 tumor types. I am interested in calculating agreement between the human examiners but I am not sure the best way to go about it. I have only ever seen ICC used in continuous measures, but there is no order to tumor types. One option is to assess agreement between examiners using a binary (0=incorrectly identified, 1=correctly identified) but I do not know how to calculate that.

A: A better option is to calculate Fleiss's kappa (or Cohen's kappa if there are only two examiners) using the categorical response data of what each examiner guesses is the correct tumor type.
https://www.datanovia.com/en/lessons/fleiss-kappa-in-r-for-multiple-categorical-variables/


text:
Q: Keeping things secret while using paramiko? I'm making an software which uploads files to my linux vps and then executes few commands there. As I can see, Paramiko is best option to do that, but only problem is keeping my vps login credentials safe. I don't want anyone who knows how to decompile py2exe or .pyc (which is not that hard nowadays) to get my root credentials. I looked into encrypt/decrypt but that actually doesn't solve my problem since I have to store string with real username/password inside code to be encrypted and later decrypted... To sum up, I want to know is there any way to keep my vps credentials safe and secure from users while using Paramiko?
Thanks in advance!

A: *

*Create a SSH key

*Set your key's public part as an authorized key on the server

*Make your software use said SSH key

With paramiko:
client = paramiko.SSHClient()
client.connect('127.0.0.1', username='user', key_filename='/home/user/.ssh/id_rsa')


text:
Q: Can i make maven-war-plugin to *only* copy the classes.jar but not the .war into local repo? OK, so i'm using the maven-war-plugin to build my war, which works fine.
I also have it setup to generate a -classes.jar.
When i run the build, both the war and -classes.jar gets copied into my .m2 repo, which takes up a lot of space.
I would like for only the classes-jar to get copied. Howver, setting the maven-install-plugin to "skip" skips both war and the classes-jar.
Is there a way for me to configure the war build so that only the classes jar gets copied into the repo?
Thanks in advance


text:
Q: peewee get_or_create and then save: error binding Is there an easy way to update a field on a get of a get_or_create?
I have a class ItemCategory and I want to either create a new entry or get the already created entry and update a field (update_date).
What I do is:
item,created= ItemCategory.get_or_create(cat=cat_id,item=item_id)
if created == True:
     print "created"
else:
     item.update_date = datetime.now
     item.somethingelse = 'aaa'
     item.save()

This works for a while in my loop. But after 50-100 get/create it crashes:

peewee.InterfaceError: Error binding parameter 4 - probably unsupported type.

Maybe I should use upsert(), I tried but wasn't able to get anything working. Also it's not probably the best solution, since it makes a replace of the whole row instead of just a field.
I like peewee, it's very easy and fast to use, but I can't find many full examples and that's a pity

A: Newbie mistake
item.update_date = datetime.now()

I am not 100% sure this is the only answer though. I modified my code so many times that it might be also something else.
Regarding my question about create_or_update , I've done this:
try:
    Item.create(...)
except IntegrityError:
    Item.update(...)

peewee is really great, I wonder why no one ever asked for a create_or_update.


text:
Q: Parent Activity not receiving Messages from Thread My test app below is roughly based on this threads tutorial by Cristian Baita.
It works as expected, with the exception that the message sent from myThread's run() method is never received by the MainActivity's handler.
I am passing the MainActivity's handler to myThread in the thread's constructor. I then use that handler's sendMessage() method to send a message back to the MainActivity, but the handler never seems to receive it. Why is this?
Note: I've found using breakpoints for debugging in eclipse is a pain with threads, so I ended up going over the top with Log statments instead to help follow the apps execution.
I've put the full code at the end of this post, but to summarise:
The constructor for the MyThread class takes a handler from the calling activity as shown below.
public class MyThread extends Thread {

    // Reference to mainHandler from the mainThread
    private Handler parentHandler;

    // Constructor
    public MyThread(Handler pHandler) {
        parentHandler = pHandler;
    }

When I create the thread in MainActivity's onCreate() method I pass it the handler mainHandler:
myThread = new MyThread(mainHandler);
myThread.start();

Then in MyThread's run() method I have:
    Message messageToParent = Message.obtain();
    messageToParent.what = 2;
    Log.i("myThread", "About to send message to parent ...");
    parentHandler.sendMessage(messageToParent);

The message should then be received by mainHandler defined in MainActivity:
    public Handler mainHandler = new Handler() {
        public void handleMessages(Message msg){
            Log.i("MainActivity", "Message Received");
            switch(msg.what) {
                case 2:
                    Log.i("MainActivity", "Handled message. msg.what = " + msg.what);
    ....

If you watch the LogCat window when this runs, you will see that MainActivity never logs "Message Received" or "Handled message... ". So the message never arrives at it's destination.
The MainActivity:
public class MainActivity extends Activity {

private MyThread myThread;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myThread = new MyThread(mainHandler);
    myThread.start();

    // Message the thread
    Message msgToThread = Message.obtain();
    msgToThread.what = 4;
    Log.i("MainActivity", "About to send message to thread...");
    myThread.getHandler().sendMessage(msgToThread);
}

public Handler mainHandler = new Handler() {
    public void handleMessages(Message msg){
        Log.i("MainActivity", "Message Received");
        switch(msg.what) {
            case 2:
                Log.i("MainActivity", "Handled message. msg.what = " + msg.what);

                // Message the thread
                Message msgToThread = Message.obtain();
                msgToThread.what = 6;
                myThread.getHandler().sendMessage(msgToThread);

                break;
            default:
                Log.i("MainActivity", "Unhandled message. msg.what = " + msg.what);
                break;
        }
    }
};
}

The MyThread class:
public class MyThread extends Thread {

// Reference to mainHandler from the mainThread
private Handler parentHandler;

// Constructor
public MyThread(Handler pHandler) {
    parentHandler = pHandler;
}

// Local handler for messages to this thread
private Handler myThreadHandler = new Handler() {
    public void handleMessage(Message msg) {

        switch(msg.what) {

            case 4:
                Log.i("myThread", "Handled message. msg.what = " + msg.what);
                break;

            case 6:
                Log.i("myThread", "Handled message. msg.what = " + msg.what);
                break;

            default:
                Log.i("myThread", "Unhandled message. msg.what = " + msg.what);
                break;
        }
    }
};

@Override
public void run() {
    super.run();

    int count = 0;
    boolean keepGoing = true;

    try {

        while(true) {

            Log.i("myThread", "run() method - while loop is ticking ..." + count);

            // some arbitrary conditions to make stuff happen
            switch(count) {
                case 5:
                    Message messageToParent = Message.obtain();
                    messageToParent.what = 2;
                    Log.i("myThread", "About to send message to parent ...");
                    parentHandler.sendMessage(messageToParent);
                    break;
                case 10:
                    keepGoing = false;
                    break;
            }

            if(!keepGoing) {
                Log.i("myThread", "myThread is going to stop");
                break;
            }

            count++;
            sleep(500);

        }

    }
    catch (Exception e) {
        Log.e("My Log", "Thread Loop Exception - " + e);
    }
    Log.i("myThread", "myThread has reached the end of it's run() method");
}

public Handler getHandler() {
    return myThreadHandler;
}

}

A: From an initial look, it might be because your parent handler is private. change it to public and try once!

A: I've realized I misunderstood what we are doing when we write the handleMessage() method for our handler.
I thought we were writing a new method for the handler, so I named it something slightly different handleMessages() (notice the plural).
In fact what we are doing is overriding one of the handler's existing method.
In the sample code I was following, Cristian Baita does not use an @Override statement before his handleMessage() method. This is fair enough, since @Override is only a convenience for you and your compiler to highlight bugs. Embarrassingly it is my fault for assuming that because @Override wasn't there, we weren't overriding anything. Hopefully this slip up will help some others in their learning curve.
BTW: I would still thoroughly recommend Cristian Baita's 3 thread tutorials, as they are very clearly explained and easy to follow. The problem was mine, in making assumptions!


text:
Q: AngularJS, ng-repeat, checkboxes and toggleAll There's no question. Searching over the internet, you can easily find examples with how ng-repeat and checkboxes work. All these examples include only few checkboxes. But, have you tried to create several hundred checkboxes, then use some toggle button to check/uncheck all checkboxes? The app becomes totally unresponsive. In browser it is kind of okay, but testing the app on device (iPad4, iPad mini etc), the app gets totally unresponsive.
I've created a Plunker example here: http://plnkr.co/edit/wfa3TIp3BYaPvzX8ehAf?p=preview
Try to test toggle checkbox with at least 500 entries so you could see the delay. The question now is, is there any way to improve the performance? Checking recording of Timeline, this is the result I'm getting for 500 entries (:
19.131 ms Scripting
150.104 ms Rendering
55.543 ms Painting
138.402 ms Other
2.95 s Idle

As you can see, rendering takes the precious time and we cannot afford that kind of time to be lost.
HTML:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
  <title>Ionic Framework Example</title>
  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet"/>
  <link href="index.css" rel="stylesheet"/>

<ion-view view-title="main module">
  <ion-content ng-controller="StartCtrl">

        Options

        Add more entries

        Clear entries

        Entries in array
        {{entries.length}}

          <input type="checkbox" ng-model="checkedAll" ng-click="toggleAll()">

        Toggle all

        Entries

          <input type="checkbox" ng-model="entry.checked" name="entry.id">

        {{entry.id}} - {{entry.name}}
        {{$index}}

  </ion-content>
</ion-view>

JS:
// Code goes here
var app = angular.module('myApp', []);

app.controller('StartCtrl', function ($scope) {

  // bind data from service
  // this.someData = Start.someData;
  $scope.entries = [];

  $scope.generateEntries = function () {
    var names = ['Mark', 'John', 'Maria', 'Lea', 'Marco'];
    var obj = {};
    for (var i = 0; i < 50; i++) {
      obj = {'id': Math.floor(Math.random() * 10000), 'name': names[Math.floor(Math.random() * names.length)]};
      $scope.entries.push(obj);
    }
  };

  $scope.clearEntries = function () {
    $scope.entries = [];
  };

  $scope.toggleAll = function () {
    for (var i = 0; i < $scope.entries.length; i++) {
      $scope.entries[i].checked = $scope.checkedAll;
    }
  };
});

Thanks to everyone that will participate in this discussion.

A: Use entry in entries track by entry.id instead of $index. Having 500 entries this improved the stats alot for me:
Using track by $index
65.660 ms Scripting
246.985 ms Rendering
129.748 ms Painting
1.23 s Other
3.31 s Idle

Using track by entry.id
46.534 ms Scripting
30.827 ms Rendering
17.631 ms Painting
226.515 ms Other
3.18 s Idle

A: Both replies, from @Numyx and @jaycp were very helpful. I've made a few improvements to the code:
1. I'm using track by entry.id instead of track by $index which speeded up the rendering as @Numyx said,
2. I've used ion-infinite-scroll so I don't load all results (5000 for example) at once, but only approx. 25. Scrolling to bottom loads more.
3. I'm using 2 datasets. 1 for ALL entries and 1 for view entries. View Entries array is filled when we scroll. The more we scroll, the more entries from ALL array are added to view array,
4. I'm using $timeout to show $ionicLoading and hiding $ionicLoading when rendering is finished,
So, when using toggle button, now we aren't making all entries as checked but only those, which are in visible array.
Here is the updated code:
start.html
<ion-view view-title="main module">
  <ion-content>

        Options

        Add more entries

        Clear entries

        Entries in array
        {{start.entries.length}}

          <input type="checkbox" ng-model="start.checkedAll" ng-click="start.toggleAll()">

        Toggle all

        Entries {{start.entriesView.length}}

          <input type="checkbox" ng-model="entry.checked" name="entry.id">

        {{entry.id}} - {{entry.name}}
        {{$index}}

      <ion-infinite-scroll
      on-infinite="start.loadMore()"
      ng-if="start.canLoadMore()"
      immediate-check="false"
      distance="1%">
      </ion-infinite-scroll>

  </ion-content>
</ion-view>

start-ctrl.js
'use strict';
angular.module('main')
.controller('StartCtrl', function (Utility, $timeout, $scope) {

  // bind data from service
  // this.someData = Start.someData;
  this.entries = [];
  this.entriesView = [];
  this.numEntriesToCreate = 5000;
  this.numEntriesToAdd = 25;
  var self = this;

  $scope.$on('$stateChangeSuccess', function () {
    console.log('START');
    self.loadMore();
  });

  /**
   * generate more entries
   */
  this.generateEntries = function () {
    var names = ['Gregor', 'Mathias', 'Roland', 'Jonas', 'Marco'];
    var obj = {};

    for (var i = 0; i < self.numEntriesToCreate; i++) {
      obj = {'id': Math.random() + Math.random() * 10000, 'name': names[Math.floor(Math.random() * names.length)]};
      self.entries.push(obj);
    }
  };

  this.clearEntries = function () {
    self.entries = [];
  };

  this.toggleAll = function () {
    self.startLoading();

    console.log(self.checkedAll);

    // we wait for spinner to appear (500ms), then start..
    $timeout(function () {
      for (var i = 0; i < self.entriesView.length; i++) {
        self.entriesView[i].checked = self.checkedAll;
      }

      self.finishedLoading();

    }, 500);
  };

  this.loadMore = function () {
    if (self.canLoadMore()) {
      // self.startLoading();
      $timeout(function () {
        self.entriesView = self.entriesView.concat(
          self.entries.slice(self.entriesView.length, self.entriesView.length + self.numEntriesToAdd) // exact items from our original entries
        );

        $scope.$broadcast('scroll.infiniteScrollComplete');
        // self.finishedLoading();
      }, 500);
    }
    //
  };

  this.canLoadMore = function () {
    return (self.entriesView < self.entries) ? true : false;
  };

  this.startLoading = function () {
    Utility.startTimer();
    Utility.showLoading();
  };

  this.finishedLoading = function () {
    $timeout(function () {
      Utility.hideLoading();
      console.log('execution took ' + Utility.endTimer() + 'ms.');
    });
  };

  console.log('init. creating ' + self.numEntriesToCreate + ' entries');
  self.generateEntries();

});
utility-serv.js
'use strict';
angular.module('main')
.service('Utility', function ($ionicLoading) {
  this.opt = {
    startTime: null
  };
  this.showLoading = function () {
    $ionicLoading.show({template: '<ion-spinner></ion-spinner>'});
  };
  this.hideLoading = function () {
    $ionicLoading.hide();
  };
  this.startTimer = function () {
    this.opt.startTime = new Date().getTime();
  };
  this.endTimer = function () {
    return ((this.opt.startTime) ? new Date().getTime() - this.opt.startTime : null);
  };
});

I've also published the full example on GitHub. Project was generated using generator-m. You can simply clone the github and run it using gulp watch command.


text:
Q: Horizontal barplot grouped by column pandas I have a df that looks like this.
Education                 Food_expenditures   Mitigative_expenditures   Household_expenditures
0   Primary (incomplete)    0.549451          6.923077                  2.527473
1   Illiterate              5.000000          5.000000                  0.000000
2   Primary (completed)     2.868217          4.883721                  2.248062
4   Illiterate              5.593220          3.559322                  0.847458
5   Primary (incomplete)    3.333333          5.555556                  1.111111

I would like to have a horizontal bar plot that is grouped by the expenditures and then by education.
Something that looks like this (only this example is just grouped by two levels for the second part).

I also want to invert it, so group first for Education and then for expenditures. But I'm sure I can figure that out based on the first one.
I just couldn't find a good example.

A: First aggregate values by Education by some function like sum or mean and transpose DataFrame:
df1 = df.groupby('Education').sum().T
print (df1)

Education                Illiterate  Primary (completed)  Primary (incomplete)
variable
Food_expenditures         10.593220             2.868217              3.882784
Household_expenditures     0.847458             2.248062              3.638584
Mitigative_expenditures    8.559322             4.883721             12.478633

Then use DataFrame.plot.barh:
df1.plot.barh()


text:
Q: Sending linux commands in Perl - Grep piped to grep The basic code:
my $ContentDate = `date -d '1 hour ago' '+%Y-%m-%e %H:'`;
my $Fail2banNo = `grep Ban /var/log/fail2ban.log | grep $ContentDate | wc -l`;

if (($Fail2banNo > $fail2ban)) {

} else {

}

Why wont Perl complete these commands correctly? $fail2ban is already defined to 0, so that's not the issue.
The fail2ban.log does contain a line that should match(when running command from shell it matches):
2018-07-19 xx:11:50,200 fail2ban.actions[3725]: WARNING [iptables] Ban x.x.x.x

The error i keep getting is:
grep: 10:: No such file or directory
sh: -c: line 1: syntax error near unexpected token `|'
sh: -c: line 1: ` | wc -l'
Argument "" isn't numeric in numeric gt (>) at /usr/local/bin/tmgSupervision.pl line 3431.

All the commands run fine from bash/shell, seems at if perl is not happy with grep being piped to another grep? I've tried many different ways of adding the variable($ContentDate) into the grep without helping.

A: I notice that the answer you've accepted has a rather over-complicated way to calculate the timestamp an hour ago, so I present this alternative which uses Perl's built-in date and time handling in a more efficient manner.
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Time::Piece;

my $log = '/var/log/fail2ban.log';
my $fail2ban = 0;

my $ContentDate = localtime(time - 3600)->strftime('%Y-%m-%e %H:');
my $Fail2banNo = qx{grep Ban $log | grep "$ContentDate" | wc -l};

if ($Fail2banNo > $fail2ban) {
  say 'Yes';
}
else {
  say 'No';
}

But the only change you actually needed was to change:
my $Fail2banNo = `grep Ban /var/log/fail2ban.log | grep $ContentDate | wc -l`;

to:
my $Fail2banNo = `grep Ban /var/log/fail2ban.log | grep "$ContentDate" | wc -l`;

Quoting $ContentDate because it contains a space.

A: The first problem is that $ContentDate ends with a line feed.
The second problem is that you improperly create the shell literal from $ContentDate (using grep 2018-07-19 08: instead of something like grep '2018-07-19 08:').
Let's first fix your answer.
use String::ShellQuote qw( shell_quote );

my $fail2ban_log_qfn = '/var/log/fail2ban.log';

my $content_date = `date -d '1 hour ago' '+%Y-%m-%e %H:'`;
chomp($content_date);

my $grep_cmd1 = shell_quote('grep', 'Ban', $fail2ban_log_qfn);
my $grep_cmd2 = shell_quote('grep', '--', $content_date);
my $fail2ban_count = `$grep_cmd1 | $grep_cmd2 | wc -l`;
chomp($fail2ban_count);

No need to shell out to get the date, though.
use POSIX              qw( strftime );
use String::ShellQuote qw( shell_quote );

my $fail2ban_log_qfn = '/var/log/fail2ban.log';

my $content_date = strftime('%Y-%m-%e %H:', localtime(time - 3600));

my $grep_cmd1 = shell_quote('grep', 'Ban', $fail2ban_log_qfn);
my $grep_cmd2 = shell_quote('grep', '--', $content_date);
my $fail2ban_count = `$grep_cmd1 | $grep_cmd2 | wc -l`;
chomp($fail2ban_count);

No need to shell out to to count the matching lines either.
use POSIX qw( strftime );

my $fail2ban_log_qfn = '/var/log/fail2ban.log';

my $fail2ban_count = 0;
{
   my $content_date = strftime('%Y-%m-%e %H:', localtime(time - 3600));

   open(my $fh, '<', $log_qfn)
      or die("Can't open \"$fail2ban_log_qfn\": $!\n");

   while (<$fh>) {
      ++$fail2ban_count if /Ban/ && /\Q$content_date/;
   }
}

A: Try this
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my $log = "/var/log/fail2ban.log";
my $fail2ban = 0;

my $ContentDate = backintime(3600); #backintime in seconds from now
my $Fail2banNo = qx{grep Ban $log | grep \"$ContentDate\"| wc -l};

if ($Fail2banNo > $fail2ban) {
        say "Yes";
}
else {
        say "No";

}

sub backintime {
        my ($to_today) = @_;
        my $temps = time - 60*60*24*0;
        $temps = $temps - $to_today;
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($temps);
        if($sec < 10) {$sec = "0" . $sec;}
        if($min < 10) {$min = "0" . $min;}
        if($hour < 10) {$hour = "0" . $hour;}
        if($mday < 10) {$mday = "0" . $mday;}
        $year+=1900; $mon++; if($mon < 10) {$mon = "0" . $mon;}
        my $sectime = $year."-".$mon."-".$mday." ".$hour.":";
        return($sectime);
}


text:
Q: Serializing JSON response in Flutter I would need assistance in serializing the below JSON Response. By far, I've managed to only extract the district property but cannot seem to understand how to go about with the properties of ward_no. The code for what I've done is below. Please note that I would like to serialize the JSON response in the same approach as on my code as I found it nearly impossible to wrap my head around the Serializing techniques suggested in the Official Documents.
The Response:
[
    {
        "district": "Kolkata",    //I've only managed to extract this.
        "ward_no": [
            {
                "ward": "6",
                "grievance": [
                    {
                        "serial_number": "0001",
                        "name": "Siddhartha Chatterjee"
                    },
                    {
                        "serial_number": "0002",
                        "name": "Sajujjo Ghosh"
                    }
                ],
                "general": [
                    {
                        "serial_number": "0003",
                        "name": "Dr. Partha Pratim Paul"
                    },
                    {
                        "serial_number": "0004",
                        "name": "Dr. Partha Pratim Paul"
                    }
                ],
                "urgent": [
                    {
                        "serial_number": "0005",
                        "name": "Ritwick Banerjee"
                    },
                    {
                        "serial_number": "0006",
                        "name": "Soumadip Banerjee"
                    }
                ],
                "services": [
                    {
                        "serial_number": "0007",
                        "name": "Tanajeet Biswas"
                    },
                    {
                        "serial_number": "0008",
                        "name": "Durba Chatterjee"
                    }
                ]
            }
        ]
    }
]

The code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Model {
  final String district;

  Model({required this.district});
}

class ModelClass with ChangeNotifier {
  List<dynamic> _data = [];

  List<dynamic> get data {
    return [..._data];
  }

  Future<void> getData() async {
    final url = Uri.http('192.168.0.6:3007', '/fetchData');
    final response = await http.get(url);
    print(response);
    final extractedData = json.decode(response.body);
    print(extractedData);
    Map<String, Model> temp = {};
    extractedData.forEach((value) {
      temp.putIfAbsent(
          value['_id'],
          () =>
              Model(district: value['district']));
    });
    print(temp);
    _data = temp.values.toList();
    print(_data);
  }
}

P.S: I'm not looking to use boilerplate code generated by those JSON to Dart converter links

A: You can use this tools which will generate data class form the provided json
https://jsontodart.zariman.dev/
class Response {
    String? district;
    List<WardNo>? wardNo;

    Response({this.district, this.wardNo});

    Response.fromJson(Map<String, dynamic> json) {
        this.district = json["district"];
        this.wardNo = json["ward_no"]==null ? null : (json["ward_no"] as List).map((e)=>WardNo.fromJson(e)).toList();
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["district"] = this.district;
        if(this.wardNo != null)
            data["ward_no"] = this.wardNo?.map((e)=>e.toJson()).toList();
        return data;
    }
}

class WardNo {
    String? ward;
    List<Grievance>? grievance;
    List<General>? general;
    List<Urgent>? urgent;
    List<Services>? services;

    WardNo({this.ward, this.grievance, this.general, this.urgent, this.services});

    WardNo.fromJson(Map<String, dynamic> json) {
        this.ward = json["ward"];
        this.grievance = json["grievance"]==null ? null : (json["grievance"] as List).map((e)=>Grievance.fromJson(e)).toList();
        this.general = json["general"]==null ? null : (json["general"] as List).map((e)=>General.fromJson(e)).toList();
        this.urgent = json["urgent"]==null ? null : (json["urgent"] as List).map((e)=>Urgent.fromJson(e)).toList();
        this.services = json["services"]==null ? null : (json["services"] as List).map((e)=>Services.fromJson(e)).toList();
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["ward"] = this.ward;
        if(this.grievance != null)
            data["grievance"] = this.grievance?.map((e)=>e.toJson()).toList();
        if(this.general != null)
            data["general"] = this.general?.map((e)=>e.toJson()).toList();
        if(this.urgent != null)
            data["urgent"] = this.urgent?.map((e)=>e.toJson()).toList();
        if(this.services != null)
            data["services"] = this.services?.map((e)=>e.toJson()).toList();
        return data;
    }
}

class Services {
    String? serialNumber;
    String? name;

    Services({this.serialNumber, this.name});

    Services.fromJson(Map<String, dynamic> json) {
        this.serialNumber = json["serial_number"];
        this.name = json["name"];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["serial_number"] = this.serialNumber;
        data["name"] = this.name;
        return data;
    }
}

class Urgent {
    String? serialNumber;
    String? name;

    Urgent({this.serialNumber, this.name});

    Urgent.fromJson(Map<String, dynamic> json) {
        this.serialNumber = json["serial_number"];
        this.name = json["name"];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["serial_number"] = this.serialNumber;
        data["name"] = this.name;
        return data;
    }
}

class General {
    String? serialNumber;
    String? name;

    General({this.serialNumber, this.name});

    General.fromJson(Map<String, dynamic> json) {
        this.serialNumber = json["serial_number"];
        this.name = json["name"];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["serial_number"] = this.serialNumber;
        data["name"] = this.name;
        return data;
    }
}

class Grievance {
    String? serialNumber;
    String? name;

    Grievance({this.serialNumber, this.name});

    Grievance.fromJson(Map<String, dynamic> json) {
        this.serialNumber = json["serial_number"];
        this.name = json["name"];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data["serial_number"] = this.serialNumber;
        data["name"] = this.name;
        return data;
    }
}


text:
Q: Updating GUI from multiple threads I've created a user control. In the control I have two methods – sending and receiving some data. Those methods also update the data grid located on the user control.
public void RunTX()
{
    tx_run = new Thread(new ThreadStart(SendCanFrames));
    if (!tx_run.IsAlive)
    {
        tx_run.IsBackground = true;
        tx_run.Start();
    }

}

public void RunRX()
{
    rx_run = new Thread(new ThreadStart(ReadCanFrames));
    if (!rx_run.IsAlive)
    {
        rx_run.IsBackground = true;
        rx_run.Start();
    }
}

private void ReadCanFrames()
{
    ushort prev_time_stamp = 0;

    while (running)
    {
        if (CanDevice != null)
            CanDevice.Read(ref rx_can_msg, 1, ref read_cnt);

        if (read_cnt == 1)
        {
            read_cnt = 0;

            dataGridViewCanRx.Rows[0].Cells[0].Value = rx_can_msg[0].Id.ToString("X");
            dataGridViewCanRx.Rows[0].Cells[1].Value = rx_can_msg[0].Size.ToString();
            dataGridViewCanRx.Rows[0].Cells[2].Value = BytesToString(rx_can_msg[0].Data);
             dataGridViewCanRx.Rows[0].Cells[3].Value = (rx_can_msg[0].TimeStamp - prev_time_stamp).ToString();

            prev_time_stamp = rx_can_msg[0].TimeStamp;
        }

        prev_time_stamp = rx_can_msg[0].TimeStamp;
    }
}

private void SendCanFrames()
{
    if (tx_can_msg.Length == 0) return;

    VSCAN_MSG[] l_msgs = new VSCAN_MSG[2];

    while (running)
    {
        for (int i = 0; i < tx_can_msg.Length; i++)
        {
            if (can_messages[i].CountRun < can_messages[i].CountMax)
            {
                can_messages[i].TimeStamp1 = DateTime.Now;
                interval = can_messages[i].TimeStamp1 - can_messages[i].TimeStamp2;

                if (interval.TotalMilliseconds >= can_messages[i].Period)
                {
                    can_messages[i].TimeStamp2 = DateTime.Now;

                     l_msgs[0] = tx_can_msg[i];

                     //send CAN frame
                     CanDevice.Write(l_msgs, 1, ref written_cnt);
                     // send immediately
                     CanDevice.Flush();

                     can_messages[i].CountRun++;

                    dataGridViewCanTx.Rows[i].Cells[4].Value = can_messages[i].CountRun.ToString();

                }
            }
        }
    }
}

I put four user control instances on the main form and start all four controls.
private void buttonStartAll_Click(object sender, EventArgs e)
{
    int can_channel;
    for (can_channel = 0; can_channel < 4; can_channel++)
    {
        if (started[can_channel] == false)
        {
            if (connected[can_channel] == true)
            {
                switch (can_channel)
                {
                    case 0:
                        mainform.userControlCan1.RunTX();
                        mainform.userControlCan1.RunRX();
                        started[can_channel] = true;
                        break;
                    case 1:
                        mainform.userControlCan2.RunTX();
                        mainform.userControlCan2.RunRX();
                        started[can_channel] = true;
                        break;
                    case 2:
                        mainform.userControlCan3.RunTX();
                        mainform.userControlCan3.RunRX();
                        started[can_channel] = true;
                        break;
                    case 3:
                        mainform.userControlCan4.RunTX();
                        mainform.userControlCan4.RunRX();
                        started[can_channel] = true;
                        break;
                }
            }
        }
    }
}

All is running, however the GUI freezing and data grids updated by jumps. Why?

A: I recomend you to look at two key points: Invoke and Application.DoEvents.
First one will help you to update your GUI in main thread instead of child threads.
Have a look at : https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.invoke?view=netframework-4.8
Application.DoEvents() method tells the system to do other waiting jobs without blocking in some loops. Otherwise updating GUI jobs are postponed and GUI is blocked. Here is the information about this method: https://learn.microsoft.com/tr-tr/dotnet/api/system.windows.forms.application.doevents?view=netframework-4.8
private delegate void dlgUpdateRows(object[] rx_can_msg, int tID);

// Write actual type of rx_can_msg instead of object[] in method signature , second parameter should be your thread id if needed
private void UpdateRows(object[] rx_can_msg, int tID =0)
    {
        try
        {
            if (this.InvokeRequired)
            {
                object[] obj = new object[2];
                obj[0] = rx_can_msg;
                obj[1] = Thread.CurrentThread.ManagedThreadId;
                this.Invoke(new dlgUpdateRows(UpdateRows), obj);
            }
            else
            {
                //Here update your datagrid using rx_can_msg

            }
            //This row is important to avoid blocking
            Application.DoEvents();
        }
        catch (Exception ex)
        {
            //Do error handling
        }

    }


text:
Q: Is it possible to get the annotated element from an annotation instance? If we have a class like this:
public class Foo {

  @MyAnnotation
  private String name;

}

And then have an instance of Foo:
Foo foo = new Foo();

Using reflection, we can get a Field instance representing name and from there using getAnnotation(MyAnnotation.class) we can get the instance of the annotation that is applied to the that field.
My question is, is it possible to get the annotated element (i.e. field, method, type, etc.) from an annotation?
For example:
MyAnnotation anno = ...;
anno.getField(); // returns the `Field` object representing the `name` field of a particular instance of `Foo`

A: No. :)
It appears to be a one way reference. I assume you want to pass the annotation to some other code which would then need to know what it was applied to? When you extract the annotations from the annotated element, you would store the field, method etc with the annotation at that time.  Perhaps create a wrapper bean which contains the Annotation and the annotated element.
Or, if the original class is available, get all annotations all compare them for equality, returning the element when there is a match. Not preferable, but possible.


text:
Q: How to initialize a GLfloat array? I want to put some lighting into a project i created, but i get the following compiler error:
error C2440: 'initializing' : cannot convert from 'float' to 'GLfloat []'

What is the problem?
GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);

GLfloat lightColor0[] = (0.5f, 0.5f, 0.5f, 1.0f);
GLfloat lightPos0[] = (4.0f, 0.0f, 8.0f, 1.0f);

glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightPos0);

GLfloat lightColor1[] = (0.5f, 0.2f, 0.2f, 1.0f);
GLfloat lightPos1[] = (-1.0f, 0.5f, 0.5f, 0.0f);

glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightPos1);

A: You have used wrong array initialization syntax. You may not use () to list array elements.
Syntax is { list_of_the_elements }
So change () to {}
GLfloat lightColor0[] = (0.5f, 0.5f, 0.5f, 1.0f);

to
GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f};

A: GLfloat lightColor0[] = (0.5f, 0.5f, 0.5f, 1.0f);

You need curly braces there {...} not parentheses (...). The way you wrote it, the compiler sees a buch of floating point literals, with comma operators inbetween. The last expression of a comma series becomes the value of what's inside the parenthesis.

A: You must use { ... }, not ( ... ) to initialize your array of floats.
Note that you are doing it right in the first line:
GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f};

But wrong in the lines below:
GLfloat lightColor0[] = (0.5f, 0.5f, 0.5f, 1.0f);

A: In the example shown you have parentheses around the data for lightColor0 and onwards.  I think you meant curly braces as used for ambientColor.


text:
Q: Environment Variables in C I know this type of question has been asked a lot but none of the answers seem to help.  I set an environment variable through setenv() function call in Ubuntu Linux.  However, the program doesn't seem use this environment variables.  If I use getenv() it gets the correct value but the output to the program is wrong.  However, when I use export BLOCKSIZE=512 in the shell, the output to the program is correct.  I am not spawning different processes from the program.  Below is only a code snippet of what I am doing, it is not my whole program.
Is there any reason for this?

A: The issue here is that Ubuntu Linux has a default BLOCKSIZE of 1024 not 512.  Therefore, when counting the blocks in the stat structure, namely the st_blocks field, I received a different answer than the normal ls because in stat the blocks are only counted in 512 byte blocks.  This means that my program would not have to take into account the size of the environment variable.  The main issue here was assuming that Linux used a 512 byte block size as I was told in a textbook.

A: There is nothing in the code shown that would be affected by the BLOCKSIZE environment variable.
No system call is affected by BLOCKSIZE.  I can see nowhere where you use 512.  Programs such as ls get the data from the o/s using the same system calls and then adjust the values that they present to you based on the setting of the environment variable.  But the key point is that it is a decision by ls in user code, not by the kernel in kernel code.
Since your code is not invoking ls or any other program, there's nothing to be affected by the environment variable.


text:
Q: Command to copy files from a repo to current one (React) on build/start I have a repo with a React project. I need to, on npm start or npm build, copy all the files in another repo, and paste them into the folder public/locales.
Is there any way to do this?

A: Assuming you are developing on some common flavor of GNU/Linux, and that the other repo is cloned on your local machine, change the start script on your package.json by this:
cp <route-to-the-other-repo-in-your-machine> public/locales && react-scripts start

And the build script on package.json by this:
cp <route-to-the-other-repo-in-your-machine> public/locales && react-scripts build


text:
Q: Using Gradle in IntelliJ IDEA Only for the Dependencies Aspect
*

*Intellij: 2018.3

*Gradle: 4.10.3

*Java: 10

*OS: Windows 10 Enterprise

I want to use Gradle dependencies in IntelliJ, but not any of the build/compile aspect of Gradle. After I import build.gradle, the runner starts a build which takes a long time, and fails midway, with some cryptic message like "Invalid tag type ...". So I don't see any of the Gradle dependencies setup either External Libraries or in the project settings dialog.
I realize developers can still run a Gradle compile task on their own since I use a Gradle Java plugin. I think the error encountered during the compile phase is preventing IntelliJ from settings up the dependencies.
I have a Java project with multiple modules. The project contains a structure as follows:
 DATA
  build.gradle
  DATA.iml
 DOMAIN
  build.gradle
  DOMAIN.iml
 SERVICE
  build.gradle
  SERVICE.iml
 WEB
  build.gradle
  WEB.iml
 build.gradle
 settings.gradle
 MyProject.ipr

This is an enterprise environment, so my developer machine may be locked down in some ways; it's possible.


text:
Q: Array multisort in php I have the following array:
Array (
 [0] => Array (
 [0] => Array ( [value-a] => 230.00 [value-b] => 1610.00 [value-c] => 3.00)
 [1] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 4.00)
 [2] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 2.00)
 )
)

How can I sort ascending by value-b and then by value-c?

A: You can remove first array wrapper:
Array (
    [0] => Array (
        [0] => Array ( [value-a] => 230.00 [value-b] => 1610.00 [value-c] => 3.00)
        [1] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 4.00)
        [2] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 2.00)
    )
)

to
Array (
    [0] => Array ( [value-a] => 230.00 [value-b] => 1610.00 [value-c] => 3.00)
    [1] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 4.00)
    [2] => Array ( [value-a] => 170.00 [value-b] => 1190.00 [value-c] => 2.00)
)

and here you can use usort() function :
http://php.net/manual/en/function.usort.php


text:
Q: Word for "after one's career" Posthumous is the word used to denote that something occurred after someone's death. Is there a word that could be used for after one's career? The best I got is postcurricular, but I think that is more specific towards after one's schooling.
Here is an example of what I am shooting for:

He received the award posthumously.
He received the email post __?

As a side note, I could use post employment, but that is not what I'm looking for.

A: Before reading @FumbleFingers in retirement, I would have said post-retirement. I would consider his comment better, but thought I'd throw this out for your consideration.

A: If you're really determined to use a post- prefix, I suppose you could say postvocationally.


text:
Q: How to get selected terms from Taxonomy web tagging control I have created a web part in which there is one taxonomy picker control to enable user to select department.
I want to store the selected term to the list column which is of type Managed Metadata.
The declarative part is:

        <asp:Label ID="lblProjectOwnerDepartment" runat="server" Text="Owner Department"></asp:Label>

        <Taxonomy:TaxonomyWebTaggingControl OnLoad="taxProjectOwnerDepartment_Load" ID="taxProjectOwnerDepartment" runat="server" Visible="true" IsDisplayPickerButton="true" IsMulti="false"
              AllowFillIn="false" IsAddTerms="false" IsIncludePathData="false"></Taxonomy:TaxonomyWebTaggingControl>

        <asp:CustomValidator ID="cvProjectOwnerDepartment" runat="server" OnServerValidate="cvProjectOwnerDepartment_ServerValidate"  />

How do I get the terms? I searched over internet but only found the articles to get terms from sharepoint.
Please help.

A: TaxonomyWebTaggingControl on the server side
TaxonomyWebTaggingControl.Text Property is used to set or get value that represent a Term object

Get values from this control as pairs of labels and GUIDs. The
  delimiter between a label and a GUID is the | character. When using
  multiple values, delimit them with a ; character.
  Example:
  term1|12345678-1234-1234-1234-123456789012;term2|87654321-4321-4321-4321-210987654321

TaxonomyWebTaggingControl on the client side
There is an alternative way to access and manipulate TaxonomyWebTaggingControl from client side Client side
For example to get Taxonomy control value
//Get Taxonomy ControlObject value
//webTaggingId - TaxonomyWebTaggingControl ID
function getTaxonomyControlObjectValue(webTaggingId) {
    var webTaggingCtl = $get(webTaggingId);
    var taxCtlObj = new Microsoft.SharePoint.Taxonomy.ControlObject(webTaggingCtl);
    var termValue = taxCtlObj.getRawText();
    return termValue;
}

For more details refer this post - Using SharePoint TaxonomyWebTaggingControl control: Access and manipulate from client side

A: Control Definition
<Taxonomy:TaxonomyWebTaggingControl id="**txtFileType**" runat="server" IsAddTerms="True" IsDisplayPickerButton="True" AllowFillIn="false">

How to call from javascript
var txtFileType = GetTerm("txtFileType");

Javascript function
function GetTerm(controlname) {

    var inputs = document.getElementsByTagName('span');
    for (var i = 0; i < inputs.length; i++) {

        {
            if (inputs[i].id.indexOf(controlname) > 0) {
                var b = inputs[i].getElementsByTagName("input");

                    if(b[0].value == "")
                        return "";

                    if(b[0].value.indexOf("|") == -1 || b[0].value.indexOf("-2222-2222-2222-") > 0)
                        {
                                alert("Invalid value " + b[0].value.split("|")[0] + ". Please select from list");
                                return "error";
                        }
                return b[0].value.split("|")[0];
            }
        }
    }
}


text:
Q: 1046: Type was not found or was not a compile-time constant: ServerSocketConnectEvent I am trying to get the adobe AIR SocketServer class to work. When I pasted in this code from the adobe website:
import flash.net.ServerSocket;
import flash.events.ServerSocketConnectEvent;

function onConnect(e:ServerSocketConnectEvent):void
{
    var incomingSocket:Socket = e.socket;
}
var server:ServerSocket = new ServerSocket();
server.addEventListener(Event.CONNECT, onConnect);
server.bind(8888);

I got the error saying that the SocketServerConnectEvent could not be found. However, there is an import statement importing precisely that class at the line above it. What am I missing here?

A: This is happening because when you launch your Air app it is trying to run it in the normal flash player and it obviously doesn't have access to those classes.
There was an article about it let me see if I can find it. Well can't find it.
If you run it from flash (cs5 etc) it should run fine. In flex builder I think you hit ctrl+f11.
I use flash develop most of the time and I am not sure how you would do it there. If that is what you use then the reason I stated above is why it is happening. (confirmed on my box)


text:
Q: Can't insert html with  tag I'm struggling with ckeditor 4.5, as I'm creating plugins to insert specific tags in current document after having uploaded a file on my server.
For some specific file types, I want to embed the element. I can add <audio> or <video> tags (by using allowContent=true in my config file), but when I insert an <object> tag (to embed a pdf file), the tag is just ignored.
I already tested adding config.extraAllowedContent = 'object[id, name, width, height, data, type] to the config file, with no avail.
I found some workarounds by adding a <div> around the <object>, but the pdf viewer is not displayed in the editor (but the <object> tag is there).
I think I'm doing something wrong with ACF, but I really don't see what.

A: only wrapped the  tag with  or , and if you use wordpress  , or drupal try to disable Advanced content filter from cms

A: <object> is not recommended for PDF and should not be a part of an editable area. There is no way it can be editable like text or paragraph. However, it can be a non-editable element inside the editor, with some editable parts. This is what CKEditor call widget, here is a tutorial how to create it: https://ckeditor.com/docs/ckeditor4/latest/guide/widget_sdk_intro.html
Note PDF format is not normally classed as "Media" more generally "Document" but there are two ways to embed. One is to use the allMedia plugin that does include PDF as a media format ;-) the other is to include content via google docs. So review the various "Demonstrations" on the website.


text:
Q: Class ParseClient not found in PHP I keep on trying to get my program to work with back4app, so I used PHP development   to get it to work. I have already inserted my keys, etc, but for some reason, in the end it says "Fatal error:  Uncaught Error: Class 'Parse\ParseClient' not found in mycode.php"
Here is my code:
require "parse-php-sdk/autoload.php";

use Parse\ParseClient;
use Parse\ParseQuery;
use Parse\ParseUser;
use Parse\ParseObject;
use Parse\ParseACL;
use Parse\ParsePush;

$appid = "x";
$rest = "x";
$masterKey = "x";

ParseClient::initialize( $appid, $rest, $masterKey );
ParseClient::setServerURL('https://parseapi.back4app.com', '/');

And here is the code that is placed in autoload.php
$base_dir = defined('PARSE_SDK_DIR') ? PARSE_SDK_DIR : __DIR__.'/src/Parse/';

And yes, I do have the right directory for the classes.
I still don't understand what I'm doing wrong.

A: You will have to use it like this:
Parse\ParseClient::initialize(..)

since in the beginning you init. Parse SDK as use Parse\ParseClient
you will need to add Parse\ before any class you will use.