text:
Q: ¿Cómo corregir un error al crear un histograma? Necesito crear un histograma a partir de unos datos de posición y velocidad. EL código que utilizo es
import numpy as np
import matplotlib.pyplot as plt

g = np.genfromtxt('posandvel2.txt')
px=g[:,0]
py=g[:,2]
vx=g[:,1]
vy=g[:,3]
d=np.sqrt(px**2+py**2)
v=0.5*(vx**2+vy**2)

plt.hist(v, bins=30)
plt.title("Histograma de energía cínetica al momento 0")
plt.show()

plt.hist(d, bins=30)
plt.title("Histograma de distancia al momento 0")
plt.show()

#N-20
f = np.genfromtxt('posandvel.txt')
px=f[:,0]
py=f[:,2]
vx=f[:,1]
vy=f[:,3]
d=np.sqrt(px**2+py**2)
v=0.5*(vx**2+vy**2)

plt.hist(v, bins=30)
plt.title("Histograma de energía cínetica al momento N-20")
plt.show()

plt.hist(d, bins=30)
plt.title("Histograma de distancia al momento N-20")
plt.show()

Y el error que se me presenta es el siguiente:

ValueError                                Traceback (most recent call last)
/home/wamba/Documentos/UdeC/11° Semestre/Software/ayuda3.py in <module>()
     11 v=0.5*(vx**2+vy**2)
     12
---> 13 plt.hist(v, bins=30)
 14 plt.title("Histograma de energía cínetica al momento 0")
 15 plt.show()

/home/wamba/.local/lib/python2.7/site-packages/matplotlib/pyplot.pyc in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, >     orientation, rwidth, log, color, label, stacked, hold, data, **kwargs)
   3079                       histtype=histtype, align=align, >     orientation=orientation,
   3080                       rwidth=rwidth, log=log, color=color, >     label=label,
-> 3081                       stacked=stacked, data=data, **kwargs)
 3082     finally:
 3083         ax._hold = washold

/home/wamba/.local/lib/python2.7/site-packages/matplotlib/__init__.pyc in >inner(ax, *args, **kwargs)
1896                     warnings.warn(msg % (label_namer,      func.__name__),
1897                                   RuntimeWarning, stacklevel=2)
-> 1898             return func(ax, *args, **kwargs)
1899         pre_doc = inner.__doc__
1900         if pre_doc is None:

/home/wamba/.local/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in >hist(***failed resolving arguments***)
  6193             # this will automatically overwrite bins,
  6194             # so that each histogram uses the same bins
  -> 6195             m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
   6196             m = m.astype(float)  # causes problems later if it's an >int
   6197             if mlast is None:

/home/wamba/.local/lib/python2.7/site-packages/numpy/lib/function_base.pyc in >histogram(a, bins, range, normed, weights, density)
 665     if mn > mx:
 666         raise ValueError(
--> 667             'max must be larger than min in range parameter.')
 668     if not np.all(np.isfinite([mn, mx])):
 669         raise ValueError(

 ValueError: max must be larger than min in range parameter.

Los textos necesario estan en pastebin1
y pastebin2

A: El problema estaba en los datos de entrada y en la forma que los lees. Para futura referencia pongo aquí las tres primeras líneas de uno de los ficheros de entrada:
pos(x)          vel(x)              pos(y)                  vel(y)
0.02071,        -0.2938,            -8.033,                  -0.6579
3.308,           0.04636,           -5.784,                  -0.3808

Como vemos tiene una línea inicial que no son datos, sino una especie de cabecera, y después los datos en sí llevan una coma tras cada uno de ellos (salvo el último de la línea).
Tal como los lees con genfromtxt(), sin más opciones, lo que espera numpy es que todo sean datos y separados por espacios o tabuladores. Ya que no es así, el resultado de la lectura contiene gran cantidad de NaN (datos que no ha podido interpretar como números). Por ejemplo:
>>> g = np.genfromtxt('posandvel2.txt')
>>> print(g)
[[      nan       nan       nan       nan]
 [      nan       nan       nan -0.6579  ]
 [      nan       nan       nan -0.3808  ]
 ....

Así que no es de extrañar que no pueda pintar los histogramas.
La solución consiste en pasarle parámetros a getfromtxt() que le informen de cuántas líneas componen la cabecera (para que no intente leerla) y cuál es el delimitador entre datos (basta decirle que es la coma, pues los espacios los ignorará al tratar de leerlos como float, que es el tipo de datos que supone por defecto). Es decir:
g = np.genfromtxt('posandvel2.txt', skip_header=1, delimiter=",")

Y análogamente para la lectura de f. Con ese cambio ya funciona. Como muestra, uno de los histogramas obtenidos:


text:
Q: Why appear variable undefined after trying do something with get input? I have the following problem to solve, when I start writing text in input, this one should turn red. Unfortunately, for unknown reasons, the variable is unidentified. Perhaps the problem is that js is not able to define the variable as input. I don't understand something here. Please help.
var input_Login = document.getElementsByTagName('input')[0];

console.log(input_Login);

function inputCheck(input_Login){
    input_Login.style.color='pink';
}

var doit = input_Login.addEventListener('oninput', inputCheck);

A: You need to use the event input and the keyword thisin your function, see the example below:

var input_Login = document.getElementsByTagName('input')[0];

console.log(input_Login);

function inputCheck(input_Login){
    this.style.color='pink';
}

var doit = input_Login.addEventListener('input', inputCheck);
<input type="text">

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I make the trapezoidal shadow on a rectangle as shown in the image? Here is my html and css. I am able to stack one div onto another in order to create something like given in the image.I am struggling to add a trapezoidal shadow(3-d) as shown in the image.

.another {
  background-color: #9D8F7E;
  height: 50px;
  position: relative;
  top: 30px;
  margin: 50px 0px -48px 0px;
  width: 90px;
  border: 1px ridge black;
}

A: clip-path can do this:

.box {
  --s:20px;

  width:300px;
  height:200px;
  background:red;
  border-left: var(--s) solid;
  border-right:var(--s) solid;

  clip-path:polygon(
      0 var(--s)                 ,var(--s) 0,
      calc(100% - var(--s)) 0   ,100% var(--s),
      100% calc(100% - var(--s)),calc(100% - var(--s)) 100%,
      var(--s) 100%             ,0 calc(100% - var(--s)))
}

to make a shadow effect you can try pseudo element with some filter:

.box {
  width:300px;
  height:200px;
  background:red;
  margin:0 30px;
  position:relative;
}
.box:before,
.box:after{
  content:"";
  position:absolute;
  z-index:-1;
  top:1px;
  bottom:1px;
  width:30px;
  filter:blur(3px);
  background:#000;
}
.box:before {
  right:100%;
  transform:perspective(100px) rotateY(-35deg);
  transform-origin:right;
}
.box:after {
  left:100%;
  transform:perspective(100px) rotateY(35deg);
  transform-origin:left;
}


text:
Q: Referencing javascript from trac wiki I have a problem running javascripts from trac.
I know there are security issues around this, but my trac installation is only used as an intranet.
I have got the following code to work (requires setting rendering_unsafe_content = true under [wiki] in trac.ini):
{{{
#!html

<script type="text/javascript" >
document.write("This is a test")

</script>

}}}

However, replacing this with the javascript in a seperate file will fail:
{{{
#!html

<script type="text/javascript" src="/tracproject/htdocs/test.js" >

</script>

}}}

where tracproject is the root folder of trac and test.js contains document.write("This is a test").
Any clues?

A: Have you tried the 'Add Headers Plugin' (http://trac-hacks.org/wiki/AddHeadersPlugin) ?  It looks like it allows you to do include custom javascript like you want but in a more straightforward way than having to modify templates directly.

A: The option is [wiki] render_unsafe_content (see documentation). You can reference the file in your site htdocs directory on the path /tracproject/chrome/site/test.js. I tried your example just now and it work correctly once the src path is changed.
See the TracInterfaceCustomization page for more details.


text:
Q: how to identify file system running on a partition I am not very clear with identifying the partition type or filesystem
residing on it
here is what lvscan reports me
 ACTIVE            '/dev/virtualization/vm1' [100.00 GiB] inherit
 ACTIVE            '/dev/virtualization/vm2' [150.00 GiB] inherit
 ACTIVE            '/dev/virtualization/vm3' [50.00 GiB] inherit
 ACTIVE            '/dev/virtualization/vm4' [100.00 GiB] inherit

How can I identify the file system running on it.
It is a Ubuntu server and the above are LVM partitions created by virt-manager.
The output of mount command is
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
nfsd on /proc/fs/nfsd type nfsd (rw)

The output of blkid as some one requested below is
blkid /dev/sda1
/dev/sda1: UUID="6876c294-0c70-4b4e-87a2-636ea19e5ed6" TYPE="ext4"   but this did not helped me much.Also I did
blkid /dev/virtualization
  but there was no result i.e. nothing in output.
  Also the output of file command
I did file /dev/virtualization/*
site4:      symbolic link to `../mapper/virtualization-site4'
site3: symbolic link to `/dev/mapper/virtualization-site3'
site2:   symbolic link to `../mapper/virtualization-site2'
site1: symbolic link to `../mapper/virtualization-site1'

What more should I be doing?

A: blkid the device or use file otherwise (like dd if=/dev/sde1 bs=1M count=1 | file -)

A: You could try just to mount them. (mount /dev/virtualization/vm1 /mnt/tmp). Kernel will detect (actually, not detect, but try all supported filesystems) and you'll see fs type in the output of mount command.

A: file -s /dev/mapper/virtualization-site4
Because man file told me:

Specifying the -s option causes file to also read argument files which are block or character special files.  This is useful for determining the filesystem types  of the data in raw disk partitions, which are block special files.

However in your case, you will be led by a symlink to /dev/dm-*.

A: Well, if they are VM file systems, just login to the VM and see what file systems are used.


text:
Q: Getting an undefined response from a Google Sheets call? Here's what I'm doing:
var oauth_token = 'hidden_for_stack_overflow';

var the_sheet = '';

fs.readFile('usethesecreds.json', (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);

    const {client_secret, client_id, redirect_uris} = JSON.parse(content).installed;
    const auth = new google.google.auth.OAuth2(client_id, client_secret, redirect_uris[0])
    auth.setCredentials({ access_token: oauth_token })
    the_sheet = google.google.sheets({version: 'v4', auth});
  });

// Get cells
function get_cells_MainSheet(spreadsheetId, range) {

    var response = the_sheet.spreadsheets.values.get({
        spreadsheetId: spreadsheetId,
        range: range
    })

    console.log(response.status)
    console.log(response.statusText)

}

All I'm getting from those two console.logs is "undefined".
The spreadsheetId is correct, range is 'A:P'...
I think my problem is that I'm storing the_sheet as a global variable. But I'm not sure what to do for an alternative.


text:
Q: Multiple selects with a single scan over an expensive table expression How do I (efficiently) do multiple selects over an expensive table expression?
I have a table with a structure like this
CREATE TABLE facts (
    subject_id INT,
    visit_id INT,
    study_id INT,
    provider_id INT,
    variable_id INT,
    value TEXT
)

i.e. each row is a measurement that has a number of dimensions and a value. The facts table is large, but each dimension is much smaller, e.g. the cardinality of SELECT DISTINCT subject_id FROM facts could be a few hundred.
Now I want to find the unique dimension values for a subset of facts, i.e. the ids of the distinct subjects, visits, providers and variables for study_id = X. That is simple to query for by doing multiple queries as in
SELECT DISTINCT subject_id FROM facts WHERE study_id = X;
SELECT DISTINCT visit_id FROM facts WHERE study_id = X;
SELECT DISTINCT provider_id FROM facts WHERE study_id = X;
SELECT DISTINCT variable_id FROM facts WHERE study_id = X;

but each query then has to do a separate scan over the facts table (or an index). (The cardinality of SELECT * FROM facts WHERE study_id = X is also large, though not as large as the entire table.)
Is there some way to combine these queries so that the db only has to do one scan over the facts table and collect all the distinct dimension id's in one go?
So far I tried using a common table expression, but that still results (in Postgres) in multiple scans over the CTE so it doesn't help. e.g:
WITH selected AS (SELECT * FROM facts WHERE study_id = X)
SELECT DISTINCT subject_id, 1 FROM selected
UNION ALL SELECT DISTINCT visit_id, 2 FROM selected
UNION ALL SELECT DISTINCT provider_id, 3 FROM selected
UNION ALL SELECT DISTINCT variable_id, 4 FROM selected

Is there any way to have the DB only do a single scan over the facts and collect all needed results? I'm specifically interested in Postgres and Oracle support.

A: This could be an approach in Oracle.
setup:
create table test(a, b, c) as (
    select  1,  2,  3 from dual union all
    select  1, 20, 30 from dual union all
    select  1,  2, 30 from dual union all
    select  1, 20, 30 from dual union all
    select 10,  2,  3 from dual union all
    select 10, 22,  3 from dual union all
    select  1, 20,  3 from dual
)

query:
select distinct column_name, column_value
from test
unpivot (column_value for column_name in  (a, b, c) )

plan:
-----------------------------------------------------------------------------
| Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |      |    21 |   336 |    10  (10)| 00:00:01 |
|   1 |  HASH UNIQUE         |      |    21 |   336 |    10  (10)| 00:00:01 |
|*  2 |   VIEW               |      |    21 |   336 |     9   (0)| 00:00:01 |
|   3 |    UNPIVOT           |      |       |       |            |          |
|   4 |     TABLE ACCESS FULL| TEST |     7 |   273 |     3   (0)| 00:00:01 |
-----------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("unpivot_view_006"."COLUMN_VALUE" IS NOT NULL)

result:
C COLUMN_VALUE
- ------------
B           22
C            3
C           30
A           10
A            1
B            2
B           20

I made the test with a very small table; here the plan shows a single full scan of the table, but followed by the unpivot and an hash unique.
For the same table, the solution with the UNION does:
select distinct a , 'a' from test union
select distinct b , 'b' from test union
select distinct c , 'c' from test

----------------------------------------------------------------------------
| Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------
|   0 | SELECT STATEMENT    |      |    21 |   273 |    12  (75)| 00:00:01 |
|   1 |  SORT UNIQUE        |      |    21 |   273 |    12  (75)| 00:00:01 |
|   2 |   UNION-ALL         |      |       |       |            |          |
|   3 |    TABLE ACCESS FULL| TEST |     7 |    91 |     3   (0)| 00:00:01 |
|   4 |    TABLE ACCESS FULL| TEST |     7 |    91 |     3   (0)| 00:00:01 |
|   5 |    TABLE ACCESS FULL| TEST |     7 |    91 |     3   (0)| 00:00:01 |
----------------------------------------------------------------------------


text:
Q: Hadoop HDFS connection in PowerCenter I have installed Cloudera's Hadoop QuickStart VM and I am attempting to pass records from my local database to HDFS using a PowerCenter mapping.
I've set up the Hadoop_HDFS_Connection in PowerCenter Workflow Manager but when I run the workflow I get the following error: "Unable to establish a connection with the specified HDFS host".  It gives a "java.net.ConnectionException" error when trying to connect to the host name and port.
I think the error may be in the hostname notation. On Cloudera Manager on the VM, the host name is listed as 'localhost.localdomain' but I don't know how to translate this in the PowerCenter connection settings.
Anybody got this connection to work?
Many thanks.
Brian


text:
Q: WooCommerce Load and customize archive-product.php from my Plugin Folder I am trying to load template files from my-plugin folder instead of using default woocommerce template. I want to customize the shop page base from my-plugin folder template structure, so i edit the archive-product.php to comment and check which display blank page or not but it load the default woocommerce template (archive-product.php). I already moved the template files to the my-plugin/woocommerce/ folder Here is my code i tried
 function cc_woocommerce_locate_template($template, $template_name, $template_path) {

        global $woocommerce;
        global $post;
        $plugin_path = untrailingslashit(plugin_dir_path(__FILE__)) . '/woocommerce/';
    //returns my-plugin folder with base file name echo $plugin_path;
               //   echo $template_name;
            if (file_exists($plugin_path . $template_name)) {
                $template = $plugin_path . $template_name;
               // var_dump($template);
                return $template;
            }

        return $template;
    }

and the hook i pointed is
add_filter('woocommerce_locate_template', 'cc_woocommerce_locate_template', 1, 3);

A: I tested the provided code and it runs without problems, so in such situations it is best to start over. Create a new plugin and paste the code below. It contains two filters:

wc_get_template_part - for templates used in loop
woocommerce_locate_template   - for all other templates

//
// get path for templates used in loop ( like content-product.php )
add_filter( 'wc_get_template_part', function( $template, $slug, $name )
{

    // Look in plugin/woocommerce/slug-name.php or plugin/woocommerce/slug.php
    if ( $name ) {
        $path = plugin_dir_path( __FILE__ ) . WC()->template_path() . "{$slug}-{$name}.php";
    } else {
        $path = plugin_dir_path( __FILE__ ) . WC()->template_path() . "{$slug}.php";
    }

    return file_exists( $path ) ? $path : $template;

}, 10, 3 );

// get path for all other templates.
add_filter( 'woocommerce_locate_template', function( $template, $template_name, $template_path )
{

    $path = plugin_dir_path( __FILE__ ) . $template_path . $template_name;
    return file_exists( $path ) ? $path : $template;

}, 10, 3 );

Now create a subfolder woocommerce inside the plugins main folder and copy inside original files archive-product.php and content-product.php. And finally, make some small modification ( echo something ) in that files just to see if they are loaded. I tested this example and templates are loaded with no problems in the following hierarchy:

theme/template_path/template_name
theme/template_name
plugin/template_path/template_name
default/template_name

A: I found a solution for archive-product.php or single-product.php load from plugin. I think it should work.
public function include_template_function( $template_path ) {
    if ( get_post_type() == 'product' ) {
        if ( is_single() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array ( 'single-product.php' ) ) ) {
                $template_path = $theme_file;
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . 'woocommerce/single-product.php';
            }
        }

        if ( is_archive() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array ( 'archive-product.php' ) ) ) {
                $template_path = $theme_file;
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . 'woocommerce/archive-product.php';
            }
        }
    }
    _log($template_path);
    return $template_path;
}

add_filter( 'template_include', array($this, 'include_template_function' ), 100 );


text:
Q: How to use rateable in silverstripe I am newbie in silver stripe.
I have added the extension
https://github.com/sheadawson/silverstripe-rateable
But, I am unable to understand how to use this extension....
I am unable to create the data object... please help....
"Then in your templates you can use $RateableUI, when in the context of your rateable object to render the star rating UI"
this step i am unable to understand
Regards

A: never used this extension but the way I see it you could do for example:
Add the extension to the DataObjects you want in _config.php:
Object::add_extension('ApplePage', 'Rateable');
Object::add_extension('Apple', 'Rateable');

Remember to run dev/build.
Here ApplePage is a Page with a $has_many relations 'Apples' => 'Apple'
Then in you ApplePage.ss template you could use something like:

Rate my Apple Page: $RateableUI

Apple list

   <% loop %>

$Name (Rating: $RateableUI)

   <% end_loop %>


text:
Q: Strange "command not found" and "No such file or directory" errors Very strange errors of multiple forms:

*

*Running brew install c-ares fails with command not found, seemingly not even executing brew:
$ brew install c-ares
-bash: brew install c-ares: command not found

Yet brew install cmake executes brew as expected:
$ brew install cmake
Warning: Treating cmake as a formula. For the cask, use homebrew/cask/cmake
Warning: cmake 3.25.1 is already installed and up-to-date.
To reinstall 3.25.1, run:
  brew reinstall cmake

*Cannot prepend /usr/local/opt/qt5/bin to $PATH with the error No such file or directory:
$ export PATH=/usr/local/opt/qt5/bin:$PATH
-bash: export PATH=/usr/local/opt/qt5/bin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/Library/Apple/usr/bin: No such file or directory

That folder does exist:
$ [ -d /usr/local/opt/qt5/bin ] && echo "exists"
exists

As do all the others on $PATH:
$ echo $PATH
/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/Library/Apple/usr/bin
$ for i in $(echo $PATH | awk -F: '{for (i=1; i<=NF; i++) { print $i; }}'); do if [ -d "$i" ]; then echo "$i exists"; else echo "$i does not exist"; fi; done
/usr/local/bin exists
/System/Cryptexes/App/usr/bin exists
/usr/bin exists
/bin exists
/usr/sbin exists
/sbin exists
/Library/TeX/texbin exists
/usr/local/MacGPG2/bin exists
/opt/X11/bin exists
/Library/Apple/usr/bin exists

Yet adding /tmp works:
$ export PATH=/tmp/:$PATH
$ echo $PATH
/tmp/:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/Library/Apple/usr/bin

*Same errors with zsh:
$ zsh
% brew install c-ares
zsh: command not found: brew install c-ares
% brew install cmake
Warning: Treating cmake as a formula. For the cask, use homebrew/cask/cmake
Warning: cmake 3.25.1 is already installed and up-to-date.
To reinstall 3.25.1, run:
  brew reinstall cmake
% export PATH=/usr/local/opt/qt5/bin:$PATH
zsh: no such file or directory: export PATH=/usr/local/opt/qt5/bin:/tmp/:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/Library/Apple/usr/bin

I'm quite baffled and don't know how to debug shell built-ins.
Nothing comes to mind of what recently changed that could cause this. I upgraded to Ventura 13.1 today hoping this would go away, but it was happening before the upgrade and continues to happen.
I tried restarting and it didn't help.
System information:
% system_profiler SPSoftwareDataType SPHardwareDataType | grep -v -e UUID -e UDID -e 'User Name' -e 'Computer Name' -e Serial
Software:

    System Software Overview:

      System Version: macOS 13.1 (22C65)
      Kernel Version: Darwin 22.2.0
      Boot Volume: MainDisk
      Boot Mode: Normal
      Secure Virtual Memory: Enabled
      System Integrity Protection: Disabled
      Time since boot: 22 minutes, 2 seconds

Hardware:

    Hardware Overview:

      Model Name: MacBook Pro
      Model Identifier: MacBookPro15,1
      Processor Name: 6-Core Intel Core i7
      Processor Speed: 2.6 GHz
      Number of Processors: 1
      Total Number of Cores: 6
      L2 Cache (per Core): 256 KB
      L3 Cache: 9 MB
      Hyper-Threading Technology: Enabled
      Memory: 16 GB
      System Firmware Version: 1916.60.2.0.0 (iBridge: 20.16.2059.0.0,0)
      OS Loader Version: 564.40.4~55
      Activation Lock Status: Enabled

A: As per the comment from @gidds, both of the failing commands (export and brew install) were copy/pasted from the compiling Wireshark page. Instead, manually duplicating the commands by typing them solved the issue. It seems some whitespace or control characters from the Wireshark page cause both zsh and bash on macOS to interpret the whole command as the name of the command to run instead of word-splitting.


text:
Q: Is there a relatively easy way to find whether two plane curves have a "common component"? I am interested in determining all intersections between two plane curves f(x,y)=0 and g(x,y)=0.  (f is degree 4, and g is degree 3.) I would like to use Bezout's Theorem.
I have found 12 total intersections by hand (including at infinity and including multiplicities), and I would be finished, except for that bit of Bezout's Theorem where we are required to assume  there is no common component between the two curves.
My problem is: I am new to this stuff, and my curves are pretty complicated. They look like this:
$0=c_1x^4+c_2x^3+c_3x^3y+c_4x^2y^2+c_5x^2y+c_6xy^3+c_7xy^2+c_8xy+c_9y^3+c_{10}y^4$
$0=d_1x^3+d_2x^2y+d_3xy^2+d_4x+d_5y^3+d_6y$
where the (real) coefficients $c_k,d_k$ are given in terms of some unknown constants.
My question is: In general, how do people determine whether two curves have a "common component"? All of the examples I have seen are curves where it is incredibly easy to find factors...Is there a relatively painless way to show that two curves do not have a common component, even when the curves themselves are quite complicated?
Thank you


text:
Q: Android: How to use intent-filter to process a PDF email attachment? I've been trying to have either the email or gmail applications give me the option of using my application to open a PDF attachments to no avail. My intent-filter looks like:
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:mimeType="application/pdf" />
        </intent-filter>

When I look in the emulator, the activity manager broadcasts this:
02-04 15:45:03.626: INFO/ActivityManager(59): Starting activity: Intent { act=android.intent.action.VIEW dat=content://com.android.email.attachmentprovider/1/17/RAW flg=0x80001 }

What I'm I doing wrong?
Thanks in advance...

A: I'm having a similar problem opening csv files from mail (Using Android 2.2). It finally worked using
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="*/*" android:host="*" android:pathPattern=".*.csv" />
</intent-filter>

Changing anything in the data tag made it impossible to call my application from the e-mail application on opening the csv file.
You might also want to check Intent filter to download attachment from gmail apps on Android


text:
Q: Does importing the same library repeatedly impact performance? I'm importing a library from a CDN in main.js:
import * as foo from "https://cdn.jsdelivr.net/npm/foo";

However, that same library is also used in all other modules, a.js, b.js etc... Thus, in all of them, I'm repeating the import.
Does the browser sends a request to the CDN for every import, impacting performance? Or does the browser imports the library just once, and keeps it in memory for the import in the other modules?

PS: This could be a XY problem... my real original question was how to share a single import between several modules. I found solutions such as creating a global (window.foo = foo), but they seemed a bit hacky.

A: As said from me in the comments, and asked from op:
You can test that very simple by your own.
Create a webpage with a bunch of imports to the same library/module.
Open the developer tools and view the network tab.
How many http requests are done to the the lib/url you are importing?
TL;DR: There are no additional requests for each import statement.


text:
Q: Как создать папку с текстовыми файлами в проекте и пользоваться ими? Хочу добавить в проект несколько csv файлов и пользоваться ими, как текстовыми ресурсами. Ну и чтобы лежали вместе в папке для порядка. Создать папку проблем нет.
контекстное меню проекта ➙ Добавить ➙ Создать папку
Файлы тоже создаются
контекстное меню папки ➙ Добавить ➙ Создать элемент ➙ элементы Visual C# ➙ Текстовый файл
Но как пользоваться их содержимым?

A: https://stackoverflow.com/questions/3314140/how-to-read-embedded-resource-text-file
После добавления ресурса необходимо задать в дизайнере свойство Действия при сборке значением Внедренный ресурс (именование в русифицированной Visual Studio, в англоязычной будут Build Action и Embedded Resource).
Для извлечения текстового файла понадобится использовать метод GetManifestResourceStream() класса Assembly, экземпляр которого соответствующий исполняемый сборке можно получить статическим методом Assembly.GetExecutingAssembly(). Не забудьте также что для использования Assembly нужно вписать using System.Reflection в заголовок модуля или обращаться к нему System.Reflection.Assembly.
GetManifestResourceStream() вернет Stream. Зная, что мы имеем дело с текстом, либо считываем System.IO.StreamReader весь файл в экземпляр string.
using System.Reflection;
using System.IO;
...
public static string GetTextResource(string @namespace, string folder, string filename)
{
    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                                $"{@namespace}.{folder}.{filename}"))
    {
        using (StreamReader sr = new StreamReader(stream))
        {
            return sr.ReadToEnd();
        }
    }
}

Либо организуем другую логику считывания файла.

A: Используйте механизм ресурсов.
Зайдите в свойства проекта, вкладка "Ресурсы", добавьте новый файл ресурсов (если его ещё нет), добавьте новый или существующий текстовый файл.
После этого можно обращаться к этому файлу как к Properties.Resources.<Имя файла>.
Т.е. если Вы добавили файл main.csv, то можно будет обратиться к его содержимому как к Properties.Resources.main. Это будет read-only строка с содержимым файла.


text:
Q: How do I append a Carriage Return character to a string? I am writing to a USB and need to append with the carriage return character.
Right now I'm doing:
usbSerial.write("CMD01".toByteArray())

But it needs CR added to the end.  How do I add that to the current string?

A: Did you try use the \r:
usbSerial.write("CMD01\\r".toByteArray())


text:
Q: Model does not have values for ListBoxFor in MVC4 I am able to display values in ListBoxFor control from controller to view. However when I move values from one listbox to another and post the view the model on controller side does not preserve the values in the listboxes.
Here is my Model
namespace MvcApplication1.Models
{
  public class EmployeeClass
  {
    public int EmpCode { get; set; }
    public string EmpName { get; set; }
  }

   public class EmployeeViewModel
  {
    public string Department { get; set; }
    public list<EmployeeClass> AvailalableEmployee { get; set; }
    public list<EmployeeClass> SelectedEmployee { get; set; }

    public int [] AvailableEmpCodeArray { get; set; }
    public int [] SelectedEmpCodeArray { get; set; }
  }
}

Here is my Controller
namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult EmployeeDisplayTool()
        {
            EmployeeViewModel model = new EmployeeViewModel();

            model.Department = "Techology"
            model.AvailalableEmployee.Add(new Employee(1,"Emp1"));
            model.AvailalableEmployee.Add(new Scenario(2,"Emp2"));
            model.AvailalableEmployee.Add(new Scenario(3,"Emp3"));

            model.SelectedEmployee.Add(new Scenario(4,"Emp4"));
            model.SelectedEmployee.Add(new Scenario(5,"Emp5"));
            model.SelectedEmployee.Add(new Scenario(6,"Emp6"));
            return View(model);
        }
        [HttpPost]
        public ActionResult EmployeeDisplayTool(EmployeeViewModel model)
        {
            //model.Department is populated as "Technology"

            //All of the follownig collections are null.
            //model.AvailalableEmployee is null.
            //model.AvailableEmpCodeArray is null.

            //model.SelectedEmployee is null.
            //model.SelectedEmpCodeArray is null.
        }
    }
}

Here is my View and JavaScript
@using (Html.BeginForm())
{

        @Html.TextBoxFor(m => Model.Department, new { id = "txtDepartment" })

       @Html.ListBoxFor(m => Model.AvailableEmpCodeArray, new MultiSelectList(Model.AvailalableEmployee, "EmpCode", "EmpName", Model.AvailableEmpCodeArray), new { id = "lbxAvailableEmployees" })

        <input type="button" id="btnSelectEmployee" value=" >> "/>

        <input type="button" id="btnUnSelectEmployee" value=" << "/>

         @Html.ListBoxFor(m => Model.SelectedEmpCodeArray, new MultiSelectList(Model.SelectedEmployee, "EmpCode", "EmpName", Model.SelectedEmpCodeArray), new { id = "lbxSelectedEmployees" })

}

A: Inside your HttpPost action you cannot expect the AvailalableEmployee and SelectedEmployee collections to be populated. That's due to the nature of how HTML works. Only the selected values are sent to the server when you submit the form. The text values of the select fields are never sent to your server when you submit the form.
So all you can hope of getting populated inside this HttpPost action is the AvailableEmpCodeArray and the SelectedEmpCodeArray collections. They will contain the values of the selected items in the corresponding select fields. Notice that I have bolded selected. This means that only if you select any items in the corresponding boxes those collections will be bound. If you don't select anything, they will remain null and that's perfectly normal.
Here's an example of the user that has selected nothing. He just used the << and >> buttons to toggle the values between the lists, but please notice how absolutely nothing is selected:

Notice how nothing is selected? So that's all you will get in your controller action - nothing.
Now please compare with the following screenshot:

Do you see the difference? Notice how the user explicitly selected the Emp2, Emp5 and Emp6 values (using the Shift key to select multiple values)? That's what you're gonna get inside your HttpPost action. The AvailableEmpCodeArray collection will contain a single element with the value of 2 and the SelectedEmpCodeArray will contain 2 elements with the values of 5 and 6.
Now to your second problem. If you intend to redisplay the same view from your HttpPost controller action the first thing you need to ensure is that you have assigned values to the AvailalableEmployee and SelectedEmployee collections. This should be done the same way you did in the HttpGet action:
model.AvailalableEmployee.Add(new Employee(1,"Emp1"));
model.AvailalableEmployee.Add(new Scenario(2,"Emp2"));
model.AvailalableEmployee.Add(new Scenario(3,"Emp3"));

model.SelectedEmployee.Add(new Scenario(4,"Emp4"));
model.SelectedEmployee.Add(new Scenario(5,"Emp5"));
model.SelectedEmployee.Add(new Scenario(6,"Emp6"));

or if those values are coming from a database you will have to re-query this database inside the HttpPost action because those values, as I already explained, will never get bound from the view.


text:
Q: Magento 1.9.2.1 site caching literally everything. Must manually reload cart, admin panel, etc. to see changes I've got a client who has a very odd problem that appeared out of virtually nowhere. It seems that their site is caching absolutely everything that could possibly be cached. I've turned Magento cache off and talked to the hosting company, and there is apparently no caching set up for the site right now.
Right now, if you place an item in your cart for the first time, everything seems to work fine. If you attempt to remove an object, the cart will appear to still have the item in it. The only way to get the cart to update is to refresh the browser 2 or 3 times. If you attempt to put another item into the cart, you must refresh the browser to get it to appear in the cart.
If you log into the admin panel and try to clear cache, reindex, turn on path hints, or really do anything that would show that you updated anything on the back end, you have to refresh the browser to get it to show up. So, for instance, say you tell the site to reindex the search engine. The site will act like it's reindexing, then do the usual auto-refresh, but the search engine will still appear to need indexing (ie it will be red) until you hit F5 to reload. Then the search engine index warning will turn green.
I'm at a loss at this point for why the entire site is caching like this. I have a dev site that is roughly identical to this live site and it's not having any of these problems. The only difference is that the dev site is hosted with a different company entirely.
The only StackExchange post I've seen that resembles this issue is here, but the reported fix didn't work for me. Any help is much appreciated.

A: Sounds like local browser caching to me rather than server side.  Try sending the following headers for each page to disable browser caching.
<?php
header('Cache-Control: max-age=0, no-cache, must-revalidate');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');

A: So, we finally figured out the issue. The site was being cached by a 3rd party security application that sat between the DNS and the server. We had no idea that this caching had been turned on, and the hosting company wasn't seeing any caching on their end, so it was driving us crazy.
So anyone who runs into this problem in the future, make sure to check if there are any 3rd party security apps running separate from your host.


text:
Q: Javascript Regex abbreviation detection/ Count words in sentence? I am using a regex in order to split up a text into its sentences. This is my Code:
elem.replace(/([.?!])\s+(?=[A-Z])/g, "$1|").split("|");

Problem is that e.g. an abbreviation like. "Appl. No." or "Doc." are recognized as a sentence.
Is there any method to prevent such behavior?
Does anyone know e.g. how to modify the regex to split only if a sentence contains more than 1 word?

var text= "hello eveyone. This is a text, with a Abbreviation. Appl. No. is 2134."

result=text.replace(/([.?!])\s+(?=[A-Z])/g, "$1|").split("|");

/*
Result is "hello eveyone., This is a text, with a Abbreviation., Appl., No., is 2134."
But it should be:
Result is "hello eveyone., This is a text, with a Abbreviation., Appl. No. is 2134."
*/


text:
Q: add Item to selectItem after add my datasource I'm trying to add one option per default in my selectItem, it has binding one datasource and after do that i try to add one option per default. My problem is that i always see the items in the datasource but never my default option. Those are my lines of code :
Option 1
LinkedHashMap<String, String> valueMap= new LinkedHashMap<String, String>();
valueMap.put("null","null3");
branchSelectionItem.setValueMap(valueMap);

Option 2
Record rec = new Record();
rec.setAttribute("Name","asdad");
branchDs.addData(rec);
branchSelectionItem.setOptionDataSource(branchDs);

I used to methods first one try to add with valueMap option and the second one is add one record to my datasource, but any of them works. Any Idea ?
thanks a lot!!

A: Ok , i solved this problem adding a empty value for select again for default.
 branchSelectionItem.setAllowEmptyValue(true);


text:
Q: Example of php query strings updating html img src using GET? I have a site, www.example.com/index.html
It has two text input fields for users to paste img/gif urls
Clicking a submit button uses javascript to create a div with an img tag in it in my html file and it also converts the user input value into the div's img's src.
How would the submit button also update the site url to example.com/index.html?gif=someurl.com&gif2=someurl2.com
This way the user could copy and paste the url with query parameters and share it with someone and when that someone click the link, they're brought to the site, both of the divs would have img src's automatically loaded.

A: It is not a "php query string".
It is URL with params, not strictly related to PHP or any other backend language.
If you will change the url via:
window.location = 'url';

The browser will navigate to the new page.
I recommend updating URL hash with
window.location.hash = 'url';

The at the beggining of your javascript, check if hash matches the pattern and contains a properties of the image file. The execute your function which shows IMG with the values.

A: You cannot update the url dynamically unless you have a hash in it (like example.com/index.html#gif=someurl.com&gif2=someurl2.com).
Here's an example of how you would do it with a hash:
if(window.location.hash) {
    var imgArray = window.location.hash.split("&gif=");

    for(var i=0; i<imgArray.length; i++) {
        $("#imgDiv").append($("<img>").attr("src", imgArray[i]));
    }
}


text:
Q: iPhone - core motion rotationRate Using just the rotationRate property of Core Motion or Gyroscope is it possible to extract how much radians (or degrees if you like) the device rotated?
I have tried to do a timed sampled of Core Motion data, for example, sampling it 5 times per second so I know that there's 0.2seconds between each reading. Then if I have a rotationRate of 0.5 radians per second from one read to another, in theory I could divide this by 5 and know now much radians the device rotated since the last time.
This seems logical, but the results have nothing to do with reality. Rotating the device 90 degrees will produce results telling me that the device rotated 100 times less than that.
Is it possible to extract how much the device rotated just by looking at rotationRate?
What am I missing?

A: Need more space than a comment ;-) iOS retrieves all data in radians and if your other calculations are correct, I thought it might be the angle measured in radians.
In general your approach seems to be alright: Take every signal's angle velocity, multiply it with time delta and you will have the angle delta for this timeframe. Then sum all your angles and the result should be the covered distance as angle in radians. Angle phi is the integral of angle velocity omega over the elapsed time and doing numerical integration with the trapezoidal rule (i.e. like described) is OK for gyroscope's data (not for accelerometer).
In general I would recommend to use the timestamp delivered by core motion instead of the defined period (1/5) as recommended by Apple, because device motion data is often delivered in a lower frequency than expected (see What is the official iPhone 4 maximum gyroscope data update frequency and or Push method for core motion and frequency of Accelerometer/Gyroscope Data.
Furthermore you should take a higher frequency to avoid errors in your numerical integration.
[Update from comments section:]
If your are interested in integrating via extended Simpson's Rule I recommend this paper (German only, p. 173 ff.) and An Extension to Newton-Cotes Formulae. Some sample code as extracted snippet taken from an existing project can be found here: DevicePosition.m Note that it might not compile, no warranty, as is, ... you know this from other sites ;-)
A free app displaying sensor input as graphs for iPhone: Sensor Monitor


text:
Q: How to view files in container while building? When I am building container I get next message:
Step 13/29 : RUN source $PERLBREW_ROOT/etc/bashrc && perlbrew install -j 8 --notest --switch $PERL_VERSION
 ---> Running in a4efbc14a7b5

Fetching perl 5.24.1 as /opt/perlbrew/dists/perl-5.24.1.tar.bz2
Download http://www.cpan.org/authors/id/S/SH/SHAY/perl-5.24.1.tar.bz2 to /opt/perlbrew/dists/perl-5.24.1.tar.bz2
Installing /opt/perlbrew/build/perl-5.24.1/perl-5.24.1 into /opt/perlbrew/perls/perl-5.24.1

This could take a while. You can run the following command on another shell to track the status:

  tail -f /opt/perlbrew/build.perl-5.24.1.log

But how to do tail -f /opt/perlbrew/build.perl-5.24.1.log if there is no container yet?

A: Instead of trying to access that intermediate container even if it was possible to do, It may not be helpful in other cases like when you have a CI and the build was failed then you need to check the reason. So I suggest switching to verbose mode in perlbrew using -v option which makes the output go to STDOUT instead of file.
-v| --verbose
Log output to STDOUT rather than a log file.


text:
Q: Better question throttling experience on mobile? I suppose this is an enhancement to the existing feature.
My case:

*

*had a problem, reported it here;

*had a suggestion right at the same time;

*got throttled with sorry can post only one thing in 20 minutes.

Fair enough. Reputation, spammers etc.
Consider the following though:

*

*on mobile (iOS in my case) I took a long time to craft my question, select title, tags, whatnot.

*I tap "post the question"

*I get "sorry blah blah only every 20 minutes"

The problems I had, as a user/customer:

*

*that was unexpected;

*the message didn't say how long I have to wait to post something new;

*mobile-specific. In iOS at least the memory management is pretty aggressive. What this means is if I use any other apps while waiting for that 20 minute window the Safari app is gonna get killed, and that in my experience means full reload and loss of the carefully crafted question.

You see? On desktop doesn't matter. On mobile – more so.
My suggestion would be:

*

*for mobile only (because SE already knows if I'm mobile by looks of it);

*either state at the beginning that I can't post because my quota is exceeded (easily done? Appreciate performance impact);

*or perhaps say how much I have to wait until I can post after I have attempted to do so.

Because otherwise I'm a bit stuck, and I don't know for how long either.
I would suggest stating "you can't post because you need to wait XX minutes" at the beginning of the posting process on mobile only would be the preferred solution to me personally.
Summary: provide a better experience on mobile re throttling. Ideally pre- asking question. Otherwise, saying how long the wait is before can post.
(Posting from iPhone apologies for typos and things like that :))
PS: ironically, had lots or trouble posting this, complaining about terms UX all over the place :)


text:
Q: SnakeYaml create object via static method I'm trying to use snakeyaml with Play Framework 2 to create Ebean objects
it works well with
!!models.User
  name: Leon

But I'd like to reference allready persisted items. which means I don't want to create new objects.
So if I do something like this to try to reference the already created group
!!models.Group &mygroup
  id: 1

!!models.User
  group: *mygroup

It will complain that the group with id: 1 already exists
Ebean has a a method EbeanServer.getReference(type, id) which is accessible from the static find method on the model class
Group.find.ref(1)

I would like to be able to do something like this (but it doesn't work now)
!!models.Group.find.ref(1) &mygroup

How can I call this static method from snakeyaml to get a reference instead of a new object?

A: To solve this I had to create a custom Yaml constructor that uses Ebean.getServer("default").getReference(models.User.class, 1)
https://gist.github.com/4326933
Hope it will help someone!


text:
Q: Synchronization two ionic-range I have the following two ion-range components.
I set the minimum and maximum values to 0 and 100 respectively.
But also I want to restrict the movement of the thumb in order Start couldn't be greater than Stop


text:
Q: Android - Custom AlertDialog Background Color So I see we can have alertdialogs with gray and white (when setinverse...) background colors.
To learn why I checked themes.xml of the sdk, checking it I was led to drawables and there I realized the alertdialog background is not done programatically but via some images. And these images guarantee that there are two gray(or white when inverse color) horizontal lines on top(title area) and bottom(just above button area) of the dialog when we use LayoutInflater to just set a different backgroundcolor.
So my question is, as LayoutInflator is useless and guessing I have to subclass alertdialog, what do you suggest I do to generate an AlertDialog with a different backgroundcolor? What should I override?

A: Instead of using AlertDialog, I ended up using a Dialog. To get a custom look:
1-Create the Dialog and remove the title area(Otherwise you'll get a blank gray area on top):
myDialog = new Dialog(this);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

2-Design a layout in xml, and set as dialog's content:
myDialog.setContentView(R.layout.mydialog_layout);

3-If the layout is not a rounded rect, it will intersect with the rounded corners of the dialog box. So, design the layout as a rounded rect:
in mydialog_layout.xml:
android:background = "@layout/mydialog_shape"

mydialog_shape.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle"
     >
     <gradient android:startColor="#FF0E2E57"
     android:endColor="#FF0E2E57"
            android:angle="225" android:paddingLeft="20dip"/>

    <corners android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp"
     android:topLeftRadius="5dp" android:topRightRadius="5dp" android:paddingLeft="20dip"/>
</shape>

4-Add listeners to the buttons in your activity:
Button button = (Button)myDialog.findViewById(R.id.dialogcancelbutton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    myDialog.cancel();
}});

That's about it.

A: I recall reading that not all Android Dialogs are created equally. Therefore, if you don't want to use the dialog that shipped with the device's Android version; You need to code a completely fresh dialog from the ground up.
Edit:
I think you need to override the onCreateDialog with a custom dialog builder class. Like I said, I've never done it. Remember, to keep with the Android MVC style, you need to define the dialog in XML as well. If I was going to do it; I would probably start with the XML layout, then code a custom dialog class using the same methods as a regular dialog builder class. Sorry to be so vague, I'm still learning Java and Android myself.

A: so easy..
Dialog d=builder2.create();
...
d.show();
d.getWindow().setBackgroundDrawableResource(R.drawable.mydialog_shape);


text:
Q: Xamarin for Android: Automatically taking photos -- something similar to UWP's MediaCapture functionality A wrote a robotics app using UWP a few years ago, which automatically takes photos. I want to convert it to an Android (and possibly iOS) app with Xamarin, but I noticed that Xamarin's MediaPicker is a far cry from UWP's MediaCapture object. With MediaCapture I could have my app take several pictures completely on its own, without the user having to click on any buttons, with this code:
MediaCapture mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync(mediaSettings);
LowLagPhotoCapture photoCapture = await mediaCapture.PrepareLowLagPhotoCaptureAsync(imageProperties);
CapturedPhoto photo = await photoCapture.CaptureAsync();
CapturedFrame frame = photo.Frame;
SoftwareBitmap SWBitmap = frame.SoftwareBitmap;

Is there a way to do the same in Xamarin?


text:
Q: how to send rest data using httppost in android I am developing a hotel booking app using expedia. I need to send the following rest data to server using the httppost
http:/api.ean.com/ean-services/rs/hotel/v3/list?minorRev=[current minorRev #]
&cid=55505
&apiKey=xxx-yourOwnKey-xxx
&customerUserAgent=xxx
&customerIpAddress=xxx
&locale=en_US
&currencyCode=USD
&city=Seattle
&stateProvinceCode=WA
&countryCode=US
&supplierCacheTolerance=MED
&arrivalDate=09/04/2012
&departureDate=09/05/2012
&room1=2
&numberOfResults=1
&supplierCacheTolerance=MED_ENHANCED

A: String urlToSendRequest = "https://example.net";
String targetDomain = "example.net";

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost targetHost = new HttpHost(targetDomain, 80, "http");

HttpPost httpPost = new HttpPost(urlToSendRequest);

httpPost.addHeader("Content-Type", "application/xml");

StringEntity entity = new StringEntity("<input>test</input>", "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(targetHost, httpPost);

Reader r = new InputStreamReader(response.getEntity().getContent());


text:
Q: Using multiple address locators in ArcGIS I am geocoding millions of addresses for my research (every registered voter in six states).
I am using two geocoders: one that is really fast and one that has fewer unmatched addresses when I geocode.
Is there a way to use ArcMap or ArcCatalog to use the second address locator on only the unmatched addresses from the first?
Right now I am importing the attribute table using the R programming language, exporting only the unmatched addresses as a CSV, re-importing them to ArcGIS, and geocoding, but I figure there has to be a faster way.

A: You can create a Composite Address Locator using ArcCatalog that has this functionality.  You first create your individual locators, then add them to the Composite locator.  You set the order of the individual locators in the composite locator setup.  If the address does not find a match in the first locator in the list, it is passed to the next locator in the list.
ESRI Help Instructions


text:
Q: GraphQL use an object type from a file in another file Guys I want to do something like that, but I cant find the answer. I want to be able to use an object type defined in one file, inside another file.
**post.schema.ts**

type Post{
name:String!
}

**user.schema.ts**

type User{
name:String!
posts:[Post!]
}


text:
Q: Call external application from Unity mobile application I would like to call the default sms and email editor from my unity 3d mobile application.
More specifically I want to give to my users the possibility to share their referral code calling and precompiling an email or an sms.
The game is for Android and IOS both.
Please ask for more details
Thanks in advance

A: Try:
void SMS(long number, string message) {
    string separator=(Application.platform == RuntimePlatform.IPhonePlayer)?";":"?";
    Application.openURL(string.Format("sms:{0}{1}body={2}", number, separator, WWW.EscapeURL(message)));
}

Based on https://stackoverflow.com/a/19126326/785171


text:
Q: Want to call an already running native process from within Adobe AIR What I wanted to achieve is to call an already running native process from within Adobe AIR. Actually from within Adobe AIR, I wanted to trigger something to already running native process so that it (native process) can take further actions based on input.
What I understood from NativeProcess class that it starts a new native process. So what happens if that process is already running on operating system? Will adobe air interact with already running process or will it start a new process independent of the other already running?
Your help is appreciated. Let me know if I was not clear enough.
Thank you.


text:
Q: How to put a combo box inside the DataGridView that is populated from a Sql query? So i am displaying my data in my datagridview using this:
con.Open();
adap = new SqlDataAdapter("SELECT ID, Course_Description as
'Course',Student_Name as 'Name', Classroom as 'Room', Seat_Number as
'Seat No.' from TBL_SeatPlan WHERE Course_Description = '"+
cmbCourse.Text +"' ", con);
ds = new System.Data.DataSet();
adap.Fill(ds,"SeatPlan");
dtSeat.DataSource = ds.Tables[0];

DataGridViewComboBoxColumn Dcolumn = new DataGridViewComboBoxColumn();
Dcolumn.HeaderText = "Status";
Dcolumn.Items.Add("Absent");
Dcolumn.Items.Add("Present");

con.Close();

what i want to do is add another column that has a combo box to verify if a student is absent or present.
DataGridViewComboBoxColumn Dcolumn = new DataGridViewComboBoxColumn();
Dcolumn.HeaderText = "Status";
Dcolumn.Items.Add("Absent");
Dcolumn.Items.Add("Present");

this line of codes does not seem to appear in my datagridview

A: Yes i can now manage to add another column but what exactly i want is put a combo Box in that column i added.
con.Open();
adap = new SqlDataAdapter("SELECT ID, Course_Description as 'Course', Year_Level as
'Year Level', Student_Name as 'Name', Classroom as 'Room', Seat_Number as 'Seat No.'
from TBL_SeatPlan WHERE Course_Description = '" + cmbCourse.Text + "' and Year_Level
= '" + cmbYrLvl.Text + "' ", con);
DataTable dt = new DataTable();
adap.Fill(dt);
dtSeat.DataSource = dt;

DataGridViewComboBoxColumn Dcolumn = new DataGridViewComboBoxColumn();

dt.Columns.Add(new DataColumn("Status", typeof(char)));

Dcolumn.HeaderText = "Status";
Dcolumn.Items.Add("Absent");
Dcolumn.Items.Add("Present");

con.Close();


text:
Q: What is the best way to embed HTML in an RSS feed? I am using Django's RSS capabilities to build an RSS feed. The <description> of the RSS feed items contains HTML markup. Currently, I am just injecting the HTML markup into the feed using the following template:
{{ obj.post }}

Django, of course, translates special characters (<, >, &, etc.) to their respective HTML entities.
I know I could just output the HTML and wrap all the HTML code in <![CDATA[...]]> sections. This page says that either method is acceptable. If that's true, is there a good reason to pick one method over the other? And if I use example #2, is there a filter for Django to automatically wrap the HTML text in CDATA tags, or should I just change my template to:
<![CDATA[
{{ obj.post|safe }}
]]>

Edit
It seems that Django autoescapes special characters in RSS feeds (or any XML for that matter) no matter what, regardless of whether you pass it through the safe filter or not (the issue is discussed in this ticket). However, general answers are welcome.

A: When I run into issues like this with Django my first instinct is to run off and find a normal Python lib that does what I want. In this case PyRSS2Gen might be your saviour.
It'll probably require a bit more fannying around (because it'll be unaware of what Django objects are) but it should be raw enough to let you do as you wish.
And if it isn't, it's just a script. You can hack it apart to allow raw HTML if you please =)

A: Embedding HTML is CDATA has troubled me in the past. Hope RSS readers have evolved to handle such embeds.

A: Instead of writing your own RSS XML feed, consider using the Django syndication framework from django.contrib.syndication:
https://docs.djangoproject.com/en/dev/ref/contrib/syndication/


text:
Q: Animate gravity layout changes of FloatingActionButton in android I have a TabLayout with 2 tabs besides FloatingActionButton. On switching tabs, I can change the layout_gravity of FloatingActionButton from left to right and vice versa. I want to animate this button (show movement from left to right or right left)  just like Android new phone book dialer floating button when it moves from center to right.
This is how I am changing the gravity.
 @Override
        public void onPageSelected(int position) {
            CoordinatorLayout.LayoutParams params = new CoordinatorLayout.LayoutParams( CoordinatorLayout.LayoutParams.WRAP_CONTENT, CoordinatorLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(16,16,16,16);

            if(position == 0){
                params.gravity = Gravity.BOTTOM|Gravity.START;
            }else if(position == 1){
                params.gravity = Gravity.BOTTOM|Gravity.END;
            }
            fab.setLayoutParams(params);

        }


text:
Q: When and where do you close a PDDocument? I get bytearrays of several pdfs from a backend source.
I load all these bytearrays into PDDocuments and add them to a list, like this:
List<PDDocument> pdfs = new ArrayList<>();
for (...the amount of bytearrays...) {
    PDDocument pdf = PDDocument.load(bytearray);
    pdfs.add(pdf);
}

I then merge these pdfs into one PDDocument:
PDDocument mergedPdf = new PDDocument();
PDFMergerUtility PDFmerger = new PDFMergerUtility();
for(...all pdfs in list...) {
    PDFmerger.appendDocument(mergedPdf, pdf);
}

And then I save the mergedPdf to a file:
mergedPdf.save("c:\temp\mergeddoc.pdf");

My question is now: where do I call the close() method on these pddocuments?
Is this after loading them? But then that means I can't work any further with them, because I have closed the pdfs.
Or is this only needed at the end after I do the save?

A: You're on the safest side if you call close() on the source documents after saving the destination document. There have been bugs in older PDFBox 2.0.* versions where the destination PDF still kept references on the source PDFs - usually these were tagged PDFs. The soon to be released (likely in March) version 2.0.14 has all of these bugs fixed, hopefully, and you can close the source PDF after calling appendDocument(). Obviously you can't call close() directly after loading because the document is needed for appendDocument().


text:
Q: Nginx shows correct rewrite data, but not executing as expected I have a laravel app running behind Nginx using fastcgi.
There are images available at www.example.com/media/images/someImage.jpeg
There are also images of different size of the same image available at www.example.com/media/images/660x440/someImage.jpeg
There is a script running on laravel which makes this image available for this size IF its not existing available at www.example.com/api/images/660x440/someImage.jpeg
For example if www.example.com/media/images/660x440/someImage.jpeg does not exist, www.example.com/api/images/660x440/someImage.jpeg can be accessed which will show the image and now this image also exists under www.example.com/media/images/660x440/someImage.jpeg, hopefully this makes sense.
Ok so the issue I am trying to figure out right now is how to make this happen with nginx rewrite.
Idea is that when user tries to access www. example.com/media/images/660x440/someImage.jpeg and it does not exist, nginx rewrites this to /api/images/660x440/someImage.jpeg (the script) and shows the generated image, but all of this without changing the URL. So the URL requested stays like www. example.com/media/images/660x440/someImage.jpeg but under the hood it requests the script at /api/images/660x440/someImage.jpeg and shows the generated image at the same www. example.com/media/images/660x440/someImage.jpeg.
My nginx config is as below
server {
    listen  8080;
    root /var/www/public;
    index index.php index.html index.htm;
    client_max_body_size 100M;
    resolver kube-dns.kube-system.svc.cluster.local;       #this is for rancher purposes
    set $target app-fpm.app.svc.cluster.local;             #also this

    error_log /var/log/nginx/error.log notice;

    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    location /media/images/ {
        alias /var/www/storage/app/public/media/images/;
        try_files $uri /$uri @generator;
    }
    location @generator {
        rewrite ^/media/images/(.*)  /api/images/$1 last;
    }
    location ~ ^/.+\.php(/|$) {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        fastcgi_pass $target:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

I have enabled rewrite debug in nginx and in error log I can see this -
2020/09/11 23:14:28 [notice] 1034#1034: *161 "^/media/images/(.*)" matches "/media/images/660x440/someImage.jpeg", client: 10.42.0.0, server: , request: "GET /media/images/660x440/someImage.jpeg HTTP/1.1", host: "www. example .com"
2020/09/11 23:14:28 [notice] 1034#1034: *161 rewritten data: "/api/images/660x440/someImage.jpeg", args: "", client: 10.42.0.0, server: , request: "GET /media/images/660x440/someImage.jpeg HTTP/1.1", host: "www. example .com"

As you can see rewritten data is correct, it is /api/images/660x440/someImage.jpeg, but it shows 404 error as per access.log
10.42.0.0 - - [11/Sep/2020:23:33:43 +0300] "GET /media/images/660x440/someImage.jpeg HTTP/1.1" 404 622 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"

But it should show the new generated image instead.
Is this even possible what I am trying to achieve here?
I would really appreciate the help,
Thank you!


text:
Q: Calling Twitter Streaming API (statuses/filter) from vb.net webpage I am trying to call Streaming API filter inside my .net webpage.
I did create an app on twitter and took the credentials needed(consumer key,consumer secret,access token and access token secret)
This is the code am using
 Public Function StreamAPI()
    Dim url As String = "https://stream.twitter.com/1.1/statuses/filter.json?track=example.com/example"

    Dim oauthconsumerkey As String = "consumerkey"
    Dim oauthconsumersecret As String = "consumersecret"
    Dim oauthsignaturemethod As String = "HMAC-SHA1"
    Dim oauthversion As String = "1.0"
    Dim oauthtoken As String = "token"
    Dim oauthtokensecret As String = "tokenkey"

    Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
    Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
        0, DateTimeKind.Utc)
    Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
    Dim basestringParameters As New SortedDictionary(Of String, String)()
    basestringParameters.Add("track", "example.com/example")
    basestringParameters.Add("oauth_version", oauthversion)
    basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
    basestringParameters.Add("oauth_nonce", oauthnonce)
    basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
    basestringParameters.Add("oauth_timestamp", oauthtimestamp)
    basestringParameters.Add("oauth_token", oauthtoken)

    Dim baseString As New StringBuilder()
    baseString.Append("GET" + "&")
    baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) + "&"))
    For Each entry As KeyValuePair(Of String, String) In basestringParameters
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")))
    Next

    Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)

    Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) + "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))

    'Sign the request
    Dim hasher As New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
    Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))

    Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
    Dim authorizationHeaderParams As New StringBuilder()
    authorizationHeaderParams.Append("OAuth ")
    authorizationHeaderParams.Append("oauth_nonce=" + """" + Uri.EscapeDataString(oauthnonce) + """,")
    authorizationHeaderParams.Append("oauth_signature_method=" + """" + Uri.EscapeDataString(oauthsignaturemethod) + """,")
    authorizationHeaderParams.Append("oauth_timestamp=" + """" + Uri.EscapeDataString(oauthtimestamp) + """,")
    authorizationHeaderParams.Append("oauth_consumer_key=" + """" + Uri.EscapeDataString(oauthconsumerkey) + """,")
    If Not String.IsNullOrEmpty(oauthtoken) Then
        authorizationHeaderParams.Append("oauth_token=" + """" + Uri.EscapeDataString(oauthtoken) + """,")
    End If
    authorizationHeaderParams.Append("oauth_signature=" + """" + Uri.EscapeDataString(oauthsignature) + """,")
    authorizationHeaderParams.Append("oauth_version=" + """" + Uri.EscapeDataString(oauthversion) + """")
    webRequest__1.Headers.Add("Authorization", authorizationHeaderParams.ToString)

    webRequest__1.Method = "GET"
    webRequest__1.ContentType = "application/x-www-form-urlencoded"

    webRequest__1.Timeout = 3 * 60 * 1000
    Try

        Dim webResponse As HttpWebResponse = TryCast(webRequest__1.GetResponse(), HttpWebResponse)

        Dim dataStream As System.IO.Stream = webResponse.GetResponseStream()
        ' Open the stream using a StreamReader for easy access.
        Dim reader As New StreamReader(dataStream)
        ' Read the content.
        Dim responseFromServer As String
        responseFromServer = reader.ReadToEnd()
        Return responseFromServer
    Catch ex As Exception
    End Try

End Function

The function doesnt return anything. At row containingreader.ReadToEnd() in debug mode it is showing "Unable to evaluate expression".
The same code works correctly if the url is in this format
https://api.twitter.com/1.1/application/rate_limit_status.json
or
https://api.twitter.com/1.1/search/tweets.json?q=example
Any reason why it doesn't work for stream apis? I cant use search api since it doesn't return all results I need, for example tweets containing urls are not returned by search api.
I did try tweetinvi library for .net projects as suggested by twitter website.
Public Sub Twit()
    Dim oauthconsumerkey As String = "consumerkey"
    Dim oauthconsumersecret As String = "consumersecret"
    Dim oauthsignaturemethod As String = "HMAC-SHA1"
    Dim oauthversion As String = "1.0"
    Dim oauthtoken As String = "token"
    Dim oauthtokensecret As String = "tokensecret"

    Auth.SetUserCredentials(oauthconsumerkey, oauthconsumersecret, oauthtoken, oauthtokensecret)
    Auth.ApplicationCredentials = New TwitterCredentials(oauthconsumerkey, oauthconsumersecret, oauthtoken, oauthtokensecret)

    Dim filteredStream = Tweetinvi.Stream.CreateFilteredStream()
    filteredStream.AddTrack("example")
    Dim txt As String = ""

    AddHandler filteredStream.MatchingTweetReceived, Sub(sender As Object, args As Tweetinvi.Core.Events.EventArguments.MatchedTweetReceivedEventArgs)
                                                         Console.WriteLine(args.Tweet.Text)
                                                         txt &= args.Tweet.Text
                                                     End Sub

    filteredStream.StartStreamMatchingAllConditions()

End Sub

But this is not returning anything. The event is not getting called and i am not getting any result.
Both methods failed.Is there any other clear example that I can use to call statuses/filter from vb.net webpages?

A: I am the developer of Tweetinvi.
Your code looks correct. Would you please let me know what exception you receive.
Also, I am not sure to understand if this code is invoked directly in the page (I am not familiar with WebForms), but please not that StartStreamMatchingAllConditions will be blocking the Thread it runs in until the stream stop.
If you want this to be running behind the scene you will want to use the async version : StartStreamMatchingAllConditionsAsync().
Finally, the way I send stream tweets to a UI is by using WebSocket and send information from the server to a javascript handler.


text:
Q: Smoothness of a subalgebra Assume $A \subseteq B \subseteq C$ are commutative noetherian domains of zero characteristic, $C$ is a f.g. $B$-module, $B$ is a f.p. $A$-algebra ($B$ is not necessarily a f.g. $A$-module), $C$ is a flat and separable $A$-algebra (hence, $C$ is a smooth $A$-algebra) and $B$ is a flat $A$-algebra.
My question: Is it true that $B$ is a smooth $A$-algebra?; equivalently, is it true that $fd_{B \otimes_A B}(B) < \infty$? (please see Corollary 2).

*

*I have tried to show formal smoothness of $B$ over $A$ (since $B$ is f.p. over $A$, smoothness is equivalent to formal smoothness), namely: For each $A$-algebra $E$, and each ideal $J$ in $E$ with $J^2=0$, the canonical homomorphism $Hom_{A−alg}(B,E) \to Hom_{A−alg}(B,E/J)$ is surjective. However, I had a problem when, given an $A$-algebras homomorphism $f: B \to E/J$ to extend it to an $A$-algebras homomorphism $F: C \to E/J$ (since, if we have such $F$, then $F$ has a preimage $G: C \to E$, and then we can restrict $G$ to $B$, and get a preimage for $f$, if I am not wrong).

*I suspect there exists a counterexample.
Remarks:
(1) This answer is not applicable in the current question, since there $B$ is not a domain. (Also, I prefer to assume that $A$ is not a field, and here $C$ is not assumed to be a finitely generated $A$-module).
(2) This question asks about smoothness of $C$ over $B$.
(3) Please see this question.

A: First let me come back to my initial example $A = k$, $B=k[x,y]/(y^2-x^3-x^2)$, $C$ the integral closure of $B$ in its quotient field $K(B)$.
Then $B/A$ is flat and of finite type, $C$ is nonsingular, therefore $C/k$ smooth, and $C/B$ is finite. The properties "finite", "of finite type", "flat" and "smooth" are preserved under base extension. Therefore it is possible to extend the base $A=k$ to every $k$--scheme $S$. Of course this gives only utterly trivial examples, as every fiber is the same.
To get something a little more interesting one can use the slightly changed original setup:
$$
\begin{align}
A & =\mathbb{Q}[a,b] \\
B & =A[x,y]/((y-b)^2-((x-a)^3+(x-a)^2))
\end{align}
$$
and $C$ again the integral closure of $B$ in its quotient field.
If one computes $\Omega_{C|A}$ one gets $C$, so it is free of rank $1$ as necessary for smoothness over $A$.
The computation of $\Omega_{C|A}$ goes over the sequence
$$(*) \quad I/I^2 \to \Omega_{S|A} \otimes_S C \to \Omega_{C|A} \to 0$$
where $C = S/I$ and $S=A[w,x,y]$, $I=(f_1,f_2,f_3) \subseteq S$ a certain ideal of three elements of $S$ that is found by Macaulay 2 on computing the integral closure $C$ of $B$.
It remains to prove flatness of $C$ and $B$ over $A$. Flatness of $B$ over $A$ follows from the following statement:
Let $R[X_1,\ldots,X_n] = S$ and $S_1=S/(f)$, $f \in S$. Then $S_1$ is flat over $R$ if for every maximal ideal $\mathfrak{m}$ of $R$ the ring $S_1 \otimes_R R/\mathfrak{m}$ is not equal to $S \otimes_R R/\mathfrak{m}$.
This can be found in Milne, Etale Cohomology, Chapter 1, Remark 2.6(a).
To prove the flatness of $C = S/I$ over $A$ seems to be more difficult and I currently can not prove it. The case $A=k[a]$ is considerably simpler in this regard, as one needs only check that every irreducible component of the domain dominates $\operatorname{spec}(A)$.


text:
Q: Check if each string (all of them) on a list is a substring in at least one of the strings in another I am having a hard time trying to check if all of the strings in a python list are a subset of any string in another Python list.
Example:
I want to check if each string(all of them) of list1 is in at least one of the strings in the list2 and if it is, do something.
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']

In this example for instance it would return True.

A: You can use generator expressions combined with any/all functions:
>>> list1 = ['tomato', 'onions','egg']
>>> list2 = ['Two tomatos', 'two onions','two eggs','salsa']
>>> all(any(i in j for j in list2) for i in list1)
True

A: You can do with a single command using list comprehension, any, and all.
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']
result = all([any([keyword in string for string in list2]) for keyword in list1])

The first list comprehension [keyword in string for string in list2]checks that a keyword is at least present in all strings of list2 and produces a list of boolean. We use any to determine if any result was True.
The second list comprehension is built on top of the first list comprehension [any([keyword in string for string in list2]) for keyword in list1] and checks that all keywords were are least present in all the string of list2. We use all to check that all results are True.
As @Selcuk mentioned, you can do it more efficiently using generator expressions: the syntax is really is really close to list comprehensions:
result = all(any(keyword in string for string in list2) for keyword in list1)

A: You could go through the lists and execute something if it meets the condition that the word from list 1 exists in some element of list 2, for example:
list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']
for i in list1:
    for j in list2:
        if i in j:
            print("something to ", i, " and ", j)


text:
Q: Fully qualified name should we use ::class With Symfony I'm taking the habit of using the class name resolver ::class (since php5.5):
use AppBundle\Entity\Product;

// ...

$resolver->setDefaults(array(
    'data_class' => Product::class
));

instead of the FQN string:
$resolver->setDefaults(array(
    'data_class' => 'AppBundle\Entity\Product'
));

I'm doing that for readability purpose and because it's handy to introscpect in some smart IDEs.
However, I'm seeing not so much examples of this practice in official docs. So I'm wondering if this is because of the compatibility concern (< php5.5) or because it would not be good to systematically import all the classes we need to reference.
My question is: Is it a good practice to use ::class everywhere we need to reference a FQN ?

A: The answer seems to be:
Apart from the compatibility issue with php<5.5 there is nothing that would prevent one to use the ::class name resolver everywhere we need.


text:
Q: Oracle 12c desinstall ERROR:Error occurred during initialization of VM I want to desinsall ORACLE 12C from sever but i get the below error:
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object


text:
Q: The result is not sorted using aggregation and MongoDB I'm still learning Java Spring together with MongoDb and had now an issue that I cannot find any solution.
I have the following data in MongoDB:
{
    "_id" : ObjectId("603ea2eddb5621d54362d2a9"),
    "albumKey" : "3ee258ca5aef4e37a8b0bc0ff7cc3256",
    "albumName" : "Profile photos",
    "createdOn" : ISODate("2021-03-02T20:41:17.626Z"),
    "deleted" : false,
    "createdBy" : NumberLong(1),
    "privacy" : "public",
    "_class" : "com.f2.AuthApp.model.photo.PhotoAlbums",
    "albumPhotos" : [
        {
            "photoKey" : "25a370e24aa74cb49bdac85be311cc14",
            "fileName" : "3kZ3hc2YMB6LXiPohtyfKa(8).jpg",
            "createdOn" : ISODate("2021-03-02T20:41:17.640Z"),
            "deleted" : false,
            "userId" : NumberLong(1),
            "privacy" : "public"
        },
        {
            "photoKey" : "d6a2865356974a8d9c4c56ff780eb86f",
            "fileName" : "aliastudioportraitwebsize2048ver2(2).jpg",
            "createdOn" : ISODate("2021-03-02T20:41:26.099Z"),
            "deleted" : false,
            "userId" : NumberLong(1),
            "privacy" : "public"
        },
        {
            "photoKey" : "7a32b8ac45f542519a3615785c15a6cc",
            "fileName" : "DigitalGlobeWorldView150cm8bitBWDRABangkokThailand2009JAN068bitssubr1(2).jpg",
            "createdOn" : ISODate("2021-03-02T20:41:41.761Z"),
            "deleted" : false,
            "userId" : NumberLong(1),
            "privacy" : "public"
        },
        {
            "photoKey" : "2a289bb9b4a24a1db1a2153345802389",
            "fileName" : "fc03426a5fac006d576da53970a21403(1).jpg",
            "createdOn" : ISODate("2021-03-02T20:42:26.717Z"),
            "deleted" : false,
            "userId" : NumberLong(1),
            "privacy" : "public"
        }
    ]
}

and I'm trying extract what is in albumPhotos by using:
        AggregationOperation unwind = Aggregation.unwind("albumPhotos");
        AggregationOperation match = Aggregation.match(Criteria.where("createdBy").is(customUserDetails.getId()));
        AggregationOperation match2 = Aggregation.match(Criteria.where("albumPhotos.deleted").is(false));
        AggregationOperation sort = Aggregation.sort(Sort.Direction.ASC, "albumPhotos.createdOn");
        AggregationOperation group = Aggregation.group("albumPhotos");

        Aggregation aggregation = Aggregation.newAggregation(match, unwind, match2, sort, group);

        AggregationResults<AlbumPhotos> albumPhotos = mongoTemplate.aggregate(aggregation, PhotoAlbums.class, AlbumPhotos.class);

        List<AlbumPhotos> albumPhotosList = albumPhotos.getMappedResults();

and when I'm listed List the result is not in sorted by createdOn as expected, it is something like:
[
    {
        "photoKey": "25a370e24aa74cb49bdac85be311cc14",
        "fileName": "3kZ3hc2YMB6LXiPohtyfKa(8).jpg",
        "createdOn": 1614717677640,
        "deleted": false,
        "deletedOn": null,
        "userId": 1,
        "privacy": "public"
    },
    {
        "photoKey": "2a289bb9b4a24a1db1a2153345802389",
        "fileName": "fc03426a5fac006d576da53970a21403(1).jpg",
        "createdOn": 1614717746717,
        "deleted": false,
        "deletedOn": null,
        "userId": 1,
        "privacy": "public"
    },
    {
        "photoKey": "7a32b8ac45f542519a3615785c15a6cc",
        "fileName": "DigitalGlobeWorldView150cm8bitBWDRABangkokThailand2009JAN068bitssubr1(2).jpg",
        "createdOn": 1614717701761,
        "deleted": false,
        "deletedOn": null,
        "userId": 1,
        "privacy": "public"
    },
    {
        "photoKey": "d6a2865356974a8d9c4c56ff780eb86f",
        "fileName": "aliastudioportraitwebsize2048ver2(2).jpg",
        "createdOn": 1614717686099,
        "deleted": false,
        "deletedOn": null,
        "userId": 1,
        "privacy": "public"
    }
]

I'm looking for an answer since 2 days ago what I'm doing wrong sorting this inner array and without success.
Perhaps the experts in Java can see immediately what I'm doing wrong and I really appreciate if you can help me! Thank you.

A: You have a group stage after the sort stage. Unless you can find a statement in documentation for $group stating the output is sorted, which I don't see, you need to sort after grouping.


text:
Q: Adding attribute to html tag via code-behind results in error type (System.Web.UI.HtmlControls.HtmlElement) is not compatible When I try to add an attribute to my html tag in my masterpage:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" id="primtag" runat="server">

like so in code behind:
prmimaryhtml_tag.Attributes.Add("lang", "en")

I get this error:
Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The base class includes the field 'primtag', but its type (System.Web.UI.HtmlControls.HtmlElement) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).

Source Error:

Line 4:
Line 5:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Line 6:  <html xmlns="http://www.w3.org/1999/xhtml" id="primtag" runat="server">
Line 7:  <head id="Head1" runat="server">
Line 8:      <title></title>

Source File: /main.master    Line: 6

I also checked main.master.designer.vb and it holds this line:
Protected WithEvents primtag As Global.System.Web.UI.HtmlControls.HtmlElement

Now, the weirdest thing is: this code works correct on my local machine, but not on my production server. I don't know what's causing this different behavior either.
I also looked at this post: set pages main html tag in c#
UPDATE
When my situation is as follows:
main.master.designer.vb
 Protected WithEvents primtag As Global.System.Web.UI.HtmlControls.HtmlElement

main.master.aspx
<html xmlns="http://www.w3.org/1999/xhtml" ID="primtag" runat="server">

main.master.aspx.vb
commented this line:
'primtag.Attributes.Add

I get:
Parser Error

Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The base class includes the field 'primtag', but its type (System.Web.UI.HtmlControls.HtmlElement) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).

Source Error:

Line 4:
Line 5:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Line 6:  <html xmlns="http://www.w3.org/1999/xhtml" ID="primtag" runat="server">
Line 7:  <head id="Head1" runat="server">
Line 8:      <title></title>

After that I tried changing that line in the main.master.designer.vb file from Protected WithEvents primtag As Global.System.Web.UI.HtmlControls.HtmlElement to Protected WithEvents primtag As Global.System.Web.UI.HtmlControls.HtmlGenericControl On the production server I get:
Object reference not set to an instance of an object.
UPDATE 2
It may have something to do with compilation of my solution, I also checked these posts:
http://briancaos.wordpress.com/2013/08/07/system-web-ui-htmlcontrols-htmliframe-is-not-compatible-with-the-type-of-control-system-web-ui-htmlcontrols-htmlgenericcontrol/
https://connect.microsoft.com/VisualStudio/feedback/details/736011/iframe-parser-error
http://forums.asp.net/t/1884696.aspx?help+required+with+iframes+on+aspx
http://support.microsoft.com/kb/941824
http://forums.asp.net/t/1686949.aspx

I then check my IIS7.5 setting on local machine, there the application pool was set to ASP.NET4.0, same as on my production server.
My target framework compilation in Visual Studio is set to .NET Framework 4.5.
Hopefully this provides more insights in getting this to work. Please help :)

A: Possibly, each dynamically added attribute should start with any special (for example, the "xml") prefix.
Check this thread, which may be helpful.


text:
Q: How to check if a node has particular class in Dojo? I regularly hide/show nodes through JavaScript, but now I need to set those of a specific class inline-block (not block) when showing. However, I have a problem with sorting the inline-block class and the rest, the class is null in this context:
show: function (div) {
    if (typeof div === 'object' && typeof div.style === 'object') {
        if (div.class == "inline-block-class") //this doesn't work
        {
            div.style.display = "inline-block";
        } else {
            div.style.display = "block";
        }
    }
}

The divs are referenced by data-dojo-attach-point - I can work with something like this.someAttachPoint completely, but when I wrap it into some other variable (such as div in my function), I get only the CSS selectors of the node - it's an object, but I can't get its properties in FireBug.
I can workaround this by adding another parameter, a flag telling me that this node should be inline-block, but it's dirty and another opportunity for errors, so I would prefer to do the block/inline-block distinction within the function.

A: Use the dojo/dom-class and dojo/dom-style modules to check the class on a DOM node and change the style.
show: function (div) {
if (typeof div === 'object' && typeof div.style === 'object') {
    if (domClass.contains(div, "inline-block-class"))
    {
        domStyle.set(div, 'display', 'inline-block');
    } else {
        domStyle.set(div, 'display', 'block');
    }
}
}

Better solution to this is to control the div.style.display using the CSS and not Javascript. Just change the classes in Javascript and let CSS handle the styling.

A: You can use Element.classList property of the DOM element div, It expose's a method contains.

Checks if specified class value exists in class attribute of the element.

if (div.classList.contains("inline-block-class"))
{
    div.style.display = "inline-block";
} else {
    div.style.display = "block";
}


text:
Q: Python3 - Create variables with 'i' value at the end of variables' name How do I create a loop in which I will create variables with name having the 'i' value at the end of variable's name?
So far I have this but it is not working:
for i in range(0,4):
#v{i} should be v1, v2, v3, v4 at the end of loop with values being the 'i' value respectively
v{i} = i
i+=1

Thank you

A: for i in range(0,4):
    vars()['v' + str(i)] = i
    i+=1

A: The answer is that you don't want to do this in such way. If you would want to retrieve a value given a certain "variable" name, I would create a proper Python data structure for it, such as a dictionary:
d = {}
for i in range(0,4):
    d[f"name{i}"] = i
    i+=1

Look at this thread for further explanation and insights why you want to follow this strategy:
How do you create different variable names while in a loop?
There you will also find an actual answer on how to technically do what you want in Python, but is discouraged.


text:
Q: Create a column in a table view with a value based on a group of rows in another table I'd like to create a table view and include a new column that is based on values from another table.
Many rows of table B belong to one row of table A.
Table B has a status column (with values like active, completed, etc) and a foreign key (for table A).
In the new table view (for A) I want to create an active column (true / false) that is based on any related rows in table B having a status value of active and a matching foreign key.

A: If it is just about checking if the value exists, then this should do the job
select  A.c1,
        A.c2,
        -- other columns from A
        case when exists (select 1 from B_Table B where A.FK = B.FK and B.status = 'active')
            then 'true'
            else 'false'
        end as Active
from A_Table B


text:
Q: Non Azure VPS connecting to Azure SQL Server Database Ive got a VPS running a web application where its performance is being slowed incredibly by the SQL Server that is installed alongside it.  I want to use Azure SQL Server to host the database there and the Application on the VPS that is external to Azure.
Ive published the Database and its data to Azure nicely from the VPS, added the IP address of the VPS on the allowed connection list in the firewall, however when I go to use the connectionstring, I get the usual no permissions or Database does not exist..
Im relatively new to Azure services (Used visual studio to connect and configured virtual machines etc..)so what more do I need to do in order to allow this External VPS to connect and access the SQL Server on Azure?


text:
Q: Facebook, Snapchat, WhatsApp Contacts Find Friends Feature Using AWS Mobile Hub The feature I want to implement is like Snapchat or Facebook or WhatsApp, where you can find friends who are using the app, which means, a user of my app can look into their contacts to see which has used my app.
I seem to search for a lot of answers, but not sure how to implement specific to AWS Mobile Hub. I'm using AWS Cognito User Pool with phone verification method. I'm also developing an iOS App using Swift.
Anyone can give me a general direction where I can research. And if I can't find any answer, I would ask question, I would not flag as answered so soon, so sorry in advance first.

A: AWS has published a tutorial for building a fully functional mobile social chat app for iOS (Swift) or Android. The guide, "Build a multi-user messaging app with serverless architecture using Mobile Hub" is available here.
This 1-2 hour tutorial walks you through setting up the backend and generating a sample iOS Swift Xcode project using AWS Mobile Hub. The app is designed to be secure by default and have the ability to scale to millions of users.
The tutorial covers most of the common features of a social chat app like:

*

*Searching your phone contacts for active app users (matching phone
number)

*Push notifications for real-time message notification

*File/photo sharing with the option to delete the image/photo after x
minutes!


text:
Q: Remove items from List where condition I got a List<Person> listA  -> where Person has
string name
int age
List<string> jobs

I need to remove from listA all items that jobs.count() < 1, using linq, any ideas?

A: You shouldn't mutate a list using LINQ, because it's designed for querying, however, List<T> already has a RemoveAll method as part of it's protocol:
listA.RemoveAll(person => person.Jobs.Count < 1);

RemoveAll accepts a Predicate<T> delegate which should return true when an item is to be removed.
However, if you're intention is to create a new list that only contains people with less than one job, you can use LINQ:
var newList = listA
    .Where(person => person.Jobs.Count < 1)
    .ToList();


text:
Q: playing 3D rotated video on android I'm trying find a way to play a video in a view while rotating it on Android 2.2. I'm not talking about 90 degrees rotation, I'm talking about 3D rotations.
I see that starting from API level 14 there is View.SetRotation/X/Y but I want to use API LEVEL 8.
I've tried creating my own video view by extending VideoView, create a custom matrix and set:
canvas.setMatrix(matrix);

in onDraw(Canvas) and dispatchDraw(Canvas), but this didn't make a difference. My video is playing completely flat.
Any idea how I can do this?
Here you can see some examples to what I would like to achieve:
http://www.youtube.com/watch?v=PDXxPQEDegY
http://www.youtube.com/watch?v=OBoCrWrabs4
Thanks!!

A: Check out NineOldAndroids.

Android library for using the Honeycomb animation API on all versions
  of the platform back to 1.0

A: In the examples you have mentioned, no one is rotating videos.That is a simple AR app which recognizes an image provided as the "marker" in the app bundle itself.When it recognizes the image a set action is performed, that can be playing video or doing anything you want (possible in Android :)).I have done this in past and will try to fetch some snippets for you.


text:
Q: time stamp are resetting to Zero when changed from to_date to to_char in postgresql I need to change the following sql query to the postgres format. how can I do that?
eg:
round((TIME_TO_SEC(testruntest.endtime) - TIME_TO_SEC(testruntest.starttime))/60,2)

I tried this query and got error as "time_to_sec" is not a supported function...

A: Use the SQL standard EXTRACT function:
EXTRACT(epoch FROM testruntest.endtime)

The documentation describes:

For timestamp with time zone values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative); for date and timestamp values, the number of seconds since 1970-01-01 00:00:00 local time; for interval values, the total number of seconds in the interval


text:
Q: Sort based on length of an array in elasticsearch There is a field where there is an array stored. I want to sort the documents based on the array length of that field.
Sample documents
document 1 = {
"countryCodes" : ["US","UK","UA","IN"]
}

document 2 ={
"countryCodes" : ["FR","SU","UG","UK","US"]
}

So, up on sort, the results should be showing document 2 first and then document 1.

A: There are two options here.

*

*Use token count type as multi field in the mapping - This way another field would be stored as mutlti field which has the length of the array . You can learn more about it here.

*Scripting - The same can be achieved using scripting too .
{
      "sort": {
        "_script": {
          "script": "doc['countryCodes'].values.size()"
        }
      }
    }

A: For Elasticsearch 5.6.7 query should look like this:
GET index/_search
{
    "query": {
        "match_all": {}
    },
    "sort": {
        "_script": {
            "type" : "number",
            "script" : {
                "lang": "painless",
                "source": "doc.countryCodes.values.size()"
            },
            "order" : "desc"
        }
    }
}

A: The easiest way to do this would be to also index another field containing the length of the array and then sort on that field.
Another way would be to use script-based sorting and return the length of the array using groovy.
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "script": "doc.countryCodes.values.size()"
    }
  }
}

Also make sure to enable dynamic scripting in order for this to work.

A: For Elasticsearch 6.8 the query should look like this:
{
   "query": {
      "match_all": {}
   },
   "sort": {
      "_script": {
         "type": "number",
         "script": "doc.countryCodes.size()",
         "order": "desc"
      }
   }
}