text:
Q: Curl sept_opt and sept_opt_array undefined function despite php curl extension I have problems to use curl in order to do some stripe payments.I installed the php curl extension with using the absolute path in ext folder but sept_opt is still undefined but curl_init() seems ok.

Install extension php, install curl.exe, system variables
print_r(curl_getinfo($ch)); :

Array ( [url] => [content_type] => [http_code] => 0 [header_size] => 0
  [request_size] => 0 [filetime] => -1 [ssl_verify_result] => 0
  [redirect_count] => 0 [total_time] => 0 [namelookup_time] => 0
  [connect_time] => 0 [pretransfer_time] => 0 [size_upload] => 0
  [size_download] => 0 [speed_download] => 0 [speed_upload] => 0
  [download_content_length] => -1 [upload_content_length] => -1
  [starttransfer_time] => 0 [redirect_time] => 0 [redirect_url] =>
  [primary_ip] => [certinfo] => Array ( ) [primary_port] => 0 [local_ip]
  => [local_port] => 0 [http_version] => 0 [protocol] => 0 [ssl_verifyresult] => 0 [scheme] => [appconnect_time_us] => 0
  [connect_time_us] => 0 [namelookup_time_us] => 0 [pretransfer_time_us]
  => 0 [redirect_time_us] => 0 [starttransfer_time_us] => 0 [total_time_us] => 0 )

if (!function_exists('curl_setopt_array')) {
    function curl_setopt_array(&$ch, $curl_options)
    {
        foreach ($curl_options as $option => $value) {
            if (!curl_setopt($ch, $option, $value)) {
                return false;
            }
        }
        return true;
    }
 }
      $ch = curl_init();
      print_r(curl_getinfo($ch));
      $url="http://api.stripe.com/v1/".$endpoint;
      curl_septopt($ch, CURL_OPT_URL, $url);
      curl_septopt($ch,  CURL_OPT_RETURNTRANSFER, true);
      curl_septopt($ch,  CURL_OPT_USERPWD, $this->api_key ) ;
      curl_septopt($ch,  CURL_HTTP_AUTH , CURL_AUTH_BASIC);
      curl_septopt($ch,  CURL_OPTIONS_POSTFIELDS , 'http_build_query('.$data.')');

Fatal error: Uncaught Error: Call to undefined function curl_septopt()
  in C:\xampp\htdocs\venifruit\libs\stripe.php:29 Stack trace: #0
  C:\xampp\htdocs\venifruit\modules\espace-achat-primeur\stripe-creer-paiement.php(17):
  Stripe->api('customers', Array) #1
  C:\xampp\htdocs\venifruit\index.php(187):
  include('C:\xampp\htdocs...') #2 {main} thrown in
  C:\xampp\htdocs\venifruit\libs\stripe.php on line 29

A: The method is called curl_setopt(); and not curl_septopt();.
      $ch = curl_init();
      print_r(curl_getinfo($ch));
      $url="http://api.stripe.com/v1/".$endpoint;
      curl_setopt($ch, CURL_OPT_URL, $url);
      curl_setopt($ch, CURL_OPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURL_OPT_USERPWD, $this->api_key) ;
      curl_setopt($ch, CURL_HTTP_AUTH , CURL_AUTH_BASIC);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Also, there is no need to encode the Postfields. When passed as Array, it will encode it. Read the manual for details.

A: We need to use ssl connections the easier is that way
take this class on github and install to the root of server : Stripe class on github
And use this easy code :
 require_once('/path/to/stripe-php/init.php'); // Don't forget this line link to the right  library

\Stripe\Stripe::setApiKey("sk_test_votre-clé-api-stripe-secrete-test");

  $token  = $_POST['stripeToken'];
  $email  = $_POST['stripeEmail'];

  $customer = \Stripe\Customer::create(array(
      'email' => $email,
      'source'  => $token
  ));

  $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => 500,
      'currency' => 'eur',
      'description' => 'Discover France Guide by Erasmus of Paris',
      'receipt_email' => $email
  ));

  echo '
Payment accepted!
';


text:
Q: Include only used imports in the packaged bundle ReactJS I wanna use only one component from Material Ui library . I know i can import only one component using ES6 import but does webpack treeshake and remove other components from the library or include them in production .
Please help me.

A: Webpack from v2 onwards eliminates unused exports in two steps:
First, all ES6 module files are combined into a single bundle file in which exports that were not imported anywhere are not exported, anymore.
Second, the bundle is minified, while eliminating dead code. Therefore, entities that are neither exported nor used inside their modules do not appear in the minified bundle. Without the first step, dead code elimination would never remove exports.
Unused exports can only be reliably detected at build time if the module system has a static structure.
Webpack doesn't perform tree-shaking by itself. It relies on third party tools like UglifyJS to perform actual dead code elimination.
To do that, you would install it using
npm install --save-dev uglifyjs-webpack-plugin

And then adding it into the config:
webpack.config.js
const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new UglifyJSPlugin()
  ]
};

So when you add this config, your unused exports are not longer present in the minified build.

A: Webpack 5 comes with terser-webpack-plugin out of the box, hence you can just import it and configure as you wish.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $B$ be an uncountable dimensional real Banach space and $T:B \to B$ be a surjective isometry such that $T(0)=0$ , then is $T$ linear? Let $B$ be a real Banach space and $T:B \to B$ be a surjective isometry such that $T(0)=0$ , then is $T$ linear ?
I know that it is true if $B$ is a Hilbert space ( we only need an inner product actually and even without assuming $T$ is surjective , [ though if $B$ is a finite dimensional NLS then any linear isometry on $B$ is surjective] ) , but have no idea what happens for Banach spaces in general . Please help . Thanks in advance

A: A more general case is when $B$ is a real normed space. You vcan apply Mazur–Ulam theorem :

If ${\displaystyle V}$  and ${\displaystyle W}$  are normed spaces over $\mathbb{R}$ and the mapping ${\displaystyle f\colon V\to W} $
  is a surjective isometry, then ${\displaystyle f}$  is affine.

So $f$ is affine with $f(0)=0$, so $f$ is linear.
So if $B$ is a real Banach space, it is also true that $T$ is linear.
You can find a proof of the theorem on this paper : Proof of Mazur–Ulam theorem .


text:
Q: How do I use Java's MidiSystem.write() function? Java Doc for Function
I can't seem to figure out how to use this function.  I have a Java.Midi.Sequence and the File I want to write to, but I can't figure out what "int fileType" is.  There are no static int's to reference in either MidiSystem, Sequence, or MidiFileWriter.  Nor does 0 help.
The Error I get when using zero is so:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: seph.reed.effigy.MidiLoader$1 cannot be cast to javax.sound.midi.ShortMessage
at com.sun.media.sound.StandardMidiFileWriter.writeTrack(StandardMidiFileWriter.java:386)
at com.sun.media.sound.StandardMidiFileWriter.getFileStream(StandardMidiFileWriter.java:204)
at com.sun.media.sound.StandardMidiFileWriter.write(StandardMidiFileWriter.java:137)
at com.sun.media.sound.StandardMidiFileWriter.write(StandardMidiFileWriter.java:153)
at javax.sound.midi.MidiSystem.write(MidiSystem.java:1060)
at seph.reed.effigy.MidiLoader.saveClipAs(MidiLoader.java:197)
at seph.reed.effigy.EffigyMenuBar$2.onClick(EffigyMenuBar.java:47)

The personal function referenced is:
public void saveClipAs(File selectedFile) {
    try {
        Sequence out = new Sequence(Sequence.PPQ, 256);
        Track toMe = out.createTrack();

        Sequencer fromMe = ANCESTOR(Effigy.class).m_gui.getCurrentClip().m_sequencer;
//traverse linked list adding notes to track
        for(MidiEventEntity ptr = fromMe.m_head; ptr != null; ptr = ptr.m_next) {
            byte[] midiData = new byte[3];
            midiData[0] = MidiToolBox.NOTE_ON;
            midiData[1] = (byte)ptr.getNote();
            midiData[2] = (byte)127;

            long tick = (long) (256 * ptr.getBeat()); //256 ticks per 1/4 note
            MidiEvent addMe = new MidiEvent(new MidiMessage(midiData) {
                @Override
                public Object clone() {
                    return null;  }
            }, tick);
            toMe.add(addMe);
        }

  //THIS LINE BELOW
        MidiSystem.write(out, 0, selectedFile);
    }
    catch (InvalidMidiDataException e) {
        e.printStackTrace();  }
    catch (IOException e) {
        e.printStackTrace();
    }
}

Thanks for any help.  I'm utterly at a loss as to what int fileType is really asking for.
EDIT: removed a dumb secondary question.
EDIT: functional code:
for(MidiEventEntity ptr = fromMe.m_head; ptr != null; ptr = ptr.m_next) {
            byte status = MidiToolBox.NOTE_ON;
            byte note = (byte)ptr.getNote();
            byte velocity = (byte)127;

            long tick = (long) (256 * ptr.getBeat()); //256 ticks per 1/4 note
            ShortMessage msg = new ShortMessage(status, note, velocity);
            MidiEvent addMe = new MidiEvent(msg, tick);
            toMe.add(addMe);
        }

A: It looks like the int corresponds to Midi Type 0, Midi Type 1, Midi Type 2 (more details here)
In terms of how you go about determining what midi types your system supports it looks like you can call the MidiSystem.getMidiFileTypes(Sequence sequence) method.

A: According to https://docs.oracle.com/javase/tutorial/sound/SPI-providing-MIDI.html :

There are three standard MIDI file formats, all of which an implementation of the Java Sound API can support: Type 0, Type 1, and Type 2. These file formats differ in their internal representation of the MIDI sequence data in the file, and are appropriate for different kinds of sequences. If an implementation doesn't itself support all three types, a service provider can supply the support for the unimplemented ones. There are also variants of the standard MIDI file formats, some of them proprietary, which similarly could be supported by a third-party vendor.

Thus the fileType is either 0, 1, or 2.
What kinds of file types your implementation supports can be seen via MidiSystem.getMidiFileTypes().
The file type of a midi file can be identified via
MidiSystem.getMidiFileFormat() (see
http://docs.oracle.com/javase/7/docs/api/javax/sound/midi/MidiSystem.html#getMidiFileFormat%28java.io.File%29
and http://docs.oracle.com/javase/7/docs/api/javax/sound/midi/MidiFileFormat.html)


text:
Q: Does Monetdb support server-side scripting like PG/SQL? Hi I read Here that MonetDB support server-side script (like PG/SQL for Oracle). However I'm not able to found any related documentation on the MonetDB website
Can some one have any pointers, documentation, tutorial about server-side scripting in monetdb ?

A: I finally found the anwser in this web page see here


text:
Q: find polygon which contains the point using postgis/postgres I have 2 tables and both of them contain 2 columns. The first table contains 50 million rows while 2nd table contains 50 rows
Table1 - Columns: point_coord (datatype: point), id (integer)
Table2 - columns: region (datatype: geometry - they are polygons), id (integer)
The id column in the 1st table is empty and is to be filled using the 2nd table. If a point(point_coord) lies inside any of the 50(number of rows in 2nd table) polygons available in the second table then the corresponding id of that polygon gets filled in the id column of the 1st table.
I am new to using postgis using postgres. I was able to figure out that I need to use st_contains function but I am not sure what would be the best way to use it.

A: Something like this
UPDATE table1
SET id = table2.id
WHERE st_intersects(table1.point_coord , table2.region )

This would be the basic structure. you need to explore the geometry function st_intersects of postGIS. You can also use st_within too.


text:
Q: JQGrid subgrid all rows displaying first row data throughout the grid I'm trying to implement 3 level nested grid, the data is binding to the arrays is looking fine. The subgrids are returning NULL data. Here is the code
   var removeSubgridIcon = function () {
            var $this = $(this),
                idPrefix = $this.jqGrid("getGridParam", "idPrefix");
            $this.find(">tbody>tr.jqgrow>td.ui-sgcollapsed").filter(function () {
                var rowData = $this.jqGrid("getLocalRow",
                                           $.jgrid.stripPref(idPrefix, $(this).closest("tr.jqgrow").attr("id")));
                return rowData.subgrid === null;
            }).unbind("click").html("");
        };

        var isHasSubrids = function (data) {

            if (data == null) { return false; }
            else
            {
                var l = data.length, i;
                for (i = 0; i < l; i++) {
                    if (data[i].subgrid !== null) {
                        return true;
                    }
                }
            }

        };

        $gridName.jqGrid({
            datatype: 'local',
            data: records,
            colNames: ['ContractId', 'Description', 'Status', 'Classification', 'Start Date', 'End Date', 'Cancel Date'], // #PF - add opp id column later
            colModel: [
                { name: 'contractid', width: 100, fixed: true },
                // #PFG - 3/17/2014 - LATER { name: 'opportunity', index: 'opportunity', width: 100, fixed: true },
                { name: 'description', width: 200, fixed: true },
                { name: 'status', autowidth: true, align: 'center' },
                { name: 'classification', align: 'center' },
                { name: 'startdate', align: 'center' },
                { name: 'enddate', align: 'center' },
                { name: 'canceldate', align: 'center' }
            ],
            gridview: true,
            idPrefix: "m",
            rownumbers: true,
            autoencode: true,
            viewrecords: true,
            sortname: 'contractid',
            sortorder: 'desc',
            height: '100%',
            subGrid: isHasSubrids(records),
            loadComplete: function () {
                removeSubgridIcon.call(this);
            },
            subGridRowExpanded: function (subgridDivId1, rowId1) {
                var $subgrid1 = $("

"),
                    localRowData1 = $(this).jqGrid("getLocalRow", rowId1);
                $subgrid1.appendTo("#" + $.jgrid.jqID(subgridDivId1));
                $subgrid1.jqGrid({
                    datatype: 'local',
                    data: localRowData1.subgrid,
                    colNames: ['ContractLineId', 'Item Name', 'Start Date', 'End Date', 'Cancel Date', 'Description', 'Vendor Name', 'IsShipped'],
                    colModel: [
                        { name: "contractlineid", width: 130, key: true, fixed: true },
                        { name: "itemname", fixed: true, align: 'center' },
                        { name: "startdate", fixed: true, align: 'center' },
                        { name: "enddate", fixed: true, align: 'center' },
                        { name: "canceldate", fixed: true, align: 'center' },
                        { name: "description", width: 330, fixed: true, align: 'center' },
                        { name: "vendorname", fixed: true, align: 'center' },
                        { name: "isshipped", fixed: true, align: 'center' }
                    ],
                    gridview: true,
                    idPrefix: "s" + rowId1 + "_",
                    rowNum: 300,
                    rownumbers: true,
                    autoencode: true,
                    sortname: 'contractlineid',
                    sortorder: "desc",
                    height: "100%",
                    //loadComplete: removeSubgridIcon,
                    subGrid: isHasSubrids(localRowData1.subgrid),
                    subGridOptions: {
                        "plusicon": "ui-icon-triangle-1-e",
                        "minusicon": "ui-icon-triangle-1-s",
                        "openicon": "ui-icon-arrowreturn-1-e",
                        // load the subgrid data only once
                        // and the just show/hide
                        "reloadOnExpand": false,
                        // select the row when the expand column is clicked
                        "selectOnExpand": true
                    },
                    subGridRowExpanded: function (subgridDivId2, rowId2) {
                        // Sub grid2 holding product details
                        var $subgrid2 = $("

"),
                            localRowData2 = $(this).jqGrid("getLocalRow", rowId2);
                        $subgrid2.appendTo("#" + $.jgrid.jqID(subgridDivId2));
                        $subgrid2.jqGrid({
                            datatype: 'local',
                            data: localRowData2.subgrid,
                            colNames: ['ProductId', 'Name', 'Description'],
                            colModel: [
                                { name: "productid", key: true, fixed: true, align: 'center' },
                                { name: "name", fixed: true, align: 'center' },
                                { name: "description", width: 500, fixed: true, align: 'center' }
                            ],
                            gridview: true,
                            autowidth: true,
                            idPrefix: "s" + rowId1 + "_" + rowId2 + "_",
                            rownumbers: true,
                            autoencode: true,
                            sortname: 'productid',
                            sortorder: "desc",
                            height: '100%',
                            subGrid: isHasSubrids(localRowData2.subgrid),
                            subGridOptions: {
                                "plusicon": "ui-icon-triangle-1-e",
                                "minusicon": "ui-icon-triangle-1-s",
                                "openicon": "ui-icon-arrowreturn-1-e",
                                // load the subgrid data only once
                                // and the just show/hide
                                "reloadOnExpand": false,
                                // select the row when the expand column is clicked
                                "selectOnExpand": true
                            }
                            //loadComplete: removeSubgridIcon
                        });
                    }
                });
            }
        });

            //============================================================
            // set grid width
            //============================================================
        $gridName.setGridWidth($('#account-page').width() - 15, true);
    } else {
        $('#account-contract-content').html('No records exists.');
    }

data: records has the entire tree structure
localRowData1 = $(this).jqGrid("getLocalRow", rowId1);
localRowData1 is not getting any subgrid rows
subGrid: isHasSubrids(localRowData1.subgrid) here localRowData1.subgrid is returning NULL
this is how my data looks like:
 -0:Object
  |
  |  -0:Object
  |   |
  |   |     -0:Object
  |   |      |
  |   |      |
  |   |       Description:
  |   |       Name:
  |   |       Prouductid:
  |   |
  |   |      1:Object
  |   |
  |   |      2:Object
  |   |
  |   |      3:Object
  |   |
  |   |
  |   |
  |    canceldate:
  |    contractlineid:
  |    Description:
  |    EndDate:
  |    Isshipped:
  |
  |   +1:Object
  |
  |   +2:Object
  |
  |   +3:Object
  |
  |
  |
  |
   canceldate:
   classification:
   contractid:
   description:
   enddate:
   startdate:
   status:

  +1:Object

  +2:Object

  +3:Object

A: It's very bad choice to fill the grid with data using addRowData. It's not only the slowest way. You use many times addRowData using i + 1 as rowid. If you do so then the key property defined in colModel will be ignored. Instead of that the values 1,2,3... will be used. In case of usage subgids you will have a lot of id duplicates which is evil.
I strictly recommend you to fill grids using data parameter. In the case jqGrid automatically sort the data based on the values of sortname and sortorder parameters. It makes paging of data automatically too. No additional call of .trigger('reloadGrid') is required after the filling of the grid.
Even if you would use correct id value which corresponds native representation of the data you can still have id duplicates in different subgrids or between main grid and some subgrid. So it's strictly recommended to use unique idPrefix for every grid and every subgrid. See the answer or this one for more details.
UPDATED: I fixed your jsfiddle demo to the following working code: http://jsfiddle.net/OlegKi/1ggvpukb/5/


text:
Q: App dev using PhoneGap, server storage queries/advice? I am building an app using PhoneGap and the web technologies.
My goal: to generate data from a mobile device and tag it with a few tags and upload it to a server. Users should be able to call back the uploaded data filtering it by selecting a tag or tags.
I found plenty on local storage info and how-to's but its of no use in this case. I started reading about Jersey and Restlet but to a non-programmer, like myself, it seems a bit overwhelming. Lawnchair grabbed my eye and I read a lot about it but that also seems like a local storage solution.
My question: given the above criteria, bearing in mind, the simplicity, what is the fastest and most painless way of approaching this task in your opinion?


text:
Q: Html div id not aligning properly I have a main div on my page that has the attribute align="center", yet for some reason it is not aligning in the center.
for reference here is the page.
CSS:
#page{
    background-color: #4C1B1B;
    width:85%;
    height:500px;

}

HTML:

        TEST

Thanks in advance!

A: Add margin:auto to the #page rule instead and remove the align="center"
#page{
   background-color: #4C1B1B;
   width:85%;
   height:500px;
   margin:auto;
}

A: To completely centre align the div, the following formula can be applied

left = (100 - (width of the div))/2

Using Jquery this can be done as below

var left = (100 - 85)/2;
$("#page").css("left",left + "%")


text:
Q: compare two files line by line in python I want to compare two different files in python. They contain lines with probabilities, and each line has an in id in the end of the file. I need to calculate ratio of each id.  The problem is that each line might contain different number of probabilities and eventually, each text a different number of lines.  I succeeded in doing a script that compares just two files with one line, but I do not know how to do it for each line in the text. Here is my script so far:
#!/usr/bin/python
import math
import operator
f = open('output.txt','w')
file1= open("test.ppx1","r")
file2= open("test.prob1","r")
words = list(file1.read().split())
words2 = list(file2.read().split())
id1=words[-1]
id2=words2[-1]
words.remove(id1)
words2.remove(id2)
words[:]=[x[:12] for x in words]
words2[:]=[x[:12] for x in words2]
words=map(float,words)
words2=map(float,words2)
words=[math.log(y,10) for y in words]
words2=[math.log(y,10) for y in words2]
words=sum(words)
words2=sum(words2)
ratio= words-words2
print >>f, id1,words, words2,ratio

A: You might want to zip the read contents of both files and iterate over them. Note that when you use zip, for file of varying line lengths, all files get to have the length of the shortest smallest file length. See Documentation of zip builtin function
import math

file_list = []

with open("test.ppx1", "r") as file1:
    file_list.append(file1.readlines())

with open("test.prob1", "r") as file2:
    file_list.append(file2.readlines())

with open('output.txt', 'w') as file_out:
    for file1_str, file2_str in zip(*file_list):
        file1_list = file1_str.split()
        file2_list = file2_str.split()
        id1, id2 = file1_list.pop(),  file2_list.pop()
        p1 = map(float, file1_list)
        p2 = map(float, file2_list)
        p1 = map(lambda y: math.log(y, 10), p1)
        p2 = map(lambda y: math.log(y, 10), p2)
        s1, s2 = sum(p1), sum(p2)
        ratio = s1 - s2
        file_out.write("{} {} {} {}".format(id1, s1, s2, ratio))


text:
Q: How can I disable the purple splash screen at boot? How can I disable the purple "Ubuntu" splash screen that displays at boot before the login screen has loaded? I'd prefer to just see plain text scroll by.

A: Temporarily disable splash
You can edit the boot entries in the menu from within GRUB to temporarily disable the splash screen.
Try the following: Select the entry, press the key to edit this entry (it should be e), go to the kernel/linux line and remove quiet splash, then press F10 to boot.
Here are two screenshots from a VM to show you how it should look like:

Permanently disable splash
The permanent equivalent was already quoted in Riccardo Murri's answer:

*Remove splash from the kernel command-line. You can do this per-boot, or make it permanent by changing the GRUB_CMDLINE_LINUX_DEFAULT line in /etc/default/grub.

... followed by update-grub as superuser.

A: Quote from /usr/share/doc/plymouth/README.Debian (from package plymouth version 0.8.2-2ubuntu2, which is the one installed on Ubuntu 10.04):

There are two methods to disable the splash screen.  Both have the
same effect.  Your boot will show such messages as are emitted by
the starting services, and will still be able to prompt if needs be.

*

*Remove all of the plymouth-theme-* packages from your system,
including the text ones.  Plymouth will remain installed to
permit boot-time prompts.

*Remove splash from the kernel command-line.  You can do this
per-boot, or make it permanent by changing the
GRUB_CMDLINE_LINUX_DEFAULT line in /etc/default/grub.

The second method also requires running update-grub as superuser, after editing that file.


text:
Q: Almost certainly incorrect proof about $\prod p$ Let p be prime. Assume (1): $\hspace{10mm} (\prod_{p\leq n} p)^{1/n} \sim e.$
Then $$(e^{\ln \prod p})^{\frac{1}{n}} = e^{(\sum \ln p)/n} \sim e \implies \lim_{n=1}^\infty \frac{e^{(\sum \ln p)/n}}{e} = 1. $$
And so
$$ \lim_{n=1}^\infty~ e^{(\frac{\sum \ln p}{n}-1)} = 1$$ or
$$\lim \frac{\sum \ln p}{n } - 1 = 0 \implies \lim (\frac{\vartheta(n)}{n}- 1) = 0$$
But this implies that $$\lim_{n = 1}^\infty~ (\vartheta(n) - n) = 0 $$
which is false.
I have good reason to think (1) is true so perhaps someone can point to the error, which I will chalk up to hurricane-fatigue.
Thanks!

A: If $f(n) \to 0$ and $g(n) \to \infty,$ then a priori you can't say anything about
the product $f(n)g(n)$.  In your case, $f(n) = (\vartheta(n)/n) - 1$ and $g(n) = n$.

A: If $\prod\nolimits_{p \leqslant n} p $ is supposed to be the primorial ${p_n}\# $ then (1) is incorrect because primorial grows like ${e^{(1 + o(1))x\ln (x)}}$ i.e. ${p_n}\#  \sim {e^{(1 + o(1))n\ln (n)}}$, so raising it to $1/n$ gives ${n^{1 + o(1)}} \ne e$.
Edit: Regarding your second question i.e. proof of (1), note that
$$\ln \prod\limits_{p \leqslant x} p  = \sum\limits_{p \leqslant x} {\ln (p)}$$
but
$$\sum\limits_{p \leqslant x} {\ln (p)}  = \vartheta (x) \sim x$$
hence
$$\prod\limits_{p \leqslant x} p  \sim {e^x}$$
and the geometric mean is
$${\left( {\prod\limits_{p \leqslant x} p } \right)^{1/x}} \sim e$$


text:
Q: How to prevent conversion to APFS on High Sierra install The current understanding seems to indicate that "all SSD" machines will have at least their main/root file system converted to APFS on the install of High Sierra.
That means HFS+ is still a viable boot file system (as it was during testing the beta on an external rotational drive). I want to keep HFS+ for now.
How do I force a full default install, including Recovery HD, onto an "all SSD" MacBook Pro that keeps HFS+ as the only file system?

A: Read here how to do it with ....startosinstall....
https://derflounder.wordpress.com/2017/09/26/using-the-macos-high-sierra-os-installers-startosinstall-tool-to-avoid-apfs-conversion/
an easy solution, from a very experienced source.

A: One method to prevent an automatic conversion when installing High Sierra is to redirect the install onto an external drive first. (Or a traditional HDD on larger desktop machines and laptops that were modified to have these drives in addition to SSDs.)
From the external drive this installation can then be cloned back to the main internal boot drive (preferably after the boot drive is erased). Once the clone is back on an SSD the filesystem will stay at HFSplus.
If the goal of the whole procedure is a "clean install" anyway then this is less of a detour as it may seem. It might be actually faster in this way, if the options involve a slow USB-stick you have to prepare for this with createinstallmedia and then install from there vs. first installing onto a very fast external drive. [That same possible advantage may be desired when someone wants multiple machines to upgrade to High Sierra. See update2 below]
No external drives will currently be converted to APFS when installing macOS 10.13.
No-one really knows for how long this principle will hold true but currently this is the case for both kinds of drives: rotational magnetic and solid state drives.
Since this is met with so much opinion, others suggest:

Safest way to upgrade to macOS High Sierra without APFS
The way that I strongly suggest doing this is the safest and easiest. Safest because if something goes awry, the upgrade can be dropped without changing what you already have:

*

*Clone the boot drive to any spare external drive.

*Boot off the spare/clone.

*Upgrade the spare/clone. The updater will leave the file system alone—it won't be converted to APFS.

*Boot off the now updated spare/clone. Check things out and verify that things are working to your satisfaction—and don't rush this. Make sure everything is acting right and that everything you normally do is OK as well.

*Satisfied? Clone the now updated external to the original boot drive.

*Boot from the original boot drive (now updated).

  By doing it this way, there is no change to the existing boot drive until you explicitly choose to clone back over it with the updated system.

Please note that a "clean install" is different from the in-place upgrade now often preferred by users: a clean install means that previous programs, settings and data should be erased (via formatting) before the new installation is cloned back and therefore have to be restored afterwards either manually or with Migration Assistant.
While a clone of a fresh install may be performed similar like an upgrade – just on top of whatever is on your boot drive – this method is not advisable.  Formatting the internal boot drive before cloning back the new and fresh install ensures that the internal drive is in just the same "really fresh install" condition that is the primary goal of performing a "clean install".

Update2: Upgrading multiple machines in this way is not recommended by Apple anymore, since firmware updates are now rolled into the installer. Unless we figure out how the firmware updates are to be applied manually. Although this issue seems to be more pressing with APFS installations than with HFS+ as outlined in the question. In case you do need  those firmware updates, you might check out Applying Mac firmware updates manually as well.
The clone route outlined above is currently only recommendable for upgrading a single machine (where a firmware upgrade will take place) or re-installing the operating system on machines that had the firmware updates coming with and in High Sierra already applied.

The clone route outlined above is currently the best option to install High Sierra onto a MacBook that should keep HFSplus as a filesystem –– under the condition that it has an empty and unformatted replacement drive as its only internal disk. The latest High Sierra installer does not work with the combination of options --converttoapfs and --volume. An attempt to redirect the install and keeping the older filesystem will result in the error "crashed HelperTool".

A: It should work by exiting any High Sierra installer GUI and starting the install from the command line:
/Applications/Install\ macOS\ High\ Sierra.app/Contents/Resources/startosinstall --converttoapfs NO

Further install options can be obtained by using the --usage argument:

Arguments
  --applicationpath, a path to copy of the OS installer application to start the install with.
  --license, prints the user license agreement only.
  --agreetolicense, agree to license the license you printed with --license.
  --rebootdelay, how long to delay the reboot at the end of preparing. This delay is in seconds and has a maximum of 300 (5 minutes).
  --pidtosignal, Specify a PID to which to send SIGUSR1 upon completion of the prepare phase. To bypass "rebootdelay" send SIGUSR1 back to startosinstall.
  --converttoapfs, specify either YES or NO on if you wish to convert to APFS.
  --installpackage, the path of a package to install after the OS installation is complete; this option can be specified multiple times.
  --usage, prints this message.
  --volume, path to the target volume.

Sources report that the command (in the Beta version) doesn't do anything on the first execution  but on the second.


text:
Q: Android two way binding with Integer type(Livedata) I'm having some issue that two way binding with an Integer data type.
ViewModel
var saleType: MutableLiveData<Int> = MutableLiveData(1)
var saleDetail: MutableLiveData<Int> = MutableLiveData(0)
var salePrice: MutableLiveData<Int> = MutableLiveData(0)
var saleRate: MutableLiveData<Int> = MutableLiveData(0)
var printAmount: MutableLiveData<Int> = MutableLiveData(1)

layout.xml
<data>
    <import type="com.package.utils.DataBindingConverters" />
    <variable
        name="viewModel"
        type="com.package.ViewModel" />
</data>
<com.google.android.material.textfield.TextInputEditText
   android:id="@+id/sale_detail_input"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginEnd="10dp"
   android:gravity="right"
   android:selectAllOnFocus="true"
   android:inputType="number"
   android:imeOptions="actionDone"
   android:singleLine="true"
   android:maxLines="1"
   app:inputContent="@={DataBindingConverters.convertIntegerToString(viewModel.saleDetail)}"
                        />

DataBindingConverters
class DataBindingConverters {

    companion object {
        @InverseMethod("convertStringToInteger")
        @JvmStatic
        fun convertStringToInteger(value: String): Int? {
            if (TextUtils.isEmpty(value) || !TextUtils.isDigitsOnly(value)) {
                return null
            }
            return value.toIntOrNull()
        }
        @InverseMethod("convertIntegerToString")
        @JvmStatic
        fun convertIntegerToString(value: Int?): String {
            return value?.toString() ?: ""
        }
    }

}

It occurs error like this
cannot find method convertIntegerToString(java.lang.String) in class com.package.utils.DataBindingConverters

I thought it would be good to process the value for IntegerToString in two-way binding, but I get an error that can't find a method.
In two-way binding, is there any other way to handle Integer?

A: I don't know what app:inputContent does, but using android:text on the TextInputEditText should be enough:
<com.google.android.material.textfield.TextInputEditText
    ...
    android:text="@={ viewModel.salePriceString }"/>

Now you wonder what is salePriceString. It should be your 2-way binding liveData, and because android:text requires String, salePriceString typing would be LiveData<String>. Modify your viewModel to:
val salePriceString = MutableLiveData<String?>(0.toString())

Now every time you edit the text (by user input) in the TextInputEditText, your salePricesString will get updated with the new text. And anytime you update your salePriceString through code, the text of your TextInputEditText will update accordingly. For the latter case, if you want to update your salePriceString with a value of 500 for example, you would do salePriceString.postValue(500.toString()). And if you want to get the Int value from salePriceString in your code, just do salePriceString.value?.toIntOrNull().
The next steps are optional, but if you want a convenient way to get the Int value without using salePriceString.value?.toIntOrNull() every time, modify your viewModel a bit further:
import androidx.lifecycle.Transformations
...

val salePriceString = MutableLiveData<String?>(0.toString())
// add conversion to LiveData<Int>
val salePrice = Transformations.map(salePriceString) { priceString ->
    priceString?.toIntOrNull()
}

salePrice now contains the Int value of salePriceString, and is automatically updated every time salePriceString changes. salePrice is a LiveData, so you can observe it the same way you would observe salePriceString, but instead of salePriceString, you have the Int value ready in salePrice.
A final step is to observe salePrice somewhere in the code, most logically on the fragment that your viewModel is attached to:
viewModel.salePrice.observe(this, {}) // this, or viewLifecycleOwner, depending on your use case

You need to observe it, even if you then do nothing with the value. It is because Transformation.map is a bit strange one, the LiveData created by it won't go "live" unless there exists an observer for it. That means that until salePrice is observed by some observer, you won't get any value from it, i.e. salePrice.value would always be null.


text:
Q: Android keystore data getting cleared I have an app that uses AndroidKeystore, and after certain days while reopening the application the Keystore data getting cleared.
Can anybody confirm is there any lifetime or scope of the Keystore?

A: Goto File/Project Structure/Modules/Signing Congif
Here add your keystore path and other detail required in form. The Store Key Alias and Password will be save in build.gradle(app) file.


text:
Q: A conjecture on closed discrete subset I am struggling with this old problem, which is also posted here:

Let $X$ satisfy countable chain condition(abbreviated as CCC) and $X$ has a regular $G_\delta$-diagonal. Then the cardinality of $X$ is at most $\mathfrak c$.

$X$ has a regular $G_\delta$-diagonal iff there is a collection of open sets of $X^2$, say $\lbrace U_n: n\in N\rbrace$, such that $\Delta=\bigcap\lbrace \overline{U_n}: n \in N\rbrace$, where $\Delta=\lbrace(x,x): x \in X\rbrace$.
Note that the question is answered; however I hope to get new proof.
By certain effort, If $|X|>\mathfrak c$, we can get an uncountable closed discrete subset $S$ of $X$, and for any point $x \in X$, there exists an open set $U_x$ such that $\overline{U_x} \cap S$ has at most one point.
I would like to know whether the following conjecture is right, wrong, or neither:

Let $X$ be a Hausdorff space. If $S \subset X$ is an uncountable closed discrete subset of $X$, and for any point $x \in X$, there exists an open set $U_x$ such that $\overline{U_x} \cap S$ has at most one point. Then could we obtain an uncountale collection of disjoint open sets in $X$?

Thanks for your any help.

A: Assuming you want $U_x$ to be a neighbourhood of $x$, your condition on $S$ is equivalent to $S$ being closed discrete, whenever $X$ is a regular space. That's because $X$ is regular if and only if for every point $x \in X$ and every open neighbourhood $U$ of $x$ there is an open set $V$ such that $x \in V \subset \overline{V} \subset U$. Now, there are plenty of regular ccc spaces with uncountable closed discrete subspaces. For example, let $\kappa$ be any uncountable cardinal and $X=\{x \in 2^\kappa: (\exists \beta < \kappa)(x(\beta)=1 \wedge (\forall \gamma>\beta)(x(\gamma)=0)) \}$ with the topology induced from the usual topology on $2^\kappa$. $X$ has the ccc as a dense subspace of the ccc space $2^\kappa$. For $\alpha < \kappa$ define a point $x_\alpha \in X$ as follows: $x_\alpha(\beta)=1$ for $\beta \leq \alpha$ and $x_\alpha(\beta)=0$, for $\beta > \alpha$. Then $D=\{x_\alpha: \alpha < \kappa \}$ is a closed discrete subspace of $X$ of cardinality $\kappa$. To see that, note that $\{[\sigma] \cap X: \sigma \in Fn(\kappa,2)\}$ is a base for $X$, where $Fn(\kappa,2)$ denotes the set of all finite partial functions from $\kappa$ to $2$ and $[\sigma]:=\{x \in 2^\kappa: \sigma \subset x\}$. We have $[\{(\alpha,1), (\alpha+1,0)\}] \cap D=\{x_\alpha\}$ for every $\alpha < \kappa$ and hence $D$ is discrete. Moreover, $D$ is closed because if $x \in X \setminus D$, then there are ordinals $\alpha, \beta < \kappa$, $\alpha < \beta$ such that $x(\alpha)=0$ and $x(\beta)=1$ and hence $[\{(\alpha,0), (\beta,1)\}]\cap X$ is an open neighbourhood of $x$ which misses $D$.

A: I claim that every discrete space of non-measurable cardinality can be embedded as a closed subspace of some completely regular space satisfying the countable chain condition.
Let $S$ be an uncountable discrete space whose cardinality is below the first measurable cardinal. Since discrete spaces of non-measurable cardinality are realcompact, the space $S$ is embeddable as a closed subspace of some product $\mathbb{R}^{I}$ for some $I$.
However, the space $\mathbb{R}^{I}$ satisfies the countable chain condition. We can give $\mathbb{R}$ a Borel probability measure. If we take the infinite product measure, then we get a measure $\mu$ on $\mathbb{R}^{I}$ such that $\mu(U)>0$ for each non-empty open set $U$. Therefore there can only be countably many disjoint open sets in $\mathbb{R}^{I}$ since $\mu(\mathbb{R}^{I})=1$.


text:
Q: Content is the same in both ul classes I'm having a small issue here:

        <li <?php if ($_GET['dept'] == "home") {echo"class='selected'";} ?>>Home

User Panel

Report Bugs

Staff Forums

        <li <?php if ($_GET['dept'] == "management") {echo "class='selected'";} ?>>Management

User Listing

In the code, the correct floatcontainer is meant to show up in each case for the li above, however, the bottom one, the floatcontainer with the User listing li only shows in both cases.
How do I resolve this?

A: If you don't want the ul showing up unless $_GET['dept'] is some particular value, then put it inside an if() block?


text:
Q: Opengl 2.0 glColor4f not working I'm creating a view using GLKit to experiment with opengl in iOS. The view has the following load method:
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    if (!self.context) {
        NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat24;

    [EAGLContext setCurrentContext:self.context];
    self.effect = [[GLKBaseEffect alloc] init];

}

And in a draw method for a shape I have the following code:
float vertices[] = {
    -1, -1,
    1, -1,
    0,  1};

glEnableVertexAttribArray(GLKVertexAttribPosition);

glColor4f(0.0, 1.0, 0.0, 1.0);
glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glDrawArrays(GL_TRIANGLES, 0, sizeof(vertices));

glDisableVertexAttribArray(GLKVertexAttribPosition);

This code will draw a triangle in the center of the screen, however the triangle is white. I set the current color to green with the line glColor4f(0.0, 1.0, 0.0, 1.0) but this does not change the current drawing color. How can I change the color of the triangle?

A: OpenGL 2.0 uses shaders to rasterize the geometry. You need to tell your shader what color you want to see. The way to do this is usually to set the color attribute of the vertices to what you want, I haven't used GLKit but I see that it has a GLKVertexAttribColor. Try setting it to the color you want with:
GLfloat triangle_colors[] = {
    1.0, 1.0, 0.0, 1.0,
    0.0, 0.0, 1.0, 1.0,
    1.0, 0.0, 0.0, 1.0,
};

glVertexAttribPointer(
    GLKVertexAttribColor, // attribute
    4,                 // number of elements per vertex, here (r,g,b,a
    GL_FLOAT,          // the type of each element
    GL_FALSE,          // take our values as-is
    0,                 // no extra data between each position
    triangle_colors
);

A: glColor4f is not an ES 2.0 call. You must have pulled in an ES 1.0 header file to get that to compile.
The easiest approach if you just want to use a solid color is to define a uniform variable in your shader, and pass in your color as a uniform. Or you can make the color an additional vertex attribute.
If you're using pre-baked shaders provided by GLKit, you should be able to pass in colors using GLKVertexAttribColor, very similar to the way you specify your vertex positions with GLKVertexAttribPosition.


text:
Q: jQuery Datatables filter Column containing dropdowns on text not value. I am using jQuery plugin DataTables for displaying the data from database. Columns have different control type. One of the column say it as COLUMN has select box as control type.
I have also used the filter, pagination features provided by DataTables. Filter on COLUMN filters the datat based on the values in column.
Is there any way to filter data on the text displayed in the box i.e. option's text.
self.dummyDataTable = FIT.component.DataTable.init({
        renderTo: 'dummy-index-table',
        id: 'dvmyInputDataGrid',
        data: data[0],
        deferRender: true,
        perPage: 10,
        paging: true,
        scrollY: "200px",
        sScrollX: "200px",
        height: ($(window).height()) * (0.7),
        scroller: true,
        scrollCollapse: true,
        searchable: true,
        showFilters: true,
        sortable: false,
        aaSorting: [],

        columns: Columns,
        select: {
            style: 'os',
            selector: 'td:first-child'
        },
    });

For ex:
<select>
        <option value="0">--- Select Officer---</option>
        <option value="1">Sam</option>
        <option value="2">Brad</option>
        <option value="3">Nicholas</option>
        <option value="4">John</option>
</select>

when i set filter as true . for this particular select box column it shows list of "Value" attribute in filter box on top of the column like 1,2,3..
A user might get confused between text in the cells and values in the filter box of which user is totally unaware.
Is there any way to filter on the basis of texts i.e Sam, Brad, Nicholas, John.
I have added the code relevant to filtering and searching.

A: If I undertand you. You can create the select option with the value of the text you want to search, like:
...
<select id="select_name">
    <option value="0">--- Select Officer---</option>
    <option value="Sam">Sam</option>
    <option value="Brad">Brad</option>
    <option value="Nicholas">Nicholas</option>
    <option value="John">John</option>
</select>
...

And then add a on change event on select to search in the datatable, like:
$('select#select_name').change(function(){
    self.dummyDataTable.columns( <# column> ).search( this.value ).draw();
});

Where <# column> is the number of the column you want to search.


text:
Q: untracked files , untracked folders inventory I am currently working on and on off on multiple projects. (~30)
Some of them go idle for several months.
No matter how hard I tried to be organized, I always end up with multiple subdirectories , containing git repos at different depth levels.
I would like to double-check all my work directories to make sure that I did not leave uncommitted changes or untracked folders by accident.
Is there a tool to do that ?

*

*scan subdirectories for git repo.

*list untracked files

*list uncommited edits

*list directories with no git repo. ( if they contain files)

A: There is no tool that will do exactly what you want, but you can mix together some command line utilities to get what you want.
Find All Subdirectories that have .git directory.
find . -name `.git` | xargs dirname

Run git status on each one:
for d in `find . -name .git | xargs dirname `; do pushd $d; git status; popd; done;


text:
Q: When Installing gitolite I get "/tmp/id_rsa.pub does not seem to be a valid ssh pubkey file" I'm trying to install git and gitolite for our development in a CentOS linux server. Everything so far has ran ok except the step where I define the admin user for gitolite with this command:
gitolite setup -pk /tmp/id_rsa.pub
FATAL: errors found but logfile could not be created
FATAL: /home/git/.gitolite/logs/gitolite-2013-05.log: No such file or directory
FATAL: die      '/tmp/id_rsa.pub' does not seem to be a valid ssh pubkey file

It looks like two errors; in /home/git/ there's only these files
.gitolite.rc
.bashrc
.bash_profile
.bash_logout

And second (which seems to be the issue), is that the pub_key is not valid. However, according to the git book the file looks alike. I generated it like this:

*

*Installing git in my pc (not the server)

*From the git bash:

ssh-keygen.exe
(default path)
(no password)
(no password)

I copied the generated .pub file to the tmp directory on the server via a program named WinSCP.
What I'm I doing wrong? I don't find the answer in google.
PS. If you need more information, please let me know.

A: I also ran into this issue and took a look into the sources of gitolite. The code is basically executing
ssh-keygen -l -f yourFile.pub

to verify wheter the file is a valid ssh-public key... On my machine (OpenWRT router) ssh-keygen wasn't installed. Installing it with:
opkg update
opkg install openssh-keygen

fixed the problem for me.

A: Make sure the /tmp/id_rsa.pub is exactly like the one you have on your PC, in one line, without any ^M at the end of the line (\n only, not \r\n).
And reading the gitolite setup help page, you should name your public key (on the /tmp of the server) with admin's username.

The first time you run it, you need to have a public key file (usually from the admin's workstation) ready.
  If the main gitolite admin's username is "alice", this file should be named "alice.pub". Then, as the hosting user, run:

gitolite setup -pk alice.pub


text:
Q: NAT MASQUERADE response packets not coming back into private network I setup NAT for my Xen VM inside a real host, so the VM essentially forms its private network with the virtual NIC inside the host.
so the network is like this:
[ (VM 10.0.0.3) ---- bridge 10.0.0.1  ---- real NIC 192.168.0.105] ------- internet
now I set  up NAT by the steps in http://blog.manula.org/2012/04/manually-configuring-nat-networking-in.html
from inside VM, I ran "ping a_real_internet_IP "  , the issue is that the ping does not produce responses. I ran "tcpdump" on the traffic going out on the NIC, and see packets masquerading as  src=192.168.0.105,dst=a_real_internet_IP. so this shows that the MASQUERADE is working. I also see the response packets with reversed src and dst.
but the issue is that on the bridge, I only see packets src=10.0.0.3,dst=a_real_internet_IP, and not the returning packets .  since the response packets are seen on the NIC, but not on this virtual bridge, where are they dropped?
I tried to put in some TRACE, but TRACE only works on raw table, not the nat table.
weirdly the same setup works fine on my desktop server, but not on my laptop. the former runs ubuntu 20, while the latter ubuntu 18, not sure if this mattered at all. but NAT is a very basic network setup, both systems should have respected it.

A: resolved, docker messed up the iptables. even though I did "iptables -F && iptables -X " for all rules, it's still the same, I had to remove docker and reboot


text:
Q: Python,ML error: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() I am trying to categorized "DistAreaID" column of my dataset [cf_all] by grouping to its mean wrt Y.
Code:
round(cf_all.groupby("DistArea_ID")["Counterfeit_Sales"].mean(), 2)

for col in range(len(cf_all)):
    if cf_all["DistArea_ID"][col] in \
        ["Area013", "Area017", "Area018", "Area035", "Area045", "Area046", "Area049"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_2000"
    if cf_all["DistArea_ID"][col] in ["Area010", "Area019"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_400"
    if cf_all["DistArea_ID"][col] in ["Area027"]:
        cf_all.loc[col, "DistArea_ID"] = "DistArea_3000"

Error:
The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().

Can someone please guide me with this error?

A: I suggest use Series.replace or Series.map with Series.fillna:
d = {"DistArea_2000": ["Area013", "Area017", "Area018",
                       "Area035", "Area045", "Area046", "Area049"],
     "DistArea_400": ["Area010", "Area019"],
     "DistArea_3000":["Area027"]}

#swap key values in dict
#http://stackoverflow.com/a/31674731/2901002
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

cf_all["DistArea_ID"] = cf_all["DistArea_ID"].replace(d1)

#obviously faster
#cf_all["DistArea_ID"] = cf_all["DistArea_ID"].map(d1).fillna(cf_all["DistArea_ID"])


text:
Q: How to upload and read a file? I am trying to upload a file using HTML tags and read it through python. Here is the code snippet on what I am trying to do.
def upload_file(self):
    cgitb.enable()
    log.debug("file has yet to be uploaded")
    form = cgi.FieldStorage()
    fileitem = form['CSV'].value
    log.debug(fileitem)
    if fileitem:
        fn = os.path.basename(fileitem)
        with open(fn, 'r') as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                log.debug(row)
        log.debug("file uploaded")
    else:
        log.debug("No file was uploaded")

I get the following error:
  File "/base/data/home/apps/s~voicecurvetestcalls/trial.378220245396013618/handler/kellyhandler.py", line 43, in upload_file
    with open(fn, 'r') as csvfile:
IOError: [Errno 2] No such file or directory: 'Calllog.csv'

What am I missing?

A: The <form> element in your HTML does not have the proper enctype= attribute.
Here is an example of uploading a CSV file. Note the enctype="multipart/form-data":
#!/usr/bin/python2.7

import csv
import cgi
import cgitb
cgitb.enable()

print "Content-Type: text/html"
print ""
print "
Hello!
"

form = cgi.FieldStorage()

if 'CSV' in form and form['CSV'].file:
    print '
%s :
'%form['CSV'].filename
    print "
"
    reader = csv.reader(form['CSV'].file)
    for row in reader:
        print "
"
        for item in row:
            print "%s	"%item
        print "
"
    print "
"

print '''
<form method="POST"  enctype="multipart/form-data">
    <input type="file" name="CSV" />
    <input type="submit"/>
</form>'''

Reference:

*

*https://docs.python.org/2/library/cgi.html#using-the-cgi-module

*http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2

*https://www.rfc-editor.org/rfc/rfc1867


text:
Q: Prove $\int_{0}^{\frac{\pi}{2}}f(\cos(x))dx = \int_{0}^{\frac{\pi}{2}}f(\sin(x))dx$ with hint Assume $f$ is continuous, prove $\int_{0}^{\frac{\pi}{2}}f(\cos(x))dx = \int_{0}^{\frac{\pi}{2}}f(\sin(x))dx$...
I was given a hint, $\sin x=\cos(\frac{\pi}{2}-x)$. I used this property to get $\int_{0}^{\frac{\pi}{2}}f(\sin x)dx=\int_{0}^{\frac{\pi}{2}}f(\cos(\frac{\pi}{2}-x))dx$ and $\int_{0}^{\frac{\pi}{2}}f(\cos \frac{\pi}{2})dx+\int_{0}^{\frac{\pi}{2}}f(\cos(x))dx$. I am a few steps away, and I know $\cos(\frac{\pi}{2})=0$, but I only have $f(0)$, which is not $0$. If I can make it $0$, then I'm done. What is the additional step needed here?

A: Well, use the King's Rule of Integration:
$$\int_a^bg(x)\,\text{d}x=\int_a^bg(a+b-x)\,\text{d}x$$

 For proof, substitute $u=a+b-x$ so that $\text{d}u=-\text{d}x$. The limits become $b$ to $a$. So, our integral is
 $$\int_b^a-g(a+b-x)\,\text{d}x=\int_a^bg(a+b-x)\,\text{d}x$$

Here,
$$\int_{0}^{\pi/2}f(\cos x)\,\text{d}x$$$$=\int_{0}^{\pi/2}f\left(0+\frac{\pi}{2}-\cos x\right)\,\text{d}x$$
$$=\int_{0}^{\pi/2}f(\sin x)\,\text{d}x$$

Alternatively, just substitute $u=\dfrac{\pi}{2}-x$ so that $\text du=-\text dx$, and $0\rightarrow\frac{\pi}{2}$ and $\frac{\pi}{2}\rightarrow0$. So, the integral becomes
$$\int_{\frac{\pi}{2}}^0-f\Bigg(\cos\left(\frac{\pi}{2}-u\right)\Bigg)\,\text du$$
$$=\int_0^{\frac{\pi}{2}}f(\sin u)\,\text du$$
$$=\int_0^{\frac{\pi}{2}}f(\sin x)\,\text dx$$
Hope this helps. Ask anything if not clear :)

A: Hint: Use King's property
Proof. If $x=a+b−y$ then
$$
\int_{x=a}^{x=b}f(x)dx=\int_{y=b}^{y=a}f(a+b-y)d(a+b-y)=\\
=\int_{y=b}^{y=a}f(a+b-y)(-dy)=\\
=-\int_{y=b}^{y=a}f(a+b-y)dy=\\
=\int_{y=a}^{y=b}f(a+b-y)dy
$$
Now again you can change the dummy variable and the property is proven to be true.


text:
Q: Video as sreensaver with xscreensaver and websreensaver I wanted to use video as my screen saver.
I followed the steps from here.
I did all as mentioned but xscreensaver is showing black(blank) output. What should I do?
image

A: Make a backup from your $HOME/.xscreensaver
I only tested it with mpv videoplayer.
Add
"Movies"  mpv --really-quiet --no-audio --fs            \
                                  --loop=inf --no-stop-screensaver            \
                                  --shuffle --wid=$XSCREENSAVER_WINDOW        \

                                 $HOME/path/to your/video      \n\

Start
xscreensaver-demo

And choose
Forgot source


text:
Q: html input field value setter not working properly in chrome and safari using jquery I am trying to set html input field value on keyup event using jquery.
<input style="width: 45%;" type="text" name="user_phone" value="" placeholder="Your phone number" />

First I tried using .val() setter like this.
http://jsfiddle.net/6xwzy81k/3/
$(document).ready(function(){
  $('input[name=user_phone]').keyup(function() {
    var number = $('input[name=user_phone]').val();
    if (!number.contains('(') && !number.contains(')') && number.length === 2) {
        $('input[name=user_phone]').val('(' + number + ')');
    } else if (number.contains('(') && !number.contains(')') && number.length === 3) {
        $(this).val(number + ')');
    } else if (!number.contains('(') && number.contains(')') && number.length === 3) {
        $(this).val('(' + number);
    }
  });
});

This worked fine in firefox but in chrome and safari it didn't work. Then as suggested in some other questions I tried it this way using .prop() instead of .val()
http://jsfiddle.net/6xwzy81k/2/
$(document).ready(function(){
  $('input[name=user_phone]').keyup(function() {
    var number = $('input[name=user_phone]').val();
    if (!number.contains('(') && !number.contains(')') && number.length === 2) {
        $('input[name=user_phone]').prop('value','(' + number + ')');
    } else if (number.contains('(') && !number.contains(')') && number.length === 3) {
        $(this).prop('value', number + ')');
    } else if (!number.contains('(') && number.contains(')') && number.length === 3) {
        $(this).prop('value', '(' + number);
    }
  });
});

The same thing happened, it worked as expected in firefox but not in safari or chrome.

A: since the error in your code was pointed out by the other answer here is an alternate solution. if you want to format the number in the form (###) ###-#### here is a solution that uses regex to first stip non-digits, then depending on the length of the actual digits, format them. tested in chrome and safari. also handles deletes/backspace
also used your fiddle

$(document).ready(function(){

    $('input[name=user_phone]').keyup(function() {
        var number = $('input[name=user_phone]').val();
        var digits = number.replace(/[^0-9\.]+/g, '');
        var lastDigitIndex = (digits.length < 10) ? digits.length : 10;

        var key = event.keyCode || event.charCode;

        if (key != 8 && key != 46) {
            if (digits.length >= 3) {

                var output = '(' + digits.substring(0, 3) + ') ';

                if (digits.length >= 6) {
                    output += digits.substring(3, 6)
                        + '-' + digits.substring(6, lastDigitIndex);
                }
                else {
                    output += digits.substring(3, lastDigitIndex);
                }

                $(this).val(output);
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input style="width: 45%;" type="text" name="user_phone" value="" placeholder="Your phone number" />

A: It was giving number.contains is not a function in console. So I suggest you to use $.contains as below which works well and good!!
DEMO HERE
$(document).ready(function(){
    $('input[name=user_phone]').keyup(function() {
        var number = $('input[name=user_phone]').val();
        if (!$.contains(number,'(') && !$.contains(number,')') && number.length === 2) {
            $('input[name=user_phone]').val('(' + number + ')');
        } else if ($.contains(number,'(') && !$.contains(number,')') && number.length === 3) {
            $(this).val(number + ')');
        } else if (!$.contains(number,'(') && $.contains(number,')') && number.length === 3) {
            $(this).val('(' + number);
        }
    });
});


text:
Q: Scheduling AWS RDS snapshot migrations I am trying to set up a process in which a postgres staging database is populated with production data.
I have some working implementation with pg_dump and pg_restore but I was wondering if something in RDS itself is possible.
We have nightly snapshots on our production database. My goal would be RDS takes the latest database snapshot, migrates it to an existing database and does this on some scheduled cadence (1/week or something like that).
Is this possible to configure in the console? If not are there some some combination of lambda/cloud formation that can do this?

A:
My goal would be RDS takes the latest database snapshot, migrates it to an existing database

RDS never loads a snapshot into an existing database. It always creates an entirely new database server/cluster from a snapshot.

Is this possible to configure in the console? If not are there some some combination of lambda/cloud formation that can do this?

You would have to write some code that creates a new staging database server from the production snapshot, and deletes your current server.
If you are using CloudFormation, then it could manage this for you if you specify the DBSnapshotIdentifier parameter. You would have to modify that parameter each week, and then update your CloudFormation stack.


text:
Q: How reliable are .net timers? I'm looking at using a System.Timers.Timer in a windows service. I would like to know how reliable and accurate they are. In particular:

*

*Are there any guarantees about how often they will run?

*What happens when the processor or memory are overloaded? Will the ElapsedEventArgs.SignalTime always be accurate under such circumstances?

*If a timer is run for a long time, what happens when corrections are made to the system time to take into account inaccuracies in the system clock?

Update: Thanks for the answers so far. I was hoping to get more specific answers to the three issues that I detailed in my original question.

A: What is accurate for you?
Normal windows timer has accurancy of about 100Hz. If you want something more accurate, take a look at QueryPerformanceTimer (System.Diagnostics.Stopwatch uses it). It is great and very accurate for short time spans, but as CPU frequency changes (power management), it will get out of sync.
Also, I have seen system clock drift for minutes a day, so we had to install NTP utility and schedule it (the irony) to run periodically .
Basically, we never acheived submillisecond time accurancy on windows machine, even with some tries to use main clock as baseline and QuerperformanceTimer as sort of differential timer. Never worked right.

A: From my experience I can tell timers may get out of sync if you have a very high performance load.

A: If you need a very high performance clock in .NET, you should check out System.Diagnostics.Stopwatch. It uses the kernel timer in windows to measure time very precisely. Its generally intended for diagnostic purposes, such as measuring the elapsed execution time for a given piece of code...but it could probably be wrapped in a custom high performance Timer class for scheduled events if need be.

A: I use a sleeping(Thread.Sleep(int)) value while in a loop for my windows service tasks. This way you can implement calculations for how much you want to sleep if it's not interval based but specific time based. Never had a problem with this approach.


text:
Q: JOIN MAX per Group I have a pretty simple sql:
SELECT TRIM(Branch.Area)                             "Area",
       Branch.Article                                "Article"
FROM   DBA.Branch Branch
       LEFT JOIN DBA.Attribute Attribute
              ON Branch.Article = Attribute.Article
       LEFT JOIN DBA.Attribute2 Attribute2
              ON Branch.Article = Attribute2.Article
       LEFT JOIN DBA.ItemMaster ItemMaster
              ON Branch.Article = ItemMaster.Article

WHERE  Branch.Type = 'M'
       AND Branch.Area LIKE '%US%'

As you can see this query provides a table out of the intersection based on 4 tables.
The selected columns are much more than 2. But these are not necessary here.
Now I would like the cost information per Article out of a 5th table.
This table has this structure:

*

*Article

*Department

*Type

*Cost

For each code there a differents costs for per department. That means every article is listed several times. Once per Department. Now I am looking for the MAX cost for each Article.
This value I would like to add to the query above.
But how?
There are also two filters for the Cost table:

*

*Cost.Type = 'M'

*Cost.Area LIKE '%US%'

A: A solution is
SELECT TRIM(Branch.Area)                             "Area",
       Branch.Article                                "Article",
       C.maxcost
FROM   DBA.Branch Branch
       LEFT JOIN DBA.Attribute Attribute
              ON Branch.Article = Attribute.Article
       LEFT JOIN DBA.Attribute2 Attribute2
              ON Branch.Article = Attribute2.Article
       LEFT JOIN DBA.ItemMaster ItemMaster
              ON Branch.Article = ItemMaster.Article
       LEFT JOIN (SELECT Article, MAX(Cost) AS maxcost FROM DBA.ItemMaster.Cost GROUP BY Article) C
              ON C.Article=Branch.Article

WHERE  Branch.Type = 'M'
       AND Branch.Area LIKE '%US%'

I don't really get this

There are also two filters for the Cost table:
Cost.Type = 'M'
Cost.Area LIKE '%US%'

It looks like exactly the same filters as on the branch table. If you have the same article information stored on the 2 tables, then its not necessary to filter the Cost records. If not, you can do this in the additional jointure:
       LEFT JOIN (SELECT Article, MAX(Cost) AS maxcost FROM DBA.ItemMaster.Cost WHERE Type='M' AND Area LIKE '%US%' GROUP BY Article) C
              ON C.Article=Branch.Article


text:
Q: Why MSDN examples only wrap SqlConnection in using block (call dispose method)? Usually I use the pattern described in this question:

SqlConnection SqlCommand SqlDataReader IDisposable

That looks like this:
using (var conn = new SqlConnection(lewtanConnStr))
using (var cmd = new SqlCommand(sql, conn))
{
    try
    {
        await conn.OpenAsync();
        using(reader = await cmd.ExecuteReaderAsync())

However, on the MSDN/Microsoft website usually only SqlConnection is wrapped in a using block. Is it good enough to just dispose SqlConnection? (Sometimes even SqlConnection just calls close() without wrapping it in using).
The code examples on this article are one instance:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx


text:
Q: What is $\mathbb{F}_5 [x] / \langle x^2 + 2\rangle$ Apologize if this is a trivial question. Here is the original question:

Let $\mathbb{F}_5$ be the finite field of order 5, and $\mathbb{F}_5 [x]$ the polynomial ring in one
  variable over $\mathbb{F}_5$. Let $I$ be the ideal of $\mathbb{F}_5 [x]$ generated by the polynomial $x^4 + 2x^2$. Determine the number of invertible elements of the quotient ring $\mathbb{F}_5 [x]/I$.

Notice that
\begin{equation}
x^4 + 2x^2 = x^2 (x^2 + 2)
\end{equation}
Since $\gcd(x^2 , x^2 + 2) = 1$, $\langle x^2 \rangle \langle x^2 + 2\rangle = \mathbb{F}_5$. Thus, by Chinese Remainder Theorem, we have
\begin{equation}
\mathbb{F}_5 [x] / \langle x^4 + 2x^2 \rangle \cong \mathbb{F}_5 [x] / \langle x^2\rangle \times \mathbb{F}_5 [x] / \langle x^2 + 2\rangle
\end{equation}
Then I got stucked. I am confident that since $x^2 + 2$ is irreducible, $\mathbb{F}_5 [x] / \langle x^2 + 2\rangle$ is just $\mathbb{F}_{25}$ (if I got my finite field thing right). But, thinking about possible remainders, then isn't $\mathbb{F}_5 [x] / \langle x^2 + 2\rangle$ just $\mathbb{F}_5^2$? But this is impossible since one is cyclic and the other one is not?

A: The field $\mathbb{F}_{25}$ is not cyclic as an additive group, and indeed is additively isomorphic to $\mathbb{F}_5^2$.  Other than that, what you've said is correct.


text:
Q: Error 500 on dialog/oauth API after today's push at 8:21 Our apps are getting error 500 on this call :
https://www.facebook.com/dialog/oauth?client_id=89dc1edc0036d868930ccbac657e8b7f&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Frealmofempires%2F&scope=email
Does anyone know of any issues?
There is a work around, just replace the "www.facebook.com" with "m.facebook.com"

A: Facebook seems to have dropped support for the old API KEYs. If you look at your App Settings page, you'll see App Id/Api Key. These were merged back in 2011, so just replace your api_key with your app_id for the client_id parameter.
This should have been a breaking change.

A: I can reproduce your problem by removing all cookies at facebook.com and then visit your posted link.
If you visit http://www.facebook.com once, then your URL will work. If found it now needs a cookie at facebook.com to work (named datr at facebook.com). There must be a change/problem at facebook.
It also works if you visit the corresponding login.php directly.

A: Depending on what oauth tool you're using, it's possible to get an error 500 if the API key and/or secret are missing


text:
Q: What is the word for someone who is willing to do anything for a fee My character Laila is a sort of allrounder, jack of all trades and will do anything, from being your lawyer or temporary girlfriend to going undercover in the government, assassinating someone or even dropping a bomb in New York and she does not care even if the person hiring her is the mafia boss or the American government or even just a roadside beggar as long as she gets her pay. What should I call her?
Example sentence:

Laila makes her living as a ______.

A: You can try mercenary
Defined by Oxford DictionarIes as:

Primarily concerned with making money at the expense of ethics.

Your Laila is a mercenary of the highest order.


text:
Q: Jquery attr function not working in IE 9 Find the code below.  I would like to make work the same functionality in the IE.  I am struggling to make it work on IE 9.
<html>
    <head>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script type="text/javascript">
        var colors= ["#99b433", "#00a300", "#1e7145"];
        $(document).ready(function(){
            addBarColor();
        });

        var addBarColor = function(){
            $('#lineColors').html("");
            for(var color=0; color<colors.length; color++){
                //Loading List of colors
                var chartBarColor = colors[color];
                var li = document.createElement('li');
                li.style.width = "50px";
                li.style.backgroundColor = chartBarColor;

                //Adding Remove button to it.
                var remove = document.createElement('span');
                remove.id = "remove"+color;
                remove.style.cursor="pointer";
                remove.style.marginLeft = "40px";

                //remove.onclick = function(){removeBarColor(color)};

                //Adding x image
                var removeImg = document.createElement('img');
                removeImg.src = "https://cdn1.iconfinder.com/data/icons/diagona/icon/10/101.png";

                //Appedning everything to UL
                remove.appendChild(removeImg);
                li.appendChild(remove);
                $('#lineColors').append(li);

                $("#remove"+color).attr('onclick', 'removeBarColor(\''+color+'\')');
            }
        }

        //Removing the color from the array
        var removeBarColor = function (index){
            alert(index);
            colors.splice(index, 1);
            console.log(colors);
            addBarColor();
        };
    </script>
    </head>
    <body>
        <ul id="lineColors">
        </ul>
    </body>
</html>

Jquery's attr() function doesn't seems to be working in IE 9.  Alternatively I tried this remove.onclick = function(){removeBarColor(color)};  this also doesn't seems to be working in IE9.
Hope my problem is clear.  Thanks for help in anticipation.

A: I assume you're talking about this attr line:
$("#remove"+color).attr('onclick', 'removeBarColor(\''+color+'\')');

Whether it works elsewhere or not, don't hook up event handlers like that if you're using jQuery (or even, frankly, if you're not); hook up handlers using modern techniques, esp. as it's really easy with the lib you're already using:
$("#remove"+color).on('click', removeBarColor.bind(null, color));

That relies on ES5's Function#bind (which can be shimmed); alternately, you can use jQuery's proxy:
$("#remove"+color).on('click', $.proxy(removeBarColor, null, color));

Live Example
Either way, what that code does is create a new function that, when called, will call removeBarColor passing in color as the index argument (and setting this to nothing in particular; well, okay, in loose mode it'll be window, in strict mode it'll be null). Then it assigns that function as a click handler.
Another approach is to save the color on the element, and then have removeBarColor work by looking at the element that was clicked, but the above is the minimal-mods approach.


text:
Q: Select all images in the folder and save them in other folder I have a folder on my local machine that contains .jpeg files. I want to select all of these images and save them in the other folder. That is all. I am using c# and ASP.NET Webforms. Is there an easy way of doing so?
Thank you.

A: Something like this should do the trick:
var filesToCopy = Directory.EnumerateFiles(@"c:\path to images", "*.jpeg");

var directoryToCopyTo = "c:\destination folder";

foreach (var file in filesToCopy)
{
    File.Copy(file, Path.Combine(directoryToCopyTo, Path.GetFileName(file)));
}

Note: This won't copy images in sub-folders


text:
Q: How to make Outlook 2010 not warn on empty subject? I'm using the beta of Outlook 2010, and am wondering how I can set it to STOP warning me on empty subject lines. My family and friends (as opposed to work) I generally send with no subject, and it is REALLY annoying that it constantly asks me

"Really send with no subject?"

How can I turn this off?

A: http://community.spiceworks.com/scripts/show/512-disable-outlook-2010-no-subject-prompt

A: It requires Exchange 2010 and Outlook 2010 to use MailTips which also has to be configured/Turned On in order to use. I tried to use a VBA script and that hasnt worked either.

A: Go into File tab, click Options, then in Mail tab of Outlook Options box, under MailTips, click MailTips Options and then click "Never Display MailTips".


text:
Q: Placing leaflet controls outside map My requirement is to create N type of markers in leaflet. The list is huge that can not be fit in map area.
I want something similar to this :
http://blog.georepublic.info/2012/leaflet-example-with-wfs-t/
There is some problem in the above given example that while zooming in the marker moves from their original position.  Please suggest any fix for this or any other alternative to place the controls outside the map like this example.

A: Is it OK to put your controls in sidebar?
https://github.com/Turbo87/sidebar-v2

A: Simple possible way i have used:
Add below html tag, where you want move the leaflet controls:

JavaScript code:
$(document).ready(function () {

var newParent = document.getElementById('custom-map-controls');
        var oldParent = document.getElementsByClassName("leaflet-top leaflet-right")

        while (oldParent[0].childNodes.length > 0) {
            newParent.appendChild(oldParent[0].childNodes[0]);
        }
 });


text:
Q: Device Compatibility of my app I created an Android application, but I cannot view it on play store and when I access it from web play store I found that:

Cette application n'est pas compatible avec votre appareil.

I don't know the reason of that
here is my build file
apply plugin: 'com.android.application'

android {
    compileSdkVersion 17
    buildToolsVersion '21.0.0'

    compileOptions.encoding "ISO-8859-1"

    defaultConfig {
        applicationId "com.commande.soqop"
        minSdkVersion 15
        targetSdkVersion 18
        versionCode 3
        versionName "1.2"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    aaptOptions{
        cruncherEnabled = false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

I have tested on Samsung Tab 4 (Android 5.0)  and Samsung S5 (Android 6)
How can I fix this issue?

A: Increase the targetSdkVersion of your app. The devices on which you tested might be above the version you mentioned in build.gradle.
Replace target SDK with the latest one :
apply plugin: 'com.android.application'

android {
    compileSdkVersion 17
    buildToolsVersion '26.0.2'

    compileOptions.encoding "ISO-8859-1"

    defaultConfig {
        applicationId "com.commande.soqop"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 3
        versionName "1.2"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    aaptOptions{
        cruncherEnabled = false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

A: It will almost certainly be something in your manifest settings. Can you edit your question to show your AndroidManifest.xml?


text:
Q: Why wont my vmousedown, vmouseup function work I'm having trouble getting this jQuery function to work. I want to use the vmousedown and vmousemove events to work on mobile and although the function works when a mouse is involved, all of the touch events are not responding and thus in mobile nothing happens. I'm not sure what I'm doing wrong, and even when I use the touchmove events, the function still does not work.
$("#id").bind( 'vmousedown vmousemove', function( event ) {
  var swipe_y = event.pageY;
   if(swipe_y < 500){
      $('#id').removeClass('example-class');
   }
   else
   $('#id').addClass('example-class');

});


text:
Q: MongoDB aggregation and projection issue helpful people of StackOverflow!
I'm in the process of learning how to work with MongoDB, and am currently stuck with one particular problem.
I'm building a guitar tabs app, working only with an "artist" base document. All other data are subdocuments. Depending on the accessed functionality (e.g: search, list tabs by artist, view single tab), I aggregate and project my documents accordingly.
However, I can't get one projection to work as I want.
Given the following data:
{
    "artist" : "Jeff Buckley",
    "songs" : [
        {
            "name" : "Grace",
            "tabs" : [
                {
                    "version" : 1,
                    "tab" : "...",
                    "tuning" : "DADGBe"
                },
                {
                    "version" : 2,
                    "tab" : "...",
                    "tuning" : "DADGBe"
                }
            ]
        },
        {
            "name" : "Last Goodbye",
            "tabs" : [
                {
                    "version" : 1,
                    "tab" : "...",
                    "tuning" : "DGDGBD"
                },
                {
                    "version" : 2,
                    "tab" : "...",
                    "tuning" : "EADGBe"
                }
            ]
        }
    ]
}

I want to aggregate it the following way for a list view:
{
    "artist" : "Jeff Buckley",
    "tabs" : [
        {
            "song" : "Grace",
            "version" : 1
        },
        {
            "song" : "Grace",
            "version" : 2
        },
        {
            "song" : "Last Goodbye",
            "version" : 1
        },
        {
            "song" : "Last Goodbye",
            "version" : 2
        },
    ]
}

I tried it with the following projection:
    db.tabs.aggregate(
    [
        {
            $project : {
                artist : 1,
                tabs.song : "$songs.name",
                tabs.version : "$songs.tabs.version"
            }
        }
    ]
)

But instead I got:
{
    "artist" : "Jeff Buckley",
    "tabs" : {
        "version" : [[2,1],[2,1]],
        "song" : ["Grace","Last Goodbye"]
    }
}

Can anyone point me in the right direction?
Thanks!

A: your aggregation query not correct $project only affect your json document keys
your aggretion query like this
 db.tabs.aggregate(
                 {$unwind  : "$songs"},
                 {$unwind  : "$songs.tabs"},
                 {$group   : {
                             _id:"$artist",
                             tabs:{$push : {song : "$songs.name",version:"$songs.tabs.version"}}}},
                 {$project : {
                              tabs:"$tabs",
                              artist:"$_id",
                              _id:0}}
                 ).pretty()


text:
Q: c++ console in a non-console application project I'm working on a windows application in C++, and I'd like to use cout for debugging purposes.
It seems that the effects of cout are hidden, is there a configuration option that will allow a console window to open with my debug information?

A: You have a couple of reasonable options. One is to rename your entrypoint from WinMain to main, so it'll be built as a console application. That can still use things like RegisterClass and CreateWindow just fine.
The obvious alternative would be to use OutputDebugString instead of cout. The output from that will show up in a debugger, or any number of programs built specifically to display what it produces (basically mini-debuggers that just don't provide other debugging capabilities).
A third solution I'd consider less reasonable is to call AllocConsole to allocate a console, then write to it. If you don't mind doing all your writing with Windows-native console functions (WriteFile, WriteConsoleOutput, etc.) that's fine. Unfortunately, it won't initialize the C++ streams to work with the console, so you'll need to either open file streams pointing the console, or else find and use the (undocumented) function that initializes the streams library for the console. While this can be made to work, you end up doing extra work to write non-portable code, and little (if any) advantage to make up for it (and in this case, "non-portable" can include not even working with other versions of the same compiler, at least if you invoke the library's initialization function).

A: To add a console window to a GUI application, you can use the AllocConsole API.
Then you just need to open the special file name "CONOUT$" and attach your streams to it (cout, cerr, etc)
See this explanation on MSDN.

A: I believe the accepted answers are actually not what you are looking for. You say you need it only for debugging, not for release. Your best options are:
a) redirect stdout and stderr to a file and then inspect the file. This you can set in the VS project Properties > Configuration Properties > Debugging > Command Arguments: you should enter >out.txt 2>&1. This will output both stdout and stderr to out.txt
b) set your debug (you say you need it only for debugging) configuration Properties > Configuration Properties > Linker > System > SubSystem to Console (/SUBSYSTEM:CONSOLE). Then you can run the project with F5, but it will hide the console window when your application finishes. If you run it with Ctrl+F5 (but then you will not have debugger attached), then it will not be hidden.

A: The simplest way to do this is to start a Console application from scratch:
In VisualStudio, File > New Project.  Select Win32 Console Application.  Select various options and create the new project.
Note that although it says Win32 Console Application, you can create x64 builds without restriction.
At this point you have an application shell.  If you already have code and you want to bring it in to this new project, simply do Project > Add Existing Item... and select the files to include in the project.

A: Managing a console from a GUI program is horribly messy, and I suggest you do it another way. For instance, if you need to see the messages in real time, display them in a window; if not, write them to a file.

A: just use OutputDebugString() but remember to either set your character set to multibyte, or if you don't want to do that, you could write your code like this:
// with multibyte character set:

   OutputDebugString("Failed to do something");

// without multibyte character set:

   OutputDebugString(L"Failed to do something");


text:
Q: How to encrypt remote repo, with gcrypt or other? The goal is to store my code encrypted on a BitBucket remote repo. Something should deal with encrypting and decrypting so I landed on gcrypt or in full, git-remote-gcrypt.
I have a Bitbucket account with SSH keys configured.
This is what I've tried.
rsync
I copied these commands from the manual.
git remote remove cryptremote
git remote add cryptremote gcrypt::rsync://git@bitbucket.org/user/cryptremote.git
git config remote.cryptremote.gcrypt-participants "user"
git push cryptremote master

console:

gcrypt: Repository not found: rsync://git@bitbucket.org/user/cryptremote.git
gcrypt: Setting up new repository
protocol version mismatch -- is your shell clean?
(see the rsync man page for an explanation)
rsync error: protocol incompatibility (code 2) at compat.c(600) [sender=v3.2.3]
error: failed to push some refs to 'gcrypt::rsync://git@bitbucket.org/user/cryptremote.git'

A: freetalk@bitbucket.org: I confirm this would never work, as an SSH URL to a Git remote repository hosting service would always use the 'git' user (and rely on the SSH key to authenticate and identify the actual user account).
spwhitton/git-remote-gcrypt commit 6233fde does mention:

Remove deprecated gcrypt::ssh:// (use rsync instead)

So a rsync URI seems more supported, as in commit 3b69f81
In your case:
 gcrypt::rsync://git@bitbucket.org/user/cryptremote.git
                ^^^^^            ^^^

For any "protocol version mismatch -- is your shell clean?" error message, try and put in your .bashrc:
# for non-interactive sessions stop execution here -- https://serverfault.com/a/805532/67528
[[ $- != *i* ]] && return

But check also a possible rsync version mismatch (for instance, using a Bitbucket pipeline just to display rsync version).
As illustrated here, if SSH is not working, a gcrypt::https://user@bitbucket.org/user/test.git HTTPS URL might work better.

A: Thanks to the comments, I got it to work over HTTPS.
I wrote a small tutorial for myself and for you.

Encrypt remote Git repo with git-remote-gcrypt
General Workflow

*

*generate GPG private and public key (GnuPG Linux)

*create a remote repo

*init a local repo

*configure remote and gcrypt (commands below)

*clone or push

gcrypt example with rsync didn't work with Bitbucket
git remote add cryptremote gcrypt::rsync://git@bitbucket.org/USER/cryptremote.git
# gcrypt docs use :user but git usually uses /user format
# git remote add cryptremote gcrypt::rsync://git@bitbucket.org:USER/cryptremote.git
git config remote.cryptremote.gcrypt-participants "GPG_KEY_ID_OR_KEY_NAME"
git config remote.cryptremote.gcrypt-signingkey "GPG_KEY_ID_OR_KEY_NAME"
git push cryptremote master

gcrypt: Repository not found: rsync://git@bitbucket.org/user/cryptremote.git
gcrypt: Setting up new repository
protocol version mismatch -- is your shell clean?
(see the rsync man page for an explanation)
rsync error: protocol incompatibility (code 2) at compat.c(600) [sender=v3.2.3]
error: failed to push some refs to 'gcrypt::rsync://git@bitbucket.org/user/cryptremote.git'

gcrypt over HTTPS
Template from man page, modified to HTTPS, example repo name 'cryptremote':
git init
git remote add origin gcrypt::https://USER:APP_PASSWD@bitbucket.org/USER/cryptremote.git
git config remote.origin.gcrypt-participants "GPG_KEY_ID_OR_KEY_NAME"
git config remote.origin.gcrypt-signingkey "GPG_KEY_ID_OR_KEY_NAME"
# removes GPG password prompts but makes the name of the key owner public
git config remote.origin.gcrypt-publish-participants true
# in case of an existing encrypted repo
git clone gcrypt::https://USER:APP_PASSWD@bitbucket.org/USER/cryptremote.git
# in case of starting a new encrypted remote repo
git push --set-upstream origin master

Fix GPG password prompts during gcrypt push and pull

man git-remote-gcrypt

gcrypt.publish-participants
By  default, the gpg key ids of the participants are obscured by
encrypting using gpg -R. Setting this option  to  true  disables
that security measure.

Gratitude for something that works.
However, I don't like that I had to use HTTPS and an app password as Bitbucket now forces its users to use those for HTTPS.
Though I'm not sure why rsync isn't working, it seems the issue lies at Bitbucket as I use rsync flawlessly between my computer and my Android.


text:
Q: PowerShell - JSON/PsCustomObject - Why does my array get flattened into a single object? The owners key in my output (see OutputFile) I'm expecting as a line separated array, but it's outputting as a single-line space separated object/string
Script:
function Add-ApplicationOwner
{
    param (
        [string] $App,
        [object] $OutputObject
    )

    # add values to our json output
    $owners = (Get-AzureAdApplicationOwner -ObjectId $App).UserPrincipalName
    $OutputObject | Add-Member -MemberType NoteProperty -Name owners -Value $owners
}

$inputFile = Get-Content -Path "AppInput.json" -Raw | ConvertFrom-Json
$outputFile = New-Object -TypeName PsObject

foreach ($object in $inputFile.PSObject.Properties)
{
    $outputAppList = New-Object -TypeName PsObject

    foreach ($app in $inputFile.New.PsObject.Properties)
    {

        # create app
        $appRegistration = New-AzureADApplication -DisplayName "TestSPN1"

        #add application info into json object
        $outputAppValues = [PsCustomObject]@{
            app_id = $appRegistration.AppId
        }

        #add application owners by object id
        Add-ApplicationOwner -App $appRegistrationObjectId -OutputObject $outputAppValues

        $outputAppList | Add-Member -MemberType NoteProperty -Name "TestSPN1" -Value $outputAppValues

    }

    # add all created apps into json output file
    $outputFile | Add-Member -MemberType NoteProperty -Name "New Applications" -Value $outputAppList

}

$outputFile | ConvertTo-Json | Out-File "AzADAppRegistrationInfo.json" -Append

OutputFile:
{
    "New Applications":  {
                             "TestSPN1":  {
                                              "app_id":  "dsfadfdafa-3afadfdafadsfasd-343",
                                              "owners":  "user1 user2 user3"
                                          }
                         }
}

Desired Output:
{
    "New Applications":  {
                             "TestSPN1":  {
                                              "app_id":  "dsfadfdafa-3afadfdafadsfasd-343",
                                              "owners":  [
                                                   "user1",
                                                   "user2",
                                                   "user3"
                                               ]
                                          }
                         }
}

$owners Variable Examined:
$owners
user1
user2
user3

$owners.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

When I look at $outputFile.'New Applications' it's as expected
$outputFile.'New Applications' | convertto-json
{
    "TestSPN1":  {
                     "app_id":  "asdfdsfad",
                     "owners":  [
                                    "user1",
                                    "user2",
                                    "user3"
                                ]
                 }
}

When I look at $outputFile it's flattened
$outputFile | convertto-json
{
    "New Applications":  {
                             "TestSPN1":  {
                                              "app_id":  "cc6dgfsdgdsgfsdgfdsa5562614",
                                              "owners":  "user1 user2 user3"
                                          }
                         }
}

A: The most likable explanation for your issue is that -Depth is using the default Value. I have stored $outputFile.'New Applications' in the $json variable for below example.
[pscustomobject]@{
    'New Applications' = $json
} | ConvertTo-Json

Results in:
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{
  "New Applications": {
    "TestSPN1": {
      "app_id": "asdfdsfad",
      "owners": "user1 user2 user3"
    }
  }
}

Worth pointing out that the Warning Message is only displayed on newer versions of PowerShell (PS 7.1+ to be precise, thanks mklement0 for pointing it out). Windows PowerShell defaults to truncate the JSON without any warning.

However if we add 1 depth level (Default -Depth value is 2):
[pscustomobject]@{
    'New Applications' = $json
} | ConvertTo-Json -Depth 3

Results in:
{
  "New Applications": {
    "TestSPN1": {
      "app_id": "asdfdsfad",
      "owners": [
        "user1",
        "user2",
        "user3"
      ]
    }
  }
}


text:
Q: Why does returning a vector initialized with curly braces within normal brackets cause a compilation error? I just wrote a simple method to return a vector made with two int arguments. However, when I return the initialized int vector within normal brackets, it causes compilation error.
std::vector<int> getVec(int x, int y)
{
    return({x, y}); // This causes compile error
    return {x, y};  // This is fine
}

The error message says:
q.cpp: In function 'std::vector<int> getVec(int, int)':
q.cpp:8:21: error: expected ';' before '}' token
    8 |         return({x, y});
      |                     ^
      |                     ;
q.cpp:8:15: error: could not convert '((void)0, y)' from 'int' to 'std::vector<int>'
    8 |         return({x, y});
      |               ^~~~~~~~
      |               |
      |               int

A: From return statement:

*

*return expression(optional) ;   (1)

*return braced-init-list ; (2)

Remember the {..} is not an expression, has no type. There exist some contexts which allow {..} to be deduced in some type.
There is a special case for return {..} (2) and uses copy-list-initialization to construct the return value of the function.
In return ({x, y}), we go in (1), and {x, y} still has no type, no special cases for ({..}). So the error.

A: return {x, y};

{x, y} is a std::initializer_list<int>, so when your compiler sees this, it can deduce the type into:
std::vector<int>{std::initializer_list<int>{x, y}};

But:
return ({x, y});

This isn't systax correct:
std::vector<int>({std::initializer_list<int>{x, y}});

The compiler doesn't know hơ to deduce this, so it gives a compilation error.


text:
Q: How to divide number_field into 3 parts? In the model, I have an integer field for phone. In the view is this field displayed like this:
<%= f.number_field :phone %>

I am trying to display this one input for phone number as 3 inputs, I want to offer to user in the view something like this:
___ - ___ - ____

Is there any way how to do that?

A: The jQuery Masked Input plugin offers this functionality within one input field:

It allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format (dates,phone numbers, etc).

The demo page includes a phone format example: (___) ___-____

A: One way to do this would be to create 3 fields in view and let the user enter the number in 3 separate parts. In view it would look something like this
<p><%= f.number_field_tag "area_code" %> -
<%= f.number_field_tag "phone1" %> -
<%= f.number_field_tag "phone2" %> </p>

In controller you will join these 3 into 1 string to be able to save it according to your model setup
def create_user
...
@user = User.new
@user.phone_number = params[:area_code].to_s + params[:phone1].to_s + params[:phone2].to_s
...
end

I would also recommend saving the phone number as string in model to avoid incorrect storage of numbers that start with 0.


text:
Q: How to get specific data from XML API url using PHP I can display all values in it but I just want to know how to display specific data from this url. Can I display diesel price from this url?
I have tried $getdata->{'gpp:diesel'} but it display none
Here is the display of the XML API
<gpp:data xmlns:gpp="http://www.globalpetrolprices.com">
  <gpp:element>
    <gpp:country code="MY">Malaysia</gpp:country>
    <gpp:date>2019-05-13</gpp:date>
    <gpp:currency>MYR</gpp:currency>
    <gpp:diesel>2.18</gpp:diesel>
  </gpp:element>
</gpp:data>

Here is the code :
<?php
   $url = 'https://www.globalpetrolprices.com/api_gpp.php?cnt=MY&ind=dp&prd=latest&uid=1437&uidc=13fc5a9f3a45102997db4d4698669ac7';

   $getdata = file_get_contents($url);

   echo "DIESEL PRICE PER LITRE : ".$getdata."<br>";
?>