text:
Q: Can I pull information from more than one column of a csv file when using the compare-object function in PowerShell? I'm currently working on a project that compares the e-mail addresses in two different csv files using the compare-object function in PowerShell. This works fine to deliver an output that tells me if the email address was found in one or both of the csv files. However, is there a way for me to also grab the information from the other columns in one of the csv files (i.e. name, phone number, etc.)? One csv file has only email addresses, the other has a few different columns. I want to output the comparisons along with select other column information from the other csv file and output that all into one single csv.
$file1 = import-csv -Path "c:\users\$env:USERNAME\Desktop\file1.csv"
$file2 = import-csv -Path "c:\users\$env:USERNAME\Desktop\file2.users.csv"
Compare-Object $file1 $file2 -property EmailAddress -IncludeEqual | Export-Csv c:\users\$env:USERNAME\Desktop\file3.csv

The above code is what I've been working with so far. It does everything I want it to, I just can't figure out how to include the output of other columns into the resulting csv file. If I have to take a totally new route, I'm open to suggestions.


text:
Q: Previous post in WP_Query I have loop which displays a list of posts, the posts are displayed with sorting
 $query = new WP_Query([
                'posts_per_page' => 3,
                'post_type' => 'agency',
                'meta_query' => array(

                    array(
                        'key'     => 'date',
                        'value'   => array( 0, 999 ),
                        'compare' => 'BETWEEN',
                        'type'    => 'NUMERIC',
                    ),
                ),
                'meta_key' => 'date',
                'orderby'  => 'meta_value_num',
                'order'    => 'ASC'
            ]);

I need to get the metadata of the previous post from the loop, I tried to do it like this
get_post_meta(get_previous_post()->ID, 'date', true);

But I am getting the previous post wrong, ignoring the arguments in WP_Query

A: I found a solution, create into the loop have_posts
foreach($query->posts as $key => $value) {
                        if($value->ID == $post->ID){
                            $nextID = $query->posts[$key + 1]->ID;
                            $prevID = $query->posts[$key - 1]->ID;
                            break;
                        }
                    }

And now i can get prev and next post data. Just use
<?php echo get_the_title($nextID);?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rise before an hour / rise in an hour Is it grammatically correct to say :

The sun will not rise before an hour.

Or it should be

The sun will not rise in an hour.

In my opinion both sentences are correct with a subtle difference in meaning .

A: I don't think it is ever idiomatic English to use "before" with a period of time. "Before an hour" or "Before three days" always sound to me like a non-native English speaker translating from their own language.
You can use "in", but this often means at the end of the period rather than during the course of the period: which meaning applies depends on several factors, and it may be genuinely ambiguous. So

The sun will rise in an hour.

generally means that the sun will come up one hour from now, not that it will rise some time during the next hour. But

The sun won't rise in an hour.

is more ambiguous. It might be denying that sunrise is one hour from now, or it might be denying that sunrise is earlier than one hour from now.
Some other examples of this subtlety:

He'll come in twenty minutes.

almost certainly means that he is expected at the end of twenty minutes, but

He'll come in the next twenty minutes.

means that he is expected any time during the twenty minutes.
Edit: Points I forgot to make, but have been reminded by other people:

*

*A way to say that something will happen by the end of a period, but not necessarily right at the end, is "within". So The sun will not rise within an hour is clear that I'm saying it won't rise at any time in that hour, while The sun will not rise in an hour might be ambiguous as to whether I mean that, or I mean that it will not rise at the time one hour from now.

*While we don't use before with periods of time, we do use it with points in time: The sun won't rise before 8 o'clock is fine.

A: To use the first sentence, you need to append something like has passed to the end of it. This makes the timing of the hour passing event less ambiguous.

The sun will not rise before an hour has passed.

The second sentence is perfectly fine.


text:
Q: Prove that $\gamma^\Omega$ is larger than $\Omega^\gamma$, where $\gamma$ is the Euler-Mascheroni constant and $\Omega$ is the omega constant In this post we denote the Euler-Mascheroni constant as $\gamma$ and the known as omega constant as $\Omega=W(1)$ with $W(x)$ the main/principal branch of the Lambert $W$ function. I don't know if the following problem is in the literature (if you know it from the literature please add a comment).

Question. Provide a simple reasoning to prove that $\gamma^\Omega$ is larger than $\Omega^\gamma$. Many thanks.

I know that similar problems are in the literature, but I don't know if precisely this is in the literature. If you know it add the reference or a comment, and I try to search and read those reasoning from the literature. My belief is that previous constants $\Omega^\gamma$ and $\gamma^\Omega$ aren't in the OEIS.

A: $x^{1/x}$ has a maximum at $x=e$ with e as euler's number. (can be shown by taking the derivative of the function)

Because the function is increasing before and decreasing after $x=e$, if x and y are two real numbers, which are bigger than 0 and $x<y$, than if x and y are smaller than e:
$$x^{1/x}<y^{1/y}$$
Raise it to the power of $xy$.
$$x^y<y^x$$
This holds true because x and y are positive numbers.
In your case the two numbers are smaller than e, so this proof applies.


text:
Q: Finding index of a value in Numpy matrix and add it with another value I want to find the index of a value in a matrix and add it to another value. How should I do that? I did as follows but does not work.
Merci for your help. result should be 0.
import numpy as np

a=np.array([1, 2, 3, 4, 78, 55, 33 ,22])

index=np.where(a==3)

newnumber=index-2

A: You are very close. Your solution right now is not quite working because np.where is returning a tuple containing an array with the index satisfying the condition. To make it work, all you need to do is to unpack the tuple with your preferred method (could be index, = np.where(a==3) or index = np.where(a==3)[0] or whatever).
In the future, I recommend you inspect your variables when you get an unexpected result. In this case, doing print(index) would have bee enough!

A: You have two problems - ambiguity at to what you want to subtract, and the tuple nature of the where result.
Your array and the test:
In [47]: a=np.array([1, 2, 3, 4, 78, 55, 33 ,22])
In [48]: a==3
Out[48]: array([False, False,  True, False, False, False, False, False])

That boolean mask can be used directly to index a:
In [49]: a[a==3]
Out[49]: array([3])

and to change the value of that element(s):
In [50]: a[a==3] -= 2
In [51]: a
Out[51]: array([ 1,  2,  1,  4, 78, 55, 33, 22])

where on the boolean mask produces a tuple (reread the np.where/nonzero docs):
In [52]: np.where(Out[48])
Out[52]: (array([2]),)

We can't subtract a value from this tuple:
In [53]: np.where(Out[48])-2
Traceback (most recent call last):
  File "<ipython-input-53-fd4087ff32d9>", line 1, in <module>
    np.where(Out[48])-2
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

We can extract the array from the tuple, and subtract a value from that:
In [54]: np.where(Out[48])[0]-2
Out[54]: array([0])

That's just the index of the element 2 steps before the 3.  Is that what you really want?


text:
Q: MySQL column contains PHP array content, loop I am working with Laravel 5.2. I have a text (string) column in a MySQL table that contains a PHP array for breadcrumbs like this.
['employee.index' => 'Employees']

On suggestion by @weigreen I tried also JSON format for the string content like this:
{'employee.index': 'Employees'}

I then want to loop through it in my blade template like this:
@if($pageBreadcrumbs)
    @foreach($pageBreadcrumbs as $route => $name)
        @if ($name == end($pageBreadcrumbs))

{!! $name !!}

        @else

{!! $name !!}

        @endif
    @endforeach
@endif

But I have not been able to successfully get PHP to interpret the contents of this field as an array.
I have tried various combinations of this code:
$breadcrumbsArray = array();
$breadcrumbsArray = $page->breadcrumbs;
View::share('pageBreadcrumbs', $breadcrumbsArray);

and
$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);

Any help is appreciated.

A: Try to convert back to php object and use it.
If you doesn't convert it your data will be seen as string by php.
$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);

A: This answer is really @weigreen's. Thank you for your help.
Format of MySQL content should be:
{"employee.index": "Employees"}

Then in my code when reading the row, I do:
$breadcrumbsArray = json_decode($page->breadcrumbs);
View::share('pageBreadcrumbs', $breadcrumbsArray);

Works perfectly.

A: Use Eloquent Mutators. https://laravel.com/docs/master/eloquent-mutators
public function getBreadcrumbsAttribute($value)
{
    return json_decode($value, true);
}

That goes in your model for "page". Any time that's accessed through the model it will mutate it to a usable array. (second argument of "true" enforces array)
Secondly, you can use a mutator for setting the field's value.
public function setBreadcrumbsAttribute($value)
{
    $this->attributes['breadcrumbs'] = json_encode($value);
}

Then you can simply do things like
foreach($page->breadcrumbs as $route => $title)...

and
$page->breadcrumbs = [['route' => 'Title'], ['other' => 'Other Title']];
$page->save();


text:
Q: Minimo valor de una lista Estoy armando una lista
lista.append(['{}{}'.format('Metros: ', metros),nombre,direccion])

y la salida es:
[['Metros: 405', 'edificio A', 'San Lorenzo'], ['Metros: 1843', 'edificio B', 'Eusebio Blanco'], ['Metros: 3067', 'edificio C', 'Av. San Martín Sur , Godoy Cruz'], ['Metros: 2863', 'edificio D', 'Tomás Godoy Cruz']]

Como puedo obtener de la lista el valor minimo de Metros.
En este ejemplo deberia de devolver

['Metros: 405', 'edificio A', 'San Lorenzo']

A: Deberías considerar transformar la listas de listas en un lista de diccionarios si es posible como te comenta @MLStud, estas operaciones serían mucho más simples y eficientes sobretodo usando operator.itemgetter y min/max, solo a modo de idea:
lista = [{'Metros': 405,   "Nombre": 'edificio A', "Direccion": 'San Lorenzo'},
         {'Metros': 1843,  "Nombre": 'edificio B', "Direccion": 'Eusebio Blanco'},
         {'Metros': 3067,  "Nombre": 'edificio C', "Direccion": 'Av. San Martín Sur , Godoy Cruz'},
         {'Metros': 2863,  "Nombre": 'edificio D', "Direccion": 'Tomás Godoy Cruz'}]

from operator import itemgetter

minimo = min(lista, key=itemgetter("Metros"))

>>> minimo
{'Metros': 405, "Nombre": 'edificio A', "Direccion": 'San Lorenzo'}

Puedes construir el diccionario  y añadirlo a la lista con:
lista.append({'Metros': metros, 'Nombre': nombre, 'Direccion': direccion})

Si no puedes hacer esto, puedes usar igualmente el built-in min y su argumento key pero pasándole una función que se encargue de tomar cada sublista, tomar el primer item, obtener el número aplicando str.rsplit y pasarlo  a float o int (para no llevar a cabo un ordenamiento lexicográfico). Esto es significativamente más ineficiente que usar un diccionario ya que requiere una llamada a función en Python puro, llamada a str.rsplit y casting a escalar y dos operaciones de indexado sobre listas (mientras que el ejemplo anterior se realiza mayoritariamente por medio de  código C compilado directamente):
minimo = min(lista, key=lambda item: float(item[0].rsplit(" ", maxsplit=1)[-1]))

>>> minimo
['Metros: 405', 'edificio A', 'San Lorenzo']

Nota: rsplit(" ", maxsplit=1) busca el primer espacio en la cadena de derecha a izquierda y rompe ahí la cadena sin seguir buscando más.

A: min=-1
for x in lista:
   #Aqui miro si nunca ha habido un minimo y pongo el primero de la lista.
   if(min == -1):
      min=x.Metros
      menor=x
   #Comprobamos si es menor
   elif(x.Metros < min):
      min=x.Metros
      menor=x
#Imprimimos el menor
print menor

Con eso deberia de funcionar

A: Siguiendo con la respuesta de Martin, se me ocurre algo para optimizar el código.
En vez de crear una variable con un número muy bajo y sobreescribirla si no lo ha sido aún, podrías crear esa variable con un número muy alto, que nunca vayas a alcanzar, y de ahí ir comparándola con los diversos números.
    min=  #el número que quieras pero que sea más grande que cualquiera de los que puedas tener (una exageración vamos)
for x in lista:
   if(min < x.Metros):
      min=x.Metros
#Se imprime el menor
print min

Creo que con eso bastaría c:

A: Una forma muy compacta de resolverlo podría ser:
lista = [['Metros: 405', 'edificio A', 'San Lorenzo'],
         ['Metros: 1843', 'edificio B', 'Eusebio Blanco'],
         ['Metros: 3067', 'edificio C', 'Av. San Martín Sur , Godoy Cruz'],
         ['Metros: 2863', 'edificio D', 'Tomás Godoy Cruz']]

print(min([(e,float(e[0].split()[1])) for e in lista],key = lambda x: x[1])[0])

['Metros: 405', 'edificio A', 'San Lorenzo']

Detalle:

*

*Por comprensión de listas: [(e,float(e[0].split()[1])) for e in lista] armamos una nueva lista de tuplas que contendrá el elemento original junto con los metros llevados a unfloat. Con split() separamos el primer elemento de cada lista (los metros) por el espacio ya que solo nos interesa el número.

*Usamos min() sobre la lista anterior, indicando sobre que índice de las tuplas se aplicará: key = lambda x: x[1]


text:
Q: Is it possible to draw polylines in Timemap.js? I just want to ask,is this possible to create polyline and draw moving car in timemap.js ? just like this
   moving car.
 var carPolyline = new google.maps.Polyline({
        map: map,
        geodesic : true,
        strokeColor : '#FF0000',
        strokeOpacity : 1.0,
        strokeWeight : 2,
        icons: [{
          icon: iconcar,
            scale: .1,
          offset: '100%'
        }],
    });
    var carPath = new google.maps.MVCArray();
    for ( var i = 0; i < path_start.length; i++) {
        if(i === 0) {
            carPath.push(path_start[i]);
            carPolyline.setPath(carPath);
        } else {
            setTimeout((function(latLng) {
                return function() {

                    carPath.push(latLng);
                    map.setCenter(latLng);
                };
            })(path_start[i]), 100 * i);
        }
    }
}

I want to move that car every time I drag the timeline. Is this possible?
Thank you in advance.


text:
Q: how to open link in a new window and set size after page load? I have a link with querystring like "...com/default3.aspx?id=123?code=456" This link create automatically and sending in mail as a hyperlink. I design default3.aspx page and doing some operations according to querystring. Is that a way open this link in a new window and set window size, after clicked from mail this link?
I tried this but it doesn't work.
<body onload="resizeWindow()" >
...
    <script type="text/javascript">
    function resizeWindow()
   {
    // you can get height and width from serverside as well
    var width=100;
    var height=100;
    window.resizeTo(width,height);
    }
    </script>

Thank you.

A: Try to open window using window.open like window.open("", "", "width=200, height=100");
Check out sample code at W3Schools http://www.w3schools.com/jsref/met_win_open.asp
Check for demo using Try it yourself

A: I think You should use this javascript function as i have used the same code in many of my webforms and it is also tested.
window.open('Redirecturl.aspx','Graph','height=600,width=800,resizable=yes');


text:
Q: I cannot get my printf statements to align in java I am having a spot of trouble with my printf statements. I cannot get them to accurately. This is the code snippet that I am having trouble with.
while(choice != 4){
        if(choice == 1){
            System.out.println("NAME            ID          GPA\n");
            for(j = 0; j < i ;j++){
                System.out.printf("%s", fullName[j]);
                System.out.printf("%10d", id[j]);
                System.out.printf("%15.2f\n", gpa[j]);
            }
            System.out.println("");
        }

It prints this.
NAME            ID          GPA

Hoffman Caleb Joseph         1           4.00
Jones Bob Cray         2           3.80
Mitten Jose Crush         3           1.53

How can I get it to all line up?

A: If you add an int to the name format statement it will align the text:
 System.out.printf("%20s", fullName[j]);

will print
Hoffman Caleb Joseph         1           4.00
      Jones Bob Cray         2           3.80
   Mitten Jose Crush         3           1.53

If you want to left justify it then put a minus in front
 System.out.printf("%-20s", fullName[j]);

will print
Hoffman Caleb Joseph         1           4.00
Jones Bob Cray               2           3.80
Mitten Jose Crush            3           1.53

As an aside, you don't need 3 separate format statements, you can combine all 3 into 1:
System.out.printf("%-20s%10d%15.2f%n", fullName[j], id[j], gpa[j]);

Also note the new line is %n not \n.  %n is a format string that will print system dependent new line character(s)

A: In your format specifiers you should use  a - like "%-10d to align the columns.


text:
Q: Meaning of "Look at me still talking when there's science to do" It's a famous video game song.
I really can't break it down to normal sense (being non-native). Also, I feel it's slightly glitched grammar.
Anyway, what does it mean?

A: It means the speaker is saying they are wasting time talking

Look at me still talking

when there is something else that needs to be done

when there's science to do.

Consider

Look at us complaining we are hungry when we should just find a place to eat.


text:
Q: Delphi: Where is Firedac Components Editors source code? I'm working with Delphi and Firedac components.
I need to find out the Components Editor source code of Firedac components. For example FDQuery has a Component Editor with 4 items, as you can see in figure below.
My question is simple, where is Component Editor source code of FDQuery? In source directory i'm able to find only Component Editor of TDataset (class TDataSetEditor in DBReg.pas ). FDQuery should have a custom Component Editor, due to its 4 items. Where i can found its implementation??
Thank you.


text:
Q: php oop call method from another class I'm new to OOP. I'm trying to keep the SOLID principles. Got some questions. This is my code. Is there a way to access the class FileManager methods in class GenericUploader(use abstract class because I can provide some base functionality) when I pass as dependency class Image(), class Video() or something else in UploaderClient? Goal is always to have access to class FileManager methods, no metter if I pass as dependency image, video or filemanager?
interface IFile
{
    public function crete(array $data);
}

interface IFileManager extends IFile
{
    public function exist(int $id);
}

class FileManager implements IFileManager
{
    public function crete(array $data)
    {
        // store in DB files
    }

    public function exist()
    {

    }
}

class Image implements IFile
{
    public function crete(array $data)
    {
        //access to FileManager
        // store in DB image and files
    }
}

abstract class GenericUploader
{
    public $service;

    public function __construct(IFile $service)
    {
        $this->service = $service;
    }

    public function upload()
    {
        //access to FileManager if $service is new Image()
    }
}

class ImageUploader extends GenericUploader
{
    public function __construct(IFile $service)
    {
        parent::__construct($service);
    }
}

class FileManagerUploader extends GenericUploader
{
    public function __construct(IFile $service)
    {
        parent::__construct($service);
    }
}

class UploaderClient
{
    public function uploadFile(IFile $service)
    {
        $name = get_class($service);
        $uploaderClass = $name . 'Uploader';

        if (class_exists($uploaderClass)) {
            $uploader = new $uploaderClass($service);
            $uploader->upload();
        }
    }
}

$client = new UploaderClient();
$client->uploadFile(new Image());
$client->uploadFile(new FileManager());

Update: if I extend Image, for example
class Image extends FileManager implements IFile
    {
        public function crete(array $data)
        {
            //access to FileManager
            // store in DB image and files
        }
    }

Is it wrong to access class FileManage methods on that way ($this->service->exist) from GenericUploader? Does it violate open/close principles?

A: If I understood write your question - please try my code. There is one trait, and it can help you:
UPD:
interface IFile
{
    public function crete(array $data);
}

// You can only implement interface, but not extends
class Image implements IFile
{
    public function crete(array $data)
    {
        //access to FileManager
        // store in DB image and files
    }
}

class FileManager implements IFile
{
    public function crete(array $data)
    {
        // store in DB files
    }

    public function exist(int $id)
    {

    }
}

abstract class GenericUploader extends FileManager
{
    public $service;

    public function __construct(IFile $service)
    {
        $this->service = $service;
    }

    public function upload()
    {
        //access to FileManager if $service is new Image()
    }
}

class ImageUploader extends GenericUploader
{
    public function __construct(IFile $service)
    {
        parent::__construct($service);
    }
}

class FileManagerUploader extends GenericUploader
{
    public function __construct(IFile $service)
    {
        parent::__construct($service);
    }
}

class UploaderClient
{
    public function uploadFile(IFile $service)
    {
        $name = get_class($service);
        $uploaderClass = $name . 'Uploader';

        if (class_exists($uploaderClass)) {
            $uploader = new $uploaderClass($service);
            $uploader->upload();
        }
    }
}

$client = new UploaderClient();
$client->uploadFile(new Image());
$client->uploadFile(new FileManager());


text:
Q: Eagle: Pins on FPGA exchangeable, depending on configuration I'm trying to do the PCB design, using Eagle, for a small board with an FPGA that basically just routes the I/O lines to the outside.
So, for the purpose of routing this board, the pins are basically interchangeable, but obviously this doesn't transfer to the next design, so I'd rather not assign them the same swaplevel statically.
Is there a way to dynamically alter the swaplevel of the pins of components placed in a concrete project, or can I make components configurable in that way?

A: No. Eagle does not have this functionality in its current (v6) form. I don't know of any plans to add it.


text:
Q: Can't find mitmproxy-ca-cert.pem I installed mitmproxy on a Mac and a Linux but I can't seem to find the certificate. All tutorials seem to assume it is downloaded upon installation but I can't find it.
Any ideas?

A: Take a look at the mitmproxy documentation:

The mitmproxy CA cert is located in ~/.mitmproxy after it has been generated at the first start of mitmproxy.

I.e. you need to run Mitmproxy at least once for this directory to appear.


text:
Q: Three div's in two columns - equal height I need the following Layout:
+-----------+-----------+
|           |           |
|   Div A   |           |
|           |           |
|           |           |
+-----------+   Div C   |
|           |           |
|    Div B  |           |
|           |           |
|           |           |
+-----------+-----------+

The boxes should be responsive and contain images (one for each box).
I am using bootstrap 3 and found a possible solution, unfortunately the heights depend also on the image size. I can't use tables and the layout has to be responsive, so a fixed height is no solution. I searched trough stackoverflow but I could not find a solution.
One approach is this (which is working well in the fiddle, except the images:

var colHeight = $(".slider").height();
var colHeight2 = colHeight - 30;
$('.child').css('min-height', colHeight2 / 2);
.slider {
  background: #555;
}
.image1 {
  margin-bottom: 30px;
  background: #555;
}
.image2 {
  background: #555;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

And I`ve created a fiddle here:
JsFiddle

A: You could check display:flex. I would do the below:

.outer-container {
        width: 50%;
        margin: 0 auto;
    }
    .outer-container, .inner-container {
        display: flex;
    }
    .inner-container {
        flex-direction: column;
    }
    div {
        border: 1px solid;
    }

A: try this code in your jsfiddle

A: You could assign
display:flex;

To all the child div's in the row class.
example here http://codepen.io/tom-maton/pen/Ywdzeo

A:


text:
Q: Subfields of $\mathbb{C}$ isomorphic to $\mathbb{R}$ Is there any subfield of $\mathbb{C}$ which is isomorphic to $\mathbb{R}$ but not $\mathbb{R}$ ?

A: Let $B$ be a trascendence basis of $\mathbb R$ over $\mathbb Q$, so that $\mathbb R$ is an algebraic extension of $\mathbb Q(B)$. The set $B$ is infinite: let $B'$ be the result of removing one element. Since $B$ and $B'$ are in bijection, there is an algebraic extension of $\mathbb Q(B')$ contained in $\mathbb C$ which is isomorphic to $\mathbb R$, and it is not $\mathbb R$ because it does not contain the element we removed.


text:
Q: Succint syntax of converting to Map and accessing element I'd like to access values of a list converted to a Map in the syntactially most correct and immediate way. I seem to be missing something, as
val lit = List(('a',1), ('b',2), ('c',3))
val m = lit.toMap
println( m('c') )

obviously works as expected, printing 3.
However,
println( lit.toMap ('b') )

fails with a 'Type Mismatch', regardless of my attempt to put brackets around the lit.toMap expression. I must be missing something very silly, but what is it?

A: List.toMap takes an implicit parameter, when you write
lit.toMap

It will be compiled to
lit.toMap(Predef.$conforms[(Char, Int) <:< (Char, Int)])

So if you place () right after toMap, no matter lit.toMap() or (lit.toMap)() Scala compiler expects you to pass in the implicit parameter explicitly, so you need to write:
lit.toMap(implicitly[(Char, Int) <:< (Char, Int)])('b')

Or
lit.toMap.apply('b')


text:
Q: UNEXPECTED TOP LEVEL EXCEPTION while integrating a library project I am trying to integrate DHIS2 SDK into my app by trying to import the library project.
My settings.gradle looks like
include ':app', ':sdk', ':core', ':persistence', ':core-java', ':models'
project(':sdk').projectDir = new File(settingsDir, '../dhis2-android-sdk-master/app')
project(':core').projectDir = new File(settingsDir, '../dhis2-android-sdk-master/core')
project(':persistence').projectDir = new File(settingsDir, '../dhis2-android-sdk-master/persistence')
project(':core-java').projectDir = new File(settingsDir, '../dhis2-android-sdk-master/core-java')
project(':models').projectDir = new File(settingsDir, '../dhis2-android-sdk-master/models')

Now after the gradle sync when I try to run the app it gives me the following build error
UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Exception parsing classes
at com.android.dx.command.dexer.Main.processClass(Main.java:752)
at com.android.dx.command.dexer.Main.processFileBytes(Main.java:718)
at com.android.dx.command.dexer.Main.access$1200(Main.java:85)
at com.android.dx.command.dexer.Main$FileBytesConsumer.processFileBytes(Main.java:1645)
at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
at com.android.dx.command.dexer.Main.processOne(Main.java:672)
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:574)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
Caused by: com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)
at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:472)
at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
at com.android.dx.command.dexer.Main.parseClass(Main.java:764)
at com.android.dx.command.dexer.Main.access$1500(Main.java:85)
at com.android.dx.command.dexer.Main$ClassParserTask.call(Main.java:1684)
at com.android.dx.command.dexer.Main.processClass(Main.java:749)
... 12 more
1 error; aborting
Error:Execution failed for task ':app:preDexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_65\bin\java.exe'' finished with non-zero exit value 1

Any idea how can I solve this?


text:
Q: Azure Webapp x-frame-options defined but Cloudflare seems to add sameorigin We're hosting a .NET application on a WebApp in Azure. This has a web.config defined where we:

*

*remove x-frame-options

*add x-frame-options: ALLOW FROM randomurl.com;

When we directly go to the webapp with the hostname of azurewebsites, we get the correct x-frame-options defined.
However, when we go through Cloudflare, it always seem to add x-frame-options: SAMEORIGIN
Resulting in 2 x-frame-options in the response and probably ignoring our ALLOW since SAMEORIGIN is stricter.
I've checked all possible settings in Cloudflare but I can't find anything that would add this header.
We don't have any HTTP Response Header Modification set.
I don't think any WAF ruleset would automatically add a header.
Anyone has some ideas where to look further or what to test?


text:
Q: Get the geolocation of a tweet I an conducting a Twitter search and need to get the exact location of each tweet to plot on a map. I have set up core location and my code for 'fetching the tweets' is as below.
I am currently looping through to get the text component but I am unsure how to also get the location component that accompanies the tweet. You will see a couple of lines below that I have added to the loop to try and extract the location, however it is coming up blank / null.
• Am I positioning the NSString *twitlocation in the correct location in the loop? will this collected location marry up with the correct text for each tweet is I call it from separate arrays, i.e the text from tweet 1 and the location from tweet 1 will marry up when I run objectAtIndex:0 ? • Why is the log for twitterLocation null? • Am I correct in putting the locations in a NSString to add to an array or should it be a different object?
FYI's

*

*All objects have been declared in .h file - The twitText works correctly and I can get the tweets text for each tweet - twitterLocation is a NSMutableArray

Thanks!

- (void)fetchTweets
        {
            AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];

            //NSLog(@"phrase carried over is %@", delegate.a);

            // Do a simple search, using the Twitter API
            TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
                                                                 [NSString stringWithFormat:@"http://search.twitter.com/search.json?q=%@", delegate.a]]
                                                     parameters:nil requestMethod:TWRequestMethodGET];

            // Notice this is a block, it is the handler to process the response
            [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
             {
                 if ([urlResponse statusCode] == 200)
                 {
                     // The response from Twitter is in JSON format
                     // Move the response into a dictionary and print
                     NSError *error;
                     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
                     //NSLog(@"Twitter response: %@", dict);

                     NSArray *results = [dict objectForKey:@"results"];

                     //Loop through the results

                     for (NSDictionary *tweet in results) {
                         // Get the tweet
                         NSString *twittext = [tweet objectForKey:@"text"];
                         //looping through to also get the location of each tweet
                         NSString *twitlocation = [tweet objectForKey:@"location"];

                         // Save the tweet to the twitterText array
                         [_twitterText addObject:twittext];
                         //adding the twitlocation to the location array
                        [twitterLocation addObject:twitlocation];
                     }

                     dispatch_async(dispatch_get_main_queue(), ^{

        [self.tableView reloadData];

                     });

                      NSLog(@"MY ************************LOCATION************** %@", twitterLocation);

                 }

                 else
                     NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
             }];

        }


text:
Q: Symbolic vector norm with indexed variables I'd like to express a vector norm of the difference of two indexed variables. In mathematical notation what I'm after is:
|| x_a - y_b ||

Where x and y are sets of points in some space. In Sympy I've managed to create the variables:
x = sp.IndexedBase('x')
a = sp.Idx('a')
y = sp.IndexedBase('y')
b = sp.Idx('b')

And express a simple difference:
diff = (x[a] - y[b])

But how could I express the norm? It seems that every reference I've found to calculating norms leads to matrices. The variables indeed represent vectors, but I don't really care about the dimensionality.
Are there indexed matrices, should I use matrix columns and just choose a dimensionality, or is there some other way of formulating a norm?

EDIT:
I made some progress and tried to do it using another index common to both vectors, i.e. the supposed dimensionality.
N, D = sp.symbols('N D', integer=True)
d = sp.Idx('d', D)

x = sp.IndexedBase('x')
a = sp.Idx('a', N)
y = sp.IndexedBase('y')
b = sp.Idx('b', N)
norm = sp.sqrt(sp.Sum((x[a, d] - y[b, d]) ** 2, (d, 0, D - 1)))

This works indeed, but what I can't do is then e.g. differentiate with respect to the reduced index x[a]. In my mind the d index should be reduced in that expression, especially because the dimensionality is defined and the summation is done over the full range. Am I still missing something?


text:
Q: Unhandled exception in celery freezes workers I am running celery in docker via a redis backend. I have

*

*celery-beat container

*celery-worker container

*redis container

The celery worker container spawns 6 worker processes. If a celery task encounters an exception, the workers (all of them) stop consuming jobs. I tried to debug the processes a bit and it appear a single process will get stuck on pipe read and the rest on a futex call.
Debugging info:
# Worker 1
$ sudo strace -p 15959 -s 10000
strace: Process 15959 attached
read(4, ^Cstrace: Process 15959 detached
 <detached ...>

# Worker 2 through N
$ sudo strace -p 15960 -s 10000
strace: Process 15960 attached
futex(0x7f95c3f94000, FUTEX_WAIT_BITSET|FUTEX_CLOCK_REALTIME, 0, NULL, 0xffffffff^Cstrace: Process 15960 detached
 <detached ...>

$ sudo lsof -p 15958
COMMAND   PID USER   FD      TYPE DEVICE SIZE/OFF   NODE NAME
celery  15958 root  txt       REG  0,197    32248 264184 /usr/local/bin/python3.5
...
celery  15958 root    4r     FIFO   0,12      0t0 348559 pipe  # frozen here

Strangely, the workers will stay in a frozen state permanently, unless 1 of 2 things happen:

*

*Restart the workers (docker restart celery-worker)

*Jump start celery.

The "jump start celery" I find amusing. By issuing this command all the workers "wake up" and spring back to life and start consuming tasks until the next exception.
docker exec -it celery-worker celery -A CELERY_APP inspect active

Here the worker sprang back to life.
$ sudo strace -p 15958 -s 10000
strace: Process 15958 attached
read(4, "\0\0\3\36", 4)                 = 4
read(4, "\200\3K\2(Mj\nNccelery.app.trace\n_fast_trace_task\nq\0(X\"\0\0\0tasks.status_taskq\1X$\0\0\00071bf9972-cf5b-4a20-a8b7-ce4d7921fe0dq\2}q\3(X\t\0\0\0parent_idq\4NX\4\0\0\0langq\5X\2\0\0\0pyq\6X\3\0\0\0etaq\7NX\5\0\0\0groupq\10NX\7\0\0\0expiresq\tNX\t\0\0\0timelimitq\n]q\v(NNeX\6\0\0\0originq\fX\21\0\0\0gen1@03e7668436e5q\rX\10\0\0\0argsreprq\16X\2\0\0\0()q\17X\n\0\0\0kwargsreprq\20X\2\0\0\0{}q\21X\10\0\0\0reply_toq\22X$\0\0\0005ad0db0b-a759-375c-b173-07598914633eq\23X\4\0\0\0taskq\24h\1X\16\0\0\0correlation_idq\25X$\0\0\00071bf9972-cf5b-4a20-a8b7-ce4d7921fe0dq\26X\7\0\0\0root_idq\27X$\0\0\00071bf9972-cf5b-4a20-a8b7-ce4d7921fe0dq\30X\7\0\0\0retriesq\31K\0X\r\0\0\0delivery_infoq\32}q\33(X\10\0\0\0priorityq\34K\0X\10\0\0\0exchangeq\35X\0\0\0\0q\36X\v\0\0\0redeliveredq\37NX\v\0\0\0routing_keyq X\6\0\0\0celeryq!uX\6\0\0\0shadowq\"NX\2\0\0\0idq#h\2uCM[[], {}, {\"chord\": null, \"chain\": null, \"errbacks\": null, \"callbacks\": null}]q$X\20\0\0\0application/jsonq%X\5\0\0\0utf-8q&tq'}q(tq)\206q*.", 798) = 798
futex(0x7f95c3f94000, FUTEX_WAKE, 1)    = 1
write(7, "\0\0\0\34\200\3K\0(Mj\nNG@\327\204T\213\21\21\\K\nNtq\0\206q\1.", 32) = 32
getpid()                                = 10

Any idea why this is? Is this a bug? Is there something I can configure so celery does not hang on task exception?

A: I am using eventlet and I was running the workers with the default pre-fork pool. Switching to the eventlet pool seems to have fixed the problem.
Ie
celery worker -A CELERY_APP --pool eventlet


text:
Q: Empty datetime in the report I face the following problem :
Sometimes the value of my trans_in(DateTime) in my database is :1900-01-01 00:00:00.000
and it appears in my telerik report like this 12:00 AM i want to show the textbox empty instead so i create the following custom method :
  public static string NotAttend(DateTime trans_in)
        {
            if (trans_in == null || trans_in.ToString().Trim() == "1900-01-01 00:00:00.000")
            {
                return string.Empty;
            }
            else
                return trans_in.ToShortTimeString();
        }

and bind the textbox like this :
= OvertimeReports.CustomExpressions.NotAttend(Fields.trans_in)

but this didn't fix my problem still appear 12:00 AM !!

A: Your trans_in.ToString() would return you the string representation of your DateTime object based on your current culture, its better if you check your DateTime like:
public static string NotAttend(DateTime trans_in)
{
   if(trans_in == new DateTime(1900, 1, 1))
   {
        return string.Empty;
   }
    else
        return trans_in.ToShortTimeString();
}

A: The problem what you have here is more of a formatting issue with the .ToString conversion
Try using the specific format you need in the .ToString overload for this
trans_in("yyyy-M-d HH:mm:ss.fff")
So in this HH case you would have it as 00:00 instead of 12:00
A better way would be to compare it as DateTime make a DateTime obj for 1900-1-1 then compare it with trans_in.Date part which would not involve this string formatting issues

A: Try to compare the trans_in with default(new DateTime())
You shouldn't compare a date with a String without formatting it
reference:
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/d0f4578c-0585-4f38-95be-569a90ebeb21/
edit: i'm seeing here you'd best compare with DateTime.MinValue
Determining whether the new date is the default new DateTime() or not

A: You can provide a format to your DateTime by using overridden function of DateTime.ToString(). HH means time in 24 HRS where hh means 12 HRS format :
 public static string NotAttend(DateTime trans_in)
 {
   if (trans_in == null ||
       trans_in.ToString("yyyy-MM-dd HH:mm:ss.fff") == "1900-01-01 00:00:00.000")
     {
       return string.Empty;
     }
   else
    return trans_in.ToShortTimeString();
  }


text:
Q: unlink(/tmp/ci_sessiond8a5986a5bee06644d54af5adc7c8d8851c2f987): Operation not permitted error
Sometimes display this error in my updated server,but if I refresh browser, it browse to normal application.
How can I solve this error.
I'm using CodeIgniter-3.0.6
welcome to any help.

A: its just solved by $config['sess_save_path'] = 'tmp/'; inside the config file, bydefault its NULL there so change to path and make sure that folder have 775 permission.

A: chmod 777 your temp directory. check group/user permissions if your application (server) has the rights for reading writing.

A: If you want to delete file in Codeigniter you can use file helper.
$this->load->helper("file");
delete_files($path);


text:
Q: Run rails app under subfolder I've been testing my rails app on localhost:3000 and it works just fine. However, when deploying to my host, the root URL is:
http://99.88.77.66/~username
I do not have a domain name at this point.
When I point the browser to the above URL I get the root not found for:
/~username
Alternatively for
http://99.88.77.66/~username/controller/index
I get this route not found:
/~username/controller/index
I'm using Rials 4.2.3 and Ruby 2.0.
How can I make my routes work with this kind of subfolder until I can get an appropriate domain name?

A: Try setting config.relative_url_root in config/environments/production.rb:
http://guides.rubyonrails.org/configuring.html#deploy-to-a-subdirectory-relative-url-root


text:
Q: Filter open GitHub PRs that are out-of-date / up-to-date with the target branch? On a GitHub repo that has the Require branches to be up to date before merging branch protection rule enabled and that often has several open pull requests, PRs will frequently be merged in an order that requires more merge commits and CI runs than necessary.
Is there a way to quickly identify which open PRs are currently up-to-date with the base branch?

For example, with three approved open PRs:

*

*PR_A, approved but not up-to-date with main, will need main merged into the A branch and another CI run before being merged into main

*PR_B, similar to PR_A, will also need a merge from main & CI run

*PR_C, approved and up-to-date with main, could be merged immediately with no extra commit or CI run.

If PR_A or PR_B are merged first, PR_C would become out-of-date, unnecessarily requiring a merge commit from main & a CI run.
What search syntax or automatic system would highlight PR_C as the PR that should be merged first?


text:
Q: How do I show that the sup norm metric is a metric for $\Bbb{R}^n$? (the triangular inequality specifically) I am not sure how to approach such inequality. I have shown the other 3 requirement for the sup norm to be a metric for $\Bbb{R}^n$.
For $x,y,z\in \Bbb{R}^n$, we need to show that
$$\sup\{\lvert x_i - z_i\rvert \}\leq \sup\{\lvert x_i - y_i \rvert \} + \sup\{\lvert y_i - z_i \rvert \}\text{ for }i\in \{1,2,...,n\}$$
My thought is that this should be related to the cauchy schwarz inequality. But not sure how to start. since C.S is in the series form not in the supremum form.
Thanks for help

A:
Lemma: Suppose $S$ is a set and $f, g : S \to \Bbb{R}$. Then
  $$\sup_{s \in S} (f(s) + g(s)) \le \sup_{s \in S} f(s) + \sup_{t \in S} g(t).$$

Proof: Suppose $S, f, g$ are as in the statement. Note that, for any $s_0 \in S$, we have
\begin{align*}
f(s_0) \le \sup_{s \in S} f(s) \\
g(s_0) \le \sup_{t \in S} g(t),
\end{align*}
hence
$$f(s_0) + g(s_0) \le \sup_{s \in S} f(s) + \sup_{t \in S} g(t).$$
That is, $\sup_{s \in S} f(s) + \sup_{t \in S} g(t)$ is an upper bound for $\{f(s) + g(s) : s \in S\}$, hence
$$\sup_{s \in S} (f(s) + g(s)) \le \sup_{s \in S} f(s) + \sup_{t \in S} g(t).$$

In particular, apply the lemma with $S = \{1, \ldots, n\}$, $f : i \mapsto |x_i - y_i|$, and $g : j \mapsto |y_j - z_j|$. Then,
$$\sup_i (|x_i - y_i| + |y_i - z_i|) \le \sup_i |x_i - y_i| + \sup_j |y_j - z_j|.$$
Note that, by triangle inequality, we have $|x_i - z_i| \le |x_i - y_i| + |y_i - z_i|$, and hence taking the supremum of both sides, we get
$$\sup_i |x_i - z_i| \le \sup_i (|x_i - y_i| + |y_i - z_i|) \le \sup_i |x_i - y_i| + \sup_j |y_j - z_j|,$$
which is what we needed!


text:
Q: Looking for a method to handle a large diagram model for a generic purpouse context After years of developing i've decided to draw a mind "map"/"diagram" to organize all projects i've created.
I should be able to:

*

*create visual relations between

*

*projects

*frameworks / libraries

*programming languages

*hosting services

*add/remove items easily without reorganize everything at each
change ( maybe some auto-ordering tool ) since i've tons of projects
and temporary works

*add popup rich-text notes for each item
which kind of model do you suggest to use for this purpose?
Is there any Linux/Crossplatform ( possibly freeware ) software that could accomplish tasks above?
i've tried to use some basic software for UML creation such as google draw / libreoffice draw .. but they are poor of features for large models.

A: You can use a class diagram with stereotyped classes (e.g. <<idea>>) for that purpose. Depending on the tool it might look a bit clumsy but likely feasible. Enterprise Architect has a special MDG for mind mapping where special connectors (and stereotyped classes) are used.
FWIW: I'd use a simple mind map freeware. Those are designed specifically towards mind mapping (as their name suggest). E.g. Freemind saves data in XML format and it should be possible to move data over to XMI via XSLT.


text:
Q: Circle with points on its boundary and chords between points I am trying to visualize a perfect matching by drawing a circle with a given even number of points on its boundary and some number chords going between these points so that each point is incident to exactly one chord. This is my current output:
The code I'm using is modified from another example. At the moment, I get almost what I want.
\documentclass{article}
\usepackage{tikz}

\newcommand\matching[2]{
\begin{tikzpicture}
\foreach \x [count=\p] in {0,...,#1} {
    \node[shape=circle,fill=black, scale=0.5] (\p) at (-\x*360/#1:2) {};};
\foreach \x [count=\p] in {1,...,#1} {
    \draw (\x*360/#1:2.4) node {\p};};
\draw (1) arc (1:360:2);
\foreach \x/\y in {#2} {
   \draw (\x) -- (\y);}
\end{tikzpicture}}

\begin{document}
\matching{8}{7/4, 2/5, 1/8, 6/3}
\end{document}

In the above example, I want the chords between the following points 7/4, 2/5, 1/8 and 6/3 which is not in agreement with the picture. Furthermore, I would like to have the point 1 in the uppermost position instead of the 2.

A: I don't fully understand what you mean with the connections being different between your code and your output, but you can use the following code, which is a bit simpler than your approach:
\documentclass[tikz]{standalone}
\usetikzlibrary{calc}

\newcommand\matching[2]{%
 \begin{tikzpicture}
  \draw (0,0) circle (2);
  \foreach \x in {1,...,#1} {
   \node[shape=circle,fill=black, scale=0.5,label={{((\x-1)*360/#1)+90}:\x}] (n\x) at ({((\x-1)*360/#1)+90}:2) {};
  };
  \foreach \x/\y in {#2} {
   \draw (n\x) -- (n\y);
  }
 \end{tikzpicture}%
}

\begin{document}
\matching{8}{7/4, 2/5, 1/8, 6/3}
\end{document}

Resulting in:


text:
Q: Strange navigation pane
My appendices.tex file begins with
\appendix
\addcontentsline{toc}{chapter}{AppendicesTOC}

and the appendix was included in the main text using the command
\include{appendices}

I want the AppendicesTOC appear as a separate 'chapter' (same hierarchy as 'My 2nd paper') but it appears as a subsection under the section 'conclusion.'
How can I solve this?

A: You have to change the value of tocdepth just for the appendices. It's probably not necessary to reset it afterwards, since the appendices are at the end.
In the appendices tex file, ensure the counter of the the variable {tocdepth} is set to zero.
\begin{appendices}
\addtocontents{toc}{\protect\setcounter{tocdepth}{0}}
\end{appendices}


text:
Q: Field 'id' expected a number but got 'std1', how do I get the ForeignKey ID of a Model field to use in Django Form? I have Detail Model, which have the ForeignKey of the Django's default User Model. I created a Form to take the input from user and update the Detail Model fields if it exists else create a new detail.
For this purpose, I am filtering the Detail.objects.all() on the username of the user which was selected in the Form at Front-End. Now, I need a ID of the username that was selected in order to update the Detail Model. How can I get the ID? If I just pass the username, it says Field 'id' expected a number but got 'std1'.
My models.py:
class Detail(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser': False, 'is_staff': False}, verbose_name="Select a Student")
    subject = models.CharField(max_length=50, verbose_name='Subject Name', help_text='Write the name of the subject.')
    skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.")
    internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.")
    programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of 25.")
    mid_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(45)], verbose_name="Mid_Term Marks (of this subject, in numbers)", help_text="Enter the total mid-term marks of this subject, the student obtained out of 45.")
    final_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(90)], verbose_name="Final_Term Marks (of this subject, in numbers)", help_text="Enter the total final-term marks of this subject, the student obtained out of 90.")

    def __str__(self):
        return f'{self.user.username}-{self.subject}'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

My forms.py:
class UpdateStudentDetailsForm(forms.Form):
    stds = forms.CharField(widget=forms.Select(choices=STUDENTS_LIST), label='Select a Student')
    subject = forms.CharField(max_length=50)
    skype_session_attendance = forms.FloatField(min_value=0, max_value=20, label="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.")
    internal_course_marks = forms.FloatField(min_value=0, max_value=40, label="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.")
    programming_lab_activity = forms.FloatField(min_value=0, max_value=25, label="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of 25.")
    mid_term_marks = forms.FloatField(min_value=0, max_value=45, label="Mid_Term Marks (of this subject, in numbers)", help_text="Enter the total mid-term marks of this subject, the student obtained out of 45.")
    final_term_marks = forms.FloatField(min_value=0, max_value=90, label="Final_Term Marks (of this subject, in numbers)", help_text="Enter the total final-term marks of this subject, the student obtained out of 90.")
    print(stds)
    class Meta:
        fields = ['stds', 'subject', 'skype_session_attendance', 'internal_course_marks', 'programming_lab_activity', 'mid_term_marks', 'final_term_marks']

My views.py:
def updateStudentDetails(request):
    if request.method == 'POST':
        std_form = UpdateStudentDetailsForm(request.POST)

        if std_form.is_valid():
            details = std_form.cleaned_data
            usr = details['stds']

            old_details = Detail.objects.get(user=usr)      # HERE I NEED TO PUT ID INSTEAD OF 'usr'
            old_details.subject = details['subject']
            old_details.skype_session_attendance = details['skype_session_attendance']
            old_details.internal_course_marks = details['internal_course_marks']
            old_details.programming_lab_activity = details['programming_lab_activity']
            old_details.mid_term_marks = details['mid_term_marks']
            old_details.final_term_marks = details['final_term_marks']
            old_details.save()

            messages.success(request, 'Success! Academic Record/Details of ' + usr.first_name + usr.last_name + '(' + usr.username + ')' ' has been updated.')

            return redirect('update_student_details')
    else:
        std_form = UpdateStudentDetailsForm()

    return render(request, 'users/update_student_details.html', {'std_form': std_form})

A: I think design wise it has some flaws. Like here an User can have multiple Detail object as it is a ForeignKey relation. So calling old_details = Detail.objects.get(user=usr) will cause error when you have multiple instances of User. Now you can change it to OneToOne relation to avoid this problem:
class Detail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser': False, 'is_staff': False}, verbose_name="Select a Student")

Instead of Form, use forms.ModelForm. You can try like this:
class UpdateStudentDetailsForm(forms.Form):
    class Meta:
        model = Details
        exclude = 'user'

And instead of getting the stds data form, I would recommend using url to manage it. For example:
# view
def updateStudentDetails(request, user_id):  # Please use snake_case as per PEP-8 Standards
    user = get_object_or_404(User, user_id)
    if request.method == 'POST':
        std_form = UpdateStudentDetailsForm(request.POST, instance=user.detail)
        if std_form.is_valid():
            std_form.save()
            # redirect
    else:
       std_form = UpdateStudentDetailsForm(instance=user.detail)
    return render(request, 'users/update_student_details.html', {'std_form': std_form})

# url:
path('student/update/<int:user_id>/', updateStudentDetails, name="update_student_detail"),

Update
If you want to have One to Many relation between User and Detail object, then I would recommend getting Detail objects using pk.
If you insist on having a dropdown to select student, then use a different form to redirect to this updateStudentDetails page like this:
# form

Class StudentDetailChoiceForm(forms.Form):
    student = forms.ModelChoiceField(queryset=Detail.objects.all(), label="Choose a student")

# view

def redirect_to_student_update(request):
    form = StudentDetailChoiceForm(request.GET or request.POST)
    if form.is_valid():
        return redirect('update_student_detail', pk=form.cleaned_data['student'].pk)

And update the view of updateStudentDetails:
def updateStudentDetails(request, pk):  # Please use snake_case as per PEP-8 Standards
    detail = get_object_or_404(Detail, pk)
    if request.method == 'POST':
        std_form = UpdateStudentDetailsForm(request.POST, instance=detail)

BTW, you can use ModelChoiceField with your existing implementation, like:
class UpdateStudentDetailsForm(forms.Form):
    stds = forms.ModelChoiceField(queryset=Detail.objects.all(), label="Choose a student")

And rest of your implementation should work, but it won't be a clean solution as you will not be using DRY principle and you are getting data from form manually etc, where with ModelForm, the initial values would be visible in your template, less codes and Django takes care of the update itself.


text:
Q: Div for designing ASP.net Web Input Forms What is the recommended way of designing asp.net web forms using div and span. Assume that we want to design an input form for creating new customers, where it includes name, birth date, education etc.
Considering the above scenario, how div and span could be used for achieving seperation of concerns: seperation of presentation from content. We would like to define a form from the content perspective. Once a content and structure is in place, some designer can develop CSS and apply to it.
Please help. Thanks in advance.

A: There are many tutorials out there that show how to design css forms. IMHO it's more a matter of labels and inputs than divs and spans.

A:
 defines a rectangle, and forces a line break afterwards.
 is a sequence of characters, and does not force a line break.
<asp:Panel> generates a

<asp:Label> generates a
Which one you use where depends entirely on what you want your form to look like.

A: It is hard(but not impossible) to achieve full separation of concerns with asp.net web forms, it is lot easier to do it with asp.net mvc because of cleaner generated html...anyway, you have few options here...
-you can create user control with fields that you need, maybe generating inputs and labels dynamically on certain condition and then put it on your pages where you need it...for asp.net web forms world, it is fine separation
-you can try to build class for generating pure html with your labels and inputs..you will pass to the class list of properties with types(string, number) and class would know for which property to generate which label and which input field and you will render pure partial html on your page
cheers


text:
Q: Symfony 2 route error when adding parameters I seem to have come across an issue with Symfony 2 that I have not seen before (or more likley im missing something really obvious).
I had a route which took no parameters and worked perfectly, linking up to the controller and displaying the correct view. I then updated the route to take a single parameter like so:
# Note routing
    gibbo_dummy_notes_Add:
        pattern:  /notes/add/{notebook}
        defaults: { _controller: GibboDummyBundle:Note:add, notebook: 0}
        requirements:
                _method:  POST|GET

However if I now try and access this route notes/add/test I get the error The controller must return a response (null given). Did you forget to add a return statement somewhere in your controller?. If I remove the parameter it works perfectly notes/add.
This setup is exactly the same as the rest of the routes that use parameters in my app.
The action in the controller definitely returns a response object. If I place a die('test'); at the top of the action and remove the parameter from the URL I reach the die statement and see 'test', but if I add the parameter to the URL it shows the error, so its clearly not reaching my controller or action when including the parameter but as far as I can tell the route is setup correctly, and im not getting the normal route not defined error I would expect to see if there was an issue with the url.
Im running it under the dev environment and I have tried other browsers / cleared cache etc. The action inside the controller NoteController looks like
public function addAction($notebook)
{

    $pageTitle = 'Note';

    $form = $this->createForm(new NoteType(), null, array(
        'validation_groups' => array('add')
    ));

    $request = $this->getRequest();

    if ($request->isMethod('POST')) {
        $form->bind($request);

        if ($form->isValid()) {

            /** @var $em \Doctrine\ORM\EntityManager */
            $em = $this->getDoctrine()->getManager();

            /** @var $note Note */
            $note = $form->getData();
            $note->setNotebook();

            $em->persist($note);
            $em->flush();

            return $this->redirect($this->generateUrl('gibbo_dummy_note_View'));
        }
    }

    return $this->render('GibboDummyBundle:Note:new.html.twig', array(
        'pageTitle' => $pageTitle,
        'form_add'  => $form->createView(),
        'selected' => 'codebooks'
    ));

}

Can anyone shed some light about what I might be doing wrong?

A: Please add the controller code for gibbo_dummy_note_View route.
Most likely, your redirection ends up in a bad controller method - the one that does not have return statement


text:
Q: How can I get my grid column to stay the same size (height and width) when resizing viewports? I have a container that will have a picture of the day. When changing viewport sizes (mobile screen size) the container gets squashed so much that the image is not readable.. How can I get the containers in my grid system to stay the exact same size relative to the viewport? Thank you!!

html,
body,
form,
main {
  height: 100%;
}

body {
  background-color: #232A35;
  padding: 10px;
}

.content {
  height: 100%;
  margin-left: auto;
  margin-right: auto;
}

.mainheader {
  border: 1px red solid;
  width: 100%;
}

.iotd {
  grid-area: iotd;
}

.banner {
  grid-area: banner;
}

.solutions {
  grid-area: solutions;
}

.services {
  grid-area: services;
}

.tud {
  grid-area: tud;
}

.resources {
  grid-area: resources;
}

.grid-container {
  display: grid;
  grid-template-areas: 'iotd banner banner banner banner banner' 'iotd solutions services resources tud tud';
  gap: 10px;
  background-color: #2196F3;
  padding: 10px;
  height: 100%;
}

.grid-container>div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}

@media screen and (max-width: 900px) {
  .grid-container>div {
    font-size: 10px;
  }
}

IOTD

Banner

Solutions

Services

The Unrecovery Difference

Resources

The container that will hold the image is labeled as "IOTD"
Any help is appreciated

A: resolved the issue by changing the image size rather than the container size when the viewport reaches 900px. I also change the font size to a smaller size which in turn makes all of the containers smaller

A: One approach might be to include a grid-template-columns rule to specify how you want the horizontal space apportioned, this can include a minimum absolute (px) width for the first column with the option of allowing it to grow when more space is available using minmax.
For example, I've added the following rule to your css:
grid-template-columns: minmax(150px, 1fr)  repeat(5, 1fr);

This divides the grid into 6 columns to be consistent with your area template (which remains in operation) but makes the first column at least 150px wide with the option of expanding with the other columns when extra width is available. The remaining five columns are allocated 1/5 of the available space by specifying 5 1fr fractions.
Here's the rule added to your example:

html,
body,
form,
main {
  height: 100%;
}

body {
  background-color: #232A35;
  padding: 10px;
}

.content {
  height: 100%;
  margin-left: auto;
  margin-right: auto;
}

.mainheader {
  border: 1px red solid;
  width: 100%;
}

.iotd {
  grid-area: iotd;
}

.banner {
  grid-area: banner;
}

.solutions {
  grid-area: solutions;
}

.services {
  grid-area: services;
}

.tud {
  grid-area: tud;
}

.resources {
  grid-area: resources;
}

.grid-container {
  display: grid;
  grid-template-areas: 'iotd banner banner banner banner banner' 'iotd solutions services resources tud tud';
  grid-template-columns: minmax(150px, 1fr)  repeat(5, 1fr);
  gap: 10px;
  background-color: #2196F3;
  padding: 10px;
  height: 100%;
}

.grid-container>div {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}

@media screen and (max-width: 900px) {
  .grid-container>div {
    font-size: 10px;
  }
}

IOTD

Banner

Solutions

Services

The Unrecovery Difference

Resources

This page https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas has examples where grid-template-areas are combined with grid-template-columns (it also has some ideas on using media queries to suit different view ports).


text:
Q: c++ char array null character while loop I have a function that keeps on incrementing the char, so it will display the next char in the ascci code, but my problem is it never breaks the loop
     char * myFunction (char* &text)
       {
               char *temp = (char *)malloc(strlen(text));
                char *tmp = temp;
                while(*tmp != '\0')
                 {
                          *tmp = *text++;  //im incrementing the text
                          tmp +=1;

                 }
          return temp;

        }

       char *text = "hello";
        cout<<myFunction(text)<<endl;

A: while(tmp != '\0')

to be
while(*tmp != '\0')

tmp is the address of the start of the string which will never be '\0'

A: there are lots of problems in your code, I summarized them in comments below:
 // Making your argument char*& allows you to modify text variable from
 // calling function, I dont think this was your intention. If you just
 // want to pass string to this function change its type to `const char*`.
 // I dont think this return value you really want here, now you have char, but I
 // suppose you want to return string, so it should be `char*` or `const
 // char*`
 char myFunction (char* &text)
   {
           // sizeof(text) will return 4bytes, which is size of pointer,
           // you want strlen(text)+1 here to get length of string + 1
           // char for zero (end of string)
           char *temp = (char *)malloc(sizeof(text));
            char *tmp = temp;

            // You should dereference *tmp, but tmp is uninitialized here,
            // I think you want to use *text here.
            while(tmp != '\0')
             {
                      *tmp = *text++;  //im incrementing the text

                      // You are incrementing value pointed by tmp,
                      // if you want to increment tmp to next string
                      // element use tmp++;
                      *tmp +=1;

             }

             // Here assign zero to last element of text

      // temp is char* and your return value is char, this is wrong,
      // you should change return value of myFunction to char*. Also
      // remember to call free() on returned string once its no
      // longer needed - otherwise you will introduce memory leaks
      return temp;

    }

   // This should be `const char *text = "hello";` In c++ string
   // literals are of type `const char*`
   char *text = "hello";
    cout<<myFunction(text)<<endl;


text:
Q: MySQL table/query design - multiples of one item, many comments I have a site which display images, up to 30 per page.
Users can comment on the images and these comments, or at least the first few, appear under the image if there are comments.
I have a table of image references linked to a folder on my server.
e.g.
image_id // image id
user_id // user who added
image_url // ref to image

Then a separate table for all comments
comment_id
image_id // link to images table
comm_poster_id // id of user who posted comment

Now, the question is what the best way to call the information together? Ideally in one select
I can't really ajax call under each image as that would be 30 db calls per page which would kill it so whats the alternative/best method?
To clarify, in the select there would only ever be 1 image but there could of course be multiple comments for an image
Hope i've given enough info
EDIT To clarify, the question is what is the best way to collate all this information together for display - can I run one query which pulls all the images in on the page also somehow pulls the comments for images in if they exist.
As for how I would like the data to look... I don't know. This is the first time I've done anything like this so guidance needed if possible.

A: Ok, well I'm not a php expert, but I got you started on the sql side of things. I CAN help you with php, but there are others here that are more versed in it that I am.
I started this sqlFiddle for you, go have a look and you can tinker with the query to get what you want.
http://sqlfiddle.com/#!2/79ecf/1/0
From the php side, until you know how you want to display your data, it's difficult to say what your query needs to look like. I went with this for the time being:
select *
from images i
inner join comments c on i.image_id=c.image_id;

This is a VERY simple query and you will probably end up needing to add to it.
I'll assume you are using mysql as most people using php choose mysql. From my understanding there are 2 ways to connect, mysqli and pdo. PDO seems to be emerging as the preferred method, but I know nothing about it. Here are references for both. Just DO NOT USE mysql_query(), it is deprecated so don't bother learning any part of it.
PDO: http://dev.mysql.com/doc/refman/5.6/en/apis-php-pdo-mysql.html
MYSQLI: http://php.net/manual/en/mysqli.query.php

Either of these should give enough of a tutorial to show you how to query your database and then loop through the results to get to your data. It is then up to you how you want to display it on your page.
Hopefully this is enough to point you in the right direction.
Good Luck!

A: Your easiest approach is to just join the two tables together, sorting first by image and sub-sorting by comment.
SELECT i.*, c.comment_id, c.comm_poster_id
FROM images i LEFT JOIN comments c ON i.image_id=c.image_id
WHERE {whatever where clause selects your set of 30 images}
ORDER BY i.image_id, c.comm_poster_id

Use a LEFT JOIN or images without comments won't display.


text:
Q: Python loop restarting even though there is a try: except: Here is the code for a small program I just wrote to test some new things I learned.
while 1:
    try:
        a = input("How old are you? ")
    except:
        print "Your answer must be a number!"
        continue

    years_100 = 100 - a
    years_100 = str(years_100)
    a = str(a)
    print "You said you were "+a+", so that means you still have "+years_100+" years"
    print "to go until you are 100!"
    break
while 2:
    try:
        b = str(raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
    except:
        print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
        continue

    if b == "yes":
            print 'You entered "yes". Script will now restart... '
    elif b == "no":
            print 'You entered "no". Script will now stop.'
            break

It works fine for the for loop. If you type something other than a number, it will tell you only numbers are allowed.
However, in the 2nd loop, it asks you to enter yes or no, but if you enter in something different, it just restarts the loop instead of printing the message after
except:

What did I do wrong and how do I fix it so it displays the message I told it to?

A: You do not get an exception, because you are always enter a string when using raw_input(). Thus str() on the return value of raw_input() will never fail.
Instead, add an else statement to your yes or no tests:
if b == "yes":
        print 'You entered "yes". Script will now restart... '
elif b == "no":
        print 'You entered "no". Script will now stop.'
        break
else:
    print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
    continue

Note that you should never use a blanket except statement; catch specific exceptions. Otherwise, you'll mask unrelated problems, making it harder for you to find those problems.
Your first except handler should only catch NameError, EOFError and SyntaxError for example:
try:
    a = input("How old are you? ")
except (NameError, SyntaxError, EOFError):
    print "Your answer must be a number!"
    continue

as that's what input() would throw.
Also note that input() takes any python expression. If I enter "Hello program" (with the quotes), no exception would be raised, but it is not a number either. Use int(raw_input()) instead, and then catch ValueError (what would be thrown if you entered anything that's not an integer) and EOFError for raw_input:
try:
    a = int(raw_input("How old are you? "))
except (ValueError, EOFError):
    print "Your answer must be a number!"
    continue

To use the second loop to control the first, make it a function that returns True or False:
def yes_or_no():
    while True:
        try:
            cont = raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
        except EOFError:
            cont = ''  # not yes and not no, so it'll loop again.
        cont = cont.strip().lower()  # remove whitespace and make it lowercase
        if cont == 'yes':
            print 'You entered "yes". Script will now restart... '
            return True
        if cont == 'no':
            print 'You entered "no". Script will now stop.'
            return False
        print 'Please try again. Enter "yes" to do it again, or "no" to stop.'

and in the other loop:
while True:
    # ask for a number, etc.

    if not yes_or_no():
        break  # False was returned from yes_or_no
    # True was returned, we continue the loop


text:
Q: HATEOAS and Search API (FIQL / RQL) I already post this question on Spring Forum, but somebody told me to move the question here, i think it's a good option.
I would like to know how can i implement FIQL or RQL for make a Search API in FullREST / HateOAS.
I Googled for this and didn't see anything, just the implementation of CXF.
I know that we can maybe make something with Matrix Variable ? But i'm looking for something more "friendly", like the CXF Implementation, or in the "Spring Way"
Thanks for your help


text:
Q: How to synchronize applications between two terminal-service servers? We have two terminal-service server and we use Network Load Balancing (NLB) to cluster this two terminal-service servers together.
We need to have the same applications installed on the two servers, because if one user who uses the terminal is redirected to any other of  the two servers need to have the same applications.
Is possible to synchronize installing of applications between the two terminal-service servers   so that we could have the same applications on the two-severs?
This the diagram representing the topology of the configuration:

All the servers are running Windows Server 2012.

A: Yes, you can do this by using any of the software distribution products out there (e.g. SCCM).
It is not possible "out of the box". But this seems to be a pretty small environment, so can't you just make sure you install them on both servers?

A: As stated SCCM would be the way to go, however since you probably aren't going to just run out and buy it and configure it (it is also way more in depth than just doing that) what I'd recommend is this:
The Favorable (read "better" maybe even "best" given your circumstances) Way
First you could (depending on the version of Remote Desktop server you're running, which even if it is 2008 R2 then you're ok) setup one of the servers as a RemoteApp server.  You could publish all the apps you want both servers to have as RemoteApps and then distribute them as links/shortcuts through a simple GPO.  That way, any time you make a change to an application it changes for both of them simultaneously during the next time the GPO pushes the new shortcut to each server.  Here are two great resources on the details/steps (one for 2008 and the other for 2012) required to do this; it's quite simple.
2008 RemoteApp Setup
2012 RemoteApp Setup
P.s. You can turn almost anything into a RemoteApp all the way down to minuscule things like the built in Calculator for Windows.
If you can't figure this out or don't want to hassle with it, you can always do...
The Not So Favorable Way
Get all the features and applications the way you want them on one server and then use either VMware's Standalone Converter, or Disk2VHD for Microsoft to clone this server.  Make sure that you don't connect the new server to the network at first, and that you sysprep the new server after you start it up.  Then you can get it a new name, SID (sysprep takes care of the old one and when you join to the domain you'll get a new one) and IP.  This is the poor mans way, because if you install software on one terminal server down the road it won't auto install on the new server and there is probably some configuration changes that will need to be made on each server which gets tidious and time consuming.
If I can be of any further assistance don't hesitate to ask, thanks.


text:
Q: Error in code Regex I am trying to find only the word contains 3 letters(e is below example) in the word
need to find using regex.
val inputString = """edepak,suman,employdee,eeeee,eme,ev"""

and i have written the below code.
val numberPatteren = "([a-z]*e){3,}".r

but i am getting the below output which is not as expected.
employdee,eeeee

but the output should be only -- employdee
can you please help me on this.

A: You can achieve that simply by doing the following
scala> inputString.split(",").filter(word => word.count(_ == 'e') == 3).mkString(",")
//res16: String = employdee

If you want to use regex, you can do as below
scala> val numberPatteren = "[a-df-zA-DF-Z0-9]".r
//numberPatteren: scala.util.matching.Regex = [a-df-zA-DF-Z0-9]

scala> inputString.split(",").filter(numberPatteren.replaceAllIn(_, "").length == 3).mkString(",")
//res0: String = employdee


text:
Q: JavaScript calculate hashcode from real number and integer number Hi there I need function to calculate unique integer number from number (real number double precision) and integer.
Try explain I am developing GIS application in javascript and I am working with complex vector object like polygon (array of points object with two coordinate in ring) and lines array of points. I need fast algorithm to recognize that element has been changed it must be really fast because my vector object is collection of thousand points . In C# I am calculating hash code from coordinate using bitwise operation XOR.
But javascript convert all operands in bitwise operation to integer but i need convert double precision to integer before apply bitwise in c# way (binnary). In reflector i see this that c# calculate hash code fro double like this and I need this function in javascript as fast as can be.
public override unsafe int GetHashCode() //from System.Double
{
    double num = this;
    if (num == 0.0)
    {
        return 0;
    }
    long num2 = *((long*) &num);
    return (((int) num2) ^ ((int) (num2 >> 32)));
}

Example:
var rotation = function (n) {
    n = (n >> 1) | ((n & 0x001) << 31);
    return n;
}

var x: number = 1;
var y: number = 5;

var hash = x ^ rotation(y); // result is -2147483645

var x1: number = 1.1;
var y1: number = 5;

var hash1 = x1 ^ rotation(y1); // result is -2147483645

Example result is not correct hash == hash1
Example 2: Using to string there is correct result but calculate Hash from string is to complicate and I thing is not fast enough.
    var rotation = function (n) {
        n = (n >> 1) | ((n & 0x001) << 31);
        return n;
    }

     var GetHashCodeString = function(str: string): number {
        var hash = 0, i, l, ch;
        if (str.length == 0) return hash;
        for (i = 0, l = str.length; i < l; i++) {
            ch = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + ch;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
     }

    var x: number = 1;
    var y: number = 5;

    var hash = GetHashCodeString(x.toString()) ^ rotation(GetHashCodeString(y.toString()));
    //result is -2147483605
    var x1: number = 1.1;
    var y1: number = 5;

    var hash1 = GetHashCodeString(x1.toString()) ^ rotation(GetHashCodeString(y1.toString()));
   //result is -2147435090

Example2 result is correct hash != hash1
Is there some faster way than converting number to string than calculate hash from each character? Because my object is very large and it will take lot of time and operation in this way ...
I try do it using TypedArrays but yet I am not successful.
Thanks very much for your help

A: Hi there I tried use TypedArrays to calculate Hash code from number and the result is interesting. In IE the performance 4x better in Chrome 2x in FireFox this approach is equal to string version ...
var GetHashCodeNumber = function (n: number): number {
         //create 8 byte array buffer number in js is 64bit
         var arr = new ArrayBuffer(8);

         //create view to array buffer
         var dv = new DataView(arr);

         //set number to buffer as 64 bit float
         dv.setFloat64(0, n);

         //now get first 32 bit from array and convert it to integer
         // from offset 0
         var c = dv.getInt32(0);

         //now get next 32 bit from array and convert it to integer
         //from offset 4
         var d = dv.getInt32(4);

         //XOR first end second integer numbers
         return c ^ d;
     }

I think this can be useful for someone
EDIT: using one buffer and DataView is faster !

A: I looked up some hashing libraries to see how they did it: xxhashjs, jshashes, etc.
Most seem to take a string or an ArrayBuffer, and also depend on UINT32-like functionality. This is equivalent to you needing a binary representation of the double (from your C# example). Notably I did not find any solution that included more-strange types, other than in another (unanswered) question.
His solution uses a method proposed here, which converts it to various typed arrays. This is most likely what you want, and the fastest accurate solution (I think).
I highly recommend that you structure your code to traverse objects/arrays as desired, and also benchmark the solution to see how comparable it is to your existing methods (the non-working one and the string one).

A: Here is a faster way to do this in JavaScript.
const kBuf = new ArrayBuffer(8);
const kBufAsF64 = new Float64Array(kBuf);
const kBufAsI32 = new Int32Array(kBuf);

function hashNumber(n) {
  // Remove this `if` if you want 0 and -0 to hash to different values.
  if (~~n === n) {
    return ~~n;
  }
  kBufAsF64[0] = n;
  return kBufAsI32[0] ^ kBufAsI32[1];
}

It's 250x faster than the DataView approach: see benchmark.


text:
Q: Cpanel - subdomain outside public_html I had two domains on one hosting account, managed by cpanel. During the second domain installation I opted to use root folder outside public_html because the second site was going to have independent ftp administration not related to the one of the first domain at all. So I didn't want the files of the second site to be accessible in public_html.
That worked pretty well until the second domain expired and wasn't going to be renewed. However, despite website isn't public already, I want to have web access on it for testing and other purposes but it seems like cpanel doesn't allow subdomain directories outside public_html.
Is there a way, to achieve that without having to migrate all subdomain files to public_html and thus - making them accessible for the administrators on the main domain (which is undesired)?

A: One way you can do this is by having two cPanel hosting accounts:
- domain.com
- subdomain.domain.com

In case the hosting accounts are in different servers, you should make an A record subdomain.domain.com pointing to the server that specific hosting account is created.
By doing that, you will have two separated environments, usernames, passwords and databases will be different from each other. The hosting account domain.com won't be able to see the files and manage anything on subdomain.domain.com. The same applies vice-versa.

A: create folder out side www as for example hello. and in cpanel/subdomains point that such as ../hello in Document Root


text:
Q: Retrofit send Json object and get List as response I send to my service json object like this
{
  "procedure_name": "testowa",
  "parameters": [
    {
      "Id": "1"
    }

  ]
}

As a response I get resultset of my sql procedure on the same url:
[
 {"id": 1, "email": "test", "password": "test"}

]

To do that i write this code.
This is my api interface:
public interface ApiInterface {
    @POST("/")
    Call<Object> getData(@Body Procedure procedure);
}

And this is my procedure class:
public class Procedure
{
    final String procedure_name;
    final List<HashMap<String, String>> parameters;

    public Procedure(String procedure_name, List<HashMap<String, String>> parameters)
    {
        this.procedure_name = procedure_name;
        this.parameters = parameters;
    }
}

And at the end MainActivity part where I save the response
ApiInterface service = retrofit.create(ApiInterface.class);

    HashMap<String, String> parameter = new HashMap<>();
    parameter.put("id", "1");

    List<HashMap<String, String>> list_parameters = new ArrayList<>();
    list_parameters.add(parameter);

    Procedure procedure = new Procedure("testowa", list_parameters);
    Call<Object> call = service.getData(procedure);

    call.enqueue(new Callback<Object>() {
        @Override
        public void onResponse(Call<Object> call, Response<Object> response) {
            String apiResponse = new Gson().toJson(response.body());
            textViewResult.append(apiResponse);
        }

        @Override
        public void onFailure(Call<Object> call, Throwable t) {
            textViewResult.setText(t.getMessage());
        }
    });

I save a response like a string, but  I want to save this like List of objects. I should create one more class maybe User and save response as a list of objects this class. But I don't know how to change my api interface and other methods  to do that.

A: Its Straight forward 'http://jsonschema2pojo.org/' can help you generate POJO from Api Responses. Once you get your generated POJO, replace the 'Object' type in the Api interface method with the POJO class. You will also need to change the CallBack response type to the generated POJO class

A: First step is to create a POJO based on your API response, something like this:
import com.google.gson.annotations.*;

public class User {

@Expose
private Integer id;
@Expose
private String email;
@Expose
private String password;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

Then, if you didnt' already done, you should pass a Gson builder to your Retrofit instance creation, something like this:
GsonBuilder gsonBuilder = new GsonBuilder()
Gson gson = gsonBuilder.create();
private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl("apiEndpoint/url")
                .addConverterFactory(GsonConverterFactory.create(gson));

Then you have to adapt your retrofit API accordingly to receive a list of Users just like a JSOn array:
public interface ApiInterface {
@POST("/")
Call<List<User>> getData(@Body Procedure procedure);
}

Finally, retrofit will provide you the response in a POJO form:
 call.enqueue(new Callback<List<User>>() {
    @Override
    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
        List<User> apiResponse =response.body();
    }

    @Override
    public void onFailure(Call<List<User>> call, Throwable t) {
        textViewResult.setText(t.getMessage());
    }
});

A: I send to my service json object like this
{
  "procedure_name": "testowa",
  "parameters": [
    {
      "Id": "1"
    }
]
}
// For this Request, You need to use this class -
 public class myRequest{
String procedure_name;
ArrayList<myObject> parameters;

        public String getProcedure_name() {
            return procedure_name;
        }

        public void setProcedure_name(String procedure_name) {
            this.procedure_name = procedure_name;
        }

        public ArrayList<myObject> getParameters() {
            return parameters;
        }

        public void setParameters(ArrayList<myObject> parameters) {
            this.parameters = parameters;
        }

        public myRequest() {
        }

        public myRequest(String procedure_name, ArrayList<myObject> parameters) {
            this.procedure_name = procedure_name;
            this.parameters = parameters;
        }

        public class myObject{

            String Id;

            public String getId() {
                return Id;
            }

            public void setId(String id) {
                Id = id;
            }

            public myObject() {
            }

            public myObject(String id) {
                Id = id;
            }
        }
    }

And Change this to :
public interface ApiInterface {
    @POST("/")
    Call<Object> getData(@Body myRequest myRequest);
}

And in your activity or Fragment do this to call :
ArrayList<String> list = new ArrayList<>;
list.add("1");
 myRequest myRequest = new myRequest ("testowa", list);

 Call<Object> call = service.getData(myRequest );

it will work .


text:
Q: How do I connect these clips? I bought a couple of clips like this . Does anyone know how to connect them?

A: To attach them to a wire before initial use pull out the plug on the top, feed a wire through the hole in the plug, solder the wire to the metal part on the other piece, then push the plug back into place.
To attach them to a device simply push on the plug until the metal hook extends from the end, hook it onto the device, then release the plug.


text:
Q: How should I format my 3D engine's geometry-instantiation process? I am currently working on a 3D engine in java and have run across a few problems. Such as, a reliable way to create 3D (or 2D or 1D) geometry in a reliable, simplistic way. Of course, there is no real, straight-forward answer for this, but I'm mainly anticipating this to be a discussion-type-post.. But, nonetheless, I'm looking for a simple, yet reliable way to instantiate geometry in my 3D engine.
(As an example of what exactly it is that I mean, I currently have everything being composed of 3D points (as it is in reality), but telling the engine what the points compose is a difficult task, making it hard to get reliable geometry. I need a more reliable system rather than just using many many points.)

A: Yay discussion-type question -- first off, just a warning, discussion-type questions tend to be frowned upon at stackoverflow, but I'll pitch in nonetheless:
The first thing that popped into my mind was the Half-edge Mesh Datastructure -- a simple, and powerful-enough-for-everything-I've-needed-so-far structure -- with almost no space-wise superfluous data. This would cover basically all of your mesh structure needs.
Another solution which you'll find in many 3D game engines is the object-tree system (I'm not sure whether that is the correct name), which you;ll find in action in the python panda3D game engine, Blender (kinda, not that familiar with blender), and so on and so forth. The idea is to have a simple Object3D class, which can contain other Object3D objects at relative positions within. This nested hierarchy works very well with complex systems, where parts come together to form more complex parts of other things. This nested hierarchy also lends itself very well to recursive O(log n) collision algorithms, and recursive frustum culling (for graphics). This is also very easy to code -- I wrote a basic 3D engine using object trees in 11th grade, and let's just say I wasn't exactly a MENSA member back in the day.
In any engine, we'd need some way to compute intersections and so on, so we can do frustum culling, physics collisions, and so on and so forth. The trick I used (very efficient, and just intelligent enough), was the AABB tree -- if we already have trees of objects, we simply let every object store & compute its AABB, and hey presto! AABB tree.
Anyways, you say, since I've some experience writing some code like this I must be able to provide samples, right? Yes:
public class Object3D {
    public LinkedList<Object3D> children;
    public AABB aabb; // the AABB of the object -- constructed
                      // by union of children's AABBs
    public void doesIntersect(Object3D obj){
        // intersection using AABB-AABB intersection
        // sadly web resources are sorely lacking, so I shall handle this one below
    }
}

On AAABB-AABB collisions (if you need to know)
We have two boxes. Each box is aligned with the axes, and each box has a width, height, and depth. To test if they collide, we see whether they overlap when looking along all three axes -- after all, if they don't overlap when we look along even one axis, they can't possibly be colliding. Some fancy math later, we note that:
"Box A and Box B collide" iff "Box A and B have overlapping x coordinates" and
"same for y coordinates" and "same for z coordinates" and
"same for any other dimensions of space you decide to implement".

As it turns out, this is a trivial check, both to code and to compute, which is why AABBs make good bounding volumes for object trees.
Well, for a discussion this answer has gotten rather one-sided. Anyways, comments would be lovely, I'm sure there are some useful things I've missed (verlet integration, raytracing, but all of those are easy on a base as described above)


text:
Q: What does this javascript code means? I'm working on a form that does changes on the fly and I'm trying to understand it better.
nonetheless, I came upon and input that has this and I was wondering what does this statement means any example would be appreciated. Thank you
onclick="if(this.onchange){this.onchange();}"

A: This is checking to see if this has a function defined as  onchange. In javascript, you don't need if (this.onchange != null). If the value is null, undefined, or has an empty string, the value in the if statement returned is false. This is usually a good practice to avoid null reference errors in javascript when you aren't positive that every browser is going to support whatever you're attempting to use. (or other reasons I'm missing now)
For example, when adding a line to output to the console in Google Chrome...
console.log("output here");
This may cause errors in other browsers if I remember correctly. A good way to handle this would be to use:
if (console) { console.log("output here"); }

A: In simple terms,
"If this element has function associated to it's onchange event listener, execute it.".

A: It's a way to check if it is declared
if (typeof this.onchange != "undefined"){
    this.onchange();
}


text:
Q: Java8 with Selenium WebDriver I am new to Java-8 and appium and trying to write my webdriver code in Java-8 as mentioned below
Currently below code is working fine but I don't want to write Function and Consumer in separate lines as mentioned below in lines line 5 and line 6 and i want to optimize the code more i.e something like Function within Consumer or Consumer within Function.Thanks! in Advance
public class Gestures_Drag_And_Drop {

     AndroidDriver<AndroidElement> driver;

     Function<String, AndroidElement> F = driver::findElementByXPath;//line 5
     Consumer<AndroidElement> C = AndroidElement::click;  //line 6

     Gestures_Drag_And_Drop() {
         C.accept(F.apply("//android.widget.TextView[@text='Views']"));
     }

     public static void main(String[] args) throws MalformedURLException {
         new Gestures_Drag_And_Drop();
     }
}

A: Your function or consumer variable not need to be just method reference, you can define whatever method body you want using lambda expressions. I guess you asking for something like this:
BiConsumer<String, WebDriver> findAndClick = (locator, webdriver) -> webdriver.findElement(By.xpath(locator)).click();


text:
Q: How can I manipulate contents of an extjs panel as I can a DOM element? In the following extJS page, when I click the button, the content of the HTML Div "buttonInfo" changes correctly.
I want to also change the contents of the panel that I created with extJS.
However, when I change the contents of the panel as I do the div, the whole panel is simply replaced.
How can I change the contents of my panel object from within my button's click handler?
before:

after:

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">

        <title>Simple extJS</title>

        <button id="buttonInfo">
            Show Info
        </button>

A: Ext.get gives you the dom object, use Ext.getCmp instead so that it returns the Ext object back, then you can use the update method on the panel:
Try:
Ext.getCmp('panel1').update('new info');
Hope it helps.

A: Try:
var Data = 'new info';
panel1.overwrite(panel1.body, Data);
panel1.doComponentLayout();


text:
Q: How does Time Machine encrypt backups to network disk? I see other questions regarding encrypting Time Machine backups to external disks, like this one:
If I encrypt a Time Machine backup disk, is the entire disk encrypted or just the Backups.backupdb directory?
There it says the entire disk is encrypted.
But for a network disk, I find it hard to believe that Time Machine can encrypt the disk. For example, is remote encryption of an entire disk possible via SMB?
Of course, Time Machine still supports encryption to a network drive, so then what exactly is it doing?

A: Neither the remote disk nor the remote volume is encrypted by Time Machine. Instead a special "sparse bundle (disk image)" ("backupbundle" for Catalina) is created on the network drive. In fact it's no uniform disk image file like a dmg but a special folder containing sub-folders and config/log files.
The content of the source volume(s) is saved as AES-128-encrypted band (or chunk) files in the bands folder.
The password is merged into a special file named token in the backupbundle.

The remote disk or volume could be encrypted independently though. This depends on the (TM-)server config.