text:
Q: Docker compose does not link with MySQL database correctly I have a docker-compose which will create a guacamole docker container, a guacd container and a mysql container. On the docker host, I have ithe init.db inside the /tmp/scripts
If I was to do the mysql part manually, I would run docker run --name guac-mysql -v /tmp/scripts:/tmp/scripts -e MYSQL_ROOT_PASSWORD=password -d mysql:5.7
Then run the guacamole container like this:
docker run --name guacamole --link guacd:guacd --link mysql:mysql \
-e MYSQL_DATABASE='guacamole' \
-e MYSQL_USER='guacamole' \
-e MYSQL_PASSWORD='password' \
-d -p 8080:8080 guacamole/guacamole

version: '2'

services:
  guacd:
    hostname: guacd
    image: guacamole/guacd
  mysql:
    hostname: mysql
    image: mysql:5.7
    volumes:
      - ./tmp/scripts:/docker-entrypoint-initdb.d
    ports:
      - "3306:3306"
    environment:
      - MYSQL_DATABASE="guacamole"
      - MYSQL_USER="guacamole"
      - MYSQL_PASSWORD="password"
      - MYSQL_ROOT_PASSWORD:"password"
  guacamole:
    image: guacamole/guacamole
    restart: always
    ports:
      - "8080:8080"
    links:
      - guacd
      - mysql
   environment:
      - GUACD_HOSTNAME=guacd

volumes:
  tmp-scripts:

But when I try to automate it, as shown below, I get this error:
database is uninitialized and password option is not specified
  You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD

Can you please help?
Thanks

A: : to =MYSQL_ROOT_PASSWORD="password"


text:
Q: Calculating plumb-bob coefficients from rational-polynomial coefficients for camera lense distortion Is it possible to recalculate the plumb-bob coefficients for a given OpenCV calibration file, that was created using a rational-polynomial model?
Concerning group__calib3d.html, the plumb-bob model uses the coefficients [k1, k2, p1, p2, k3] while the rational-polynomial model uses [k1, k2, p1, p2, k3, k4, k5, k6].
The distortion model looks like

Thus, the rational-polynomial model just adds a denominator in the first term.
Do I have to refit the plumb-bob into the rational polynom, or is there some easier approach to get [k1, k2, p1, p2, k3]?
Here is an example of the rational-polynomial coefficient: [0.452407000, 0.273748000, -0.000110000, 0.000152000, 0.027904000, 0.817958000, 0.358389000, 0.108657000]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как выбрать ответы на комментарии из монги? Как, в рамках одной агрегации, получить ответы на комменты?
Пример:
{
 "_id": 1,
 "reply_for": null,
 "comment": "комментарий"
},
{
 "_id": 2,
 "reply_for" 1,
 "comment": "Ответ"
}

можно-ли вообще это сделать в рамкох одной агрегации, чтобы например на выходе получить
{
     "_id": 1,
     "reply_for": null,
     "comment": "комментарий",
     "reply" : [
        {
          "_id": 2,
         "reply_for": 1,
          "comment": "Ответ"
        },
     ]
    },

A: ....
  ['$addFields' =>  ['comment_id' => ['$toString' => '$_id']],
  ['$lookup' => [
     'from' => 'collection',
     'localField' => 'comment_id',
     'foreignField' => 'reply_for',
     'as' => 'reply',
  ]
  ]
....


text:
Q: Decompress wav file (Windows IMA ADPCM compression) in Objective-C? I have some wav files that were presumably created on a Windows system and need to be decompressed (ideally "on the fly") in an Objective-C app.  The compression code is 17 -- IMA ADPCM.  I've found some source, but would prefer to use something built-in if it's accessible, especially since there are apparently several different variants of the algorithm.
Do does anyone know of an API or such that can be used to do the decompression?
Update: Trying to use Extended Audio File Services, but I can't get past setting the "ClientDataFormat".  See this post.

A: The built-in AVFoundation framework will play .wav files.


text:
Q: What's the right way to enable the node debugger with mocha's --debug-brk switch? I have some debugger statements in my module under test and want to run mocha with --debug-brk set and hit my breakpoint so that I can inspect the state of my module. Unfortunately, whenever I run mocha with this option, I end up with a blank cursor on the next line. I can enter text, but there's nothing that appears to be processing my commands (it certainly doesn't look like the node debugger):
$ mocha --debug-brk tests.js -R spec
debugger listening on port 5858
[BLANK CURSOR]

Am I doing something wrong with how I'm launching mocha?

A: UPDATE
As of mocha 7.0.0, --debug-brk has been removed in favor of --inspect-brk

Using a recent version of nodejs (>=v6.3.0) and mocha (>=3.1.0), you can use V8 inspector integration.

V8 Inspector integration allows attaching Chrome DevTools to Node.js
instances for debugging and profiling

Usage
--inspect activates V8 inspector integration, and --debug-brk adds a breakpoint at the beginning. Since nodejs v7.6.0 and mocha v3.3.0, you can use the --inspect-brk shorthand for --inspect --debug-brk
$ mocha --debug-brk --inspect
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/remote/serve_file/@62cd277117e6f8ec53e31b1be58290a6f7ab42ef/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node

With npm scripts
If you have a npm test script that uses mocha, you can pass the options from npm to your mocha script by using the end of option delimiter --:
$ npm test -- --inspect --debug-brk
Chrome tip
Instead of copy-pasting the url each time, go to chrome://inspect and click the appropriate link in the "Remote target" section.

A: To answer the original question, even though I also suggest you look into node-inspector: you can use the CLI debugger built into node through mocha with the debug option, instead of the --debug or --debug-brk flags. (Notice the lack of dashes.)
In your example, instead, it would be:
$ mocha debug tests.js -R spec
debugger listening on port 5858
connecting... ok
break in node_modules/mocha/bin/_mocha:7
  5  */
  6
  7 var program = require('commander')
  8   , sprintf = require('util').format
  9   , path = require('path')
debug> [CURSOR]
Again, debug as above in bold, with no dashes. (=
Relevant: https://github.com/visionmedia/mocha/issues/247

A: I was able to get this to work using node-inspector. I run my test like you show in one shell:
mocha --debug-brk mocha/test.js

and then run node-inspector in a second shell:
node-inspector

Bringing up the URL that node-inspector spits out in a browser allows me to debug with the web inspector.
http://127.0.0.1:8080/debug?port=5858

A: run mocha with flag --inspect-brk and click 'open dedicated DevTools for node' in chrome from page chrome://inspect. In dedicated DevTools window add connection localhost:9229 to connect automatically.
Also add a debugger statement to the file you want debug.
(this is using latest versions of node and chrome as of October 2017)

A: If you have node-insector installed you can debug you Mocha tests without actually running node-inspector first. The easiest way is to
node-debug _mocha

That should start debugging the node tests in chrome (also works on Safari)
One reason I have seen that the tests do not work is sometimes you gave to try http://localhost:8080/debug?port=5858 or http://127.0.0.1:8080/debug?port=5858


text:
Q: Overwrite log line with log4j2 is it possible with log4j2 to overwrite a logline?
So for example instead of logging
19:43:44.642 [main] INFO  main - Init...
19:43:50.348 [main] INFO  main - Init done.

one can log first
19:43:44.642 [main] INFO  main - Init...

and when the init is done instead of writing a new line rewriting the last line like (either rewrite or just append)
19:43:44.642 [main] INFO  main - Init... - done.

I am aware of the fact that the timestamp gets messed up as it is now incorrect (at least if it is not updated aswell in the case of appending).
Is it possible to do so?

A: I think it's impossible. The log system is not a console. Logs output is dumped on the file system in the stream. It was done from performance perspective.
The case you described more related to console behavior.
So this is not proper approach for using logging at all.


text:
Q: Calculate date difference in integer value I have two date fields with IDs gp_vdate_from and gp_vdate_to. And I have a hidden div which is populated by a dynamic table. The div gets visible on click of a button after entering date fields. I did something like this to calculate the date difference
function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function daydiff(first, second) {
return Math.floor((second-first)/(1000*60*60*24))
}

var diff=(daydiff(parseDate($('#gp_vdate_from').val()), parseDate($('#gp_vdate_to').val())));

The date entered is in the format 10-2-2012.
But I am not able to give to get the difference? Can someone point out why?

A: I think you do not have valid dates. Look at this line:
new Date(mdy[2], mdy[0]-1, mdy[1])

This is like writing
new Date(2012,9,'feb')

for 10-feb-2012, which is not valid. The date constructor takes arguments like this:
new Date(year, month, day [, hour, minute, second, millisecond ]);

Where all the arguments are integers ('feb' is not valid, also you were passing arguments in the wrong order.)
So I think you need to look at your parseDate method.
This is all assuming that JQuery doesn't change how the Date object works - you may need to check that.
You should use a javascript console like Firebug for firefox to help you debug.

A: You can use date.getTime() to check the difference
function daydiff(first, second) {
 return Math.floor((second.getTime()-first.getTime())/(1000*60*60*24));
}

please check with Date object create arguments
new Date(year,month,day);

A: You could try using date.js, a small but awesome JS library just for working with dates. It normalises Date objects across browsers and gives all kinds of sugary methods for working with dates :)
Can be used with jQuery too
EDIT
date.js makes working with dates less painful, but is not essential, everything you need can be done in pure JS.
Other answerers - Actually, the Date constructor in JavaScript can accept a single string as an argument, which it uses to generate a new Date object.
I made a fiddle based on your example code showing how to calculate number of days between two dates. Have a look and play around and it might be what you need :)


text:
Q: Remove a particular field for all documents in a collection using aggregation in mongoDB How to Remove a particular value for all records in the collection using aggregation :
Have a collection with data :
[
 {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas"

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:false,
    location: "texas"
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas",
    present_working:false
  }
]

Remove the rows in records for which there is present_working:false. Data need not be removed in the database, it should be only modified in the aggregation pipeline
Expected output after removing only present_working:false and present_working:false should be kept in database. :
[
 {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas"
  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    location: "texas"
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas"
  }
]

MongoDB version: 4.0

A: You can use $$REMOVE as part of $project:
db.collection.aggregate([
    {
        $project: {
            _id: 1,
            name: 1,
            occupation: 1,
            age: 1,
            location: 1,
            present_working: { $cond: [ { $eq: [ "$present_working", false ] }, "$$REMOVE", "$present_working" ] }
        }
    }
])

Mongo Playground


text:
Q: Create tests for parser combinators in Scala Consider this source code that implements a parser for a term language in Scala. The main function, designed to test its functionality is defined asÑ
def main(args: Array[String]): Unit = {
    val stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val tokens = new lexical.Scanner(stdin.readLine())
    phrase(term)(tokens) match {
      case Success(trees, _) =>
        for (t <- path(trees))
          println(t)
        try {
          print("Big step: ")
          println(eval(trees))
        } catch {
          case TermIsStuck(t) => println("Stuck term: " + t)
        }
      case e =>
        println(e)
    }
  }

However, I want to test part of the functionality by calling the term parser on concrete input. How can I provide this input? Passing a string does not work...

A: Just replace stdin.readLine() with your desired input, so
phrase(term)(new lexical.Scanner("the string you want to test")) match {
  case Success(trees, _) => ...
  case err => ...
}


text:
Q: Convert List to List I have the following problem:
public class AwesomeClass
{
    public string SomethingCool { get; set; }
    public string SomethingUseless { get; set; }
}

I have a class which contains a number of properties, and I need to convert a list of these classes into a list of strings, where the string represents a property in the class.
List<AwesomeClass> stuff = new List<AwesomeClass>();

//Fill the stuff list with some tings.

List<string> theCoolStuff = //Get only the SomethingCool property in the AwesomeClass list.

The reason why I need to convert this to a list of strings is because I have a method which takes a List as a parameter, but the SomethingCool property contains the data that I need for this list.
Note: I could use a foreach loop on the list and populate the List of strings but I'm looking for a more elegant method, perhaps LINQ can do this for me?

A: Note that you can even:
List<string> theCoolStuff = stuff.ConvertAll(x => x.SomethingCool);

because the List<T> has a special "conversion" method :-)

A: You can simply use Select:
var theCoolStuff = stuff.Select(x => x.SomethingCool).ToList();

What Select does is a projection, it projects each item and transforms (not convert) them into another form.

A: foreach (AwesomeClass member in stuff)
{
   theCoolStuff.Add(member. SomethingCool)
}


text:
Q: Differential Equation with Substitution I have this Differential Equation:
$$(2x^2 + y^2) \frac{dy}{dx} = 2xy$$
and I solved it by substituting $y=vx$ and $\frac{dy}{dx}=\frac{dv}{dx} (x +v)$
I found a result of $y^2(\ln(y) +C)=x^2$, but since it must be an implicit solution for $y$ I don't know whether I should leave it in this form. Also I hope I didn't do anything wrong in the proccess. Any help would be much appreciated

A: There is a typing mistake in :
$y=vx$ and $\frac{dy}{dx}\neq\frac{dv}{dx} (x +v)$
$$\frac{dy}{dx}=v+x\frac{dv}{dx}$$
With this, you got to :
$$x^2=y^2(c+ln(y))$$
That's OK. You can let it on the implicit form (or an equivalent form).
One can express $y(x)$ thanks to a special function called Lambert W function.
$$y=\pm \frac{\sqrt 2 \: x}{\sqrt{W(C x^2)}}$$

A: here is another way to solve $$\frac{dy}{dx} = \frac{2xy}{2x^2 + y^2}.$$  split the differential equation into two as $$\frac{dy}{dt} = \frac y{2x^2+y^2}, \frac{dt}{dx}=2x.$$
solving for $x,$ we get $$x^2 = t +C. \tag1$$ and the differential equation for $y$ is $$ \frac{dt}{dy} = \frac{2x^2+y^2}{y} = \frac{2(t + C)}{y}  + y.$$ which can be solved as $$ t + C = y^2\ln y +By^2.\tag 2$$ eliminating $t$ between $(1)$ and $(2)$ gives you $$x^2 = y^2 \ln y+By^2, \text{ where  $B$ is an arbitrary constants.  } $$
i can't figure out where i am losing an $\ln y.$
edit: thanks to narasimham. i found the error at the very beginning. i copied the wrong equation. it is good now.


text:
Q: Is there a game that works on one computer but with four players? Is there a game for Ubuntu where four players can play at once?
We have four game controllers and people with the age of 5 up to 50.
The game should be simple: 2-D, not 3-D.
It can be commercial software, too.

A: I would go for super tux kart! It's like mario kart but with a Linux feel to it :)
It's a 3D game but it has simple graphics and it's done in a playful way.
It's available in the software center or from sourceforge.
As you can see below, it works well with a 4-way split screen.


text:
Q: tinymce remove span when submitting prism.js So far when I open prism.js in tinymce text editor, it appears fine, it highlights the code, of course because when I inspect, the tag <span> exist inside the <pre> tag. The problem is, when submitted, the <span> tags don't follow any more. They just disappear. What's wrong? Is it famous unsolved problem of prism.js as tinymce plugin? Or am I missing something? I just need the <span> to be there when submitted. That's all.
Please help. Thanks in advance.
/------------- for clarity, here is the plugin code ---------------------/
tinymce.init({
    selector: '.content_textarea',
    plugins: 'advlist autolink link image lists charmap print preview codesample emoticons',
    toolbar: 'undo redo | styleselect | bold italic | numlist bullist | codesample | link image | emoticons',
    link_class_list: [
        {title: 'None', value: ''},
        {title: 'Demo', value: 'btn demo'},
        {title: 'Download', value: 'btn download'}
    ],
    codesample_languages: [
        {text: 'HTML/XML', value: 'markup'},
        {text: 'JavaScript', value: 'javascript'},
        {text: 'CSS', value: 'css'},
        {text: 'PHP', value: 'php'},
        {text: 'Ruby', value: 'ruby'},
        {text: 'Python', value: 'python'},
        {text: 'Java', value: 'java'},
        {text: 'C', value: 'c'},
        {text: 'C#', value: 'csharp'},
        {text: 'C++', value: 'cpp'}
    ],
    valid_elements: "*[*]",
    image_dimensions: false,

    image_title: true,
    image_caption: true,
    // enable automatic uploads of images represented by blob or data URIs
    automatic_uploads: true,
    // URL of our upload handler (for more details check: https://www.tinymce.com/docs/configure/file-image-upload/#images_upload_url)
    images_upload_url: base_url()+'admin_crud/img-upload-tinymce',
    // here we add custom filepicker only to Image dialog
    file_picker_types: 'image',
    // and here's our custom image picker
    file_picker_callback: function(cb, value, meta) {
        var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');

        // Note: In modern browsers input[type="file"] is functional without
        // even adding it to the DOM, but that might not be the case in some older
        // or quirky browsers like IE, so you might want to add it to the DOM
        // just in case, and visually hide it. And do not forget do remove it
        // once you do not need it anymore.

        input.onchange = function() {
          var file = this.files[0];
          var orig_filename = this.files[0].name;
          orig_filename = remove_ext(orig_filename);

          // Note: Now we need to register the blob in TinyMCEs image blob
          // registry. In the next release this part hopefully won't be
          // necessary, as we are looking to handle it internally.
          var id = orig_filename + (new Date()).getTime();
          var blobCache = tinymce.activeEditor.editorUpload.blobCache;
          var blobInfo = blobCache.create(id, file);
          blobCache.add(blobInfo);

          // call the callback and populate the Title field with the file name
          cb(blobInfo.blobUri(), { title: remove_ext(file.name) });
        };

        input.click();
    }
});

A: Those tags are added by Prism. TinyMCE calls Prism and when you add, edit or view your content inside of TinyMCE you will see the code highlighting. Viewing outside of TinyMCE results in not seeing the code highlights, this is because Prism has not been called.
In order for your code to look like what you saw inside of TinyMCE, you need to add
 Prism.highlightAll()

or a variation of it depending on your use case on your page that does not call TinyMCE. See here: https://prismjs.com/extending.html#api


text: Q: If $x_0,h$ belong to a metric vector space and $ε>0$, is there always a sequence $(t_n)_{n∈\mathbb N}\subseteq\mathbb R$ with $x_0+t_nh\in B_ε(x_0)$? Let $(X,d)$ be a metric $\mathbb R$-vector space, $x_0,h\in X$ and $\varepsilon>0$. If $d$ is induced by a norm $\left\|\;\cdot\;\right\|$, then $$x_0+th\in B_\varepsilon(x_0)\;\;\;\text{for all }|t|<\frac\varepsilon{\left\|h\right\|}.$$ However, if $d$ is not induced by a norm, can we still show that there is a $(t_n)_{n\in\mathbb N}\subseteq\mathbb R\setminus\{0\}$ with $$x_0+t_nh\in B_\varepsilon(x_0)\;\;\;\text{for all }n\in\mathbb N\tag1$$ and $t_n\xrightarrow{n\to\infty}0$?


text:
Q: Wordpress duplicating information Not sure why this is happening. The script below displays the title, link and custom meta of all pages using a specific template.
For some reason its duplicating the information.
Online example: http://greenleavesmarketing.co.uk/sherif/prices/
Script:
<?php // Display list of pages using the template page-landing.php

    $product_pages_args = array(
        'meta_key' => '_wp_page_template',
        'meta_value' => 'page-landing.php',
        'depth' => -1,
        'hierarchical' => 0,
    );

    $product_pages = get_pages( $product_pages_args );

    echo '

                    Dental Procedure
                    Cost

';

        foreach ( $product_pages as $product_page ) {

            echo '

                    ID).'">'.$product_page->post_title .'

                '; ?>
            <?php
            $custom_metabox = get_post_meta($product_page->ID,'_custom_meta',TRUE);

                if($custom_metabox['landing-para']!=false) {
                    echo $custom_metabox['landing-para'];
                } else {
                    echo 'Please contact us for a free consultation.';
                }

                echo '

';
        }

     echo '
'; wp_reset_query();  ?>

A: This doesn't necessarily fix the underlying problem, but if all $product_page->post_title values are unique, you could store them in an array as you go through the foreach loop and continue if the value already exists:
    // create a dummy array to store $product_page->post_title values:
    $post_titleArr = array();

    foreach ( $product_pages as $product_page ) {
        if (in_array($product_page->post_title, $post_titleArr)) continue;  // skip this iteration for dupe.
        $post_titleArr[] = $product_page->post_title;  // not a dupe - add it to the array.

        // continue your code...
        echo '


text:
Q: How to save multiple rows of data by looping through an array or a map? Class Buyer {
   String name
   static constraints = {
   }
}
Class Order {
    String ref
    static belongsTo = [buyer:Buyer]
    static constraints = {
    buyer(nullable:false)
    }
}

In  OrderController.groovy
...
def someAction = {
  //working
  def data1 = ["buyer.id": 2, "ref": "xyz"]
  def ord = new Order(data1);
  ord.save();

  def data2 = ["buyer.id": 2, "ref": "234xyz"]
  def ord2 = new Order(data2);
  ord2.save();

  //But in a loop - its not working
  def items = ['abc', 'def', 'ghi', 'jkl']
  def data2 = [:]
  for(e in items) {
     data2 = ["buyer.id": 2, "ref" : e.value] //keeping buyer id same
     def ord = new Order(data2);
     ord.save();
     data2 = [:] //just emptying it?
  }
}

As you would notice in "working" above, if I am able to save multiple rows by copy pasting and definging new maps but If I try to loop through an array, it doesnt work. Any ideas how do I save data by looping through an array or a map?
Any questions, please let know
Thanks

A: First, I'm not sure about ["buyer.id": 2, "ref" : e.value],  I think it should be [buyer: Buyer.get(2), ref : e.value].
Second, I would recommend using cascading save to do the task. You can try something like this(You need to define a static hasMany = [orders: Order] relation in Buyer for Buyer-Order relationship.
Buyer b = new Buyer(name: "foo")
for(e in items) {
     def ord = new Order(ref: e.value);
     b.addToOrders(ord)
  }

b.save(flush:true)

A: You should just be able to do:
def someAction = {
  def items = ['abc', 'def', 'ghi', 'jkl']
  items.each { item ->
     def ord = new Order( [ 'buyer.id':2, ref:item ] )
     ord.save()
  }
}

What errors (if any) are you getting?
Also, why are you doing e.value?  This will get you an array of Character rather than a String (which is what your first working example is using)


text:
Q: vuejs - template, store, this.$store is undefined I have a problem retreiving the vuex store in a vuejs component.
My architecture is pretty straight-forward. I have a store with two modules.
main.js
new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: {
    App
  },

Events.vue - Here I use my custom component UserDropdown in a syncfusion component, but I dont think that's relevant. The first registers the UserDropdown, the second fragment will be called when you click on a cell and returns my custom component:
...
components: {
            UserDropdown
        },
...
editTemplate: function () {
   return {template: UserDropdown}
},
...

UserDropdown.vue - here I'd like to use the store, but the result is: "this.$store is undefined". Access to the store from within other components like Events.vue  works just fine.
computed: {
        users: function () {
            return this.$store.state.usersState.users;
        }

store.js
import Vue from 'vue';
import Vuex from 'vuex';
import projectsState from './modules/projectsStore'
import usersState from './modules/usersStore'
import createLogger from 'vuex/dist/logger'

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

export const store = new Vuex.Store({
  modules: {
    projectsState,
    usersState
  },
  strict: debug,
  plugins: debug ? [createLogger()] : []
});

Why doesnt that work? Is the problem related to the "template: UserDropdown"? I thought every component should be able to access the store...

A: As it looks, one has to import the store once again in the UserDropdown.vue component. That doesn't make any sense to me, since I imported the store in the new Vue instance as shown above.
Here the code fragments to be added in the UserDropdown.vue
...
import {store} from "../store/store";
...
export default {
    store,
    name: 'UserDropdown',
...
...mapGetters({users: 'usersState/AllUsers'})
...


text:
Q: The meaning of a closed differential inequality I'm currently reading Villani's notes on hypocoercivity and on pp87 it states that the differential inequality (14.10):
$$ \frac{d}{dt}(\mathcal E (f) - \mathcal E(f_\infty)) = -\mathcal D(f) \leq -K_\epsilon(\mathcal E(f) - \mathcal E(f_\infty))^{1+\epsilon} $$
cannot in general be 'closed'. What does it mean for a differential inequality to be closed?

A: Clearly, if we have a inequality of the form as you wrote: $$\frac{d}{dt}(\mathcal E (f) - \mathcal E(f_\infty)) = -\mathcal D(f) \leq -K_\epsilon(\mathcal E(f) - \mathcal E(f_\infty))^{1+\epsilon},$$ with $K_\epsilon$ being a constant depending only on $\epsilon$, this would imply that $\mathcal{E}(f)$ decays to $\mathcal E(f_\infty)$ polynomially fast in time. However, I think Villani's (14.10) stated instead that
$$\frac{d}{dt}(\mathcal E (f) - \mathcal E(f_\infty)) = -\mathcal D(f) \leq -K_\epsilon\left(\mathcal E(f) - \mathcal E(\Pi_1 f)\right)^{1+\epsilon},$$ this inequality is clearly "not closed" (in the sense that no information regarding the decay of $\mathcal{E}(f)$ to $\mathcal E(f_\infty)$ can be inferred from this inequality).
Side remark: I have also read a bit Villani's "Hypocoercivity" so maybe we can discuss more on his monograph if you want, also I think my question (with a bounty) A possible error in Villani's monograph "Hypocoercivity" might interest you as well.


text:
Q: Counting the number of pairs $(a,b)$ such that $M \mid a+b$  with $a, b \in [N]$ We have been given first $N$ natural numbers and asked to count all distinct pairs $(a,b)$ where, $a < b$ such that $a+b$ is divisible by a given number $M$.

Example: Given $N = 4$, i.e. $\{1,2,3,4\}$
$M = 3$
Only possible pairs satisfying above conditions are $(1,2)$ and $(2,4)$.
Since, $1 < 2$ and $1+2 = 3$ is divisible by $M$.
$2 < 4$ and $2+4 = 6$ is divisible by $M$.

Values $M$ and $N$ can be very large (of the order of $10^9$), so simply generating pairs and dividing won't work.
My Idea: We need to generate pairs which sum up to multiple of $M$. Since, there is a strict ordering between $a$ and $b.$ (i.e. $a < b$) so, for generating any number $x$ which lies in the range $1$ to $N$ there are $\frac{(x-1)}{2}$ possible pairs. So, we need to sum up these values over multiples of $M$. But when the value of $x$ goes beyond $N$, this idea doesn't work (as number of pairs decrease).
I can't proceed any further. Kindly guide me if I am in a wrong direction. Or suggest any other alternative to efficiently calculate the same.

A: Hint:  Think of it as finding pairs $(a,b)$ such that $a+b\equiv 0 \mod M$.
We can write $N = Mq + r$ for some integers $q\geq 0$ and $0\leq r < M$.  Now partition the integers from $1$ to $N$ into equivalence classes modulo $M$.  For $0\leq a\leq M-1$, let $S_a = \{i\in [N] \mid i\equiv a \mod M\}$.  Then $S_a$ contains $q+1$ elements for $0\leq a\leq r$, and $q$ elements for $r+1\leq a\leq M-1$.
Now, given $a\in [N]$, how many choices for $b$ are there such that $a+b\equiv 0 \mod M$?


text:
Q: Python class members confusion First of all, i come from a java and php background and am now learning python. This may therefore seem like a silly question but it has me a little confused.
As an example in php:
class MyClass
{
   private $myMember;

   public function __construct($myMember = null)
   {
       $this->myMember = $myMember;
   }

   public function setMyMember($myMember)
   {
       $this->myMember = $myMember;
   }

   public function getMyMember()
   {
       return $this->myMember;
   }

}

This is completely textbook 101 OOP.  A class with a single private member and a getter and setter.
However, learning some python and this isn't so straightforward it seems.
First off, the constructor isn't a real constructor (but you can use at such?? )
Secondly, any class level decelerations are treated as static ??  So self.myMember in python actually sets a different variable on the instance which is not the same as the class level myMember?
Lastly, if my confusions are correct - how would the same example above be coded in python?

A: Generally, you don't use getters and setters in Python; unless you need to transform the value, need side-effects during setting or getting, or need to prevent either getting or setting, you just use attributes instead:
class MyClass(object):
    def __init__(self, member):
        self.member = member

Instance attributes are separate from class attributes; setting attributes on self means you are manipulating the instance, attributes on the class (MyClass.member) are class attributes and are thus shared amongst instances. This is achieved by using the class as a fallback when looking up attributes; first the instance is queried, then the class of the instance, then the base classes of the class; setting self.member means that any MyClass.member is no longer visible on the instance.
The __init__ method is indeed, technically, not a constructor. self already exists when __init__ is called. It is instead an initializer, you set the first values with it. If you need an actual constructor (instance factory) you need to look for the __new__ static method instead. Note that in PHP, __construct is an initializer as well, not a constructor!
For those cases where you do have a need to create setters and getters, use the property decorator function:
class MyClass(object):
    def __init__(self, member):
        self._member = member

    @property
    def member(self):
        return 'Hello {}!'.format(self._member)

    @member.setter
    def member(self, value):
        # Remove "Hello " and "!" from the start and end of any value being set.
        if value.startswith('Hello '):
            value = value.split(None, 1)[1]
        self._member = value.rstrip('!')

Demo:
>>> m = MyClass('World')
>>> m.member
'Hello World!'
>>> m.member = 'Hello Planet Earth!'
>>> m.member
'Hello Planet Earth!'
>>> m._member
'Planet Earth'

A: This would be something like this:
class MyClass(object):

    def __init__(self, myMember=None):
        self._myMember = myMember

    @property
    def myMember(self):
        return self._myMember

    @myMember.setter
    def myMember(self, value):
        self._myMember = value

Demo:
c = MyClass()
c.myMember = 10
print c.myMember

And you have:
# 10

A: In python, classes create a new namespace.  Barring funny business (like metaclasses), the stuff in the namespace become attributes on the class.
class Foo(object): #inherit from object in python2.x ... It's a good idea
     class_variable = 3
     __not_really_private_but_sort_of = 7

now I've created a class which has 2 attributes.  The first one is "public".  The second one is "private" in the sense that it is prefixed with double underscores which invokes python's name mangling.  In python, this is rarely used.  After all, we're all consenting programmers here :).
When you call a class, it invokes the __new__ method (the constructor) and then (if __new__ returns an instance of that class) it invokes the initializer (__init__).  Most of the time, you don't need to do anything with __new__ -- The default __new__ does a fine job.  Since __init__ is a regular method, it recieves the instance of the class as the first argument -- Basically filling the role of the this-> pointer from other languages:
class Foo(object):
    member = 4
    other_member = 5
    def __init__(self):
        print "__init__ called!"
        self.member = 3
        print self.member
        print self.other_member

One thing that is a little strange about python compared to other languages is the fact that if an instance doesn't have a member, python then looks for the member on the class and then on base classes (searching in the method resolution order).  If it doesn't find the member anywhere, then it raises an AttributeError.  So, if I instantiate my above class, it will print:
__init__ called!
3
5

Also note that I can access the class ("static" as you called it) members via the class:
print Foo.member

or via an instance:
print Foo().__class__.member

As far as how you would write the above PHP in python ... The answer is that you wouldn't.  It would be best to write it like this:
class MyClass(object):
    def __init__(self,mymember=None):
        self.mymember = mymember

There really is no good reason to have a setter whose sole purpose it to set a private member.  If you want the user to have the ability to reset the mymember attribute, then the idiomatic way to do it is to let them have direct access to it rather than forcing them to call a function to do the job.  You can always make mymember into a property later (as described in some of the other answers) if you find out that you actually need that functionality.

A: Here's a few points you need to know about how Python does object-orientation, if you're coming from Java/PHP.

In Python, classes are perfectly ordinary objects too. That means that classes themselves can have member variables (we usually just call them attributes). All the names you assign in a class block become attributes of the class itself, not of any of its instances (including the function def blocks that create methods; that's all a method is in Python).
Since you typically have one class and many instances, class attributes can serve a similar purpose to static variables in Java classes, but they're not quite the same concept.
Assigning names in the class block never creates attributes on the actual intances of the class; the only way to create attributes on an object (any object, class or ordinary instance) is to assign them once it exists. So the standard declaration of all the variables that a class' instances have has to live in the __init__ method in Python, assigning attributes on self.
For example:
class Foo(object):
    foo = "I am a class attribute"

    def __init__(self):
        self.bar = "I am an instance attribute"

Where this often confuses new Python programmers is that attempting to read the foo attribute from an instance will actually work, and find the class attribute (this is how method invocations find the function they're supposed to call). So it kind of looks like declaring instance attributes in the class block works to a first casual playing around. But there is actually only one attribute foo, shared between all instances, which can be very bad if it's a mutable object and you expect that each instance has its own copy.

There is no access control in Python, so there's no such thing as a private variable. This is because Python is dynamic enough that you could always get around any such restriction, making them a bit pointless.
Instead, Python programmers tend to rely on documentation and convention to ensure that programmers writing the client code know which names are part of the public API and which are implementation details. We then trust that everyone will mostly respect the rules, and those that don't have to deal with their code being things they shouldn't have relied on change.
In any language an attribute with the trivial getter and setter is really "public" anyway; the only possible concern is that you might "one day" want to change the implementation of the getter/setter so that they're no longer trivial without changing your interface. Python can address this problem with properties (basically allow you to make method calls that look like reading or writing to an attribute), so there's absolutely no reason to have getter/setter methods unless there's actually something more going on in them.
So generally if the interface by which you expect client code to manipulate your objects includes reading and writing a field, you simply document that an ordinary attribute is available to be read and written. If you want to be clear that an attribute (or method) is purely for internal use, the usual convention is to start the name with a single underscore. This forces anyone using that name to know that they're accessing an internal name (because they have to type the leading underscore), so you needn't worry that someone will "accidentally" use a private attribute.

Regarding constructors, just treat the __init__ method as __construct from PHP and it'll do what you expect (but make sure you remember that Python methods explicitly receive a self parameter; no implicit this).
There's this myth going around that __init__ is somehow different from a constructor, so you shouldn't call it one. As far as I can tell the culprit is Dive Into Python, which rather bizarrely says:

It would be tempting but incorrect to call this the constructor of the
  class. It's tempting, because it looks like a constructor (by
  convention, __init__ is the first method defined for the class), acts
  like one (it's the first piece of code executed in a newly created
  instance of the class), and even sounds like one ("init" certainly
  suggests a constructor-ish nature). Incorrect, because the object has
  already been constructed by the time __init__ is called, and you
  already have a valid reference to the new instance of the class.

But "the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class" precisely characterises how traditional constructors work, so I have no idea what point the authors are attempting to make there.
(The official line that the Python docs appear to take is that MyClass(arg1, arg2) is a constructor expression; __init__ and __new__ are both described as receiving the arguments that were given to the constructor expression, and __init__ is explicitly referred to as a constructor. Both of these terms are used rarely in the docs; they just say __init__ most all of the time.)
So I urge you to ignore anyone who tries to tell you that __init__ is not a constructor. You will do much better trying to understand __init__ by analogy with constructors than by trying to understand what key distinction they're making between whatever __init__ is and constructors.

Putting that all together, the idiomatic translation of your PHP class would be simply the following:
class MyClass(object):
    def __init__(self, myMember):
        self.myMember = myMember


text:
Q: Is it possible to embed a cross-origin-isolated iframe inside a normal page? (For some people, this question may equal to "if I can't use sharedArrayBuffer in my main site, can I open an iframe and use sharedArrayBuffer inside the iframe?")
So I want to use some wasm with sharedArrayBuffer in my site, but it's impractical to make the site cross-origin-isolated, so I made another site https://my-wasm-function.app, which is cross-origin-isolated. I hope to use it as an iframe, and communicate with my main site via postMessage.
However, I found once it's embedded as an iframe, it loses the isolation status.
A similar question has been asked in March 2021, and the accepted answer was "No" at the time. However, a more recent google blogpost seems to imply otherwise, so I want to ask again.
The blogpost has some vague instructions about how to isolate an iframe, one is to add the header Cross-Origin-Resource-Policy: cross-origin (on top of COOP and COEP, I think), I tried it, didn't work. Another is to open the iframe like this: <iframe allow="cross-origin-isolated">, I tried it too, didn't work either.

A:
In other words, if I can't use sharedArrayBuffer in my main site, can I open an iframe and use sharedArrayBuffer inside the iframe?

No. The parent can't convey to iframe a capability is doesn't have.

cross-origin-isolated is a capability. It enables several features, like:

*

*Sharing a SharedArrayBuffer in between two workers.

*High definition timers.

*etc

As of March 2022:
You get the capability when the top-level document uses COOP:same-origin and COEP:require-corp or COOP:credentialless. For iframe, the parent must also "convey" the capability downward using "allow='cross-origin-isolated'".

A: The answer is no. Got confirmation from the author of that blogpost.
It's not very clear what <iframe allow="cross-origin-isolated"> achieves, maybe it can isolate an iframe without setting headers if the parent is isolated and the iframe's header is not in your control, but it'll definitely not keep the iframe isolated if the parent isn't. The blogpost author says he'll add some clarifications.


text:
Q: Limit and convergence/divergence of an integral I was working on a problem concerning the function $$f(x) = \frac{x^2}{\ln(x)^\sqrt{x}}$$ asking for the value of $$\lim_{x \to \infty}f(x)$$ and for the convergence/divergence of $$\int_2^\infty f(x) \ dx $$
I wasn't sure if my approach for the limit was entirely valid (or maybe too complicated): $$\lim_{x \to \infty} f(x) = e^{\lim_{x \to \infty} \ln(f(x))} = e^{\lim_{x \to \infty} 2\ln(x) - \sqrt x \ln(\ln(x))}$$ $$\sqrt x > \ln(x)$$ Hence: $$\lim_{x \to \infty} \ln(f(x)) = -\infty \ ; \lim_{x \to \infty} f(x) = e^{-\infty} = 0 \ .$$
As for the integral, I started out by taking the "sum comparison approach" and tried out the root and ratio tests, but those came out inconclusive. I suspect I could use the Limit Comparison Test somehow, but I couldn't find a sufficient "g(x)" to compare to.
Could someone validate/correct my solution for the limit and/or point me in the right direction on the integral question?
Thank you kindly.

A: For the limit, notice that $f (x)$ is bounded below by $y=0$. Next realize that for $x $ sufficiently large we have that $\ln x>x^{1/3}$ hence for large $x $ we have
$$0 <f (x)<g (x)=\frac {x^2}{x^{\sqrt {x}/3}}=x^{2-\sqrt {x}/3}$$
Then notice that for $x>81$ we have that $2-\sqrt {x}/3<-1$ (it equals $-1$ at $x=81$ and is decreasing from there on out). Hence for large $x $ we have $g (x)<1/x $. We conclude that for large $x $ we have
$$0 <f (x)<\frac {1}{x}$$
Thus by the Squeeze Theorem $f (x) $ converges to $0$.
For the integral notice that for large $x $ we have $f (x)<1/x^2$ which converges (to see this, look at the $g (x) $ we used to bound $f (x) $ and notice that the exponent is decreasing and it reaches $-2$).

A: Let $f(x)=\frac{x^2}{\log^{\sqrt{x}}(x)}$.  Then, we have
$$\begin{align}
\int_2^\infty f(x)\,dx&=\int_2^\infty \frac{x^2}{\log^{\sqrt{x}}(x)}\,dx
\end{align}$$
Enforcing the substitution $x\to x^2$ yields
$$\begin{align}
\int_2^\infty \frac{x^2}{\log^{\sqrt{x}}(x)}\,dx&=2\int_\sqrt{2}^\infty \frac{x^5}{\log^x(x^2)}\,dx\\\\
&=2\int_\sqrt{2}^\infty \frac{x^5}{2^x\log^x(x)}\,dx\\\\
&\le \frac2{\log^\sqrt 2(\sqrt 2)}\int_0^\infty x^5e^{-\log(2)x}\,dx\\\\
&= \frac{240}{\log^\sqrt 2(\sqrt 2)\log^6(2)}\\\\
&<\infty
\end{align}$$


text:
Q: Vim copying the line numbers? I am using vim through and SSH connection.  I have the numbers setting set, and so when ever I try to copy sections of my code with the mouse...it grabs the numbers also.  Is there a good way to copy text that doesn't grab the numbers with it.  (I know that with in that instance of vim I can use Y, but I need a way to copy to other instances and programs).
Here's an example of what I am talking about.
1 function foo ( home, ip, hash, regex )
2 {
3 return false;
4 }

Thank you all very much for the advice.

A: Toggle the 'number' setting with a !
:set nu!

Run it once to turn off 'number'. Run the command again to turn the setting back on.
I use the following mapping in my ~/.vimrc:
nnoremap <leader>tn :set nu! nu?<cr>

It will toggle the setting and then echo out the current value of 'number'
For more help see:
:h 'nu'
:h :set-!

A: :set nonumber

copy what you want
:set number

:help number

A: *

*If you copy and paste within Vim, there is no valid reason to not use the proper commands: y to "yank" (copy, see :help y) and p to "put" (paste, see :help p).

*If you copy in remote Vim to paste in another local app, you'll have to:
:set nonumber
do your thing
:set number

You might want to verify if you are able to use "X11 Forwarding" as it enables two-way clipboard sharing.

*If you copy in a local app to paste in remote Vim, you'll have to:
copy in local app
go to Vim
:set paste
Ctrl+v or Cmd+v
:set nopaste

See :help pastetoggle for a handy mapping.


text:
Q: spring boot 2.6.8 and elasticsearch 7.17.2 compatibility I want to customize springboot 2.6.8 elasticsearch dependency to elasticsearch 7.17.2, is this ok?
Based on springboot dependency versions, 2.6.8 is mapped to elasticsearch version 7.15.2.
But I want to changed it since elasticsearch version 7.15.2 has some deprecated functions.
How to do it?
the pom.xml I am using does not have spring-boot-starter-data-elasticsearch
and if I use it Maven cannot find it in:
  <repositories>
    <repository>
      <id>shibboleth_repository</id>
      <name>Shibboleth Maven Repository</name>
      <url>https://build.shibboleth.net/nexus/content/repositories/releases/</url>
    </repository>
  </repositories>

<properties>
   <java.version>17</java.version>
 </properties>
 <parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.6.8</version>
 </parent>
 <dependencies>
       :
       :
   <dependency>
     <groupId>org.elasticsearch</groupId>
     <artifactId>elasticsearch</artifactId>
   </dependency>
   <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>elasticsearch-rest-high-level-client</artifactId>
   </dependency>
       :
 </dependencies>

A:
I want to customize springboot 2.6.8 elasticsearch dependency to elasticsearch 7.17.2, is this ok?

One never knows until they try. The ElasticSearch version 7.17.2 contains backward-compatible changes 7.15.2, hence it should be ok.

How to do it?

Check the dependency trees:

*

*spring-boot-starter-parent:2.6.8

*

*spring-boot-starter-data-elasticsearch:2.6.8

*

*spring-data-elasticsearch:4.3.4

*

*org.elasticsearch.client:...:7.15.2
... and ...

*

*spring-boot-starter-parent:2.7.0

*

*spring-boot-starter-data-elasticsearch:2.7.7

*

*spring-data-elasticsearch:4.4.0

*

*org.elasticsearch.client:...:7.17.3
You might want either to update Spring Boot to 2.7.0 for full compatibility that imports transitive dependencies of ElasticSearch version 7.17.3 or override the versions: Exclude all the org.elasticsearch.client dependencies and import them as separate dependencies.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <exclusions>
        <!-- repeat for all ElasticSearch dependencies -->
        <exclusion>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>...</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- repeat for all ElasticSearch dependencies -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>...</artifactId>
    <version>7.17.2</version>
</dependency>


text:
Q: Angular / Ionic - controller only runs once I'm starting out with Angular through the Ionic Framework but I am failing to understand why the controller only runs once i.e. I change state, the controller runs, change to another state and then back again and the controller does not run a second time. This is my state:
$stateProvider.state( 'container.previous', {
    url: 'previous',
    views: {
        main : {
            templateUrl : 'views/previous.html',
            controller : function( $scope, $cordovaSQLite ){
                $scope.firms = [];
                $cordovaSQLite.execute(window.db, "SELECT * FROM recent GROUP BY phone ORDER by id DESC").then(function(res) {
                    for (i = 0; i < res.rows.length; i++) {
                        $scope.firms.push(res.rows.item(i));
                    }
                }, function (err) {
                    console.error(err);
                });
            }
        }
    },
    onStateChangeStart : function(){
        backButton = true;

    }
});

In another state, if you click on a button related to a "firm", it saves the "firms" data to local storage. The above state shows the firms in which you have previously clicked on. But I cannot figure out how to update the $scope.firms correctly as the controller never runs again.
Can anyone help me out?

A: Building on @brandyshea's answer, I would like to add if you want to specify no caching in one area/controller/state, and take advantage of the caching in other areas, you can simply use the cache parameter in your $stateProvider for that state.

Disable cache within state provider
$stateProvider.state('myState', {
  cache: false,
  url : '/myUrl',
  templateUrl : 'my-template.html'
})

Alternatively, you can use one of the other methods too:

Disable cache with an attribute
<ion-view cache-view="false" view-title="My Title!">
...
</ion-view>

Disable cache globally
  The $ionicConfigProvider can be used to set the maximum allowable views which can be cached, but this can also be use to disable all caching by setting it to 0.
$ionicConfigProvider.views.maxCache(0);

References: http://ionicframework.com/docs/api/directive/ionNavView/ and http://ionicframework.com/docs/api/directive/ionView/

A: You don't need to disable entire app cache.
If you want to re-run controller every time you enter on it you should clear cache before you leave it:
 $scope.$on("$ionicView.afterLeave", function () {
         $ionicHistory.clearCache();
 });

A: You can put the code you want to run in $ionicView.enter:
controller : function( $scope, $cordovaSQLite ){
    $scope.$on('$ionicView.enter', function() {
        // code to run each time view is entered
    });

    ...
});

See "View LifeCycle and Events": https://ionicframework.com/docs/v1/api/directive/ionView/

A: Ionic has a cache mechanism inside. You can disable caching globally in your config function like this :
$ionicConfigProvider.views.maxCache(0);

A: Put this in your ion-view.

<ion-view cache-view="false">


text:
Q: Sending Attchaments using MailCore2 on ios 8 I am not able to send attachments through MailCore2.
Can I use MailCore for ios 8?.
Can you please provide me the proper approach for it.
I want to send docx,pdf,xls,png and jpeg files in attachments

A: Loop through all attachments (file paths) and add them to the MessageBuilder:
MCOMessageBuilder *msgBuilder = [[MCOMessageBuilder alloc] init];

NSArray *allAttachments = @[@"/var/mobile/etc..", @"/var/mobile/etc2.."];

for (int x = 0; x < allAttachments.count; x++) {
    NSString *attachmentPath = allAttachments[x];
    MCOAttachment *attachment = [MCOAttachment attachmentWithContentsOfFile:attachmentPath];
    [msgBuilder addAttachment:attachment];
}

Example of the expected attachment path:
"/var/mobile/Containers/Data/Application/B47D8576-B38E-4864-AC76-8EBC630B6B44/Documents/IMG_0522.JPG"

A: To send an image as attachment in SWIFT just add:
    var dataImage: NSData?
    dataImage = UIImageJPEGRepresentation(image, 0.6)!
    var attachment = MCOAttachment()
    attachment.mimeType =  "image/jpg"
    attachment.filename = "image.jpg"
    attachment.data = dataImage
    builder.addAttachment(attachment)

A: With Swift 4 I had to write this code:
if let imageData = self.getImageData(filename: "pic.jpg") {
    var attachment = MCOAttachment()
    attachment.mimeType =  "image/jpg"
    attachment.filename = "image.jpg"
    attachment.data = imageData
    builder.addAttachment(attachment)
}

NSData is no more usable.


text:
Q: Plupload: Select files button doesn't work when it is inside a Bootstrap modal The Plupload 'Select files' button doesn't work when it's inside a Bootstrap modal.
The problem
The problem seems to exist on Apple devices only such as the iPad and iPhone. I've tested on a Samsung Galaxy S4 Mini running Android 4.2.2 and on a Nexus 7 tablet running Android 4.4.2 and both of those devices work.
Demo
Here's a demo to illustrate the problem (note you'll need to view on a iPad or iPhone in order to see the problem):
JSFIDDLE
Notes
Interestingly, if I move the following mark-up outside of the .modal element so that the 'Select files' button is visible on the initial page load, then the problem goes away.

    [Select files]
    [Upload files]

My question
How can I get the 'Select files' button working inside the modal for iPhone and iPad?

A: PLupload has issues rendering inside initially hidden elements. You should 'refresh' plupload after the dialog is shown.
Add this code right after uploader.init()
$('#myModal').on('shown.bs.modal', function () {
    uploader.refresh();
})


text:
Q: Индексы, отдельно для каждого поля или в одном В чем разница, создавать индекс для каждого поля отдельно и в один индекс напихать несколько полей?
Например, таблица users, я знаю, что поле email - уникально. Создаю на него индекс UNIQUE с именем UNIQUE email. У меня есть еще поле логин, которое по сути тоже уникально, что лучше создать для него отдельный UNIQUE или добавить в существующий там где email? Так же интересует есть ли смысл создавать UNIQUE на id, который PRIMARY?

A: Индексы необходимы для оптимизации запросов к БД, причем это нельзя назвать универсальной штукой. То есть, просто понавставлять индексов для каждого поля не принесет абсолютно никакой полезности.
Индексы строятся на основе запросов. Соответственно, Вы смотрите какие запросы у Вас используются наиболее часто или какие запросы наиболее "тяжелые", в общем именно те запросы, которые и грузят.
Например это запрос SELECT * FROM NEWS_TABLE WHERE DATE = NOW() - допустим он используется чрезвычайно регулярно и всеми (Новости), чтобы облегчить этот запрос достаточно использовать лишь индекс DATE. Однако, если модифицировать этот запрос на SELECT * FROM NEWS_TABLE WHERE DATE = NOW() AND CATEGORY = 'Politics', который будет использован не менее часто, то для него имеет смысл организовать связный индекс для DATE и CATEGORY, во втором случае будет лучше работать именно индекс DATE, CATEGORY, чем один индекс DATE или 2 несвязных индекса DATE и CATEGORY, то же самое относится и к другим операторам SQL запросов.
По поводу unique полей, тут все аналогично, все зависит от того, что именно Вам нужно. Если важно, чтобы в базе был один единственный Киркоров Филипп Бедросович (или любая другая комбинация ФИО), а данные хранятся в разных полях Secondname, Name, Surname, то Unique нужно задавать сразу для всех 3х полей одновременно, а не для каждого по отдельности. Если Вы создадите 3 отдельных Unique поля в данном случае, то на всю базу у Вас будет 1 Киркоров, 1 Филипп, 1 Бедросович.
Primary изначально уникальный, поэтому смысла нет.

A: Для того, чтобы понять, как работают индексы, полезно рассмотреть такую штуку, как телефонный справочник. В наше время практически не встречается, тем не менее, представление о нём есть почти у всех.
В телефонном справочнике перечислены абоненты, отсортированные сначала по фамилии, затем по имени.

*

*АНДРЕЕВ ИЛЬЯ, 22-31-97

*АНДРЕЕВА МАРИЯ, 22-45-11

*АНДРЕЕВ ПЁТР, 22-94-34

Вот три записи, а представим, что таких записей 100000. Сложно ли найти, где появляется первый Андреев? Нет: поскольку строки расположены в алфавитном порядке по фамилии. Выбрав произвольную запись мы быстро понимаем, до или после неё находится наша запись. Обычный двоичный поиск.
А сложно ли найти, где появляется первый Эммануил? Очень сложно, быстрого способа не существует. Нам придётся искать подряд с самого начала. И если Эммануила в данном городе не проживает, мы это узнаем только в самом конце.
А сложно ли найти, где появляется первый Андреев Пётр? Снова просто, потому что при совпадении фамилий справочник упорядочен по именам, значит, Пётр Андреев будет после Ильи Андреева, но раньше Сергея.
Практический вывод отсюда таков: если вам нужен поиск и по фамилии, и по имени, то потребуется два индекса. Условно говоря, потребуется два справочника: в первом телефоны будут упорядочены по фамилии, а во втором по имени.
А вот если нужен поиск по фамилии, или по фамилии и имени (именно в таком порядке), то подойдёт один справочник с составным ключом.
Отдельного разговора заслуживают уникальные индексы. Дело в том, что они не ускоряют поиск, но они обеспечивают целостность данных. Кроме того, уникальные индексы важны для реализации внешних ключей: внешний ключ может указывать только на уникальный индекс в другой таблице.
Поэтому полезно завести уникальные индексы и на поле электронный адрес, и на поле логин. Хотя в наше время лучше от поля логин отказаться и хранить только электронный адрес, иначе получается слишком сложно для пользователей.


text:
Q: TTThumbsViewController on a UIView Hi is it possible to add a TTHUmbsViewController on a UIView like
[UIView addSubView:TTHUmbsViewCOntroller.view]

?????

A: Like this is better :
TTHUmbsViewController* thumbsVC = [[TTHUmbsViewController alloc] init];
[yourView addSubview:thumbsVC.view];


text:
Q: How to show that addition is primitive recursive? How do i show in an example with numbers that addition is primitve recursive.
I understand why it is primitive recursive through the proof but I just can't imagine how it works primitive recursively with numbers.

A: To show that a function φ is primitive recursive, it suffices to provide a finite sequence of primitive recursive functions beginning with the constant, successor and projection functions and terminating with φ such that each function is constructed from prior functions by composition and primitive recursion. The primitive recursive addition function is defined
add(0,x)     = φ(x)
add(n + 1,x) = ψ(n,x,add(n,x))
  where φ = P[1/1]
        ψ = S ∘ P[3/3]

where P[m/n] is the m-ary projection function returning its nth argument for n >= 1 and n <= m. To demonstrate that add is primitive recursive, we must construct φ and ψ from the basic functions:
1. P[1/1]                [Axiom]
2. P[3/3]                [Axiom]
3. S                     [Axiom]
4. S ∘ P[3/3]            [1,3 Composition]
6. PR(P[1/1],S ∘ P[3/3]) [1,4 Primitive Recursion]

The function φ is provided by the axioms of primitive recursive functions. The function ψ is constructed by composition from the primitive recursive functions S and P[3/3] in step (4). Finally, the function add is constructed from φ and ψ in step (6) by primitive recursion. To see how a value is computed by a primitive recursive function such as add, it suffices to systematically substitute the right-hand sides of function definitions where appropriate, then simplify. I've collapsed substitution and simplification of composition in the following example:
add(2,3) = S(P[3/3](1,3,add(1,3)))                 [Def. ψ]
         = S(P[3/3](1,3,S(P[3/3](0,3,add(0,3)))))  [Def. ψ]
         = S(P[3/3](1,3,S(P[3/3](0,3,P[1/1](3))))) [Def. φ]
         = S(P[3/3](1,3,S(P[3/3](0,3,3))))         [Def. P[1/1]]
         = S(P[3/3](1,3,S(3)))                     [Def. P[3/3]]
         = S(P[3/3](1,3,4))                        [Def. S]
         = S(4)                                    [Def. P[3/3]]
         = 5                                       [Def. S]

It's unclear precisely what you're asking, so I gave a general overview of the primitive recursive definition of addition, the proof that addition is primitive recursive, and provided an example computation. If you're still unclear, it might be helpful to perform computations on small values of primitive recursive functions.


text:
Q: Getting the percentage of points within an area I'm new to ArcGIS and trying to gather the number of points and a percentage of those points within a somewhat small area. How would I do this or what would this be called? Spatial query? I have attempted to find information on this but have been unsuccessful.

A: To get the density of points per a user defined area use the Point Density tool in the Spatial Analyst toolbox.  You can find the documentation for the tool here.  To get the percentage of those points you could:

*

*Open the attribute table and see how many records were in your feature class.

*Then use the raster calculator to create a new raster layer with an expression like total_count/point_density_layer*100.  The resulting raster will be the percentage of points per user defined area.

Use caution and ensure you use the environment settings so your percentage raster outputs the same cell sizes and cell registration as your point density tool.
Your question asks multiple questions which violates the one-question policy. There are multiple steps that could each be their own question. Please take the GIS Stack Exchange tour to prevent your questions from being closed by site administrators in future posts.


text:
Q: start /B doesn't start the task I'm currently launching an asynchronous job with PHP to perform some tests.
To make it work, I found on SO some tips, like the use of popen and start:
$commande = "testu.bat";
$pid = popen('start /B ' . $commande, 'r');
$status = pclose($pid);

The testu.bat's folder is in my user PATH.
This script performs some task, and to control it's execution, it should generates a log file, but I never get it.
Whereas if I just remove the /B option, it works fine and I get my log file.
Did I miss something about background execution? How can I catch the error informations when it is running in the background?

A: It appears you are operating under the assumption that the /B switch to the start command means "background". It does not. From the start usage:
B           Start application without creating a new window. The
            application has ^C handling ignored. Unless the application
            enables ^C processing, ^Break is the only way to interrupt
            the application.

Processes launched by start are asynchronous by default. Since that appears to be what you want, just run the command without the /B switch.

A: Interesting one... Ok, here's what I think is going on:
Because you run the task in the background, the PHP script will just carry on, it is not waiting for testu.bat to return anything...
Or put another way, popen does what it was instructed to do, which is starting the task in the background (which it does) but then control is handed immediately back to PHP, whilst the log file is still being created in the background and the php script carries on at the same time...
What I would do in this case is let testu.bat call the php script (or another PHP script) in a callback type fashion once it has done its processing, in a similar way as in Javascript you would use callbacks for asynchromous Ajax calls...
Maybe provide the callback script command as a parameter to testu.bat..?
Hope this is of any help...

A: I'm not quite sure about your goal here, but here are some info you might use:
for figuring out background errors, you may find these functions useful:
set_exception_handler();
set_error_handler();
register_shutdown_function();

Of course write out the errors they catch into some file.
If you do not need any data back from your requests, you can simply use:
fsockopen()
curl

and give them a short timeout (10 milisec). The scripts will run in the backround.
Alternatively if you do need the data back, you can either put it into a database and set up a loop that checks if the data has already been inserted, or simply output it into a file and check for its existence.

A: In my opinion start launches the specified command by creating a new prcoess in the "background". Therefore the execution of start itself "just" starts the second process and exists immediately.
However, using the /B switch, the command to be executed will be excuted in the context of the start process. Therefore the execution of the start process takes longer. Now what I suspect is that executing pclose terminates the start process and as a result of this you don't get your log file.
Maybe one solution (not testet though) could be executing something like
start /B cmd "/C testu.bat" where start just tries to execute cmd and cmd gets /C testu.bat as parameter which is the "command" it shall execute.
Another thought:
What happens if you don't call $status = pclose($pid);?

A: Just for some people seeking this trick to works, in my case it just needs to activate the PHP directive ignore_user_abort in php.ini or by the PHP platform function.
Without this activated, the process is killed by pclose() without finishing the job.

A: Your problem is most likely properly solved by using a queue system. You insert a job into a queue that a background process picks up and works on. In this way the background task is completely independent of the HTTP request that initiated the task - but you can still monitor its progress.
The two most popular software packages that can help you in your scenario:

*

*Gearman

*

*Check out this gist and this totorial for installation on Windows.

*RabbitMQ

*

*Check out this tutorial for installation on Windows.

Note that implementing a queuing solution is not a 5 minute prospect, but it is technically the right approach for this sort of situation. For a company product this is the only viable approach; for a personal project where you just want something to work, there is a level of commitment required to see it through for the first time. If you're looking to expand your development horizons, I strongly suggest you give the queue a shot.


text:
Q: Why were the Romulans so blase about the Dominion after it gained a foothold in the Alpha Quadrant? Early on in season three the Romulans seemed to consider the Dominion a threat even though they were still on the other side of the wormhole, as shown by their actions in the following episodes:

*

*The Search, Part 1: loaning Starfleet a cloaking device (despite a certain clause in the treaty of Algernon) in exchange for intelligence gained about this newly discovered power,

*Visionary: sending a warbird to destroy DS9 so it couldn't stop them from sealing the wormhole entrance

*Improbable Cause & The Die is Cast: building a joint fleet with the Cardassians for the purpose of a sneak attack against the Dominion's rulers (this was the Tal'Shiar, the actual military was not party to this, but still).
However in season 5's A Call to Arms and most of season 6 the Dominion has come through the wormhole, gained control of the Cardassian Union, and is effectively winning against both the Federation and the Klingons (up until Sacrifice of Angels, anyway); yet the Romulans seem to have this naive "Oh they'll stop once they conquer those guys" attitude. It took the events of In the Pale Moonlight to get them involved and that was based on a deception by Sisko and Garak.
What I'm asking is: why did the Romulan Star Empire treat the Dominion more like a threat before it came nearer their side of the galaxy than they did after?

A: The Romulans enjoyed their Alpha Quadrant brethrens' plight and were happy to be part of a winning alliance rather than wage a possibly hopeless war.
At first, it was the shared belief of the Alpha Quadrant powers — Romulans included — that the Dominion could be reasoned with or, if necessary, defeated.  But it became increasingly clear that both outcomes might be impossible, given the resolve of the Founders and the stunning defeat of the Romulan / Cardassian surprise attack on the Founders' home world.
This would certainly lead to a shift in Romulan policy, towards using the Dominion to defeat the enemies of Romulus instead of trying to wage a possibly hopeless war against the Dominion.
Indeed, the Romulans have always enjoyed seeing the Federation and Klingons suffer, by pitting them against each other or finding other ways to weaken them.  The Romulans demonstrate this in Enterprise, Star Trek VI: The Undiscovered Country (the Romulans conspired to keep the Federation and Klingons at war), and in TNG (where they fuelled the Klingon Civil War and tensions with the Federation).  Watching the Dominion dismantle the Federation and the Klingon Empire would be ultimately very satisfying to the Romulans.
Finally, in the episode "In the Pale Moonlight", Senator Vreenak explains the position of the Romulan Star Empire to Sisko:

VREENAK: You are persistent, Captain, I'll grant you that, but dogged determination isn't enough to change the reality of your situation. Time is definitely not on your side. The Dominion shipyards are working at one hundred percent capacity. Yours are still being rebuilt. The Dominion is breeding legions of Jem'Hadar soldiers every day. You're experiencing a manpower shortage. But most important, the Dominion is resolved to win the war at any cost. You and I both know the Federation has already put out peace feelers. Now, in all candor, if you were in my position, which side would you choose?

In the same episode, Dax makes a similar analysis:

DAX: Think about it. They're in the perfect position. They get to sit back and watch as their biggest rivals slug it out in a long, bloody war. No one's threatening their interests. Why should they risk their necks? There's simply no reason for them to get involved in our war. No reason at all.


text:
Q: Confusion about the action variable definition Suppose we have an integrable system consisting of a $2n$-dimensional phase space $M$ together with $n$ independent functions $f_{1\leq j \leq n }$ in involution. Suppose the level set
$$M_f = \{ (p,q)\in M | f_k(p,q)= c_k \}, \text{where} \ c_k = \text{const.},$$
is compact so that it is diffeomorphic to a torus. The action variables are then defined as the circle integrals over the $n$ independent circles on the torus:
$$ I_k = \oint_{C_k} \sum_k p_k dq_k . $$
The apparent question is then, why do we bother to define a new set of variables, i.e. the action variables in this way? Why not just take the $f$'s as the action variable? Anyway, they are already in involution.

A: The circle integrals/action variables $I_k$ are e.g. used in the construction of the angle variables, cf. e.g. this related Phys.SE post.


text:
Q: How do i get old modification values in Realm Javascript when that data has been changed Hello Everyone!
To retrieve data I use Realm.objects(some_collection) method, then I am adding .addListener() method to watch changes that data in real-time, but Realm give an unexpected result where the result from .addListener() method is just an index of the data that has been changed NOT the value
Code
import Realm from 'realm';

const userdata = Realm.objects('user')[0]; // {name: 'Herry', age: 21}

/**
 * "collection" is "[object]" same as "userdata"
 * "changes" is an object
 */
userdata.addListener(function (collection, changes) {
  /**
   * All the result from "changes" param is just an "[index_the_data_that_has_been_changed]"
   *
   * If i want to get an old modification value with
   * "collection[changes.oldModifications[0]]" it just resulting a new value
   * NOT the old value :(
   */
  console.log(changes.insertions)
  console.log(changes.modifications)
  console.log(changes.oldModifications)
  console.log(changes.newModifications)
  console.log(changes.deletions)
});

Any idea

A: Use .snapshot() method to get the old value
import Realm from 'realm';

/* Use "let" not "const" */
let userdata = Realm.objects('user').snapshot();

Realm.objects('user').addListener(function (collection, changes) {
  /* get old value */
  const oldVal = userdata[changes.oldModifications[the_index]];
  console.log(oldVal);

  /* If you done get old value from "userdata" call again */
  userdata = Realm.objects('user').snapshot();
});


text:
Q: Browser Output using fread() I am new to PHP and was just trying to write and then read a html file with following code:
<?php
 #Aim: To open , write, save and close a file in PHP

 $fileName =  "myFile.html";

 $filePointer = fopen($fileName,"w+"); // Creating a file resource

 $html = '

This is some HTml that was written to the File using the
        file pointer $filePointer in the file that is named as myFile

      '; // string to be written to the file in write+ mode*/

  write($filePointer,$html); // writing the string to the file
  fseek($filePointer,0);

  $content = fread($filePointer,filesize($fileName));

  header("Content-Length:".(string)filesize($fileName));
  header("Content-Type:text/html");

  echo $content;

  fclose($filePointer); // closing the file resource
 ?>

I can see the out in the console but fail in the browser. file_get_contents($fileName) and readfile($fileName) work fine .
What is the problem.How can I use fread() to output to the browser ?


text:
Q: Need help to write a basic Command Line code I'm using Windows 10 if it matters and I'm trying to feed a file to the "oeminst" app that will convert this file from .EDR to .CCSS. According to the app's website its usage summary is this:
oeminst [-options] [inputfiles]
 -v                      Verbose
 -n                      Don't install, show where files would be installed
 -c                      Don't install, save files to current directory
 -S d                    Specify the install scope u = user (def.), l = local system]
 infile                  Manufacturers setup.exe install file(s) or .dll(s) containing install files
 infile.[edr|ccss|ccmx]  EDR file(s) to translate and install or CCSS or CCMX files to install
                         If no file is provided, oeminst will look for the install CD.

more info can be found here https://www.argyllcms.com/doc/oeminst.html

So far I tried this code:
C:\Users\PC>oeminst infile. [C:\Users\PC\testfile.edr]
oeminst: Error - Unable to load file 'infile [C:\Users\PC\testfile]'

I'd appreciate if someone at least could tell me if I'm doing it right or not.
P.S. sorry for the messed up text. Not sure how to fix it. It looks good in editing mode.

A: Try this : oeminst infile.edr C:\Users\PC\testfile.edr

A: Nevermind, I got it.
C:\Users\PC>oeminst C:\Users\PC\testfile.edr


text:
Q: Sampling Nested For Loop My loop knowledge is very minimal but I currently have a loop written, which takes values from three vectors (small.dens, med.dens, and large.dens) and each vector has 17 values. I have the loop setup to randomly select 2 values, then 3, then 4... all the way up to 17. Using these values, it calculates the mean and standard error (using the plotrix package). It then places these calculated means and standard errors into new vectors (small.density, small.stanerr, medium.density, medium.stanerr, large.density, and large.stanerr). Next, separately from the loop, I combine these vectors into a dataframe.
library(plotrix)

small.density = rep(NA,16)
small.stanerr = rep(NA,16)
medium.density = rep(NA,16)
medium.stanerr = rep(NA,16)
large.density = rep(NA,16)
large.stanerr = rep(NA,16)

for(i in 2:17){
  xx=sample(small.dens,i,replace=TRUE)
  small.density[[i]] = mean(xx)
  small.stanerr[[i]] = std.error(xx)
  yy = sample(med.dens, i, replace=TRUE)
  medium.density[[i]] = mean(yy)
  medium.stanerr[[i]] = std.error(yy)
  zz = sample(large.dens, i, replace=TRUE)
  large.density[[i]] = mean(zz)
  large.stanerr[[i]] = std.error(zz)
}

I then want to run this loop 100 times, ultimately taking the mean, if that makes sense. For example, I would like it to select 2,3,4...17 values 100 times, taking the mean and standard error each time, and then taking the mean of all 100 times. Does this make sense? Would I make another for loop, turning this into a nested loop?
How would I go about doing this?
Thanks!

A: There are other ways to achieve what you want, but if you do not want to change your code, then just wrap it in something like this
res <- do.call(rbind, lapply(1:100, function(x) {
  within(data.frame(
    n = x,
    size = 2:17,
    small.density = rep(NA,16),
    small.stanerr = rep(NA,16),
    medium.density = rep(NA,16),
    medium.stanerr = rep(NA,16),
    large.density = rep(NA,16),
    large.stanerr = rep(NA,16)
  ), {
    for(i in 2:17){
      xx = sample(small.dens,i,replace=TRUE)
      small.density[[i - 1L]] = mean(xx)
      small.stanerr[[i - 1L]] = std.error(xx)
      yy = sample(med.dens, i, replace=TRUE)
      medium.density[[i - 1L]] = mean(yy)
      medium.stanerr[[i - 1L]] = std.error(yy)
      zz = sample(large.dens, i, replace=TRUE)
      large.density[[i - 1L]] = mean(zz)
      large.stanerr[[i - 1L]] = std.error(zz)
    }
    rm(xx, yy, zz, i)
  })
}))

res looks like this
> head(res, 20)
   n size small.density small.stanerr medium.density medium.stanerr large.density large.stanerr
1  1    2   -0.04716195    0.35754422     13.1014925       4.374055    -42.089591      30.87786
2  1    3   -0.15893367    0.34557922     -0.2680632       6.206081     52.984076      36.85058
3  1    4    0.10013995    0.62374467     -0.1944930       5.784211   -112.684774      30.50707
4  1    5    0.40654132    0.40815013      1.6096970       5.026714     45.810098      46.58469
5  1    6    0.13310242    0.32104512     -6.9989844       4.232091    -22.312165      48.14705
6  1    7    0.21283027    0.53633472     -5.0702365       3.829677    -43.266482      41.74286
7  1    8    0.13870439    0.27161346      4.1629469       3.214053     -9.045643      48.49930
8  1    9    0.06495734    0.36738163      3.9742069       3.540913    -43.954345      38.23816
9  1   10   -0.01882762    0.37570468     -3.1764203       3.740403    -43.156792      38.47531
10 1   11   -0.02115580    0.26239465     -2.2026077       2.702412      7.343837      30.58314
11 1   12    0.09967753    0.27360125      3.9603382       3.214921    -13.461632      29.39910
12 1   13    0.53121414    0.27561862      4.3593802       1.872685    -38.572491      25.37029
13 1   14    0.21547909    0.36345292     -0.3377787       2.732968     17.305232      26.08317
14 1   15    0.33957964    0.23029520      0.4832063       2.886160      8.145410      18.23901
15 1   16    0.26871985    0.26846012     -6.7634873       3.436742     -4.011269      20.33814
16 1   17    0.24927792    0.20534048     -0.7481315       1.899348      9.993280      24.49623
17 2    2   -1.10840346    0.07123407     -3.4317644       6.966096    -30.384945     121.00972
18 2    3    1.73947551    0.35986535     -2.1415966       5.628115    -57.857871      10.47413
19 2    4    0.40033834    0.41963615     -4.2156733       1.206414     27.891021      13.84453
20 2    5   -0.08704736    0.52872770      0.3137693       2.974888     -3.100414      57.89126

If you want to calculate the mean of the 100 simulated values for each size, then just
aggregate(. ~ size, res[-1L], mean)

which gives you
   size small.density small.stanerr medium.density medium.stanerr large.density large.stanerr
1     2    0.02872578     0.6341294      1.0938287       5.518797      3.141204      53.20675
2     3    0.16985732     0.5388110     -0.1627867       5.185643     -6.660756      49.83607
3     4    0.20543404     0.4815581      0.1385016       4.519419     -8.093673      46.64984
4     5    0.13019280     0.4546794      0.1299331       4.166335    -10.300542      41.40444
5     6    0.10675158     0.4307113      0.2191516       4.033863    -12.068151      38.95312
6     7    0.19326831     0.3834507      0.8784275       3.513812     -6.920378      36.17856
7     8    0.09020638     0.3580780      0.4388388       3.443349     -5.335405      30.49615
8     9    0.13956838     0.3558005      0.3740251       3.313501    -15.290834      31.64833
9    10    0.18368962     0.3397191      0.4600761       3.051425     -5.505220      29.46165
10   11    0.20653866     0.3116104      0.9913534       2.804659     -8.809398      28.79097
11   12    0.14653661     0.2988422      0.3337274       2.624418     -5.128882      26.78074
12   13    0.12255652     0.2864998      0.2085829       2.719396    -11.548064      27.08497
13   14    0.13102809     0.2830709      0.6448798       2.586491     -4.676053      25.21800
14   15    0.14536840     0.2749606      0.3415879       2.522826    -11.968496      24.44427
15   16    0.14871831     0.2571571      0.2218365       2.463486    -10.335511      23.64304
16   17    0.13664397     0.2461108      0.3387764       2.348594     -9.969407      22.84736


text:
Q: how can I add row and columns in table heading in react material UI I am new to material UI and I am struggling to add columns in the table heading, I have provided an image I am trying to do like this, under the Economics there will be 3 columns also each column will take two more columns.

Here is my code:
   <Table sx={{ minWidth: 700 }} aria-label="customized table">
          <TableHead>
            <TableRow>
           <StyledTableCell align="left" scope="col">
                Economics
                <StyledTableCell align="left" scope="col">
                  1st
                  <StyledTableCell align="left">CQ</StyledTableCell>
                  <StyledTableCell align="left">MCQ</StyledTableCell>
                </StyledTableCell>
                <StyledTableCell align="left">
                  2nd
                  <StyledTableCell align="left">CQ</StyledTableCell>
                  <StyledTableCell align="left">MCQ</StyledTableCell>
                </StyledTableCell>
                <StyledTableCell align="left">
                  AVG
                  <StyledTableCell align="left">%</StyledTableCell>
                  <StyledTableCell align="left">GP</StyledTableCell>
                </StyledTableCell>
              </StyledTableCell>
            </TableRow>
          </TableHead>

The above code UI is like the below screenshot, it's too big and not aligned

I have used the scope="col" attribute inside the StyledTableCell but it's not working, is there anything that I am missing?
Thank you.

A: try adding this colSpan attribute
<StyledTableCell  colSpan={6}>
you can check it here. in the spanning section
https://mui.com/material-ui/react-table/
your code will look like this
   <Table stickyHeader aria-label="sticky table">
    <TableHead>
      <TableRow>
        <TableCell align="center" colSpan={6}>
          Economics
        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell align="center" colSpan={2}>
          1st
        </TableCell>
        <TableCell align="center" colSpan={2}>
          2nd
        </TableCell>
        <TableCell align="center" colSpan={2}>
          AVG
        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell align="center">CQ</TableCell>
        <TableCell align="center">MCQ</TableCell>
        <TableCell align="center">CQ</TableCell>
        <TableCell align="center">MCQ</TableCell>
        <TableCell align="center">%</TableCell>
        <TableCell align="center">GP</TableCell>
      </TableRow>
    </TableHead>
  </Table>


text:
Q: Need advice for Visualization of LdaMallet model I used a tutorial for analyzing a bigger corpus of academic articles, and ended up with LdaMallet model.
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=10, id2word=id2word)

I visualized it with pyLDAvis, which provided very nice results in HTML form.
from gensim.models.ldamodel import LdaModel
def convertldaMalletToldaGen(mallet_model):
    model_gensim = LdaModel(
        id2word=mallet_model.id2word, num_topics=mallet_model.num_topics,
        alpha=mallet_model.alpha) # original function has 'eta=0' argument
    model_gensim.state.sstats[...] = mallet_model.wordtopics
    model_gensim.sync_state()
    return model_gensim

ldagensim = convertldaMalletToldaGen(ldamallet)

import pyLDAvis.gensim as gensimvis
vis_data = gensimvis.prepare(ldagensim, corpus, id2word, sort_topics=False)
pyLDAvis.display(vis_data)

My problem now is that I cannot use HTML in my academic article. So, can someone suggest to me a way how to visualize LdaMallet model into a "static" plot?


text:
Q: how to search data using "like" in sql server I typed a word "boat", so i need records that start with boat and also that contains "boat".but starting with "boat" must appear first
i tried following
Select   AsiccCodeId,AsiccDescription
FROM     AsiccCodeMaster  c
WHERE    c.AsiccDescription like 'boat%' or c.AsiccDescription like '%boat%'

and
select a.* from
(

 Select   AsiccCodeId,AsiccDescription
 FROM     AsiccCodeMaster  c
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like 'Unmilled%'

 UNION

 Select   AsiccCodeId,AsiccDescription
 FROM     AsiccCodeMaster  c
 WHERE c.IsActive = 1  and (GoodFor = 'M' or GoodFor = 'B')
 and c.AsiccDescription like '%Unmilled%'

 )a

but it gives me
4137    Combustion Boats
6360    Boat, Fibre
6361    Boat, Rubber - Motorized
6362    Boat, Wooden Canal Boats
6363    Boat, Wooden With Engine
6370    Wooden Boats Body Building
6374    Boat, Rowing / Sports
6375    Boat, Rubber - Nonmotorized
6376    Boat, Wooden Without Engine-Others
6379    Parts Of Ships, Boats Etc., N.E.C
6391    Ships, Boats & Other Vessels, N.E.C
6394    Ships, Boats & Other Vessels, N.E.C

i need records that starts with "boat" first and then records that contains "boat"

A: You need to give your results some ordering!
SELECT a.*
FROM
(
    SELECT
       AsiccCodeId, AsiccDescription, Sequence = 1
    FROM AsiccCodeMaster  c
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE 'Boat%'

    UNION

    SELECT
       AsiccCodeId, AsiccDescription, Sequence = 2
    FROM AsiccCodeMaster  c
    WHERE c.IsActive = 1 AND (GoodFor = 'M' or GoodFor = 'B')
      AND c.AsiccDescription LIKE '%Boat%'
) a
ORDER BY a.Sequence

A: Use a CASE statement in an Order By clause
SELECT   AsiccCodeId,AsiccDescription
FROM     AsiccCodeMaster  c
WHERE    c.AsiccDescription like '%boat%'
ORDER BY CASE WHEN c.AsiccDescription like 'boat%' THEN 0 ELSE 1 END, c.AsiccDescription

Since you want titles that start with 'boat' to appear first, the CASE statement will prioritize those first.  It looks at each record and, if the description starts with 'boat', assigns it a sort value of 0, otherwise it assigns it a sort value of 1.  ORDER BY sorts ascending by default, so it will put all the 0s (the ones that start with 'boat') before all the 1s (the remaining records)


text:
Q: How to configure ingress to a service in kubernetes hosted on jelastic? Here's the thing. I installed a kubernetes cluster on my jelastic account like this:

Then, I wanted to expose a service to the outside of the cluster. The HelloWorld is working out-of-the-box on the cluster, so I thought I could transform it to my needs easily. Upon cluster installation, browsing
my-helloworld-test.my-jelastic-provider.com

works perfectly fine, i.e. I see the hello world html page with styling.
Now, in my future use-cases, I will want to access my services through
my-helloworld-test.my-jelastic-provider.com/hello

or
hello.my-helloworld-test.my-jelastic-provider.com

i.e. I'd like to setup a path for my service or a subdomain. I gathered I need to define an Ingress to make that happen. I've changed the hello-kubernetes service configuration to this:
kind: Service
apiVersion: v1
metadata:
  name: hello-kubernetes
  namespace: default
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
  selector:
    app: hello-kubernetes
  type: ClusterIP
  sessionAffinity: None
  externalTrafficPolicy: Cluster

Path to service
I tried following ingress configuration to define a path to my service:
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: helloworld
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/ssl-redirect: 'false'
spec:
  rules:
    - http:
        paths:
          - path: /hello
            backend:
              serviceName: hello-kubernetes
              servicePort: 80

The goal is that browsing
my-helloworld-test.my-jelastic-provider.com/hello

displays the pre-deployed helloworld application, instead of
my-helloworld-test.my-jelastic-provider.com

I could write the helloworld application in such a way that its base url be /hello, but I learned from several blogs that it is possible to let that happen with kubernetes annotations. In particular, it seems like annotation nginx.ingress.kubernetes.io/rewrite-target would help, but I was not able to make it happen completely. Indeed, the above configuration shows me the helloworld application when I browse the /hello path, but unstyled:

How can I make the styling happen?
Subdomain to service
Another sexy possibility for that service would be to be displayed upon browsing
hello.my-helloworld-test.my-jelastic-provider.com

i.e. as a subdomain of my jelastic environment. I've tried this configuration without success:
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: jenkins
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: 'false'
spec:
  rules:
    - http:
        paths:
          - host: hello.my-helloworld-test.my-jelastic-provider.com
            path: /
            backend:
              serviceName: hello-kubernetes
              servicePort: 80

What do I need to do to my jelastic environment so that the above host be browsable and exhibits the helloworld application?
Kubernetes configuration
Client Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.6", GitCommit:"7015f71e75f670eb9e7ebd4b5749639d42e20079", GitTreeState:"archive", BuildDate:"2019-11-19T09:00:01Z", GoVersion:"go1.12.12", Co
mpiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.6", GitCommit:"7015f71e75f670eb9e7ebd4b5749639d42e20079", GitTreeState:"archive", BuildDate:"2019-11-19T08:45:41Z", GoVersion:"go1.12.12", Co
mpiler:"gc", Platform:"linux/amd64"}

on jelastic v.5.7.

A: Looks like there are 2 separate issues atm

*

*Are you sure that domain
hello.my-helloworld-test.my-jelastic-provider.com is following to a
correct IP? It is possible to add custom subdomains to the
environment, then use them for ingress rules, but that option
(custom subdomains) is now available through the API only

*Incorrect annotation argument for nginx.ingress.kubernetes.io/rewrite-target, if you use nginx ingress controller try this one

kind: Ingress
apiVersion: extensions/v1beta1
metadata:
  name: helloworld
  namespace: default
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$2
    nginx.ingress.kubernetes.io/ssl-redirect: 'false'
spec:
  rules:
    - http:
        paths:
          - path: /hello(/|$)(.*)
            backend:
              serviceName: hello-kubernetes
              servicePort: 80

UPD:
We have additionally checked the issue together with Laurent Michel and discovered that problem was caused by absolute URIs in application so rewrite was not applied to CSS/images. Simplest solution - apply two ingress rules with different annotations (one with rewrite and one without). More advanced and correct way to go - shift such applications to separate subdomains so URIs could remain the same.


text:
Q: Rendering controller action in Yii layout I'm new to Yii and I'm trying to make an application where on every page I'll have some top rated news. My question is: how can you call a controller action in a layout file? In .Net MVC there is a fine function, where in the layout you can call Html.RenderAction("TopRated", "News"). Here in the News controller you call the TopRated action. The action then renders some partial view.
How can I do this in Yii?

A: You should create a widget and include it in your main layout. Not include it on every single view.

A: You can place that function in the main controller.php, in the components folder.
public function getTopRatedNews() {
    //
}

As the other controllers extend from that base controller, you can simply call this from the view:
$news = $this->getTopRatedNews();


text:
Q: "Divide by zero encountered in log" when not dividing by zero When I do:
summing += yval * np.log(sigmoid(np.dot(w.transpose(), xi.transpose()))) + (1-yval)* np.log(1-sigmoid(np.dot(w.transpose(), xi.transpose())))

where there is no division, why do I get a "divide by zero encountered in log" error? As a result, summing becomes [nan].

A: That's the warning you get when you try to evaluate log with 0:
>>> import numpy as np
>>> np.log(0)
__main__:1: RuntimeWarning: divide by zero encountered in log

I agree it's not very clear.
So in your case, I would check why your input to log is 0.
PS: this is on numpy 1.10.4

A: I had this same problem. It looks like you're trying to do logistic regression. I was doing MULTI-CLASS Classification with logistic regression. But you need to solve this problem using the ONE VS ALL approach (google for details).
If you don't set your yval variable so that only has '1' and '0' instead of yval = [1,2,3,4,...] etc., then you will get negative costs which lead to runaway theta and then lead to you reaching the limit of log(y) where y is close to zero.
The fix should be to pre-treat your yval variable so that it only has '1' and '0' for positive and negative examples.

A: Even though it's late, this answer might help someone else.
In the part of your code.
... + (1-yval)* np.log(1-sigmoid(np.dot(w.transpose(), xi.transpose())))

may be the np.dot(w.transpose(), xi.transpose()) function is spitting larger values(above 40 or so), resulting in the output of sigmoid( ) to be 1. And then you're basically taking np.log of 1-1 that is 0. And as DevShark has mentioned above, it causes the RuntimeWarning: Divide by zero... error.
How I came up with the number 40 you might ask, well, it's just that for values above 40 or so sigmoid function in python(numpy) returns 1..
Looking at your implementation, it seems you're dealing with the Logistic Regression algorithm, in which case(I'm under the impression that) feature scaling is very important.
Since I'm writing answer for the first time, It is possible I may have violated some rules/regulations, if that is the case I'd like to apologise.

A: Try to add a very small value, e.g., 1e-7, to the input. For example, sklearn library has a parameter eps for the log_loss function.
https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/discussion/48701


text:
Q: Access (VBA) Hiding/Protecting a single Module Is there a way to hide/protect a single module from the rest of all other modules?
For example, I have a Login Module that protects the front end of the Access but I need just the Login Module to be protected differently from all of my other modules.
I know that I can have the Protection and Lock project for viewing from My New App Properties. But this covers all the vba modules/class objects.

A: well you can certainly hide it from being displayed in the navigation/database window just like you can hide any other object. right-click, object-properties, then attributes-->check the hidden box. note that this won't hide it from the VB Editor, just the database nav window.
as far as password protection goes, no. it's all or nothing.
you can consider moving that module to an external database, and make it an mde/accde, and then set a reference to it. although, this could get you into all kinds of other problems you probably don't want to get into.


text:
Q: WebClient.DownloadString() result has encoding issues with some web sites! with persian(farsi) language I would like to open a web site and read source of that.
so I wrote this code:
WebClient client = new WebClient();
htmlCode = client.DownloadString("http://www.varzesh3.com");

but I got a garbage data.
I also add this codes but still it does not work.
client.Encoding = Encoding.UTF8; client.Headers.Add("charset", "utf-8");

In addition, I use this codes but none of them did not work:
byte[] raw = client.DownloadData("http://www.varzesh3.com");

string webData1 = Encoding.ASCII.GetString(raw);
string webData2 = Encoding.BigEndianUnicode.GetString(raw);
string webData3 = Encoding.Unicode.GetString(raw);
string webData4 = Encoding.UTF32.GetString(raw);
string webData5 = Encoding.UTF7.GetString(raw);
string webData6 = Encoding.UTF8.GetString(raw);

note:
I can open and read any other website which uses persian(farsi) language but I could not open www.varzesh3.com
could you please help me ?

A: The result of that site is compressed. You need to decompress it first. More info here. Now by using the custom MyWebClient, you will have:
using (var client = new MyWebClient { Encoding = Encoding.UTF8 })
{
    var test = client.DownloadString("http://www.varzesh3.com/");
}

A: It is because the website uses gzip to compress the output.
You should decompress it
using (var hc = new HttpClient())
using (var stream = await hc.GetStreamAsync(@"http://www.varzesh3.com/"))
using (var gzstream = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzstream))
{
    var text = await reader.ReadToEndAsync();
    // do what you want with text
}