text:
Q: Deriving Multiplicative Update Rules for NMF How to derive the multiplicative update rules for the non-negative matrix factorization problem given by Lee and Seung.

Minimize $\left \| V - WH \right \|^2$ with respect to $W$ and $H$, subject to the constraints $W,H \geq 0.$

They have shown that the euclidean distance is non-increasing under multiplicative update rule but I am unable to figure out how the multiplicative update rules were derived. The multiplicative update rules are as follows:
\begin{equation}
W_{i,j} \leftarrow W_{ij}   \frac{(VH^T)_{ij}}{(WHH^T)_{ij}}
\end{equation}
\begin{equation}
H_{i,j} \leftarrow H_{ij}  \frac{(W^TV)_{ij}}{(W^TWH)_{ij}}
\end{equation}
For more information on the paper, click here. Please explain in layman terms without omitting any necessary steps.

A: $$\min_{W \in \mathbb{R}^{n \times k},H \in \mathbb{R}^{k \times m}}   \left \| V- WH \right \|^{2}_F \text{  s.t. }W,H \geq 0 $$
$$\;\;\;\;\;\;Tr((V-WH)^T(V-WH)) \;\;\;\;\;\; \scriptsize \left [   \left \|X \right \|^2 = Tr(X^TX) \right ]$$
$$  Tr((V^T - H^TW^T)(V-WH) ) = Tr( V^TV - V^TWH - H^TW^TV + H^TW^WWH) $$
using $Tr(A+B) = Tr(A) + Tr(B)$ we get,
$$Tr( V^TV) - Tr(V^TWH) - Tr(H^TW^TV) + Tr(H^TW^TWH) \;\;\;\;\;\; (1)$$
The non-negative matrix factorization problem is non-convex in W and H but it is convex in only W or only H. To optimize the above problem, we use a block coordinate descent scheme where we optimize with respect to $W$ first while keeping $H$ fixed and then vice versa.
$$W \leftarrow W -   \eta_W \cdot  \nabla_W f(W,H)$$
$$H \leftarrow H -   \eta_H \cdot  \nabla_H f(W,H)$$
Thus to solve the given problem, we need the derivatives of Eq. 1 with respect to $W$ and $H$. Since the terms in the equation are in trace form, it is simpler to get the derivatives using a few linear algebra rules.
The derivative of each term with respect to W,
$\nabla_WTr(V^TV) = 0$
$\nabla_WTr(V^TWH) = \nabla_WTr(HV^TW) = (HV^T)^T = VH^T \;\;\;\;\;\;\;\;\;\; \scriptsize \left [ \nabla_X Tr(AX) = A^T \right ]  $
$\nabla_WTr(H^TW^TV) =\nabla_WTr(VH^TW^T) = VH^T \;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\;\, \scriptsize \left [ \nabla_X Tr(X^TA) = A \right ] $
$\nabla_W Tr(H^TW^TWH) = \nabla_W Tr(WHH^TW^T)= W((HH^T)^T + HH^T) = 2WHH^T  \;\;\; \scriptsize \left [ \nabla_X Tr(XAX^T) = X(A+A^T) \right ]$
The derivatives with respect to H can computed similarly. Thus,
$$\nabla_W f(W,H) = -2VH^T + 2WHH^T$$
$$\nabla_H f(W,H) = -2W^TV + 2W^TWH$$
Using the above derivatives,
$$W \leftarrow W +   \eta_W \cdot (VH^T - WHH^T) $$
$$H \leftarrow H +   \eta_H \cdot (W^TV - W^TWH)$$
The constant $2$ can be adjusted in the learning rate and thus can be ignored for now. Traditionally in gradient descent, the learning rates are positive but since the subtraction of terms in the update rules can lead to negative elements, Lee and Seung in the above mentioned paper, proposed to use adaptive learning rates to avoid subtraction and thus the production of negative elements. The learning rates are defined in such a way that there is no subtraction in the update rules. Thus if we set $\eta_W = \frac{W}{WHH^T}$ and $\eta_H = \frac{H}{W^TWH}$, we arrive at the given update rules.
Another way to avoid subtraction and get the multiplicative update rule is to use the form,
$$\theta \leftarrow \theta \cdot \frac {\nabla_{\theta}^{-} f(\theta)}{\nabla_{\theta}^{+} f(\theta)}$$
where $\nabla_{\theta}^{-} f(\theta)$ and $\nabla_{\theta}^{+} f(\theta)$ are the negative terms and the positive terms, respectively, of the gradient $\nabla_{\theta} f(\theta)$.
Using the above mentioned formula and the derivatives produced earlier, we get the following update rule,
$$W \leftarrow W  \cdot \frac{(VH^T)}{(WHH^T)}$$
$$H \leftarrow H  \cdot \frac{(W^TV)}{(W^TWH)}$$
Lee and Seung provided the proof of convergence for these rules in the above mentioned paper.

A: A particularly simple explanation can be found in The Why and How of Nonnegative Matrix Factorization:
The authors use $X$ as $V$ and $F(W,H) = \| X - WH\|^2$. The following is from section on multiplicative update (its relation with gradient descent).

[...] Another more intuitive interpretation is as follows: we have
that
$\frac{[XH^T]_{ik}}{[WHH^T]_{ik}} \geq 1 \iff (\nabla_WF)_{ik} \leq 0$
Therefore, in order to satisfy [first order optimality condition], for each entry of W, the MU either (i) increase it if its partial
derivative is negative, (ii) decrease it if its partial derivative is positive, or (iii) leave it unchanged if
its partial derivative is equal to zero.

The paper also contains another explanation before that one, but I find this one the most straightforward.


text:
Q: Sum TD in TABLE

        One	123		32

        Two	52		53

        Three	234		56

$('#tab').click(function(){
   sum();
})

function sum(){
 //????
}

How is the best method for sum column from second and fourth TD and fill in to third TD for each TR?
LIVE: http://jsfiddle.net/bYf8C/

A: function sum(){
    $("tr").each(function(){
        var sum = parseFloat($(this).find("td:eq(1)").text()) +
                  parseFloat($(this).find("td:eq(3)").text());
        $(this).find("td:eq(2)").text(sum);
    })
}

Here, have a fiddle: http://jsfiddle.net/bYf8C/10/

A: demo: http://jsfiddle.net/bYf8C/2/
$('#tab').click(function(){
   sum();
})

function sum(){
    $('#tab').find('tr').each(function(){
        var first = $(this).children('td:eq(1)').text(),
            second = $(this).children('td:eq(3)').text();

        $(this).children('td:eq(2)').html(function(){
          return parseInt(first) + parseInt(second);
        });
    });
}

As Bojangles suggested in the comments, children() is faster than find(), and :eq is faster than :nth-child. My edit reflects that.

A: Here it is:
$(function() {
  $('#tab').on('click', function sum() {
    $('tr', this).each(function(index, tr) {
      var td1, td3;
      td1 = parseInt(tr.children[1].textContent, 10);
      td3 = parseInt(tr.children[3].textContent, 10);
      tr.children[2].innerHTML = td1 + td3;
    });
  });
});

Example: http://jsbin.com/uvuzeq/1/edit

A: function sum(){
   $('#tab tr').each(function() {
      var number1 = parseInt($(this).find("td").eq(1).html());
      var number2 = parseInt($(this).find("td").eq(3).html());
      $(this).find("td").eq(2).html(number1 + number2)
   });
}

Fiddle: http://jsfiddle.net/bYf8C/11/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to call a function from razorview to cshtml.cs I'm new to razor views and I need to pass data from a form to razor view where you can put a number and take it from your cs in a method, then I also need to be able to do the opposite, take data from the cs (a number) and pass them to the razor view.
My code actually contains this in the razor view:

@page
@model CountdownWebAPP.Models.CountdownModel
<form method="post">

                    Enter the number of seconds you want to count down

                <input type="number" id="RemainingTime" name="Remainingtime" />

                <button type="submit" value="Submit" class="btn btn-dark">Start</button>

</form>

                    Number of seconds missing:

and this in the cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace CountdownWebAPP.Views
{
    public class IndexModel : PageModel
    {
        private int time;
        [BindProperty]
        public int RemainingTimeP { get; set; }
        public void OnGet(int RemainingTime)
        {
            RemainingTimeP = RemainingTime;
        }
        public string EmailAddress { get; set; }
        public void OnPost()
        {
            var RemainingTime = Request.Form["RemainingTime"];
        }
    }
}


text:
Q: Symfony: var/cache/prod/pools is growing infinitely, what is causing this? How to avoid it? I deployed a website running Symfony 4.4. This website has very low traffic, but run automatic tasks (commands) several times per hour. It uses Doctrine to connect to a MySQL 5.6 database.
After one day, the size of the var/cache/prod/pools directory has grown to 198M.
The problem is that the filesystem is slow with so many files, so removing the old files after a deployment take so much time that sometimes it fails.
The directory contains directories:
$ ls var/cache/prod/pools/NPSipMZaUK/0/
+  -  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z

I looked at one file in a sub directory, it contains a Doctrine query and the mapping fields of the result. I see that an argument is written as is:
AND u0_.lastScan <= \'2022-06-13 23:21:52\'

So it looks like every query performed by Doctrine will create a file in this directory.

I don't have any specific configuration about Doctrine or the cache.
What process or configuration is creating the cache and all of these files? Are there options or alternatives to avoid creating all these files? The hosting provider (OVH) doesn't provide APCu or memcache.
The documentation about the cache doesn't mention this: https://symfony.com/doc/4.4/cache.html

Update: actually I was wrong, the project uses the default configuration from recipes and it defines the filesystem for storing the pools. Here is the documentation of the cache.

A: This cache can be cleared by pruning it:
php bin/console cache:pool:prune

I will run this command automatically every day.
Source.

Update: in order to disable this cache, I used this configuration that use the memory instead of the disk:
# config/packages/doctrine.yaml
when@prod:
    doctrine:
        orm:
            query_cache_driver:
                type: pool
                pool: doctrine.system_cache_pool
            result_cache_driver:
                type: pool
                pool: doctrine.result_cache_pool

    framework:
        cache:
            pools:
                doctrine.result_cache_pool:
                    adapter: cache.adapter.array
                doctrine.system_cache_pool:
                    adapter: cache.adapter.array


text:
Q: Automatic date function not working properly I made a budget spreadsheet for myself, and while I need to pretty it up a bit (because why not), everything works beautifully a full week later except one function (which seems to work in most cases.
Column D of the page 'Bills' contains the numerical day of the month that a bill is paid on. Column C of the same page has this function:

=IF(NOT(ISBLANK(D1)), IF(OR(AND('Current Week'!B$2 <= DATE(YEAR(TODAY()), MONTH(TODAY()), D1), DATE(YEAR(TODAY()),
  MONTH(TODAY()), D1) <= 'Current Week'!D$2), AND('Current Week'!D$2 <=
  DATE(YEAR(TODAY()), MONTH(TODAY()), D1),DATE(YEAR(TODAY()),
  MONTH(TODAY()), D1) <= EOMONTH(TODAY(),0))), DATE(YEAR(TODAY()),
  MONTH(TODAY()), D1), DATE(YEAR(TODAY()), MONTH(TODAY()) + 1, D1)), )

Which checks for that day being inside the current week and not before the end of the month, and turns it into the date that that bill would fall on. It works fine most of the time, including last week for the entire week, but this week, with the first of my pay-week being Tuesday, July 31 2018, it seems to have gone a little pear shaped and gone ahead and placed it into the next month (in this case, August 31) despite the 31st of July being part of this pay-week.
I feel like I've either AND-ed something incorrectly or else referenced a cell incorrectly, but I'll be damned if I can figure out where. Help!
Spreadsheet for reference (Page 'Bills' column D is the problem child. The lines "Paycheck 1" and "Example Bill showcase the problem)
https://docs.google.com/spreadsheets/d/1etOpyc_HkRjMTssWZyNX0ru-0RVaHO-NoJ1HljlzyAE/edit?usp=drivesdk


text:
Q: Structure text from words of triplets saved in a 2D list I am currently having a text with its words saved as triplets in an 2D list.
My 2D List:
[['Python', 'is', 'an'], ['interpreted,', 'high-level', 'and'], ['general-purpose', 'programming', 'language.'], ["Python's", 'design', 'philosophy'], ['emphasizes', 'code', 'readability'], ['with', 'its', 'notable'], ['use', 'of', 'significant'], ['whitespace.', 'Its', 'language'], ['constructs', 'and', 'object-oriented'], ['approach', 'aim', 'to'], ['help', 'programmers', 'write'], ['clear,', 'logical', 'code'], ['for', 'small', 'and'], ['large-scale', 'projects.']]

I am creating a Python code which picks one random set of these triplets, then tries to create a new random text by using the last 2 words and by choosing a triplet that starts with these two. Finally my program ends when 200 words are being written or none other triplet set can be chosen.
The code so far:
import random

with open(r'c:\\python\4_TRIPLETS\Sample.txt', 'r') as file:
    data = file.read().replace('\n', '').split()
    lines = [data[i:i + 3] for i in range(0, len(data), 3)]
    random.shuffle([random.shuffle(i) for i in lines])

first_triplet = random.choice(lines)
last_two = first_triplet[1:3]

output_text=[]
while True:
    candidates = [t for t in lines if t[0:2] == last_two]
    if not candidates:
        break

    next_triplet = random.choice(candidates)
    last_two = next_triplet[1:3]
    output_text.append(next_triplet)

I can't automate the repetitive procedure of searching of matches and storing them at a new list.
Any ideas?

A: You can use a recursive function (changed some parts of the code, check comments):
import random

#adding ["is", "an", "experiment"] to check if it works (no other triplet were present that satisfy the condition)
lines = [['Python', 'is', 'an'], ['interpreted,', 'high-level', 'and'], ['general-purpose', 'programming', 'language.'], ["Python's", 'design', 'philosophy'], ['emphasizes', 'code', 'readability'], ['with', 'its', 'notable'], ['use', 'of', 'significant'], ['whitespace.', 'Its', 'language'], ['constructs', 'and', 'object-oriented'], ['approach', 'aim', 'to'], ['help', 'programmers', 'write'], ['clear,', 'logical', 'code'], ['for', 'small', 'and'], ['large-scale', 'projects.'], ["is", "an", "experiment"]]

first_triplet = ['Python', 'is', 'an'] # random.choice(lines)

def appendNextTriplet(output_text, lines):
    if len(output_text) >= 200:
        return output_text
    candidates = [t for t in lines if t[:2] == output_text[-2:]]
    if not candidates:
        return output_text
    next_triplet = random.choice(candidates)
    output_text += next_triplet # changed from append to concatenation, it was not correct
    return appendNextTriplet(output_text, lines)

print(appendNextTriplet(first_triplet, lines)) # ['Python', 'is', 'an', 'is', 'an', 'experiment']

A: import random
import sys
import os
import json

outlist = []
file_in = sys.argv[1]
file_ot = str(file_in) + ".ot"

with open(file_in, 'r') as file:
    data = file.read().replace('\n', '').split()
    lines = [data[i:i + 3] for i in range(0, len(data), 1)]
print("\nΧωρισμένο Κείμενο σε Λίστα Τριπλετών:\n", lines)

triplet = random.choice(lines)
last_two = triplet[1:3]

print("\nΕπιλεγμένη Τριπλέτα: \n", triplet)
print("\nΔύο Τελευταίες Λέξεις Αυτής:\n", last_two)
outlist.extend(triplet)

proc_list = lines
# first selected, remove from list
proc_list.remove(triplet)

n = 0
while True:

    n += 1
    print("\nΕπανάληψη {0}\n".format(n))

    if proc_list == 0:
        print("a")
        break

    random.shuffle(proc_list)

    candidates = []

    for element in proc_list:
        if element[:2] == last_two:
            candidates.append(element)

    print(candidates)

    if not candidates:
        print("b")
        break

    if len(outlist) >= 200:
        print("c")
        break

    triplet = random.choice(candidates)
    outlist.append(triplet[-1])
    proc_list.remove(triplet)

    last_two = triplet[1:3]
    print(outlist)

with open(file_ot, 'w') as f:
    f.write(json.dumps(outlist, indent=10))

print(" ".join(outlist))


text:
Q: How to use useState properly in this example? I have the following code:
const [data, setData] = useState({
        name: '',
        surname: '',
        email: '',
        password: ''
    });

However, I need to have something like:
 const [name, setName] = useState('');
 const [surname, setSurname] = useState('');
 const [email, setEmail] = useState('');
 const [password, setPassword] = useState('');

but still keeping the setData() function, as it is used.

A: You can add a function which will accept all of your parameters and uses your defined useState methods.
This way you can customize and check for the value of the parameters too.
So it would be like below:
function Example() {
    const [name, setName] = useState('');
    const [surname, setSurname] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    function changeData({name, surname, email, password}){
        // call your setSates here
        setName(name)
        setName(surname)
        setName(email)
        setName(password)
    }

}

Notice that if you want to check the parameters to be passed you have to check them not to be undefined. If you don't check that it will set the variables to undefined

A: If I am understanding correctly, what you're looking for is a solution like the following:
function MyComponent(props) {
  const [data, setData] = React.useState({
    name: '',
    surname: ''
  })

  // will use `useEffect` as an example with an API call
  React.useEffect(() => {
    SomeAPICall()
      .then((data) => {
        setData({
          ...data,
          name: data.name
        })
      })
  })
}

When calling setState, you need to copy the current state and update the property/properties that you want.

Alternatively, you could use React.useReducer to accomplish the same thing:
function MyComponent(props) {
  const [state, setState] = React.useReducer((p, n) => ({ ...p, ...n }), {
    name: '',
    surname: ''
  });

  // will use `useEffect` as an example with an API call
  React.useEffect(() => {
    SomeAPICall().then((data) => {
      setState({
        ...state,
        name: data.name
      })
    })
  })
}

Similarly, you need to take the old state and update it with new values, then pass it to setState.

The spread syntax copies properties of an existing object onto a new object. Here's some reference if you're not familiar with this approach:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

A: you can use setData to update individual properties.
const [data, setData] = useState({
    name: '',
    surname: '',
    email: '',
    password: ''
});

const setValue = (fieldName, value) => setData({...data, [fieldName]: value});

// to update name
setValue("name", "bob");


text:
Q: Hijack laptop's display, connect to PC My son has a PC with no monitor, and an OLD laptop (circa 2002). They both support VGA. Is there an easy way to connect the PC to the laptop such that the PC displays on the laptop's screen? So basically the laptop's internals are not being used, we just want to use its display for a connected PC. The laptop does work, it's just too slow to be useful. But its built-in monitor still works fine.
Is there any way?

A: Not likely possible. Normal VGA is uni-directional, so even if you managed to physically connect the PC's VGA-out to the laptop's VGA-out, it would be the electrical equivalent of driving two cars towards each other -- in a single lane!
It may be possible to engineer a bidirectional VGA port that has automatic directional override, but it's either (a) too difficult or (b) too expensive, otherwise most laptops would offer the feature, and then it would already be common knowledge.
It may be feasible to disassemble the laptop and hack the screen's connection to the mainboard, but chances the manufacturer put their own twist on whatever is driving the display, and you won't find a simple "VGA signals go in here" place to wedge in your PC's VGA output.

A: Using cables will not work because the ports on laptops are usually for output not input.
You should consider using Remote Desktop or things like this. If you cant, you are out of luck.
Its better to buy a new monitor, a LCD maybe since LCDs show things almost same as LEDs and they cost lesser. New monitor worth the price.

A: You can not use the VGA output connector on your laptop as an input.
However what you can do is use a video grabber. This is a device that takes an input (e.g. from VGA) and turns it into digital information (e.g. to record what would normally appear in the screen. Think of it as an 'image microphone'.
Then 'play' the captured image in real time on the laptops display.

Note that such a device might be more expensive than a new monitor.

A: to assume the laptop and monitor have one of the following connections yes:
1)  serial to serial  (like the old printer connections)
2) vga to vga/dvi/hdmi
or you can somehow convert the  presumably vga connection on the laptop to  dvi/hdmi


text:
Q: How do I connect a page on my website to post on facebook I was searching for a while, but probably I'm just not using the right keywords.
Right now I have two separate things:
1) Articles on my website. Each article has a facebook like/recommend this article button at the end of the article. I.e. you can scroll to the bottom of the article here - http://www.thecheers.org/Travel/article_4915_Ryanair---how-can-they-fly-with-their-prices.html - you'll probably see that there's a text next to the button saying that "13 people recommend this".
2) I have a facebook page which has also posted a link to this article there. The post on Facebook page has a couple of likes.
The question - how can I make it so that when someone clicks the Recommend button on my website, it would also update the number of post likes on my facebook page? Keeping in mind that I am not talking about Facebook page likes but individual facebook post/article likes.
Any ideas? IN theory, it sounds like it should be easy...yet right now it doesn't really look like it.

A: Number of likes on a Facebook publication can be only increased by "real people" liking via Facebook. No third-party integration or API can deal with likes counter.


text:
Q: synchronize text boxes of two clients I am a new bee to AJAX. i want to synchronize text box of one client and the text box of another client that is contents typed by one client in his text box should be viewed by another client in his text box.
I wrote a code to write the contents of text box of clients to a single file and to load the contents of the file at the same time to the text boxes of clients but the problem was only loading from file to text box happens and it is not writing the text box values to the file.
my code is:
index.php
<html>
<head>
<script type="text/javascript">
function fun1()
{
var a;

if (window.XMLHttpRequest)
{
  a=new XMLHttpRequest();
}
else
{
a=new ActiveXObject("Microsoft.XMLHTTP");
}

name=encodeURIComponent(document.getElementById("name").value);
a.open("GET","quickstart.php?name=" + name,true);

a.onreadystatechange=function()
{

document.getElementById("name").value=a.responseText;

}

a.open("POST","123.txt",true);

a.send();

} // fun1() close

</script>
</head>
<body>
<input type="text" id="name" onkeyup="fun1()" />

</body>
</html>

quikstart.php
<?php
header('Content-Type: text/xml');

echo '<response>';
$name=$_GET['name'];
$file=fopen("123.txt","w");
fwrite($file, $name);
fclose($file);
echo '</response>';
?>


text:
Q: Can't pass apex trailhead challenge even though code works fine I'm going through the Bulk Apex Trigger module and I can't get to pass the hands on challenge even though my code works correctly.
This is the code I wrote:
trigger ClosedOpportunityTrigger on Opportunity (after insert, after update) {

    List<Task> tasksToCreate = new List<Task>();

    for (Opportunity a : Trigger.new) {

        if (a.StageName == 'Closed Won') {

            Task newTask = new Task();
            newTask.Subject = 'Follow Up Test Task';
            newTask.WhatId = a.Id;

            tasksToCreate.add(newTask);

        }
    }

    if (tasksToCreate.size() > 0) {
        insert tasksToCreate;
    }
}

Code works fine. I've tested it and it creates a task whenever an opportunity is either created or updated with a status of Closed Won. So why can't I pass the challenges? I get the following error:

I just want to understand whether I'm missing something or the issue is in trailhead doing some weird stuff when checking challenges.

A: I just tested your code in my Trailhead, and it works, which I expected it to, as it meets the design specs. If you're having trouble, make sure that (a) you're using the correct trailhead org, (b) you successfully saved the file (e.g. it didn't have a stray character that caused a compilation error), and (c) you don't have any other triggers or processes that may interfere (e.g. validation rules). If you're still having problems, create a new Trailhead Org and copy the code fresh into that org.

A: Since you are expecting to work on 'after insert' and ' after update', you need to write DML statement as upsert.
Below is my code and it worked:
trigger ClosedOpportunityTrigger on Opportunity (after insert,after update) {
list<Task> newTask= new list<Task>();
    for(Opportunity oppWon :[Select Id from Opportunity where StageName='Closed Won'
                            and Id in: Trigger.new]){
        newTask.add(new Task (Subject ='Follow Up Test Task',WhatId=oppWon.Id));
    }
    if(newTask.size()>0){
        upsert newTask;
    }
}


text:
Q: GeoPandas: Calculate coordinates of a point within a linestring I have two datasets, one is a GeoJSON of a highway with around 1509 linestrings.
The other is a list of incidents that have occurred along said highway, but, instead of coordinates, the file specifies the kilometer where the incident happended.
I.e

incident_id
km
incident_type

1
10
vehicle theft

2
152
dui

What I need to do is get the coordinates of each incident.
I know that you can calculate the distance between two coordinates using geopy.distance, but is there any way to calculate the coordinates of a point which is x kilometers away from a given set of coordinates?


text:
Q: Minting NFT on rinkeby network with opensea testnet, images not showing so tested with the "validity" site, saying "valid: false"? enter image description here
So as title, I am doing a testrun of minting NFTs using rinkeby network on testnet opensea, the images are just not showing up on there, so I used the site
https://testnets-api.opensea.io/asset///validate/
to check for validity,
as in the photo it is saying valid is false, does that mean something is wrong with the .json file (metadata) itself, or can it be something else, if so, like what?


text:
Q: Static class in typescript Is there any way to create an static class in typescript, node.js
I want to create an static class to keep all constants and string in that.
what could be the best way to do that ?

A: You can put your variables and functions you want inside a module which means that it doesn't have to be instantiated.
module constants {
   export var myValue = 'foo';

   export function thisIsAStaticLikeFunction () {
      console.log('function called');
   }
}

.....
console.log(constants.myValue);

There really is no such thing as a true static class, but this comes pretty close to replicating it.

A: Sure you can define a class with static properties:
export class Constants {
    static MAX_VALUE = 99999;
    static MIN_VALUE = 0;
}

Then use it when you need:
import { Constants } from '../constants';
console.log(Constants.MAX_VALUE);

A: Now you can use Enums like that:
export enum Numbers {
   Four = 4,
   Five = 5,
   Six = 6,
   Seven = 7
}

Then use it:
import { Numbers } from './Numbers';
Numbers.FIVE


text:
Q: Database "Migration" for Plugins? I'm creating a plugin for WordPress.  This plugin will need to save data to the database.  In other programming frameworks I've worked with, there are systems called "database migrations".  These migrations are

*

*SQL ALTER TABLE or CREATE TABLE statements/scripts

*Sometimes abstracted into the programming language of the framework

*Written and stored in a common way such that a user of my plugin/extension/etc can say "run the migrations" and the database will be update, per my instructions

*

*And sometimes includes features that allow you to "rollback" those changes

An example migration system is Laravel's.
Does WordPress have a system that's similar to migrations?  If not, is there a canonical way (via a particular hook, plugin registration, etc) to package up the new database tables and/or changes to existing WordPress tables my plugin will need?

A: Surprisingly not. Instead, you need to use the following function which is run whenever the plugin is activated.
define( 'YOUR_PLUGIN_VERSION', '1.0.0' );

register_activation_hook( __FILE__, 'your_plugin_activation_function' );

function your_plugin_activation_function() {
  // Do activation tasks here.
  your_install_function();
  your_upgrade_migration_function();
}

Run your install script.
function your_install_function() {

  // Set the current version of the plugin in the db.
  update_option( 'your_plugin_version', YOUR_PLUGIN_VERSION );
}

Then for each new version, you do a compare which basically performs your database migrations, etc.
function your_upgrade_migration_function() {

  // Using a version prior to 1.1.1
  if ( version_compare( YOUR_PLUGIN_VERSION, '1.1.1', '<' ) ) {
    // Do upgrade things unique for this version.
  }

  // Using a version prior to 1.2.0
  if ( version_compare( YOUR_PLUGIN_VERSION, '1.2.0', '<' ) ) {
    // Do upgrade things unique for this version.
  }
}


text:
Q: Should mobile app questions be closed now that the apps are officially retired? Today, Yaakov Ellis, a Stack Exchange staff member, stated in response to an app bug report that,

We are not providing any further support for the mobile apps. There will not be any more builds made for either the Android or the iOS app (even for breaking bugs). We encourage all mobile users to use the responsive website. We hope to continue to incrementally improve the user experience for mobile users.

Should we now close app bug reports? I'm thinking about either closing them as "can no longer be reproduced" (as they cannot be reproduced any more by any current software) or as duplicates of a canonical "The app is broken???->The apps are no longer supported, please use the responsive website kthx." post, but wanted to see what the community consensus is on the disposition of these posts (of which there are many, both recent and not-so-recent).

A: Somehow I managed to miss this question, but the problem being addressed was the main reason I started a canonical post: How can I report bugs with or request features for the Stack Exchange mobile apps? which has been extensively edited by the community and nowadays is used as dupe target for almost all new ios-app and android-app questions. According to one of Shog9's SEDE queries found by @zcoop98, 70 times already. So my observation is that we've chosen the

as duplicates of a canonical "The app is broken???->The apps are no longer supported, please use the responsive website kthx." post

way.

A: Perhaps just have "archived" questions added so if someone is using an older version for whatever reason, they can still find the solutions to asked questions, but have someway for people that are using the most up-to-date versions don't have to sift through a ton of outdated questions. As this is pretty common with how fast updates can happen with mobile projects.


text:
Q: How to condense PowerShell script to fit on a single line Quick question. I am trying to write the following PowerShell script, but I would like it to fit on a single line:
$app = New-Object -comobject Excel.Application
$wb1 = $app.Workbooks.Open("C:\xampp\upload_files\Launchpad.xlsm")
$app.Run("Refresh")
$wb1.Close($false)
$app.Quit()

The pseudo-code would look something like this:
$app = New-Object -comobject Excel.Application AND $wb1 = $app.Workbooks.Open AND "C:\xampp\upload_files\Launchpad.xlsm") AND $app.Run("Refresh") AND $wb1.Close($false) AND $app.Quit()

The reason I want to fit on a line is because I would like to insert the arguments directly in the 'arguments' box of Windows Task Scheduler. The reason for this is that for some reason scripts have been disabled (e.g. I cannot call a .ps1 file...)
I know this will still work, as I already have a "one liner" PS script running. What would the syntax look like??
Kind regards,
G.

A: Powershell statements can be separated with semicolons:
$app = New-Object -COM 'Excel.Application'; $wb1 = $app.Workbooks.Open("..."); ...

The PowerShell executable takes a -Command parameter that allows you to specify a command string for execution in PowerShell:
powershell.exe -Command "stmnt1; stmnt2; ..."

To run this via Task Scheduler you'd put powershell.exe into the "program" field and -Command "stmnt1; stmnt2; ..." into the "arguments" field of the task.
However, as @alroc said: you should verify why script execution has been restricted. If it's just the default setting you can simply change it by running Set-ExecutionPolicy RemoteSigned or override it by adding -ExecutionPolicy ByPass to a PowerShell command line. However, if the setting is enforced by policy changing/bypassing the setting will fail, and you could get into quite some trouble for violating company policies.

A: Here is a solution that you might use if the script is not that easy to convert, but you are on Windows running at least PowerShell V5.
It converts the code into Base64 and uses PowerShell.exe with the parameter -encodedCommand to pass the encodedCommand as string.
$command = Get-Content .\YourPowerShellFileContainingTheCode.ps1 -raw
# Get-Content may require "-encoding utf8" or other encodings depending on your file
$encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
Write-Output "Text for application:"
Write-Output "PowerShell.exe" ""
Write-Output "Text for argurments:"
Write-Output "-encodedCommand $encodedCommand"

It would look like this, but with a much larger command:
Text for application:
PowerShell.exe

Text for argurments:
-encodedCommand SABvACAASABvACAASABvACwAIABzAHQAYQBjAGsAbwB2AGUAcgBmAGwAbwB3AA==


text:
Q: Listing and adding JMS Physical Destinations to GlassFish v3.1 After adding a destination(Queue) to Destination Resources from Admin Console at Resources/JMS Resources/Destination Resources, no physical destinations are displayed at server(Admin Server)/JMS Physical Destinations .Instead, the following error message is displayed below the heading:
An error has occured
Unable to list JMS Destinations
Also, on trying to add a new Physical Destination at server(Admin Server)/JMS Physical Destinations, of type 'Queue', following error message is displayed:
An error has occured
Unable to create JMS Destination
On trying to add a Physical Destination using asadmin in command-line as:
asadmin> create-jmsdest -T queue DemoQueue

the following error is displayed:
remote failure: Unable to create JMS Destination.

Command create-jmsdest failed.

Here, GlassFish Server Open Source Edition 3.1-b24 is run on Ubuntu with kernel 2.6.28-11-server.
Any help is appreciated.

A: I don't think that you should create physical destinations manually. All you need to do to set up JMS resources in GlassFish is defining a connection factory and destinations - all under Resources - JMS resources branch in admin interface. When your destinations are used physical destinations will be created automatically.

A: confused me to no end first time so I sympathise
For GFv2.1.1 (and I suspect for v3) a physical destination - mq.sys.dmq - is already created and configured and queues are created here.  The messaging server is SunMQ and if it is your intention to use this out-of-the-box then you don't need to create another physical destination.
if you do indeed need to create another physical destination launch [path-to-glassfish]/imq/bin/imqadmin.exe (or ubuntu equiv) and do it there.


text:
Q: Why, intuitively, is the order reversed when taking the transpose of the product? It is well known that for invertible matrices $A,B$ of the same size we have $$(AB)^{-1}=B^{-1}A^{-1} $$
and a nice way for me to remember this is the following sentence:

The opposite of putting on socks and shoes is taking the shoes off, followed by taking the socks off.

Now, a similar law holds for the transpose, namely:
$$(AB)^T=B^TA^T $$
for matrices $A,B$ such that the product $AB$ is defined. My question is: is there any intuitive reason as to why the order of the factors is reversed in this case?
[Note that I'm aware of several proofs of this equality, and a proof is not what I'm after]
Thank you!

A: A matrix is a collection of entries that may be represented with 2 indices. When we multiply two matrices, each resultant entry is the sum of the products
$$C_{ik} = \sum_j A_{ij} B_{jk} $$
Crucially, the 'middle' index, $j$, must be the same for both matrices (the first must be as wide as the second is tall).
A transpose is just a reversal of indices:
$$A_{ij}^T = A_{ji}$$
It should now go without saying that
$$C_{ik}^T = C_{ki} = (\sum_j A_{ij} B_{jk})^T = \sum_j B_{kj} A_{ji}$$
Memory shortcut: multiplication fails immediately for non-square matrices when you forget to commute for a transpose.

A: the intuitive reason is that the entries of a product matrix are feynman path integrals, and transposing the matrixes corresponds simply to reversing the arrow of time for traveling along the paths.
(so it's practically the same idea as in your shoes-and-socks example: matrix transposition is about time-reversal, just like function inversion is about time-reversal.)
the (i,k)th entry in a product matrix ab is the sum over j of a(i,j).b(j,k).  in other words, it's a sum over all "2-step paths" (i,j,k) from i to k, each path visiting one intermediate point j on its way from i to k.
this sum over paths is called a "feynman path integral".  if you read feynman's original paper on the subject, focusing on the parts that are easy to understand, you'll see that that was feynman's basic message: that whenever you have a big long string of matrixes to multiply, each entry in the product matrix is a "sum over paths" aka "path integral", with the contribution of each particular path being a long product of "transition quantities", each associated with one transition-step along the path.
this "path" interpretation of matrix multiplication actually gets more intuitive for longer strings of matrixes, because then each path consists of many steps.  for example each entry of a matrix product abc...z is a sum over 26-step paths; each path visits 27 points but with just 26 transition-steps from one point to the next.

A: $\hspace{3cm}$
Turn (transpose) to the street $B^T$ perpendicular $B$, then turn (transpose) to $A^T$ perpendicular $A$.

A: [this is an attempt to combine two previously given answers, mdup's video demo and my "path-sum" story, so it might help to refer to those.]
after watching mdup's video demo i started wondering how it relates to the "path-sum" interpretation of matrix multiplication.  the key seems to be that mdup's hand-drawn picture of the matrix product AB wants to be folded up to form the visible faces of an oblong box whose three dimensions correspond precisely to the points i, j, and k in a three-point path (i,j,k).  this is illustrated by the pairs of pictures below, each pair showing the oblong box first in its folded-up 3-dimensional form and then in its flattened-out 2-dimensional form.  in each case the box is held up to a mirror to portray the effect of transposition of matrixes.
in the first pair of pictures, the i, j, and k axises are marked, and in the folded-up 3-dimensional form you can see how transposition reverses the order of the axises from i,j,k to k,j,i.  in the flattened-out 2-dimensional form you can see how it wants to be folded up because the edges marked j are all the same length (and also, because it was folded up like that when i bought the soap).

(source: ucr.edu)

(source: ucr.edu)
the second pair of pictures indicate how an entry of the product matrix is calculated.  in the flattened-out 2-dimensional form, a row of the first matrix is paired with a column of the second matrix, whereas in the folded-up 3-dimensional form, that "row" and that "column" actually lie parallel to each other because of the 3d arrangement.

(source: ucr.edu)

(source: ucr.edu)
in other words, each 3-point path (i,j,k) corresponds to a location inside the box, and at that location you write down (using a 3-dimensional printer or else just writing on the air) the product of the transition-quantities for the two transition-steps in the path, A_[i,j] for the transition-step from i to j and B_[j,k] for the transition-step from j to k.  this results in a 3-dimensional matrix of numbers written on the air inside the box, but since the desired matrix product AB is only a 2-dimensional matrix, the 3-dimensional matrix is squashed down to 2-dimensional by summing over the j dimension.  this is the path-sum- in order for two paths to contribute to the same path-sum they're required to be in direct competition with each other, beginning at the same origin i and ending at the same destination k, so the only index that we sum over is the intermediate index j.
the 3-dimensional folded-up form and the 2-dimensional flattened-out form have each their own advantages and disadvantages.  the 3-dimensional folded-up form brings out the path-sums and the 3-dimensional nature of matrix multiplication, while the 2-dimensional flattened-out form is better-adapted to writing the calculation down on 2-dimensional paper (which remains easier than writing on 3-dimensional air even still today).
anyway, i'll get off my soapbox for now ...

A: By dualizing $AB: V_1\stackrel{B}{\longrightarrow} V_2\stackrel{A}{\longrightarrow}V_3$, we have $(AB)^T: V_3^*\stackrel{A^T}{\longrightarrow}V_2^*\stackrel{B^T}{\longrightarrow}V_1^*$.
Edit: $V^*$ is the dual space $\text{Hom}(V, \mathbb{F})$, the vector space of linear transformations from $V$ to its ground field, and if $A: V_1\to V_2$ is a linear transformation, then $A^T: V_2^*\to V_1^*$ is its dual defined by $A^T(f)=f\circ A$. By abuse of notation, if $A$ is the matrix representation with respect to bases $\mathcal{B}_1$ of $V_1$ and $\mathcal{B}_2$ of $V_2$, then $A^T$ is the matrix representation of the dual map with respect to the dual bases $\mathcal{B}_1^*$ and $\mathcal{B}_2^*$.

A: One of my best college math professor always said:

Make a drawing first.

Although, he couldn't have made this one on the blackboard.

A: They key property of the transpose is that it is the unique matrix which satisfies
$$
\langle Ax, y \rangle = \langle x, A^T y \rangle
$$
for all $x,y$.
Notice that
\begin{align}
\langle B A x, y \rangle &= \langle Ax, B^T y \rangle \\
&= \langle x, A^T B^T y \rangle
\end{align}
for all $x,y$. This shows that
$$
(BA)^T = A^T B^T.
$$

A: Here's another argument. First note that if $v$ is a column vector then $(Mv)^T = v^T M^T$.  This is not hard to see - if you write down an example and do it both ways, you will see you are just doing the same computation with a different notation.  Multiplying the column vector $v$ on the right by the rows of $M$ is the same as multiplying the row vector $v^T$ on the left by the columns of $M^T$.
Now let $( \cdot , \cdot )$ be the usual inner product on $\mathbb{R}^n$, that is, the dot product.  Then the transpose $N = M^T$ of a matrix $M$ is the unique matrix $N$ with the property
$$(Mu, v) = (u, Nv).$$
This is just a consequence of associativity of matrix multiplication.  The dot product of vectors $u,v$ is given by thinking of $u,v$ as column vectors, taking the transpose of one and doing the dot product: $(u,v) = u^T v$.
Then $(Mu,v) = (Mu)^T v = (u^T M^T) v =  u^T (M^Tv) = (u, M^Tv)$.
Exercise: Show uniqueness!
With this alternate definition we can give a shoes-and-socks argument.  We have
$$( ABu, v) = (Bu, A^Tv) = (u, B^TA^Tv)$$
for all $u,v$, and so $(AB)^T = B^T A^T$. The argument is exactly the same as the one for inverses, except we are "moving across the inner product" instead of "undoing".

A: Each element of the matrix $AB$ is the inner product of a row of $A$ with a column of $B$.
$(AB)^T$ has the same elements that $AB$ does (just in different places), so its elements too must each come from a row of $A$ and a column of $B$.
However if we want to start with $A^T$ and $B^T$, then a row of $A$ is the same thing as a column of $A^T$ (and vice versa for $B$ and $B^T$), so we need something that has columns of $A^T$ and rows of $B^T$. The matrix that we take columns from is always the right factor, to $A^T$ must be the right factor in the multiplication.
Similarly, $B^T$ must be the left factor because we need its rows (which are columns of the original $B$).

A: (Short form of Jair Taylor's answer)
In the expresson $v^tA B w$, vectors $v$ and $w$ "see" $A$ and $B$ from different ends, hence in different order.

A: Considering the dimensions of the various matrices shows that reversing the order is necessary.
If A is $m \times p$ and B is $p \times n$,
AB is $m \times n$,
(AB)$^T$ is $n \times m$
A$^T$ is $p \times m$ and B$^T$ is $n \times p$
Thus  B$^T$A$^T$ has the same dimension as(AB)$^T$

A: In electrical engineering this can be illustrated nicely as time reversal of FIR filters.
Convolution with a FIR filter can be represented by a circulant or Toeplitz matrix. How far from the diagonal the values are, the further into the future or past they select their values.
The trivial example is probably a permutation matrix which is power of cyclic group generator element representation matrix.

A: I'm going to make @JohnCFrain's answer a little more intuitive.
Lets say that we have matrix $A$ which is
$m*p$
And we have matrix $B$ which is
$p*n$
Remember that columns of A has to equal rows of B
Then we take $A^T$, it is
$p*m$
Because the rows and columns switch.
And we have $B^T$, which is
$n*p$
But, we have to switch because the columns of $A^T$ are not equal to the rows of $B^T$ --> $m \neq n$, so we can't multiply (which is why we switched).
Hope this helped someone who happened to scroll down (4 years and 2 months after original post)! :D


text:
Q: Swift errors: 'manager()' is unavailable: use object construction 'AFHTTPRequestOperationManager()' I have this swift code that I think should work but it can't handle objective c static fields. I have tried to add "()" multiple places but nothing works.
func AFHTTPRequestOperationManagerDispatchOnMainQueue(mainQueue: Bool) -> AFHTTPRequestOperationManager {
    var manager = AFHTTPRequestOperationManager.manager
    manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
    manager.requestSerializer = AFJSONRequestSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
    if (!mainQueue) {
        manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    }
    return manager;
}

The field and properties looks like this:
+ (instancetype)manager;
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

I get those error messages:

Error: 'manager()' is unavailable: use object construction
  'AFHTTPRequestOperationManager()' Error: '() ->
  AFHTTPRequestOperationManager!' does not have a member named
  'responseSerializer' Error: '() -> AFHTTPRequestOperationManager!'
  does not have a member named 'requestSerializer' Error: '() ->
  AFHTTPRequestOperationManager!' does not have a member named
  'completionQueue' Error: function produces expected type
  'AFHTTPRequestOperationManager!'; did you mean to call it with '()'?

A: When Objective-C is imported into Swift, as you're doing with AFNetworking here, identifiable factory methods are converted to simple initializers.  In this case that means that (as @Martin points out) you should be using that form instead:
var manager = AFHTTPRequestOperationManager()


text:
Q: Dynamically add a Dojo-enabled Element in Zend I'm writing a form using Zend_Dojo_Form.
Everything goes fine, unless I dynamically insert elements into the form (using ajax, the user can add more elements by clicking a [+] button).
I managed to insert my new Zend_Dojo_Form_Element_FilteringSelect into the page, but the element isn't dojo-enabled (no auto-completion, or tundra styling).
I'm guessing dojo transforms existing form elements once the page is loaded the first time, and doesn't parse them again when a new node is added... But I can't find how to tell dojo there's new elements in town.
What I've tried:

*

*Executing dojo.parser.parse(); or dojo.parser.parse('id_of_new_element'); after the insertion of a new element

*Adding Zend_Dojo_View_Helper_Dojo::setUseDeclarative(); in my Dojo_Form's init() method (as seen on nabble's forums)

My method for adding new elements is the one described by Jeremy Kendall.
I don't know if my problem comes from an incompatibility with Zend, Dojo, or if I'm missing something...

A: After some fiddling I finally managed to get it running.
In Jeremy Kendall's javascript code you have to insert the following script in the function ajaxAddField()
// Insert new element before the Add button
$("#addElement-label").before(newElement);

// Parse the element to receive Dojo style
var n = dojo.byId("newName" + id);
n.outerHTML = newElement;
dojo.parser.parse(n);

and replace
searchString = '*[id^=newName' + lastId + '-]';
$(searchString).remove()

in the function removeField() by
// Destroy dijits before destroying the node
var n = dojo.byId("newName" + lastId);
var dijits = dijit.findWidgets(n);
if (dijits) {
    for (var i = 0, n = dijits.length; i < n; i++) {
        dijits[i].destroyRecursive();
    }
}
dijits = dojo.parser.parse("newName" + lastId);

// Destroy the node
dojo.destroy("newName" + lastId);

Maybe there is still a better way to do it, but it worked for me. When removing the node, the dijits have to be destroyed before since otherwise the HTML fragment will not get parsed again.


text:
Q: Need help getting a javascript/html slider to work I am trying to get the below html code to work and can't figure it out.  I do not think the domready event is being fired and can't figure out why.
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>

I just want to have a slider on my webpage and can't use html 5 because of browser restrictions.  What is the simplest slider I can use to do this?

A: First problem that I see is in the var slider = $('slider'); statement.
You need to change it to var slider = $('#slider'); or var slider = $('.slider'); depends on if you want to access it via ID or CLASS name.
You can also use http://nivo.dev7studios.com/ as a slider which is a good jQuery plugin that I've been using.

A: Rather than using window.addEvent();, why not use
$(function(){
    // your code here.
});

That uses jQuery's on ready event, so you can be sure it will fire on document ready
And as stated by Odinn above, you are using $('slider'), which means that jquery is looking for an element that is . you need to specifiy if you are searching for an ID $('#slider') or by class $('.slider');
Other than that, i would keep your console open to look for any errors and post those. Hope that helps.


text:
Q: How to check similarity between two name pairs interchangeably and give them a unique identifier in python pandas dataframe? I have a dataframe as follows,
df_names = pd.DataFrame({'last_name':['Williams','Henry','XYX','Smith','David','Freeman','Walter','Test_A'],
                        'first_name':['Henry','Williams','ABC','David','Smith','Walter','Freeman','Test_B']})

A new column full name adding last and first names as below -

Here i would like to check how similar the full names are ? Williams Henry and Henry Williams to be considered as same and give it a unique identifier some random code.
similarly Smith David and David Smith should also be consider as one unique identifier.
Final expected output as below.

A: Use:
res = (df_names.assign(group=df_names[["last_name", "first_name"]].apply(frozenset, axis=1))
               .groupby("group")
               .ngroup() + 1)

df_names["unique_identifier"] = "A-" + res.astype("string")
print(df_names)

Output
  last_name first_name unique_identifier
0  Williams      Henry               A-1
1     Henry   Williams               A-1
2       XYX        ABC               A-2
3     Smith      David               A-3
4     David      Smith               A-3
5   Freeman     Walter               A-4
6    Walter    Freeman               A-4
7    Test_A     Test_B               A-5

The idea is to use frozenset to map each row to an object where the order of the elements is irrelevant. It has to be a frozenset so is hashable, this is a requirement of pandas.

A: Try this:
a = df_names.groupby(lambda idx: tuple(sorted(df_names.iloc[idx])))

Output:
a.apply(print)

  last_name first_name
2       XYX        ABC
  last_name first_name
5   Freeman     Walter
6    Walter    Freeman
  last_name first_name
0  Williams      Henry
1     Henry   Williams
  last_name first_name
3     Smith      David
4     David      Smith
  last_name first_name
7    Test_A     Test_B


text:
Q: What does CGContextSetTextMatrix do? I am not sure what this function does or is supposed to do.
void CGContextSetTextMatrix (
   CGContextRef c,
   CGAffineTransform t
);

The reference isn't all that helpful. :(

Sets the current text matrix.
The text matrix specifies the transform from text space to user space. To produce the final text rendering matrix that is used to actually draw the text on the page, Quartz concatenates the text matrix with the current transformation matrix and other parameters from the graphics state.
Note that the text matrix is not a part of the graphics state—saving or restoring the graphics state has no effect on the text matrix. The text matrix is an attribute of the graphics context, not of the current font."

Can you explain it to me?

A: The text matrix is a special transform that's applied to text. You can use it to change the orientation of text drawn with Core Text (or Core Graphics before CGContextShowText was deprecated). On iOS, Core Text and Core Graphics have different coordinate systems. Typically you solve this by flipping the Core Graphics coordinate system, but it is possible to flip the text matrix instead, though I don't recommend it except for very simple text (it messes up text layout).
(Why?!?!? he asks, would they have different coordinate systems? Well, because when iPhoneOS came along, Apple decided that iPhone devs would like the origin to be in the upper left like on Windows, rather than the lower left where mathematicians and Mac developers are used to it being. So they flipped the coordinate system, but when they ported over Core Text from Mac they kept its coordinate system, which was very good for all of us who have complicated text layout code that we could port over easily, and I'm sure it dramatically simplified porting, and... well... reasons. Not that this has anything to do with the text matrix; that's existed since 10.0, and exists so you can rotate text.)
Since the text matrix is not initialized for you, it is best practice to always initialize it before drawing text with low-level frameworks. You initialize it like so:
CGContextSetTextMatrix(context, CGAffineTransformIdentity);

This of course is not necessary if you're drawing text with UIKit. UIKit will handle all of this for you.


text:
Q: Install ASP.Net MVC Nuget Package with NetCore App 1.0 on Visual Studio 2015 Update3 I need to install Microsoft ASP Net MVC Nuget Package as reference on my project, I am using Microsoft Net Core App 1.0.1 on Microsoft Visual Studio 2015 Update 3. Using Nuget Package Manager I found the 5.2.3 version of MVC Package but I got this error:

Package Microsoft.Mvc.5.2.3 is not compatible with netcoreapp1.0
  The same is with WebPages,Razor and Infrastructure packages.

I have already tried with older version of the same package but still got the same error.
I have been googling this error but I did not find useful info, in fact, many pages are focused on 2.0 version of NetCore.
My question is: what am I missing in order to install MVC in my project? how can I solve the not compatible message?
Thank you in advance


text:
Q: Reload div on parent page from iframe So, I'm making a small application, but I ran into a problem. Basically, I have a page which consists of header and an iframe. Application itself runs in the iframe, while header stays the same, but here's the thing. Header displays some data from database which is updated from the application. In order for data in the header to stay up to date, I need to refresh it on button click from iframe. So my question is - is it possible? Is it possible to reload a div element in parent page from iframe?
All I have fro now is this jQuery:
var auto_refresh = setInterval(function()
     $('#stats').load('reload.php');
}, 5000);

Which reloads my div every 5 seconds, but I don't know if it's a good idea to reload a div automatically after a period of time. Well, I hope you guys understand my problem. :)

A: You can access the parent window (=main window) from the iframe, not a problem.

myFrame.htm:

If you want, you can do ajax requests and everything else you need, as long as the some origin policy is not violated (domains, ports & protocols must match).


text: Q: AWS authentication to Cognito for AWS Resources I am trying to reduce the number of login a user needs to gain access to multiple application. I have aws ad set that provides me authentication to vpn and mail client. No i need a website that I can use ad creds to allow users to upload,dowload and list files in an s3 bucket. it seems like i can do this with cognito maybe but the aws ad doesn't seem to support SAML/ADFS that allows you to link cognito to aws ad. Is there something I am missing


text:
Q: What is the difference between a "legation" and an "embassy"? I notice that history books dealing with pre-WW2 times frequently refer to the place where diplomats are to be found as a legation, but nowadays everyone calls this building an embassy.
Is there any particular reason for this change?

A: Until World War II, only great powers exchanged ambassadors and had embassies in each other's capitals.  During the war, small-state Allies with legations in London and Washington elevated their status to embassy.  Gradually, all legations became embassies -- except diplomatic missions exchanged by members of the British Commonwealth, which used the term high commission.

A: From Wikipedia

A legation was the term used in
  diplomacy to denote a diplomatic
  representative office lower than an
  embassy. The distinction between a
  legation and embassy was dropped
  following World War II. All diplomatic
  representative offices are now
  designated as embassies or high
  commissions.


text:
Q: WooCommerce Color Variants On WooCommerce, if we have multiple colors of the a given shirt and would like to show different Product Name, Product Description, Product Quantity, Product Price and set of pictures for each color of the product(i.e. 5 pics of red shirt on the red product page, not one red, one green, one blue), is there a way to do so? Presumably should create the products as two separate products and have a way to link them to one another such that the color options show up on the different pages, but the user is routed to a new page when clicking on the color option.
Is there a plug-in for this?

A: There is no need to create seperate products, as in WooCommerce you can define "attributes" (also called variants) for each of your products, you can create an attribute "color", create several color values and on the product edit page, link some of them to you products, you can define a different price, upload new product picture (etc.) to each of the variants.
For more please visit:
https://docs.woocommerce.com/document/variable-product/


text:
Q: Unwanted Scrollbar error in Magento I Installed Magento and a theme from envato . However it was working with out any issue and at some point of time it started giving an additional unwanted verical scrollbar in my template
Please check the URL : http://shoptwiz.com/about-shoptwiz   with 2 scrollbar on the right hand side .
Can any one point out the problem ?![enter image description here][1]
http://oi61.tinypic.com/29ftphy.jpg   Screen shot Link
I have tried to disable or comment http://www.shoptwiz.com/skin/frontend/default/ves_superstore/css/styles.css
at line 4378
overflow-x: hidden;
which removes the scroller . But this gives out another bug .
There is unusual Gap below the footer and the footer of website do not stick to its place .
This is a screen shot after i try to edit css from firebug
http://oi57.tinypic.com/2s8pd9w.jpg
Any one with a good advice ???

A: Thats a css issue. overflow property problem. I think they have set(theme providers) multiple time the same property. Anyway just open the below file,
http://duwj1c2q9eaye.cloudfront.net/skin/frontend/default/ves_superstore/css/styles.css

at line 4378 remove or comment this css property
overflow-x: hidden;

That's it. If you have any doubt comment here.


text:
Q: Need to copy text from one file to another in batch file Need to copy text from one file to another.
file1 as below:
locked/agent.jms.remote.host=<AGENTHOST>
locked/agent.jms.remote.port=<AGENTPORT>

file2 will be
locked/agent.jms.remote.host=mkdfvsh_a-2341
locked/agent.jms.remote.port=1234

 &  need to replace when creating the second file
command i used:
SET newfile=file2
SEt filetoCOpy=file1

for /f "tokens=*" %%i in (%filetoCOpy%) do (
  SET "line=%%i"
  SETLOCAL EnableDelayedExpansion
  SET line=!line:<AGENTHOST>=%AGENTHOST%!
  SET line=!line:<AGENTPORT>=%AGENTPORT%!

      echo !line!>>%newfile%
)

Result i got
locked/agent.jms.remote.host=<AGENTHOST>
locked/agent.jms.remote.port=<AGENTPORT>

variable value not changing.
Can someone help here what's wrong?

A: You should be getting an error with the code you posted. The < and > are treated as redirection unless they are escaped or quoted:
SET line=!line:^<AGENTHOST^>=%AGENTHOST%!
SET line=!line:^<AGENTPORT^>=%AGENTPORT%!

or
SET "line=!line:<AGENTHOST>=%AGENTHOST%!"
SET "line=!line:<AGENTPORT>=%AGENTPORT%!"

But you still have at least one problem - If you enable delayed expansion within a loop, then you must ENDLOCAL at the end of the loop, otherwise you can run out of SETLOCAL stack space.
Also, I don't see where AGENTHOST or AGENTPORT is defined.

A: You can try something like that :
@echo off
SET newfile=file2.txt
SEt filetoCOpy=file1.txt
set "ReplaceString1=mkdfvsh_a-2341"
set "ReplaceString2=1234"
If exist %newfile% Del %newfile%

for /f "tokens=*" %%i in (%filetoCOpy%) do (
  SET "line=%%i"
  SETLOCAL EnableDelayedExpansion
  SET line=!line:^<AGENTHOST^>=%ReplaceString1%!
  SET line=!line:^<AGENTPORT^>=%ReplaceString2%!
      echo !line!>>%newfile%
)
EndLocal
start "" %newfile%


text:
Q: xtrabackup: too many open files (more than 1048576) When using xtrabackup to backup a mysql database with lots of tables, the proces fails with Error 24: 'Too many open files'.
This is a FAQ on the Percona website: https://www.percona.com/doc/percona-xtrabackup/2.2/faq.html#backup-fails-with-error-24-too-many-open-files
My problem is that I cannot increase the allowed number of file descriptors any further, because the Linux kernel has a hard coded open file limit of 1048576.
Does anybody know:

*

*If we can configure xtrabackup in a way that will open less tables (or less concurrently)?

*How we can increase the kernel open file limit of 1048576?


text:
Q: How to get .data() using jQuery $.get (or $.ajax) On our site, the <body> tag holds various data-*="*" attributes:
<body data-someData="someValue" data-someOtherData="someOtherValue">

I need to get the values of these attributes while on other pages. So, I am using jQuery AJAX $.get to get the page's HTML, and thus these data attributes.
My current script:
// The call (used on different pages)
var stock = getProductData('stock', '/some/product/url');

// The "GET" function
function getProductData(type, url) {
    var jqxhr = $.get(url, function( data ) {
        console.log('Data found!');
        var $body = $(data).find('body');
        var val = $body.data('stock');
        console.log('Returning Value: "' + val + '"');
        return val;
    }).done(function(){
        // Request is complete
        console.log('getProductData Finished...');
    }).fail(function(){
        console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url);
    });
}

So, what's the problem? Well, the $(data).find('body').data('stock'); is coming back as undefined. I also tried $(data).find('body').attr('data-stock');, but it returned the same thing.
So, how can I return the body tag's data-someData="someValue" attribute values using $.get?
The data-stock attribute used in the example above looks like this on my product page:
<body data-stock="3">

EDIT: Not a duplicate: this question refers specifically to the parsing of specific attributes of elements. I am not asking how to just return the data using AJAX.

A: Let me suggest perhaps a crazy idea... You provided a sample url of:
var stock = getProductData('stock', '/some/product/url');
So is the file on the same domain?
If so, what about loading it into a hidden iframe and then accessing the iframe's document property? That won't work though if the content is on another domain for security reasons. If it's the same domain, then window.frames["framename"].document would give you the contents of the IFrame if I'm not mistaken.

A: Okay, so the short answer is that you are not able to reference data attributes inside the <body> tag in this way. Thus, you are not able to use var productData = $(body).data('someData');. jQuery evidently does not pay attention to the body tag when using $.ajax- even if the returned data is referenced as an object.
What you can do is:

*

*Move the data attributes to a hidden input (or any other tag inside the )
After doing this, you can then reference data attributes in your ajax requests.
There was one other thing I was doing wrong in my OP... My ajax request function kept returning 'undefined'. This was because the variable was being used externally before the ajax request was complete. So the return val; did not return anything until after the scripts that used the stock variable were done using it.
So, I had to use a callback and rework my script a little bit, but now everything works fine...
So- bottom line: you cannot return .data() from the body tag, but you can from other tags inside of the .
For anyone needs some help with this, here is my script (that works)...
The Call
// Needed for use inside AJAX request
var $el = $(this);
var url = $el.data('url');

// List Stock
getProductData('stock', url, function(val) {

  var stock = val;
  var str;
  var cls;

  if ( stock > 0 ) {
    str = stock + ' ' + 'In Stock';
    cls = 'in-stock';
  } else {
    str = 'Out of Stock';
    cls = 'out-of-stock';
  }

  $el.find('label.stock').addClass(cls).text(str);

});

The AJAX Request
// Get data from the product page
function getProductData(type, url, callBack) {

  $.ajax({
    url: url,
    method: 'GET',
    dataType: 'html',
    success: function(data){

      var $data = $(data).find('#product-data');

      var val = $data.data(type);

      return callBack( val );

    },
    error: function(data) {
      console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url );
    }
  });

}


text:
Q: Angular 2 HTTP response animations I'd like to run jQuery animations after a HTTP response has been received by the client.
My web service, it's a simple web service that uses AngularJS's Http functionality:
import {Component, View, Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {JsonObj} from './JsonObj.class';
@Injectable()
export class WebService {
    private http: Http;

constructor(http: Http) {
    this.http = http;
}

get(url: string) {
    return this.http.get(url)
        // Call map on the response observable to get the parsed people object
        .map(res => {
            let _d = res.json();
            return new JsonObj(_d.code, _d.status, _d.data, _d.error);
        });
    }
}

The JsonObj, this is simply an object that hosts the data from the web service:
export class JsonObj {
private code: Number;
private status: String;
private data: any;
private error: Array<any>;

constructor(_c: Number, _s: String, _d: Array<any>, _e: Array<any>) {
    this.code = _c;
    this.status = _s;
    this.data = _d;
    this.error = _e;
}

getCode() {
    return this.code;
}
getStatus() {
    return this.status;
}
getData() {
    return this.data;
}
getError() {
    return this.error;
}
}

The Component making the web service call:
import {Component, ElementRef} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Rotate} from './Rotate.class';
import {WebService} from '../../App/js/WebService.class';

@Component({
selector: 'Reviews',
viewProviders: [HTTP_PROVIDERS],
templateUrl: 'assets/templates/reviews.template.html'
})
export class Reviews {
public review: Array<any>;
private speed = 5000;
private outElem = null;
private parentElem = null;
private interval = null;

constructor(ws: WebService, el: ElementRef) {
    console.log('Reviews');

    ws.get('assets/temp_quotes.json').subscribe(
        data => this.review = data.getData().reviews,
        err => console.log('Error getting Review feed', err.getCode(), err.getError()),
        () => {
            console.log('Successful retrieval of the Review feed', this.review);
            let rotator = new Rotate(el);
            rotator.loop();
        }
    );
}
}

The template, the ngFor loops through the data from the web service and outputs it:

What people have to say about us...

{{el.quote}}

{{el.name}}, United Kingdom
Reviews.co.uk, {{el.date}}

Read all Reviews

My problem is that when the Component calls this:
let rotator = new Rotate(el);
rotator.loop();

the el (ElementRef) content from the web service has not been populated even though the dom has been updated with the response. It seems that rotator.loop() has been called too soon. I want to do an animation that loops through each of the list items one at a time. Any idea on how that can be done correctly?

A: Whatever comes last starts the animation
constructor(ws: WebService, el: ElementRef) {
  console.log('Reviews');
  private _initialized: boolean false;

  ws.get('assets/temp_quotes.json').subscribe(
    data => this.review = data.getData().reviews,
    err => console.log('Error getting Review feed', err.getCode(), err.getError()),
    () => {
        console.log('Successful retrieval of the Review feed', this.review);
        if(!this._initialized) {
          this._initialized = true;
        } else {
          this.startAnimation();
        }
    });
  }

  ngAfterViewInit() {
    if(!this._initialized) {
      this._initialized = true;
    } else {
      this.startAnimation();
    }
  }
  startAnimation() {
    let rotator = new Rotate(el);
    rotator.loop();
  }
}

You could also create an observable and add an event when getData() completed and another one in ngAfterViewInit(). Subscribe on the observable, ignore the first event and execute startAnimation() on the 2nd and than cancel the subscription.
I don't use TS myself therefore it's hard for me to provide a code example.


text:
Q: Looping through InDesign file, placing graphic on each page I've set-up a document that contains identical structures, including a text box labeled "pageNumber" to hold a variable based on the page number, an empty rectangle to receive an illustrator file, and a text box filled with placeholder text.
Eventually, I'll be using data-merge to create a much longer document, comprised of identically structured pages, but containing personalized data.
(I created a zip file containing these elements, in case it would be helpful to see what I'm testing)( http://arthousemedia.com/files/PageNumbers.zip )
The jsx I've created works to an extent. When I run it, there are a couple alerts that show I've created the right variables) But instead of placing pageNumber-p1.ai on page one and pageNumber-p2 on the second page, whichever page I'm "focused" upon gets its graphic placed twice on page 1. Apparently, I'm not succeeding in looping through pages. Not sure.
Any advice you have would be helpful. Thanks.
var doc = app.activeDocument,
pagesLength = doc.pages.length;

for (var i = 0; i < pagesLength; i++) {

    var myLabel = "pageNumber",
    myPage = app.properties.activeWindow && app.activeWindow.activePage,
    myTextFrames = myPage.textFrames.everyItem().getElements(myLabel).slice(0),
    l = myTextFrames.length,
    myVariable

    alert(myVariable);

    while (l--) {
        if (myTextFrames[l].label != myLabel) continue;
        myVariable = myTextFrames[l].contents;
        break;
    }

   var thisState = "~/Documents/PageNumbers/pageNumber-" + myVariable + ".ai";

   alert(thisState);

   var rect = doc.pages[i].rectangles[0];

   try {
       rect.place(File(thisState));
       rect.fit (FitOptions.CONTENT_TO_FRAME);
       rect.fit (FitOptions.PROPORTIONALLY);
       rect.fit (FitOptions.CENTER_CONTENT);
   }

   catch(e){
       alert(e);
   };

}


text:
Q: How do I use Jquery UI .css files only for some components? I downloaded Jquery UI (http://jqueryui.com/download/) I marked everything except accordion since I have my own css for that. My main page has a menu in an Accordion, in this main page I don't use JQuery UI .css file. When I click any item in the menu it loads a page that uses JQuery UI .css file and it completly changes my accordion.
I want to be able to use JQuery UI .css file for Dialog, Datepicker,... but I don't want it in my accordion. Is there a way to do that or do I have to create my own css for all the other components?

A: You can choose to make abuse of !important attribute or exploit css class specification feature. Simply add more classes to your accordion and be consequently more specific in your css selectors. Including your css after the jQueryUI standard css can help as well.


text:
Q: redirect on page by position i have problem regarding on how to redirect page by thier respective postion after clicking log in. i have "employee" table in my database and  the ff fields in my "employee"  table are "e_fullname , e_position " my probem is that if im going to log in in the page it must be redirect on the page depending on the position of the employee. let say for example i logged in and my position is  a cashier so the page must be redirect to cashier.php and if im  admin  it must be redirect to admin.php. . .i tried searching different technique on how to solve this problem but seems not working with me. this is my code so far. this code is working but not on what i am looking for.any answer is accepted .thank you !
$login = clean($_POST['username']);
$password = clean($_POST['password']);

//Create query
$qry="SELECT * FROM employee WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    if(mysql_num_rows($result) > 0 || $login = "james") {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['username'];
        session_write_close();
        header("location: user/auto.php?id=0");
        exit();
    }

    else {
header("location: index.php");

    }

}

A: header() takes a string. Just replace the appropriate value for the position within the string.
header("Location: $pospage.php");


text:
Q: Parsing an arithmetic expression and building a tree from it in Java I needed some help with creating custom trees given an arithmetic expression. Say, for example, you input this arithmetic expression:
(5+2)*7

The result tree should look like:
    *
   / \
  +   7
 / \
5   2

I have some custom classes to represent the different types of nodes, i.e. PlusOp, LeafInt, etc. I don't need to evaluate the expression, just create the tree, so I can perform other functions on it later.
Additionally, the negative operator '-' can only have one child, and to represent '5-2', you must input it as 5 + (-2).
Some validation on the expression would be required to ensure each type of operator has the correct the no. of arguments/children, each opening bracket is accompanied by a closing bracket.
Also, I should probably mention my friend has already written code which converts the input string into a stack of tokens, if that's going to be helpful for this.
I'd appreciate any help at all. Thanks :)
(I read that you can write a grammar and use antlr/JavaCC, etc. to create the parse tree, but I'm not familiar with these tools or with writing grammars, so if that's your solution, I'd be grateful if you could provide some helpful tutorials/links for them.)

A: Assuming this is some kind of homework and you want to do it yourself..
I did this once, you need a stack
So what you do for the example is:

    parse    what to do?                Stack looks like
      (      push it onto the stack     (
      5      push 5                     (, 5
      +      push +                     (, 5, +
      2      push 2                     (, 5, +, 2
      )      evaluate until (           7
      *      push *                     7, *
      7      push 7                     +7, *, 7
      eof    evaluate until top         49

The symbols like "5" or "+" can just be stored as strings or simple objects, or you could store the + as a +() object without setting the values and set them when you are evaluating.
I assume this also requires an order of precedence, so I'll describe how that works.
in the case of: 5 + 2 * 7
you have to push 5 push + push 2 next op is higher precedence so you push it as well, then push 7.  When you encounter either a ) or the end of file or an operator with lower or equal precedence you start calculating the stack to the previous ( or the beginning of the file.
Because your stack now contains 5 + 2 * 7, when  you evaluate it you pop the 2 * 7 first and push the resulting *(2,7) node onto the stack, then once more you evaluate the top three things on the stack (5 + *node) so the tree comes out correct.
If it was ordered the other way: 5 * 2 + 7, you would push until you got to a stack with "5 * 2" then  you would hit the lower precedence + which means evaluate what you've got now.  You'd evaluate the 5 * 2 into a *node and push it, then you'd continue by pushing the + and 3 so you had *node + 7, at which point you'd evaluate that.
This means you have a "highest current precedence" variable that is storing a 1 when you push a +/-, a 2 when you push a * or / and a 3 for "^".  This way you can just test the variable to see if your next operator's precedence is < = your current precedence.
if ")" is considered priority 4 you can treat it as other operators except that it removes the matching "(", a lower priority would not.

A: Several options for you:

*

*Re-use an existing expression parser. That would work if you are flexible on syntax and semantics. A good one that I recommend is the unified expression language built into Java (initially for use in JSP and JSF files).

*Write your own parser from scratch. There is a well-defined way to write a parser that takes into account operator precedence, etc. Describing exactly how that's done is outside the scope of this answer. If you go this route, find yourself a good book on compiler design. Language parsing theory is going to be covered in the first few chapters. Typically, expression parsing is one of the examples.

*Use JavaCC or ANTLR to generate lexer and parser. I prefer JavaCC, but to each their own. Just google "javacc samples" or "antlr samples". You will find plenty.
Between 2 and 3, I highly recommend 3 even if you have to learn new technology. There is a reason that parser generators have been created.
Also note that creating a parser that can handle malformed input (not just fail with parse exception) is significantly more complicated that writing a parser that only accepts valid input. You basically have to write a grammar that spells out the various common syntax errors.
Update: Here is an example of an expression language parser that I wrote using JavaCC. The syntax is loosely based on the unified expression language. It should give you a pretty good idea of what you are up against.
Contents of org.eclipse.sapphire/plugins/org.eclipse.sapphire.modeling/src/org/eclipse/sapphire/modeling/el/parser/internal/ExpressionLanguageParser.jj

A: I wanted to respond to Bill K.'s answer, but I lack the reputation to add a comment there (that's really where this answer belongs).  You can think of this as a addendum to Bill K.'s answer, because his was a little incomplete.  The missing consideration is operator associativity; namely, how to parse expressions like:
49 / 7 / 7

Depending on whether division is left or right associative, the answer is:
49 / (7 / 7) => 49 / 1 => 49

or
(49 / 7) / 7 => 7 / 7 => 1

Typically, division and subtraction are considered to be left associative (i.e. case two, above), while exponentiation is right associative.  Thus, when you run into a series of operators with equal precedence, you want to parse them in order if they are left associative or in reverse order if right associative.  This just determines whether you are pushing or popping to the stack, so it doesn't overcomplicate the given algorithm, it just adds cases for when successive operators are of equal precedence (i.e. evaluate stack if left associative, push onto stack if right associative).

A: The "Five minute introduction to ANTLR" includes an arithmetic grammar example. It's worth checking out, especially since antlr is open source (BSD license).

A: the given expression (5+2)*7 we can take as infix
Infix  :     (5+2)*7
Prefix :     *+527

from the above we know the preorder and inorder taversal of tree ... and we can easily construct tree from this.
Thanks,


text:
Q: PenAlignment.Outset has no effect I'm drawing a rectangle with Pen.Alignment = PenAlignment.Outset onto a PictureBox (which has a green background).
This is the code:
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

    Dim iTop As Integer = 1
    Dim iLeft As Integer = 1
    Dim iRight As Integer = 3
    Dim iBottom As Integer = 3

    Dim r As Rectangle = Rectangle.FromLTRB(iLeft, iTop, iRight, iBottom)

    Using nPen As Pen = New Pen(Color.Black)
        nPen.Alignment = PenAlignment.Outset
        e.Graphics.PageUnit = GraphicsUnit.Pixel
        nPen.Width = 1
        e.Graphics.DrawRectangle(nPen, r)
    End Using

End Sub

However, the PenAlignment doesn't have any effect.
This is the output:

Instead of drawing the rectangle with "outset", it draws exactely where the rectangle is. I expect the black lines to be drawn just around the rectangle.
So the first black point should be at 0-0, not at 1-1.
What might be going wrong here?

A: I had the same problem and got no answers so I had to work around it.
Here's what I did:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint

    'Main Shape Values
    Dim x = 100
    Dim y = 100
    Dim wdth = 300
    Dim hght = 200
    Dim shP = 2

    'Main Shape
    Dim ShapePen As New Pen(Color.Black, shP)
    Dim Shape As New Rectangle(x, y, wdth, hght)
    e.Graphics.DrawRectangle(ShapePen, Shape)

    'Values For the Alignment
    Dim P_Thck = 20
    Dim R_ThickL = (P_Thck / 2) + (shP / 2)
    Dim R_ThickS = R_ThickL * 2

    Dim AlignmentPen As New Pen(Color.Red, P_Thck)
    'Dim Align_Outset As New Rectangle(x - R_ThickL, y - R_ThickL, wdth + R_ThickS, hght + R_ThickS)
    Dim Align_Inset As New Rectangle(x + R_ThickL, y + R_ThickL, wdth - R_ThickS, hght - R_ThickS)

    'e.Graphics.DrawRectangle(AlignmentPen, Align_Outset)
    e.Graphics.DrawRectangle(AlignmentPen, Align_Inset)

End Sub

I use two shapes.
One is my working shape and the other is the one I adjust for my alignment graphics.
Inset
Outset


text:
Q: Existence of edge in graph I want to know whether an edge exist between two specific vertex?
Is there any function like EdgeExist[g,{v1,v2}]?

A: Yes, there is  EdgeQ:
g = Graph[{1 -> 2, 2 -> 3, 3 -> 1}, VertexShapeFunction -> "Name"]

{EdgeQ[g, 1 -> 2], EdgeQ[g, DirectedEdge[1, 2]],
 EdgeQ[g, 1 <-> 2], EdgeQ[g, UndirectedEdge[1, 2]],
 EdgeQ[g, 2 -> 1], EdgeQ[g, DirectedEdge[2, 1]]}

{True, True, False, False, False, False}

If you need a function that takes a list of (unordered) vertices as the second arguments, you can use
edgeQ[g_, e : {_, _}] := Or @@ (EdgeQ[g, #] & /@ {DirectedEdge @@ e,
     DirectedEdge @@ Reverse[e], UndirectedEdge @@ e})

edgeQ[g, {1, 2}]

True

If the ordering is important, remove DirectedEdge @@ Reverse[e] from the function definition.
Notes: As @Szabolcs noted in the comments, a <-> b is equivalent to UndirectedEdge, but a -> b is not the same as DirectedEdge.  a -> b is treated as DirectedEdge only in a directed graph; in an undirected or mixed graph it is treated as UndirectedEdge.


text:
Q: Lodash move objects under a key part of same object I have an JSON object like
datas = [
    {"id":1,"name":"Test","age":24},
    {"id":2,"name":"Test1","age": 30}
]

I want to modify the JSON object like below
datas = [
        {"1":{"name":"Test","age":24}},
        {"2":{"name":"Test1","age": 30}}
    ]

I want to do the same using lodash . I can understand map over the data and create a new object should fix this
updated_data=[]
_.map datas, (data) ->
  Obj = {}
  Obj[data.id] = data
  updated_data.push(Obj)

But I am looking for lodash way of achieving the same .

A: Use Array.map() (or _.map()) with destructuring and object rest (...):

const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]

const result = datas.map(({ id, ...o }) => ({ [id]: o }))

console.log(result)

With lodash you can do the same, but instead of destructuring use _.omit() to remove the id from the original object, and use _.zipObject() combine it with the id:

const datas = [{"id":1,"name":"Test","age":24}, {"id":2,"name":"Test1","age": 30}]

const result = _.map(datas, o => _.zipObject([o.id], [ _.omit(o, 'id')]))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

A: I think you don't need to use an extra library for this. This way you can achieve the desired result:
datas.map((item) => {
  const { id, ...rest } = item;
  return {
    id: rest,
  };
});


text:
Q: How to query star (*) character in a field in where clause for mysql I want to query a table with field that contains star (*) character but I could't find a valuable answer. I tried something below
WHERE fieldName regexp '\*'

There are solutions like using 'like' keyword but I wanna know a way that uses 'regexp' keyword.
Thanks in advance.

A: You need to escape the backslash one more time since a single backslash inside double or single quotes would be considered as an escape sequence.
WHERE fieldName regexp '\\*'

OR
Use character class.
WHERE fieldName regexp '[*]'


text:
Q: How to add Mopub ads in android studio I am trying to integrate Mopub ads into my Android Studio project, but I am encountering an error when building the project. I have followed the instructions provided in the link (https://developers.mopub.com/publishers/android/integrate/#option-3-cloned-github-repository), but I am still unsure how to resolve the error. The error message is:
Caused by: org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method implementation() for arguments [com.mopub:mopub-sdk:@aar, build_2jh7i72qxdht1wclzb0v2ink0$_run_closure1$_closure3$_closure5@13b54e85] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Here is my build.gradle file for reference:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        jcenter()
        google()
        maven { url "https://s3.amazonaws.com/moat-sdk-builds" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.3'
        classpath 'com.google.gms:google-services:4.3.3'
        implementation('com.mopub:mopub-sdk:@aar') {
            transitive = true
        }
        // NOTE: Do not place your application dependencies here; they belon
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

A: The implementation('com.mopub:mopub-sdk:5.13.1@aar') goes into your app's (not project's)  build.gradle.


text:
Q: Laravel 5: how to insert data in database and return field back Sorry if it's a stupid question, but I am new in framework programming, and also in Laravel. I want to insert my data in a database and return id back, but in the database the field in the table is not id, but owner_id. How i can return it back? I'm using PostgreSQL and set it auto-incrementing ready.
This is my code:
    $regis = new ltd_owner;
    $regis->owner_name = $register['firstname'] . ' ' . $register['lastname'];
    $regis->represent_company_id = $register['isRepresent'];
    $regis->gender = $register['sex'];
    $regis->address_id = '7598';
    $regis->nationality_id = '24';
    $regis->save();

Please help me to fix it, thanks

A: You need to set a different primary key in your Model:
protected $primaryKey = "owner_id";

Then, after you do the save(), the field should be populated automatically, and you can access it:
var_dump($regis->owner_id);

A: If you use different id name, you should define it in the Model.
Add the following line to the ltd_owner model:
protected $primaryKey = 'owner_id';

Then if you create a new model, you can get back the id.
$regis = new ltd_owner;
$regis->owner_name = $register['firstname'] . ' ' . $register['lastname'];
$regis->represent_company_id = $register['isRepresent'];
$regis->gender = $register['sex'];
$regis->address_id = '7598';
$regis->nationality_id = '24';
$regis->save();
//inserted model id:
$regis->owner_id;

A: After passing $regis->save();
$regis will hold your new data.
You can get those variable by calling them $regis->column_name for example $regis->owner_id;, $regis->address_id; $regis->gender
Hope you understand what's happening


text:
Q: Options for 2 or 3 band active audio tone control circuits with quite steep frequency response I'm trying to roughly replicate the sound of the per-stereo-channel 3 band equaliser conttols of an old Citronic Pro-8 / Pro-10 DJ mixer. If I'm correct had a fairly steep curve so bass and treble controls didn't affect middle frequencies much, and were very effective at cutting bass/treble as required.
As long as the sound is all flat when tone controls are centred and there are no odd peaks /resonances.
What type of filter might it have used? Googling 3 band audio equaliser brings up circuits that I don't think would do it? Technically they all seem to be first order if Im correct? OK I should try it first but in principle something to try next anyway? Second order filters? Or even a half way house of technically easy in analogy circuits?
My mixer wasn't parametric but I guess a single parametric tone control (not thought this out at all mind you) could give the same effect on top of a simple first order set of tone controls.
Ideas:

*

*http://rane.com/pdf/acceler.pdf

A: There is a real problem when using higher-order filters as tone controls at audio frequencies.  The phase response and delay that those filters introduce become additive and subtractive at various frequencies as the controls are adjusted.
Early graphic equalizers are good example of this problem.  The frequency response changes in odd fashions as you make what should be minor changes to the different filters.  This is both audible and easily measured.
On the other hand, both peaking and shelving high-pass and low-pass filters use at the very ends of the audio spectrum don't have as much problem with this.  These high-pass and low-pass filters are often 2nd order filters (12 dB / octave) but I have seen even higher-order filters in older analog audio mixing consoles.
I suspect that what you are calling "bass" and "treble" controls on the DJ mixer you are referring to are, in fact, shelving high-pass and low-pass filters.


text:
Q: Facebook "Like" popup appears behind sidebar on Wordpress site Just finished installing G+, Facebook Like and Tweet buttons onto my site (www.biginjapan.co) on each individual post.  My issue though is that when you press the FB Like button the popup box opens up so you can share the article if desired, but part of it appears behind the sidebar.  It looks like this:
Picture showing my problem
Am not sure if you'll need any code to advise me here, but if you do please let me know.  All I want to do is make the Facebook popup appear above the sidebar so you can view it properly.

A: Remove the line overflow: hidden for #content. it's on line 247.

A: In your content div
#content {
   overflow: hidden;
   float: left;
   width: 619px;
   padding: 0pt 15px;
}

Remove overflow hidden.

A: It is layer issue. It can be handle by z-index. For the slider layer (content), use lower z-index means
.slider{ z-index: -1; }

For the popup layer (content ) use higher z-index than slider
.popup{ z-index: 123; }


text:
Q: JOIN the Strings of different textboxes and again SPLIT I am new in vb.net, so not much familiar with all VB functions. While working on 1 Windows Application, while taking order we need to save product and its specification like weight, height, width, color, length, material etc.
since every product can have different specification so its is not possible to determine and provide for fields in database.
So, I decided to provide textboxes so user can enter name & value while entering product details. 1 textbox for name & other textbox for value.
like this
Textbox1 = "WEIGHT"     TextBox2 = "10" '(Value of Weight)
Textbox3 = "WIDTH"      TextBox4 = "5" '(value of Width)
Textbox4 = "LENGTH"      TextBox5 = "5" '(Value of Length)

(All these textboxes are dynamically created in Groupbox "GBox1")
Instead of saving product specification in separate column. I want to save these names & values as String e.g. "WEIGHT=10;WIDTH=5;LENGTH=5" in SQL Database(TEXT OR VARCHAR field). Because we dnt want any calculations or search etc. on this. just customer requirements to book order & save in Database for future records.
Then again While calling or editing Product SPLIT the string as separate fields, String Before = Separate & string after = separate, then display all names & their corresponding values in Textboxes (as Displayed while adding) so user can edit and after changes again save as single string value.
After search I found SPLIT & JOIN functions for this purpose.
need some help in using these functions in Loop to merge string from textboxes
for each loop to read all textboxes in Groupbox
Dim ItemList As New ArrayList()
Dim PrDetails As String
For Each Ctrl As Control In GBox1.Controls
    If TypeOf Ctrl Is TextBox Then
        ItemList.Add(CType(Ctrl, TextBox).Text)
    End If
Next
PrDetails = String.Join()

How to perform join on these array list? and again SPLIT this pattern while retrieving from Database.
Also need suggestions regarding this approach or any other way to implement. Thanks.

A: For this solution to work, you will need to accept the fact that there needs to be some amount of standardization to your solution. TextBox1 and TextBox3 won't work as names, so I used txtName1 and txtValue1 etc. To test this solution, make a new form, put GroupBox1, paste the code in the class and run.
Private nameTextBoxName = "txtName" ' name textbox prefix
Private valueTextBoxName = "txtValue" ' value textbox prefix
Private paramSeparator = ";" ' between sets of parameters
Private nameAndValueSeparator = "=" ' between name and value
Private xOffset = 10 ' for horizontal spacing inside the groupbox
Private yOffset = 20 ' for vertical spacing inside the groupbox

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' your example data
    Dim testString = "WEIGHT=10;WIDTH=5;LENGTH=5"
    ' set the textboxes
    setTextBoxes(testString)
    ' get the string from the textboxes
    Dim result = getTextBoxesString()
End Sub

' call to get a string with all the data from the textboxes
Private Function getTextBoxesString() As String
    Dim stringToDatabase = ""
    Dim textBoxes = GroupBox1.Controls.OfType(Of Control).
        Where(Function(co As Control) TypeOf co Is TextBox).
        Select(Of TextBox)(Function(co As Control) CType(co, TextBox))
    Dim nameTextBoxes = textBoxes.Where(Function(co As Control) co.Name.Contains(nameTextBoxName))
    Dim valueTextBoxes = textBoxes.Where(Function(co As Control) co.Name.Contains(valueTextBoxName))
    stringToDatabase = nameTextBoxes.Select(Of String)(
        Function(nameTextBox As TextBox)
            Dim valueTextBox = valueTextBoxes.
                Where(Function(vtb As TextBox) vtb.Name = nameTextBox.Name.Replace(nameTextBoxName, valueTextBoxName)).
                First()
            Return nameTextBox.Text & nameAndValueSeparator & valueTextBox.Text
        End Function).Aggregate(Function(oldValue, newValue) oldValue & paramSeparator & newValue)
    Return stringToDatabase
End Function

' call to set the textboxes inside the groupbox based on the data string
Private Sub setTextBoxes(textBoxesString As String)
    Dim params = textBoxesString.Split(paramSeparator)
    Dim index = 1
    GroupBox1.Controls.Clear()
    For Each param In params
        Dim nameAndValue = param.Split(nameAndValueSeparator)
        Dim nameTextBox As New TextBox With
            {.Name = nameTextBoxName & index.ToString(),
             .Text = nameAndValue(0),
             .Location = New Point(xOffset, (index - 1) * .Height + yOffset)}
        Dim valueTextBox As New TextBox With
            {.Name = valueTextBoxName & index.ToString(),
             .Text = nameAndValue(1),
             .Location = New Point(.Width + xOffset, (index - 1) * .Height + yOffset)}
        GroupBox1.Controls.Add(nameTextBox)
        GroupBox1.Controls.Add(valueTextBox)
        index += 1
    Next
End Sub