text:
Q: How to get a "Type Mapping" function typed correctly I have a type which is for a function which maps from one type I to another type O (aka, input and output types). It looks like this currently:
export interface IFunctionalMapping<I, O, K extends keyof O> {
  [prop: Extract<O[K], string>]: (input: keyof I, obj?: I) => K;
}

With the idea that one would use it like so:
export interface IFunctionalMapping<I, O, K extends keyof O> {
  [prop: Extract<K, string>]: (input: I) => O[K];
}

export interface IInput {
  firstName: string;
  lastName: string;
}

export interface IOutput {
  fullName: string;
}

const mapping: IFunctionalMapping<IInput, IOutput> = {
  fullName: (i) => `${i.firstName} ${i.lastName}`
}

The goal would be that the properties for mapping would be constrained to valid properties of IOutput and that the type exported by the function would be of the type of IOutput's property type.
It seems I'm not doing things 100% right as first off all I get an error on the IFunctionalMapping interface:

Which I would have thought would be avoided by my use of the Extract syntax.
Second, my attempt to type mapping to IFunctionalMapping complains that it needs 3 types ... I would have though that K extends keyof O would not need to be passed in as it's implied by the definition of O. But clearly I must be wrong about that too.

A: If you need to use a mapped type to map the types of IOutput :
export type IFunctionalMapping<I, O> = {
    [K in keyof O]/*?*/: (input: I) => O[K]; // If you don't want all properties to be required, uncomment the ?
}

export interface IInput {
    firstName: string;
    lastName: string;
}

export interface IOutput {
    fullName: string;
}

const mapping: IFunctionalMapping<IInput, IOutput> = {
    fullName: (i) => `${i.firstName} ${i.lastName}`
}


text:
Q: Android 12 save image from gallery Why i dont need permissions for saving a image from gallery? I dont acccept "READ_EXTERNAL_STORAGE", but nevertheless i can store the image to my private app folder. I want to use permissions for comparing the "old" api with the new photopicker api.
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},Read_Permissions);
        }

single.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SINGLE_PICTURE);
            }
        });

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            Snackbar failsnackbar = Snackbar.make(findViewById(android.R.id.content), "failure", Snackbar.LENGTH_LONG);
            failsnackbar.show();
            return;
        }
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        imagesEncodedList = new ArrayList<String>();
        switch (requestCode) {

            case SINGLE_PICTURE:
                if (data.getData() != null) {

                    Uri mImageUri = data.getData();

                    Bitmap bitmap = null;
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    saveToInternalStorage(bitmap);
///other stuff

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mypath=new File(directory,timeStamp+".jpg");

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
 image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return directory.getAbsolutePath();

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use bootstrap in my back-end module? I'm trying to build my first backend module and I was wondering if it is possible to use the bootstrap in the Magento Backend, or if it is only with html tags? I tried to use the bootstrap added in the default_head_blocks.xml of my module but it didn't work.

A: At the time of writing there was no information to go on from the question, so I am answering based on some assumptions - until the question is broadly improved where someone else may assist further.
The Magento 2 default_head_blocks.xml generally only goes into your theme folder, not in the code folder of a module.   This is also only for the frontend area.
In other words for frontend, do not put it in app/code/Vendor/Theme/ folder, but it needs to be registered as a Theme.
app/design/frontend/Vendor/Theme/Magento_Theme/layout/default_head_blocks.xml
However since you are targeting an adminhtml, the file default_head_blocks.xml are not used as far as I can see.
You could potentially override any of these layout areas, and target <head> section as you wanted to with default_head_blocks.xml.
Magento_Backend layouts
You should also take a look at reference on how to add javascript resource using require-js
A possible way to do it:
app/code/VendorName/ModuleName/view/adminhtml/layout/adminhtml_system_config_edit.xml:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="header">
            <block class="VendorName\ModuleName\Block\YourBlock" template="VendorName_ModuleName::import-js.phtml"/>
        </referenceContainer>
    </body>
</page>
app/code/VendorName/ModuleName/view/adminhtml/templates/import-js.phtml:

<script type="text/javascript">
    require(
        ['bootstrap'],
        function($) {
            $(function() {
                // My js code
            });
        });
</script>

See the references above on which folder locations will help you.


text:
Q: Filestream/Streamwriter not assigning values correctly I have no experience with Filestream of StreamWriter so I am not sure if there is something obvious that I am missing or not understanding.
I have a method that is using attributes from its current class, and writing them to lines within a file, but it just seems to write blank values to the file.
public void FileWrite()
{
    FileStream fs = new FileStream("test.txt", FileMode.Append, FileAccess.Write);

    StreamWriter sw = new StreamWriter(fs);

    sw.WriteLine("Title = " + title);
    sw.WriteLine("Name = " + fName);
    sw.WriteLine("Last name = " + lName);
    sw.WriteLine("Gender = " + gender);
    sw.WriteLine("Medicare no = " + medicareNo);
    sw.WriteLine("Height = " + height);
    sw.WriteLine("Weight = " + weight);
    sw.WriteLine("Age = " + age);
    sw.WriteLine("Daily Recommended calories = " + cal);
    sw.WriteLine("Ideal Weight = " + idealWeight);

    sw.Flush();
    sw.Close();
    fs.Close();

    Readfile();
}

Any help would be much appreciated as I have not worked with Filestream or StreamWriter in the past.
EDIT:
public class PatientDetails
{
    public void ValuePass()
    {
        FileHandler file = new FileHandler();

        file.setTitle(this.title);
        file.setName(this.fName, this.lName);
        file.setMedicare(this.medicareNo);
        file.setGender(this.gender);
        file.setMeasurements(this.weight, this.height, this.age);
        file.setCalcs(this.cal, this.idealWeight);

        Console.WriteLine(this.fName + this.lName);
    }
}

This is how the values are passed from within a different class.
And the values are obtained from user input:
do
{
    Console.WriteLine("\nPlease enter the Title");
    this.title = Console.ReadLine();

A: you can do as below
FileHandler fh = new FileHandler();
fh.setTitle("New Title"); // set all the values.....
fh.FileWrite();

A: Your code in FileWrite() function is fine and correct. You should first check whether the attributes of PatientDetail class have values or not. If they do, then file.setTitle() must be implemented as follow:
file.setTitle(string text)
{
title = text; //title is the attribute of `FileHanlder` class
}

Also please call file.FileWrite() in the  ValuePass() function.


text:
Q: How can I make a grid class that conserves memory? Most of the time, the way you would make a grid of objects in C++ is like this:
class Grid {
private:
    GridObject[5][5];
};

But is there a way to save memory and not use tiles that have nothing in them? Say you had a chess board. What if you didn't want to use memory in unoccupied spaces? I was thinking of ways to do this but they are inefficient.

A: I would have a structure like:
class GridObjectWithIndex
{
public:
    size_t index;
    GridObject obj;
};

Where index is a value of the form x + y * GRIDSIZE so that you easily can decode the x and y of it.
And in your Grid class have:
class Grid
{
    std::vector<GridObjectWithIndex> grid_elements;
};

A: The first thing which comes to my mind is storing pointers GridObject* in the grid. It will still consume sizeof(GridObject*) bytes for non-existent elements but it saves you from the nightmare of managing the data structure. If it's not absolutely critical - don't make it more complex than needed. It's definitely not worth for chess (8x8).
fritzone's solution will be good if you have a small number of elements over a wide range of indices. However think about read/write performance.
If you want to save the space while sending over the network or saving in a file you may want to consider archiving algorithms. Althogh it only makes sense for large sets on data.

A: What you are calling for is called a sparse data-structure, the most striking examples being sparse matrices.
The idea is to trade memory for CPU: use less memory at the cost of more operations. In general it means:

*

*having a structure only representing the "unusual" values (with a fast access by coordinates)

*keeping the "usual" value aside

As a proof of concept, you can use a std::map< std::pair<size_t, size_t>, Object > for the sparse structure and just have another Object on the side for whenever it's not present in the map.


text:
Q: product_tag to style an image I want to style my product images depending on product tags (not only the first tag, but all of them).
I am using this:
<img class="<?php echo get_the_term_list( $post->id, 'product_tag'); ?>"

and it is not working, because Woocommerce/Wordpress is styling the product tags as a link.
Help appreciated!

A: try looking to see if there is css that is causing this issue. Then your code might work. This may just be a specificity issue in your css.


text:
Q: Subgroup generated by two permutations Given the permutation:
$$\sigma:=
\left(
\begin{matrix}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14\\
10 & 13 & 6 & 1 & 14 & 2 & 11 & 12 & 4 & 7 & 9 & 5 & 3 & 8
\end{matrix}
\right)\in S_{14}
$$
1) Determine the period of $\alpha:=\sigma^{27797848}$
2) Determine and motivate if $\beta:=(273)$ is or not in the subgroup of $S_{14}$ generated by $\alpha$ and the 3-cycle $(123)$
I can do 1:
$\sigma=(1\;10\;7\;11\;9\;4)(2\;13\;3\;6)(5\;14\;8\;12)$
period of $\sigma$ is $lcm(6,4)=12$
so $27797848=4\;(mod\;12)$
so $\alpha=\sigma^4=(1\;9\;7)(10\;4\;11)$
and period of $\alpha$ is $lcm(3,3)=3$
Now for 2:
My first question is: if the order of a subgroup generated by one permutation is equal to the period of the permutation, what about a subgroup generated by two permutations? Is it the $lcm$ of the periods?
Second: the two permutations haven't disjoint orbits so the product is not commutative. I guess I'll quite some elements in the subgroup so I can't calculate it to check if $(2\;7\;3)$ is in it.
Third: Can I deduce if $(2\;7\;3)$ is in it?
I'll appreciate any hint or suggestion or answer. Thank you.

A: Let $\gamma = (1 2 3)$. Then $\gamma^2 = (2 1 3)$. We have $\alpha^{-1}(1) = 7, \alpha^{-1}(2) = 2, \alpha^{-1}(3) = 3$, so $\alpha^{-1}\gamma^2\alpha = (2 7 3) = \beta$.


text:
Q: Best Algorithm to avoid nested loops without Brute Force approach I want to make this method run as fast as possible.
int[] p = new int[] {1,4,4,5,1,3,6};
int[] q = new int[] {2,1,3,1,6,4,3};
int k =4.
void nestLoop(){
 for(int i = 0; i < q.length; i++){
     for(int j = 0; j < p.length; j++){
       //code continues
       // inside here...
       //This approach
        // takes a longer
         //time to finish
         // executing. I need a better algorithm

      }

  }
}

To be clearer; at q[0], p = 1,  since 1 is less than q[0], choose 1, and p[4] is also lower, choose 1; hence the answer when it is q[0] are 1 and 1 : but because 1 and 1 are two ints, they are not equal to k = 4, then return 0. If the answer had been 1, 1,1,1 then the number is 4 which is equal to k. [1,1,1,1] will be returned. The same for other q and so on

A: If I understand correctly you are returning either k or 0, correct?
Then this is the way to do it:
int[] p = new int[] {1,4,4,5,1,3,6};
int[] q = new int[] {2,1,3,1,6,4,3};
int k =4.

void notNested()
{
    TreeSet<Integer> ts = new TreeSet<Integer>();
    // Find the kth smallest number in the array.
    PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
    for (int p1 : p)
    {
        if (pq.size() < k)
        {
            pq.add(p1);
        } else if (pq.peek() > p1)
        {
            pq.poll();
            pq.add(p1);
        }
    }

    int ksm = pq.poll();
    // For each q, compare against kth smallest only.
    for (int q1 : q)
    {
        if (q1 >= ksm)
        {
            results.add(k);
        }
        else
        {
            results.add(0);
        }
    }
}

A: If the number of different elements in p is relatively small compared to the total number of elements, the following might work. If, however, there are many different elements, or even all elements are different, then it will be much slower.

*

*create a Map mapping elements to their indices, e.g. [1,4,4,5,1,3,6] would become {1: [0,4], 4: [1,2], 5: [3], 3: [5], 6: [6]}

*from that map, get the lists of indices for all elements smaller than the current element from q

*put those into a Heap, or Priority Queue, sorted by the next unused index for that element

*pop lists from the heap, get the first index, and put them back onto the heap for the next index until you get k indices

If there are many repeated elements (and only then), this may somewhat reduce the complexity. For P elements in p, d of which being distinct, Q elements in q, and k, this should have complexity of O(P + Q*(d+k*log(d))) (P for creating the map, and d for selecting the lists and k heap operation with log(d) for all the Q queries).

A: This is a solution using Java Streams:
package javaapplication3;
import java.util.Arrays;
import java.util.stream.*;

public class JavaApplication3 {
    public static void main(String[] args) {

        int[] p = new int[] {1,4,4,5,1,3,6};
        int[] q = new int[] {2,1,3,1,6,4,3};
        int[][] results = new int[q.length][]; // Array of arrays to store results
        int k =4;

        // For each element q[i], execute in parallel
        IntStream.range(0, q.length).parallel().forEach(i -> {
            final int qi = q[i];
            // Get first k elements of p <= q[i]
            results[i] = Arrays.stream(p).filter(v -> v <= qi).limit(k).toArray();
        });

        for(int i=0; i<q.length; i++) {
            int[] result = results[i];
            System.out.print("Values less or equal than " + q[i] + ": {");
            for (int v : result)
                System.out.print(" " + v);
            System.out.println(" }");
        }

    }
}

Output:
Values less or equal than 2: { 1 1 }
Values less or equal than 1: { 1 1 }
Values less or equal than 3: { 1 1 3 }
Values less or equal than 1: { 1 1 }
Values less or equal than 6: { 1 4 4 5 }
Values less or equal than 4: { 1 4 4 1 }
Values less or equal than 3: { 1 1 3 }

Note: You can optionally sort p which will improve performance if p is large and k is small.


text:
Q: Automatically get the error message instead of the outcome I am making a page where you can calculate all kinds of stuff but can't get the one for circles to work the way its supposed to right now it keeps saying that the input is incorrect while nothing has been selected yet and it doesn't calculate anything at all it just refreshes the page and it should be instead returning the outcome of the conversion.
The code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link href="styling.css">
    <title>Title</title>

Calculator and Converter

    Home
    TBD
    TBD
    TBD

<content>
    <form method="POST">
        This converter is for circles
        <input type="number" name="input" placeholder="">
        <select name="circles" class="meters">
            <option value="radius">Radius</option>
            <option value="diameter">Diameter</option>
            <option value="circumference">circumference</option>
        </select>

        <select name="convercircle" class="meters">
            <option value="radius">Radius</option>
            <option value="diameter">Diameter</option>
            <option value="circumference">circumference</option>
        </select>
        <input type="submit" name="submit" class="submit" value="submit">
    </form>
</content>

<?php
$input=$_POST[''];
$circles=$_POST[''];
$convercircle=$_POST[''];
$submit=$_POST['submit'];

if (isset($_POST['submit'])) {
    if ($circles==['diameter'] && $convercircle==['radius']) {
        $output=$input*2;
        echo "The radius is $output";
    }
    elseif ($circles==['circumference'] && $convercircle==['radius']) {
        $output=$input/2;
        echo "The radius is $output";
    }
    elseif ($circles==['radius'] && $convercircle==['diameter']) {
        $output=$input*2;
        echo "The diameter is $output";
    }
    elseif ($circles==['radius'] && $convercircle==['circumference']) {
        $output=$input*2*3.14;
        echo "The circumference is $output";
    }
    elseif ($circles==['diameter'] && $convercircle==['circumference']) {
        $output=$input*3.14*2;
        echo "The circumference is $output";
    }
    elseif ($circles==['circumference'] && $convercircle==['diameter']) {
        $output=$input*3.14*2;
        echo "The diameter is $output";
    }
    else {
        echo "Please select a circle and a conversion";
    }

}

?>

A: *

*You're missing the array keys when you set the variables from $_POST.

*When you're comparing the variables, you have [] around the strings. That puts the string in an array, but the values of the variables are just strings. Don't do that.

<?php

if (isset($_POST['submit'])) {
    $input=$_POST['input'];
    $circles=$_POST['circles'];
    $convercircle=$_POST['convercircle'];

    if ($circles=='diameter' && $convercircle=='radius') {
        $output=$input*2;
        echo "The radius is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='radius') {
        $output=$input/2;
        echo "The radius is $output";
    }
    elseif ($circles=='radius' && $convercircle=='diameter') {
        $output=$input*2;
        echo "The diameter is $output";
    }
    elseif ($circles=='radius' && $convercircle=='circumference') {
        $output=$input*2*3.14;
        echo "The circumference is $output";
    }
    elseif ($circles=='diameter' && $convercircle=='circumference') {
        $output=$input*3.14*2;
        echo "The circumference is $output";
    }
    elseif ($circles=='circumference' && $convercircle=='diameter') {
        $output=$input*3.14*2;
        echo "The diameter is $output";
    }
    else {
        echo "Please select a circle and a conversion";
    }
}


text:
Q: Error Messages not displaying in codeigniter I want to show error on my view but when i submit register-designer and after validation redirect to main view and there i want to display error this is not working how should i solve this.
My Controller:
public function designer_basic()
{
    if($this->form_validation->run('as_designer')==true){
        echo "good";
    }else{

        return redirect('Designers/as_designer');
    }
}

My View is:

<?php if(!empty(validation_errors())){?>

            <?php echo validation_errors();?>

    <?php }?>

A:
You should set rules to validate  post values in controller like this

$this->form_validation->set_rules('as_designer', 'Designer', 'required');

Check the documentation of Codeigniter

A: You should set rules to the controller like this :
$this->load->library('form_validation');
$this->form_validation->set_rules('as_designer', 'Designer', 'required');

if ($this->form_validation->run() == false) {
     ......
 } else {
     ......
 }

I hope it's working fine for you.


text:
Q: networkx: Draw text on edges for my thesis I need to draw some probabilistic control flow graphs. i.e. control flow graphs with probabilities depicted on the edges.
I found graph-tool which seems quite useful, since it can use deep-copies of existing graphs and my graphs are quite similar.
So my question is, if there is a possibility to draw edge properties (or some strings) on/next to the edges? If it's not possible or highly complicated, is there a tool which is better to use in this case?
Edit:
I need directed edges that can even create loops between 2 nodes and have different values. Is there a possibility for this too? So I can see both values? By now I can see the directed graph with a 2-directional edge, but there's only one value on it.
So e.g. in networkx (in reference to Hooked) it would look like:
G = nx.MultiDiGraph()
G.add_edge(0,1)
G.add_edge(1,0)
labels = {(0,1):'foo', (1,0):'bar'}

So that both 'foo' and 'bar' are visible and you can see which direction they are connected to.
But as networkx renders it, I get 1 bidirectional edge with 1 of the labels.

A: You can draw text next to the edges with graph-tool using "edge_text" option of the graph_draw() function:
from graph_tool.all import *

g = Graph()
g.add_vertex(4)
label = g.new_edge_property("string")
e = g.add_edge(0, 1)
label[e] = "A"
e = g.add_edge(2, 3)
label[e] = "foo"
e = g.add_edge(3, 1)
label[e] = "bar"
e = g.add_edge(0, 3)
label[e] = "gnat"

graph_draw(g, edge_text=label, edge_font_size=40, edge_text_distance=20, edge_marker_size=40, output="output.png")

A: import networkx as nx

# Sample graph
G = nx.Graph()
G.add_edge(0,1)
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(1,3)

labels = {(0,1):'foo', (2,3):'bar'}

pos=nx.spring_layout(G)

nx.draw(G, pos)
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels,font_size=30)

import pylab as plt
plt.show()

EDIT: If you need multidigraphs with edge labels, I don't think you can do this completely within networkx. However you can do most of it in python and do the rendering and layout with another program:
import networkx as nx

G = nx.MultiDiGraph()
G.add_edge(0,1, label='A')
G.add_edge(1,0, label='B')
G.add_edge(2,3, label='foo')
G.add_edge(3,1, label='bar')
nx.write_dot(G, 'my_graph.dot')

I use graphviz to turn this into an image. On my Unix machine I run this from the command-line
dot my_graph.dot -T png > output.png

Which gives the desired output you are looking for. Note that graphviz has many ways to customize the visual appearance. The above example simply produces:


text:
Q: Adding functionality to Makefile gives error :- "multiple definitoon here ..." I have been given an already working Makefile which is actually working fine.
Makefile Contents can be found here in this post ...
Questions about Makefile - what is "$+" & where are .c files/dependencies called here ?
I am asking this question separately from my previous post mentioned above as it involves a different issue and adding it to that question would unnecessarily increase its length.
Now I have added one more functionality which is being used quite frequently at many places so I thought creating a separate file would be a nice idea so I created linklayer.c and added linklayer.o to $LIBOBJS.
I added this ...
 LIBOBJS= linklayer.o csum.o compact.o protoname.o headers.o
 parseargs.o cryptomod.o crc32.o

and this
 linklayer.o:    linklayer.c
    $(CC) -o $@ -c -I. $(CFLAGS) $+

I have declared function in sendip_module.h which is already declared and accessed in each of the module present in the project.
But now this multiple definition error is coming ... Have I done something wrong or misunderstood something?
Note: "ipv6_opts" is defined in ipv6.h
$ make all
for subdir in mec ; do \
    cd $subdir ;\
    make  ;\
    cd ..  ;\
    done
make[1]: Entering directory `/home/udit/Desktop/sendip-2.5-mec-2/mec'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/home/udit/Desktop/sendip-2.5-mec-2/mec'
  gcc-4.4 -o ipv6.so -fPIC -fsigned-char -pipe -Wall -Wpointer-arith
 -Wwrite-strings -Wstrict-prototypes -Wnested-externs -Winline -Werror
 -g -Wcast-align -DSENDIP_LIBS=\"/usr/local/lib/sendip\" -shared ipv6.c
  libsendipaux.a libsendipaux.a

 libsendipaux.a(linklayer.o):(.data.rel.local+0x0)
                              : multiple definition of `ipv6_opts'
 /tmp/ccxa4tMX.o:(.data.rel.local+0x0): first defined here
 collect2: ld returned 1 exit status
 make: *** [ipv6.so] Error 1

and why this libsendipaux.a libsendipaux.a two times ? Is there something wrong with the Makefile itself.
Do I first need to manually compile it and then add it to libsendipaux.a ?
I am new to this Makefile stuff, so please help me understand how this is all working out here ?
Thanks.
Edit :
Remake debugging output -
 remake -x

Reading makefiles...
Updating goal targets....
/home/udit/Desktop/sendip-2.5-mec-2/Makefile:33 File `all' does not exist.
/home/udit/Desktop/sendip-2.5-mec-2/Makefile:48 File `subdirs' does not exist.
/home/udit/Desktop/sendip-2.5-mec-2/Makefile:48 Must remake target `subdirs'.
for subdir in mec ; do \
    cd $subdir ;\
    make  ;\
    cd ..  ;\
    done
make[1]: Entering directory `/home/udit/Desktop/sendip-2.5-mec-2/mec'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/home/udit/Desktop/sendip-2.5-mec-2/mec'
/home/udit/Desktop/sendip-2.5-mec-2/Makefile:48 Successfully remade target file
`subdirs'.
File `ipv6.so' does not exist.
Must remake target `ipv6.so'.
gcc-4.4 -o ipv6.so -fPIC -fsigned-char -pipe -Wall -Wpointer-arith
-Wwrite-strings -Wstrict-prototypes -Wnested-externs -Winline -Werror
-g -Wcast-align -DSENDIP_LIBS=\"/usr/local/lib/sendip\" -shared ipv6.c
 libsendipaux.a libsendipaux.a
 libsendipaux.a(linklayer.o):(.data.rel.local+0x0)
                                  : multiple definition of `ipv6_opts'
 /tmp/ccb0oaXR.o:(.data.rel.local+0x0): first defined here
 collect2: ld returned 1 exit status
 remake: *** [ipv6.so] Error 1

 #0  ipv6.so at ??
 #1  all at /home/udit/Desktop/sendip-2.5-mec-2/Makefile:33

33rd line -> all:    $(LIBS) subdirs sendip $(PROTOS) sendip.1 sendip.spec
I guess it could not help me out .... actual problem is with my understanding of scenario itself. Please help me bring out of the mess.

A: the problem you are facing, is that you are linking together several objects where at least two of them define de function ipv6_opts.
since there are two implementations of the function, your linker cannot decide which one to use and throws an error.
the problem most likely comes from the fact that you are linking libsendipaux.a twice into your final binary.
the reason why this happens is here:
 %.so: %.c $(LIBS)
        $(CC) -o $@ $(CFLAGS) $(LIBCFLAGS) $+ $(LIBS)

in this target, $+ will expand to all the dependencies of your target (that is: %.c $(LIBS), which will in turn be resolved to ipv4.c libsendipaux.a
the actual call to the compiler can then be read as $(CC) -o $@ $(CFLAGS) $(LIBCFLAGS) ipv4.c $(LIBS) $(LIBS), and $(LIBS) $(LIBS) will expand to libsendipaux.a libsendipaux.a, which will produce the erroneous double linkeage.
so the solution is to remove extraneous $(LIBS) from the .so target:
 %.so: %.c $(LIBS)
        $(CC) -o $@ $(CFLAGS) $(LIBCFLAGS) $+

btw, the errors you get in remake about non-existing files, are because all and subdirs are indeed no files, but phony targets (targets that do no generate files called after the target-name).
to prevent those warnings, add something like the following to your makefile:
.PHONY: all subdirs


text:
Q: Dynamically define variable name and assigning value in Google Apps Script I`m writing a script to generate a form in Google Apps Script.
The idea is, that the user should select his/her name from a dropdown list, and then be transferred to the question block for him/her.
Although the questions are the same, there are slight changes in the choices if the dropdowns for some of the questions.
I have an array with the names of the users, and I've defined the questions for every single user.
This is not ideal, as if there is any change in the questions I have to rewrite every block oone by one.
I want to use a loop which generates the question blocks by creating the variables names using the array of the usernames.
I tried the following (this is not the actual code, but throws the same error)
for (a=0; a < 10; a++)
{
 eval('var beginning'+a);
}

for (b=0;b<10; b++)
{
 eval('beginning' + b) = 1;
}

The first for loop runs fine, but when I try to assign any value it throws an error. (I use here two for loops for debugging only.)
E.g.:
 eval('beginning' + b) = 1;  //Throws: We're sorry, a server error occurred. Please wait a bit and try again.
 eval('beginning' + b + '= 1;');  //Throws: We're sorry, a server error occurred. Please wait a bit and try again.
 eval('beginning' + b = 1);  //Throws: Invalid assignment left hand side. (line 1, file "Code")

Using eval like this is also fine: choices = eval('lCountries' + Names[i]).getChoices();.
How can I assign values to these variables in a for loop?
Thank you very much in advance.

A: As far as I read up so far, eval() is almost always a bad choice, should be handled with caution and mostly never used. Using dynamic variables in such way is also a bad programming logic. I've never seen a case where it is a must, and your case obviously isn't. You can easily get around it with an object, just define a generic object var myVariables = {}, and then start assigning its properties dynamically for your variables.
var myVariables = {};
myVariables[ "beginning" ] = 1;

for( i = 0; i < 10; i++){
  myVariables[ ("beginning" + i) ] = i;
}

Logger.log( myVariable[ "beginning5" ] ); //Loggs 5


text:
Q: Rails sort_by method if value is not empty So I've got a method that I'm using to sort by the result instead of a database column at the moment which works nicely. It will return from the below each loop with a value against each record, then sort the table based on these:
<% @records.sort_by(&:methodName).reverse.each do |record| %>
    <%= record.methodName %>
<% end %>

This works really well - however this method only gets used after a user interacts with the record itself. For instance like a rating, so a record will begin life without a rating, then ratings will be submitted after this point.
It works nicely, until you create a new record that doesn't have a value for this to sort by - is there a way of saying "Sort by what this method returns, if the record doesn't have a value for this, put it at the bottom"?
At the moment I get an exception because it's not a number 'NaN'...because it's empty :(
As always - any help massively appreciated for a Rails beginner here..!

A: Try this
<% @records.sort_by{|r| r.try(:methodName)}.reverse.each do |record| %>

Edit:
<% @records.sort_by{|r| r.methodName.nan? ? 10000 : r.methodName}.reverse.each do |record| %>

A: Assuming that methodName always exists (as a method) and returns a Numeric when the value exists and nil or false otherwise:
@records.sort_by{ |r| r.methodName || -9999999 }

That will cause all records with no entry to be at the start of the list before the reverse, and at the end of the list afterwards.
If that doesn't work, please state what methodName returns for the new records.
Alternatively, you could do this:
newrs, oldrs = @records.partition{ |r| r.methodName }
newrs.each do |r| ... records that have a value for methodName ... end
oldrs.each do |r| ... records with no value for methodName ... end


text:
Q: MS Microsoft SQL Server Management Studio - Import/Export-Database with Default Value or Binding I am using the Microsoft SQL Server Management Studio to clone a database and its tables and data (which runs a MS SQL Server 2008) to a new one (which runs a MS SQL Server 2012).
I know there is the possibility to do so with
"Tasks->Import Data"
and the transfer worked fine for the tables and the data of the tables. Sadly the old database also has set "Default Value or Binding"-Properties for some columns. These seem to have been lost during the transfer. Is there a way to tranfer these values as well?

A: Try to a create a "create script" for your source table and use that script to create your target structure. Then you can copy the data using the import wizard.


text:
Q: Why the second initialization work while the first one fail because of the "element type does not match"? In c++ primer-initializing a Container as a copy of another container.
The element types in the new and original containers can differ as long as it is possible to convert the elements we are copying to the element type of the container we are initializing.
For example:
vector<const char*> articles = {"a", "an", "the"};
vector<string> words(articles) ; //error:element types must match
forward_list<string> words(articles.begin(), articles.end()); // ok, convert const char* to string

My question is why the second initialization work while the first one fail because of the element type does not match ?

A: The first line calls the constructor with an initializer_list of the same type as the element type ( const char*).
something like this:
vector<T>(initializer_list<T> t ) {....}

--> OK!
The second is a copy-constructor call which is only defined for the same element type.
vector<T>(const& vector<T> t) {...}

What you did is something like this:
vector<string>(const& vector<const char*> t){..}

--> Which does not exist!

A: First line performs copy-list-initialization (cfr. initializer_list constructor).
Second line has no matching constructor since the types don't match (it can't call a copy constructor).
Third line instead uses the iterator range constructor which emplace-constructs elements and has a viable const char* to string conversion to use.

A:
My question is why the second initialization works while the first one fails

You're constructing a something. This isn't done by magic, it just has to call one of the something's constructors. Any expression which can't match one of the constructors, can't compile.

So, let's first consider
vector<const char*> articles = {"a", "an", "the"};
vector<string> words(articles);

Now, we need some std::vector constructor that makes sense with this expression. They're listed here, and the only ones that come close to matching are numbers 5 and 6 (at the time of writing - they're the copy and move constructors).
The move constructor is out because we're not using std::move or otherwise working directly on an rvalue reference, so let's take a look at the copy constructor:
vector<string>::vector<string>(const vector<string> &other);

Note that this isn't templated to take any argument type, or to take a vector of any type: it only matches a const reference to a vector of exactly the same type. Even though const char * is implicitly convertible to std::string, the type vector<string> is still not the same as vector<const char *>. So, no constructor matches the argument type given.

Then, consider
forward_list<string> words(articles.begin(), articles.end());

The std::forward_list constructors are listed here. Note number 4:
template< class InputIt >
forward_list(InputIt first, InputIt last,
             const Allocator& alloc = Allocator() );

Firstly, this is templated on the iterator type, so passing vector<string>::iterator or vector<const char *>::iterator or whatever is no problem. Secondly, the conversion to std::string from const char * is sufficient for this overload to actually compile once it is selected.

Now, a couple of notes:

*

*You mentioned the explicit keyword: this just prevents a single-argument constructor being used as an implicit conversion. It doesn't affect higher types though: even if string::string(const char *) is allowed as an implicit conversion, that doesn't make vector<const char *> convertible to vector<string>. That still has to go through one of vector's constructors.

*We're mostly talking here about how an overload (in this case an overloaded constructor) is selected. It's entirely possible the compiler can select an overload, and then still fail to compile. For example, using that second iterator range constructor, where the iterators point to some incompatible (not even explicitly convertible) type.


text:
Q: Excel-like table for counting costs with html/javascript I have created a table with three rows. With three columns and n amount of rows.
The three columns have headers name, quantity and total.
The name needs to be an object which holds the price as parameter.
I have all the objects created and the table aswell, but I can't get the total row to work so that it takes in a user input for the quantity and multiplies it with the price of the product.
<!DOCTYPE html>

            <input type="number" name="qua" value="" />

            <MATH>p1*qua</MATH>

As you can probably tell the code is very clumsy... I am a total beginner as I started this project (and my first HTML and JS) two weeks ago, so please keep it simple.
Thanks a lot in advance!

A: I modified your code as slightly as possible to implement the desired functionality in the existing structure:
<!DOCTYPE html>

            <input type="number" name="qua" value="" onchange = "setTotal(this, p1)"/>

A: I have created a fiddle for you with an example on how you can do it in pure javascript:
http://jsfiddle.net/Mowday/3T9Ct/
Basically I have created a new function for you:
// Adds a product to the table
function addRow(product)
{
    // Get the table reference
    var table = document.getElementById("myTable");

    // Get the number of rows
    var noRows = table.rows.length;
    // Create a new row at the end of the table
    var row = table.insertRow(noRows);

    // Create the three cells
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    // Populate the first row with the price
    cell1.innerHTML = product.price;

    // Create an input field and add it to cell2
    var input = document.createElement("input");
    input.value = 1;
    cell2.appendChild(input);

    // Listen when the user enters anything into the input field
    input.onchange = function()
    {
        // And when the user does input something update the last cell value
        cell3.innerHTML = Number(input.value) * product.price;
    };

    // Call the onchange function ones to populate the last cell
    input.onchange();
};

You have to seperate HTML from Javascript. HTML by itself is static (not entirely true) so you can't update values dynamically or perform maths calculations based on values inside HTML.
That's where javascript comes in. So I cleaned up the table to only contain the column names, and then the new javascript function creates a new row for each product and ties it's values together creating a dynamic table.
So to add more products, you simply call the function again and pass in the product.
That being said, it's a lot easier to use jQuery and something like jqGrid.
jQuery allows you to setup datamodels that can be visualised easily by jqGrid. It's always good to learn the basics and learn how javascript works, but do check out jQuery as well!


text:
Q: Why is ww[[1]] not a valid variable in FindMinValue and Plot Why is ww[[1]] not a valid variable when given to FindMinValue and Plot, but is a variable in Minimize? How can I fix the problem?
In:
ww = Table[w[i], {i, 1, 6}];
a1[y1_, x_] = Function[#1*Cos[#1*0.1] + #2*2][y1, x];

Minimize[a1[ww[[1]], 3], ww[[1]]]
FindMinValue[a1[ww[[1]], 3], {ww[[1]], 1}]
Plot[a1[ww[[1]], 3], {ww[[1]], 0, 1}]

Out:
{0.389037, {w[1] -> -8.60334}}

FindMinValue::vloc: The variable ww[[1]] cannot be localized so that it can
be assigned to numerical values. >>

FindMinValue[a1[ww[[1]], 3], {ww[[1]], 1}]

Plot::write: Tag Part in ww[[1]] is Protected. >>

Plot[a1[ww[[1]], 3], {ww[[1]], 0, 1}]

A: This is not so much an answer as some advice on how you can avoid all the issues that are causing you problems by getting rid of unnecessary complications in your code. You will do better by abandoning the array ww and Function.
a1[y_, x_] := y Cos[.1 y] + 2 x
min = Minimize[a1[w[1], 3], w[1]]

{0.389037, {w[1] -> -8.60334}}

FindMinValue[a1[w[1], 3], {w[1], -1}]

0.389037

To make a plot showing the minimum, extract the coordinates of the minimum
minPt = {min[[2, 1, 2]], min[[1]]}

{-8.60334, 0.389037}

and add it to a plot of a with Epilog.
Plot[a1[w[1], 3], {w[1], -15, 1},
  Epilog -> {Red, AbsolutePointSize[5], Point[minPt]}]


text:
Q: Two Join Statements So I have this query:
SELECT DISTINCT(b.friend_id) AS possible_id
FROM friend_friends a
    JOIN friends_friends b
      ON b.user_id = a.friend_id
WHERE a.user_id = 1703122278

It retrieves the friends of friends of a specific user.
I have another database that contains data on people who have said they are NOT friends.
Here is the query to get the list of said not friends:
SELECT friend_id
FROM friends_not_friends
WHERE user_id = 1703122278
AND not_friends = 1

Then I compare the list of not friends, from the list of possible friends and remove the not friends from the list.
How can I combine these two queries without using a sub-query but rather using Joins?

A: SELECT DISTINCT(b.friend_id) AS possible_id
FROM friend_friends a
  JOIN friends_friends b
    ON b.user_id = a.friend_id
  LEFT JOIN friends_not_friends n
    ON b.friend_id = n.friend_id
      AND n.user_id = a.user_id
      AND n.not_friends = 1
WHERE a.user_id = 1703122278
  AND n.friend_id IS NULL

This shows the
(1st list of friends of friends of 1703122278)
MINUS
(2nd list of not friends of 1703122278)

I hope you don't want the
list of friends of
   (friends of 1703122278
    minus
    (2nd list of not friends of 1703122278)
   )

Just fooling around, here are the queries using NOT IN.
I personally find these more clear, however they may be less efficient regarding speed.
-- Friends of friends of a user
SELECT DISTINCT(b.friend_id) AS possible_id
FROM friend_friends b                      -- the b and a aliases
WHERE b.user_id IN                         -- can be removed
  ( SELECT a.friend_id
    FROM friends_friends a
    WHERE a.user_id = 1703122278
  )
;

and the asked one:
-- Friends of friends of a user that
-- are also not not_friends of the user:
SELECT DISTINCT(b.friend_id) AS possible_id
FROM friend_friends b                      -- the b, a and n aliases
WHERE b.user_id IN                         -- can be removed too
  ( SELECT a.friend_id
    FROM friends_friends a
    WHERE a.user_id = 1703122278
  )
  AND b.friend_id NOT IN
  ( SELECT n.friend_id
    FROM friends_not_friends n
    WHERE n.user_id = 1703122278
      AND n.not_friends = 1
  )
;

A: in oracle i would use MINUS operator.
i thik there is a correlary function in mysql - probably a left join or NOT IN clause

A: Here an solution that filters the "not friends" on  both levels  (it filters the not-friends of the user and the not-friends of the friends of the user):
  SELECT
     DISTINCT(b.friend_id) AS possible_id
  FROM
     friend_friends a
     JOIN friend_friends b ON b.user_id = a.friend_id
     LEFT JOIN friends_not_friends nfa
         ON a.friend_id = nfa.user_id and nfa.not_friends = 1
     LEFT JOIN friends_not_friends nfb
         ON b.friend_id = nfb.user_id and nfb.not_friends = 1
  WHERE
     a.user_id = 1703122278
     AND nfa.friend_id IS NULL
     AND nfb.friend_id IS NULL

The "trick" is to do an LEFT JOIN and check if there is no data (NULL).
By the way - is there an reason that you want no subselect? Sometimes the LEFT JOIN-way is faster, but sub-select are often an good choice.

A: Try a left outer join to the friend_not_friends table (matching on friend_id, filtering on user_id and the not_friends flag) and then eliminate rows where there was a matching row from not_friends (that is, eliminate rows where the not_friend id is NOT NULL)
SELECT DISTINCT(f.friend_id) AS possible_id
  FROM friend_friends a
  JOIN friends_friends f
    ON f.user_id = a.friend_id
  LEFT
  JOIN friends_not_friends n
    ON n.user_id = a.user_id
   AND n.friend_id = f.friend_id
   AND n.not_friends = 1
 WHERE a.user_id = 1703122278
   AND n.user_id IS NULL

The trick is filtering out the rows that matched, leaving the rows that did not find match in the friends_not_friends table. It's the last predicate in the query (n.user_id IS NULL) that does that filtering for you.

Absent the requirement not to use a subquery, then something like this would work as well:
 SELECT DISTINCT(f.friend_id) AS possible_id
   FROM friend_friends a
   JOIN friends_friends f
     ON f.user_id = a.friend_id
  WHERE a.user_id = 1703122278
    AND NOT EXISTS
        ( SELECT 1
            FROM friends_not_friends n
           WHERE n.friend_id = f.friend_id
             AND n.user_id = a.user_id
             AND n.not_friends = 1
        )


text:
Q: Python: codecs and utf-8 global error handling I need to setup a global error handling in codecs for third party package.
In my code I can do something like:
import codecs

print(
    codecs.encode('\ud83d', encoding='utf-8', errors='replace')
)

I want to achieve the same behavior globally. I am trying something like:
def relaxedutf8(exc):
    if not isinstance(exc, UnicodeDecodeError):
        raise TypeError("don't know how to handle %r" % exc)
    if exc.object[exc.start:exc.start+2] == "\xc0\x80":
        return (u"\x00", exc.start+2) # retry after two bytes
    else:
        raise exc

codecs.register_error("test.relaxedutf8", relaxedutf8)

print(
    codecs.encode('\ud83d', encoding='utf-8')
)

but it doesn't work. The error is:
  File "codecs_errros.py", line 18, in <module>
    codecs.encode('\ud83d', encoding='utf-8')
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 0: surrogates not allowed


text:
Q: Excluding a temporary column from MySQL report I am looking for a way to exclude a column that I'm using as a sort key from displaying in the reporting.  In Oracle I can simply say COLUMN SORTKEY NOPRINT, but I haven't been able to find an equivalent in MySQL.  As far as I can tell, I need the sort key so that the rows display in the proper order (Debit, Credit, then Total).
The query I am working with is as follows (it's quite large):
SQL
SELECT    CASE
        WHEN t.transaction_account = '111-111-111-111' THEN 'Debit'
        WHEN t.transaction_account = '222-222-222-222' THEN 'Credit'
      END AS "Transaction",
      CASE
        WHEN t.transaction_account = '111-111-111-111' THEN 1
        WHEN t.transaction_account = '222-222-222-222' THEN 2
      END AS "SORTKEY",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 1 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jan",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 2 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Feb",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 3 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Mar",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('1','2','3') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ1",
                LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 4 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Apr",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 5 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "May",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 6 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jun",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('4','5','6') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ2",
                LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 7 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jul",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 8 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Aug",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 9 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Sep",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('7','8','9') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ3",
                          LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 10 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount

              ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Oct",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 11 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Nov",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 12 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Dec",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('10','11','12') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ4",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "YTD"
FROM     transaction t INNER JOIN common_lookup cl
ON       t.transaction_type = cl.common_lookup_id
WHERE    cl.common_lookup_table = 'TRANSACTION'
AND      cl.common_lookup_column = 'TRANSACTION_TYPE'
GROUP BY  CASE
       WHEN t.transaction_account = '111-111-111-111' THEN 'Debit'
       WHEN t.transaction_account = '222-222-222-222' THEN 'Credit'
     END
,        CASE
       WHEN t.transaction_account = '111-111-111-111' THEN 1
       WHEN t.transaction_account = '222-222-222-222' THEN 2
     END
UNION ALL
SELECT    'Total' AS "Transaction",
      3 AS "SORTKEY",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 1 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jan",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 2 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Feb",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 3 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Mar",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('1','2','3') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ1",
                LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 4 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount

              ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Apr",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 5 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "May",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 6 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jun",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('4','5','6') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ2",
                LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 7 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount

              ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Jul",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 8 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Aug",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 9 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Sep",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('7','8','9') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ3",
                          LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 10 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount

              ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Oct",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 11 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Nov",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) = 12 AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "Dec",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(MONTH FROM transaction_date) IN ('10','11','12') AND
                 EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                  ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "FQ4",
      LPAD(FORMAT(SUM(
          CASE
            WHEN EXTRACT(YEAR FROM transaction_date) = 2009
            THEN
              CASE
                WHEN cl.common_lookup_type = 'DEBIT'
                  THEN t.transaction_amount
                ELSE t.transaction_amount * -1
              END
          END), 2),10,' ') AS "YTD"
FROM     transaction t INNER JOIN common_lookup cl
ON       t.transaction_type = cl.common_lookup_id
WHERE    cl.common_lookup_table = 'TRANSACTION'
AND      cl.common_lookup_column = 'TRANSACTION_TYPE'
GROUP BY  'Total'
ORDER BY SORTKEY;

The query shows as such:
+-------------+---------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+
| Transaction | SORTKEY | Jan        | Feb        | Mar        | FQ1        | Apr        | May        | Jun        | FQ2        | Jul        | Aug        | Sep        | FQ3        | Oct        | Nov        | Dec        | FQ4        | YTD        |
+-------------+---------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+
| Debit       |       1 |   2,957.40 |   4,022.70 |   5,654.04 |  12,634.14 |   4,595.10 |   2,219.64 |   1,300.62 |   8,115.36 |   2,413.62 |   2,149.68 |   2,162.40 |   6,725.70 |   3,291.30 |   3,246.78 |   2,299.14 |   8,837.22 |  36,312.42 |
| Credit      |       2 |    -750.48 |    -992.16 |  -1,437.36 |  -3,180.00 |  -1,217.94 |    -546.96 |    -302.10 |  -2,067.00 |    -597.84 |    -537.42 |    -604.20 |  -1,739.46 |    -829.98 |    -829.98 |    -594.66 |  -2,254.62 |  -9,241.08 |
| Total       |       3 |   2,206.92 |   3,030.54 |   4,216.68 |   9,454.14 |   3,377.16 |   1,672.68 |     998.52 |   6,048.36 |   1,815.78 |   1,612.26 |   1,558.20 |   4,986.24 |   2,461.32 |   2,416.80 |   1,704.48 |   6,582.60 |  27,071.34 |
+-------------+---------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+

A: I'm not aware of any functionality in MySQL that allows this, but I believe you can use CASE in ORDER BY in MySQL, so you probably don't need to.
/* Remove SORTKEY from SELECT */
...
ORDER BY
  CASE
    WHEN t.transaction_account = '111-111-111-111' THEN 1
    WHEN t.transaction_account = '222-222-222-222' THEN 2
  END;


text:
Q: Object doesn't support property or method 'prepend' Estou tentando tornar minha aplicação WEB compatível com o Navegador Edge. Porém eu recebo a mensagem "Object doesn't support property or method 'prepend'" no console quanto eu tento executar o seguinte código:
    var li = document.createElement("li");
 ...
    var list = document.getElementById("history");
    if (this.stackHistory.size() === 0) {
        list.innerHTML = "";
        list.appendChild(li);
    } else {
        if (document.getElementById("historyorder").value === "last")
           list.prepend(li); //ERROR AQUI
        else
           list.appendChild(li);
}

Tal código funcionou no Google Chrome e Firefox

A: O método prepend que indicou não é suportado no navegador Edge nem no IE.
Isso é algo que consegue confirmar na parte de compatibilidade da documentação
No entanto pode utilizar o polyfill que a própria documentação indica:
(function (arr) {
  arr.forEach(function (item) {
    if (item.hasOwnProperty('prepend')) {
      return;
    }
    Object.defineProperty(item, 'prepend', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function prepend() {
        var argArr = Array.prototype.slice.call(arguments),
          docFrag = document.createDocumentFragment();

        argArr.forEach(function (argItem) {
          var isNode = argItem instanceof Node;
          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
        });

        this.insertBefore(docFrag, this.firstChild);
      }
    });
  });
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);

Link para este polyfill no github
O polyfill acima indicado é o código que irá adicionar "ao navegador" ao função prepend caso ele não a suporte. Por este motivo terá de ser executado antes do código que utiliza o prepend.


text:
Q: Composition of permutations in factoradic notation The Lehmer code maps between permutations and natural numbers.  My question: Is a "nice" algorithm known for composing permutations directly in the factoradic form?
When the permutations commute, it looks like digits can be added in modular fashion.  For example, $$1\,1\,1\,0_{!} \cdot 2\,1\,0\,0_{!} =3\,2\,1\,0_!.$$
But when they don't, something more is wanted.


text:
Q: Combine Excel workbooks into one workwook I have 50 workbooks each having 7 worksheets. Now I need to combine them in such a way that the new workbook should have 7 worksheets and each worksheet should have the respective data from all the 50 workbooks.
For example: Worksheet1 of new workbook must contain the data from all the sheet1 of 50 workbooks. Similarly Worksheet2 should contain all the data from sheet2 of all 50 workbooks and so on... till sheet7.

A: Sub simpleXlsMerger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
'change folder path of excel files here
Set dirObj = mergeObj.Getfolder("C:\Users\607182604\desktop\Heinz Jun'15 MI Template\consolidated")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
bookList.Close
Next
End Sub
@dougGlancy and @omegastripes I want the data to be merged Row by Row, Without Any Gaps and yes all workbooks are in the same folders.
The problem I am facing is that it is only merging the 1st worksheet of every workbook. What I want is that, it should merge the data of all the 50 excel files with 7 worksheets in one consolidated workbook but 7 different worksheets.


text:
Q: Android app custom web service authentication using HttpPost does not stick In my application I'm fetching data in JSON format from a web service (Yii PHP site acting as a REST service) that requires authentication.
HttpPost post = new HttpPost(login_url);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(name, pass);
post.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false));

All methods are executed by a single instance of DefaultHttpClient with use of subclassed AsyncTask.
Authentication works fine, but fetching data from another URL gets authentication fail (custom message in internal service format).
HttpPost post = new HttpPost(service_url);
client.execute(post);

Trying to figure out what's the problem I've checked for answers and tested some of them.
I've managed to establish that CookieStorage in DefaultHttpClient instance actually receives and holds Cookies, after first call there are two, one of them is PHPSESSID and it's not expired. Second one appears to be some encoded stuff and it's expiration date seems to be creation time, because it's already expired when I receive it.
If you have any thoughts on this issue, please comment. I've hit a deadend with searching and trying out things that worked for other people.

A: It turned out there was no problem with my code, but the service had an error. Thanks for viewing this question and to @Joël for formatting this for me. Kudos


text:
Q: Why does this simple bash code give a syntax error? I have the following bash code, which is copied and pasted from "bash cookbook" (1st edition):
#!/bin/bash

VERBOSE=0;
if [[ $1 =-v ]]
then
    VERBOSE=1;
    shift;
fi

When I run this (bash 4.0.33), I get the following syntax error:
./test.sh: line 4: conditional binary operator expected
./test.sh: line 4: syntax error near `=-v'
./test.sh: line 4: `if [[ $1 =-v ]]'

Is this as simple as a misprint in the bash cookbook, or is there a version incompatibility or something else here? What would the most obvious fix be? I've tried various combinations of changing the operator, but I'm not really familiar with bash scripting.

A: Bash uses spaces to tokenise scripts. The line:
if [[ $1 =-v ]]

should be:
if [[ $1 = -v ]]


text:
Q: How can I merge the drives of two computers and see them all as one directory? I want to share the drives of two computers using Manjaro Linux and see them all as one directory in both computers.
I've been using mergerfs and sshfs and it was working when I shared one drive of B with A, merged them there and shared the merged folder back with B. Now I've tried merging the drives of B too but I haven't managed to do it.
If possible I would like the computers to still work while the other is disconnected. NFS made one computer hang when the other was disconnected which is why I ended up using sshfs.
The only error I had before was some applications giving input/output error or permission denied. Which I guess it's because I didn't have the proper permissions. I would like to avoid that error too, without having to execute something like chmod -R 777 /mnt/merged often. I don't know if this solution works with mergerfs.
This is what I've tried to do without success
user@A ❯ cat /etc/fstab
# <file system>                        <mount point>  <type>  <options>  <dump>  <pass>
UUID=1615d12a-a9fb-41a9-a84b-34c618f16832 /mnt/hdd1    ext4          nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=d605a480-f133-443c-8fe7-5b0a2d1c60c1 /mnt/hdd2    ext4          nosuid,nodev,nofail,x-gvfs-show 0 0
user@192.168.1.45:/mnt/hdd0  /mnt/hdd0  fuse.sshfs  IdentityFile=/home/user/.ssh/id_rsa,uid=1000,gid=1000,allow_other,default_permissions,_netdev,follow_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,reconnect,noatime,auto  0  0
/mnt/hdd*  /mnt/storage  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,x-gvfs-show  0  0

user@B ❯ cat /etc/fstab
# <file system>             <mount point>  <type>  <options>  <dump>  <pass>
UUID=301e3d8d-6c0a-4f7c-864b-4185a70efbb0 /mnt/hdd1      auto    nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=be8b9fd3-7ed2-45ae-881a-25fa06f4de47 /mnt/hdd2      auto    nosuid,nodev,nofail,x-gvfs-show 0 0
user@192.168.1.122:/mnt/storage  /mnt/hdd0  fuse.sshfs  IdentityFile=/home/user/.ssh/id_rsa,uid=1000,gid=1000,allow_other,default_permissions,_netdev,follow_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,reconnect,noatime 0 0
/mnt/hdd*  /mnt/storage  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,x-gvfs-show 0 0

This is what I was using. It slows the access to the merged folder since it's sharing a drive back and forth.
user@A ❯ cat /etc/fstab
# <file system>                        <mount point>  <type>  <options>  <dump>  <pass>
UUID=1615d12a-a9fb-41a9-a84b-34c618f16832 /mnt/hdd1    ext4          nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=d605a480-f133-443c-8fe7-5b0a2d1c60c1 /mnt/hdd2    ext4          nosuid,nodev,nofail,x-gvfs-show 0 0
user@192.168.1.45:/mnt/hdd1 /mnt/hdd0 fuse.sshfs _netdev,follow_symlinks,IdentityFile=/home/user/.ssh/id_rsa,allow_other,default_permissions,uid=1000,gid=1000,ServerAliveInterval=45,ServerAliveCountMax=2,reconnect,noatime,auto,x-gvfs-show 0 0
/mnt/hdd*  /mnt/storage  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,x-gvfs-show  0  0

user@B ❯ cat /etc/fstab
# <file system>             <mount point>  <type>  <options>  <dump>  <pass>
UUID=301e3d8d-6c0a-4f7c-864b-4185a70efbb0 /mnt/hdd1      auto    nosuid,nodev,nofail,x-gvfs-show 0 0
UUID=be8b9fd3-7ed2-45ae-881a-25fa06f4de47 /mnt/hdd2      auto    nosuid,nodev,nofail,x-gvfs-show 0 0
user@192.168.1.122:/mnt/storage /mnt/storage fuse.sshfs _netdev,follow_symlinks,IdentityFile=/home/user/.ssh/id_rsa,allow_other,default_permissions,uid=1000,gid=1000,ServerAliveInterval=45,ServerAliveCountMax=2,reconnect,noatime,auto,x-gvfs-show 0 0

A: user@A ❯ cat /etc/fstab
/mnt/hdd*  /mnt/merged  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,posix_acl=true  0  0

user@192.168.1.45:/mnt/merged  /mnt/shared  fuse.sshfs  _netdev,user,idmap=user,follow_symlinks,IdentityFile=/home/user/.ssh/id_rsa,allow_other,default_permissions,uid=1000,gid=1001,reconnect,ServerAliveInterval=15,ServerAliveCountMax=3,noatime,x-gvfs-show 0 0

/mnt/hdd*:/mnt/shared  /mnt/storage  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,posix_acl=true,x-gvfs-show  0  0

user@B ❯ cat /etc/fstab
/mnt/hdd*  /mnt/merged  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,posix_acl=true  0  0

user@192.168.1.122:/mnt/merged  /mnt/shared  fuse.sshfs  _netdev,user,idmap=user,follow_symlinks,IdentityFile=/home/user/.ssh/id_rsa,allow_other,default_permissions,uid=1000,gid=1001,reconnect,ServerAliveInterval=15,ServerAliveCountMax=3,noatime,x-gvfs-show 0 0

/mnt/hdd*:/mnt/shared  /mnt/storage  fuse.mergerfs  allow_other,use_ino,cache.files=partial,dropcacheonclose=true,ignorepponrename=true,func.mkdir=epall,posix_acl=true,x-gvfs-show  0  0

I did this in both computers

*

*Change the permissions

❯ sudo chown $USER:$USER /mnt/storage &
❯ chmod -R ugo+rw /mnt/storage &

*Set the setgid bit, so that files/folder under  will be created with the same group as

❯ chmod g+s /mnt/storage &

*Set the default ACLs for the group and other

# Gives read,write,exec permissions for currently existing files and folders, recursively.
❯ setfacl -R -m u::rwx,g::rwx,o::rwx /mnt/storage &

# Gives rwx permissions by default, recursively.
❯ setfacl -R -d -m u::rwx,g::rwx,o::rwx /mnt/storage &


text:
Q: Logging into websites I am trying to run a VB Script that logs into several websites. I can get the first website in the list to login, but am having issues when it opens a new tab and trys the next website. I have verified that the IDs and values are all correct, and that the webpage is loaded before it attempts. It doesn't seem to be able to see the forms and such on that second tab. Any help would be greatly appreciated!
'This is all part of a loop, if it's not the first webpage, it'll open a new tab
   if i = 2 then
      IE.Navigate wp
   else
      IE.Navigate2 wp, 2048
      Wait IE
   end if

'My hack at errorhandling, it has to go through the code at least once
'and THEN fail 5 times before it gives up and quits

errnum = 0
On Error Resume Next
try = 0

do until Err.Number = 0 And try = 1

   try = 1
   if errnum > 5 then
      msgbox "STOPPED"
      objExcel.ActiveWorkBook.Close
      WScript.Quit
   End if

   Wait IE
   Err.Clear

   with IE.Document
      .getElementByID(unid).value = unval
      .getElementByID(pwid).value = pwval
      .getElementByID(but).Click
   End With

   errnum = errnum + 1
loop

A: Navigate2 creates a new IE object, you have to find it.
Your IE object is only a reference to the first tab. the Navigate2 method creates a new window, which is not referenced by the IE object.  The new windows can be accessed from the shell.application object, but you'll have to identify the correct IE or window to operate on.
newIE = getWindow("Title of New Tab")
if isObject(newIE) then
    With newIE.Document
        .getElementByID(unid).value = unval
        .getElementByID(pwid).value = pwval
        .getElementByID(but).Click
    End With
else
    WScript.echo "Window not found"
end if

Function getWindow(sTitle)
    Dim wins, w, result

    set wins = createobject("shell.application").windows
    for i = 1 to 10 ' max iterations before fail
        for each w in wins
            on error resume next
            if instr(1, typename(w.document),"html", vbTextCompare) > 0 then
                if instr(1, w.document.title, sTitle, vbTextCompare) = 1 then
                    set result = w
                    do until w.document.readyState = "complete" : WScript.sleep 50 : loop
                    exit for
                end if
            end if
            on error goto 0
        next
        if isObject(result) then exit for
        WScript.sleep 500 ' ms to wait for each iteration (tab must load before we can get obj)
    next

    if not(isObject(result)) then result = false;
    getWindow = result;

end Function ' getWindow

[EDIT:] Alternate means of locating the correct window
Within the getWindow() function, w is set as an IE object. Thus, you can redefine the getWindow() function to identify the window according to any of the methods available in the InternetExplorer object.
Change the comparison conditional in the main getWindow() loop.
if instr(1, w.document.title, sTitle, vbTextCompare) = 1 then

w is the window, so:

*

*Use the Window.LocationURL property:

*

*`if instr(1, w.LocationURL, sURL, vbTextCompare) = 1 then

*you'll have to define the sURL variable.

*Use the Window.Document.URL property:

*

*`if instr(1, w.Document.URL, sURL, vbTextCompare) = 1 then

*you'll have to define the sURL variable.

Additionally, once you have the window reference w, you can do pretty much anything else you want to with the document, like w.Document.Focus.


text:
Q: $\cos{(A-2B)}+\cos{(B-2C)}+\cos{(C-2A)}=\cos{(2A-B)}+\cos{(2B-C)}+\cos{(2C-A)}$ Let $A,B,C\in \mathbb{R}$ with $\sin{A}+\sin{B}+\sin{C}=0$. Prove that
$$\cos{(A-2B)}+\cos{(B-2C)}+\cos{(C-2A)}=\cos{(2A-B)}+\cos{(2B-C)}+\cos{(2C-A)}$$

A: This is not so much an answer, but a caveat that you cannot simply resolve the $LHS$ of math110's proposed identity (1) into the $RHS$. WolframAlpha gives the complete version as,
$$\cos{(A-2B)}+\cos{(B-2C)}+\cos{(C-2A)}-\big(\cos{(2A-B)}+\cos{(2B-C)}+\cos{(2C-A)}\big) = 8\sin{\left(\frac{A-B}{2}\right)}\sin{\left(\frac{A-C}{2}\right)}\sin{\left(\frac{B-C}{2}\right)}\big( \sin A +\sin B +\sin C\big)$$
Hence, to prove (1), you have to show that the $LHS$ of this new equation is identically equal to the $RHS$.

A: The first idea that comes to mind it to express everything in terms of $\sin A,\ \sin B,\ \sin C$ (and the cosines). It turns out that it works:
Begin with $\cos (A - 2B ) = \cos A \cos 2B + \sin A \sin 2B $ (by the formula for $\cos (x+y)$). Now, get rid of the double angles: $\cos 2B = 1 - 2 \sin^2 B$ and $\sin 2B = 2 \sin B \cos B$. This gives you:
$$\cos (A - 2B ) = \cos A - 2 \cos A \sin^2B + 2 \sin A \sin B \cos B $$
Now, the expression on the left side is (using cyclic summation):
$$ L = \sum_{\text{cyc}} \cos A - 2\sum_{\text{cyc}} \cos A \sin^2B + 2 \sum_{\text{cyc}}\sin A \sin B \cos B $$
Note that it follows from the assumption $\sin A + \sin B + \sin C = 0$ (by moving $\sin B$ to the other side, and multiplying by $\sin B$) that $- \sin^2 B = \sin A \sin B + \sin C \sin B$, so this is:
$$ L = \sum_{\text{cyc}} \cos A + 2\sum_{\text{cyc}} \cos A \sin B \sin A + 2\sum_{\text{cyc}} \cos A \sin B \sin C + 2 \sum_{\text{cyc}}\sin A \sin B \cos B $$
This has grown a little messy, but if you shift the summation in the last sum so that it becomes $ \sum_{\text{cyc}}\sin C \sin A \cos A$, you can rearrange it into something nicer:
$$ L = \sum_{\text{cyc}} \cos A + 2\sum_{\text{cyc}} \cos A (\sin A \sin B + \sin B \sin C + \sin C \sin A ) \\
= (1 + 2\sin A \sin B + 2\sin B \sin C + 2\sin C \sin A )\sum_{\text{cyc}} \cos A
$$
Now, look at the right side. Of course, we might redo the computations, and it would come out the same. There is a nicer way to see this: right side differs from the left side just by ordering of $A,B,C$ (in the sense that if you denote the expression on the left by $L(A,B,C)$, and the one on the right by $R(A,B,C)$, then $R(A,B,C) = L(C,B,A)$). But the formula we arrived at does not depend on the order of $A,B,C$! So $R(A,B,C) = L(C,B,A) = L(A,B,C)$, which is what we wanted.

To make sure the proposed solution is more readable, let me explain what I mean by $\sum_{\text{cyc}}$. If $f(A,B,C)$ is any expression involving $A,B,C$, by $\sum_{\text{cyc}} f(A,B,C)$ I mean the expression $f(A,B,C) + f(B,C,A) + f(C,A,B)$. For example, $\sum_{\text{cyc}} \sin A \cos B = \sin A \cos B  + \sin B \cos C  + \sin C \cos A$. The reasoning strongly relies on the fat that the problem does not change under cyclic rearrangement of $A,B,C$, so if I do some computation for, say, $\sin^2 B$, roughly the same can be done for $\sin^2 A $ and $\sin^2 C$. Note that $\sum_{\text{cyc}} f(A,B,C) = \sum_{\text{cyc}} f(B,C,A)$. Also, $\sum_{\text{cyc}} f(A,B,C)g(A,B,C) = g(A,B,C) \sum_{\text{cyc}} f(A,B,C)$ provided that $g(A,B,C)= g(B,C,A)=g(C,A,B)$


text:
Q: Replicate and transpose data I've been attempting to reshape my data and I've come to a block in how to accomplish this. I have rather large data sets but here's an example of a single row:
TJ25_TAD

TJ_num     Date                Bin 1    Bin2    Bin3
TJ25       4/18/2006 19:00     1.5      73.9    16.2

I want to replicate each row (each date/hour value for which I have hundreds of rows) and then have a single column for the values so it looks like this:
TJ25_TAD

TJ_num     Date                TAD
TJ25       4/18/2006 19:00     1.5
TJ25       4/18/2006 19:00     73.9
TJ25       4/18/2006 19:00     16.2

For each date value I actually have 12 bins. I've managed to be able to replicate each date value 12 times, I just don't know how to fill in the Bin data. I've read about the melt() function, but I don't know how to employ it properly.

A: dt <- read.table(text = "TJ_num  Date  'Bin 1' 'Bin 2' 'Bin 3'
    TJ25 '4/18/2006 19:00' 1.5 73.9 16.2",
                 header = TRUE, stringsAsFactors = FALSE)

library(dplyr)
library(tidyr)

dt2 <- dt %>%
  gather(Bin, TAD, 'Bin.1', 'Bin.2', 'Bin.3') %>%
  select(-Bin)


text:
Q: Is it appropriate to use reflection to create a list of objects of all subclasses? In my program, different features are divided into different modules, potentially hundreds of modules,
each module is a subclass of an abstract Module class
which look something like this
public abstract class Module {

    public final String name;

    public Module(String name){
        this.name = name;
    }

    public abstract void execute();
}

with subclasses that look like this
public class Mod1 extends Module{
    public Mod1() {
        super("Mod1");
    }

    @Override
    public void execute() {
        //Do something
    }
}

and I need to make a list of instances of all modules but doing it like this is kinda tedious since my program might have hundreds of modules and it might be hard to debug(I might miss a few lol)
private static final List<Module> MODULES = new ArrayList<>();

public void init(){
    MODULES.add(new Mod1());
    MODULES.add(new Mod2());
    MODULES.add(new Mod3());
    MODULES.add(new Mod4());
    MODULES.add(new Mod5());
}

so I think using reflection might be the way to go but after a quick google search, I see many people don't like reflection in production code, so I come here to ask if this is an appropriate case to use reflection or is there any reason or design change to avoid using reflection in this particular case
edit: the list will be used stuff like rendering modules in gui or calling execute method of the module from other user interface like command(simply find the module with matching name and execute it)
note: this is not how my code actually look like but a highly simplified version that give a similar idea

A: For a minimal-effort approach, java provides the built-in class java.util.ServiceLoader.
With this class you can obtain all available implementations of a service class (in this case Module) like
ServiceLoader moduleLoader = ServiceLoader.load(Module.class);
for (Module mod : moduleLoader) {
    System.out.println(mod.name);
}

Note that I highlighted the term available in the previous sentence. In fact, the ServiceLoader implementation does not perform any advanced class-hierarchy lookup, instead it relies on a specific resource file named equal to the canonical name of the Module class.
META-INF/services/com.example.project.Module
com.example.project.impl1.Module1
com.example.project.impl2.Module2

Where each line of the file references an available implementation of Module.

Now, ServiceLoader is an implementation of the java SPI specification, which does not necessarily have to qualify perfectly for your use case. However, since its idea of service loading and providing is rather simple, you can easily build your own variant.
public class JsonServiceLoader<S> {

    private Class<S> service;
    private Map<String, String> serviceIdentifiers;

    public static <T> JsonServiceLoader load(Class<T> service, ClassLoader cl) {
        Map<String, String> serviceIdentifiers = new HashMap<>();
        String name = "META-INF/json-services/" + service.getCanonicalName();
        // TODO check for null references where necessary
        for (Enumeration<URL> resources = cl.getResources(name); resources.hasMoreElements();) {
            try (InputStream resource = resources.next().openStream()) {
                for (Map.Entry<String, String> identifier : parseJson(resource).entrySet()) {
                    serviceIdentifers.merge(
                        identifer.getKey(),
                        identifer.getValue(),
                        (value1, value2) -> throw new ServiceConfigurationError(
                            "duplicate service identifier '" + identifier.getKey() + "'"
                        );
                    );
                }
            }
        }
        return new JsonServiceLoader<>(service, serviceIdentifiers);
    }

    private static Map<String, String> parseJson(InputStream resource) {
        // TODO parse JSON data from the given stream using your favourite JSON facility
        /*
         * If you want to use a different style of resources, e.g. XML, this is the only
         * location you have to change (you might want to rename 'json-services' though).
         */
        return new HashMap<>();
    }

    private JsonServiceLoader(Class<S> service, Map<String, String> serviceIdentifiers) {
        this.service = service;
        this.serviceIdentifiers = serviceIdentifiers;
    }

    public Set<String> getServiceIdentifiers() {
        return Collections.unmodifiableSet(serviceIdentifiers.keySet());
    }

    public S getService(String name) {
        String className = serviceIdenfiers.get(name);
        if (null == className) {
            throw new IllegalArgumentException("invalid service identifier '" + name + "'");
        }
        // TODO improve error handling
        try {
            return service.cast(Class.forName(className).newInstance());
        } catch(Exception exc) {
            throw new ServiceConfigurationError("could not load service '" + name + "'", exc);
        }
    }

}

Your JSON resources could look like
META-INF/json-services/com.example.project.Module
{
    "Mod1" : {
        "class" : "com.example.project.impl1.Module1"
    },
    "Mod2" : {
        "class" : "com.example.project.impl2.Module2"
    }
}

allowing future extensions.
At this point, the Module class also does not need to know its name (the class member name) anymore, since you can always ask the service loader for an appropriate instance. (If you do so at some place in your code, you will already know for which name you just asked.) If so desired, you can also add more logic to this JsonServiceLoader, such as caching.
Ultimately, it all depends on how much information you want to process around your Module and how much of this information you want the Module implementations to handle and how much of it you want the service framework to handle.

A: Perhaps you can pass the list into the constructor of the parent class and add subclass itself to the list in the constructor method.
Just like this
public abstract class Module {

    public final String name;

    public Module(String name, List<Module> list) {
        this.name = name;
        list.add(this);
    }

    public abstract void execute();
}

private static final List<Module> MODULES = new ArrayList<>();

public void init(){
    new Mod1(MODULES);
}


text:
Q: UIScrollView Notification? Is there any notification sent when UIScrollView changes its scroll state? I would like to listen to that notification rather than using delegate methods.

A: If you don't want to use delegate methods you can observe contentOffset value changes using KVO (key-value-observing)

A: You can subclass UIScrollView, overload touchesMoved:withEvent:, and send this notification every time your scroll view will scroll.
As the scrolls need to be lightweight events I would not recommend using notifications for every scroll as it will impact your performance much greater than using a delegate method.

A: These are the delegates that handle scrolling for UIScrollView.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset

Is there any specific reason you dont prefer delegates & want notifications? So you can use scrollViewDidScroll for any changes in scroll state.


text:
Q: How to get F# project templates in Visual Studio 2013 Update 2 RC? With Visual Studio 2013 Update 2 RC
I can open existing F# projects but can't create new.
Repaired FSharp_Bundle (F# Tools 3.1.1) but it made no effect.
So how to get F# project templates in Visual Studio 2013 Update 2 RC?


text:
Q: Angular 1.6.9 and socket.io chat application The following code I have developed so far for a chat application using Angular and Socket.io. The crucial part that I can't seem to fix is the "nickWrap". It consists of a message 'Enter Nickname', an input text box and a submit button. The nickname is passed to the server where it checks in an array if the nickname is already present. If not then it should give back a success, then I should disable the form and show another div content. But it seems that after I get back a success message, I have to type something in the input textbox again and only then it gets disabled. Also, the list of users online after this form is disabled is not always correctly shown in select using ng-repeat. There is always an empty space. Plus when another user connects, then the existing user can't dynamically see new user in the select list, while the new user can see old users. If any one user disconnects, then the select list of other user's client doesn't dynamically update the list either. I am pretty new to Angular, nodejs, socket.io and all of this
The Client Code is:
<!doctype html>

        <title>chat</title>

        </script>

            Enter NickName:

                <form ng-submit="myFunc()">
                    <input type="text" placeholder="random nickname" ng-model="nickname" ng-disabled="ok">
                    <input type="submit" ng-disabled="ok">
                </form>

                <select name="sometext" size="20" style="width:200px" ng-model="selector">
                    <option ng-repeat="namelist in names">{{namelist}}</option>
                </select>

                LIST OF ONLINE USERS

            <form ng-submit="sendRequest()">
                <input type="submit" value="Send Chat Request to {{selector}}"/>
            </form>

            MESSAGES WILL APPEAR HERE SOON!!!!!!

The server code is:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var nicknames=[];

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});
app.post('/log', function(req, res){
  console.log('someone connected');
});

io.on('connection', function(socket){
    console.log('a user '+socket.id+' connected');
    socket.on('disconnect', function(){
      console.log('user '+socket.id+' disconnected');
      //if(!socket.nickname) return;
      nicknames.splice(nicknames.indexOf(socket.nickname),1);
      socket.emit('usernames',nicknames);
      //updateNames();
    });
    socket.on('chat message', function(msg){
      console.log('message from user '+socket.id+' : ' + msg);
    });
    socket.on('new user',function(data, callback){
      console.log(data);
      if(nicknames.indexOf(data)!=-1){
        callback(false);
      }
      else{
        callback(true);
        socket.nickname=data;
        nicknames.push(data);
        //updateNames();
        socket.emit('usernames',nicknames);
      }
    });
    socket.on('chat message', function(msg){
      io.emit('chat message', msg);
    });
    //function updateNames(){
      //socket.emit('usernames',nicknames);
    //}
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

A: Your first 2 problems (input disabled and ng-repeat) are linked.
In angularJS, when you call a service like socket.emit, you go out of angular's context and the $scope is not updated.
After you set your variables you need to force a call to $scope.$apply()
socket.emit('new user',$scope.nickname,function(data){
  if(data){
    alert('You picked good nickname');
    $scope.ok=true;
  } else {
    alert('Pick a different Nickname');
    $scope.ok=false;
  }
  $scope.$apply();
});


text:
Q: Restructuring an object with map and forEach I've got an object that i'm trying to map to a react component (using lodash). The current shape of the objects that I get back from my API (firebase) looks like this...
// ex. 1
{
  "-Kdkahgiencls0dnh": {
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  "-Ksdfadfvcls0dsnh": {
    "name": "another name",
    "desc": "another description",
    "other": "some more"
  },
  "-kgoandiencls0dnh": {
    "name": "I am a name",
    "desc": "I am a description",
    "other": "I am some other guff"
  }
}

...but, I loose the primary key when i run through _.map()
What i'm trying to do is get my object in the shape of:
// ex. 2
[
  {
    "id": "-Kdkahgiencls0dnh",
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  {... the next object ...},
  {... etc ...}
]

What i'm doing now is getting my data in the componentWillMount lifecycle method like so:
componentWillMount() {
  firebaseRef.on('value', snap => {
    let data = snap.val() // the whole original object (see ex. 1)
    let tempArray = [] // an array to store my newly formatted objects
    _.forEach(data, (item, key) => {
      // Here's where i'm not really sure what to do.
      // I want to use Object.assign to set a new key:value
      // That adds "id": "-theobjectsmainkey" to a new object
      // then push to my tempArray and finally setState with the
      // correctly formatted array of objects.
    })
  })
}

Ideas? Thoughts? Thanks.

A: Lodash's _.map() callback receives as a 2nd parameter the iterated key. Use object assign, to create a new object with the key as id:
const array = _.map(data, (item, id) => Object.assign({ id }, item))

Demo:

const data = {"-Kdkahgiencls0dnh":{"name":"a name","desc":"a description","other":"some other guff"},"-Ksdfadfvcls0dsnh":{"name":"another name","desc":"another description","other":"some more"},"-kgoandiencls0dnh":{"name":"I am a name","desc":"I am a description","other":"I am some other guff"}};

const array = _.map(data, (item, id) => Object.assign({ id }, item));

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

A: You can use Object.entries(), .map() and object spread

const data = {
  "-Kdkahgiencls0dnh": {
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  "-Ksdfadfvcls0dsnh": {
    "name": "another name",
    "desc": "another description",
    "other": "some more"
  },
  "-kgoandiencls0dnh": {
    "name": "I am a name",
    "desc": "I am a description",
    "other": "I am some other guff"
  }
}

let res = Object.entries(data).map(([id, prop]) => ({id, ...prop}));

console.log(res);

A: componentWillMount() {
  firebaseRef.on('value', snap => {
    let data = snap.val() // the whole original object (see ex. 1)
    let tempArray = Object.keys(data).map((item, key) => {
        return {
            "id": item,
            "name": data[item].name // etc, a structure what you want
            ...
        };
    })
  })
}

A: Here you go, using only pure JS :
const raw = {
  "-Kdkahgiencls0dnh": {
    "name": "a name",
    "desc": "a description",
    "other": "some other guff"
  },
  "-Ksdfadfvcls0dsnh": {
    "name": "another name",
    "desc": "another description",
    "other": "some more"
  },
  "-kgoandiencls0dnh": {
    "name": "I am a name",
    "desc": "I am a description",
    "other": "I am some other guff"
  }
}

let formatted = Object.keys(raw).map(
  key=>Object.assign(raw[key], {"id": ""+key})
);

Here is a fiddle to get a live demo.