text:
Q: Converting flat array to tree structure with javascript I have an issue with converting a flat array and could use your assistance!
Currently the data format is like this:
    [
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": null,
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 1,
            "OVERALL_MARKET_VALUE": 8
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
            "MARKET_VALUE": 10,
            "OVERALL_MARKET_VALUE": 5
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
            "MARKET_VALUE": 5,
            "OVERALL_MARKET_VALUE": 3
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 5,
            "OVERALL_MARKET_VALUE": 10
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1
        },
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
            "MARKET_VALUE": 10,
            "OVERALL_MARKET_VALUE": 5
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": null,
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 1,
            "OVERALL_MARKET_VALUE": 8
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
            "MARKET_VALUE": 10,
            "OVERALL_MARKET_VALUE": 5
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
            "MARKET_VALUE": 5,
            "OVERALL_MARKET_VALUE": 3
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 5,
            "OVERALL_MARKET_VALUE": 10
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
            "MARKET_VALUE": 10,
            "OVERALL_MARKET_VALUE": 5
        }
    ]

And I'm hoping to end up with a result like this:
    [
        {
            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
            "SUB_ACCOUNT_NAME": null,
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1,
            "children": [
                {
                    "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                    "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                    "TERTIARY_ACCOUNT_NAME": null,
                    "MARKET_VALUE": 1,
                    "OVERALL_MARKET_VALUE": 8,
                    "children": [
                        {
                            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
                            "MARKET_VALUE": 10,
                            "OVERALL_MARKET_VALUE": 5
                        },
                        {
                            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
                            "MARKET_VALUE": 5,
                            "OVERALL_MARKET_VALUE": 3
                        },
                    ]
                },
                {
                    "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                    "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                    "TERTIARY_ACCOUNT_NAME": null,
                    "MARKET_VALUE": 5,
                    "OVERALL_MARKET_VALUE": 10,
                    "children": [
                        {
                            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
                            "MARKET_VALUE": 6,
                            "OVERALL_MARKET_VALUE": 1
                        },
                        {
                            "MASTER_ACCOUNT_NAME": "MAIN_ENTITY",
                            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
                            "MARKET_VALUE": 10,
                            "OVERALL_MARKET_VALUE": 5
                        },
                    ]
                },
            ]
        },
        {
            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
            "SUB_ACCOUNT_NAME": null,
            "TERTIARY_ACCOUNT_NAME": null,
            "MARKET_VALUE": 6,
            "OVERALL_MARKET_VALUE": 1,
            "children": [
                {
                    "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                    "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                    "TERTIARY_ACCOUNT_NAME": null,
                    "MARKET_VALUE": 1,
                    "OVERALL_MARKET_VALUE": 8,
                    "children": [
                        {
                            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
                            "MARKET_VALUE": 10,
                            "OVERALL_MARKET_VALUE": 5
                        },
                        {
                            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                            "SUB_ACCOUNT_NAME": "MAIN_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
                            "MARKET_VALUE": 5,
                            "OVERALL_MARKET_VALUE": 3
                        },
                    ]
                },
                {
                    "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                    "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                    "TERTIARY_ACCOUNT_NAME": null,
                    "MARKET_VALUE": 5,
                    "OVERALL_MARKET_VALUE": 10,
                    "children": [
                        {
                            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_1",
                            "MARKET_VALUE": 6,
                            "OVERALL_MARKET_VALUE": 5
                        },
                        {
                            "MASTER_ACCOUNT_NAME": "SECOND_ENTITY",
                            "SUB_ACCOUNT_NAME": "SECOND_ACCOUNT",
                            "TERTIARY_ACCOUNT_NAME": "TERTIARY_ACCOUNT_2",
                            "MARKET_VALUE": 10,
                            "OVERALL_MARKET_VALUE": 5
                        },
                    ]
                },
            ]
        },
    ]

Apologies for the sheer size of it! The top level section will be MASTER_ACCOUNT_NAME, level after that will be SUB_ACCOUNT_NAME and the lowest level items will TERTIARY_ACCOUNT_NAME.
I've made numerous attempts to do this with lodash and vanilla javascript but have to concede that data manipulation is not really my area of skill and I'm struggling hard with it!
Thanks in advance for any help you can provide me!

A: This solution is specific for your example data and you might need to tweak it if you have other data shape.
Yet it's not recommended if you have like 1000 item.
function makeTree(data) {
  return data
    .filter(
      (masterItem) =>
        masterItem.SUB_ACCOUNT_NAME === null &&
        masterItem.TERTIARY_ACCOUNT_NAME === null
    )
    .map((masterItem) => ({
      ...masterItem,
      children: data
        .filter(
          (subItem) =>
            subItem.MASTER_ACCOUNT_NAME === masterItem.MASTER_ACCOUNT_NAME &&
            subItem.SUB_ACCOUNT_NAME !== null &&
            subItem.TERTIARY_ACCOUNT_NAME === null
        )
        .map((subItem) => ({
          ...subItem,
          children: data.filter(
            (tertiaryItem) =>
              tertiaryItem.SUB_ACCOUNT_NAME === subItem.SUB_ACCOUNT_NAME &&
              tertiaryItem.TERTIARY_ACCOUNT_NAME !== null
          ),
        })),
    }));
}

A: What about using javascript and lambdas to manipulate your array? Something like this:
const yourArray = [....];
const result = yourArray.filter(obj => obj['SUB_ACCOUNT_NAME'] == null);
result.forEach(node => node["CHILDRENS"] = yourArray.filter(obj => obj['SUB_ACCOUNT_NAME'] != null && obj['TERTIARY_ACCOUNT_NAME'] == null && obj["MASTER_ACCOUNT_NAME"] == node["MASTER_ACCOUNT_NAME"]));

This create a two level structure.. now , to generate the third, you would need to do something similar for each second level node.. it could be generalized with a function.. something like this:
function putChildrenFromArray(nodes, elements, howToSelectSons) {
  nodes.forEach(node => node["CHILDRENS"] = elements.filter(obj => howToSelectSons(obj, node)));
}

calling it like this:
putChildrenFromArray(result, yourArray, (obj, father) => obj['SUB_ACCOUNT_NAME'] != null && obj['TERTIARY_ACCOUNT_NAME'] == null && obj["MASTER_ACCOUNT_NAME"] == father["MASTER_ACCOUNT_NAME"])

and you could call it one for the second level.. then one once for each first level node, passing its childrens and, of course, changing the lambda / function used to select sons.
You should change minimal stuff between the two lambdas.. and you could generalize it even more if you can have even more levels.

A: You could combine reduce method with while loop and an array to store values on different levels that will be mapped from another levels object.

const data = [{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":null,"TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":6,"OVERALL_MARKET_VALUE":1},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":1,"OVERALL_MARKET_VALUE":8},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_1","MARKET_VALUE":10,"OVERALL_MARKET_VALUE":5},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_2","MARKET_VALUE":5,"OVERALL_MARKET_VALUE":3},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":5,"OVERALL_MARKET_VALUE":10},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_1","MARKET_VALUE":6,"OVERALL_MARKET_VALUE":1},{"MASTER_ACCOUNT_NAME":"MAIN_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_2","MARKET_VALUE":10,"OVERALL_MARKET_VALUE":5},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":null,"TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":6,"OVERALL_MARKET_VALUE":1},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":1,"OVERALL_MARKET_VALUE":8},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_1","MARKET_VALUE":10,"OVERALL_MARKET_VALUE":5},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"MAIN_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_2","MARKET_VALUE":5,"OVERALL_MARKET_VALUE":3},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":null,"MARKET_VALUE":5,"OVERALL_MARKET_VALUE":10},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_1","MARKET_VALUE":6,"OVERALL_MARKET_VALUE":1},{"MASTER_ACCOUNT_NAME":"SECOND_ENTITY","SUB_ACCOUNT_NAME":"SECOND_ACCOUNT","TERTIARY_ACCOUNT_NAME":"TERTIARY_ACCOUNT_2","MARKET_VALUE":10,"OVERALL_MARKET_VALUE":5}]

const result = []
const levels = [
  'MASTER_ACCOUNT_NAME',
  'SUB_ACCOUNT_NAME',
  'TERTIARY_ACCOUNT_NAME'
]

data.reduce((r, e) => {
  let value = { ...e, children: [] }
  let level = levels.length

  while (level--) {
    if (e[levels[level]]) {
      r[level + 1] = value.children
      r[level].push(value)
      break
    }
  }

  return r;
}, [result])

console.log(result)


text:
Q: SonarQube Dashboard - Can I show just the leaks I'm using the latest version of SonarQube.  Is it possible to display the front "Projects" dashboard with just covering the leaks period?

A: This is not possible in SonarQube 6.3, but it will be implemented in SonarQube 6.4 for sure.
You can watch the ticket SONAR-8912 that we'll soon start working on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ordering of gallery images without using shortcode in theme I using the built-in gallery in wordpress to store and sort images inside a custom post type. In the theme I was using:
$attachments = get_posts(
                 array('post_type' => 'attachment',
                       'post_parent' => $post->ID,
                       'orderby' => 'menu_order'
                 )
);

The above code returns the gallery images correctly, but in the wrong order. When I look at the content field for the post containing the gallery, it contains the gallery data:
[gallery ids="2,5,7,8"]

So, my guess is that the built-in gallery doesn't store the sorting in a separate field like menu_order instead it stores a sorted list of attachment ids in the content field of the parent post.
So my question is what would be the best way to get the gallery images sorted correctly from the theme?
I tried something like:
$matches = array();
if(preg_match('/ids="(.*)"/', $post->post_content, $matches)) {
    $ids = $matches[1];

    $query = "SELECT * FROM $wpdb->posts ".
             "WHERE post_type = 'attachment' &&
                    post_parent = $post->ID ".
             "ORDER BY FIELD(ID, $ids)";
    $attachments = $wpdb->get_results($query);
 }

This seems to work but is there a cleaner way of doing this.

A: You are correct.
The menu_order is no longer used for media in the gallery. Not sure if this is by design or an oversight. Could be by design since you can now include media in a gallery even if it is not "attached" to the page/post. In any case, below is the method I use to grab the ids and get the attachments based on the order specified in the shortcode:
// helper function to return first regex match
function get_match( $regex, $content ) {
    preg_match($regex, $content, $matches);
    return $matches[1];
}

// Extract the shortcode arguments from the $page or $post
$shortcode_args = shortcode_parse_atts(get_match('/\[gallery\s(.*)\]/isU', $post->post_content));

// get the ids specified in the shortcode call
$ids = $shortcode_args["ids"];

// get the attachments specified in the "ids" shortcode argument
$attachments = get_posts(
    array(
        'include' => $ids,
        'post_status' => 'inherit',
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'order' => 'menu_order ID',
        'orderby' => 'post__in', //required to order results based on order specified the "include" param
    )
);

Hope that helps!


text:
Q: How to Import local text file to populate drop downs with FileReader() I'm kind of stuck on a problem, I'm trying to import a text file from my local computer to JavaScript and populate HTML drop down's according to the text file. I have spent a lot of time looking at similar questions on stack overflow and i haven't found the solution to the problem yet. Here is an example of what the text file looks like:
 Dogs -
 Blue Dog
 Black Doggo
 Random Doggo

 Cats -
 Neon cat
 Grumpy cat
 Potato cat

Here is what my JS looks like:
    function LoadTxtFile(p) {
        var AllTxtdata = '';

        var FileRead = new FileReader();
        FileRead.onload = function (e) {
            if (FileRead.readyState === 2) {

                AllTxtdata = FileRead;
                var lines = FileRead.result.split('\n').map(function (line) {
                    return line.trim();
                });

                var select = $("select[name=MySelect]");
                var optionCounter = 0;
                var currentGroup = "";
                lines.forEach(function (line) {

                    if (line.endsWith(" -")) {
                        currentGroup = line.substring(0, line.length - 2);
                        optionCounter = 0;
                        select.append("<optgroup id'" + currentGroup + "' label='" + currentGroup + "'>");
                    } else if (line === "") {
                        select.append("</optgroup>");
                    } else {
                        select.append("<option type='checkbox' id='" + (currentGroup + optionCounter) + "' name'"
                            + (currentGroup + optionCounter) + "' value='"
                            + line + "'>" + line + "</option>");
                    }

                });
            };
        }

    }

HTML
    <div class="Bark">

    <input type="file" id="file" />
     </div>

i'm trying to populate HTML dropdown select "MySelect" with an option group and options.

A: You're missing couple of things in your code.

*

*Attach the event to the file control.

*Read the actual file from within the function.

Here, I have created a Fiddle using your own code. Below, I am only highlighting the lines of code that, I have added there. Rest of the code is same.
Get the target file first, inside LoadTxtFile().
var targetFile = p.target.files[0];

Once, it's established, that there are files, start reading the file in the last line.
FileRead.readAsText(targetFile);

Finally, outside the method declaration, attach the event to the file control.
document.getElementById('myFile').addEventListener('change', LoadTxtFile, false);


text:
Q: What is the subject of this sentence? While discussing a piece of scientific writing today, I was confused about the subject (and therefore the singular/plural state) of this sentence.

The presence of very high cell densities in the embryoid body outgrowths makes accurate quantitation of adipogenesis difficult.

What is the subject in this sentence? Is it "presence" or "densities"? What are some rules that I can use to determine the subject of similar sentences?

A: Remove  the prepositional phrase of very high cell densities in the embryoid body outgrowths from the sentence and what is the subject? That word  is still the subject with the prepositional phrase in the sentence.
In addition, which word (presence or densities)  shows subject-verb agreement? Makes is used for third person singular nouns.

A: Ditto AlanCarmack. In general, when searching for a subject or verb, it is ofteen helpful to drop out qualifying words and phrases. Drop any adjectives or adverbs, and then any phrase that starts with a preposition, like "of ...", "to ...", "for ..." etc. What's left should be the "heart" of the sentence.


text:
Q: Implement \$x^{\gamma}\$ function using op amps Is there a way to implement \$f(x) = x^{\gamma}\$ for a fixed (most conveniently, adjusted by a pot) value of \$\gamma\$, using op amps or other analog circuitry?
What I want is for the circuit to take an input voltage \$x\$V between 0V and 1V, and output the voltage, say, \$x^{2.2}V\$. A possible use-case for this would be properly gamma-corrected control of light intensity (since the commonly used log/antilog approach is considered less accurate in relation to human perception)

A: A few possibilities:

*

*Log->gain->Antilog (variable gain with a pot is easy and does not require an expensive multiplier chip)
eg. \$e^{\ln(x)\cdot\gamma} = x^{\gamma}\$
Log-antilog circuits (typically using a transistor junction as a fairly ideal diode) have various challenges such as temperature sensitivity, required trimming, and frequency response that varies with signal.

*Your exponent is close to 2 so using the FET characteristic Id \$\approx (V_{\text{gs}}-V_{\text{t}})^2\$ is a possibility.

*Use a precision on-chip trimmed multiplier chip as a squarer to get an accurate characteristic without trimming. More multiplier chips could be used to generate a series approximation, but that gets expensive.

*Piecewise linear approximation, with diodes and resistors (not easily adjustable).

A: No it is not possible with opamps and resistors. These are linear components and can only implement linear functions of the inputs (so multiplication by a constant, add a value, integrate or differentiate etc.). These constants can be dependent on resistor values, but there is no simply way to make the effective resistor value depend on another signal.
There are a few methods commonly used to achieve what you want:

*

*Bipolar transistors have an exponential relationship between base-emitter voltage and collector current. This can be used to develop voltages proportional to the logarithm of a signal, and this in turn can be used to generate an output dependent on the logarithm. This does allow a multiplication or power-law (or exponential) function to be implemented. ICs are available (https://www.analog.com/en/products/analog-functions/analog-multipliers-dividers.html).

*MOSFETs have a square-law characteristic (drain current depends on the square of VGS), but this is not extremely accurate in most MOSFETs, and so is seldom used to implement multiplication functions.

*The signals can be digitized with an ADC, the mathematical function implemented in software and converted back to an analog signal with a DAC.


text:
Q: clang: error: the clang compiler does not support '-march=corei7-avx' I am getting the following error when installing the rasa==3.2.8 python package.
I am using a Macbook M1 pro machine.
Error I am getting is: clang: error: the clang compiler does not support '-march=corei7-avx'
Since I am using M1 Max processor, why it is picking up corei7-avx?
Traceback (most recent call last):
        File "<string>", line 1, in <module>
        File "/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/setup.py", line 239, in <module>
          setup(
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/__init__.py", line 87, in setup
          return distutils.core.setup(**attrs)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 185, in setup
          return run_commands(dist)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 201, in run_commands
          dist.run_commands()
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 973, in run_commands
          self.run_command(cmd)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/dist.py", line 1217, in run_command
          super().run_command(command)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 992, in run_command
          cmd_obj.run()
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/command/install.py", line 68, in run
          return orig.install.run(self)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/command/install.py", line 698, in run
          self.run_command('build')
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 319, in run_command
          self.distribution.run_command(command)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/dist.py", line 1217, in run_command
          super().run_command(command)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 992, in run_command
          cmd_obj.run()
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/command/build.py", line 132, in run
          self.run_command(cmd_name)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 319, in run_command
          self.distribution.run_command(command)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/dist.py", line 1217, in run_command
          super().run_command(command)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 992, in run_command
          cmd_obj.run()
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/site-packages/setuptools/_distutils/command/build_ext.py", line 346, in run
          self.build_extensions()
        File "/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/setup.py", line 103, in build_extensions
          objects = self.compile_objects(compiler.split("-")[0], arch, OBJ_DIR)
        File "/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/setup.py", line 188, in compile_objects
          objects.append(self.build_object(env=env, **spec))
        File "/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/setup.py", line 201, in build_object
          subprocess.check_call(command, cwd=BLIS_DIR)
        File "/Users/avirajkhare/.pyenv/versions/3.8.10/lib/python3.8/subprocess.py", line 364, in check_call
          raise CalledProcessError(retcode, cmd)
      subprocess.CalledProcessError: Command '['clang', '-c', '/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/blis/_src/kernels/sandybridge/3/bli_gemm_sandybridge_asm_d8x4.c', '-o', '/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/tmp7n00zegk/bli_gemm_sandybridge_asm_d8x4.o', '-O3', '-mavx', '-mfpmath=sse', '-march=corei7-avx', '-fPIC', '-std=c99', '-D_POSIX_C_SOURCE=200112L', '-DBLIS_VERSION_STRING="0.5.1"', '-DBLIS_IS_BUILDING_LIBRARY', '-Iinclude/darwin-x86_64', '-I./frame/3/', '-I./frame/ind/ukernels/', '-I./frame/1m/', '-I./frame/1f/', '-I./frame/1/', '-I./frame/include', '-I/private/var/folders/l5/7tbnm_3d2f1_hdm70q95lbpc0000gn/T/pip-install-bfyhfasf/blis/blis/_src/include/darwin-x86_64']' returned non-zero exit status 1.


text:
Q: Ionic 2 Http POST Method ERROR Hi Im going to call http post method using ionic 2.but in the response always im getting error.can any one help me.
this is my json type
{
"username":"user",
"password":"pass"
}

This is my code
import {Page, NavController} from 'ionic-angular';
import {Http, Headers, RequestOptions} from 'angular2/http';
import 'rxjs/Rx';
@Page({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  constructor(http: Http, nav: NavController) {
    this.http = http;
    this.makePostRequest();
  }

  makePostRequest() {

    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('url',
      JSON.stringify({ username: 'admin', password: 'a' }),
      { headers: headers })
      .map((res: Response) => res.json())
      .subscribe((res) => console.log("res", res));

  }

}

error Log
4     236980   log      DEVICE READY FIRED AFTER, 1437, ms
5     237420   group    EXCEPTION: [object Object]
6     237426   error    EXCEPTION: [object Object]
7     237431   error    STACKTRACE:
8     237433   error
9     237435   groupEnd
10    237525   error    Uncaught #<Response>, http://192.168.1.13:8100/build/js/app.bundle.js, Line: 7834

How can i solve this.?
I added the error handling
this is the log in browser
Failed to load resource: the server responded with a status of 403 (Forbidden)
(index):1 XMLHttpRequest cannot load http://url/login/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 403.
app.bundle.js:67773 error Response_body: ProgressEventbubbles: falsecancelBubble: falsecancelable: falsecurrentTarget: XMLHttpRequestonabort: undefinedonerror: undefinedonload: undefinedonloadend: undefinedonloadstart: undefinedonprogress: undefinedonreadystatechange: undefinedontimeout: undefinedreadyState: 0response: ""responseText: ""responseType: ""responseURL: ""responseXML: nullstatus: 0statusText: ""timeout: 0upload: XMLHttpRequestUploadonabort: nullonerror: nullonload: nullonloadend: nullonloadstart: nullonprogress: nullontimeout: null__proto__: XMLHttpRequestUploadconstructor: XMLHttpRequestUpload()arguments: nullcaller: nulllength: 0name: "XMLHttpRequestUpload"prototype: XMLHttpRequestUploadconstructor: XMLHttpRequestUpload()arguments: nullcaller: nulllength: 0name: "XMLHttpRequestUpload"prototype: XMLHttpRequestUpload__proto__: XMLHttpRequestEventTarget()<function scope>onabort: (...)onerror: (...)onload: (...)onloadend: (...)onloadstart: (...)onprogress: (...)ontimeout: (...)Symbol(Symbol.toStringTag): "XMLHttpRequestUpload"__proto__: XMLHttpRequestEventTarget__proto__: XMLHttpRequestEventTarget()<function scope>onabort: (...)onerror: (...)onload: (...)onloadend: (...)onloadstart: (...)onprogress: (...)ontimeout: (...)Symbol(Symbol.toStringTag): "XMLHttpRequestUpload"__proto__: XMLHttpRequestEventTargetwithCredentials: false__proto__: XMLHttpRequestdefaultPrevented: falseeventPhase: 0isTrusted: trueisTrusted: truelengthComputable: falseloaded: 0path: Array[0]returnValue: truesrcElement: XMLHttpRequesttarget: XMLHttpRequesttimeStamp: 2726.8050000000003total: 0type: "error"__proto__: ProgressEventheaders: Headers_headersMap: Mapsize: (...)__proto__: Map<entries>[0]No Entries__proto__: Objectstatus: 200statusText: "Ok"type: 3url: null__proto__: ObjectarrayBuffer: ()blob: ()constructor: Response(responseOptions)arguments: [Exception: TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
    at Function.remoteFunction (<anonymous>:3:14)]caller: (...)length: 1name: "Response"prototype: Object__proto__: ()<function scope>json: ()arguments: (...)caller: (...)length: 0name: ""prototype: Object__proto__: ()<function scope>text: ()__proto__: Object

A: It seems that you have a cross origin problem:
XMLHttpRequest cannot load http://url/login/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 403.
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
You need to allow your client domain on the server side by using proper headers


text:
Q: Launch Fragment on notification click without losing state I have chat app where is also launched directly by notification click. Chat fragment also launches manually by click inside the app.
I want if user tap home button while on chat fragment and then click on the notification, it should launch in the last state and don't call activity's onDestroy then onCreate.
Launch Fragment by notification in Activity like this.
((AppCompatActivity)context).getFragmentManager().beginTransaction().replace(R.id.Navigation_Main_Layout, screenFragment,"Chat").commit();

I am handling the notification from FirebaseMessagingService
public class FireBase_Messaging_Service extends FirebaseMessagingService {

    public static final String TAG="###FireBase MSG###";
    public static final int NOTIFICATION=5;
    String UserName;
    String ID;
    String Msg;

    Map<String,String> data;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d(TAG,"From "+remoteMessage.getFrom());
        if (remoteMessage.getData().size()>0){
            data = remoteMessage.getData();
            Log.d(TAG,"Message Data "+remoteMessage.getData());
            data = remoteMessage.getData();

            UserName = data.get("name");
            ID = data.get("ID");
            Msg = data.get("Message");

            showNotification(Msg,ID,UserName);
        }

        if (remoteMessage.getNotification()!=null){
            Log.d(TAG,"Message Notification Body "+remoteMessage.getNotification().getBody());
           // Toast.makeText(this, "Notification "+remoteMessage.getNotification().getBody(), Toast.LENGTH_LONG).show();
        }
    }

    private void showNotification(String Message,String ID,String UserName) {
        Log.d(TAG,"Show Notification "+Message+" "+ID);
        Intent intent=new Intent(this, Navigation_Drawer.class);
        intent.putExtra("Type","Text");
        //intent.putExtra("Type",MsgType);
        intent.putExtra("ID",ID);
        intent.putExtra("uname",UserName);
        intent.putExtra("Message",Msg);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,NOTIFICATION,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        int color = getResources().getColor(R.color.black);
        String ChannelID = "Message";
        notificationChannel(ChannelID,"Chat");
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),ChannelID)
                .setSmallIcon(R.drawable.default_x)
                .setColor(color)
                .setContentTitle(UserName)
                .setContentText(Message)
                .setChannelId(ChannelID)
                .setTicker("My App")
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS)
                .setLights(0xff00ff00, 1000, 500) // To change Light Colors
                .setStyle(new NotificationCompat.BigTextStyle().bigText(Message))//For Expandable View
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
        managerCompat.notify(NOTIFICATION,builder.build());
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }

    private void notificationChannel (String ChannelID, String channelName) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel  channel = new NotificationChannel(ChannelID,channelName, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLightColor(Color.GREEN);
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

In above code, I tried Intent with different flags, such as Intent.FLAG_ACTIVITY_NEW_TASK,Intent, FLAG_ACTIVITY_SINGLE_TOP, FLAG_ACTIVITY_BROUGHT_TO_FRONT, FLAG_ACTIVITY_CLEAR_TOP etc. However, it always calls activity's (Navigation Drawer) onDestroy first and then onCreate. Then it launches fragment from start.
How can I avoid app to recreate Activity and Fragment?

A: As per my knowledge, the desired behaviour from Android activity conflicts with the Android lifecycle of the activity and fragment. When the user presses the back or home button, the activity or fragment will go through the onPause and onDestroy following the life cycle of that activity or fragment instance. There is no way you can avoid it unless you are calling a finish in your activity which avoids the onDestroy function call in an activity. However, you do not want to finish the activity, you want to use the same activity and want that activity not to be recreated.
So I was thinking of a different way of solving your problem. Mostly the problem with recreating an activity or fragment directly indicates to the resources to be fetched and for heavy resources to be fetched while initializing an activity or fragment is an overhead. So we might avoid fetching the resources to be used in an activity or fragment when the resources are already available in the saved instance state.
For example, when you are fetching some data saved in a SQLite database in the onCreate function of your activity, you might do not want to fetch it again on orientation changes of your activity, which forcefully recreates the activity. In that case, you might need to choose a loader (I am talking about CursorLoader with the implementation of LoaderCallbacks) which survives the Activity recreation. The implementation with the loader will not fetch the data again from SQLite database if fetched already and will serve the data on recreating an activity.
Another beautiful thing that I want to recommend is to use ViewModel. You may find the documentation here explaining the implementation. ViewModel survives the Activity recreation you can save the instance state using a ViewModel which will reduce the load time.
The whole point is, you might not be able to trick the lifecycle functions, but you might choose using data models which will survive the recreation of your activities and fragments.

A: I was loading activity and fragment at first launch without any flags. When i receive notification i was adding a flag which make activity to call onDestroy first then onCreate.
I add android:launchMode="singleTask" in Manifest file under activity tag whenever activity first create. It helps me to avoid recreate Fragment in Activity.
 <activity
            android:name=".Navigation_Drawer"
            android:launchMode="singleTask"
            android:theme="@style/AppTheme"/>


text:
Q: How to set up a server that others on my work network can access using node.js? I'm very new to node.js, I've created a server two ways.
One way like this:
server.js:
var connect = require("connect");
var serveStatic = require("serve-static");
connect().use(serveStatic(__dirname)).listen(8080);

node.js cmd line:
H:\> npm install connect serve-static
H:\> node server.js

And the other way like this
H:\> npm install http-server -g
http-server "C:\directory"

But these just create servers on my computer at http://localhost:8080. How can I adjust this code to make the server accessible for other people on my work network?
Thanks in advance.

A: The server is accessible from your network already.  Just use your IP address or real hostname.
http://203.0.113.1:8080/


text:
Q: Get Value of dynamically create dropdownlist in JSP I am new to JSP and servlet for 1 month, and there are many things that I am still unsure off.. Inside a JSP, I have a dropdownlist(the values inside are grab from database) and it would be dynamically created on the number that the user keyed in. Example, the user key in 3, this digit would store in session, and 3 dropdownlist would be generated.
I am able to do this, however I am unable to grab the value of all the 3 dropdownlist in a servlet. and instead of getting 3 diff values, the output repeat the value of the first dropdownlist. Example "john,john,john" instead of "john, ken, andy".
JSP code:
    <form action="Adding" method="post">
    <%
    session = request.getSession();
    ProjectGroup projGrp1  = (ProjectGroup)session.getAttribute("PROJECTNAME");

    //getMaxMember is the int that user keyed in
    int staff =projGrp1.getMaxMember();

    for(int i = 0; i < staff; i++) {
     %>

     <select name="list1"  >

     <%@page import="sit.bean.*,sit.data.*"%>

    <%
    GroupTaskManager mgr3 = new GroupTaskManager();

    GroupTask[] at3 = mgr3.getCheckBox();
    for(int g = 0; g < at3.length; g++) {
    %>

  <option><%=at3[g].getStaffName()%></option>

 <%
  }
  %>
  </select>

  <%
  }
  %>
 <input type="submit" name="submit">
 </form>

In servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     HttpSession session = request.getSession();
    ProjectGroup projGrp = (ProjectGroup)session.getAttribute("PROJECTNAME");

            int member =  projGrp.getMaxMember();

    String total = null;
    for(int i=0; i< member; i++)
    {
        String names = request.getParameter("list1");
        total += names + " , ";
    }

    PrintWriter pw = response.getWriter();

    pw.write("");
            pw.write(total);
            pw.write("");

    pw.close();

}

Can i set the downdownlist name like "list<%i%>", to set different id to each downdownlist? therefore i can retrieve each of them seperately???

A: In servlet you are getting same parameter every time which is list1 in loop.
and also in JSP creating dropdownlist with same name attribute,
that's why you are getting john,john,john instead of john, ken, andy.
Yes you can use list<%i%> to set different id as well as name
change your select with below in JSP
<select name="list<%=i%>"  >

and for loop in servlet with below
for(int i=0; i< member; i++)
{
    String names = request.getParameter("list1"+i);
    total += names + " , ";
}


text:
Q: Update By Query to update multiple fields at a time in elastic search i have a use case of update by query in elastic search.
I am keeping a doc like -
"a" : "1",
"b" : "2",
"version1" : 456
"c" : {
   "version2" : 123,
   "d" : "3"
}

Now dependently for my use case-

*

*I either want to update field a, b and version1

*Or I will update field d and version2.

I got partial answer in Update By Query in Elasticsearch using Java.
I am trying things like this-
    BulkIndexByScrollResponse r = ubqrb.script(script)
        .script(script1)
        .script(script2)
        .script(script3)
        .script(script4)
        .filter(qb).get();

However UpdateByQueryRequestBuilder doesn't allow me to give multiple scripts and only and last one, ie script4 is used and rest are neglected.
I also tried -
    Script script4 = new Script("ctx._source.a=\"abc\",b=\"xyz\"");

However this one also failed.
Any idea what can be done using update by where.
Thanks in advance

A: Try :
new Script("ctx._source.a=\"abc\"; ctx._source.b=\"xyz\"");


text:
Q: How to solve " C:\msys64\mingw64\bin\python.exe: can't open file " error? I am getting error when I want to run my python script in terminal which says...
C:\msys64\mingw64\bin\python.exe: can't open file

Possible Problem Cause:
I have installed MSYS2 in my machine so that I can use g++ and gcc compilers for C/C++ Programs and to use g++ and gcc I needed to add C:\msys64\mingw64\bin path to system environment variables.
C:\msys64\mingw64\bin folder has python.exe in it; so I am guessing that it is causing some kind of collision between my python interpreter and C:\msys64\mingw64\bin's python.exe
When I remove C:\msys64\mingw64\bin path from system Environment variables, I am getting expected output.
What do I want?
I want a solution in which I can keep using both, python and g++/gcc.

A: I reordered paths in System/User's environmental variables and now I am getting what I needed.


text:
Q: ViewModel Fragment Recreates On Screen Rotation I'm building an application with latest android architecture components. I'm using firebase firestore as a database with jetpack navigation(Bottom nav). I'm successfully able to display data from DB. But Whenever I rotate mt screen the store fragment recreates & makes request to DB.
Repo
    override fun getAllStores() = callbackFlow<State<List<Store>>> {
    // Emit loading state
    send(State.loading())

    val listener = remoteDB.collection(Constants.COLLECTION_STORES)
        .addSnapshotListener { querySnapshot, exception ->
            querySnapshot?.toObjects(Store::class.java)?.let { store ->
                // Emit success state with data
                offer(State.success(store))
            }
            exception?.let {
                // emit exception with message
                offer(State.failed(it.message!!))
                cancel()
            }
        }
    awaitClose {
        listener.remove()
        cancel()
    }

}.catch {
    // Thrown exception on State Failed
    emit(State.failed(it.message.toString()))
}.flowOn(Dispatchers.IO)

ViewModel
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
class StoreViewModel(private val repository: DBInterface = Repo()) : ViewModel() {

fun getAllStores() = repository.getAllStores()

}

Store Fragment
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
class StoreFragment : Fragment(R.layout.fragment_store) {
private lateinit var storeAdapter: StoreAdapter
private val viewModel: StoreViewModel by viewModels()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    (activity as MainActivity).supportActionBar?.title = getString(R.string.store_title)

    setUpRV()

    // get all stores
    lifecycleScope.launch {
        getAllStores()
    }

}

private suspend fun getAllStores() {
    viewModel.getAllStores().collect { state ->
        when (state) {
            is State.Loading -> {
                store_progress.show()
            }

            is State.Success -> {
                storeAdapter.differ.submitList(state.data)
                store_progress.animate().alpha(0f)
                        .withEndAction {
                            store_rv.animate().alpha(1f)
                            store_progress.hide()
                        }

            }
            is State.Failed -> {
                store_progress.hide()
                activity?.toast("Failed! ${state.message}")
            }
        }
    }
}

private fun setUpRV() {
    storeAdapter = StoreAdapter()
    store_rv.apply {
        adapter = storeAdapter
        addItemDecoration(SpacesItemDecorator(16))
    }
}

}
Main activity(Nav graph)
@InternalCoroutinesApi
@ExperimentalCoroutinesApi
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    // init bottom navigation
    bottom_navigation.setupWithNavController(nav_host_fragment.findNavController())

}
}

Every time it recreates my fragment. I don't want to save or retain any views using methods. Because ViewModel used to protect view on screen rotation. Kindly let me know any tips & tricks. Thanks in advance ;)

A: Flow in itself is not stateful - that is a key difference between it and LiveData. That means that after your collect completes, the next collect starts the callbackFlow from scratch.
This is precisely why the lifecycle-livedata-ktx artifact contains the asLiveData() extension that allows you to continue to use a Flow at the repository layer while maintaining the stateful (and Lifecycle) properties of LiveData for your UI:
@ExperimentalCoroutinesApi
@InternalCoroutinesApi
class StoreViewModel(private val repository: DBInterface = Repo()) : ViewModel() {
    fun getAllStores() = repository.getAllStores().asLiveData()
}

You'd change your UI code to continue to use LiveData and observe().
Kotlin is working on a shareIn operation that would allow your ViewModel to save the state of a Flow. That would allow you to use Flow at all layers of your app without requerying information from scratch when the Fragment/Activity that is calling collect gets destroyed and recreated.

A: you can add android:configChanges="orientation|screenSize|screenLayout" to your manifest for the activity. this should prevents restarts when orientation changes.
check this site and also here are som infos.


text:
Q: Sort the posts in my feed from latest to oldest (using Swift and Parse) I created a simple Instagram-like app using Parse. My problem is that the feed is organized with the oldest posts at the top of the feed and the latest posts at the bottom. How can I reverse the sorting order, so that posts are displayed from most recent at top to oldest at bottom?

A: You can also reverse your data array to
let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

var reversedNames = [String]()

for arrayIndex in stride(from: names.count - 1, through: 0, by: -1) {
    reversedNames.append(names[arrayIndex])
}


text:
Q: Проброс запроса из docker контейнера Есть kubernetes job который ходит в базу и за тем отправляет http запрос. База реальная и находится в совершенно другом месте, данные с нее я удачно получаю. А в качестве хттп сервера я использую заглушку которую развернул на своем компьютере. В качестве кластера использую minikube. Вопрос в том как отправить хттп запрос из докера, который находится в minikube, на localhost машины на которой запущен minikube

A: Попробуйте использовать host.docker.internal вместо localhost.
Дополнительное чтение по теме: How to connect to the Docker host from inside a Docker container?


text: Q: How the process parameters changes with the length of data aggregation? Is there any general relationship for a process(e.g. ARMA, O-U process) applied to financial data over different time intervals. e.g.In this question there is an answer telling the O.P. to aggregate his hourly data to obtain daily data and re-estimate the parameters because the dynamics of an hourly process can be very different from daily. How the process parameters changes with the length of data aggregation? How will parameters  get affected if one has a daily dataset for a very long period of time and start aggregating over a week? Kindly illustrate. Thanks


text:
Q: ValueError: No password or public key available I'm trying to connect to a remote MySQL database through an SSH Tunnel and deploying my code to Streamlit. When I try to do it, I get this error:
File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 966, in __init__

    (self.ssh_password, self.ssh_pkeys) = self._consolidate_auth(

  File "/home/appuser/venv/lib/python3.9/site-packages/sshtunnel.py", line 1169, in _consolidate_auth

    raise ValueError('No password or public key available!')

ValueError: No password or public key available!

I've tried a lot of things, from updating my SSH keys to my server and github to changing my code.
The code I have for the SSH - MySQL section looks like this:
import MySQLdb as db
from sshtunnel import SSHTunnelForwarder

def query(q):

    with SSHTunnelForwarder(
          ssh_address_or_host=("host_ip"),
          ssh_username=("host_username"),
          ssh_pkey=("path_to_private_sshkey"),
          remote_bind_address=("private_host_ip", "host_port")
     ) as server:

          conn = db.connect(
            host="localhost",
            port=server.local_bind_port,
            user="db_username",
            passwd="db_password",
            db="db_database"
            )

          return pd.read_sql_query(q, conn)

I appreciate any help you can give me.

A: conn = db.connect(host="localhost"),
port=server.local_bind_port,
user=("db_username"),
passwd=("db_password"),
db=("db_database")

Because you have a closing parentheses on the first line, only the host argument is being passed to the db.connect() function.  And so the function is complaining that it doesn't have a password, username, etc.
The other lines are creating plain local variables.


text:
Q: bash -x /var/lib/cloud/instance/user-data.txt runs but user-data from terraform gives error I am trying to run a script using terraform. The content of the user-data is as follows:
.
.
cat <<EOH | java -jar ./jenkins-cli.jar -s $JENKINS_URL -auth admin:$PASSWORD create-credentials-by-xml system::system::jenkins _
<com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey plugin="ssh-credentials@1.16">
  <scope>GLOBAL</scope>
  <id>$CRED_ID</id>
  <description>$SLAVE_IP pem file</description>
  <username>ec2-user</username>
  <privateKeySource class="com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey\$DirectEntryPrivateKeySource">
    <privateKey>${worker_pem}</privateKey>
  </privateKeySource>
</com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey>
EOH
.
.

When it executes as part of user-data it gives out an error as No such command create-credentials-by-xml.
But when I log in to the instance and execute bash -x /var/lib/cloud/instance/user-data.txt it runs as expected.
Can anyone please tell what is the reason for it and how to fix it? Thanks!
I have tried #cloudhook and separating the lines as well, but didn't work.

A: Answering my question:
Where was the problem:
The issue was not with bash but with jenkins-cli.jar itself.
The error message showed No such command create-credentials-by-xml which made me think, it was bash error but in reality, it was jar file error all along.
Reason:
The reason it was failing at user-data execution and not at bash execution was that it was unable to load configuration of plugins in a short amount of time.
Solution:
From the given reason, it is obvious that it needs time so I gave it sleep 25 to confirm it works or not and yes it does work but it was not an ideal solution.
Optimized Solution:
To make it better I listed the plugins before executing any jar commands and if the list came empty re run the commnd
# Creating CMD utility for jenkins-cli commands
jenkins_cmd="java -jar /opt/jenkins-cli.jar -s $JENKINS_URL -auth admin:$PASSWORD"

# Waiting for Jenkins to load all plugins
while (( 1 )); do
  count=$($jenkins_cmd list-plugins 2>/dev/null | wc -l)
  ret=$?

  echo "count [$count] ret [$ret]"

  if (( $count > 0 )); then
      break
  fi

  sleep 30
done


text:
Q: Poisson process at infinity Is the following probability well-defined?

Let $(X_t)_{t>0}$ be Poisson process ~ (pt)

$$\lim_{N\to\infty}P(X_{N/(2p)}< N ) = ?$$
How do I deal with the fact that the time is infinite ($t=\frac{N}{2p}$) and the number of arrivals if infinite (N)?

A: I'm not quite sure what you're asking, but here's my best guess.
If $X_t$ is a Poisson process with intensity $p$, you seem to be asking about
the limit as $N \to \infty$ of ${\mathbb P}(X_{N/(2p)} < N)$.  Or maybe
it's asking about something like $\mathbb P(\lim_{N \to \infty} X_{N/(2p)}/N < 1)$.
Hint: $X_{N/(2p)}$ is the sum of $N$ independent Poisson random variables
$X_{1/(2p)}$, $X_{2/(2p)} - X_{1/(2p)}$, ..., $X_{N/(2p)} - X_{(N-1)/(2p)}$, each with expected value $1/2$.  Use the Laws of Large Numbers.  The Weak Law addresses the first question, and the Strong Law the second.


text:
Q: i.i.d. estimation of variance Let ${X_i}$ for $i\in N$ be a string i.i.d. with a known expected value of $\mu = E (X_1)$. Investigate the properties
the estimator of the variance given by the formula : $\frac{1}{n} \sum(X_i ^2 - \mu ^2)$ (sum from 1 to n). Have you got some hints?


text:
Q: mlr - Access data between or after preprocessing steps Is there a way to access the data after performing a preprocessing step using a wrapper in mlr? Here a stripped version of the code:
library(mlr)
library(mlbench)

data <- BreastCancer[, 2:11]
lrn <- makeLearner(cl = "classif.ranger",
                        predict.type = "prob",
                        fix.factors.prediction = TRUE,
                        importance = "permutation")

lrn <- makeImputeWrapper(lrn, classes = list(integer = imputeMedian(),
                                                  numeric = imputeHist(),
                                                  factor = imputeMode()))

lrn <- makeRemoveConstantFeaturesWrapper(lrn, na.ignore = TRUE)

classif.task <- makeClassifTask(data = rawdata, target = "Target", positive = "1")

model <- train(lrn, classif.task)

The code defines a learner, removes constant features and performs imputation. Is there a way to see how the data will look like after the removal of the constant features or, more interestingly, after the imputation?

A: This isn't implemented at the moment -- the point of the wrappers is to encapsulate everything so that you don't have to worry about the intermediate steps.
You can however use the impute() function to do the same imputation separately (and similarly for the removal of constant features). See the tutorial for more information.


text:
Q: Не подключается шрифт в Sass Не подключается шрифт:
   @font-face
     font-family: 'CyrillicOld'
     src: url('../fonts/cyrillic_old.ttf')

Потом к элементу пишу
font-family: 'CyryllicOld', sans-serif

Не работает, путь к шрифту правильный, на sass пишу.

A: *

*Для sass путь может быть и правильный, но он должен быть правильным для компилируемого css. Проверьте правильно ли указан путь для для компилируемого подключаемого css файла.

*Посмотрите - что написано в консоли? Есть ли ошибка подключения шрифта, если есть, то проблема в пути, и его нужно исправить на тот, что требуется в консоли. Если нет, то проблема с самим шрифтом.

*Убедитесь, что для требуемого элемента в стилях этот шрифт подключен и не перекрывается другими шрифтами.

A: font-family: 'CyrillicOld'
font-family: 'CyryllicOld'

Найди 10 отличий


text:
Q: How to create an NSMutableDictionary containing many NSMutableArrays I need to dynamically, at run time do the following with a NSMutableDictionary ...

*create (perhaps thousands) of arrays that are added to the dictionary.  This will be done inside a loop and the number of arrays needed will be unknown as they are driven off a plist of words.

*create (thousands) of strings for each array.  Again, data driven, the number of strings is known only at runtime.

*Use the key to represent some character pattern for the particular array (ex: 'm-m-' means the array contains strings with two m's at the 2nd & 4th location.)

*Use the value to represent the count of strings that match the pattern (ex:200 strings are of '-m-m' pattern), and use the array to have the actual 200 strings.
So once implemented, the dictionary will contain a count/value of each pattern/key and the actual strings that match that pattern.
I need help with the proper syntax for creating dictionary and adding arrays dynamically, and incrementing the count/value, and I suppose appending/inserting the strings but that part I think I am good with.
related post: NSMutableArray or NSMutableDictionary : which is best for this scenario?

A:
I need help with the proper syntax for creating dictionary and adding
  arrays dynamically, and incrementing the count/value,

Arrays are objects, and you add them to a dictionary the same way that you'd add any other object to a dictionary:
[someDictionary setObject:theArray forKey:theKey];

I'm not clear on what you mean about "incrementing the count/value". A dictionary knows how many key/value pairs it contains -- no need to increment anything. Same goes for arrays.
So it sounds like your code is going to go something like:
NSMutableDictionary *dict;
for (NSString *word in wordlist) {
    @autorelease {
        NSMutableArray *wordStrings = [NSMutableArray array];
        while (/*some condition based on word*/) {
            NSString *newString = [NSString stringWithFormat:...];
            [wordStrings addObject:newString];
        }
        [dict setObject:wordStrings forKey:word];
    }
}

I'm sure that's not quite right -- I have no idea what you're really trying to do, but the code above shows how you'd generate some number of arrays and add them to a dictionary. The rest is up to you.
Looking at your edit, I think you may be a little confused about what's stored in a dictionary. A dictionary is just a set of key/value pairs. In this case, the values are the arrays that you add, and the keys are the pattern strings. There's no space for an extra "value" for each key that stores a count. You could have two entries for each pattern using some convention for the keys like pattern and *pattern_count*. There's no need to do that, though... the array stored for each pattern can easily tell you how many objects it contains:
NSArray *wordList = [dictionary objectForKey:pattern];
int count = [wordlist count];


text:
Q: An implausibly plausible Collatz result. Should I believe the results of Reduce? Update 3 @azerbajdzan 's info in comment on OddQ explains the failure to find solutions, misinterpretation of which lead to the "implausibly plausible" conclusion. However repeated with Mod in place of OddQ, Reduce not produces (after LogicalExpand) 2592 conditions... all of which are manifestly unsatisfiable. I shall not pollute this question further with details of that; a new question will be asked.
Update 1 -- the collatz formula has been corrected in the Sum[] part; the change did not alter the result of Reduce. See also Update 2 below for new doubts.
Original
Thanks to @bob-hanlon's answer to How to specify and use indexed variables of undefined quantity?, with the elimination of subscripted variables in favour of indexed variables, I am not able to instantly dismiss the result, despite its implausibility. One reason for doubting the result though is that there is no explicit restriction of n to positive integers, and there are solutions in the negative integers, but maybe something is implicitly limiting the Reduce to +ve integers.
In the question Interpreting Reduce output (in the recreational context of the 3n + 1 problem) I asked for help in interpreting the long and complex results of Reduce; that task is now rather different.
Note: the Collatz, a.k.a. 3 n + 1 problem concerns the iteration of the rules, if n is odd, multiply by three and add one, if n is even divide by two.
Every positive n ever iterated has fallen into the {1, 4, 2} cycle. Whether this is true for all n is unknown. Answering that (Terence Tao recently proved that ~it is almost always true, which was amazing, other results include, n is very large if there are other cycles and any such cycle must be very long) can be split into two: a) are there any other cycles?, or b) might the iterated sequence drift off to infinity.
By applying MMA to a closed form we obtain a specific answer to question a), which is surprising, to say the least. (And Update 2 below addresses question b) )
The questions are now:
1/ Is the following result a) true and b) if so, how could MMA's workings be inspected to confirm this manually?
2/ In the rather more likely event that the result is not true, what is wrong with the setup or MMA's workings, or how might I investigate the latter?
3/ Can anyone adapt the setup so it does identify the solutions n = -1, -5, -17?
Set up.
Format[q[n_]] := Subscript[q, n]
Q[n_] := 2^Sum[q[j], {j, 1, n}]
collatz[P_, n_] := (n (3^P ) +  3^(P - 1) + Sum[Q[i] 3^(P - i - 1), {i, 1, (P - 2)}] + Q[P - 1])/Q[P]

Reduce[collatz[P, n] == n && P >= 2 && OddQ[n], n, Integers, GeneratedParameters ->(Subscript[k, #] &) ]

(* False *)

(Understanding MMA's limitations and how to work with it better are implied goals of the questions above.)
PS Does collatz[P,n] even "Make sense?" (responding to @azerbajdzan)
These make perfect sense to me, and have the correct coefficients
collatz[2, n] == n // TeXForm
collatz[3, n] == n // TeXForm
collatz[4, n] == n // TeXForm

$2^{-q_1-q_2} \left(9 n+2^{q_1}+3\right) = n$
$2^{-q_1-q_2-q_3} \left(27 n+3\ 2^{q_1}+2^{q_1+q_2}+9\right) = n$
$2^{-q_1-q_2-q_3-q_4} \left(81 n+9\ 2^{q_1}+3\ 2^{q_1+q_2}+2^{q_1+q_2+q_3}+27\right)$
and this seems no less valid
collatz[7, -17] == -17 // TeXForm

$2^{-q_1-q_2-q_3-q_4-q_5-q_6-q_7} \left(243\ 2^{q_1}+81\ 2^{q_1+q_2}+27\ 2^{q_1+q_2+q_3}+9\ 2^{q_1+q_2+q_3+q_4}+3\
   2^{q_1+q_2+q_3+q_4+q_5}+2^{q_1+q_2+q_3+q_4+q_5+q_6}-36450\right)=-17$
in which case the question (ultimately) would be, what are the various $q_i$?
Update 2
A new reason for thinking there is something rotten in the state of Denmark is that Reduce[collatz[P, n] (<, >) n && OddQ[n], ...] are also False.

A: TL;DR The postulated result  of Reduce is not to be believed because the core element of the collatz function has no effect in the presence of OddQ applied to a symbolic argument (for which, see the documentation). Use Mod[] instead. The OP was probably misled by Confirmation Bias re the positive integers (and even more confused by the absence of solutions in negative integers).
Full Form
The application of Reduce
Reduce[collatz[P, n] == n && P >= 2 && OddQ[n], n, Integers, GeneratedParameters ->(Subscript[k, #] &) ]

(* False *)

is independent of the equations collatz[P, n] == n && P >= 2 because, as pointed out by @azerbajdzan, the behaviour of OddQ and its ilk is unusual, especially in the context of symbolic manipulation - as here - where it will always return False.
In order to use oddness or similar in Reduce, one should use Mod[].
As to the operation of OddQ, further clarity is desirable. It says in the documentation for OddQ

gives True if expr is an odd integer, and False otherwise.

However, one should attend to the Detail (which is normally collapsed and so not immediately visible), where it says

OddQ[expr] returns False unless expr is manifestly an odd integer
(i.e. has head Integer, and is odd).

The adverb manifestly is important: even though 3.0 == 3 is True, OddQ[3.0] is False, because 3.0 has Head Float.
Commentary
Whilst the functions OddQ, etc. are described accurately, this behaviour may not be expected and therefore its effects hard to spot, and in my opinion it runs counter to the general feature of the language that the application of a function to a type for which it is undefined returns the function expression unevaluated, which does not happen with OddQ.
Since this is noted in the documentation under Possible Issues (where application of FullSimplify is consequently recommended), there is probably some good reason for the way that OddQ etc. work but I have no information on that; any link to an explanation would be welcome
(* MMA returns an expression unevaluated if it is not defined for that type *)
f[x_Integer]:=4 x;
f["1"]
(* f["1"] *)
(* But OddQ and the like return False instead *)
OddQ["1"]
(* False *)

@domen's link to the TestingExpressions documentation should also be noted; it says there

Functions that "ask a question" have names that end in Q. They return
True for an explicit true answer, and False otherwise.

where we see "explicit" used apparently synonymously with "manifestly", neither of which are immediately meaningful IMO, serving only to confirm what one might already know.


text:
Q: OpenCV: Highlights Adjustment Without Affecting Shadows I originally attempted to use the script located here to darken the highlights of a captured 8mm film frame without affecting the shadows.
I never call the script with parameters that returned an acceptable improvement in the image. I have since attempted to try this code:
import numpy as np
import cv2

def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

def gammaCorrection(src, gamma):
    invGamma = 1 / gamma

    table = [((i / 255) ** invGamma) * 255 for i in range(256)]
    table = np.array(table, np.uint8)

    return cv2.LUT(src, table)

image = cv2.imread(r'X:\temp2\Test00001-02.jpg')
resize = ResizeWithAspectRatio(image, width=1280) # Resize by width OR
# resize = ResizeWithAspectRatio(image, height=1280) # Resize by height

cv2.imshow('Image', resize)

#gammaImg = gammaCorrection(resize, 0.3)

#cv2.imshow('Gamma corrected image', gammaImg)

# Convert to HSV and take V channel
V = cv2.cvtColor(resize,cv2.COLOR_BGR2HSV)[...,2]

# Threshold V channel at 100 to make alpha channel (A)
_, A = cv2.threshold(V,150,255,cv2.THRESH_BINARY)

# Threshold V channel at 100 to make alpha channel (A)
_, A2 = cv2.threshold(V,0,255,cv2.THRESH_BINARY)

# Stack A channel onto RGB channels
result = np.dstack((resize,A))

# Stack A channel onto RGB channels
fullchannel = np.dstack((resize,A2))
gammaImg = gammaCorrection(result, 0.3)
final_im = cv2.addWeighted(fullchannel, 1, gammaImg, 0.5, 0)

# Save result
cv2.imwrite(r'X:\temp2\original_im.png',resize)
cv2.imwrite(r'X:\temp2\final_im.png',final_im)
cv2.imwrite(r'X:\temp2\gamma_adjusted.png',gammaImg)
cv2.imwrite(r'X:\temp2\fullchannel.png',fullchannel)

The following images show the output of this script.
Original Image:

Gamma Adjusted Image:

Full Channel Image:

Final Image:

The final image actually makes the highlights in the image even brighter, so there is something I am doing wrong when I merge the gamma adjusted image with the full channel image.
So, any thoughts on getting just the highlights above a set threshold to darken and not affect the darker regions of the image?


text:
Q: MySQL error 1093. how to delete from this Select worked:
select * from A
where A.id not in
(
select id from A as a
inner join B as b
where (a.`name` = b.`name`
   and a.`status` = b.`description`))

delete doesn't work:
delete from pre_log
where pre_log.id not in
(
select id from pre_log as p
inner join sobg_table as s
where (p.`name` = s.`name`
   and p.`status` = s.`description`)
)

Error Code: 1093. You can't specify target table 'pre_log' for update in FROM clause  0,001 sec

A: You have specified pre_log table in your sub query from which you actually Delete the records
try this might help you..
delete l.* from pre_log l
where l.id not in
(
select id from
   (
   select id from pre_log as p
    inner join sobg_table as s
    where (p.`name` = s.`name`
       and p.`status` = s.`description`)
    ) x
    )

A: delete c.* from cars c
where c.id in (
               select c2.id
               from cars c1
               join cars c2 on c1.model = c2.model and c1.brand = c2.brand
               where c1.id < c2.id
               )

this method didn't work it gave an error but
then I used a second subquery in the 'where' clause to get the results of the first
subquery and it worked
where c.id in (select id from (
select c2.id
from cars c1
join cars c2 on c1.model = c2.model and c1.brand = c2.brand
where c1.id < c2.id
) temp
) ```


text:
Q: AngularJS attaching value to factory/Service I have a controller below, in which I get (user's google forms) as res.data , I try to attach it to my Userr service by means of setter and try to get it in another controller by means of getter.
Here is my controllers:
.controller('googleFormsCtrl', function ($scope, $http, $window, Userr,$timeout,$location) {
        // SEND THE HTTP REQUEST
        var url;
        var externalWindow;
        // MAKE API REQUEST for Authorization
        $http.get('/api/googleAuth').then(function (response) {
            url = response.data;
        });

        this.googleAuthentication = function () {
            externalWindow = $window.open(url, "Please Sign in with Google", "width:350px,height:350px");
        };
        // Close Authorization and set credentials
        window.onmessage = function (info) {
            externalWindow.close();
            // Get the URL
            var urlCode = info.data;

            // Get pure code of user
            var idx = urlCode.lastIndexOf("code=");
            var code = urlCode.substring(idx + 5).replace("#", "");

            // GET ALL FORMS
            Userr.getCredentials(code).then(function (res) {
                Userr.setForms(res.data);
                $timeout(function(){
                    $location.path('/usersForms');
                },100);
            });

        };
    })
    .controller('GoogleAuthCallback', function ($scope, $http) {
        this.googleAuthentication = function () {
            window.opener.postMessage("My URL is : " + location.href, "*");
        };
    })
    .controller('getSheetData', function (Userr,$scope) {
        console.log("comes here");
        console.log(Userr.getForms());
    })
    ;

I assign the value in googleFormsCtrl and try to access data in getSheetData controller.
Here is the part of my factory where I created getters and setters:
angular.module('userServices',[])

.factory('Userr',function($http){
    userFactory = {};
    var forms = {};

    userFactory.setForms = function(value){
        forms.value = value;
        console.log(forms.value);
    }

    userFactory.getForms = function(){
        console.log(forms.value);
        return forms.value;
    }

    //User.create(regData);
    userFactory.create = function(regData){
        return $http.post('/api/users',regData);
    };

When I try to access the data in another page through getSheetData controller it retrieves undefined. Could not find problem for 2 hours.Any hep appreciated. Thanks in advance.


text:
Q: How to plot a distribution function in matplotlib if input data has has two options of distribution that can be followed? I have to plot graph b/w x1(and x2) and f where f is the the distribution function. I want to know that my input data x1 and x2 are following which one the  two distribution functions? So how should I plot graph for this purpose?
`#Input data
x1=np.array([0.433172   0.48298582 0.92493727 2.15890491])
x2 = np.array([0.22727232 0.52651793 1.51814772 1.72806203])
f = np.exp(-x) #Poisson-distribution
f =  x*np.pi/2.*np.exp(-x*x*np.pi/4) #WD distribution

On y-axis I have to plot distribution function. I want to check which distribution my input data is following. But if I mention formula of any distribution suppose Poisson distribution the I'will force my data to follow this specif distribution that I don't want. So how can I do that?


text:
Q: A problem in sequences and series Three numbers in AP are removed from first $n$ consecutive natural numbers and average of remaining numbers is found to be $\frac{43}{4}$. Find $n$ as well as removed numbers if one of the removed number is a perfect square.

A: If we let $k-d$, $k$, $k+d$ be the 3 terms in AP which are removed, then we are trying to find integer solutions to $$\dfrac{1}{n-3} \left( \dfrac{n(n+1)}{2} - 3k \right) = \dfrac{43}{4}$$
We can conclude that $n \geq 18$, because if $n = 17$, the greatest average we could get would be to remove $1$, $2$, $3$, giving an average of $10.5 < 43/4$. And of course, if $n < 17$ the average would be even smaller. Similarly $n \leq 23$.
Now, in the above equation, since $n(n+1)/2 - 3k$ is an integer, and we need the denominator to be $4$, we must have that $n-3$ is divisible by $4$. This gives only two possible values: $n=19$ and $n=23$. Putting $n=23$ into our original equation gives $k = 61/3$, which is bogus. However, $n=19$ gives $k=6$. Restricting one of the terms removed to be a square, any of $d=2,3,5$ will work.


text:
Q: valgrind does not complain for memory corruption? I have a small block of code as blow
class singler
{
    private:
        singler() { _id = id++; };
    public:
        ~singler() { cout<<"In destructor of "<<_id<<endl;};
        static singler* allocate() { singler* p = new singler(); return p; };
        static int id;
        int _id;
};
int singler::id = 0;
singler& create_new(singler*& ptr)
{
    singler * p = singler::allocate();
    ptr = p;
    return (*p);
}
int main()
{
    singler* ptr;
    singler obj = create_new(ptr);
    delete ptr;
}

So you can see that the destructor of the object will be called twice, as a proof, i compiled and ran it, it gave output as
In destructor of 0
In destructor of 0

Problem is in valgrind, it does not complain for anything, the valgrind output is as below
==2
0408== Memcheck, a memory error detector
==20408== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20408== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20408== Command: a.out
==20408==
In destructor of 0
In destructor of 0
==20408==
==20408== HEAP SUMMARY:
==20408==     in use at exit: 0 bytes in 0 blocks
==20408==   total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==20408==
==20408== All heap blocks were freed -- no leaks are possible
==20408==
==20408== For counts of detected and suppressed errors, rerun with: -v
==20408== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

So how to detect this type of errors efficiently? ( i mean using some tool which will atleast tell me if there is any problem, and if yes, where is it? )

A: There are no corruption in your program, and valgrind worked fine in your case.
Two objects are indeed created. The first object is allocated on a heap, and the second is a copy of the first object. That is why you see the destructor called twice.


text:
Q: How to multiply 2 values from different tables in Linq? I try to multiply 2 values from different table but it's keep error like this:

Here's my code:
    //Label12 is in datalist
    var Label12 = (Label)(((Button)sender).Parent).FindControl("Label12");

    var item2 = from c in db.OrderTemps
                join o in db.Products
                on c.Prod_ID equals o.Prod_ID
                select new
                {
                   o.Prod_ID,
                   o.Prod_Price, //Type "Decimal"
                   c.Amount, //Type "Integer"
                   c.Total, //Type "Decimal
                   s = o.Prod_Price * c.Amount
                };

     foreach (var i in item2)
     {
        Label12.Text = Convert.ToString(i.s); //an error happen here!!
     }

Any help appreciated.

A: There is nothing wrong with you LINQ query. If no records joined, then there will be nothing to enumerate and you will skip foreach body. I think you have Label12 equal to null. Check if it really exist on senders parent.
SIDE NOTE: Why are you trying to assign text in loop? Label will keep only last value assigned.

A: Check whether your amount value in OrderTemps table is null. or Check whether you really have a controller which has the ID = Label12.
Nothing wrong in your Linq query...


text:
Q: Looking for clustering message framework for Python I'm looking for a messaging framework to build up a cluster in Python (something similar to Apache Tribes).
Are there any such frameworks in Python?

A: I am not too familiar with Apache Tribes but have you looked at Pyro?
http://www.xs4all.nl/~irmen/pyro3/


text:
Q: Sort Google places autocomplete results by distance using iOS SDK I'm using Google places autocomplete iOS API (as instructed here)
I need to sort the results to show the nearest places first.
Can I do this using the iOS API? if yes, please point me to a reference or something.
Thanks

A: I think the easiest is to get the user's location, then calculate the distance between each point and the user like this

Calculate distance between two place using latitude-longitude in gmap for iPhone

then order it by the distance.


text:
Q: Nginx latency is too high I use 2 servers for php and mysql.
users connect via Cloudflare > Varnish > Ngnix > Php-fpm --> Mysql Server
But i connected my website with nginx port directly so that was same
My server properties are 16 GB ram, E3-1231v3 cpu (8 core)
Server load is always 1.30 and free ram is 3 gb But at weekend, my website gets a lot of traffics and sometimes website response is late, it likes freezing.
When i check php-fpm and nginx connections, php-fpm is usually at 30-40 but it has seen max 650.
Nginx is usually 100 but that sometimes comes to 400-500-600 and starts to freezing, I see writing connections increase same with nginx connections at the same time and website response become late.
I setup munin and monitored nginx, php-fpm and network they are like that.

And my nginx conf like that
user www-data;
worker_processes auto;
pid /var/run/nginx.pid;

error_log  /var/log/nginx/error.log info;
worker_rlimit_nofile 65536;

events {
worker_connections 65536;
use epoll;
multi_accept on;
}

http {

##
# Basic Settings
##
log_format  main  '$http_cf_connecting_ip - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
log_format combined2 '$http_cf_connecting_ip - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';

sendfile on;
keepalive_timeout 15; #65;
keepalive_requests 100000;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;
# server_tokens off;
client_body_buffer_size 10K; #15M;
client_max_body_size 10M;

# send_timeout 10;
client_header_buffer_size 10k;
large_client_header_buffers 2 10k;
output_buffers 1 32k;
postpone_output 1460;
client_header_timeout  12; #4m;
client_body_timeout    12; #4m;
send_timeout           10; #4m;
open_file_cache max=1000 inactive=5m;
open_file_cache_valid 2m;
open_file_cache_min_uses 5;
open_file_cache_errors off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

include /etc/nginx/mime.types;
default_type application/octet-stream;

##
# SSL Settings
##

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

##
# Logging Settings
##

access_log off; #/var/log/nginx/access.log;
error_log off; #/var/log/nginx/error.log;

##
# Gzip Settings
##

gzip on;
gzip_disable "msie6";

gzip_vary on;
# gzip_proxied any;
gzip_comp_level 2;
gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
upstream backend {
server 127.0.0.1:9000;
}

real_ip_header X-Forwarded-For;
# Cloudflare
set_real_ip_from 199.27.128.0/21;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/12;
real_ip_header CF-Connecting-IP;
real_ip_header X-Forwarded-For;
}

I suspect network bandwith and nginx config, Do you have any idea?


text:
Q: llvm clang 2.6: "not using the clang compiler for C++ inputs " LLVM 2.6 + clang.
Trying to compile C++ file and got:
clang: warning: not using the clang compiler for C++ inputs

How can I start clang in C++ mode?

A: I would get the trunk code. C++ support has been much improved since 2.6.
The clang driver Makefile in tools/clang/tools/driver uses the CLANG_IS_PRODUCTION define to control whether C++ is on or off. CLANG_IS_PRODUCTION means C++ off. The default for a trunk build is no CLANG_IS_PRODUCTION (i.e. a development build).

A: I know that the trunk code has c++ enabled. Perhaps you could use that instead?


text:
Q: synctex(busy) latex file not compiling I am trying to compile a latex file but I noticed that the file ``freezes" at the point of this array:
\[\left(\begin{array}{ccc}
a_{11} & a_{12} & a_{13}\\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{23} & a_{33}
\end{array}\right)
\left(\begin{array}{c}
u_{t}^{\tau} \\
u_{t}^{g} \\
u_{t}^{y}
\end{array}\right)
=
\left(\begin{array}{ccc}
b_{11} & b_{12} & b_{13}\\
b_{21} & b_{22} & b_{23} \\
b_{31} & b_{23} & b_{33}
\end{array}\right)
\left(\begin{array}{c}
e_{t}^{\tau} \\
e_{t}^{g} \\
e_{t}^{y}
\end{array}\right)
\]

That array was a copy and paste from another latex file. Is there a particular package that creates this problem ? Once I remove the array from the file it compiles with no problems.  The document class that I use is {book} with the following sample of packages:
\usepackage[a4paper, total={6in, 9.5in}]{geometry}
\usepackage{amsmath, mathtools}
\usepackage{amssymb}
\usepackage{multirow}
\usepackage[flushleft]{threeparttable}

A: Your MWE works as expected. Try to manually erase all files generated at LaTeXing of your example. This should help. This error is usually caused by editor, when it hangs on some open pdf file, so it is not really related to (La)TeX.
from your fragments of code I put together the following MWE:
\documentclass{book}
    \usepackage[a4paper, total={6in, 9.5in}]{geometry}
    \usepackage{mathtools,amssymb}
%    \usepackage{multirow}
%    \usepackage[flushleft]{threeparttable}

    \begin{document}
\[
\left(\begin{array}{ccc}
a_{11} & a_{12} & a_{13}\\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{23} & a_{33}
\end{array}\right)
\left(\begin{array}{c}
u_{t}^{\tau} \\
u_{t}^{g} \\
u_{t}^{y}
\end{array}\right)
=
\left(\begin{array}{ccc}
b_{11} & b_{12} & b_{13}\\
b_{21} & b_{22} & b_{23}\\
b_{31} & b_{23} & b_{33}
\end{array}\right)
\left(\begin{array}{c}
e_{t}^{\tau} \\
e_{t}^{g} \\
e_{t}^{y}
\end{array}\right)
\]
% example of use `pmatrix`
\[
\begin{pmatrix}
a_{11} & a_{12} & a_{13}\\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{23} & a_{33}
\end{pmatrix}
\begin{pmatrix}
u_{t}^{\tau} \\
u_{t}^{g} \\
u_{t}^{y}
\end{pmatrix}
=
\begin{pmatrix}
b_{11} & b_{12} & b_{13}\\
b_{21} & b_{22} & b_{23}\\
b_{31} & b_{23} & b_{33}
\end{pmatrix}
\begin{pmatrix}
e_{t}^{\tau} \\
e_{t}^{g} \\
e_{t}^{y}
\end{pmatrix}
\]
    \end{document}

where I added the example of use pmatrx for writing of matrices. Commented packages in preamble doesn't influence on working of above code. I skip to explicit load amsmath˙ since it is automatically loaded bymathtools`. Obtained resulta you can see below.


text:
Q: Turf.js pointsWithinPolygon works for Polygon but not FeatureCollection I am trying to use Turf.js to find all points within a bounding box for a FeatureCollection. According to the documentation, you can provide the function pointsWithinPolygon with either a Feature or a FeatureCollection of Points.
Using a modified version of the official example from the documentation, I get the following error message: "Uncaught TypeError: Cannot read property '0' of undefined".
    var locationA = turf.point([-75.343, 39.984], {
        name: 'Location A'
    });
    var locationB = turf.point([-75.833, 39.284], {
        name: 'Location B'
    });
    var locationC = turf.point([-75.534, 39.123], {
        name: 'Location C'
    });

    var collection = turf.featureCollection([
        locationA,
        locationB,
        locationC
    ]);

    var points = turf.points([
        [-80, 30],
        [-70, 30],
        [-70, 50],
        [-80, 50],
    ]);

    console.log(turf.pointsWithinPolygon(points, collection)); // Doesn't work

Any idea what is going wrong here or what might cause the problem?
The application seems to work for a Polygon, but not for a Feature Collection.
var searchWithin = turf.polygon([[
    [-46.653,-23.543],
    [-46.634,-23.5346],
    [-46.613,-23.543],
    [-46.614,-23.559],
    [-46.631,-23.567],
    [-46.653,-23.560],
    [-46.653,-23.543]
]]);

console.log(turf.pointsWithinPolygon(points, searchWithin)); // Works

A: Why
console.log(turf.pointsWithinPolygon(points, collection)); // Doesn't work

According to the document at
https://turfjs.org/docs/#pointsWithinPolygon
pointsWithinPolygon(points, polygons)
the parameters:
points: Point(s)
polygons: Polygon or Multipolygon

Your collection (of points) does not meet the requirement, it is just a collection of 3 points, not Polygon or Multipolygon required.

// This checks if tutf is loaded?
try {
  /* Begin: put your code in this area below */
  // Points as polygon vertices
  var locationA = turf.point([-75.343, 39.984], {
    name: "Location A"
  });
  var locationB = turf.point([-75.833, 39.284], {
    name: "Location B"
  });
  var locationC = turf.point([-75.534, 39.123], {
    name: "Location C"
  });

  var poly_from_points = turf.polygon([[
    turf.getCoord(locationA),
    turf.getCoord(locationB),
    turf.getCoord(locationC),
    turf.getCoord(locationA)
  ]]);

  /* This use [x,y] directly
  var poly_from_points = turf.polygon([[
        [-75.343, 39.984],
        [-75.833, 39.284],
        [-75.534, 39.123],
        [-75.343, 39.984]]], { name: 'poly1' });
  */

  // These are points that need to find out ...
  // ... which are inside the polygons
  var four_points = turf.points([
    [-80, 30],
    [-70, 30],
    [-70, 50],
    [-80, 50],
    [-75.55, 39.35]
  ]);

  console.log("Points inside the polygon:");

  var ptsWithin = turf.pointsWithinPolygon(four_points, poly_from_points);
  console.log("Result:", ptsWithin);
  console.log("_End_");
  /* End of javascript code. */
} catch (err) {
  console.log("ERR! Turf is not loaded!");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/5.1.5/turf.min.js"></script>


text:
Q: How to make Python get_wch capture Enter key? When I am using
ch = wnd.getch()

in curses under Python, I can capture the enter key which wnd.getch returns 10. However it does not work when I replaced getch by get_wch. Is there any problems with get_wch?

A: The functions getch and get_wch have different interfaces:

*

*getch returns a character

*get_wch returns a status code, and sets a wide character via the pointer passed as a parameter.

They use different interfaces because special keys (such as KEY_HOME) can be handled with getch as "extra" characters beyond the range of "normal" (8-bit) characters.  You cannot do that with wide characters (not as easily, since the end of the wide character range is less definite), so get_wch uses a status code to tell if the value that it sets via the pointer is a wide character or a special key.
Although the manual page is clear enough, the python developers did not notice this distinction when adding the feature to the curses wrapper.  The description in the Python documentation corresponds to getch rather than get_wch:

*

*Issues #15785: curses.get_wch() returns keypad codes incorrectly

The bug report indicates that a fix was applied to python 3.4.

*16.10. curses — Terminal handling for character-cell displays

*window.get_wch([y, x])

Get a wide character. Return a character for most keys, or an integer for function keys, keypad keys, and other special keys.
New in version 3.3.

Further reading:

*

*getch, wgetch, mvgetch, mvwgetch, ungetch, has_key - get (or push back) characters from curses terminal keyboard

*get_wch, wget_wch, mvget_wch, mvwget_wch, unget_wch - get (or push back) a wide character from curses terminal
   keyboard


text:
Q: How to solve the diophantine equation $2(x+y)=xy+9$?
The following diophantine equation came up in the past paper of a Mathematics competition that I am doing soon: $$ 2(x+y)=xy+9.$$

Although I know that the solution is $(1,7)$, I am unsure as of how to reach this result. Clearly, the product $xy$ must be odd since $2(x+y)$ must be even, however beyond that, I am unable to see anything else that I can do to solve the problem. I have also tried using the AM-GM inequality, however, it did not simplify the problem much:$$(x+y)+(x-xy+y)\le(\frac{(x+y)+(x+y-xy)}{2})^2.$$
Any help would be greatly be appreciated.

A: We need to solve $$xy-2(x+y)+4=-5$$ or
$$(x-2)(y-2)=-5$$
and it remains to solve the following systems.
$x-2=1$ and $y-2=-5$;
$x-2=-1$ and $y-2=5$;
$x-2=5$ and $y-2=-1$ and
$x-2=-5$ and $y-2=1$,
which gives the answer: $\{(1,7),(7,1), (3,-3),(-3,3)\}$.

A: $2(x+y) = xy +9 \implies 2x - xy = 9 - 2y \implies x = \frac{9-2y}{2-y} = \frac{2y-9}{y-2} = 2 - \frac{5}{y-2}$.
If $x$ is an integer, then $\frac{5}{y-2}$ is also an integer. This will tell you what $y$ can be, then what $x$ can be. Trying these out will give you the solution $y=7, x=1$ and the solution $y=3,x=-3$, which then will give you four solutions, since you can switch $x,y$ (it doesn't change the equation) and get more solutions.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
& 2\pars{x + y} = xy + 9 \implies y = {2x - 9 \over x - 2} = 2 + {5 \over 2 - x}
\implies
\left\{\begin{array}{ll}
{\large\bullet} & \pars{2 - x} \mid 5
\\
{\large\bullet} & \pars{x \leq 2}\quad\mbox{or}\quad\pars{x \geq 5}
\\
{\large\bullet} & x\ odd
\end{array}\right.
\end{align}
If $\ds{x \geq 0}$ the only possibility is $\ds{\pars{x,y}
= \pars{\color{red}{\large 1},\color{red}{\large 7}}}$ or $\ds{\pars{x,y}
= \pars{\color{red}{\large 7},\color{red}{\large 1}}}$ because
$\ds{\verts{2 - x} \leq 5}$.


text:
Q: Manage Instances of the same Service I was wondering if someone here can help me with an issue:
I have this background service running that starts when the phone boots and, from then, every 15 min.
I want this same service to also start when i click the app icon. Is there any way i can manage the service's instances so I am 100% sure that only one instance of the service is running? I mean, I want to make sure that I only start one Service instance.
Sorry for the question but I'm a beginner and searched everywhere for this and still couldn't fine an exact answer for this issue (or maybe I'm the one that doesn't know how to look). If this question is already answered I'm sorry.
Cheers.

A: I'd recommend reading up on Services here: http://developer.android.com/guide/components/services.html.
To answer your question.  Only a single instance of a service is ever running at one time.  When you call startService(), If the service doesn't exist, it's created and the onStartCommand() is invoked.  If the service already exists though, then only the onStartCommand() method is invoked.  It will be your responsibility in onStartCommand() to determine if whatever operation you're running is currently running.