text:
Q: Smith Normal Form Would the Smith Normal Form of the following matrix over $\mathbb Q[x]$
$$\begin{pmatrix}
  (x+a)(x+b) & 0 & 0 &0 \\
 0 & (x+c)(x+d) & 0 & 0 \\
  0  &0 & x^3(x+a) & 0  \\
  0 & 0 & 0& x^2(x+b)
 \end{pmatrix}$$
 simply be
$$\begin{pmatrix}
  f(x) & 0 & 0 &0 \\
 0 & f(x) & 0 & 0 \\
  0  &0 & f(x) & 0  \\
  0 & 0 & 0& f(x)
 \end{pmatrix}$$
where $f(x)= x^3(x+a)(x+b)(x+c)(x+d)$?
I am not sure because that would make the question quite trivial.

A: No.
Let $s_k$ denote the $k$th entry on the diagonal of Smith form (i.e., the $k$th invariant factor). Then $$s_k = \frac{d_k}{d_{k-1}},$$ where $d_k = \gcd$ of all $k \times k$ minors of the original matrix (aka $k$th determinantal divisor). I'm assuming $a,b,c,d$ are distinct here. So the Smith form is:
$$
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0\\
0 & 0 & x^2(x+a)(x+b) & 0\\
0 & 0 & 0 & x^3(x+a)(x+b)(x+c)(x+d)
\end{pmatrix}
$$


text:
Q: Integrate $\frac{\sin x^3}{x^3}$ as a power series Today, I tried to do this by taking the MacLaurin of Sin to 4 terms, putting in $x^3$ in place of $x$, multiplying the terms by $x^{-3}$, and integrating. I came out with a sum that had $x^{6n+1}$ as the numerator, and $(6n+1)(n+1)!$ as the denominator. I don't think it was right. How should I have gone about this and what should I have gotten?

A: $$\sin(x)=\sum_{n\geq 0}\frac{(-1)^n x^{2n+1}}{(2n+1)!} $$
hence:
$$\sin(x^3)=\sum_{n\geq 0}\frac{(-1)^n x^{6n+3}}{(2n+1)!}$$
and:
$$\frac{\sin(x^3)}{x^3}=\sum_{n\geq 0}\frac{(-1)^n x^{6n}}{(2n+1)!}$$
so:
$$ \int\frac{\sin(x^3)}{x^3}\,dx = C+\sum_{n\geq 0}\frac{(-1)^n x^{6n+1}}{(6n+1)\cdot(2n+1)!}.$$
Also notice that:
$$ \int_{0}^{+\infty}\frac{\sin(x^3)}{x^3}\,dx =\frac{1}{3}\int_{0}^{+\infty}\frac{\sin z}{z^{5/3}}\,dz $$
and since $\mathcal{L}(\sin z)=\frac{1}{1+s^2}$ while $\mathcal{L}^{-1}(z^{-5/3})=\frac{s^{2/3}}{\Gamma(5/3)}$,
$$ \int_{0}^{+\infty}\frac{\sin(x^3)}{x^3}\,dx = \frac{1}{3\cdot\Gamma(5/3)}\int_{0}^{+\infty}\frac{s^{2/3}}{1+s^2}\,ds = \color{red}{\frac{\sqrt{3}}{4}\,\Gamma\left(\frac{1}{3}\right)}$$
by the Euler's beta function and the $\Gamma$ reflection formula.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Method is not executing sequentially I have the below code:
public Dictionary<int, Ticket> GetNewTickets()
    {
        Dictionary<int, Ticket> output = new Dictionary<int, Ticket>();

        foreach (KeyValuePair<int, Ticket> item in ticketStore)
        {
            if (!ticketStoreNew.ContainsKey(item.Key))
            {
                output.Add(item.Key, item.Value);
            }
        }

        ticketStoreNew = ticketStore;

        return output;
    }`

It takes a dictionary, ticketStore, checks to see if it has any new elements not in ticketStoreNew and puts them in the output dictionary. Then, ticketStoreNew is set to ticketStore until ticketStore is updated with another method and this method is ran again.
However, when I include the line ticketStoreNew = ticketStore, the program returns an empty dictionary. It looks like the method is not executing sequentially and this is running prior to the for loop.
I really just need to return any new items added to the ticketStore dictionary.
EDIT
Below is the code for getting ticketStore:
public void UpdateTickets(string inputXml)
{
    // If no new tickets exit
    if (inputXml.Trim() == "") { return; }
    //xmlString = inputXml;

    // Load XML into an enumerable
    XElement xelement = XElement.Parse(inputXml);
    IEnumerable<XElement> xml = xelement.Elements();

    foreach (var item in xml)
    {
        if (item.Name == "incident")
        {
            int id;

            // If ID can be converted to INT
            if (Int32.TryParse(item.Element("id").Value, out id))
            {
                // If ticket is not already in store create ticket and populate data
                if (!ticketStore.ContainsKey(id))
                {
                    Ticket ticket = new Ticket();
                    ticket.id = id;
                    ticket.number = Int32.Parse(item.Element("number").Value);
                    ticket.title = item.Element("name").Value;
                    ticket.description = item.Element("description").Value;

                    ticketStore.Add(id, ticket);
                }
            }
        }
    }
}

}
The tickets are all based on getting XML from the Samanage API.

A: If another method updates ticketStore then the assignment is the problem. It doesn't copy the contents of ticketStore to ticketStoreNew it sets the reference ticketStoreNew to point to the same instance as ticketStore. Thus they are the same object and always have the same contents. Try creating a new Dictionary to copy the items:
ticketStoreNew = new Dictionary<int, Ticket>(ticketStore);

A: Try this code:
    private Dictionary<int, Ticket> ticketStoreNew =
        new Dictionary<int, Ticket>(); // add this line
    public Dictionary<int, Ticket> GetNewTickets()
    {
        Dictionary<int, Ticket> output = new Dictionary<int, Ticket>();

        foreach (KeyValuePair<int, Ticket> item in ticketStore)
        {
            if (!ticketStoreNew.ContainsKey(item.Key))
            {
                output.Add(item.Key, item.Value);
                ticketStoreNew.Add(item.Key, item.Value); // add this line
            }
        }

        //ticketStoreNew = ticketStore; remove this line

        return output;
    }


text:
Q: How can I access a select in an HTML table cell I added a select to a column of table cells with an ID. Using console.log I can see the select with the ID I gave it but when I try to set the value of the box using the ID I get a NULL reference error. What would the correct reference be for the box? Thanks.
JavaScript
function GetProc_Responce(r, responce) {
  var table = "
Emp	RA	PI	First Name	Last Name	Is A	Date Created	Date Modified
";
  strXml = new XMLSerializer().serializeToString(responce);

  //console.log("returnString: " + strXml);
  var oParser = new DOMParser();
  oDOM = oParser.parseFromString(strXml, "text/xml");

  //console.log(oDOM.getElementsByTagName("EmployeeID").length);
  var l = oDOM.getElementsByTagName("EmployeeID").length;
  for (i = 0; i <= l - 1; i++) {
    a = oDOM.getElementsByTagName("Emp")[i];
    _Emp = a.childNodes[0].nodeValue;
    b = oDOM.getElementsByTagName("RA")[i];
    _RA = b.childNodes[0].nodeValue;
    c = oDOM.getElementsByTagName("PI")[i];
    _PI = c.childNodes[0].nodeValue;
    d = oDOM.getElementsByTagName("FirstName")[i];
    _FirstName = d.childNodes[0].nodeValue;
    e = oDOM.getElementsByTagName("LastName")[i];
    _LastName = e.childNodes[0].nodeValue;
    f = oDOM.getElementsByTagName("IsA")[i];
    _IsA = f.childNodes[0].nodeValue;
    g = oDOM.getElementsByTagName("DateCreated")[i];
    _DateCreated = g.childNodes[0].nodeValue;
    h = oDOM.getElementsByTagName("DateModified")[i];
    _DateModified = h.childNodes[0].nodeValue;
    table += "
" +
      a.childNodes[0].nodeValue + "	" +
      b.childNodes[0].nodeValue + "	" +
      c.childNodes[0].nodeValue + "	" +
      d.childNodes[0].nodeValue + "	" +
      e.childNodes[0].nodeValue + "	" +
      //f.childNodes[0].nodeValue + "	" +
      "<select id=\"s1\"><option value=\"0\">0</option><option value=\"1\">1</option></select>" + "	" +
      g.childNodes[0].nodeValue + "	" +
      h.childNodes[0].nodeValue + "
";

    document.getElementById('Proc').rows.item(3).cells(5).value = 1;
    //OR
    document.getElementById('s1').selectedValue = 1;
    //NEITHER ONE WORKS

  }
  document.getElementById("Proc").innerHTML = table;

  console.log(document.getElementById('Proc').rows(3).cells(5));
}

HTML

A: You must assign unique id values. Your code assigns all of them the id value s1 which is invalid in HTML.
Change your code as follows to assign s0, s1, s2 ... etc. For clarity I don't repeat the code that is not concerned:
for (i = 0; i <= l - 1; i++)
{
    // ...
    table += "
" +
            // ...
            e.childNodes[0].nodeValue + "	" +
            "<select id=\"s" + i + "\"><option value=\"0\">0</option><option value=\"1\">1</option></select>" + "	" +
            // ...
 }

You can access one of the select elements by its id with getElementById:
var element = document.getElementById('s' + i);

Where i is a number from 0 to the last one assigned in the loop.
You can get or set the value of a select element via its value attribute. For example, to set its value to 1, do:
document.getElementById('s' + i).value = '1';

A: Here we'll get div object
var div     = document.getElementById('test');

Here we'll get table object
var table = div.getElementsByTagName('table')[0];

Here we'll add new select to td
table.rows[0].cells[0].innerHTML += '<select id="s2"></select>';

Search existed select (with id="s1")
var select_1 = table.rows[0].cells[0].getElementsByTagName('select')[0];
console.log(select_1);

Search all selects in td
var select_array = table.rows[0].cells[0].getElementsByTagName('select');
console.log(select_array);

https://jsfiddle.net/e59dzhsy/

A: document.getElementById('Proc').rows.item(3).cells(5) references a td, which does not have a value.
document.getElementById('s1') references the select box
you want document.getElementById('Proc').rows.item(3).cells(5).children[0] to reference the select
A better method would be to use some of the built in tag finding functions such as document.getElementById('Proc').rows[3].getElementsByTagName('select')[0].  Then you don't have to deal with what column the select is in.  Of course, if you have more than one select on the row, then you'll need to do something different.  At that point, I'd suggest adding class names to your selects so you can use document.getElementById('Proc').rows[3].getElementsByClassName('select1')[0]


text:
Q: Java 8: How to chunk multipart file for POST request I have a multipart file, it will be an image or video, which needs to be chunked for POST request. How can I chunk the file into byte array segments?
edit: I'm using Twitter API to upload image, according to their docs, media must be chunked

A: I've found a solution thanks to https://www.baeldung.com/2013/04/04/multipart-upload-on-s3-with-jclouds/
public final class MediaUtil {

    public static int getMaximumNumberOfParts(byte[] byteArray) {
        int numberOfParts = byteArray.length / (1024 * 1024); // 1MB
        if (numberOfParts == 0) {
            return 1;
        }
        return numberOfParts;
    }

    public static List<byte[]> breakByteArrayIntoParts(byte[] byteArray, int maxNumberOfParts) {
        List<byte[]> parts = new ArrayList<>();
        int fullSize = byteArray.length;
        long dimensionOfPart = fullSize / maxNumberOfParts;
        for (int i = 0; i < maxNumberOfParts; i++) {
            int previousSplitPoint = (int) (dimensionOfPart * i);
            int splitPoint = (int) (dimensionOfPart * (i + 1));
            if (i == (maxNumberOfParts - 1)) {
                splitPoint = fullSize;
            }
            byte[] partBytes = Arrays.copyOfRange(byteArray, previousSplitPoint, splitPoint);
            parts.add(partBytes);
        }

        return parts;
    }
}

// Post the request
int maxParts = MediaUtil.getMaximumNumberOfParts(multipartFile.getBytes());

List<byte[]> bytes = MediaUtil.breakByteArrayIntoParts(multipartFile.getBytes(), maxParts);
int segment = 0;
for (byte[] b : bytes) {
    // POST request here
    segment++;
}

A: Well, you may need this:
File resource = ResourceUtils.getFile(path);
if (resource.isFile()) {
    byte[] bytes = readFile2Bytes(new FileInputStream(resource));
}

private byte[] readFile2Bytes(FileInputStream fis) throws IOException {

    int length = 0;
    byte[] buffer = new byte[size];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((length = fis.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toByteArray();
}


text:
Q: Script doesn't print to console in real time [PYTHON] I am testing how to receive real time data through interactive brokers' API and reqMktData. The algorithm is run through an infinite while loop, which allows for real-time live streaming data until I stop the script.
When I run it, it is supposed to continuously print data to the console as specified in the code below. However, nothing is printed until I hit "stop the current command". Then I get a huge data dump consisting of all the data received since the execution of the script.
I have tried the following solution, where I import sys in the beginning of the script and flush the output after each print. However, this doesn't work either:
import sys
sys.stdout.flush()

I'm using python 2.7 and spyder - and am quite new to python.
Hope someone can help! Any inputs are greatly appreciated.
The script I'm testing:
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import pandas as pd
import datetime as dt

class AlgoSystem:
    def __init__(self, symbol, qty, resample_interval,
                 averaging_period=5, port=7496):
        self.client_id = 1
        self.order_id = 1
        self.qty = qty
        self.symbol_id, self.symbol = 0, symbol
        self.resample_interval = resample_interval
        self.averaging_period = averaging_period
        self.port = port
        self.tws_conn = None
        self.bid_price, self.ask_price = 0, 0
        self.last_prices = pd.DataFrame(columns=[self.symbol_id])
        self.average_price = 0
        self.account_code = None

    def error_handler(self, msg):
        if msg.typeName == "error" and msg.id != -1:
            print "Server Error:", msg

    def tick_event(self, msg):
        if msg.field == 1:
            self.bid_price = msg.price
        elif msg.field == 2:
            self.ask_price = msg.price
        elif msg.field == 4:
            self.last_prices.loc[dt.datetime.now()] = msg.price
            resampled_prices = \
                self.last_prices.resample(self.resample_interval,
                                          how='last',
                                          fill_method="ffill")
            self.average_price = resampled_prices.tail(
                self.averaging_period).mean()[0]

        print dt.datetime.now(), "average:", self.average_price, \
            "bid:", self.bid_price, "ask:", self.ask_price

    def create_contract(self, symbol, sec_type, exch, prim_exch, curr):
        contract = Contract()
        contract.m_symbol = symbol
        contract.m_secType = sec_type
        contract.m_exchange = exch
        contract.m_primaryExch = prim_exch
        contract.m_currency = curr
        return contract

    def request_market_data(self, symbol_id, symbol):
        contract = self.create_contract(symbol,
                                        'STK',
                                        'SMART',
                                        'SMART',
                                        'USD')
        self.tws_conn.reqMktData(symbol_id, contract, '', False)
        time.sleep(1)

    def cancel_market_data(self, symbol):
        self.tws_conn.cancelMktData(symbol)
        time.sleep(1)

    def connect_to_tws(self):
        self.tws_conn = Connection.create(port=self.port,
                                          clientId=self.client_id)
        self.tws_conn.connect()

    def disconnect_from_tws(self):
        if self.tws_conn is not None:
            self.tws_conn.disconnect()

    def register_callback_functions(self):
        # Assign error handling function.
        self.tws_conn.register(self.error_handler, 'Error')

        # Register market data events.
        self.tws_conn.register(self.tick_event,
                               message.tickPrice,
                               message.tickSize)

    def start(self):
        try:
            self.connect_to_tws()
            self.register_callback_functions()
            self.request_market_data(self.symbol_id, self.symbol)

            while True:
                time.sleep(1)

        except Exception, e:
            print "Error:", e
            self.cancel_market_data(self.symbol)

        finally:
            print "disconnected"
            self.disconnect_from_tws()

if __name__ == "__main__":
    system = AlgoSystem("FB", 100, "30s", 5)
    system.start()

A: I don't know anything about the interactive brokers API, but my guess is that your start method needs to be changed to something along the lines of :
def start(self):

    try:
        self.connect_to_tws()
        self.register_callback_functions()
        while True:
            self.request_market_data(self.symbol_id, self.symbol)
            time.sleep(1)

    except Exception, e:
        print "Error:", e
        self.cancel_market_data(self.symbol)

    finally:
        print "disconnected"
        self.disconnect_from_tws()

currently your infinite loop just repeatedly sleeps. I think you want the request_market_data to be inside the while loop.


text:
Q: Selenium error on OSX when doing Protractor Tutorial I am trying to get protractor up and running on OSX 10.11.6 by following the guide on Protractor webpage.
here is the setup:
$ npm install -g protractor
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
/usr/local/bin/webdriver-manager -> /usr/local/lib/node_modules/protractor/bin/webdriver-manager
/usr/local/bin/protractor -> /usr/local/lib/node_modules/protractor/bin/protractor
/usr/local/lib
└── protractor@4.0.4

$ webdriver-manager update
[16:01:00] I/update - chromedriver: file exists /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22mac32.zip
[16:01:00] I/update - chromedriver: unzipping chromedriver_2.22mac32.zip
[16:01:00] I/update - chromedriver: setting permissions to 0755 for /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22
[16:01:00] I/update - chromedriver: v2.22 up to date
[16:01:00] I/update - selenium standalone: file exists /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-2.53.1.jar
[16:01:00] I/update - selenium standalone: v2.53.1 up to date

$ webdriver-manager start
[16:01:15] I/start - java -jar /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver=/usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22
[16:01:15] I/start - seleniumProcess.pid: 21540
16:01:16.017 INFO - Launching a standalone Selenium Server
Setting system property webdriver.chrome.driver to /usr/local/lib/node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.22
16:01:16.042 INFO - Java: Oracle Corporation 25.102-b14
16:01:16.042 INFO - OS: Mac OS X 10.11.6 x86_64
16:01:16.051 INFO - v2.53.1, with Core v2.53.1. Built from revision a36b8b1
16:01:16.097 INFO - Driver provider org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
registration capabilities Capabilities [{ensureCleanSession=true, browserName=internet explorer, version=, platform=WINDOWS}] does not match the current platform MAC
16:01:16.097 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver registration is skipped:
registration capabilities Capabilities [{browserName=MicrosoftEdge, version=, platform=WINDOWS}] does not match the current platform MAC
16:01:16.097 INFO - Driver class not found: com.opera.core.systems.OperaDriver
16:01:16.097 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
16:01:16.099 INFO - Driver class not found: org.openqa.selenium.htmlunit.HtmlUnitDriver
16:01:16.099 INFO - Driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
16:01:16.141 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
16:01:16.141 INFO - Selenium Server is up and running
16:03:10.472 INFO - Executing: [new session: Capabilities [{count=1, browserName=chrome}]])
16:03:10.479 INFO - Creating a new session for Capabilities [{count=1, browserName=chrome}]
Starting ChromeDriver 2.22.397929 (fb72fb249a903a0b1041ea71eb4c8b3fa0d9be5a) on port 32768
Only local connections are allowed.
16:03:30.725 WARN - Exception thrown
java.util.concurrent.ExecutionException: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'Sebastians-MacBook-Pro.local', ip: '10.251.17.130', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_102'
Driver info: driver.version: unknown
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.openqa.selenium.remote.server.DefaultSession.execute(DefaultSession.java:183)
    at org.openqa.selenium.remote.server.DefaultSession.<init>(DefaultSession.java:119)
    at org.openqa.selenium.remote.server.DefaultSession.createSession(DefaultSession.java:95)
    at org.openqa.selenium.remote.server.DefaultDriverSessions.newSession(DefaultDriverSessions.java:124)
    at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:59)
    at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:1)
    at org.openqa.selenium.remote.server.rest.ResultConfig.handle(ResultConfig.java:111)
    at org.openqa.selenium.remote.server.JsonHttpCommandHandler.handleRequest(JsonHttpCommandHandler.java:79)
    at org.openqa.selenium.remote.server.DriverServlet.handleRequest(DriverServlet.java:204)
    at org.openqa.selenium.remote.server.DriverServlet.doPost(DriverServlet.java:166)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.openqa.selenium.remote.server.DriverServlet.service(DriverServlet.java:132)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.openqa.jetty.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
    at org.openqa.jetty.jetty.servlet.ServletHandler.dispatch(ServletHandler.java:680)
    at org.openqa.jetty.jetty.servlet.ServletHandler.handle(ServletHandler.java:571)
    at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1526)
    at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1479)
    at org.openqa.jetty.http.HttpServer.service(HttpServer.java:920)
    at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
    at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
    at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
    at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:243)
    at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:358)
    at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:537)
Caused by: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'Sebastians-MacBook-Pro.local', ip: '10.251.17.130', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_102'
Driver info: driver.version: unknown
    at org.openqa.selenium.remote.server.DefaultDriverProvider.callConstructor(DefaultDriverProvider.java:113)
    at org.openqa.selenium.remote.server.DefaultDriverProvider.newInstance(DefaultDriverProvider.java:97)
    at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance(DefaultDriverFactory.java:60)
    at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:222)
    at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.server.DefaultDriverProvider.callConstructor(DefaultDriverProvider.java:103)
    ... 9 more
Caused by: org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'Sebastians-MacBook-Pro.local', ip: '10.251.17.130', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_102'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:665)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:138)
    ... 14 more
Caused by: java.lang.IllegalStateException: The process has not exited yet therefore no result is available ...
    at org.apache.commons.exec.DefaultExecuteResultHandler.getException(DefaultExecuteResultHandler.java:76)
    at org.openqa.selenium.os.UnixProcess.checkForError(UnixProcess.java:171)
    at org.openqa.selenium.os.CommandLine.checkForError(CommandLine.java:185)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:177)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:166)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:644)
    ... 19 more
16:03:30.732 WARN - Exception: The process has not exited yet therefore no result is available ...

and here I run the test:
$ protractor conf.js
[16:03:10] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[16:03:10] I/launcher - Running 1 instances of WebDriver
[16:03:30] E/launcher - The process has not exited yet therefore no result is available ...
[16:03:30] E/launcher - WebDriverError: The process has not exited yet therefore no result is available ...
    at WebDriverError (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:26:26)
    at Object.checkLegacyResponse (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:639:15)
    at parseHttpResponse (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:538:13)
    at /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:472:11
    at ManagedPromise.invokeCallback_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1379:14)
    at TaskQueue.execute_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
    at TaskQueue.executeNext_ (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2896:21)
    at /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2820:25
    at /usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (internal/process/next_tick.js:103:7)
From: Task: WebDriver.createSession()
    at Function.createSession (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:329:24)
    at Builder.build (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/builder.js:458:24)
    at Hosted.DriverProvider.getNewDriver (/usr/local/lib/node_modules/protractor/built/driverProviders/driverProvider.js:37:33)
    at Runner.createBrowser (/usr/local/lib/node_modules/protractor/built/runner.js:190:43)
    at /usr/local/lib/node_modules/protractor/built/runner.js:264:30
    at _fulfilled (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:834:54)
    at self.promiseDispatch.done (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:863:30)
    at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:796:13)
    at /usr/local/lib/node_modules/protractor/node_modules/q/q.js:556:49
    at runSingle (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:137:13)
[16:03:30] E/launcher - Process exited with error code 199

Here are the files
// conf.js
exports.config = {
  framework: 'jasmine',
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js']
}

// spec.js
describe('Protractor Demo App', function() {
  it('should have a title', function() {
    browser.get('http://juliemr.github.io/protractor-demo/');

    expect(browser.getTitle()).toEqual('Super Calculator');
  });
});

I have sat with this issue and searching for days and I really need to get this working.


text:
Q: Limitations of Ray-casting algorithm and optional robust solution(approach) for the same? As per the study of point-containment algorithms and analysis of some irregular polygons, I've personally observed that in some cases this approach(Ray-casting algorithm) fail's if,

*

*The ray drawn from test point crosses(intersects) once and then just "touches" one point on the outside, forming something like a "tangent"

*The polygon is of self-intersecting type and the ray drawn from test point crosses exactly through such a crossing point

*The ray crosses a section of a polygon where two lines of the this same polygon are drawn exactly on top of each other
So can some one please suggest a solution or an optional approach for the point containment check that can give a more robust and optimized results?


text:
Q: Is there a way to resize child elements of a GridLayout so that they fit the screen? I have created a GridLayout with 6 rows and 6 columns and I want to fill it with ImageViews and TextViews. I placed the Views in the 6 columns, but they are too big for the screen. What is the best way to adjust them so that the GridLayout columns automatically adjust to the screen?
Here is the XML that I have so far (only the first row is filled here)
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:rowCount="6"
    android:columnCount="6">

    <ImageView
        android:id="@+id/imageButton1"
        android:layout_column="0"
        android:layout_gravity="left|top"
        android:layout_row="0"
        android:src="@drawable/number_placeholder" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_column="1"
        android:layout_gravity="left|top"
        android:layout_row="0"
        android:src="@drawable/sign_placeholder"
       />

    <ImageView
        android:id="@+id/imageButton2"
        android:layout_column="2"
        android:layout_gravity="left|top"
        android:layout_row="0"
        android:src="@drawable/number_placeholder"
         />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_column="3"
        android:layout_gravity="left|top"
        android:layout_row="0"
        android:src="@drawable/sign_placeholder"
         />

    <ImageView
        android:id="@+id/imageButton3"
        android:layout_column="4"
        android:layout_gravity="left|top"
        android:layout_row="0"
        android:src="@drawable/sign_placeholder"
  />

    <TextView
        android:id="@+id/textView1"
        android:layout_column="5"
        android:layout_gravity="left|center_vertical"
        android:layout_row="0"
        android:text="TextView"
    />

</GridLayout>

A: Try match_parent instead wrap_content in your GridLayout:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:rowCount="6"
  android:columnCount="6">

And then experiment with the layout_width and layout_height of your image and text views until you have the desired result.


text:
Q: Session changes on page refresh in laravel 5.2 I am running on Laravel 5.2. Every time I run page refresh the session id changes. I haven't added 'Web middleware' as it's added by default to routes.php. Found like this issues floating on forums but none really seems to be the solution. Help will be appreciated.

A: We got threw this error too, and this is what seems to fix the problem :
• Check that your storage/ folder have the correct right
• Try to disable all the Javascript in your pages (either by disabling it via navigator or inside the code) and make sure that 'http_only' => true,
• Try to use with and without https
• Make sure the SESSION_DRIVER variable is NOT null
• Try to switch between 'encrypt' => false, and 'encrypt' => true,
• Try to change the cookie name 'cookie' => 'laravelsession',
• Try either to set your SESSION_DOMAIN to your actual domain OR null
• Try to switch between 'secure' => env('SESSION_SECURE_COOKIE', false), and 'secure' => env('SESSION_SECURE_COOKIE', true),
After every step, this bug seems to be fixed, but somehow, the cookie still is not set in the navigator sometime until we use https on development too.
I am sorry not to be able to provide a 100% fix, but having the EXACT same issue, I wanted to share my experience with you.


text:
Q: php imagecreatefromjpeg not working I am new to PHP, so this might be an easy one.
I just want to display an image once it is uploaded and sent to the script by POST. But I am not able to see the image.
Please find the code below:
Name of the php file is test.php
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

    if(isset($_FILES['photo'])
    && is_uploaded_file($_FILES['photo']['tmp_name'])
    && $_FILES['photo']['error'] == UPLOAD_ERR_OK){

        if ($_FILES['photo']['type']=='image/jpeg') {

            $tmp_img = $_FILES['photo']['tmp_name'];
            $image = imagecreatefromjpeg($tmp_img);
            header('Content-Type: image/jpeg');
            imagejpeg($image,'',90);
            imagedestroy($image);

        }else{
            echo "Uploaded file was not JPEG","
";
        }
    }else{
        echo "No file uploaded","
";

    }
}else{
    ?>
    <form action="test.php" method="post" enctype="multipart/form-data">
        Photo :
        <input type="file" name="photo"/>
        <input type="submit" value="Upload a JPEG photo"/>
    </form>

<?php } ?>

A: Do you get any errors?
Is GD installed? imagecreatefromjpeg is a GD method.
http://php.net/manual/en/image.installation.php

A: You need to pass NULL here:
        imagejpeg($image,NULL,90);

From the documentation under Parameters:
filename

  The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

  To skip this argument in order to provide the quality parameter, use NULL.


text:
Q: How to color/identify plot points by date I am trying to build a geom_line plot in ggplot2 to show some call center data over time.  I have my graph built as I want it, but I would like to identify specific dates (Monday's to be specific.. IE, 1/7, 1/14, 1/21, 1/28, 2/4, etc) with something like a special marker/color.. currently the dates are character format (how they were given to me), but with lubridate I believe they could be converted with little/no issue if needed.  Is this possible?
I am super novice at plotting with R, I have gotten to this point from other SO posts and a few 'cheat sheets'.
The only 'relevant' post I could find that directly mentions using any kind of function with ggplot is here: http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/#use-a-function-to-alter-labels.  This doesn't exactly fit what I am looking for either.
Here is my code as it sits:
a <-  ggplot(cleantargetcounts)+
   geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
   scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
   geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
   geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
   theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
   labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

Here is what my graph looks like currently:

and here is a basic idea of what I am looking for:

It would not matter to me HOW Monday's are identified.. whether it is a date colored, the plotted points are different.. just as long as they are easy to point out.
Here's my data:
    DTE        DISPOSITION TOTAL
   <chr>      <chr>       <int>
 1 2019-01-08 Approval      454
 2 2019-01-08 Denial        120
 3 2019-01-08 Skip          135
 4 2019-01-09 Approval      425
 5 2019-01-09 Denial        141
 6 2019-01-09 Skip          203
 7 2019-01-10 Approval      448
 8 2019-01-10 Denial        112
 9 2019-01-10 Skip          169
10 2019-01-11 Approval      666

Attempted codes provided by Heck1
cleantargetcounts$weekday <- wday(ymd(cleantargetcounts$DTE), label = TRUE, abbr = FALSE)

a <-  ggplot(cleantargetcounts)+
  geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
  scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
  geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
  geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1, color = ifelse(cleantargetcounts$weekday == "Monday", "red", "black")))+
  labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

which provides the following plot

Which is a bit odd as it correctly identified the days of the week in my data frame.
 DTE        DISPOSITION TOTAL weekday
  <chr>      <chr>       <int> <ord>
1 2019-01-07 Approval      455 Monday
2 2019-01-07 Denial         95 Monday
3 2019-01-07 Skip          154 Monday
4 2019-01-08 Approval      454 Tuesday
5 2019-01-08 Denial        120 Tuesday
6 2019-01-08 Skip          135 Tuesday

Attempting Jason's answer
I get an error that I am not familiar with
 df_tidy <- cleantargetcounts %>%
gather(DISPOSITION, TOTAL, -DTE) %>%
mutate(dow = wday(ymd(cleantargetcounts$DTE, abbr = TRUE, label = TRUE)))

Error: Column `dow` must be length 306 (the number of rows) or one, not 155
In addition: Warning message:
 2 failed to parse.

correction to Jason's answer
I had to modify part of Jason's answer to get it working correctly for me as follows:
df_tidy <- cleantargetcounts2 %>% mutate(dow = wday(DTE, abbr = TRUE, label = TRUE))
df_regions <- df_tidy %>% filter(dow == "Mon") %>% mutate(min = DTE - 0.5,
                                                          max = min + 1,
                                                          ymin = -Inf,
                                                          ymax = +Inf)

a <-  ggplot(df_tidy)+
  geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
  scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
  geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
  geom_text_repel(aes(label=df_tidy$TOTAL, x=DTE,y=TOTAL))+
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
  labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")+
  geom_rect(data = df_regions,aes(xmin = min, xmax = max, ymin = ymin, ymax = ymax), fill = "blue", alpha = 0.2, color = NA)

Which produced the most accurate end result I was looking for like this:

A: without knowing your data, a solution with lubridate would look like this:
 library(lubridate)
 cleantargetcounts$weekday <- wday(ymd(cleantargetcounts$DTE), label = TRUE, abbr = FALSE)

Output of cleantargetcounts$weekday should be a vector with "Monday" "Tuesday" and so on. Then to mark mondays on your plot you could use:
a <-  ggplot(cleantargetcounts)+
   geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
   scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
   geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
   geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
   theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1,
colour = ifelse(cleantargetcounts$weekday == "Monday",
                                         "red","black)
    ))+
   labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

A: Please try and make a reproducible example, however, based on your pictures, the following should get you what you want. In short, just pass "filtered" data into a geom call:
library(tidyverse)
library(lubridate)

set.seed(101)

df <- tibble(
  date = seq(ymd("2019-01-07"), ymd("2019-03-18"), by = "day"),
  approval = runif(n = 71, 225, 800),
  denial = runif(n = 71, 85, 120),
  skip = runif(n = 71, 120, 300)
)

df %>%
  gather(metric, value, -date) %>%
  mutate(
    dow = wday(date, abbr = TRUE, label = TRUE)
  ) %>%
  ggplot(aes(x = date, y = value, color = metric)) +
  geom_point() +
  geom_line() +
  geom_point(data = . %>% filter(dow == "Mon"), color = "deeppink", size = 3)

Alternatively, you could create a highlights data.frame like this and pass this to geom_rect:
df_tidy <-
  df %>%
  gather(metric, value, -date) %>%
  mutate(
    dow = wday(date, abbr = TRUE, label = TRUE)
  )

df_regions <-
  df_tidy %>%
  filter(dow == "Mon") %>%
  mutate(
    min = date - 0.5, # we want the highlighted region 'around' the point, not on the point.
    max = min + 1,
    ymin = -Inf,
    ymax = +Inf
  )

df_tidy %>%
  ggplot(aes(x = date, y = value, color = metric)) +
  geom_point() +
  geom_line() +
  geom_rect(
    data = df_regions,
    aes(xmin = min, xmax = max, ymin = ymin, ymax = ymax),
    fill = "orange", alpha = 0.2, color = NA
  )

Created on 2019-03-25 by the reprex package (v0.2.1)


text:
Q: Which it is the best way to fill a dropdowlist in ASP.NET MVC Which it is the best way in which you do not have to repeat the code in the Get and Post method to populate a DropDownList
That in view of creating and editing , I need to deploy some dropdowlist of related tables and do not want to be repeating viewbag in the GET and POST methods
Example :
A view where employees are recognized at an apartment, there is a Department employee relationship with.
public class Employee
{
    public int EmployeeId { get; set; }

    [DisplayName("Employee Name")]
    [Required]
    public string EmployeeName { get; set; }

    [DisplayName("Department Id")]
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
}

public class Department
{
    public int DepartmentId { get; set; }

    [DisplayName("Department Name")]
    [Required]
    public string DepartmentName { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

public class CompanyContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
}

And the controller method
public ActionResult Create()
{
    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName");
    return View();
}

[HttpPost]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        db.Employees.Add(employee);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentName", employee.DepartmentId);
    return View(employee);
}

A: Move it to a method and call it in both the places. I recommend using a strongly typed view model for transferring data between your action method and view ,instead of using dynamic stuff like ViewBag and ViewData.
public class CreateUserVM
{
  public int UserId {set;get;}
  public string Name {set;get;}
  public List<SelectListItem> Departments {set;get;}
  public int SelectedDept {set;get;}

  public CreateUserVM()
  {
    this.Departments = new List<SelectListItem>();
  }

}

And in the GET action,
public ActionResult Create()
{
    var vm = new CreateUserVM();
    vm.Departments = GetDeperatements();
    return View(vm);
}

private List<SelectListItem> GetDeperatements()
{
   return db.Departments.Select(s=> new SelectListItem {
                                    Value=DepartmentId.ToString(),
                                    Text = "DepartmentName"
                               }).ToList();
}

Your view is bound to the CreateUserVM view model
@model YourNamespaceHere.CreateUserVM
@using(Html.BeginForm())
{
  @Html.DropdownListFor(s=>s.SelectedDept,Model.Departments,"Select on")
  @Html.TextBoxFor(s=>s.Name)
  @Html.HiddenFor(s=>s.UserId)
  <input type="submit" />
}

[HttpPost]
public ActionResult Create(CreateUserVM model)
{
    if (ModelState.IsValid)
    {

        //Map the view model to entity

        var emp = new Employee();
        emp.Name = model.Name;
        emp.DepartmentId = model.SelectedDept;

        db.Employees.Add(emp);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    employee.Departments = GetDeperatements();
    return View(employee);
}

For Your edit screen, You can use the same code as create action except you need to accept and id, Read the entity from db, map it to the viewmodel. (Set the SelectedDept id property value as well) and send it to the view.


text:
Q: Bootstrap 3 - Managing column wrap Needing to nest rows in Bootstrap 3.  Main requirements

*

*Three large columns

*Each column equal width

*Columns to contain either one or two images

*Layout structure should be maintained for all device sizes

This Codeply is where we are at right now
http://www.codeply.com/go/bp/jwSEq9JSrH
The layout is as required for desktop but goes funny on tablet down
We'd welcome any comments
Kind regards
Mike


text:
Q: My Imagick code never seems to resize and still produce a sharp image I fear that Imagick may not support sharp image resizing. Even the best filters are returning blurry results which are sub par, even horrible in my humble opinion.
This is the BEST quality I can get out of Imagick:

This is resized using TimThumbs:

NOTICE the drastic quality difference? Can anyone provide an example of a sharp image being produced by Imagick?
Below is the Imagick code used to generate the first image:
function imgSize($imagePath,$imageName,$imageExt,$width,$height,$copy) {
    $file = "img/".$imageName."-".$width."x".$height.".".$imageExt;
    if (!file_exists($file)) {
        try {
                $image = $imagePath;
                $im = new Imagick();
                $im->pingImage($image);
                $im->readImage($image);
                $im->setImageFormat($imageExt);
                //$im->thumbnailImage($width,$height,true);
                $im->cropThumbnailImage($width,$height);
                $im->resizeImage($width,$height,Imagick::FILTER_LANCZOS,0,false);
                $im->cropThumbnailImage($width,$height);
                if ($imageExt=("jpg"||"JPG")) {
                    $img->setComression(Imagick::COMPRESSION_JPEG);
                    $img->setComressionQuality(100);
                }
                if (!$copy==null) {
                    $draw = new ImagickDraw();
                    $draw->setFont("fpdf/font/Montserrat-Regular.ttf");
                    $draw->setFontSize(35);
                    $draw->setFillColor("Gray");
                    $draw->setFillAlpha(0.5);
                    $draw->setGravity(Imagick::INTERPOLATE_AVERAGE);
                    $im->annotateImage($draw,0,0,-45,$copy);
                }
                $im->writeImage("img/".$imageName."-".$width."x".$height.".".$imageExt);
                $im->destroy();
                return "img/".$imageName."-".$width."x".$height.".".$imageExt;
        }
        catch(Exception $e) { echo $e->getMessage(); }
    }
};

I am aware there are similar questions but there has not been a sufficient answer to this image quality problem. Most attempts to address Imagick's image quality issues are to reduced the problem to, "well that's what you get when you shrink an image." But the TimThumbs image example I have provided in this post disproves that assumption. You can shrink an image and get stunning results using PHP.

A: This seems better to me, I just resized it 20% of original image. Using GD and 100% quality as JPEG
function resizeImg($filename, $percent, $saveTo) {

    list($width, $height) = getimagesize($filename);
    $newwidth = $width * $percent;
    $newheight = $height * $percent;

    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);

    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($thumb, $saveTo, 100);
    imagedestroy($thumb);
}

resizeImg('image.jpg', 0.2, 'image02.jpg');

I have compiled php55-imagick extension to check your code , first of all you have misspelled  2 method names , when fixed  resulting image  is actually OK setCompression not setComression
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);

Here is image with correct methods as showdev commented , doubling image size (121K vs 329K ) , but to me not much benefit
$im->setImageCompression(Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(100);


text:
Q: Can I harm my iPhone if I damaged my lightning cable chip or scratched the contacts? I was using a Dremel to make the aluminum shell on a new lightning cable (long, braided) fit through the hole in my iPhone 6S+ case.
The aluminum shell got extremely hot. The cable seems to charge fine (didn't try data transfer), but I'm neurotic enough to worry that maybe the chip is somewhat damaged and something bad could happen in the future...Neurotic, right?
Also, I scraped some of the contacts (it was my first time using the Dremel!), which I'm guessing is no big deal either...?
Thanks :)


text:
Q: What is the maximum number of consecutive periods can be used in a grammatically-correct sentence? I'm curious how many period characters can be in a row in a valid sentence.
I acknowledge that there are different conventions for how to treat dots (e.g. treating an ellipsis as a single character or putting a space before and after an ellipsis), but for the purposes of this question, I think we should allow reasonable conventions that could be considered acceptable, even if they aren't perhaps recommended. I'm also fine ignoring whitespace.
Examples

*

*Here's a sentence with one period.

*This sentence combines two periods into one, according to some prof.

*This sentence ends with an ellipsis....

*This sentence also might make sense, according to Knowsalot et al.....

Clarification
Please read the question carefully and in its entirety before voting to close a question.
Some closed this question because they thought this question has an answer here: When "etc." is at the end of a phrase, do you place a period after it?. Those people have made unreasonable assumptions about what this question is asking.
For clarity: I am not asking whether or not the period following an abbreviation gets put at the end of a phrase. I am not asking about a period before or after an ellipsis. I am asking how many periods can be in a row for any reason. Clearly, those other questions are relevant to my question, but to answer my question, you'd need the answers to all of those kinds of questions and combine their answers to be able to answer this question.

A: Five?
The most I can get is five (the last example in the question), which has one period from an abbreviation ("et al."), three for an ellipsis ("..."), and one to close the sentence (".").
Some manuals would prefer that last sentence to be written as follows:

This sentence also might make sense, according to Knowsalot et al. ... .

Since you specify that you are ignoring whitespace, that's five dots.
Sure, this is bad form, but from what I've read and seen, it's okay to have a period from an abbreviation before an ellipsis (discussion), and it's okay to have an ellipsis at the end of a sentence followed by a period (source).


text:
Q: Rolling point of contact I have been reading "variational principles in classical mechanics" by Douglas Cline and the following page rather confused me. It states that for a cylinder rolling without slipping, the velocity of rolling point of contact is not zero. What am I missing here?

A: The contact point is stationary when the wheel (or cylinder) is rolling. Otherwise it wouldn't be rolling, but sliding. The "without slipping" part is emphasizing this - if the two surfaces slide over one another, then we have slipping. If they don't, then we have no slipping.
And if they don't slide over one another, well, then they are stationary relative to each other.
But only for a moment.
To roll, the wheel therefor isn't sliding over the surface. Rather, the point-of-contact on the wheel is "placed on" the surface and the rest of the wheel moves over this point. Then this point is "lifted off" from the surface. A new point takes over right away, so that there is basically always contact. This contact point is stationary in each moment, but is constantly replaced by a new point on the wheel.


text:
Q: Button Click and change int value? I make a database app. I have one button and one int value; I need to change int value.
Example = sayi = 1
button 1st. click = sayi = 2
button 2nd. click = sayi = 3
P.s = Sorry, I don't know english very well.
int sayi = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);
    final TextView oku = (TextView)findViewById(id.oku);
    final Button diger = (Button)findViewById(id.diger);
    diger.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int sayi = 2;
        }
    });

    Veritabani veritabanim;
    veritabanim = new Veritabani(this);
    try {

        veritabanim.createDataBase();

    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    SQLiteDatabase dbm = veritabanim.getReadableDatabase();

    Cursor c = dbm.rawQuery("SELECT _id,soyleyen,soz FROM sozler WHERE _id = "+sayi+" ", null);
    if(c.moveToFirst()){
        do{

            //assing values
            String column1 = c.getString(0);
            String column2 = c.getString(1);
            String column3 = c.getString(2);
            //Do something Here with values
            oku.setText(column3);

        }while(c.moveToNext());
    }
    c.close();
    dbm.close();
    }
}

A: Do it like this...
int sayi = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
Button diger = (Button)findViewById(id.diger);
diger.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        sayi++;
        getDBOperation();
    }
});
}

private void getDBOperation()
{
    TextView oku = (TextView)findViewById(id.oku);

    Veritabani veritabanim;
    veritabanim = new Veritabani(this);
    try {
        veritabanim.createDataBase();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    SQLiteDatabase dbm = veritabanim.getReadableDatabase();

   Cursor c = dbm.rawQuery("SELECT _id,soyleyen,soz FROM sozler WHERE _id = "+sayi+" ", null);
   if(c.moveToFirst()){
       do{
          //assing values
         String column1 = c.getString(0);
         String column2 = c.getString(1);
         String column3 = c.getString(2);
         //Do something Here with values
         oku.setText(column3);
       }while(c.moveToNext());
  }
  c.close();
  dbm.close();
  }


text:
Q: Tesseract: UnsatisfiedLinkError - undefined symbol: TessBaseAPICreate I'm getting the following error when I tired to run Tess4j sample program.
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'TessBaseAPICreate': /usr/local/lib/libtesseract.so: undefined symbol: TessBaseAPICreate
    at com.sun.jna.Function.<init>(Function.java:179)
    at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:350)
    at com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:330)
    at com.sun.jna.Library$Handler.invoke(Library.java:203)
    at $Proxy0.TessBaseAPICreate(Unknown Source)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:253)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:220)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:166)
    at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:151)
    at Test.main(Test.java:12)
Java Result: 1

I'm using Redhat Linux 32 bit.

A: Looks like binding error - shared lbrarz was found, but contents difer from what java expected.  You will have to check versions carefully.


text:
Q: Can opposing centripetal forces help us play catch in a space station? Let's say we are inside a wheel in our brand-new space station, which spins to simulate gravity, using the centrifugal force. We decide to celebrate our ground-breaking success by play catch in space.
We immediately realize the path of the ball gets annoyingly skewed by the rotation, making for a frustratingly difficult game of catch. We decide this won't do and go about fixing it.
After some thougthful discussion, we use our unlimited resources to build an additional wheel inside the original wheel that spins counter to it, compensating the skewing of the ball being thrown, so we can play a proper game.
What would happen? Would it work?

A: Yes, it would work - sort of.
If the second wheel spun at a rate that undid the rotation of the first wheel, there would be no rotation. It would be as if there were no wheels.
The ball would be seen to go in a straight line, but you would be weightless.


text:
Q: SQL Server and ADO.NET mis-generation Has anyone tried to generate from two table like so
Table1
ID - PK
Table2Id - FK (unique constraint and nullable)
Log - String

Table2
Id - PK
Request - String

When I generate from these tables, I expect a 0..1 to 0..1 relationship or when I make it not nullable, I expect a 0..1 to 1 relationship which also doesn't seem to generate correctly.
Does this work for other people?
Caveat: I do mostly java, so I am probably missing something simple.
Also, a follow on question. I am more used to hibernate and also find it strange that it generates a Table1.Table2 field AND a Table1.Table2Id field. In hibernate world, it only generates the Table1.Table2 field and when you call Table1.Table2.Id it gets the id not from Table2 but from the FK column of Table1 to avoid the database hit. I.e. why does C# bother having the second id field on generation as it seems like a waste?


text:
Q: Getting the centroids of Lat and Longitude in a data frame I have a dataframe (df) which has three column likes so: (all numbers random)
ID  Lat    Lon
1   25.32 -63.32
1   25.29 -64.21
1   24.12 -62.43
2   12.42  54.64
2   12.11  53.43
.   ....   ....

Basically I wanted to have the centroid per ID like so:
ID  Lat    Lon    Cent_lat   Cent_lon
1   25.32 -63.32  25.31      -63.25
1   25.29 -64.21  25.31      -63.25
1   24.12 -62.43  25.31      -63.25
2   12.42  54.64  12.20       53.60
2   12.11  53.43  12.20       53.60

I tired the following:
library(geosphere)
library(rgeos)
library(dplyr)

df1 <- by(df,df$ID,centroid(df$Lat, df$Long))

But this gave me this error:

Error in (function (classes, fdef, mtable):
          unable to find an inherited method for function 'centroid' for signature '"numeric"'

I even tired
df1 <- by(df,df$ID,centroid(as.numeric(df$Lat), as.numeric(df$Long)))

But this gave me this error:

Error in (function (classes, fdef, mtable)  :
    unable to find an inherited method for function 'centroid' for signature '"function"'

A: library(geosphere)
library(ggplot2)
library(dplyr)

states <- map_data("state")

head(states)
##        long      lat group order  region subregion
## 1 -87.46201 30.38968     1     1 alabama      <NA>
## 2 -87.48493 30.37249     1     2 alabama      <NA>
## 3 -87.52503 30.37249     1     3 alabama      <NA>
## 4 -87.53076 30.33239     1     4 alabama      <NA>
## 5 -87.57087 30.32665     1     5 alabama      <NA>
## 6 -87.58806 30.32665     1     6 alabama      <NA>

cntrd <- function(x) {
  data.frame(centroid(as.matrix(x[,c("long", "lat")])))
}

by(states, states$group, cntrd) %>% head()
## $`1`
##         lon      lat
## 1 -86.82976 32.82735
##
## $`2`
##         lon      lat
## 1 -111.6698 34.34309
##
## $`3`
##         lon      lat
## 1 -92.43826 34.92167
##
## $`4`
##         lon      lat
## 1 -119.6713 37.40289
##
## $`5`
##         lon      lat
## 1 -105.5526 39.02653
##
## $`6`
##         lon      lat
## 1 -72.72553 41.62706

group_by(states, group) %>%
  do(cntrd(.))
## Source: local data frame [63 x 3]
## Groups: group [63]
##
##    group        lon      lat
##    <dbl>      <dbl>    <dbl>
## 1      1  -86.82976 32.82735
## 2      2 -111.66978 34.34309
## 3      3  -92.43826 34.92167
## 4      4 -119.67130 37.40289
## 5      5 -105.55264 39.02653
## 6      6  -72.72553 41.62706
## 7      7  -75.51543 39.00879
## 8      8  -77.03411 38.91083
## 9      9  -82.51260 28.69498
## 10    10  -83.46361 32.67562
## # ... with 53 more rows

A: To use centroid you need polygons with longitude and latitude, in that order. See this example:
df<-rbind(c(-180,-20), c(-160,5), c(-60, 0), c(-160,-60), c(-180,-20),
c(-100,-50), c(-160,-60), c(-180, -10), c(-160,10), c(-60,0),c(-100,-50))
df<-data.frame(ID=rep(c(1,2),times=c(5,6)),Lon=df[,1],Lat=df[,2])
df1 <- by(df[,c("Lon", "Lat")],df$ID,centroid)
df1
df[,c("Cent_lon","Cent_lat")]<-NA
for(i in names(df1))df[df$ID==i,c("Cent_lat","Cent_lon")]<-df1[[i]]
df

   ID  Lon Lat   Cent_lon   Cent_lat
1   1 -180 -20  -23.89340 -133.33333
2   1 -160   5 -133.33333  -23.89340
3   1  -60   0  -23.89340 -133.33333
4   1 -160 -60 -133.33333  -23.89340
5   1 -180 -20  -23.89340 -133.33333
6   2 -100 -50 -127.66065 -127.66065
7   2 -160 -60  -26.10686  -26.10686
8   2 -180 -10 -127.66065 -127.66065
9   2 -160  10  -26.10686  -26.10686
10  2  -60   0 -127.66065 -127.66065
11  2 -100 -50  -26.10686  -26.10686

You can use plotArrows to see the polygon
pol<-split(df[,2:3],df$ID)
#plotArrows(pol[[1]])
plotArrows(as.matrix(pol[[1]]))
points(df1[[1]],col=4)

A: Here's a data.table approach. As @czeinerb mentioned, Lon is the first argument of the centroid function, and Lat is the second. We re-define the centroid function below so that, in the data.table aggregation, it receives a matrix with 2 columns (Lat|Lon), which is the required input into the geosphere's centroid function.
# Import packages
library(geosphere)
library(data.table) # Using a data.table approach

# Sample data
df = data.frame("ID" = c(1, 1, 1, 2, 2, 2), "Lat" = c(25.32, 25.29, 24.12, 12.42, 12.11, 12.22), "Lon" = c(-63.32, -64.21, -62.43, 54.64, 53.43, 53.23))

df

  ID   Lat    Lon
1  1 25.32 -63.32
2  1 25.29 -64.21
3  1 24.12 -62.43
4  2 12.42  54.64
5  2 12.11  53.43
6  2 12.22  53.23

# Convert to data.table
setDT(df)

# Re-define centroid function - Lon is first argument and Lat is second
# Geosphere takes a matrix with two columns: Lon|Lat, so we use cbind to coerce the data to this form
findCentroid <- function(Lon, Lat, ...){
  centroid(cbind(Lon, Lat), ...)
}

# Find centroid Lon and Lat by ID, as required
df[, c("Cent_lon", "Cent_lat") := as.list(findCentroid(Lon, Lat)), by = ID]
df

   ID   Lat    Lon  Cent_lon Cent_lat
1:  1 25.32 -63.32 -63.32000 24.91126
2:  1 25.29 -64.21 -63.32000 24.91126
3:  1 24.12 -62.43 -63.32000 24.91126
4:  2 12.42  54.64  53.76667 12.25003
5:  2 12.11  53.43  53.76667 12.25003
6:  2 12.22  53.23  53.76667 12.25003

A: Function centroid of the geosphere package takes a matrix as data argument: "Arguments : x a 2-column matrix (longitude/latitude)"
https://cran.r-project.org/web/packages/geosphere/geosphere.pdf
Also, longitude is the first and latitude is the second column, not the other way around :)
So the code in your case could be like:
library(geosphere)

df <- data.frame(ID = c(1,1,1,2,2,2,2)
                , Lon = c(-63.32, -64.43, -62.43, 54.64, 53.43, 54.64, 53.43)
                , Lat = c(25.32, 25.29, 24.12, 12.42, 12.11, 11.11, 10.55))
mx <- as.matrix(df)

(mx1 <- by(mx[,2:3], mx[,1], centroid))

With the output:
> INDICES: 1
> lon      lat
> [1,] -63.39333 24.91126
> -----------------------------------------------------------------
> INDICES: 2
> lon lat
> [1,] Inf  90

A: From ?centroid it says that it only takes a 2-column matrix as its argument. The ID information you have is making the matrix three columns.
df <- rbind(c(25.32,-63.32),c(25.29,-64.32),c(24.12,-62.43),c(12.42,54.64),c(12.11,53.43)
centroid(df)
  lon       lat
[1,] 24.27109 -60.37098


text:
Q: Upper right Dini derivative and indefinite integral I don't understand how the proof of the theorem below works. (Theorem 13.26, Real Analysis, J. Yeh, 2nd ed.)

Let $f$ be a real-valued continuous function on $[a,b]$ such that $f'$ exists almost everywhere (a.e.)  and $f'$ is $\mu_L$-integrable on [a,b]. If the upper-right Dini derivative $D^+f > -\infty$, on [a,b), then we have
$$
\int\limits_{[a,x]}f'd\mu_L=f(x)-f(a)
$$  for every $x\in[a,b]$.

The proof goes like this. The author defines additional functions.
$$
\begin{split}
g_n(x) &=\min\{f'(x),n\},\quad G_n=\int\limits_{[a,x]}g_nd\mu_L \\
\lim\limits_{n\rightarrow\infty}G_n &=\lim\limits_{n\rightarrow\infty}\int\limits_{[a,x]}g_nd\mu_L=\int\limits_{[a,x]}f'd\mu_L
\end{split} \text{ for }x\in[a,b]
$$
and
$$
\begin{split}
h_n(x)&=\max\{f'(x),-n\},\quad H_n=\int\limits_{[a,x]}h_nd\mu_L \\ \lim\limits_{n\rightarrow\infty}H_n&=\lim\limits\limits_{n\rightarrow\infty}\int\limits_{[a,x]}h_nd\mu_L=\int\limits_{[a,x]}f'd\mu_L
\end{split}\text{ for }x\in[a,b]
$$
Then,
$$
D^+G_n(x)=\limsup\limits_{h\downarrow0}h^{-1}\int\limits_{[x,x+h]}g_nd\mu_L\le\limsup\limits_{h\downarrow0}h^{-1}\int\limits_{[x,x+h]}n\mu_L=n,
$$ and
$$
D^+(f-G_n)\ge D^+f-D^+G_n\gt -\infty
$$ (in addition to $\ge 0$ a.e.), because $D^+f > -\infty$ by supposition, and $D^+G_n\le n$.
Thus, the real valued continuous function $f-G_n$ is an increasing function, and
$$
\begin{align}
f(x)-G_n(x)-(f(a)-G_n(a))&\ge0,\\
f(x)-f(a)&\ge G_n(x)
\end{align}
$$  for $x\in[a,b)$.
Since this holds for every $n\in\mathbb{N}$,
$$
f(x)-f(a)\ge\lim\limits_{n\rightarrow\infty}G_n(x)=\int_{[a,x]}f'd\mu_L.$$
Also,
$$
\begin{split}
D^+H_n(x) & = \limsup\limits_{h\downarrow0}h^{-1}\int_{[x,x+h]}h_nd\mu_L \\
& \ge \limsup\limits_{h\downarrow0}h^{-1}\int_{[x,x+h]}-n\mu_L=-n
\end{split}
$$ and
$$
D^+(H_n-f)\ge D^+H_n-D^+f\gt -\infty
$$ (and $\ge 0$ a.e.), because
$$
D^+f > -\infty\text{ and }D^+H_n\ge -n. \label{1}\tag{$***$}
$$
Thus, $H_n-f$ is an increasing function, and
$$
\begin{split}
H_n(x)&-f(x)-(H_n(a)-f(a)) \ge0,\\
H_n(x)&\ge f(x)-f(a)\\
\lim\limits_{n\rightarrow\infty}H_n(x)&=\int_{[a,x]}f'd\mu_L\ge f(x)-f(a)
\end{split}
$$ for $x\in[a,b)$.
Finally,
$$
\begin{split}
\int_{[a,x]}f'd\mu_L &\ge f(x)-f(a)\ge\int_{[a,x]}f'd\mu_L,\\
\int_{[a,x]}f'd\mu_L & = f(x)-f(a).
\end{split}
$$
I'm stuck at the line marked by \eqref{1}
How does $D^+f > -\infty$ and $D^+H_n\ge -n$ mean $D^+H_n-D^+f\gt -\infty$?

A: The Cantor function is a counterexample to the quoted claim:

"Let $f$ be a real-valued continuous function on [a,b] such that $f'$ exists almost everywhere (a.e.)  and $f'$ is $\mu_L$-integrable on [a,b]. If the upper-right Dini derivative $D^+f > -\infty$, on [a,b), then we have $\int_{[a,x]}f'd\mu_L=f(x)-f(a)$  for every $x\in[a,b]$."

Indeed, let $f$ be the Cantor function. Then $f$ is a real-valued continuous function on $[0,1]$ such that $f'=0$ a.e., so that $f'$ is $\mu_L$-integrable on $[0,1]$. Since $f$ in nondecreasing, we have
$D^+f \ge0> -\infty$ on $[0,1)$. However,
$$
\int\limits_{[0,1]}f'd\mu_L=0\ne1-0=f(1)-f(0).
$$

Of course, the logical transition that you marked by ($***$) is also wrong.


text:
Q: Get path of process file I'm trying to do a program that needs to catch the full path of files being used (anywhere in the system)
Straight to an example.
I opened a file called "notify.py" whichis in the
/home/miguel/Dropbox/prog/python/notify/

directory.
When I call
ps aux

in linux shell, the process line corresponding to this file's process is
miguel   11798  0.7  0.4 512320 34176 pts/2    Sl   22:41   0:06 gedit notify.py

which doesn't say anything about the path of the file that I actually opened!
What I wanted (and have been looking for hours, be it using ps, lsof or python's psutil) was a way to get the full path of the file corresponding to that process, that is, I'd like, from the process, to get the directory line referenced above.
Thanks for your answers

A: You might try to readlink(2) the file /proc/<pid>/exe, which should be exactly what you want:
$ ls -l /proc/$$/exe
lrwxrwxrwx 1 aw aw 0 Apr  7 00:02 /proc/11700/exe -> /bin/zsh
$

But note that this is not overly portable.  It should work on Linux and at least FreeBSD, but might fail on other UNICes.  That's also the reason why e.g. sshd want's to be called with a full path, so that it would be sufficient to take $0 (or argv[0] or whatever corresponds to the 0th command line argument) to know the exact location of the binary.  There's no portable way to do this.


text:
Q: Configure Maven installation in Jenkins per individual job Is there a way to configure Jenkins to use specific Maven installation per job?
e.g.
Job A - Maven 3.3.3
Job B - Maven 3.3.9

A: Jenkins allows you to select which Maven installation to use per job. You can setup multiple installations of Maven, multiple settings configurations of Maven to be exact, through Manage Jenkins → Configure System.
Then to configure per job, in Jenkins, select your specific build job and choose Configure. From there, assuming it is a Maven project build, you should have option(s) under the Build section (might have to hit the Advanced button) where you can select the Maven settings for your installation you want.
khmarbaise's comment is very valid, though. Unless you have a very specific reason to downgrade Maven for a given job, your build shouldn't be too reliant on what minor versions of the build tool to use.

A: For newer Jenkins versions, management of Maven installations is placed here:
Manage Jenkins → Global Tool Configuration → section Maven.
Per job configuration: "Maven Version" dropdown placed in "Build" section.


text:
Q: Automatically translated resources in Android Does anyone know if there are string resources that are automatically translated to the user's language?
I observed the Google "Sign in" button text has this characteristic of adapting to the user's language

xml: com.google.android.gms.common.SignInButton/>
Any other resources with this behaviour there?
I would need for my app some common words like: Email, Message, Logout, Call, Loading, Select all, Settings, Delete.
I know about the hard-way method  (values-fr > strings...) but I hope that Google translated the common words for us somewhere.

A: You can create localizable strings. In res folder, create a values-<locale>. And inside, create a strings.xml file containing the translated strings.
Example folder
values-ja

Example strings
<string name="app_name">私のアプリケーション</string>

When you change your phone language, your app will change to your desired localization if it is available.
For more info, check here


text:
Q: SIGINT signal gets dropped during write to a pipe I have a program that dumps pcap data gathered using the libpcap to stdout using pcap_dump function, with stdout as the FILE *.  There is a little bit of cleanup necessary on SIGINT, so I handle that with sigaction().  This works nicely when executed from a shell.
However, this program is intended to be called by another program, which doesn't seem to work.  This "caller" program calls a pipe(), then a fork(), then the child's stdout file descriptor is closed, and replaced with the write end of the pipe.  Finally, the aforementioned pcap program is executed in the child process.  This way the pcap data is written to the caller program through the pipe.  This also works nicely.  However, when I send a SIGINT to the child process while it is writing to the pipe (well, the pcap program thinks its writing to stdout, but its file descriptor was changed), the signal seems to get dropped, and the signal handler function never gets called at all.
Why is that?  If I write the pcap data to stderr or a file, the SIGINT never gets dropped.  Only when writing to the pipe.
Here is how we are setting up the pipe/fork/execute:
int fd[2];

//Create pipe
pipe(fd);

pid = fork(); //We forked a child

if(pid == 0){ //We are the child now

    close(1); //close child's stdout

    dup(fd[1]); //duplicate child's stdout to the write end of the pipe

    close( fd[0]); //close unused file descriptors
    close( fd[1]);

    //Load the new program
    execlp("./collectraw", "collectraw", NULL);

    perror("Exec");
    exit(127); //Should never get called but we leave it so the child
    //doesnt accidently keep executing
}
else{ //We are the parent

    //Set up the file descriptors
    close(fd[1]);
}

then to kill the child we use:
kill( pid, SIGINT);

In the child, the callback function for our pcap_loop() can be as simple as:
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet){
    write(1,"<pretend this is like a thousand zeros>",1000); //write to stdout, which is really a pipe
}

And we will basically always drop the SIGINT.  There's a lot of packets to capture by the way, so it's pretty safe to assume it's nearly always in the callback function.
But if we change from
write(1,... ); //write to stdout, which is really a pipe

to
write(2,...); //write to stderr, or writing to a file would work too

then everything gets hunky-dory again.
Why does our SIGINT get dropped during a write to a pipe?
Thanks for helping.
EDIT:  The child's SIGINT handler was never being called at all, but the reason wasn't really a problem in the child, it was a problem in the parent.  I used to kill the child like:
if( kill( pid, SIGINT) == -1){
    perror("Could not kill child");
}
close(pipefd);
fprintf(stdout, "Successfully killed child\n");

And this used to be our SIGCHLD handler:
void handlesigchild(int sig) {
    wait();

    printf("Cleaned up a child\n");
}

So, as described in the accepted answer, closing the pipe immediately was causing our child to exit with a SIGPIPE before the SIGINT was being handled.  We just moved the close(pipefd) to the SIGCHLD handler and it works now.

A: You don't show enough of your code to know what is going on.  You should always try to construct an SSCCE and post that if you want people to be able to comment on your program.
Best guess: your parent exits after sending the signal, closing the read end of the pipe.  This causes the client to immediately exit with a SIGPIPE, before it gets a chance to handle the SIGINT.  Try doing your cleanup on SIGPIPE as well, or ignore SIGPIPE.


text:
Q: File path php , unlink method I am trying to delete pictures from a file with the unlink method.
I couldent make the unlick method work with a relativ path so I tried it with an absolute one.
Here is the code:
echo '	',
"<form method=post>
 <input type=submit name=delete value=Supprimer>
 </form>	";

 $filepath='\images\ '.$tableau[$i].'';
 $path=dirname(__FILE__) . $filepath ;

 echo $path;

if(isset($_POST['delete']))
{
  unlink ($path);
}

But this codes gives:
D:\logiciels\XAMPP\htdocs\upload-test\images\ 1.jpg
Warning: unlink(D:\logiciels\XAMPP\htdocs\upload-test\images\ 1.jpg):   No  such file or directory in D:\logiciels\XAMPP\htdocs\upload-test\test.php on line 62

Why is it comparing with the test.php file path when I put an absolute one?
Then I tried something more simple: just looking if the file exists:
<?php
     $filepath='\images\ 1.jpg';
     $filename=dirname(__FILE__) . $filepath ;

     echo $filename;

     if (is_file($filename)) {

       echo 'File exists';

     } else {
       echo 'File does not exist';
      }
      ?>

And I get this:
D:\logiciels\XAMPP\htdocs\upload-test\images\ 1.jpg File does not exist

But the file really exists and I can execute it in Windows with the same path.
So I can't get whats the problem!
Thanks in advance for your help.

A: Try by removing space like
<?php
     $filepath='\images\1.jpg';
     $filename=dirname(__FILE__) . $filepath ;

     echo $filename;

     if (is_file($filename)) {

       echo 'File exists';

     } else {
       echo 'File does not exist';
      }
      ?>

A: Now here we are:
if (is_file($path)) {

   echo 'File exists';

} else {
   echo 'File does not exist';
  }

  echo '';

And I get a broken link with no Image display beside "File exists"


text:
Q: Column Selection - AgGrid Community I am using AgGrid community version with React. I am trying to present a checkbox on each column in the header. Which on selection should highlight the cells under that column selected.
Moreover, I need to record the change on the columns selected.
My columnDefs are an array of following object built based on data from back-end
{headerName: 'Name Of Header', headerCheckboxSelection: true, field: field }

Output

Problem
Below is the picture, when I click on any of the column checkbox it does two things

*

*Selects other column header checkboxes

*Selects all the rows
Whereas I need to do the following

*

*Marking only the checkbox that the user checks

*Highlighting only the columns under that column

*Handle the checkbox selection event
Any pointers?

A: As far as I know, there is no API for column selection, in the same way as row selection, but you are able to use rangeSelection method
here is an interface:
interface AddCellRangeParams {
    // start row
    rowStartIndex?: number;
    rowStartPinned?: string; // either 'top', 'bottom' or undefined

    // end row
    rowEndIndex?: number;
    rowEndPinned?: string; // either 'top', 'bottom' or undefined

    // columns
    columnStart?: string | Column;
    columnEnd?: string | Column;
    columns?: (string | Column)[];
}

a possible scenario based on your task
this.gridApi.addCellRange({
  rowStartIndex: 0,
  rowEndIndex: this.rowData.length-1,
  columnStart: "col_3",
  columnEnd: "col_3"
});

working Demo
P.S. Not sure about tracking headerCheckboxSelection property event, but seems you have to create own headerComponent and track checkbox event by yourself (and I suppose it's even better to keep everything under your control)


text:
Q: Laravel default email verification layout? How can I change Laravel default email verification layout

A: This verification email has several parts which are found in different locations.
The email's subject and message can be changed here \vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail.php. Look for this function
public function toMail($notifiable)
{
    $verificationUrl = $this->verificationUrl($notifiable);

    if (static::$toMailCallback) {
        return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
    }

    return (new MailMessage)
        ->subject(Lang::get('Verify Email Address'))
        ->line(Lang::get('Please click the button below to verify your email address.'))
        ->action(Lang::get('Verify Email Address'), $verificationUrl)
        ->line(Lang::get('If you did not create an account, no further action is required.'));
}

The email template is here vendor\laravel\framework\src\Illuminate\Notifications\resources\views\email.blade.php
The views and other styling information including the css can be found here \vendor\laravel\framework\src\Illuminate\Mail\resources\views\

A: Email layout
You can use this artisan command to publish the vendor email templates (the layout of the emails):
php artisan vendor:publish --tag=laravel-mail

A copy of the email templates will now be located in resources/views/vendor/mail and can be customized by you.
Laravel will use these published templates instead of the ones from the Laravel framework vendor code.

References:

*

*https://laravel.com/docs/5.8/mail#view-data

A: Layout for verification email is located in resources/views/auth/verify.blade.php. You can change it there directly.
If you want to use completely different view for your verification, you can override the show() method inside the VerificationController. All you need to do is add this method on top of that controller:
public function show(Request $request)
    {
        return $request->user()->hasVerifiedEmail()
                        ? redirect($this->redirectPath())
                        : view('your.view');
    }

A: You can publish view files by running this command
php artisan vendor:publish --tag=laravel-notifications

Then edit blade file in resources/views/vendor/notification
For more information about customizing email template visit this link
How to Customize the Templates

A: you should run this
php artisan vendor:publish --tag=laravel-notifications


text:
Q: Determining whether two known vectors are coplanar in a certain plane orthogonal to an unknown vector. Suppose you have some vector $a$ in $\Bbb{R}^n$. Let $H$ be the hyperplane such that $\Bbb{R}^n=\operatorname{span}\{a\}\oplus H$, so that every vector orthogonal to $a$ lies on this plane.
What is the equation of this plane? Edit: the equation of the plane is in fact trivial. However, I am actually interested in determining whether two vectors lie in this plane - see below.
This came up for me when I gave a (I now believe mistaken) answer on this site, which I have now removed, that stated:
$$a_1\frac{1}{9}+a_2\frac{1}{15}+a_3\frac{1}{21}+\cdots+a_n\frac{1}{6n+3}\neq a_1\frac{1}{5}+a_2\frac{1}{7}+a_3\frac{1}{9}+\cdots+a_n\frac{1}{2n+3}$$
And my rationale at the time was that, considering dot products between $a$ and the vectors formed by the LHS and RHS coefficients (the LHS being clearly smaller in magnitude) could not be the same, but I realised I couldn't prove it and so I removed my answer. This lead me to the thought: if you know $a\cdot b=a\cdot c$, where $b,c$ are known, can you derive $a$? And then I thought, we know $a\cdot(b-c)=0$, and in the question I could actually find another pair such that $a\cdot(d-e)=0$, with again $d,e$ being known, and I pictured the plane around $a$ of all vectors orthogonal to it, looking for a geometric intuition, being frustrated that even though I knew $b-c$ and $d-e$, I could not show that it was impossible for them both to lie on this plane, $H$ - which has now led me to this question. In sum, if $b,c,d,e$ are all known and $a$ is unknown, can you derive $a$ or show the non-existence of $a$ from $a\cdot(b-c)=a\cdot(d-e)=0$? I felt as if being able to find an equation to the plane $H$ would be useful in this, but I couldn't begin to solve this. Edit: again, the plane equation is trivial, but it doesn't immediately help me to determine if $b-c$ and $d-e$ can both lie on this plane.
The original question I was working on is here.

A: If $b = c$ then information gathered from $c$ does not add anything to information gathered from $b,$ so we should exclude that case.
If $b$ and $c$ are parallel and unequal then it is not possible that
$a \cdot b = a \cdot c,$ so we should exclude that case also.
So let's assume $b$ and $c$ are two independent vectors. Neither is a scalar product of the other. This implies that $n \geq 2$ since you cannot have two independent vectors in a one- or zero-dimensional vector space.
Given the known vectors $b$ and $c$ in $\mathbb R^n$ and any scalar constant $m$,
if you know that $a \cdot b = m$ then you know a hyperplane of dimension
$n - 1$ in which $a$ must lie.
Likewise, if you know that $a \cdot c = m$ then you again know a hyperplane
of dimension $n - 1$ in which $a$ must lie.
Since the vectors $b$ and $c$ are independent the hyperplanes are not parallel;
they intersect.
In the case $n = 2$ the hyperplanes are lines and they intersect in a single point, so you know $a.$
But if $n > 2$ the intersection of the hyperplanes has at least one dimension,
and there are infinitely many possible vectors that could be the vector $a.$
If you know that $a \cdot b = a \cdot c$ but do not know what the value of either product is, things are even worse.
Suppose $a = a_1$ is a solution to the system $a \cdot b = a \cdot c = 1.$
Then $a = 2a_1$ is a solution to the system $a \cdot b = a \cdot c = 2.$
But obviously $a = a_1$ is not a solution to $a \cdot b = a \cdot c = 2.$
So without knowing which real number $a \cdot b$ is equal to,
you cannot decide whether $a_1$ is a possible value of $a$ and $2a_1$ is not,
or whether $2a_1$ is a possible value of $a$ and $a_1$ is not.
Moreover, there are an infinite number of other possible values of $a \cdot b,$
each giving a different candidate for $a$ that is incompatible with any of the
results for any other value of $a \cdot b.$

As pointed out previously in a comment, however, if you know the values
of each of the products
$a \cdot b_1,$ $a \cdot b_2, \ldots,$ $a \cdot b_n$
for a linearly independent set of vectors
$b_1, \ldots, b_n,$
then you have enough information to identify the vector $a.$
This is essentially a way of using $n$ coordinates
(not necessarily rectangular or equal-scaled) to uniquely describe
every vector in the vector space $\mathbb R^n.$

A: The equation is
$$\sum_{i=1}^n a_ix_i=0$$
aka all vectors $x$ whose inner product with $a$ is $0$.


text:
Q: How do I make a heart beat with 3.JS and Leap Motion? So I have a scene with my 3D model of a heart which I have imported from Blender.
I have hooked it up with a Leap Motion so that we can move and rotate the heart model.
I want to be able to make the heart grow and shrink (to simulate a beating heart) and to play a beating heart sound effect, but only when someone is interacting with the Leap.
I am new to 3.JS and have no idea where to start.
Can someone help?

A: I'm fairly new to THREE JS but was working on a similar project in the recent past. To make the heart grow and shrink, I would invoke the Scale tool within the Animation loop of THREE.js :
        count = 0

        function render() {

        if (count < 21){
            heart.scale.x += 0.01
            heart.scale.y += 0.01
            heart.scale.z += 0.01
            count += 1
            }
        if ((count > 20) && (count < 40)) {
            heart.scale.x = cube.scale.x - 0.01
            heart.scale.y = cube.scale.x - 0.01
            heart.scale.z = cube.scale.x - 0.01
            count += 1
            } else if (count == 40){ count = 0}

        renderer.render( scene, camera );

        }

You could also use Tween JS for a more clinical and realistic heartbeat function.
for Sound, take a look at this example : http://threejs.org/examples/#misc_sound
for setup with your LeapMotion, I would imagine that you would have a conditional that triggers the animation loop when receiving input and triggering the beating heart and sound loop. Syncing the animation and sound loop should be straightforward.
Hope this helps.


text:
Q: How to prevent a URL in an email I send from being auto-linked by the recipient's email client? When I type a URL into an email in Outlook, it automatically converts it to a hyperlink.  I can, of course, remove the hyperlink from the context menu:

But, then when the email is received and when I view it in my Sent Items folder, the urls are again converted to hyperlinks.  How can I prevent this?  Embedded images are no good because the URL must be copy and pasteable (among numerous other reasons that this approach is not great).  And it must retain the formatting applied when I send it.
This answer on stackoverflow shows a good trick for preventing auto linked urls when sending an email programmatically, but I'm looking for a way to do this from the UI.  Perhaps there a way to edit the HTML of the message before it is sent?
If not, I guess I'm off to write an Outlook Add-in.

A: You can't prevent this (without somehow breaking the URL), because it's the recipient's client that displays the URL as a clickable link.

A: You can edit the HTML of the link before you send it. Just click the Edit Hyperlink... showed in your image there and then add the <z></z> tag within the hyperlink, as outlined in the SO answer you showed.

This has the advantage of showing up like a link, but attempting to click it does nothing.  However, you are not prevented from selecting it to copy/paste.

The z isn't necessary; any invalid HTML tag will do.  You could replace the whole link with something invalid, but then it would still try to open it in a browser.  For some reason, having the invalid tag in the middle prevents it from even trying to open it even though it still knows it's a hyperlink.

A: I've found that inserting a zero-width space in the URL works pretty well. For example, after the slashes and dots.
It prevents e-mail clients from formatting the text as links, but leaves the text copyable. See the difference:

*

*http://google.com/

*http://google.com/

It can be entered in Unicode as U+200B. For example on Ubuntu you can hit ctrl+shift+u then type 200b and space to enter it anywhere.
At first I thought this would break eventually, namely after pasting into the browser. But in Chromium the pasted link worked just fine (although the link was broken when the ZWSP was anywhere inside the http://). Even pasting a directory to Bash worked. Both the browser and the shell just ignored these zero-width characters.
Beware, that it probably will break something. For example, if pasted into a source code editor – you could end up with nasty bugs in your programs.


text:
Q: How to create an Access database at runtime in C#? How can I create an Access Database at runtime in C#?

A: Create a blank access database and store it in your resource files.
Now whenever you want to use it, fetch that database from your resources and copy it to wherever you want, rename it to whatever you want and execute your database setup script to create default tables and load values in them.

A: This article from John Russell Plant explains how you'd do it in specific detail with code samples. There are three steps:

*

*Create the catalog.

*Create the tables.

*Release the relevant COM objects.

A: Try:
using ADOX; //Requires Microsoft ADO Ext. 2.8 for DDL and Security
using ADODB;

public bool CreateNewAccessDatabase(string fileName)
{
  bool result = false;

  ADOX.Catalog cat = new ADOX.Catalog();
  ADOX.Table table = new ADOX.Table();

  //Create the table and it's fields.
  table.Name = "Table1";
  table.Columns.Append("Field1");
  table.Columns.Append("Field2");

  try
  {
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5");
    cat.Tables.Append(table);

    //Now Close the database
    ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
    if (con != null)
    con.Close();

    result = true;
  }
  catch (Exception ex)
  {
    result = false;
  }
  cat = null;
  return result;
}

http://zamirsblog.blogspot.com/2010/11/creating-access-database.html

A: The first thing you need to do is get a COM reference to the Microsoft ADO Ext. X.X for DDL and Security. The X.X represents whatever version you happen to have on your machine. Mine used to be version 2.7, but with Visual Studio 2008, it was updated to 6.0.
alt text http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/AddReference_2.png
Once you have added the reference, ADOX will be added to the using section of your code.
alt text http://blog.jrpsoftware.com/content/binary/WindowsLiveWriter/CreateanAccessDatabaseinC_10DDD/Using_2.png
Next you will want to create the catalog for the database. Insert the filename you wish into the following string and pass it to the CatalogClass.
CatalogClass cat = new CatalogClass();
string tmpStr;
string filename = "Sample.MDB";
tmpStr = "Provider=Microsoft.Jet.OLEDB.4.0;";
tmpStr += "Data Source=" + filename + ";Jet OLEDB:Engine Type=5";
cat.Create(tmpStr);

The next step is to create the table and columns for your database. This is a pretty straight forward operation as shown in the example below.
 Table nTable = new Table();
 nTable.Name = "PersonData";
 nTable.Columns.Append("LastName", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("FirstName", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("Address 1", DataTypeEnum.adVarWChar, 45);
 nTable.Columns.Append("Address 2", DataTypeEnum.adVarWChar, 45);
 nTable.Columns.Append("City", DataTypeEnum.adVarWChar, 25);
 nTable.Columns.Append("State", DataTypeEnum.adVarWChar, 2);
 nTable.Columns.Append("Zip", DataTypeEnum.adVarWChar, 9);
 cat.Tables.Append(nTable);

The final step is very important or you will get error when you close your application. Once the all the tables and columns have been added, you will need to release the com objects properly and in the proper order.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(nTable);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.Tables);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);

That is it. You should now have a Access Database that you can write to. Hope this helps.
Reference: John Russell Plant - Create an Access Database in C#

A: static void IF_EXISTS_DELETE_AND_CREATE(string cn)
{
    //cn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source =";
    //cn += AppDomain.CurrentDomain.BaseDirectory.ToString() + "test.mdb";
    try
    {
        OleDbConnection connection = new OleDbConnection(cn);
        object[] objArrRestrict;
        objArrRestrict = new object[] { null, null, null, "TABLE" };
        connection.Open();
        DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, objArrRestrict);
        connection.Close();
        string[] list;
        if(schemaTable.Rows.Count > 0)
        {
            list = new string[schemaTable.Rows.Count];
            int i = 0;
            foreach (DataRow row in schemaTable.Rows)
            {
                list[i++] = row["TABLE_NAME"].ToString();
            }
            for ( i = 0; i < list.Length; i++)
            {
                if(list[i] == "TEMP")
                {
                    string deletedl = "DROP TABLE TEMP";
                    using (OleDbConnection conn = new OleDbConnection(cn))
                    {
                        using (OleDbCommand cmd = new OleDbCommand(deletedl, conn))
                        {

                            conn.Open();
                            cmd.ExecuteNonQuery();
                            conn.Close();
                        }
                    }
                    break;
                }
            }
        }
        string ddl = "CREATE TABLE TEMP (USERID INTEGER NOT NULL,[ADATE] TEXT(20), [ATIME] TEXT(20))";
        using(OleDbConnection conn = new OleDbConnection(cn))
        {
            using(OleDbCommand cmd = new OleDbCommand(ddl, conn))
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    catch (System.Exception e)
    {
        string ex = e.Message;
    }
}