text:
Q: how to load Alignment format in python? Is there a way to load alignment file to python. If I have file like this:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<rdf:RDF xmlns='http://knowledgeweb.semanticweb.org/heterogeneity/alignment#'
xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
xmlns:xsd='http://www.w3.org/2001/XMLSchema#'
xmlns:align='http://knowledgeweb.semanticweb.org/heterogeneity/alignment#'>
<Alignment>
<map>
      <Cell>
          <entity1 rdf:resource="http://linkeddata.uriburner.com/about/id/entity//www.last.fm/music/Catie+Curtis"></entity1>
          <entity2 rdf:resource="http://discogs.dataincubator.org/artist/catie-curtis"></entity2>
        <relation>=</relation>
        <measure rdf:datatype="http://www.w3.org/2001/XMLSchema#float">1.0</measure>
      </Cell>
    </map>
<map>
      <Cell>
          <entity1 rdf:resource="http://linkeddata.uriburner.com/about/id/entity//www.last.fm/music/Bigelf"></entity1>
          <entity2 rdf:resource="http://discogs.dataincubator.org/artist/bigelf"></entity2>
        <relation>=</relation>
        <measure rdf:datatype="http://www.w3.org/2001/XMLSchema#float">0.8</measure>
      </Cell>
    </map>
<map>
      <Cell>
          <entity1 rdf:resource="http://linkeddata.uriburner.com/about/id/entity//www.last.fm/music/%C3%81kos"></entity1>
          <entity2 rdf:resource="http://discogs.dataincubator.org/artist/%C3%81kos"></entity2>
        <relation>=</relation>
        <measure rdf:datatype="http://www.w3.org/2001/XMLSchema#float">0.9</measure>
      </Cell>
    </map>
</Alignment>
</rdf:RDF>

I want to keep confidence value as well as triple:
Subject:http://linkeddata.uriburner.com/about/id/entity//www.last.fm/music/Catie+Curtis
Predicate:owl:SameAs
Object:http://discogs.dataincubator.org/artist/catie-curtis
Confidence:1.0
I was trying to do it with RDFlib, but did not managed to.
Any suggestions will help, thanks!

A: Try with Redland libraries:
http://librdf.org/docs/python.html
import RDF
parser = RDF.Parser(name="rdfxml")
model = RDF.Model()
parser.parse_into_model(model, "file:./align.rdf", None)

And then query the model variable. For example, in order to retrieve all the alignments and return their measure, the query is the following:
for statement in RDF.Query("SELECT ?a ?m WHERE {?a a <http://knowledgeweb.semanticweb.org/heterogeneity/alignment#Cell> ; <http://knowledgeweb.semanticweb.org/heterogeneity/alignment#measure> ?m. }",query_language="sparql").execute(model):
print "cell: %s measure:%s"%(statement['a'],statement['m'])

The result will contain an iterator of dictionary objects  (variable name , result) and it will be printed out as follows:
cell: (r1301329275r1126r2) measure:1.0^^<http://www.w3.org/2001/XMLSchema#float>
cell: (r1301329275r1126r3) measure:0.8^^<http://www.w3.org/2001/XMLSchema#float>
cell: (r1301329275r1126r4) measure:0.9^^<http://www.w3.org/2001/XMLSchema#float>

APIs in python for retrieving Nodes content can be retrieved here: http://librdf.org/docs/python.html
   For an overview of the SPARQL query language you can read this: http://www.w3.org/TR/rdf-sparql-query/


text:
Q: Fetch page with jQuery and extract all links with specific class I want to fetch a page with jQuery and then extract values from the response, specifically I want to access all href attributes of a tags with a specific class.
The page is on the same domain, so there are no cross origin problems. The specific page returns a HTML page, but it would be great if it would work regardless of the content type.
What I have so far:
// the page to fetch (index2.html).

click
click2

On this page, this JS code works fine:
$('.getthis').each(function(){
    alert($(this).attr('href'));
})

What I now tried is this:
$.get('/index2.html', function(data){
    $(data).find('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

Fetching the page works fine, but extracting the data does not work. I tried a lot of variations on this idea, but none seem to work.
How can I fetch a HTML page with jQuery and then work on the DOM of the response, eg to extract all elements with a specific class?
I'm using jQuery 3.3.1, but it would be great if a solution would work on all versions.

A: Parse your data from ajax to DOM node via $.parseHTML().
And find element via .filter()
$.get('/index2.html', function(data){
    data = $.parseHTML(data);
    $(data).filter('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

A: I think,You can parse data like that
Create an invisible div

and set data into this
$.get('/index2.html', function(data){
    var container = document.querySelector('#index2Data');
    var root = container.createShadowRoot();
    $(root).html(data);
    $(root).find('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

A: If you want to work directly with the "data" and typeof data === "string" as in your example this might work for you:
var links;

$.ajax('index2.html').done(function (data) {
    // note that data is just a string
    // get all a tags with specific class
    links = data.match(//gi);

    // iterate over links and ...
    links.forEach(function (item, index) {

        // remove everything in front of the href attr value ...
        var start = item.indexOf('href=') + 6;
        links[index] = item.substring(start);

        // then remove everything after the href attr value
        var end = links[index].indexOf('"') > - 1
        ? links[index].indexOf('"')
        : links[index].indexOf('\'');

        links[index] = links[index].substring(0, end);
    });
});

console.log(links);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creath an array by input in VBA I would like to create an array to store the name of different departments of the company. First of all, I make users to input the total amount of departments and then create a array, allowing users to key in the name of departements.
But the compiler said the index of array is out of range.
Dim myarray As Variant
myarray = Array

deptnum = InputBox("Please enter the total amount of departments.")

For k = 0 To deptnum
x = InputBox("Please enter the name of department:"
x = myarray(k)
Next

A: If you still use the array, you can use the redim array, then use array(index) to assign the name you have entered.
Sub Test()
    Dim departments() As String
    Dim x As String

    deptnum = InputBox("Please enter the total amount of departments.")
    If Not (IsNumeric(deptnum)) Then Exit Sub
    ReDim departments(deptnum - 1)

    For k = 0 To deptnum - 1
        x = InputBox("Please enter the name of department:")
        departments(k) = x
    Next
End Sub


text:
Q: Collecting exported resource multiple times Is it possible to use the same exported resource in two different classes?
https://puppet.com/docs/puppet/5.2/lang_exported.html#exported-resource-collectors
For example, this will exports its own SSH host key and then collect the SSH host key of every node (including its own).
class hudson_destination::public_key {
  @@sshkey { "${fqdn}":
    type => rsa,
    key  => $sshrsakey,
    tag  => 'build_destination',
  }
}

I then collect this resource in another module that outputs to /etc/ssh/ssh_known_hosts files.
Sshkey <<| tag == 'build_destination' |>>

Can I use this collector in another class to output to, say ~/.ssh/known_hosts w/ a File resource?
*Note - I tried to duplicate the sshkey resource with a different title tag using:
@@sshkey { "${fqdn}_luntbld":
name => $fqdn,
type => rsa,
key  => $sshrsakey,
tag  => 'build_destination_luntbld',
target => '/com/home/luntbld/.ssh/known_hosts.puppet',

}
But go the error below about duplicate hostkeys already declared

Cannot alias Sshkey[fqdn_luntbld] to [\"yobot1.qa.norvax.net\"] at /etc/puppet/devqa/modules/hudson_destination/manifests/public_key.pp:22; resource [\"Sshkey\", \"yobot1.qa.norvax.net\"] already declared at /etc/puppet/devqa/modules/hudson_destination/manifests/public_key.pp:14 at /etc/puppet/devqa/modules/hudson_destination/manifests/public_key.pp:22 on node yobot1.qa.norvax.net\u001b[0m\n\u001b[1;31mWarning: Not using cache on failed catalog\u001b[0m\n\u001b[1;31mError: Could not retrieve catalog;


text:
Q: Jquery Not Synchronized with the DOM I found a new problem where when i manipulate the dom using jquery. The dom is not updated.
Here we go.
var PostCard = function($root) {
    this.$root = $root;
    this.stuff_id = this.$root.data('stuff_id');
    this.id = this.$root.data('id');
    this.is_owner = this.$root.data('is_owner');
    this.$propose_button = null;
    this.$favorite_button = null;
    this.init();
    this.initEvents();
};

PostCard.prototype.init = function () {
        this.$propose_button = this.$root.find("." + PostCard.prototype.CSS_CLASSES.PROPOSE_BUTTON);
this.$proposal_box_modal = this.$root.find("." + PostCard.prototype.CSS_CLASSES.PROPOSAL_MODAL);
this.$proposal_box = this.$root.find("." + PostCard.prototype.CSS_CLASSES.PROPOSAL_BOX);
this.$favorite_button = this.$root.find(".post-card-button-favorite");
this.$total_favorite = this.$root.find('.post-card-total-favorite');
this.$image_view_editor = this.$root.find("#" + this.id + "-image-view");
this.image_view_editor = new ImageViewEditor(this.$image_view_editor);
this.proposal_box = new HomeProposalBox(this.$proposal_box);

};

PostCard.prototype.initEvents = function() {
    var self =this;
    $(document).on("click", "#" + this.id,function(e) {

        if(e.target && $(e.target).hasClass('post-card-button-propose') ){
            if(self.is_owner ) {
            return false;
            }
            if(CommonLibrary.isGuest()) {
                return false;
            }
            self.$proposal_box_modal.modal("show").load($(this).attr("value"));
        } else if(e.target && $(e.target).hasClass('post-card-button-favorite')) {
            self.clickFavoriteButton_();
        }
    });

PostCard.prototype.clickFavoriteButton_ = function() {
        this.markFavorite();
};

PostCard.prototype.markFavorite = function() {

    this.$favorite_button.addClass('post-card-button-red');
};

When Favorite button is clicked, the clickFavoriteButton() will be trigerred, and markfavorite method will be fired next.
The problem is although this.$favorite_button is updated (the class is added to the variable), the dom in the page is not updated
this only happens to dynamically loaded element, and does not happen to element that has been around since the page is loaded.
The PostCard is created in PostList class
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var PostList = function($root) {
    this.$root = $root;
    this.stuff_ids = '';
    this.id = $root.data('id');
    this.location = $root.data('location');
    this.query = '';
    this.post_cards = [];
    this.$post_list_area = null;
    this.permit_retrieve_post = true;
    this.init();
    this.initEvents();
};

PostList.prototype.SCROLL_VALUE = 95;

PostList.prototype.init = function() {
    $.each($(".post-card"), function(index, value) {
        this.post_cards.push(new PostCard($(value)));
        if(this.stuff_ids === '' ) {
            this.stuff_ids += $(value).data('stuff_id');
        } else {
            this.stuff_ids += "," + $(value).data('stuff_id');
        }
    }.bind(this));

    this.$post_list_area = this.$root.find('.post-list-area');
};

PostList.prototype.initEvents = function() {
    $(window).scroll({self:this}, this.retrievePostWhenScroll_);
};

PostList.prototype.retrievePostWhenScroll_ = function(e) {
    var self = e.data.self;
    var scrollPercentage =
            ((document.documentElement.scrollTop + document.body.scrollTop) /
            (document.documentElement.scrollHeight - document.documentElement.clientHeight) * 100);
    if(scrollPercentage > PostList.prototype.SCROLL_VALUE) {
        if(self.permit_retrieve_post) {
            self.permit_retrieve_post = false;
            $.ajax({
                url: $("#base-url").val() + "/site/get-more-posts",
                type: 'post',
                data: {'ids' : self.stuff_ids, query: self.query, location: self.location},
                success: function(data) {
                    var parsedData = JSON.parse(data);
                    if(parsedData['status'] === 1) {
                        self.$post_list_area.append(parsedData['view']);
                        $(parsedData['view']).filter('.post-card').each(function(index, value) {
                            self.post_cards.push(new PostCard($(value)));
                            self.stuff_ids += "," + $(value).data('stuff_id');
                        });
                    }
                    self.permit_retrieve_post = true;
                },
                error : function(data) {
                    self.permit_retrieve_post = true;

                }
            });
        }
    }

};

When you scroll the page, the retrieveWhenScroll method will be fired and PostCard will be dynamically added


text:
Q: With the product topology $(X^\omega)^\omega$ and $X^\omega$ are homeomorphic From some lecture notes:

Here $a_n$ are sequences. The standard bijection in question is $\langle n, m \rangle = 2^n(2m + 1) - 1$. The topology on $Y^\omega$ is the product topology, both for $Y = X$ and $Y = X^\omega$.
I don't see why $h^{-1}$ is continuous, as any small change in $a \in X^\omega$ according to the metric (which induces the product topology):
$$ d(a, b) = \begin{cases}
0 & \text{ if } a = b \\\\
2^{-n} & \text{ if } a \upharpoonright n = b \upharpoonright n \land a(n) \neq b(n)
\end{cases}$$
impacts the sequence $(h^{-1}(a))(0)$ already. So that no matter the distance $d_{X^\omega}(a, b)$, we have $d_{(X^\omega)^\omega}((h^{-1}(a)), (h^{-1}(b))) = 1$.

A: It's easier to work directly with the product topology.
${^\omega}({^\omega}X)$ has a base consisting of sets $B$ of the following form. Let $F\subseteq\omega$ be finite, and for each $n\in F$ let $F_n$ be a finite subset of $\omega$. For each $n\in F$ and $k\in F_n$ let $U(n,k)$ be an open set in $X$. Let
$$B_n=\left\{a\in{^\omega}X:a(k)\in U(n,k)\text{ for each }k\in F_n\right\}\,,$$
a basic open set in ${^\omega}X$, and let
$$B=\left\{\langle a_n:n\in\omega\rangle\in{^\omega}({^\omega}X):a_n\in B_n\text{ for each }n\in F\right\}\,.$$
Let $a\in{^\omega}X$. Then $a\in h[B]$ iff there is $\langle a_n:n\in\omega\rangle\in{^\omega}({^\omega}X)$ such that $a=h(\langle a_n:n\in\omega\rangle)$ and $a_n(k)\in U(n,k)$ for each $n\in F$ and $k\in F_n$. But if $a=h(\langle a_n:n\in\omega\rangle)$, then $a(\langle n,k\rangle)=a_n(k)$ for each $n\in F$ and $k\in F_n$, so $a\in h[B]$ iff $a(\langle n,k\rangle)\in U(n,k)$ for each $n\in F$ and $k\in F_n$. That is,
$$h[B]=\left\{a\in{^\omega}X:a(\langle n,k\rangle)\in U(n,k)\text{ for each }n\in F\text{ and }k\in F_n\right\}\,,$$
which is open in ${^\omega}X$. Thus, $h$ is a continuous, open bijection and is therefore a homeomorphism.

A: A function $f: Y \to {{}^\omega}X$ is continuous (where the power has the product topology) iff $\forall n \in \omega: \pi_n \circ h: Y \to X$ is continuous where $\pi_n: {{}^\omega}X \to X;\, \pi_n(a)  =a(n)$ for all $n$ (the projection maps, which are always continuous on products). This is a standard fact about product topologies.
So with $\mathbb{h}_X$ we have that for $k \in \omega$ that $\pi_k \circ \mathbb{h}_X = \pi_n \circ \pi_m$ where $n,m$ are the unique members of $\omega$ such that $\langle n,m \rangle = k$, and this is a composition of two continous projections, hence continuous. So $\mathbb{h}_X$ is continuous.
For the inverse map (call it $\mathbb{k}$, say) we use a similar argument,
but then we have a "power of powers" so we need that $\pi_n \circ \pi_m \circ \mathbb{k}$ is continous for all $n,m$ but this just equals $\pi_{\langle n,m\rangle}$ (or the other order, it's late) and so just a (continous) projection again.
So both $\mathbb{h}_X$ and its inverse are continuous.


text:
Q: Como transformar um arquivo INI em um Array? Como posso transformar um arquivo INI em um array em PHP?
Exemplo:
[database]
host = localhost
password = sabe_de_nada_inocente
port = 3306

A: Se usar parse_ini_file ele irá interpretar sem as sessões, ficará algo como:
Array
(
    [host] => localhost
    [password] => sabe_de_nada_inocente
    [port] => 3306
)

Mas se aplicar o segundo parâmetro parse_ini_file('arquivo.ini', true); assim terá isto:
Array (
   [database] => Array (
        [host] => localhost
        [password] => sabe_de_nada_inocente
        [port] => 3306
    )
)

Se o conteúdo vier de uma string use então parse_ini_string, assim:
<?php

$data = '[database]
host = localhost
password = sabe_de_nada_inocente
port = 3306';

print_r(parse_ini_string($data, true));

Alguns detalhes que mudaram:

*

*PHP 5.3.0
Adicionado o terceiro parametro, o scanner_mode, aspas simples (apostrofos) são usados para setar a variavel e deixam de fazer parte do valor delas.
Hashs # não devem ser usadas para comentários, use ;, usar o hash vai causar um warning, pois esta em desuso, apesar do parse_ini_* ainda interpretar o hash como comentário.

*PHP 5.6.1
Adicionado o modo INI_SCANNER_TYPED, no terceiro parametro.

*PHP 7.0.0
Hashs finalmente não são mais usados como comentários e causa um erro de parse se tentar usar.
Usando o modo scanner_mode
Se tiver um .ini assim:
[foo]
baz = true
bar = false
foobar = On
foobaz = Off

E fizer isto:
<?php

var_dump(parse_ini_file('meu.ini', true));

Irá retornar isto, string com valor 1 se true ou On, ou string vazia se Off ou false:
array(1) {
  ["foo"]=>
  array(4) {
    ["baz"]=>
    string(1) "1"
    ["bar"]=>
    string(0) ""
    ["foobar"]=>
    string(1) "1"
    ["foobaz"]=>
    string(0) ""
  }
}

Note que se usar aspas ou apóstrofos ele não irá fazer o parse para 1 ou vazio, semelhante ao INI_SCANNER_RAW:
baz="true"
bar="false"
foobar= "On"
foobaz="Off"
testnumer="0"

Se usar INI_SCANNER_RAW (PHP 5.3.0+)
<?php

var_dump(parse_ini_file('meu.ini', true, INI_SCANNER_RAW));

Não irá fazer o parse de On, Off, true e false, serão todos string "literais":
array(1) {
  ["foo"]=>
  array(4) {
    ["baz"]=>
    string(4) "true"
    ["bar"]=>
    string(5) "false"
    ["foobar"]=>
    string(2) "On"
    ["foobaz"]=>
    string(3) "Off"
  }
}

Se usar INI_SCANNER_TYPED (PHP 7) ele irá tratar On, off, true e false como boolean:
<?php

var_dump(parse_ini_file('meu.ini', true, INI_SCANNER_TYPED));

Retorna isto:
array(1) {
  ["foo"]=>
  array(4) {
    ["baz"]=>
    bool(true)
    ["bar"]=>
    bool(false)
    ["foobar"]=>
    bool(true)
    ["foobaz"]=>
    bool(false)
  }
}

A: Use a função parse_ini_file(). Caso exista 'campos' com o mesmo nome, o último entrará como chave no array. Para evitar essa situação, passe true como segundo argumento, assim o array será separado por sessões.
config.ini
[database]
host = localhost
password = sabe_de_nada_inocente
port = 3306
[ftp]
user = admin
password = admin1234

php:
$arr = parse_ini_file('config.ini', true);

echo "<pre>";
print_r($arr);

Saida:
Array
(
    [database] => Array
        (
            [host] => localhost
            [password] => sabe_de_nada_inocente
            [port] => 3306
        )

    [ftp] => Array
        (
            [user] => admin
            [password] => admin1234
        )

)

Sem o informar o segundo argumento o retorno é:
Array
(
    [host] => localhost
    [password] => admin1234
    [port] => 3306
    [user] => admin
)


text:
Q: IE11 css for one particular class not showing in new tab I have this very weird IE11 behavior which occurs with some of our customers out of the blue.
We have a large table filled with several codes. Every code has its own (background) color assigned. Say the code is SOS, the css for its class is:
.cellSOS {
    background-color: #ff1837;
    color: #ffffff;
    height: 18px;
}

The HTML for a td looks like this:

SOS

In this case there are +/- 120 different codes.
If I load the page in IE11 the (background) color for all codes are shown correctly. Now the problem: if open the same page in a new tab, all codes have a (background) color, except SOS. The same problem when the page is opened with window.open.
If I use the developer tool (F12) and examine the cells, all cellXXX elements have their style defined  (the same format as .cellSOS). But when I examine a cell containing SOS, the style is not there.
I tried moving the class within the css to another position to see if that gave another result, but still it was SOS without (background) color.
I compared the HTML for the page displayed correctly and the faulty page and they are both the same.
The problem occurs not with all our customers, but when it occurs it is always just one code that gives this problem and in that case it is always the same code, no matter where I define the style.
I also tested it in IE8 and there it shows fine. FireFox and Chrome also display correctly.

Solved, sort of:
I have found the cause, but not an explanation.
The codes used are activities, used in a planning system. There are also users in this system. There was a user with the code Sos, and that caused the cell for activity SOS to display without a style.
Note: there is no connection whatsoever between the classes for activities and users.
Also a fun fact: if I change the user code to SOS (all uppercase, now it is exactly equal to the activity code) the problem does not occur.


text:
Q: my php code is secure? php to pdo over eval function i'm writing a php web script with mvc, but i'm concerned about code is safe.
i fear most "eval($str)", but i try a lot of php function string but nothing happened.
$a = func_get_args();
  if((func_num_args()-1)%2 == 0){
    $str = "";
    array_shift($a);
    for($i = 0;$i<sizeof($a);$i++){
      if($i%2==0){
        if(!is_numeric($a[$i])){
          if($a[$i] == 'filter'){
            $filter=1;
          }
          $str.= "$".stripslashes($a[$i])." = ";
        }else{
          $str.= 'page';
        }
      }else{
        if($filter != 1){
          if(is_numeric($a[$i])){
            $str.= stripslashes($a[$i]).";";
          }else{
            $str.=1;
          }
        }else{
          $arr = explode("-",$a[$i]);
          $dizz = 'array(';
          for($j=0;$j<sizeof($arr);$j++){
            if(($j%2)==0){
            $dizz .= '\''.stripslashes($arr[$j]).'\'=>';
            }else{
            $dizz .= '\''.stripslashes($arr[$j]).'\',';
            }
          }
          $dizz = rtrim($dizz,',');
          $dizz .= ');';
          $str.= $dizz;
        }
      }
    }
    eval($str);
  }

  $filter = isset($filter) ? $filter : false;
  $page= isset($page) ? $page: '';
  $count= isset($count) ? $count: '';
  if($count == ''){
    switch ($process) {
      case 'table':
      $count = 40;
      break;
      case 'detailed':
      $count = 3;
      break;
      case 'mobile':
      $count = 12;
      break;
      default:
      $count = '';
      break;
    }
  }
  if($count != ''){
    if(is_numeric($count )){
      if($count <=200 && $count >0){
        $count = $count ;
      }else{
        $count = 40;
      }
    }else{
      $count = 1;
    }
  }
  if(!is_numeric($page)){
    $page= 1;
  }

to sql query->
$new_filter = "Where ";
  if($filter){
    foreach ($filteras $key => $value) {
      $new_filter .= 'k.'.$key.'='.$value.' and ';
    }
    $new_filter = rtrim($new_filter,' and ');
    $filter= $new_filter;
  }else{
    $filter= '';
  }
  $limit = ($limit) ? 'LIMIT 30' : '';
  if($id == ''){
    $where = $filter;
  }else{
    $where = $id;
  }

  $query = 'select * from kullanici as k join kisiler as ki on k.id = ki.kullanici_id join iletisim as i on k.id = i.kullanici_id '.$where.' '.$siralama.' '.$limit;
  $query = $this->_db->prepare($query);
  $query->execute();

example url:
profile/show/mobile/page/4/count/5/filter/echo-"'xzcxza'"-sadas-asdxc
this results:
$page = 4;$count= 5;$filter= array('echo'=>'%22%27xzcxza%27%22','sadas'=>'asdxc');


text:
Q: How do I connect to the serial console port os a Sunfire 280R? We have a Sunfire 280R (old SPARC/Solaris server) that is refusing to come up after being relocated.  We're trying to connect to the serial console port, but all we get is random gibberish on the screen.  We've tried both connecting with a DB25>DB9 adapter and using a DB-25->RJ45 adapter with a cisco RJ45->DB9 adapter to a windows laptop.
We're configuring the laptop to 9600 baud, 8 bit, 1 stop bit, no parity.  We've tried both no flow control and Xon/Xoff.
We get the same results hooking up to the serial port on a working SPARC server, so it's probably something in our setup rather than a fault with the server.
How do we get access to to serial console so we can work out what is stopping this box from getting to the network?  Is there a special sun adapter we need to get/make to get the serial link working?

A: Did you try a null modem cable in the middle?  I think that the Sun wants a real terminal.

A: You have to use the cable DB-25->RJ45. Put RJ45 in the sparc workstation serial port and the db-25 head in the serial port A of 280R. On sparc workstation use the command "tip hardwire"


text:
Q: Create and dynamically modify .dtsx file via MS Access VBA I am attempting to utilize a single .dtsx file with a dynamic execution file name through MS Access VBA. I am attempting to do this as part of an Access tool already created at work. While I
I have been able to get around the issue of linking the .dtsx to multiple files in the same folder by renaming each file to a singular, unique name, running the .dtsx, and then changing the name back. However, the folder directory is not necessarily guaranteed, as many other users may use the tool.
Imports Microsoft.SqlServer.Dts.Runtime

Module ApplicationTests

  Sub Main()

    ' The variable pkg points to the location of the
    ' ExecuteProcess package sample that was installed with
    ' the SSIS samples.
    Dim pkg As String = _
      "C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" & _
      "\Package Samples\ExecuteProcess Sample\ExecuteProcess\UsingExecuteProcess.dtsx"

    Dim app As Application = New Application()
    Dim p As Package = app.LoadPackage(pkg, Nothing)

    ' Now that the package is loaded, we can query on
    ' its properties.
    Dim n As Integer = p.Configurations.Count
    Dim p2 As DtsProperty = p.Properties("VersionGUID")
    Dim pl As DTSProtectionLevel = p.ProtectionLevel

    Console.WriteLine("Number of configurations = " & n.ToString())
    Console.WriteLine("VersionGUID = " & CType(p2.GetValue(p), String))
    Console.WriteLine("ProtectionLevel = " & pl.ToString())
    Console.Read()

  End Sub

End Module

This is the code I found at https://learn.microsoft.com/en-us/sql/integration-services/building-packages-programmatically/creating-a-package-programmatically?view=sql-server-ver15, but it only works for VB.Net, which I do not have access to. I am hoping to mimic this idea, but in Access VBA - create/modify a SSIS package.

A: So my quick searching confirmed what I believed to be true - VBA/VBScript isn't going to work with the object model that you are attempting to pull in with your Imports Microsoft.SqlServer.Dts.Runtime
You can write a bridge between the DTS assemblies so that you can use it in VBA but given that you're attempting to use Access's VBA because you don't have access to proper tooling, well, there's a circular reference.
Alternatives.
SQL Server Data Tools, SSDT, is free. It is the tool for authoring SSIS packages. It has a Script Task that uses .NET and has the references to the managed object model already set so write a package that modifies another package.
Expressions - most every object within an SSIS package supports Expressions so with sufficient elbow grease, you can get some very dynamic packages up and running.
Biml - Business Intelligence Markup Language is a free addon for Visual Studio that takes a different approach to making packages.
A common data processing pattern is a truncate and reload of data. Many neophytes to SSIS want a single package that takes any source and matches it to a destination and they want that to be dynamic - specify a new source/destination and magic happens. The engine doesn't support that. What Biml let's you do is define the pattern - Truncate a table -> Data flow with flat file source to OLE DB Destination. Now that you've got your pattern, you then use metadata (these files go to these target tables) and build out N packages. You get an explosion of packages but you don't care because the hard part was defining the pattern and collecting the metadata. The packages are almost disposable artifacts as they'll be standard across the entire ecosystem you develop.


text:
Q: Flutter button with icon and text looks odd I am trying to create a Flutter app that has a button with a text and icon as label, the icon being placed right of the text. The approach described in this post yields an odd looking button that seems expanded to the width of the app, see this image (link as I am not allowed to attach images):
Button becomes wide when adding a Row widget as child
It is not clear to me which layout widgets to use to tweak the text+image button to be formatted as the plain text button.
The code for producing the above example:
Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            new RaisedButton(
              onPressed: _incrementCounter,
              child: new Row(
                children: <Widget>[
                  new Text("Button with text and icon!"),
                  new Icon(Icons.lightbulb_outline)
                ],
              ),
            ),
            new RaisedButton(
              onPressed: _incrementCounter,
              child: new Text("Button with only text")
              ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

A: Row property mainAxisSize: MainAxisSize.min does the trick here.
@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Home'),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new RaisedButton(
              onPressed: () {},
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  new Text('Button with text and icon!'),
                  new Icon(Icons.lightbulb_outline),
                ],
              ),
            ),
            new RaisedButton(
              onPressed: () {},
              child: new Text('Button with only text'),
            )
          ],
        ),
      ),
    );
  }

A: You can simply use this RaisedButton.icon
Simple Usage:
RaisedButton.icon(
   onPressed: () {},
   elevation: 2.0,
   shape: new RoundedRectangleBorder(
      borderRadius: new BorderRadius.circular(5.0),
   ),
   color: const Color(0xFFFFB822),
   icon: Icon(Icons.add_shopping_cart),
   label: Text("Add to Cart",
             style: TextStyle(
             fontWeight: FontWeight.w900,
    ),
  ),
)

A: Very Simple and Easy...
ElevatedButton(
                style: ElevatedButton.styleFrom(
                    primary: Colors.green, elevation: 2),
                onPressed: () {},
                child: Row(
                  children: [
                    Icon(Icons.edit_outlined),
                    SizedBox(
                      width: 10.0,
                    ),
                    Text('Edit'),
                  ],
                ),
              ),

you can change your icon or text color, whatever you want to.
Hope this'll help you.


text:
Q: App doesn't exit from MainLoop after dialog I have this problem.
I have solved, it but does it correct for big application (in future:)?
#!/usr/bin/perl

use strict;
use warnings;

use lib '.';
use MyApp;
use LoginFrame;

my $f = LoginFrame->new;
$f->ShowModal;
if(int($f->GetReturnCode)) {
    print '['.$f->GetReturnCode."]\n";
    $f->Destroy;

    my $app = new MyApp;
    $app->MainLoop;

} else {
    print "PLEASE NOT THIS CRAP AGAIN!!!\n";
    print '['.$f->GetReturnCode."]\n";
}

A: "The ( main ) loop will not terminate until there are top level windows."

*

*wxPerl tutorial http://wxperl.sourceforge.net/tutorial/tutorial2.html#id4690123


text:
Q: Interface with symbol ppt88xx's bar code scanner using .NET CF I need to interface with a symbol ppt88xx's bar code scanner using .NET CF.
Any ideas?

A: If you mean on the scanner itself (from memory PPT8800 runs on Windows Mobile 2003? 2002?) you don't need to do anything to interface with it. When you scan something it sends the result of any successful read as keystrokes to the active application (just stick a textbox or something on your form, give it focus and voila). If you mean from another PDA, you can attach the PPT8800 as a Bluetooth device and, again, it acts like a virtual keyboard as far as the active application is concerned. You don't have to directly interface with the scanner at all.


text:
Q: ColorThief returning wrong dominant color In my UWP app we have images that users upload and they can be pretty much any size - so when I load these into in an Image control I resize them proportionally so they fit best into our image container (which is fixed at 112w x 152h) but as some images are wider than higher what I want to is find the background color of the image so I can set the Background of the image.
So to do this I am using the NuGet ColorThief package and the code below (taken from the sample I found there) is returning me the wrong dominant color in many cases:
var ct = new ColorThief();
QuantizedColor qc = await ct.GetColor(decoder);  //BitmapDecoder containing image
Windows.UI.Color c = Windows.UI.Color.FromArgb(qc.Color.A, qc.Color.R, qc.Color.G, qc.Color.B);
setImageBackgroundColor(bgColour);

One image I tried it on was this one - now the dominant colour should clearly be black but it's returning some medium grey colour.... so is there something wrong with my code or my image or is there something else I need to do?  I'm just not finding it reliable but I know others use it without issue.

A: According to the source code of the library, it seems it is actually averaging out the colors from the color palette of the picture
public async Task<QuantizedColor> GetColor(BitmapDecoder sourceImage, int quality = DefaultQuality,
                                           bool ignoreWhite = DefaultIgnoreWhite)
{
    var palette = await GetPalette(sourceImage, 3, quality, ignoreWhite);

    var dominantColor = new QuantizedColor(new Color
    {
        A = Convert.ToByte(palette.Average(a => a.Color.A)),
        R = Convert.ToByte(palette.Average(a => a.Color.R)),
        G = Convert.ToByte(palette.Average(a => a.Color.G)),
        B = Convert.ToByte(palette.Average(a => a.Color.B))
    }, Convert.ToInt32(palette.Average(a => a.Population)));

    return dominantColor;
}

In this particular case, I think setting ignoreWhite to true might return the actual black color, although it seems true is indeed the default setting.
I recommend using the other public method the library provides: GetPalette, to see what is the actual color palette of this image. This should explain why you are getting this particular color.
var palette = await GetPalette(decoder);

A: In my opinion you need to set quality from 5 to 10 and use GetPalette method with first color from palette.
QuantizedColor dominantColor = colorThief.GetPalette(tempBitmap, 5, 5, true)[0];


text:
Q: Create folder inner folder with Google Drive SDK iOS I'm trying to create a folder using the Google Drive SDK for iOS.
I Use as below code, Main drive in create  folder inner create.
GTLDriveFile *folder = [GTLDriveFile object];
folder.title = @"Testing";
folder.mimeType = @"application/vnd.google-apps.folder";
NSString *parentId = @"Testing";

folder.parents = @[parentId];

// ... execute query

GTLQueryDrive *query1 = [GTLQueryDrive     queryForFilesInsertWithObject:folder uploadParameters:nil];
[self.driveService executeQuery:query1 completionHandler:^(GTLServiceTicket *ticket,
                                              GTLDriveFile *updatedFile,
                                              NSError *error)
{
    if (error == nil)
    {
        NSLog(@"Created folder %@",updatedFile.identifier);

         GTLDriveParentReference *parentReference = [GTLDriveParentReference object];

         parentReference.identifier = updatedFile.identifier;
         GTLDriveFile *subFolder = [GTLDriveFile object];
         subFolder.title = @"Testing12352";
         subFolder.mimeType = @"application/vnd.google-apps.folder";
         NSString *parentId = updatedFile.identifier;
         subFolder.parents =  @[parentReference];

        // ... execute query

        GTLQueryDrive *query1 = [GTLQueryDrive queryForFilesInsertWithObject:folder uploadParameters:nil];
        [self.driveService executeQuery:query1 completionHandler:^(GTLServiceTicket *ticket,
                                                                   GTLDriveFile *updatedFile,
                                                                   NSError *error)
         {
             if (error == nil)
             {
                  NSLog(@"Created folder %@",updatedFile.parents);
             }
         }];

Work Perfect.
Google drive Folder inner folder create..

A: If you want to create Testing folder in root and Testing12352 inside Testing folder then for Testing you need to set parents to [@"root"] and for Testing12352 you need to set Testing's identifier as parents.
GTLDriveFile *folder = [GTLDriveFile object];
folder.title = @"Testing";
folder.mimeType = @"application/vnd.google-apps.folder";
NSString *parentId = @"root";

folder.parents = @[parentId];

// ... execute query

GTLQueryDrive *query1 = [GTLQueryDrive     queryForFilesInsertWithObject:folder uploadParameters:nil];
[self.driveService executeQuery:query1 completionHandler:^(GTLServiceTicket *ticket,
    GTLDriveFile *updatedFile,
    NSError *error)
    {
        if (error == nil)
        {
            NSLog(@"Created folder %@",updatedFile.identifier);

            GTLDriveFile *subFolder = [GTLDriveFile object];
            subFolder.title = @"Testing12352";
            subFolder.mimeType = @"application/vnd.google-apps.folder";
            NSString *parentId = updatedFile.identifier;
            subFolder.parents = @[parentId];

            // ... execute query

            GTLQueryDrive *query1 = [GTLQueryDrive queryForFilesInsertWithObject:subFolder uploadParameters:nil];
            [self.driveService executeQuery:query1 completionHandler:^(GTLServiceTicket *ticket,
            GTLDriveFile *updatedFile,
            NSError *error)
            {
                if (error == nil)
                {
                    NSLog(@"Created folder %@",updatedFile.parents);
                }
            }];

Note : Don't forgot to set scope to kGTLAuthScopeDrive

A: Swift 5
    func createFolder(
    subFolderName: String,
    service: GTLRDriveService,
    completion: @escaping (String) -> Void) {

    let folder = GTLRDrive_File()
    let parentId = "root"
    folder.mimeType = "application/vnd.google-apps.folder"
    folder.name = "MainFolder"
    folder.parents = [parentId]

    // Google Drive folders are files with a special MIME-type.
    let query = GTLRDriveQuery_FilesCreate.query(withObject: folder, uploadParameters: nil)

    service.executeQuery(query) { (_, file, error) in

        if error == nil {

            let folder = file as! GTLRDrive_File
            print("MainFolder Id \(folder.identifier!)")

            let subFolder = GTLRDrive_File()
            subFolder.mimeType = "application/vnd.google-apps.folder"
            subFolder.name = subFolderName
            subFolder.parents = [folder.identifier!]

            let query2 = GTLRDriveQuery_FilesCreate.query(withObject: subFolder, uploadParameters: nil)

            service.executeQuery(query2) { (_, file2, error2) in

                if error2 == nil {

                    let folder2 = file2 as! GTLRDrive_File

                    print("subfolder Id \(folder2.identifier!)")
                    completion(folder2.identifier!)

                }
            }
        }
    }
}


text:
Q: do parallel in R issue I am trying to modify a large matrix containing 0,1,2 values and replacing the 2 by 1.
The matrix contains 500.000 columns and 7000 rows. The data is already read in by 50 rows and now I want to break it up in blocks and multi-thread using foreach() %dopar%.
> SNPchunk
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    0    0    0    1    0    0    2
[2,]    1    0    1    0    1    1    1    0
[3,]    1    0    1    0    1    1    0    1
[4,]    0    0    0    0    1    0    0    2
[5,]    0    0    0    0    2    0    2    1
[6,]    0    0    0    0    0    0    0    1
[7,]    0    0    0    0    1    0    0    2
[8,]    0    0    0    0    2    0    1    1
[9,]    1    1    1    0    1    1    0    1
[10,]   0    0    0    0    1    0    1    1

chunk = foreach (part = 1:snpsplit) %do%
{
    snpchunk = SNPcomponents[,snp.start[part]:snp.stop[part]]

    #print(part)

    res = foreach(SNP=1:ncol(snpchunk), .combine='cbind') %dopar%
    {
        a = snpchunk[,SNP]
        a[a==2] <- 1
        print(a)
    }
}

with the print(a) statement the returned variable res is a matrix of n by x with all 2s replaced by 1s.
       result.1 result.2 result.3 result.4 result.5 result.6 result.7 result.8
[1,]        0        1        1        1        0        1        1        1
[2,]        0        0        0        0        0        0        0        0
[3,]        1        0        0        0        0        0        0        0
[4,]        0        0        0        0        0        0        1        1
[5,]        0        1        1        1        0        0        1        1
[6,]        1        0        1        1        0        1        1        1
[7,]        0        1        1        1        0        0        1        1
[8,]        0        1        0        0        1        1        1        1
[9,]        0        0        0        0        0        0        0        0
[10,]       1        1        0        0        0        0        0        1

However without the print(a) statement the returned variable res is a matrix of 1 by x containing only the value 1.
>res
result.1 result.2 result.3 result.4 result.5 result.6 result.7 result.8
   1        1        1        1        1        1        1        1

How do I get the first result without using the print statement?
Thank you for helping!
J.

A: If you completely remove print(a) the a[a==2] <- 1 line returns 1. That is why you should use a instead of print(a)
res = foreach(SNP=1:ncol(snpchunk), .combine='cbind') %dopar%
{
    a = snpchunk[,SNP]
    a[a==2] <- 1
    a
}


text:
Q: android: Displaying multiple images like INSIDE the Tinder-cards How would I go about displaying multiple images the way Tinder does it: it should display the next image when I click on the right side of the image and display the previous image when I click on the left side of the image.

It should also display a little arrow to the right or left only when clicked and show somehow which picture is being displayed (with little bars like tinder or dots or something).
Is there a library for that?
EDIT:
To clarify: I already implemented the Tinder swipe-cards with the help of the Diolor/Swipecards library. What I'm suprisingly a little stuck with is implementing the image gallery INSIDE the Tinder swipecards. Only the part seen in the picture above.

A: There are a lot of libraries to it for you
https://github.com/janishar/PlaceHolderView
https://github.com/yuyakaido/CardStackView
https://github.com/Ivaskuu/tinder_cards
https://github.com/Yalantis/Koloda-Android

A: My solution was adding two pictures of arrows, putting two layouts above them, then adding onClickListeners for the Layouts, which select the next/previous picture in the adapter to be displayed in the ImageView.
The layout .xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:clipToPadding="false"
    android:outlineProvider="bounds"
    android:paddingLeft="10sp"
    android:paddingTop="10sp"
    android:paddingRight="10sp"
    android:paddingBottom="100sp">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:elevation="2dp"
        app:cardCornerRadius="4dp">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageViewMainBackground"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@mipmap/ic_user_default" />

            <ImageView
                android:id="@+id/imageNext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|end"
                android:scaleType="centerCrop"
                android:src="@drawable/outline_keyboard_arrow_right_black_48" />

            <ImageView
                android:id="@+id/imagePrevious"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:scaleType="centerCrop"
                android:src="@drawable/outline_keyboard_arrow_left_black_48" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:weightSum="1">

                <LinearLayout
                    android:id="@+id/previousLayout"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight=".50"
                    android:orientation="horizontal" />

                <LinearLayout
                    android:id="@+id/nextLayout"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_gravity="end"
                    android:layout_weight=".50"
                    android:orientation="horizontal" />
            </LinearLayout>

            <TextView
                android:id="@+id/nameTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:padding="20sp"
                android:shadowColor="@color/colorBlack"
                android:shadowRadius="20"
                android:textColor="@color/colorWhite"
                android:textSize="30sp"
                tools:text="hello" />

            <ImageView
                android:id="@+id/infoImageViewItemCard"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|end"
                android:scaleType="centerCrop"
                android:padding="20sp"
                android:shadowColor="@color/colorBlack"
                android:shadowRadius="20"
                android:src="@drawable/outline_info_white_48" />

            <LinearLayout
                android:id="@+id/bottomLayout"
                android:layout_width="match_parent"
                android:layout_height="110dp"
                android:layout_gravity="bottom"
                android:orientation="horizontal" />

        </FrameLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>


text:
Q: How to catch a particular name assignment? (Based on this question):
One can override the __setattr__ magic method for an object to have additional instructions when an attribute of an object is set. As in:
class MyClass(object):
    def __init__(self, attribute=None):
        object.__init__(self)
        self.attribute = attribute

    def __setattr__(self, name, value):
        self.__dict__[name] = value
        if name == 'attribute':
            print("attribute's value is modified to {}.".format(
                                                        self.attribute))

if __name__ == '__main__':
    my_obj = MyClass(True)
    while True:
        my_obj.attribute = input()

*

*How can I catch a particular name assignment in the current script
without using classes(specifically to call a method with more
instructions)?

def b_is_modified():
    print("b is modified!")

if __name__ == '__main__':
    a = 3
    b = 4
    b = 5

How to call b_is_modified when b is assigned a value?

A: I think the other answer by Nae sums it up; I'm not aware of any built-in mechanisms in the Python languages to detect assignments, so if you want an interrupt-like event system to trigger upon assignment I don't know if it's feasible.
However, you seem quiet determined to get a way to "detect" assignment, so I want to describe an approach that might get you closer than nothing.
There are the built-in functions globals() and locals() that creates dictionary of variables in global and local scope respectively. (They, in additon to vars() are further explained here).
A noteworthy point is that locals() will behave differently if called from inside a function:

If locals() is called inside a function it constructs a dictionary of the function namespace as of that moment and returns it -- any further name assignments are not reflected in the returned dictionary, and any assignments to the dictionary are not reflected in the actual local namespace
If locals() is called outside a function it returns the actual dictionary that is the current namespace. Further changes to the namespace are reflected in the dictionary, and changes to the dictionary are reflected in the namespace:

Here is a "hacky" way to detect changes to variables:
def b_is_modified():
    print("b is modified!")

if __name__ == '__main__':
    old = locals().get('b')

    a = 3
    b = 4
    b = 5

    new = locals().get('b')
    if id(new) != id(old) and new is not None:
        b_is_modified()

This is nothing else but an (obfuscated?) way of checking if the value of b has changed from one point in execution to another, and there is no callback event or trigger action that detects it. However, if you want to expand on this approach continue reading.
The rest of the answer explains how to check for changes in b by rewriting it to something like:
if __name__ == '__main__':
    monitor = ScopeVariableMonitor(locals())

    a = 3
    b = 4
    monitor.compare_and_update()  # Detects creation of a and b
    b = 5
    monitor.compare_and_update()  # Detects changes to b

The following will "detect" any changes to the variables, and I've also included an example where it's used inside a function, to reiterate that then the dictionary returned from locals() does not update.
The ScopeVariableMonitor-class is just an example, and combines the code in one place. In essence, it's comparing changes to the existence and values of variables between update()s.
class ScopeVariableMonitor:
    def __init__(self, scope_vars):
        self.scope_vars = scope_vars  # Save a locals()-dictionary instance
        self.old = self.scope_vars.copy()  # Make a shallow copy for later comparison

    def update(self, scope_vars=None):
        scope_vars = scope_vars or self.scope_vars
        self.old = scope_vars.copy()  # Make new shallow copy for next time

    def has_changed(self, var_name):
        old, new = self.old.get(var_name), self.scope_vars.get(var_name)
        print('{} has changed: {}'.format(var_name, id(old) != id(new)))

    def compare_and_update(self, var_list=None, scope_vars=None):
        scope_vars = scope_vars or self.scope_vars
        # Find new keys in the locals()-dictionary
        new_variables = set(scope_vars.keys()).difference(set(self.old.keys()))
        if var_list:
            new_variables = [v for v in new_variables if v in var_list]
        if new_variables:
            print('\nNew variables:')
            for new_variable in new_variables:
                print(' {} = {}'.format(new_variable, scope_vars[new_variable]))

        # Find changes of values in the locals()-dictionary (does not handle deleted vars)
        changed_variables = [var_name for (var_name, value) in self.old.items() if
                             id(value) != id(scope_vars[var_name])]
        if var_list:
            changed_variables = [v for v in changed_variables if v in var_list]
        if changed_variables:
            print('\nChanged variables:')
            for var in changed_variables:
                print('  Before: {} = {}'.format(var, self.old[var]))
                print(' Current: {} = {}\n'.format(var, scope_vars[var], self.old[var]))
        self.update()

The "interesting" part is the compare_and_update()-method, if provided with a list of variables names, e.g. ['a', 'b'], it will only look for changes to those to variables. The scope_vars-parameter is required when inside the function scope, but not in the global scope; for reasons explained above.
def some_function_scope():
    print('\n --- Now inside function scope --- \n')
    monitor = ScopeVariableMonitor(locals())
    a = 'foo'
    b = 42
    monitor.compare_and_update(['a', 'b'], scope_vars=locals())
    b = 'bar'
    monitor.compare_and_update(scope_vars=locals())

if __name__ == '__main__':
    monitor = ScopeVariableMonitor(locals())
    var_list = ['a', 'b']
    a = 5
    b = 10
    c = 15
    monitor.compare_and_update(var_list=var_list)

    print('\n *** *** *** \n')  # Separator for print output

    a = 10
    b = 42
    c = 100
    d = 1000
    monitor.has_changed('b')
    monitor.compare_and_update()

    some_function_scope()

Output:
New variables:
 a = 5
 b = 10

 *** *** ***

b has changed: True

New variables:
 d = 1000

Changed variables:
  Before: b = 10
 Current: b = 42

  Before: a = 5
 Current: a = 10

  Before: c = 15
 Current: c = 100

 --- Now inside function scope ---

New variables:
 a = foo
 b = 42

Changed variables:
  Before: b = 42
 Current: b = bar

Conclusion
My answer is just a more general way of doing:
b = 1
old_b = b

# ...

if b != old_b:
    print('b has been assigned to')

The dictionary from locals() will hold everything that is a variable, including functions and classes; not just "simple" variables like your a, b and c.
In the implementation above, checks between "old" and "new" values are done by comparing the id() of the shallow copy of before with id() of the current value. This approach allows for comparison of ANY value, because the id() will return the virtual memory address, but this is assumable far from a good, general comparison scheme.
I'm curious to what you want to achieve and why you want to detect assignments: if you share your goal then perhaps I can think of another way to reach it in another way.

A: Based on this answer:
It can't be catched(at least in python level).
Simple name assignment(b = 4), as oppposed to object attribute assignment (object.b = 5), is a fundamental operation of the language itself. It's not implemented in terms of a lower-level operation that one can override. Assignment just is.


text:
Q: Swift 3 UITableView sections showing after the list I'm trying to create a list of products using swift 3 UITableViewController, but the sections is showing after the list of the products. There must be something I'm missing, couldn't find anywhere
Here is a simplified code
let data = [["0,0", "0,1", "0,2"], ["1,0", "1,1", "1,2"], ["2,0", "2,1", "2,2"],  ["3,0", "3,1", "3,2"]]

override func numberOfSections(in tableView: UITableView) -> Int {
    return data.count//productCategoriesSections.count
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data[section].count//productCategories[section].count
}

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "defaultCategoryCell", for: indexPath) as! CategoryDefaultTableViewCell
    cell.titleTextView.text = data[indexPath.section][indexPath.row]
    return cell
 }

override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
    return "Section \(section)"
}

screenshot

A: It is because you are using wrong callback.
Use override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? instead of override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String?.
The former will place the text as a header above the section. The latter places it at the bottom.


text:
Q: Android layout on high density displays i just released my app on android and have problems with customers with high density displays.
i added a debug thing to see what's going in, here is one sample output
Device: Nexus 10 Android version: 4.2.2
DisplayMetrics{density=2.0, width=2560, height=1504, scaledDensity=2.0, xdpi=298.275, ydpi=298.823}
MainView w=1900 h=1342
mDrumKitMode=BIG
KitView w=640 h=1266 x=1920.0 y=0.0
the main view is the music notation area on the left of the screen shot, its 1900 wide (MainView w=1900 h=1342) the drum kit is a bitmap that is 640w and 640 high. somehow, the display is scaling it to be full height of the parent, (KitView w=640 h=1266 x=1920.0 y=0.0). this doesn't happen on displays where density=1.0.
i have no way to test this since i can't get the emulator work on big displays for some reason and i don't have a high density tablet.
does anyone have an idea what could be going on? thanks

and here's another customer with a similar problem
Device: A700 Android version: 4.1.1
DisplayMetrics{density=1.5, width=1920, height=1128, scaledDensity=1.5, xdpi=224.73732, ydpi=224.11765}
MainView w=1260 h=1044
mDrumKitMode=BIG
KitView w=640 h=968 x=1280.0 y=0.0
i think its the scaledDensity=1.5 parameter, maybe i need to do something to disable automatic image scaling, i.e. set scaledDensity=1?
i should add that the entire application is based on exact pixel positions, both for the music notation display and the drum kit display which overlays images on top of the base drum kit image (you can see the drum pedals are in the wrong place on this image too). i don't want automatic scaling as i handle scaling inside the app for different display sizes and user preferences.
i should also add that all my drum kit images are in drawable-mdpi and all the other dpis are empty. this is because i scale images programmatically based on screen size and user preference BUT i think maybe the problem is a need to put some images in xhdpi? i guess i can do that but it will be a lot of work.
PS, i guess i found my answer here http://developer.android.com/guide/practices/screens_support.html
Provide different bitmap drawables for different screen densities
By default, Android scales your bitmap drawables (.png, .jpg, and .gif files) and Nine-Patch drawables (.9.png files) so that they render at the appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities.
i wonder if simply copying all the -mdpi images to -xhdpi will work?

A: If you intend for this app to be used across devices you have no choice but to put in images for all the various density folders that exist (xhdpi,xxhdpi, hdpi, mdpi).  It's also worth considering that you may want to change the actual layouts you include, to offer different ones for different devices.
Consult the documentation for how to handle this.
http://developer.android.com/guide/practices/screens_support.html
If that creates an apk that's too heavy (I have no idea how many images you have) then you can go the other way and specify a no scaling drawable folder which will just use the images in their native density across devices.  It's definitely wrong to use ONLY mdpi unless you intend to support only mdpi devices.


text:
Q: Wrong package.appxmanifest picked by msbuild when packaging in command line I have a C# solution with VS 2017, containing an app project, a desktop extension project, and a packaging project. As I mentioned in the answer of this question, I finally get msbuild to create a single bundle with both x86 and x64 for me. However, after I tried to install from that bundle, I found that msbuild actually picked up the wrong package.appxmanifest because they have different version numbers.
So... I have two package.appxmanifest, one in packaging project, and one in my main app project. When I build from the wizard in VS 2017, the one in packaging project will be used, which is correct. When I use msbuild to build with just one platform, it will pick the right one as well, like this:
msbuild .\MyApp.sln /p:Configuration=Release /p:Platform=x86

Only when I use msbuild to build two platforms together, it will use the one in my main app project:
msbuild .\MyApp.sln /p:Configuration=Release /p:AppxBundlePlatforms="x86|x64" /p:UapAppxPackageBuildMode=StoreUpload

I also tried to build the packaging project instead of the solution, but because our desktop extension project is only x86, I will get errors about configurations when building x64.
Questions:

*

*Does anyone know why this is happening?

*I am also very confused about how to build multi-platform using AppxBundlePlatforms in the command line. Since I cannot specify the platform, which platform is used to build?

*Should I add <AppxBundle>Always</AppxBundle> or <AppxBundle>Never</AppxBundle> to the packaging project?

A:

*

*Does anyone know why this is happening?

That because you have two Package.appxmanifest files with same ID in the solution. When you create the App Bundle with .sln, MSBuild/Visual Studio could not to know clearly which Package.appxmanifest should be use.

*I am also very confused about how to build multi-platform using AppxBundlePlatforms in the command line. Since I cannot specify the
  platform, which platform is used to build?

Not sure the reason why you can not specify the platform. To resolve this issue, you can try yo build the project file .csproj instead of the solution file. For example, when you build the app project, you can use the command line:
msbuild .\MyApp.csproj /p:Configuration=Release /p:AppxBundlePlatforms="x86|x64"

And then build the packaging project:
msbuild .\YouPackaging.csproj /p:Configuration=Release /p:AppxBundlePlatforms="x86"

*Should I add Always or
  Never to the packaging project?

If you build the project, no need to add those two properties to the project file, those two properties are used to the solution level and you have a project that you do not want to add to the bundle:

because at the solution level, it's not clear which app should appear
  in the bundle. To resolve this issue, open each project file and add
  the following properties at the end of the first
  element

Hope this helps.


text:
Q: regex replace in a file I am trying to do a replace of a specific set of characters in a file in Perl but it does not seem to work, here is my code.
my $file = shift;
open(FILE, "$file") or die "File not found";
while (<FILE>){
   $data .=$_
}
$data =~ s/[^A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}\s?[0-9]{2}\s?[0-9]{2}\s[0-9]{2}\s?[A-DEM]{0,1}$/XX012345X/g;

I know that my pattern matching works for finding the set of characters, I am not entirely sure the replace works. However, my main concern is the Perl code. The file remains untouched after I run it.
Sample File.
AB123456C Ab12345678 DG657465 GH123456FG

A: The code does not alter the file because you don't tell it to. You open the file for reading, not writing, plus you do not print anything.
If you want a quick way to handle this, just put your regex substitution in a file and use it as a source file. Like this:
Content of regex.pl:
s/[^A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}\s?[0-9]{2}\s?[0-9]{2}\s[0-9]{2}\s?[A-DEM]{0,1}$/XX012345X/g;

One-liner:
perl -p regex.pl inputfile.txt > output.txt

This way you can quickly check the output. You can also pipe to a pager command or not at all.

A: The file your are opening is read only. So you need to open a temporary second file (File::Temp) where your write the $data variable, close it, remove the first file (unlink) and rename the temporary file to the desired name.
This SO question may be helpful.
Off topic note: please, use modern Perl approach to handle your files. For example:
open my $fh, "<", $filename or die "Cannot open file $filename"

See also this SO question. Avoid the use of package-global typeglob filehandles.


text:
Q: quotients of polynomial rings What is the meaning of this quotients of polynomial rings
 R[x] mod x.x ? I want to find some ring ,s.t.x.x=0, x is a
element of the ring. Is there the ring? Is it R[x] mod x.x  ?
What is the meaning? Thank you!

A: The ring $R[x]/(x^2)$ is the quotient ring of the polynomial ring $R[x]$ by its ideal generated by $x^2$. In this quotient ring, the class of $x$ is not zero but its square is zero.
In fact, you can write every element of $R[x]$ as $a_0+a_1x+\dots+a_dx^d$ for some $a_0,\dots,a_d\in R$ (by definition of $R[x]$), and it is equivalent to $a_0+a_1x$. So you can see $R[x]/(x^2)$ isomorphic as a $R$-module to $\{a_0+a_1x\mid a_0,a_1\in R\}\simeq R^2$. The multiplication is then given by $$(a_0+a_1x)(b_0+b_1x)=a_0b_0+(a_1b_0+a_0b_1)x.$$

A: On underlying set $R\times R$ define addition $\left(r,s\right)+\left(r',s'\right)=\left(r+r',s+s'\right)$
and multiplication $\left(r,s\right)\left(r',s'\right)=\left(rr',rs'+r's\right)$.
This makes it a ring with unit $(1,0)$ and zero $(0,0)$, and we denote this ring as $S$.
Note that $\left(0,1\right)^{2}=\left(0,0\right)$ in $S$.
There is a surjective
ringhomomorphism $\phi:R\left[x\right]\rightarrow S$ determined by
$x\mapsto\left(0,1\right)$.
Its kernel is the principal ideal generated
by $x^{2}$ leading to: $$R\left[x\right]\text{ mod }x^{2}\simeq S$$


text:
Q: Return multiple values for antd form item, value pass in array of items I am working in react on a ruby on rails backend using antd. I have an antd form that passes in options from the controller in the backend. The point of this form item is to get an item id number, but I would also like to pass in a couple other attributes that are included in the controller.
The data works for me, so in the code example if I change <Option key={"item_" + o.id} value={o.id}> to <Option key={"item_" + o.id} value={o.attribute2}> I correctly get the other attribute I want. The problem is I want id, attribute2, and attribute3 to all pass in.
Is it possible for an antd form item to have multiple values. In my code example the commented out lines are things I have tried. I tried doing an array like value={o.id, o.attribute2, o.attribute3} and then extracting them with value.attribute2 or value[1], but nothing seems to work.
Or if I can pass in the data as just information like have value={} and then otherdata = {} that would work too, but that didn't seem to work either.
Below is my code,

    <Form.Item name="item_id" label={"item"} style={{ marginBottom: "0px" }}>
  <Select style={{width:"200px"}} onChange={(value, attribute2) => {
                              id_variable = value;
                              // id_variable = value[0];
                              // attribute2_variable = value.attribute2;
                              // attribute2_variable = value[1];
                              // attribute2_variable = attribute2
                            }}>
    {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id}>{o.label}</Option>)}
    {/* {options.tanks.map((o) => <Option key={"item_" + o.id} value={o.id, o.attribute2, o.attribute3} attribute2={o.attribute2}>{o.label}</Option>)} */}
  </Select>
</Form.Item>

A: Figured out what I was doing wrong. In case anyone sees this and has a similar problem: I wasn't making value an array correctly.
value={o.id, o.attribute2, o.attribute3}

should be
value={[o.id, o.attribute2, o.attribute3]}

Then you can call
<Select onChange={(value) => {
                              id_variable = value[0];
                              attribute2_variable = value[1];
                              attribute2_variable = value[2];


text:
Q: Return last directory in a path I am trying to return the last directory in a path.  For instance, for the following path, I wish to return "third".  My paths always start with no slashes and end with a slash.  If the path is empty, I wish to return an empty string.
first/second/third/
Below is my attempt.  Any recommendations on a better way?
var path='first/second/third/';
path1=path.substring(0, path.length - 1);
path2=path1.substr(path1.lastIndexOf('/') + 1);

A: split your way to success
var parts = path.split("/");
var last = parts[parts.length-1];

Of course, you'll need to decide what to do on fist/path/to/last vs. first/path/to/last/. Your usecases might require handling either one or both.

A: var path='first/second/third/';
var path2 = path.split('/');
path2 = path2[path2.length-2];

-2 because the last one is empty because of the last slash.

A: The lighter way of achieving such thing :)
// Remove trailing slash and split by slashes, then pick the last occurrence
path = path.replace(/\/$/, "").split("/").pop();

A: Try splitting the path and if the last directory is undefined (because the path is empty) use an empty string:
var path='first/second/third/';
var parts = path.split("/");
var path1 = parts[parts.length - 2] || ""

A: Maybe split would be better/cleaner choice here..
var directories = path.split("/");
var lastDir     = directories[directories.length - 1]

A: Try this,
var path='first/second/third/';
path.match(/([^\/]*)\/*$/)[1]; // return third

A: Here's a function segment that will take a url like string and return a specific part of it (using 1 counting, not 0). So, segment(str, 1) return first, and segment(str, 3) returns third. It also includes a trim function to strip off nasty preceding or trailing slashes which would cause empty items in the segments array... but maybe you want those so in that case just use return str.split... in the segment function.
var trim = function (str, charset) {
    charset = charset || "\s";

    var regex = new RegExp("^[" + charset + "]+|[" + charset + "]+$", "g")
    return str.replace(regex, "");
};

var segment = function (str, offset) {
    return trim(str, '/').split('/')[offset - 1];
}


text:
Q: How to pass a ref to a child component that is wrapped in a higher-order component - TypeScript error I am having a bit of trouble with the useRef hook with TypeScript and within a higher-order-component and was wandering if anyone would have a better insight into where I'm going wrong.
I am trying to pass the ref down from a parent component to the child via the ref prop. However, the child component is 'wrapped' in a higher-order component and I'm unsure how to resolve this.
I have tried implicitly adding types to the useRef hook, but to no avail. I am able to get it to work without the higher-order component, but I'm struggling to pass the ref to the child.
I am getting the following error:
Type '{ ref: RefObject<HTMLElement>; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
Property 'ref' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.  TS2322

Here are my components:
Parent Component
const App = () => {

  function handleNavClick() {
    window.scrollTo(0, aboutRef.current!.offsetTop);
  }

  const aboutRef = useRef(null);

  return (

        <Home />
        <About ref={aboutRef} />
        <Contact />

  );
};

export default App;

Child Component
import SectionWrapper from "../../wrappers/section/SectionWrapper";
import React, { forwardRef } from "react";

const About = (props: any, ref: any) => {
  return (

  );
};

export default SectionWrapper(forwardRef(About));

Higher-order component
import Container from "react-bootstrap/Container";

export default (Component: React.FC): React.FC => {
  return function WrappedComponent(props: any): JSX.Element {
    return (

        <Container>
          <Component {...props} />
        </Container>

    );
  };
};

Any help or insight would be greatly appreciated. Many thanks


text:
Q: How to manage and synchronize data on 7 separate computers Hypothetically speaking, let's say you live in a really big house and have 7 computers (designated them A-G for simplicity), each in different rooms/spaces of the house, connected either by wire or wireless to a router and sharing a single internet connection. Is there any way to turn one computer (A) into a server that'll run all my programs/games and store all my files on it, and the rest (B-G) will simply be "terminals" that allow me to access stuff?

A: Dropbox is a great cross-platform way to sync up to 2GB of content for free.  It will exist in the cloud (it's Amazon's S3 at the back end) and sync to your Windows and Macs.  The latest versions include "LAN Sync" which syncs the data across your local network instead of up to and down from the cloud everytime.  I use it for a subset of my data.
The rest of my data lives on a server (Server 2008 R2) and is accessed over the network.  The "Documents" directory on my Windows 7 PCs is redirect to a share on that server.  My MacBook Pro can access the same data, and my Windows 7 laptop uses Offline Files to ensure it's all available when I'm not on the LAN.
My pictures, video and music are also shared on the network from the main server; although I don't take them with me with Offline files (too much content/don't need it on the road).  My iTunes folder is on the music share which means I can open iTunes to the same library on multiple machines - just not at the same time.
There are many, many ways to skin this particular cat.  This is just my (Microsoft-centric) take on it.

A: As fretje points out you can use the "cloud" for some things. Then there are services such as Dropbox and Windows Live Mesh that can help turn other types of files to sort of being in the cloud as well (Windows Live Mesh can do so with Macs as well).
Lifehacker runs articles about these types of things ever so often. A little searching and reading the comments might help you.
As for running applications off one computer while being by the other one, the short answer is No. The longer answer is that on Windows that is called Remote Desktop Services (not to be confused with RDP or remote viewing), formerly Terminal Services, and in today's jargon it's called VDI (Virtual Desktop Infastructure). You would need a server (computer able to handle multiple terminals), expensive software, etc. Then there is the question of how fast the whole shebang works. The major players in this space have just released products that can do full screen video. Real games with realistic frame rates? not happening, at least not yet. (There is a web company that was working on games running on their servers, haven't read anything about them in about a year so I can't give you a link.)
There are some web game portals, flash games, Quake Live, etc.
So it appears that your best bet is to use the cloud for as many SAAS applications as possible, use the cloud for file sharing and syncing, and try to use it for games as well. All is dandy until your Internet cuts out for an hour!

A: Why don't you just use "the cloud" (e.g. Google Docs for documents, Flickr for pictures, ...) as your "mainframe", and use all 7 of your PC's to access your data through your shared internet connection?

A: the "...is done on the mainframe" part of question suggests you are after some sort of thin client set up, where processing is done on the server.
Ubuntu thin client tutorial.
Windows thin client tutorial.
This may be something best asked on serverfault.com though.

A: If you are going to be doing heavy gaming, it's going to be tricky to get good performance on the client PCs unless they have good hardware of their own.
You may want to consider having the server be simply a large file server, running an array or two of Raid 5 disks, and then limit gaming to only a few PCs to save on expense.

A: A simple (but not elegant) solution would to have the server store Virtualbox disk images, then have the PCs run a light-weight OS just for the purpose of hosting the virtualbox guests stored on the server.
Very trivial to keep (everything) in synch, but a tedious process saving and loading the image across the network whenever you change computers. (Unless you have some sort of gigabit lan set up).

A: In my experience there is no better solution than Dropbox, where update is lightening fast. In free account you'll be able to use it only on 2 computers.
The 2nd option would be Sugarsync, where same 2GB in free acc, but there is chance to select your own folder for sync. But update falls behind Dropbox (considering an pdf file 30 MB or more).
May be use these 2 free sevice, or check plans at Dropbox.
To add: i've used webOS, like Glide or g.ho.st, both give ca. 30 GB, but upload is a pain (on a broadband of 3mbps)


text:
Q: Push messages from Azure worker role to asp.net web page hosted in web role I need help about my azure project.
I have one worker and one web role. In worker role I have TCP listener
that accept connections in Run() method. Every time connection is accepted
I create new thread that handles accepted client. I send data from IOT device.
6 bytes every 1100ms. I have two integer value from those 6 bytes.
In web role I host asp.net web page with two asp. net chart and button start.
I need to add those integer values periodically so that I have trend and client can see change in real time.
First I implement data transaction between roles using azure queue, put message in queue in worker role and read it in web role.
I put my chart in update panel and set timer to refresh it every 1s.
I enable timer with click on start button.
In timer event i read message from queue, process it and delete it.
Later I realize this scenario is bad because what if I have two client watching at web page from different computers(one delete message and others can't see it). Second problem is that I only want to show last 2 min of trend(100 message apr.), I cannot guarantee that I will have 100 message in queue and because azure queue is FIFO I could read old data.
More legitime situation is that I push messages from worker role every time i have one ready for transmitting and on client side manage to have only 100 points oh chart. Or I could code long pulling so that client periodically fetch message from server. I was reading about signalR for first solution an classic ajax jquery for second.
I am not sure am I on the right path to solve this problem? Is it possible for worker role to push data to all client using signalR, or can I implement jquery in web role. I am little bit confused can this work in way I planed, or my concept is wrong.

A: you should use signalr.
signalr consists of two parts: 1. many signalr clients.  2. one signalr server.
signalr client can be a simple html or .aspx files with JavaScript function defined.
signalr Server can be a console or winform or service.
the signalr Server can also call any internal/external dll, webservices, webapi, whatever.
if there is any new data in the signalr server, the Server can call clients' JavaScript function to update the clients' page content, so you don't have to use timer in clients to retrieve data from server every second.
you may also store the whole set of latest data in the Server so that when there is a new client connected, the client can get the latest data immediately.


text:
Q: GCC format of error messages I need to implement simple data mining from error messages I get from gcc ( Java app is some JavaIDE for microprocessors which calls GCC in back and I need to tell user error in usable way). Is there any standard format for error messages in GCC ?

A: I think the format is  filename:line: message. Vim also parses gcc output so you can check :help efm-entries to see the patterns used.


text:
Q: Prevent checking a checkbox after onclick How can I prevent that a checkbox gets checked (without the use of disable)?
I tried
function nocheck() {
   if(somevar.value>3){
        alert("Not allowed");
        document.getElementById('mybox').checked = false;
   }
};

with
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" />

But this way the checkbox still gets checked after the alert message pops up.
EDIT:
Thanks to the comments/answers, I was able to come closer to a solution but not yet solved the problem - what's wrong with this code? http://jsfiddle.net/9kS8E/1/
HTML
<div class="ez-checkbox">
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck();" class="ez-hide">
</div>

JS
var user = { premium : false };
function nocheck() {
    if(!user.premium){
     return false;
    } else {
     return true;
   };
};

A: i think  i not understand your question but i think you are searching this,
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="return false;" />

OR
html
<input type="checkbox" name="mybox" id="mybox" value="test" onclick="nocheck()" />

js
function nocheck() {
   if(somevar.value>3){
        alert("Not allowed");
        return false;
   }else
        return true;
};

A: (1) save value of check box in a variable [ while "click" value of checkbox will get changed ]
(2) check user type,

*

*if not a premium user, toggle value of check box.

*else no need to change value of checkbox
(*) by using toggle : checkbox is already checked or not, we are not allowing a normal user to check it.
Fiddle : http://jsfiddle.net/aslancods/rQG3r/
       <input type="checkbox" name="mybox" id="mybox" value="test" onclick="noCheck(event)" />

        var user = { premium : true };
        function nocheck(elem) {
           var newValue = elem.checked;
           if(!user.premium) {
         alert("not allowed");
             elem.checked = !newValue;// toggle value
           } else {
             alert(" allowed ");
           }
        };

A: Your code should also work.
It's getting unchecked after alert.
You can say alert after unchecking like this.
if(somevar.value>3){
    document.getElementById('mybox').checked = false;
    alert("Not allowed");
}


text:
Q: Programmatically show tooltip in winforms application How can I programatically cause a control's tooltip to show in a Winforms app without needing the mouse to hover over the control?  (P/Invoke is ok if necessary).

A: If you are using the Tooltip control on the form, you can do it like this:
ToolTip1.Show("Text to display", Control)
The MSDN documentation for the ToolTip control's "Show" method has all the different variations on this and how to use them.

A: System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip(this.textBox1, "Hello");

The tooltip will be set over the control "textBox1".
Have a read here:
http://msdn.microsoft.com/en-us/library/aa288412.aspx

A: First You need to add tooltip control to the form
Second attach the tooltip control to some control you want the tooltip to show on (MyControl)
Third do this:
Tooltip1.Show("My ToolTip Text", MyControl)

A: Kevin, if you want to create your own balloon, read this link:Task 3: Showing Balloon tips. There mentioned NativeMethods class with the TOOLTIPS_CLASS constant.

A: This is the code I use:
static HWND hwndToolTip = NULL;

void CreateToolTip( HWND hWndControl, TCHAR *tipText )
{
    BOOL success;

  if( hwndToolTip == NULL )
  {
    hwndToolTip = CreateWindow(  TOOLTIPS_CLASS,
                                 NULL,
                                 WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 CW_USEDEFAULT, CW_USEDEFAULT,
                                 NULL, NULL,
                                 hInstResource,
                                 NULL );
  }

  if( hwndToolTip )
  {
    TOOLINFO ti;

    ti.cbSize   = sizeof(ti);
    ti.uFlags   = TTF_TRANSPARENT | TTF_SUBCLASS;
    ti.hwnd     = hWndControl;
    ti.uId      = 0;
    ti.hinst    = NULL;
    ti.lpszText = tipText;

    GetClientRect( hWndControl, &ti.rect );

    success = SendMessage( hwndToolTip, TTM_ADDTOOL, 0, (LPARAM) &ti );
  }
}

Call CreateToolTip function to create a tool tip for a certain control.

A: If you create your variable private to the whole form, you will be able to call the sub for the and adjust the initialdelay.
Public Class MyForm
Private MyTooltip As New ToolTip
...
Sub ApplyToolTips
'For default
ApplyToolTips (1000)
End Sub

Sub ApplyTooltips (ByVal Delay as Integer)

MyTooltip .InitialDelay = Delay
MyTooltip.AutoPopDelay = 5000
...
MyTooltip.SetToolTip(Me.btnClose, "Close the form")

End Sub

Private Sub Btn_Click(sender As System.Object, e As System.EventArgs) Handles Btn.Click
    Dim PicBox As PictureBox = CType(sender, PictureBox)
    ApplyTooltips (0)
    ApplyTooltips (1000)
End Sub

A: After trying @Keithius's code and finding that the tip showed with mouse-over once the OnClick code had run, I ended up doing this:
Button Click event:
ToolTip1.Show("Text to display", Control);

Button MouseLeave event:
ToolTip1.Hide(Control);

But then I found that if I specified a position - using either explicit x and y co-ords or a Point, it worked as expected:
Button Click event:
ToolTip1.Show("Text to display", Control, Control.Width+20, 0, 2000);

or
ToolTip1.Show("Text to display", Control, new Point(Control.Width+20, 0), 2000);

This is possibly due to the modality of some overloads as mentioned in the Microsoft doco.


text:
Q: Typescript: Precompile modify properties I often encounter the following block of code, sometimes with many fields in a class:
// initialize the private, editable properties so
// they can be manipulated within the class
private readonly aSubject = new SubjectVariant<A>()
private readonly bSubject = new SubjectVariant<B>()
private readonly cSubject = new SubjectVariant<C>()

// make the the streams publicly viewable, but not
// editable, so they don't get manipulated by accident
public readonly a$ = aSubject.asObservable()
public readonly b$ = bSubject.asObservable()
public readonly c$ = cSubject.asObservable()

is there some way to DRY this with a @decorator, while still keeping type suggestions?


text:
Q: crypt module not outputting a SHA512 hash as expected I'm currently using the crypt module in Python to try and create a SHA512 hash in the following manner.
When I run the following line of code from this SO post:
>>> import crypt
>>> crypt.crypt('password', '$6$' + 'salt1234')

Instead of seeing the following output of the salt followed by the SHA512 hash per this SO post:
'$6$salt1234$Zr07alHmuONZlfKILiGKKULQZaBG6Qmf5smHCNH35KnciTapZ7dItwaCv5SKZ1xH9ydG59SCgkdtsTqVWGhk81'

I get the following:
$6FMi11BJFsAc

Below is a screenshot as proof:

Why is it that I'm unable to obtain the SHA512 hash that I'm expecting?

A: From https://docs.python.org/3/library/crypt.html:

This module implements an interface to the crypt(3) routine, which is a one-way hash function based upon a modified DES algorithm; see the Unix man page for further details. […]
Notice that the behavior of this module depends on the actual implementation of the crypt(3) routine in the running system. Therefore, any extensions available on the current implementation will also be available on this module.

and from the documentation of the function itself (emphasis mine):

The optional salt is either a string as returned from mksalt(), one of the crypt.METHOD_* values (though not all may be available on all platforms)

The crypt of the platform you're on probably doesn't support SHA-512. You can confirm this by checking whether crypt.METHOD_SHA512 is in crypt.methods.
>>> crypt.methods
[<crypt.METHOD_CRYPT>]
>>> "\N{CRYING FACE}"
''

One could look at a description of SHAcrypt and make an implementation based on it, or use someone else's.
from passlib.hash import sha512_crypt
sha512_crypt.hash('password')


text:
Q: How to create cross platform continuous(even in background as well) running Timer for iOS and Android in React Native? I want to create a continuous running timer in react native that will run in the background as well in the app if I move to another screen.
I have used react-native-background-timer but that is not working on iOS Platform
is there any way to achieve this?  Any help will be appreciated
Thanks

A: For iOS, the following Swift function executes a code block after a given delay, even if the app is not active:
private var backgroundTaskId = UIBackgroundTaskIdentifier.invalid

func executeAfterDelay(delay: TimeInterval, completion: @escaping(()->Void)){
    backgroundTaskId = UIApplication.shared.beginBackgroundTask(
        withName: "BackgroundSound",
        expirationHandler: {[weak self] in
            if let taskId = self?.backgroundTaskId{
                UIApplication.shared.endBackgroundTask(taskId)
            }
        })

    let startTime = Date()
    DispatchQueue.global(qos: .background).async {
        while Date().timeIntervalSince(startTime) < delay{
            Thread.sleep(forTimeInterval: 0.01)
        }
        DispatchQueue.main.async {[weak self] in
            completion()
            if let taskId = self?.backgroundTaskId{
                UIApplication.shared.endBackgroundTask(taskId)
            }
        }
    }
}


text:
Q: Qt: how to set main window's initial position? I think the normally window manager determines the initial position of the QMainWindow position on the desk top. I want to set the initial position myself. How is this done with Qt on Windows?

A: I believe you're looking for setGeometry.

A: You can restore the window geometry with restoreGeometry(), and the state of docked elements with restoreState(), during the construction of your MainWindow...
    QSettings settings("yourcompany", "yourapp");

    restoreGeometry(settings.value("geometry").toByteArray());
    restoreState(settings.value("state").toByteArray(),YOUR_UI_VERSION);

Then, if you override closeEvent(), you can save the state as follows:
    QSettings settings("yourcompany", "yourapp");

    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState(YOUR_UI_VERSION));

YOUR_UI_VERSION is a constant you should increment when your UI changes significantly to prevent attempts to restore an invalid state.


text:
Q: How to plot intersecting ranges in Excel/R/Matlab Any idea about how to plot intersecting ranges in Excel or R or Matlab
my table looks like this

Start pos  End pos
    5              10
    7              12
  1              3

I would like to color differently all lines and intersections
Thanks
Suleyman

A: I'm not clear what you require, but the series as shown plotted as a stacked bar chart in Excel, with Series 1 and 3 without fill and gradient fill for Series 5 produces:

A: Something like this?
ranges <- data.frame(x=factor(1:3), ymin=c(5,7,1), ymax=c(10,12,3))
library(ggplot2)
ggplot(ranges) +
  geom_linerange(aes(x=x, ymin=ymin, ymax=ymax, color=x),size=2) +
  geom_point(aes(x=x,y=ymin, color=x),shape=1, size=5) +
  geom_point(aes(x=x,y=ymax, color=x),shape=1, size=5) +
  coord_flip() + labs(x="",y="")


text:
Q: Obstacle Avoidance Sensor Data Using the DJI SDK (V4.3.2) I am currently working with the Inspire 2 & the M210 RTK. Can anyone help me in getting the Obstacle Avoidance sensor data output from the drone using the Mobile-SDK? I would like to get the exact distance reading from the object in front of the drone in an constantly updating value. Any code examples? I am relatively new to the DJI SDK so any help would be greatly appreciated. Thanks in advance!

A: Before getting into this, keep in mind that the distance you receive is not perfectly accurate.
There is a few ways you can access the sensors with the mobile SDK.
1/ Traditional interfaces using the obstacle avoidance part of the DJIFlightAssistant

*

*Implement the delegate DJIFlightAssistantDelegate

*Implement the didUpdateVisionDetectionState method

*In the DJIVisionDetectionState object, there is a detectionSectors property which is an array of DJIObstacleDetectionSector which have a obstacleDistanceInMeters.

2/ Using the keys, you can start listening to the Flight Controller key DJIFlightAssistantParamDetectionSectors. The block called will contain an array of DJIObstacleDetectionSector which have a obstacleDistanceInMeters:
guard let detectionSectorsKey = DJIFlightControllerKey(param: DJIFlightAssistantParamDetectionSectors) else {
    // failed to create the key
    return;
}

guard let keyManager = DJISDKManager.keyManager()? else {
    // failed to access the keyManager. You're most likely not registered yet.
    return;
}

keyManager.startListeningForChanges(on: detectionSectorsKey, withListener: self, andUpdate: { (oldValue, newValue) in
    let sectors = newValue?.value as! [DJIObstacleDetectionSector]

    //do stuff.
})


text:
Q: Load Analysis GUI tools for Linux - individual process and overall I need to do some load analysis on a Linux server and would like a nice GUI to help me.  I don't need any fancy history, logging, or alerting.  I need more information than top, and would like it wrapped in one utility or package that is not difficul tto set up.  Something like Process Explorer on Windows:
Statistics

*

*Viewable for Global, individual Processes, and individual Threads

*CPU

*

*Usage

*Kernel Time, User Time

*Context Switch Delta

*Interrupt Delta

*DPC Delta

*Handles

*Threads

*Processes

*Memory

*

*Virtual Memory

*Working Set

*Private

*Page Faults

*I/O

*

*Separate for Network / Disk

*Total/Delta Read/Write

*Open sockets, file handles

A: I'd recommend Observium if you want a pretty web-based display of system information. It covers most of the attributes you wish to track and works well in single-server installs as well as multiple system deployments. Take 20 minutes to set it up and give it a try. There's also a live demo available.

If you need realtime data in a text user interface, look at collectl.

Edit:
Today, I recommend Netdata.
https://my-netdata.io

A: You could get some useful information from utilities like dstat or sar.
Those two are usually easily installed with a package manager like apt.
The best tool I know to analyze Linux performance is Collectd but it requires you to set it up to produce rrd files and to install some apps to show graphs (like kcollectd) or some web cgi (included with collectd)

A: and of course there's collectl - not related to collectd.  no set up required, just install the rpm and /etc/init.d/collectl start.  collects far more data than sar and has no external dependencies.
re rrd - be careful as it does NOT plot all the data you collect, that is if you collect it fairly frequently like collectl does, about 1 sample every 10 seconds.  Of course there are a lot of people who are happy collecting data every 5-10 minutes and while it gives a warm feeling that everything is fine, there could be a lot more going on that you're missing by not being finer grained in your monitoring.
-mark