text:
Q: How to display different color depending on temperature? I am receiving data from an XML with info about the weather from some locations. I am fetching info about the temperature, which I want to display like this:

If the temperature is above 13, the numbers shall be displayed in red

If the temperature is between or equal to 0 and 12, the numbers shall be displayed in white

If the temperature is lower than 0, the numbers shall be displayed in blue

I have currently tried this:
 if ($result[0]['temperature'] > 13){
    $temperature = "". $result[0]['temperature']. "°"."";
  }
  if ($result[0]['temperature'] >=0 && $result[0]['temperature'] <=12){
    $temperature = "". $result[0]['temperature']. "°"."";
  }
  if ($result[0]['temperature'] < 0){
    $temperature = "". $result[0]['temperature']. "°"."";
  }

This code^ works but soon gets very long and "unclear". This $temperature is only one temperature and when I want to show 7 temperatures (one for each day in a week) and for multiple locations, I soon get very many ´$temperature n` variables and lines. Example: one temperature like I have shown is 9 lines of code. When I want to show it for 7 days and 3 locations it's 9x7*3 = 189 lines + spacing, you get the idea.
Maybe the best is to have this code in another file and just refer to it?
For info:
The XML shows temperatures for each 6 hours (0-6, 6-12, 6-18, 18-24) this means I fetch $result[0],[4],[8],[12] to get for each day.

A: Make an array of breakpoints, and assign the color based on the breakpoint:
function getColor($temp) {
  $defaultColor = 'blue';
  $breakPoints = [
    '0' => 'white',
    '13' => 'red',
    ];

  $out = $defaultColor;
  foreach($breakPoints as $target => $color) {
      if ( (float)$target <= (float)$temp) {
          $out = $color;
      }
  }
  return $out;
}

Since we set up the breakpoints in ascending order, we set the default color to be the color for negative values.  Then, as we iterate through the breakpoints, keep changing the color until the breakpoint is greater than the temperature being tested.
Note that putting this in a function allows it to be used throughout your script:
<?php
// do all your php stuff, including the getColor function
?>

<?php foreach($result as $row): ?>

The temperature is
    <span style="color:<?= getColor($row['temperature']) ?>">
      <?= $row['temperature'] ?> °

<?php endforeach; ?>

A: You can try creating an array with each locations containing an array with all the temperatures. When you iterate through the array you can do use the switch statement to check for each temperature result so that you don't have 100 if statements.

A: use an array to set the lower and upper limits for color white, and foreach() to construct the correct HTML. This way you can accommodate for any number of array entries (temperatures).
<?php
$limits = [0, 12]; // below 0 = blue, between 0 and 12 = white, above 12 = red
$result = [
    ['temperature' => -3,], ['temperature' => 9,], ['temperature' => 13,], ['temperature' => 6,],
    ['temperature' => -5,], ['temperature' => 11,], ['temperature' => 17,], ['temperature' => 4,],
];

$tempHtml = []; // store for HTML
foreach ($result as $key => $value) {
    $temp = $value['temperature'];
    $color = 'white'; // default
    if ($temp > $limits[1]) {
        $color = '#FD1B1C'; // red
    } elseif ($temp < $limits[0]) {
        $color = 'blue';
    }
    $tempHtml[] = "" . $value['temperature'] . "°" . "";
}

echo '
';
var_dump($tempHtml);
echo '
';

Output:
array (size=8)
  0 => string '-3°' (length=36)
  1 => string '9°' (length=36)
  2 => string '13°' (length=39)
  3 => string '6°' (length=36)
  4 => string '-5°' (length=36)
  5 => string '11°' (length=37)
  6 => string '17°' (length=39)
  7 => string '4°' (length=36)

Note: if you need to target elements [0], [4], [8]... wrap the logic inside the foreach in a modulo condition:
foreach ($result as $key => $value) {
    if($key %4 === 0) {
      ...
    }


text:
Q: How can I fix 'No space left on device' error in Docker? I'm running a Mac-native Docker (no virtualbox/docker-machine).
I have a huge image with a lot of infrastructure in it (Postgres, etc.).
I have run cleanup scripts to get rid of a lot of cruft--unused images and so forth.
When I run my image I get an error like:
could not create directory "/var/lib/postgresql/data/pg_xlog": No space left on device

On my host Mac /var is sitting at 60% space available and generally my disk has lots of storage free.
Is this some Docker configuration I need to bump up to give it more resources?
Relevant lines from mount inside docker:
none on / type aufs (rw,relatime,si=5b19fc7476f7db86,dio,dirperm1)
/dev/vda1 on /data type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /etc/resolv.conf type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /etc/hostname type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /etc/hosts type ext4 (rw,relatime,data=ordered)
/dev/vda1 on /var/lib/postgresql/data type ext4 (rw,relatime,data=ordered)

Here's df:
[11:14]
Filesystem     1K-blocks    Used Available Use% Mounted on
none           202054928 4333016 187269304   3% /
tmpfs            1022788       0   1022788   0% /dev
tmpfs            1022788       0   1022788   0% /sys/fs/cgroup
/dev/vda1      202054928 4333016 187269304   3% /data
shm                65536       4     65532   1% /dev/shm
tmpfs             204560     284    204276   1% /run/docker.sock

A: I ran into this recently on with a docker installation on linux that uses the devicemapper storage driver (default). There was indeed a docker configuration I needed to change to fix this.
Docker images are made of read-only layers of filesystem snapshots, each layer created by a command in your Dockerfile, which are built on top of a common base storage snapshot. The base snapshot is shared by all your images and has a file system with a default size of 10GB. When you run your image you get a new writable layer on top of all the layers in the image, so you can add new files in your running container but it's still eventually based on the same base snapshot with the 10GB filesystem. This is at least true for devicemapper, not sure about other drivers. Here is the relevant documentation from docker.
To change this default value to something else, there's a daemon parameter you can set, e.g. docker daemon --storage-opt dm.basesize=100G. Since you probably don't run the daemon manually need to edit the docker daemon options in some file, depending on how you run the docker daemon. With docker for mac you can edit the daemon parameters as JSON in the preferences under Daemon->Advanced. You probably need to add something like this:
{
    "storage-opts": ["dm.basesize=100G"]
}

(but like I said, I had this problem on linux, so didn't try the above).
Anyway in order for this to take effect, you'll need to remove all your existing images (so that they're re-created on top of the new base snapshot with the new size). See storage driver options.

A: I haven't found many options for this, the main issue in github is https://github.com/docker/for-mac/issues/371
Some of the options suggested there are:

*

*If you can remove all images/containers, you can follow these instructions:

docker rm $(docker ps -a -q)
docker rmi $(docker images -q)
docker volume rm $(docker volume ls |awk '{print $2}')
rm -rf ~/Library/Containers/com.docker.docker/Data/*

*

*You can try to prune all unused images/containers but this has proven not very effective:

docker system prune

*

*Use a template image that is larger, install qemu using homebrew and move the image around, see this specific comment: https://github.com/docker/for-mac/issues/371#issuecomment-242047368 but you need to have at least 2x of space left to do this without losing containers/images.

See also: How do you get around the size limitation of Docker.qcow2 in the Docker for Mac?
And https://forums.docker.com/t/no-space-left-on-device-error/10894/26

A: I ran into the same issue, running docker system prune --volumes resolved the problem.
"Volumes are not pruned by default, and you must specify the --volumes flag for docker system prune to prune volumes."
See: https://docs.docker.com/config/pruning/#prune-everything

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare jQuery Arrays with multiple DOM elements Consider this:

one

two

They all print false although they contain the same elements. One would think that .is() would work for comparing but it doesnt. How would you compare two jQuery objects?

A: We can use .not()
var i1 = $('.test');
var i2 = $('.test');
alert(i1.not(i2).get().length == 0); //alerts true

A: i1 and i2 are not equal because they are different objects.
Sounds like what you're wanting is to find out if the elements in both the jQuery objects are the same elements.
You'd have to iterate over the numeric contents of both these objects and compare them instead.
For instance, something like:
for (var i = i1.length; i--;) {
  if (!i2[i] || i2[i] !== i1[i]) {
    // jquery objects don't contain same elements
  }
}

A: i1 and i2 are distinct objects created by the jQuery constructor. The elements inside you can compare if you wish.
i1[0] == i2[0].
You can create a function to iterate through the entire element to compare and make sure the elements match up.
You could also do .is('.test') but you'd always have to specify the selector.

A: They aren't the exact same. You're comparing the same element, but they are different nonetheless.
The .is() call must also fail, because element i1 does not match i2. You could use .is() to check for the class name for instance:
i1.is('.text') === true

update
because of your comment, http://www.jsfiddle.net/htcxT/
You are maybe even looking for the .unique() jQuery method, which which removes duplicated DOM elements from an array: .unique()


text:
Q: converting python program into windows executable using pyinstaller I am not able to convert following python code into windows executable using pyinstaller. Python code is working fine with python 2.7 and python 3.6. I have installed pyinstaller from github/pyinstaller/pyinstaller/archive/develop.tae.gz
import cv2
import os
import inspect
import os.path

filename = inspect.getframeinfo(inspect.currentframe()).filename
path     = os.path.dirname(os.path.abspath(filename))

os.chdir(path)
id = open('Emp.txt', 'r').read()
writePath = "./Images/"

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
cam = cv2.VideoCapture(0)

sampleNum = 0

while(True):
    # Capture frame by frame
    ret, frame = cam.read()
    #frame = np.full((100,80,3), 12, dtype = np.uint8)
    grayFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(grayFrame,scaleFactor=1.5, minNeighbors=5)
    for (x,y,w,h) in faces:
        sampleNum = sampleNum + 1
        cv2.imwrite(writePath + str(id) + "." +str(sampleNum) + ".jpg", grayFrame[y:y+h,x:x+w])

        color = (255,0,0)
        thickness = 2
        cv2.rectangle(frame,(x,y),(x+w, y+h),color, thickness)
    cv2.imshow ("frame",frame)
    cv2.waitKey(2)
    if (sampleNum > 5):
        break

cam.release()
cv2.destroyAllWindows()


text:
Q: Python Pandas DataFrame Merge: Strange Sort Order for How = Inner I do not understand the sort order for Python Pandas DataFrame merge function with how="inner". Example:
import pandas as pd

df2 = pd.DataFrame({'a': (6, 7, 8, 6), 'b': ("w", "x", "y", "z")})
print(df2)
print("left:")
dfMerge2 = pd.merge(df2, df2, on='a', how="left")
print(dfMerge2)
dfMerge = pd.merge(df2, df2, on='a', how="inner")
print("inner:")
print(dfMerge)

Result:
   a  b
0  6  w
1  7  x
2  8  y
3  6  z
left:
   a b_x b_y
0  6   w   w
1  6   w   z
2  7   x   x
3  8   y   y
4  6   z   w
5  6   z   z
inner:
   a b_x b_y
0  6   w   w
1  6   w   z
2  6   z   w
3  6   z   z
4  7   x   x
5  8   y   y

I would expect that for how="inner" the order of the resulting rows with
6   z   w and
6   z   z
would be the same as with how="left", as the documentation https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html says:

*

*left: use only keys from left frame, similar to a SQL left outer join; preserve key order

*inner: use intersection of keys from both frames, similar to a SQL inner join; preserve the order of the left keys


text:
Q: How do I add another function to the bot? I'm trying to add an 8ball function to my Discord bot, but when I tried to run the code, it said there was an Unexpected token ",". When I removed the comma, it then said there was an Unexpected token function. Here are the functions:
bot.on('message', function (user, userID, channelID, message, evt), function (doMagic8BallVoodoo)) {
    var rand = ['Yes', 'No', 'No, eat a dick.', 'YAS!', 'Ask again later.', 'shlap shlap shlap', 'Get mega memed, bitch.'];

And here is the 8ball command:
case '8ball':
    bot.sendMessage({
    to: channelID
    message: 'Flat Earth says:' + (doMagic8Ballvoodoo)));
    });

edit: I've done some changes to the code. I'm able to run the script now, but the bot responds to every command except the 8ball one. Here's all the commands:
            case 'flatearth':
                bot.sendMessage({
                    to: channelID,
                    message: 'The earth is flat.'
                });
            break;
            case 'roundearth':
                bot.sendMessage({
                    to: channelID,
                    message: 'You fool. You absolute buffoon. The earth is flat, you fucking plebeian.'
                });
                break;
            case '8ball':
}

function doMagic8BallVoodoo() {
    var rand = ['Yes', 'No', 'No, eat a dick.', 'YAS!', 'Ask again later.', 'shlap shlap shlap', 'Get mega memed, bitch.'];

    return rand[Math.floor(Math.random()*rand.length)];
}
                };
         })

Edit 2: I've modified the 8ball code, this is what it looks like:
            case '8ball':
                bot.sendMessage({
                    to: channelID,
                    message: 'Flat Earth says:' (doMagic8Ballvoodoo())
}

function doMagic8BallVoodoo() {
    var rand = ['Yes', 'No', 'No, eat a dick.', 'YAS!', 'Ask again later.', 'shlap shlap shlap', 'Get mega memed, bitch.'];

    return rand[Math.floor(Math.random()*rand.length)];
            });
            break;
}
                };
         })

I know I'm doing something wrong, as I keep getting syntax errors (When I put this 8ball code into an editor, it says "Unexpected token )" on what would be line 11 in this section of code). I'm also uncertain about the placement of the 8ball function, should I have kept it with the other function or before the 8ball command or...?

A: Your issues are at lines 47 and 48. You need a comma at the end of line 47 and you need to remove the two end parens and semicolon from the end of line 48. You seem to also have one too many end parens near the end of line 20 as well.


text:
Q: Delete all files created till yesterday in directory (but not directory) - one liner solution How can I delete all older files created till yesterday in directory (but not directory)?
I tried with this but unable to get delete files exists till yesterday.
for(File file: new File(strFile).listFiles())
      if (!file.isDirectory() && file.lastModified() < 1.0)
         file.delete();

A: First lastModified returns:

A long value representing the time the file was last modified,
  measured in milliseconds since the epoch (00:00:00 GMT, January 1,
  1970), or 0L if the file does not exist or if an I/O error occurs

You need to get current time in milliseconds then subtract what last modified returns and the verify if it was modified before your target period. Or perform the time calculation in any type you desire.
Following your code:
    long day = 1000 * 60 * 60 * 24;
    long now = System.currentTimeMillis();
    for(File file: new File(DIRECTORY).listFiles())
          if (!file.isDirectory() && (now - file.lastModified() > day))
             file.delete();

Ideally you would be running this as an scheduled task

A: here is an example which deletes all temp files more than a day old:
import org.apache.commons.lang3.Validate;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

public class StackOverflow44850006 {
  /**
   * deletes all the files in a directory modified before a given timestamp
   *
   * @param directoryPath path to delete from
   * @param stamp         everything with a mod date before this timestamp will  be deleted
   * @return the number of items deleted
   */
  public static long deleteOld(final String directoryPath, final Date stamp) {
    final File[] files = new File(directoryPath).listFiles();
    Validate.notNull(files, "Unable to open dir. Does it exist?");
    return Arrays.stream(files)
        .filter(f -> !f.isDirectory())
        .filter(f -> f.lastModified() < stamp.getTime())
        .map(File::delete)
        .filter(Boolean::booleanValue)
        .count();
  }

  public static void main(String[] args) {
    final String tempDir = System.getProperty("java.io.tmpdir");
    final Calendar yesterday = Calendar.getInstance();
    yesterday.add(Calendar.DATE, -1);
    System.out.println(deleteOld(tempDir, yesterday.getTime()));
  }
}


text:
Q: FileHandler double logs string in a file import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')

for handler in logger.handlers:
    handler.close()

logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')

I am trying to understand why the above code logs B! string in logloglog.log file twice. It confuses me, since I log both A! and B! only one time. Can you help me?

A: logger.addHandler was called twice, so there are two file handlers (pointing at the same filename):
>>> logger.handlers
[<FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>,
 <FileHandler /home/wglenn/git/modules/logloglog.log (NOTSET)>]

By the time logger.critical('B!') is called, each handler will write out the event once.
It does not matter that you've closed handlers earlier, logging will just re-open the resource when it needs to emit, if necessary.

A: When a new log message arrives the file handler will automatically reopen the file.
so
for handler in logger.handlers:
    handler.close()
    logger.removeHandler(handler) // add this line.

see the ref.


text:
Q: I am using a comet server and I want it to interact with C++ I am using persevere for an application I am writing that controls remote hardwere.
Persevere is written in Java and doesn't supply an alternative API.
I am using a web-based GUI as the control panel. So far, so good.
I can get and set data using REST channels like dojo does but the problem is that I don't really know how to use REST channels. Which library should I use to do so?

A: If you use gcc as your toolchain you can embed a JVM with GCJ to run persevere inside your application. GCJ makes it easy to call C++ from Java with it's CNI interface (much easier than JNI). I used that method to use Java scripting inside our C++ application. You can even compile the persevere jar into a native library and link it to your app with GCJ.
The best reference is the GCJ Documentation.
There is also a Linux Journal contains the article Embedded Java with GCJ that you can read.
You can also study applications that use gcj.


text:
Q: Share / repin button on pinterest developing an app, and I was wondering if someone on here could give me some general information about what this thing from the pinterest app on both android and ios is called and where i can find out more information about how to create a more basic one etc... it is where you press down and hold on a picture and 3 buttons come up in a fan sort of pattern. here is a pic
thanks a bunch! Any info to start learning would be great!

A: It is called an 'ArcMenu' and one Android implementation can be found here:
https://github.com/daCapricorn/ArcMenu

Credit to 'Capricorn' for the GitHub library


text:
Q: Java String to enum I have this class constructor AppData(Map params, Operations operation)
where Operations is
public enum Operations
{
create,update,delete,view,compare
}

How can I instantiate AppData with parameters constructor?
for the map parameter its fine i get that from servlet, (req.getParameterMap())
but the main problem for me is knowing the operation type, which also comes from the map parameter, So in order to do this AppData data=new AppData(req.getParameterMap(),op); what shall I assign to op or what shall an op type be?
Note: I can get the String create , update ... from req.getParameterMap() by using iterator and Map.Entry object.getKey() and Value

A: Assuming you're starting with a string (e.g., "update"), you can use Enum.valueOf. Your Operations enum will inherit a form of that, so:
Operations op = Operations.valueOf(theString);

...or use the one from Enum, though you'd really only have to do this if you don't have direct, compile-time access to Operations. I think you do have compile-time access, so use the above. But for completeness:
Object op = Enum.valueOf(Class.forName("Operations"), theString);


text:
Q: I found two groups in Slackware 14, named nogroup and nobody. Why? I wonder why in my Slackware 14 (32 bit) distribution there are two groups named "nobody" and "nogroup":
bash-4.2$ cat /etc/passwd | grep nobody
nobody:x:99:99:nobody:/:/bin/false
bash-4.2$ cat /etc/group | grep nobody
nobody:x:98:nobody
bash-4.2$ cat /etc/group | grep nogroup
nogroup:x:99:
bash-4.2$ groups nobody
nobody : nogroup nobody
bash-4.2$

User "nobody" has "nogroup" as primary group.  So, what's the utility for "nobody" group with gid=98?
(In Debian "nobody" group doesn't exist).
Thank you


text:
Q: Weird output from console.log(res) NodeJS While using console.log on the response Obj from createServer, the output prints ServerResponse before printing the actual object data. I wonder what is so special about res, which causes this effect ???
...
http.createServer((req, res) => {
// Parsing and Logging endpoint on console.
const URL = url.parse(req.url, true).pathname;
console.log(res);
});
...

A: It's not special. res is an object, not a string. That's just how Node.js's console.log shows objects. For example:
class Example {
    constructor() {
        this.foo = "bar";
    }
}
console.log(new Example);

outputs:

Example { foo: 'bar' }

You're telling it to log a ServerResponse object, so it does, creating output similar to the above, just with a lot more properties.


text:
Q: Custom extension Admin grid not displaying When I try to load my custom grid view in the admin page, I got a blank page with the default admin layout loaded in instead of my grid. I tried many things but I can't find the bug.
My controller is implemented as follows:
<?php
class Brain2Terminal_CertWizard_Adminhtml_CertinfoController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction() {
        $this->loadLayout();
        $this->_setActiveMenu('sales/sales');
        $this->_addContent($this->getLayout()->createBlock('CertWizard/adminhtml_certinfo'));

        $this->renderLayout();
    }
}

Grid container:
<?php
class Brain2Terminal_CertWizard_Block_Adminhtml_Certinfo extends
Mage_Adminhtml_Block_Widget_Grid_Container
{
    public function __construct()
    {
        parent::__construct();
        $this->_controller = "adminhtml_certinfo";
        $this->_blockGroup = "CertWizard";
        $this->_headerText = Mage::helper ( 'flexibleforms' )->__ ( 'Manage Infos' );
        $this->_addButtonLabel = Mage::helper ( 'CertWizard' )->__ ( 'Add Info' );
    }

    protected function _prepareLayout()
    {
        $this->setChild( 'grid', $this->getLayout()->createBlock( $this->_blockGroup.'/' . $this->_controller . '_grid', $this->_controller . '.grid')->setSaveParametersInSession(true) );
        return parent::_prepareLayout();
    }
}

The Grid:
<?php
class Brain2Terminal_CertWizard_Block_Adminhtml_Certinfo_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    public function __construct()
    {
        parent::__construct();
        $this->setId("certinfoGrid");
        $this->setDefaultSort("id");
        $this->setDefaultDir("ASC");
        $this->setUseAjax(true);
        $this->setSaveParametersInSession(true);
    }

    protected function _prepareCollection()
    {
        $collection = Mage::getModel("CertWizard/certinfo")->getCollection();
        $this->setCollection($collection);
        return parent::_prepareCollection();
    }

    protected function _prepareColumns()
    {
        $this->addColumn("id", array(
            "header" => $this->__("ID"),
            "align" => "right",
            "width" => "30px",
            "type" => "number",
            "index" => "id",
        ));
        $this->addColumn("attributeset_id", array(
            "header" => $this->__("Attributeset"),
            "align" => "right",
            "width" => "50px",
            "type" => "varchar",
            "index" => "attributeset_id",
        ));
        $this->addColumn("info", array(
            "header" => $this->__("Info"),
            "align" => "right",
            "width" => "50px",
            "type" => "varchar",
            "index" => "info",
        ));

        return parent::_prepareColumns();
    }
}

If any more information is needed, please let me know.

So my layout.xml file looks like follows:
 <layout>
 <adminhtml_certinfo_index>
    <reference name="content">
        <block type="CertWizard/adminhtml_certinfo" name="certinfo" />
    </reference>
</adminhtml_certinfo_index>
</layout>

Like you said i added a node with prefixing adminhtml_ in addition i refer to the correct block. When i debug everything is fine and block is also called without problems. Certainly i'm getting no gridview. Why?
Once again I've debugged the part where the the controller loads the layout and put the method
        var_dump(Mage::getSingleton('core/layout')->getUpdate()->getHandles());
    die();

after loadLayout().
The result was
    array (size=4)
  0 => string 'default' (length=7)
  1 => string 'STORE_admin' (length=11)
  2 => string 'THEME_adminhtml_default_MAG100207_MobileStore/' (length=46)
  3 => string 'adminhtml_certinfo_index' (length=24)

But still I can't find the bug.

A: Initially, I read the question as saying that you didn't see anything on the screen.
If you see a completely blank screen:
In Magento, when a blank page is displayed with no error warning, it's typically symptomatic of a PHP error, usually related to improper syntax. I'd try uploading the files to an online PHP linter to ensure that the basic syntax is correct, and fix any errors.
If your grid is not showing, but the rest of the Magento admin layout is:
The issue is likely related to layout XML. You probably aren't assigning the blocks to the correct controller handle (remember that admin handles are usually all prefixed with adminhtml_*, like adminhtml_sales_order_view), or the container block doesn't have the grid block associated with it properly (usually done in the container's _prepareLayout() method), or some other layout-related issue. Maybe the grid container isn't assigned to the handle at all.
You're seeing the Magento admin layout, so the issue is more likely related to my second point. In your specific case, your _prepareLayout() method looks fine, so I'd look in the layout XML file next.


text:
Q: How do I split up a row array in GAS? I have an array which is in range E10:O10 and when I enter the following script:
var array1 = ss.getRange('E10:O10').getValues();
Logger.log(array1)
for (var i in array1)
{
panel.add(app.createLabel(array1), 10, 12);
//Can I do something with array1.length + '' in here to split the values?
}

The array comes up with commas between them. Is there any way to split them up and define the pixel width or do you need to use array1.length?

A: Arrays retrieved with getValues are two dimensions even when only one row is extracted. Something like:
var array1 = ss.getRange('E10:O10').getValues();
Logger.log(array1)
for (var i = 0; i < array1[0].length; i++ )
{
panel.add(app.createLabel(array1[0][i], 10, 12);
}


text:
Q: Radius of curvature for a strictly convex curve Suppose I have a strictly convex curve $\gamma$ parametrised by arc length $s$ in the plane. I take a point $s_{1}$ on $\gamma$ and issue a straight line from $s_{1}$ to another point $s_{2}$ on $\gamma$. Assume $s_{2} > s_{1}$. Let's denote the length of the line by $L$. Now $L = L(s_{1}, s_{2})$ as it depends on the points $s_{1}$ and $s_{2}$.
I  position a circle $C$ of radius $R$ on the midpoint of $L$ and choose $R$ such that the circle $C$ is $\textit{tangent}$ to $\gamma$ at some point $s_{0} \in (s_{1}, s_{2})$.
How do I obtain a expression for the radius $R$ in terms of $s$ and $L$?
Would appreciate any suggestions.

A: HINT: This will have to be the osculating circle of $\gamma$ at the point $\gamma(s_0)$, so the radius will be the reciprocal of the curvature, and the midpoint of $L$ will have to lie on the normal line at that point. It follows that that (at least usually) $\gamma(s_0)$ will be the point on $\gamma$ (between $\gamma(s_1)$ and $\gamma(s_2)$) closest to the midpoint of $L$.


text:
Q: convergence related to chordal metric Suppose that $\Omega$ is an open connected subset of $\mathbb{C}$ and $\{f_n:\Omega\to \mathbb{C}^*\}$ is a sequence of meromorphic functions on $\Omega$, where $\mathbb{C}^*$ is the extended complex plane endowed with the chordal metric and $\Omega$ endowed with the usual euclidean metric. Suppose that $f_n\to f$ uniformly on compact subsets of $\Omega$. Prove that $f$ is either meromorphic on $\Omega$ or identically $\infty$.
Let $\sigma(z,w)=\frac{2|z-w|}{\sqrt{1+|z|^2}\sqrt{1+|w|^2}}$ be the chordal metric on $\mathbb{C}^*$.
I think that the key point of the proof is the following claim:
Suppose that $f(z_0)\neq \infty$. We claim that there is a ball $B(z_0, \epsilon)$ and a constant $M$ such that $f_n$ is analytic in $B(z_0, \epsilon)$ and $|f_n(z)|\leq M$ for all $z\in B(z_0,\epsilon)$ and all $n$ sufficiently large.
Fix $\epsilon>0$, there exists $N>0$ such that $\sigma(f_n(z_0),f(z_0))<\epsilon$ for all $n>N$.
Since $\{f_n\}$ is a normal family, it is uniformly equicontinuous. Thus, there exists $\delta>0$ such that $\sigma(f_n(z),f_n(z_0))<\epsilon$ for all $n$ and all $z\in \overline{B(z_0,\delta)}$, and so
$$\sigma(f_n(z),f(z_0))\leq \sigma(f_n(z),f_n(z_0))+\sigma(f_n(z_0),f(z_0))<2\epsilon$$
for all $n$ sufficiently large. Now note that if $f_n(z)=\infty$ for some $z$ , then $\sigma(f_n(z),f(z_0))=2/\sqrt{1+|f(z_0)|^2}$. Therefore, if we choose $\epsilon < 1/\sqrt{1+|f(z_0)|^2}$, then $f_n(z)\neq \infty$ in $\overline{B(z_0,\delta)}$.
Since the chordal metric is equivalent to Euclidean metric on $\mathbb{C}$, we see that for all $n$ sufficiently large, and for all $z\in B(z_0, \delta)$, we have $|f_n(z)-f(z_0)|<\epsilon.$ In other words, there is a ball $B(z_0, \delta)$ and a constant $M$ such that $f_n$ is analytic in $B(z_0, \epsilon)$ and $|f_n(z)|\leq M$ for all $z\in B(z_0,\epsilon)$ and all $n$ sufficiently large.
Now, on this ball $B(z_0,\delta)$ we have $\{f_n\}$ analytic and $f_n\to f$ uniformly on compact subsets of $B(z_0,\delta)$ (with respect to Euclidean metric). Thus $f$ is analytic on $B(z_0,\delta)$.
Now my question is: is there anything wrong to my proof and is there a better way to prove this? Thanks


text:
Q: Create a public key to allow scp server to server My scenario is this, I am trying to SCP from server1 to server2 and and I need to create a public_key on server1 to allow server2 access to it. How do I do this?

A: the internet is full of answers to your question. On unix like machines, google for keyword. ssh-keygen, running that command for example as : ssh-keygen -t rsa on server 1 will give you two files id_rsa and id_rsa.pub. You save id_rsa into your $HOME/.ssh and you copy id_rsa.pub to server2:$HOME/.ssh/authorized_keys. Make sure the permission are 0600.
Nonetheless I did a quick google just to see what you would find on the topic and here is 1 which takes the case where your server 1 may be windows as well. : http://www.mtu.net/~engstrom/ssh-agent.php

A: *

*login server1 with the user, which will scp files.

*ssh-keygen -t rsa

*ssh-copy-id <user>@server2

*Test if you can ssh from server1 to @server2

*Done.


text:
Q: C# Reader value in Datatable columns I am new at C# and I would like to ask how is it possible to get a value of the reader (XML file) to a table column. I want the reader value to be a string. I tried to get the value to a listbox1 and it works, but that's not what I need. Thank you.
private void button1_Click(object sender, EventArgs e)
    {
        string file;
        OpenFileDialog ofd = new OpenFileDialog();
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) ;
        file= ofd.FileName;

        XmlTextReader reader = new XmlTextReader(file);
        XmlNodeType type;

        DataSet dsload = new DataSet();
        dsload.ReadXml(file);

        while (reader.Read())
        {
            if (reader.Name == "name")
            {
                reader.Read();
                listBox1.Items.Add(reader.Value);
                DataTable dt = new DataTable("MyTable");
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                data.DataSource = dsload.Tables[0];
            }

        }

A:   while (reader.Read())
        {
            if (reader.Name == "name")
            {
                reader.Read();
                listBox1.Items.Add(reader.Value);
            }
        }
 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("Name", typeof(string)));
 foreach (string value in listbox1.Items)
 {
    dr = dt.NewRow();
    dr[0] = value;
    dt.Rows.Add(dr);
  }
  data.DataSource=dt;


text:
Q: Alias Loop in csh Why is there an Alias loop error created here:
alias df 'printf "\n"; df -hP | column -t'

But not here:
alias df 'df -hP | column -t'

I realize I could call the alias something else and still have it work, however, I'm trying to understand the underlying operation.

A: This is explained in the tcsh man page (I suspect you're using tcsh, not csh); see the third quoted paragraph.

The shell maintains a list of aliases which can be set, unset and
  printed by the alias and unalias commands.  After a command  line
  is parsed into simple commands (see Commands) the first  word of
  each command, left-to-right, is checked to see if it has an alias. If
  so, the first word is replaced by the alias. If the alias contains a
  history reference, it undergoes History substitution (q.v.) as
  though the original command were the previous input line. If the alias
  does not contain a history reference, the argument list is left
  untouched.
Thus if the alias for `ls' were `ls -l' the command `ls /usr' would
  become `ls -l /usr', the argument list here being undisturbed.
  If the alias for `lookup' were `grep !^ /etc/passwd' then `lookup
  bill' would become `grep bill /etc/passwd'. Aliases can be used to
  introduce parser metasyntax. For example, `alias print 'pr !* |
  lpr'' defines a ``command'' (`print') which pr(1)s its arguments to
  the line printer.
Alias substitution is repeated until the first word of the command has
  no alias. If an alias substitution does not change the first word (as
  in the previous example) it is flagged to prevent a loop. Other loops
  are detected and cause an error.

A good workaround is to precede a command with a \ character to inhibit alias expansion:
alias df 'printf "\n"; \df -hP | column -t'

A: It appears that when the alias name is also the first command, it's not interpreted as an alias, but beyond that it is.  This can be worked around with the absolute path:
alias df 'printf "\n"; /bin/df -hP | column -t'

Or, as a Keith pointed out in a comment and answer, \ prevents alias expansion:
alias df 'printf "\n"; \df -hP | column -t'


text:
Q: Does the Frying Pan knockback enemies Using the Frying Pan as a melee weapon is definitely one of the high points TF2 has.  But one thing I'm curious is the fact that everytime I hit someone, they seemed to be knocked into the air.  Even though it is a stock weapon reskin, and its description does not show any advantages over standard weapons, does it actually cause a knockback? Or was it just the server I was on?

A: Two things.

*

*All damage causes knockback, even DoTs like burning and bleed (just try and keep your scope steady as an immolated Sniper!).

*Crits get a significant amount of bonus knockback.
This means, if you crit, you can knock someone back a goodly distance.
If you noticed it happening on non-crits, or on every swing, then it's quite likely it was related to the server you were on, because the Frying Pan is simply a reskin of the stock melee weapons of the class that is using it. (I.e., Scout's Fryingpan is faster but deals less damage)


text:
Q: How to change background image set with inline style mapping an array? I am trying to change my background image which is set with inline style mapping an array as follow:
const changeBgImage = () => {
  let bgImages = [
    "/ihpbnkKoningzaal12Owres.jpg",
    "https://static.wixstatic.com/media/28661c_577a107e4ea648a18285371cd03bd121f000.jpg/v1/fill/w_1263,h_649,al_c,q_85,usm_0.33_1.00_0.00,enc_auto/28661c_577a107e4ea648a18285371cd03bd121f000.jpg",
  ];
  setInterval(() => {
    bgImages.map((bgImg, index) => {
      console.log(bgImg, index);
      window.document.getElementById("bg-container").style.backgroundImage = `url(${bgImg})`;
      window.document.getElementById("bg-container").style.backgroundSize =
        "cover";
      window.document.getElementById("bg-container").style.backgroundRepeat =
        "no-repeat";
      window.document.getElementById("bg-container").style.backgroundPosition =
        "center";
      window.document.getElementById(
        "bg-container"
      ).style.backgroundAttachment = "fixed";
    });
    // window.document.getElementById("bg-container").style.backgroundImage =
    //   "url('/ihpbnkKoningzaal12Owres.jpg')";
  }, 5000);
};

I call the above function inside a useEffect so the background image can change on page load as per below:
 useEffect(() => {
    changeBgImage();

    );
  }, []);

for some reason i don't understand it does not work, how ever, if I don't map though the array and run the commented line at the end, it works fine which make me think the issue is with the map function maybe.
Can someone advise what i do wrong, please?

A: i don't get it why you are using set interval or even mapping through an array
anyway in the mapped version you never set the background image of "bg-container"
that's why it works differently when being mapped

A: Seems to me that you forgot to put quotes there.
Running url(${bgImg}) on first element will result to url(/ihpbnkKoningzaal12Owres.jpg), try url('${bgImg}') instead.
Also in react it is better to use refs instead of document.getElement

A: Let's change your element background randomly according to backgrounds array.
// in-range random number generator
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

const fn = () => {

   // random index for bgImages array - a number from 0 to array.length - 1,
   // -1 is because this array length is 2, but last index is 1.

   const randomIndex = getRandomArbitrary(0, bgImages.length - 1);

   // all styles for html element
   const styles = {
      backgroundSize: "cover",
      backgroundRepeat: "no-repeat",
      backgroundPosition: "center",
      backgroundAttachment: "fixed",
      backgroundImage: `url("${bgImages[randomIndex]}")`
   }

   // reference to html element, no need to make a search for your element in  DOM for every css property
   const bgCont = document.getElementById("bg-container");

   // walking over styles object and applying css props to html element
   Object.entries(styles).forEach(([key, value]) => {
       bgCont.style[key] = value
   })

}

setInterval(fn, 5000)

Here we can make some improvement like applying css class to element and changing only single property, initializing bgCont outside the function and other stuff. This is a very straight, fast and unoptimal approach.


text:
Q: How to create temporary urls to prevent hotlinking in php? Im looking to build a simple upload site, that will generate temporary URLS to video files after a captcha has been entered. I need to protect the true location of the files, so they cannot be hotlinked directly. A time based url, that expires after x minutes seems like the best option, but Im not sure on the actual implementation.
Any tips?

A: Make your urls like this:
http://myvid.com/video?id=1&timestamp=12341561234&hash=1203941h23jk479sdf87sdf
Where timestamp is the unix timestamp and hash is an md5 hash, say, of the timestamp appended to a secret string on the server.
Then, when you play that video, check if the timestamp field is valid (by using the hash), and then check to see how old the timestamp is.

A: Yegor, they use Mod Rewrite. So when someone enters
www.domain.com/video/1234567890/theLongHashCode
you write in .htaccess that the url should be treated as video.php?timestamp=12341561234&hash=1203941h23jk479sdf87sdf
This allows you prevent from showing the actual url.
Some sources on mod rewrite: http://www.modrewrite.com/
What you would need to put in .htaccess file, considering you have mod_rewrite module enabled on Apache:
RewriteEngine On
RewriteRule ^video/([0-9]+)/(.*)  video.php?timestamp=$1&hash=$2

This only takes in 2 values: timestamp and hash. The video id is not sent. I would not even send the timestamp. For temporary url, I only generate a hash, store it in the database along with the timestamp. So when someone visits an url, I look up the hash from the database. If the hash exists, then I compare the timestamp from the database with the current time, and if it is within the time limit, then the url is considered valid, otherwise it is invalid and write to the page "This link has expired."
So I would have the url look like:
http://hsbsitez.com/video/thehashcodehere
With the following .htaccess file to interpret that url.
RewriteEngine On
RewriteRule ^video/(.*)  video.php?hash=$1

Where video.php is the file that checks if the hash exists in the database or not.

A: header('Content-Type: application/force-download');

$fileee = 'filename.zip';
$file_Location = "/..yourfolder/" . $fileee;

header('Content-Length:' . filesize($file_Location));
header("Content-Disposition: inline; filename=\"".$fileee."\"");

$file_Pointer = fopen($fileLocation,"rb");
fpassthru($file_Pointer);

A: Use a FORM with method set as PUT
Have you thought about using a form with PUT method? This is exactly one of the cases that PUT is designed for - not being able to revist the page with the same URL. Just create a simple form that has a few hidden fields and you can make a javascript link that submits it. This way you don't have to worry about users trying to revist the links or having the links in their history.
Example:
<form id="myform" method="put" action="viewimage.php">
<input type="hidden" name="id" value="uniquevalue" />
<input type="hidden" name="filename" value="foo.jpg" />

Image foo.jpg
</form>

Superficially, no one will be able to revisit the image without having to do some HTTP magic beyond your typical user. However, to further verify that the image is only launched after a click, you can register the id in the session and timestamp it, then check against the timestamp when the image is viewed.

A: I would recomend not printing whole file via php, because it is resource-consuming(even fpassthru).
There is another option - using own script for generating pairs temporary url => original url with rewritemap prg.
But this option should be used careful.


text:
Q: vb.net HttpWebRequest BeginGetResponse parameters I'm doing threaded webrequests. How do I pass the parameter 'index' from the Start() sub to GetResponseCallback()?
The two subs:
Shared Sub Start(ByVal index As Integer)
    Dim request As HttpWebRequest = CType(WebRequest.Create("http://sternbud.com/login/checklogin.php"), HttpWebRequest)

    request.ContentType = "application/x-www-form-urlencoded"
    request.Method = "POST"

    Debug.Print(index & ">" & AccountArray(dictThread.Keys(index)))

    Dim result As IAsyncResult = CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), IAsyncResult)

    allDone.WaitOne()
End Sub

Private Shared Sub GetRequestStreamCallback(ByVal asynchronousResult As IAsyncResult)
    Dim request As HttpWebRequest = CType(asynchronousResult.AsyncState, HttpWebRequest)

    Dim postStream As Stream = request.EndGetRequestStream(asynchronousResult)
    Dim postData As [String] = "myusername=" & AccountArray(AccountIndex) & "&mypassword=test"

    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

    postStream.Write(byteArray, 0, postData.Length)
    postStream.Close()

    Dim result As IAsyncResult = CType(request.BeginGetResponse(AddressOf GetResponseCallback, request), IAsyncResult)
End Sub

A: You pass it as an Object in the last parameter to BeginGetRequestStream. Currently you have:
Dim result As IAsyncResult = CType(request.BeginGetRequestStream(AddressOf GetRequestStreamCallback, request), IAsyncResult)

You're passing the result in the state parameter, and that value gets set in the AsyncState property of the passed IAsyncResult.
If you want to pass two values, you have some choices:

*

*Create a new object that has the result and index values as separate properties.

*Create an array of Object where the first item is the request and the second is the index. You can then get the AsyncState property, case it to an object array, and peel out the items.

*Create a Tuple from your two values, and pass that Tuple in the state parameter.

I prefer the second because it's so easy, but creating a Tuple is cleaner (i.e. type-safe) and almost as easy. I have a C# example of the second method at https://stackoverflow.com/a/4555766/56778.


text:
Q: How to access localhost from VirtualBox using a smartphone? I want to access VirtualBox's localhost using a smartphone for me to see how the website looks like in a phone.
More Details:

*

*Host OS - Windows 7 Pro

*Guest OS - Ubuntu 16.0.4 LTS

*SmartPhones' OS - Android and iOS

A: You actually shouldn't need this, most browsers have a "responsive design view mode" which you can activate by pressing F12 to activate the developer console and clicking on the mobile phone/tablet icon on the left of it.
But to answer your question, yes, this can be done through port forwarding.

*

*Go to the settings for the Ubuntu VM, and select the "Network" tab.

*Make sure that the "Attached to" value is "NAT".

*Click on the "Advanced" dropdown and click on the "Port Forwarding" button.

*Click on the "+" symbol to add a port forwarding rule. Say, you have a server running in Ubuntu in port 80, so enter 80 in the "Guest Port" value. Now, say, you want to access the server on port 8080 of the host machine, so type in 8080 for the "Host Port" value.

*Click on "OK" on the windows to save your settings.

At this point, you can access your server on your host machine by typing in localhost:8080.
To open it on your phone, connect the phone and the computer on the same network (such as a WiFi hotspot). Determine the local IP address of your computer with ipconfig /all. For example, if the IP is 192.168.1.1, type in 192.168.1.1:8080 on your phone.


text:
Q: overlay rotated density plot I'm struggling to overlap rotated density plot onto the original scatterplot. Here are 2 plots I have:
require(ggplot2); set.seed(1);

df1 <- data.frame(ID=paste0('ID',1:1000), value=rnorm(1000,500,100))

p1 <- ggplot(data = df1, aes(x=reorder(ID, value), y=value)) +
  geom_point(size=2, alpha = 0.7)+
  coord_trans(y="log10")

p2 <- ggplot(data = df1, aes(x=value)) +
  coord_trans(x="log10") +
  geom_density() +
  coord_flip()

p1
p2

First, there's a little problem with the density plot that its vertical axis is not log10-transformed. But main issue is that I can't find how to draw it on the previous plot keeping correct coordinates.

A: Because you are using coord_flip on your second plot you are effectively trying to plot two different values onto the same x axis (density and ID). There are plenty of posts discouraging this, here's one for example: How do I plot points with two different y-axis ranges on the same panel in the same X axis?.


text: Q: Can ios local notifications execute business logic? I have a requirement. Assuming that there is a database of jokes in the app, a piece of data is retrieved from the jokes every hour and displayed to the user in a notification manner. Can I use local notifications? I checked a lot of information and said it is local The notification cannot execute any business logic, that is, there is no way to get data


text:
Q: need some jquery if-else statement help the code below is broken, but I'm not sure how.  I've definitely made some big assumptions here as a newbie.
I'm basically trying to create an if else where imBannerRotater functions on #cast if the variable is true and #pram if it is false.
How could I fix this to get that result?
The # are URLs.
Thanks!-zeem
$(document).ready(function(){
                    if (mmjsRegionName == 'CO')
                        {
                $("#cast").imBannerRotater({
                    return_type: 'json',
                    data_map: {
                        image_name: 'name',
                        url_name: 'url'
                    },
                        image_url: '#',
                        base_path: '#',
                });
                    }
                    else
                        {
                $("#pram").imBannerRotater({
                                return_type: 'json',
                                data_map: {
                                    image_name: 'name',
                                    url_name: 'url'
                                },
                                    image_url: '#',
                                    base_path: '#',
                });

            });

A: $(function(){
  var $target  = $('#cast'); // or whatever you want as a default
  if (mmjsRegionName == 'CO'){
    $target = $('#cast');
  }else{
    $target = $('#param');
  }
  $target.imBannerRotater({
    return_type: 'json',
    data_map: {
      image_name: 'name',
      url_name: 'url'
    },
    image_url: '#',
    base_path: '#',
  });
});

Little refactored, but should get you there.
(Though I'm not sure what you mean by "if the variable is true"--check if (mmjsRegionName){ instead of comparing it to a string maybe?)

EDIT
If it is a true/false case, you may be better off using this:
$(function(){
  $(mmjsRegion?'#cast':'#param').imBannerRotater({ // note the in-line if statement
    return_type: 'json',
    data_map: {
      image_name: 'name',
      url_name: 'url'
    },
    image_url: '#',
    base_path: '#',
  });
});

A: If you are testing whether mmjsRegionName is true or false, then your if statement should just be:
if(mmjsRegionName) { ...

A: The best way to do it would be to create a variable and change it to either "cast" or "pram"
var myID = "pram";
if (mmjsRegionName == 'CO') {
    myID = "cast";
}
$('#' + myID.imBannerRotation({
    //your script here...


text:
Q: Change tracking after reboot We have 2 SQL Server servers (Microsoft SQL Server 2014 12.0.6433.1 Enterprise Edition and Microsoft SQL Server 2016 Standard) that have been logging change tracking procedure failed with too many arguments. All databases do not have change tracking enabled. We tried enabling change tracking on the database and then disabling change tracking. This did not work.

Procedure or function sp_flush_commit_table_on_demand has too many arguments specified.

received after reboot.


text:
Q: jQuery $(this) inside function I want to pass $(this) to function but I am not sure. There is one similar thread, but I still can not make it working. I hope somebody can help me.
$(document).ready(function() {
  var delay = (function(){
    var timer = 0;
    return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
    };
  })();

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }, 1000 );
  });
});

A: You should save a reference to this :
$('input').keyup(function() {
    var $this = $(this);
    delay(function(){
      alert($this.val());
    }, 1000 );
});

Another option is to re-bind this to the function:
  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }.bind(this), 1000 );
  });

A: You would need to bring the context:
return function(callback, ms, context){
  clearTimeout (timer);
  timer = setTimeout(function() {
      callback.call(context);
   }, ms);
};

And then
delay(function() {
    alert($(this).val());
}, 1000, this );

But as others posted, saving the context in a local variable might be what you really want. Here is another way to do it:
$('input').keyup(function() {
  delay((function(self) {
    return function() {
      alert($(self).val());
    };
  }(this)), 1000);
});

A: Keep a reference to $(this) outside the function.
 // ...

    $('input').keyup(function() {
        var $this = $(this);
        delay(function() {
            alert( $this.val() );
        }, 1000)
    });

A: this changed because of function scope change.
You need to store the value using a closure.
If all you pass is the value you don't need $(this)
$('input').keyup(function() {
  var val = this.value;
  delay(function(){
    alert(val);
  }, 1000 );
});

Another way would be
$('input').keyup(function() {
  delay((function(val){
    return function() {
      alert(val);
    };
  }(this.value)), 1000 );
});


text:
Q: Symfony2 Twig table view sort by alphabetical I have a 2 table in database and i want to get the view like this. It is sorted by alphabetical by name. Let's say that I have 2 max rows only and I have 2 data then the 2 data will be display on the left side. If I have 4 data then the other 2 data will display on the right.

In my database, the "Name" is the parent and the Account number and Bank Name are the children of the Name. I have created a query in controller something like this:
$query = $em->createQuery(
         "SELECT
             e.id, e.name,
             eb.numId, eb.bankName, eb.bankAcct
          FROM Bundle:table1 e
          LEFT JOIN Bundle:table2 eb
          WITH e.id = eb.numId
          ORDER BY e.name ASC"
         );
$entity = $query->getArrayResult();

this is my twig:
{% for list in entity|batch(1) %}

    {% for column in list %}
        {{ column.entityName }}
        {{ column.bankName }}
        {{ column.bankAcct }}
    {% endfor %}

{% endfor %}

I've been trying to work this out and I got stuck. thanks in advance for the help.

A: This is the logic that may work,
Display First div(which is on left)
{% set CurrentIndex = '' %}

        {% for i in [1, 2, 3, 4, 5]|slice(0, 2) %}
            {# will iterate over 0 and 1 element #}

          {% if loop.index < 2 %}
              #Display table columns

      #set Current index at which loop will break, so that we can use it in next iteration
              {% set CurrentIndex = loop.index %}
          {% endif %}

        {% endfor %}

Display Second div(which is on Right)

        {% for i in [1, 2, 3, 4, 5]|slice(CurrentIndex, 2) %}
            {# will iterate over 0 and 1 element #}

          {% if loop.index < 2 %}
              #Display table columns
          {% endif %}

        {% endfor %}

loop.index will give current index and  slice(start,length) will display rows from index start upto given length
I didn't tried this, but logic may work.
Links-
Slice , set


text:
Q: Create a variable inside another statement Is there a way to allocate a variable within the scope of a parameter list? By using new we can do the following :
Class A{ /*... snip ...*/ };

void myFunc(A* a){ }

int main(...){
    myFunc(new A());
    return 0;
}

This will create a new A. What if the signature of myFunc was
void myFunc(A a);

instead. Is there a syntax to create local instance inside the myFunc() parameter list? I'm looking for something like
myFunc(A());

or
myFunc(A a());

Another use would be for something like :
A a(123);
if(a == A(123)){ }

The net effect is to save one line, but it also creates a scope within the parameters list which makes me wonder if it is allowed at all.

A: If you just want to create a variable to pass to the function you can use a aggregate initialization / list initialization
#include <iostream>
#include <cmath>
using namespace std;

class A{ /*... snip ...*/ };

void myFunc(A a){ }

int main(){
    myFunc(A{});
    return 0;
}

Live Example
You can also use this with classes that have constructors that take multiple parameters
#include <iostream>
#include <cmath>
using namespace std;

class A
{
private:
    int foo;
    int bar;
    double foobar;
public:
    A(int a, int b, double c) : foo(a), bar(b), foobar(c) {}

};

void myFunc(A a){ }

int main(){
    myFunc(A{1,2,3.0});
    return 0;
}

Live Example

A: C++ supports this with the myFunc(A()); syntax you posed in your question.
#include <stdio.h>

char lazybuff[500];

class Point
{
  public:
    Point (double x, double y) : m_x(x), m_y(y) { }
    char * ToString (void) { sprintf (lazybuff, "%f, %f", m_x, m_y); return lazybuff; }

  private:
    double m_x, m_y;
};

void print_point (Point print_me)
{
  printf ("%s\n", print_me.ToString());
}

int main (void)
{
  print_point (Point(5, 3));

  return 0;
}


text:
Q: Cannot click and drag highlight multiple lines from the far left, in Ms Word 2013 In earlier versions of Word I was able to move the mouse near the far left and get that mouse cursor as pictured, and be able to click and drag down and select multiple lines.
Not in Ms Word 2013.
I know I can put the cursor at the beginning or end of the bunch of lines and do shift up/down, but I want to be able to do it with a click and drag of the cursor from the far left, not clicking on a precise cursor position. But getting that arrow by just moving the cursor to the far left of the line and dragging up and down. Now it is not working.
A box comes up asking me to change the font, as pictured, and not letting me highlight up or down behond that highlighted line.

A: The behavior you describe in question still applies to Word 2013. I think what is happening is that you clicking on the word and getting that floating dialog to change text. You should be able to just find a specific spot, click and start dragging your mouse.
Added (incorporating SaUce's comment to his/SaUce's post)
it is a feature of 2013 and yes it does appear for me, and not only is it in Word but also in Outlook and other Microsoft products. How ever you can disable it if you go to Options and Look in General under "User Interface Option" there is check box for "Show Mini Toolbar on Selection"


text:
Q: extract a letter from a string in processing im trying to get a letter from a string in processing
so lets say the sketch receives the string "x193" it would need to be able to isolate the x and the 193 and put them in different variables.

A: You don't really need to get and put the 'x' as it is always the same, so just get what is after it, until the end of the string. Something like:

String[] a = {"x1", "x12", "x123"};

String[] onlyNumbers = new String[3];

void setup(){
  for (int i = 0; i length; i++){
    String stirp = a[i].substring(a[i].indexOf('x')+1, a[i].length());
    onlyNumbers[i] = stirp;
  }
  println(onlyNumbers);
}

If you need performance you can also use StringBuilder, wich is much faster.

A: You need something like this:
String inQuestion = "x193";
String myCharacter = inQuestion.substring(0, 1);
See http://www.processing.org/reference/String_substring_.html


text:
Q: Connect to SQL 14 Azure db from Pyodbc if SQL Server is MS 2012 Some contractors I work with set up an Azure SQL db, ms server version 14. Is it possible to still connect with pyodbc if my personal machine still has SQL v11? If not, is there another method to connect?
Most of my connections are with ms server v11, so I would like to avoid upgrading my ms server if at all possible. I only need to connect to their azure server for a single query. Tried a few variations on the normal connection (trusted_connection = no, etc.)
engine = create_engine('mssql+pyodbc://user:pass@azure_server/db')

A: Whoops, think this was buried in Connecting to Azure SQL with Python
Install ODBC driver 13 FTW!


text:
Q: Laravel 5.8 Auth guard [api] is not defined When I use auth api guard for my controller I am facing with the following exception

Auth guard [api] is not defined

When I remove Authorization in request header, my controller work is true but when I add Authorization and accept to request header, I get this error.
My route:
Route::group(['prefix' => 'category','middleware' => 'auth:api'], function () {
  Route::post('add', 'Api\CategoryController@addCategory');
  Route::post('edit', 'Api\CategoryController@editCategory');
  Route::get('get/{id}', 'Api\CategoryController@getCategory');
  Route::get('get', 'Api\CategoryController@getCategory');
  Route::get('delete', 'Api\CategoryController@deleteCategory');
});

auth.php file:
 'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
],

and i added Passport::routes() to AuthServiceProvider.php and i migrated passport migration and i installed passport for create passport client access
i think every thing is ok but get error

A: You need to clear config cache to take effect.
for Unauthenticated it means token is not valid or is not passed correctly
https://laravel.com/docs/5.7/passport#passing-the-access-token


text:
Q: Emit reStructuredText from sphinx autodoc? CPython doesn't use autodoc for its documentation - we use hand-written prose.
For PEP 3144 (the ipaddress module), I'd like to use sphinx-apidoc to generate the initial reference documentation. That means I want to run a two-pass operation:

*

*Use sphinx-apidoc to emit a Sphinx project for the module that depends on autodoc

*Run a sphinx builder that creates new reStructuredText source files, with all the autodoc directives replaced by inline reStructuredText content and markup that produces the same output
The first step is straightforward, but I have no idea how to do the second step and can't even think of good ways to search for any existing projects along these lines.

A: I had same problem and for one time generating of docs I've used quite ugly solution to patch Sphinx, see Make Sphinx generate RST class documentation from pydoc.

A: Not a full answer, more or less a starting point:
autodoc translates auto directives to python directives.
So one can use autodoc events to get the translated python directives.
For example if you have the following mymodule.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is my module.
"""

def my_test_func(a, b=1):
    """This is my test function"""
    return a + b

class MyClass(object):
    """This is my class"""

    def __init__(x, y='test'):
        """The init of my class"""
        self.x = float(x)
        self.y = y

    def my_method(self, z):
        """This is my method.

        :param z: a number
        :type z: float, int
        :returns: the sum of self.x and z
        :rtype: float
        """
        return self.x + z

sphinx-apidoc will create
mymodule Module
===============

.. automodule:: mymodule
    :members:
    :undoc-members:
    :show-inheritance:

The following extension (or addition to conf.py):
NAMES = []
DIRECTIVES = {}

def get_rst(app, what, name, obj, options, signature,
            return_annotation):
    doc_indent = '    '
    directive_indent = ''
    if what in ['method', 'attribute']:
        doc_indent += '    '
        directive_indent += '    '
    directive = '%s.. py:%s:: %s' % (directive_indent, what, name)
    if signature:  # modules, attributes, ... don't have a signature
        directive += signature
    NAMES.append(name)
    rst = directive + '\n\n' + doc_indent + obj.__doc__ + '\n'
    DIRECTIVES[name] = rst

def write_new_docs(app, exception):
    txt = ['My module documentation']
    txt.append('-----------------------\n')
    for name in NAMES:
        txt.append(DIRECTIVES[name])
    print '\n'.join(txt)
    with open('../doc_new/generated.rst', 'w') as outfile:
        outfile.write('\n'.join(txt))

def setup(app):
    app.connect('autodoc-process-signature', get_rst)
    app.connect('build-finished', write_new_docs)

will give you:
My module documentation
-----------------------

.. py:module:: mymodule

This is my module.

.. py:class:: mymodule.MyClass(x, y='test')

    This is my class

    .. py:method:: mymodule.MyClass.my_method(z)

        This is my method.

        :param z: a number
        :type z: float, int
        :returns: the sum of self.x and z
        :rtype: float

.. py:function:: mymodule.my_test_func(a, b=1)

    This is my test function

However as autodoc emits no event, when the translation is completed, So further processing done by autodoc has to be adapted to the docstrings here.


text:
Q: Couldn't load SIP module - python disabled Recently my QGIS started refusing to load SIP module, from day to day without any significant changes in the system (I'm on Windows7 x64). Message thrown at startup:
Nie można wczytać modułu SIP. (Couldn't load SIP module)
Wsparcie dla Pythona zostanie wyłączone. (Python support will be disabled)

Traceback (most recent call last):
  File "", line 1, in
ImportError: cannot import name wrapinstance

Wersja Pythona: (Python version)
2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]

Wersja QGIS: (QGIS version)
1.8.0-Lisboa 'Lisboa', f440b60

Lokalizacja Pythona: (Python location)
['C:/PROGRAMS/Geodesy/OSGeo4Win/apps/qgis/./python', 'C:/Users/Muciek/.qgis//python', 'C:/Users/Muciek/.qgis//python/plugins', 'C:/PROGRAMS/Geodesy/OSGeo4Win/apps/qgis/./python/plugins', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\qgis\\python', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib', 'C:\\Windows\\system32\\python27.zip', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\DLLs', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\plat-win', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\lib-tk', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\qgis\\bin', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages\\PIL', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages\\win32', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages\\win32\\lib', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages\\Pythonwin', 'C:\\PROGRAMS\\Geodesy\\OSGeo4Win\\apps\\python27\\lib\\site-packages\\wx-2.8-msw-unicode']

I tried reinstalling various versions of QGIS (1.7 - 1.9) and manipulated with system Path and PYTHONPATH both with no result.
QGIS starts perfectly on different user account (without administration rights). It means that it may be a problem with sone software installed but still I have no idea what could it be.
Any help or suggestion would be appreciated, thanks in advance.


text:
Q: How to find every number in a row and store average in separate per-row variable I just started learning shell scripting.
I'm trying to read from a file structured like:
harddrive1 10 20 30 40
harddrive2 20 30 40 50
harddrive3 30 40 50 60

I want to save the average of each row in a separate variable somehow...there will only be 3 rows, 5 columns.
So my output would be:
hd_AVG1=20
hd_AVG2=35
hd_AVG3=45

How can I accomplish that?
EDIT: I need to save it in DIFFERENT variable so that i can call the variable...for example
if [[ $hd_AVG1 -eq 20 ]];
    then
    do something...
elif [[ $hd_AVG2 -gt 40 ]];
    then
    do something...
fi

A: $ awk '{print $1"="($2+$3+$4+$5)/4}' file
harddrive1=25
harddrive2=35
harddrive3=45

A: This bash script should do what you want. It calls bc to do the float arithmetics since bash cannot do it itself.
#!/bin/bash
while read -a line ; do
    sum=0
    for ((i=1; i<${#line[@]}; i++)) ; do
        let sum+=line[i]
    done;
    hd[j++]=$(bc -l <<< "$sum/($i-1)")
done < input
echo ${hd[0]} ${hd[1]} ${hd[2]}

A: With Perl (very portable):
perl -lane 'print $F[0] . "=" . ($F[1] + $F[2] + $F[3] + $F[4]) / 4' file.txt

A: Using an array population trick I just learned from @steve:
$ cat file
harddrive1 10 20 30 40
harddrive2 20 30 40 50
harddrive3 30 40 50 60
$
$ hd_AVG=($(awk '{print ($2+$3+$4+$5)/4}' file))
$ echo "${hd_AVG[0]}"
25
$ echo "${hd_AVG[1]}"
35
$ echo "${hd_AVG[2]}"
45

A: You could do it like this with coreutils and sed:
. <(paste -d=                                                   \
      <(cut -d' ' -f1  infile                                 ) \
      <(cut -d' ' -f2- infile  | sed 's/$/ + + + 4 \/ p/' | dc) \
   )
echo $harddrive1 $harddrive2 $harddrive3

Output:
25 35 45

Explanation
The <( ) notation runs the commands within and pipes their output through a fifo, so paste sees two pipes and columnates their output with = as their delimiter.
The second cut takes the numbers from the file, sed appends appropriate operators to the numbers and lets dc do the calculation. The input to dc looks like this:
cut -d' ' -f2- infile | sed 's/$/ + + + 4 \/ p/'

Output:
10 20 30 40 + + + 4 / p
20 30 40 50 + + + 4 / p
30 40 50 60 + + + 4 / p

dc is a reverse polish calculator; it supports arbitrary precision, but needs to be told to use decimals. This will make dc use two decimals:
cut -d' ' -f2- dims | sed 's/^/2k/; s/$/ + + + 4 \/ p/'

The whole command is also wrapped in <( ) and sourced with ., i.e. the variables will be available in the current environment.


text:
Q: How do you stop IIS SMTP Server from sending bounce emails? How do you stop the "Default SMTP Virtual Server" from sending bounce messages for email addresses that you don't have?
i.e. I'm using IIS' SMTP server to handle my email and if an email is sent unknown at mydomain.com a bounce email with 'address not known' (or something like that) is sent back to the sender. I want it to silently fail.

A: I found this article which has a script you can run to configure a catch-all account on your server.  All emails which would generate a NDR will instead be directed to this account.  Sorry, I haven't tested it.  The article above has been removed here it is via the WayBack Machine
Basically the short answer to your question is no.
On another note, if you don't want to spend any money, or have no budget, and want a better email system, try something like Smarter Mail which you can use for free up to 10 users.  I am sure there are others out there, but I have used Smarter Mail in the past successfully.

A: This isn't an IIS failure. The SMTP server receiving the message is looking for a valid email address, and when it doesn't find one, sends an email back to your email address saying that there isn't one there. The only way to have it silently fail is by putting the from address as a bogus email like  no-reply@company.com, etc.

A: From an SMTP point of view, a better way to handle this is to reject the RCPT request at some point during the SMTP transaction. This way, your server isn't responsible for sending any blowback to the alleged sender.
I don't know how to configure IIS to do this specifically, but you certainly can with Postfix (which is what I use).


text:
Q: Do all Android phones with a built-in camera use a folder called "DCIM" to store captured images? I am developing an app which uses the phone's default camera application to capture an image and then allow the user to perform some basic editing.
I use the following snippet...
Intentintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT,*<file>*);
startActivityForResult(intent, TAKE_PHOTO_CODE);

I want the image captured to be saved in a location that is consistent with the stock camera application.  Can I use the DCIM folder and assume all phones will use that location?

A: I would expect that the default Android camera app will save images in the DCIM folder.  If for some reason a phone manufacturer customized Android with a different camera app, the default location could be different.
You could always check for the existance of the DCIM folder first, and if it doesn't exist, have some kind of a "fall back" location that's specific to your app.

A: I don't recommend assuming such a thing e.g. Droid Incredible has an internal 8GB storage and I'm not sure how it stores the images inside so check that.


text:
Q: How can scroll calendar horizontally on React Native like Way of Life App. you can see a video by the link you can see on google drive
https://drive.google.com/open?id=1UWUfli7g5vlh25PNHbGR46Cs6weROdQV
enter image description here

A: Are you forced to use Flatlist? Do you have a small number of items to display? If you have a small list, you can switch to <ScrollView> and use snapToAlignment={VALUE} or snapToInterval={NUMBER} https://facebook.github.io/react-native/docs/scrollview#snaptointerval


text:
Q: Magento 2 product quantity increasing automatically I have magento 2.2.7, the issue is when I update product quantity to zero "0", it automatically increments the quantity after some time. I tried on 3 products and each products increment was different.
I checked in logs, none were generated, checked product update time, that too also isn't changing after automatic increment. Any guesses, how can resolve it??

A: Resolved. Just commented out sales_clean_orders cron in vendor/magento/module-sales/etc/crontab.xml


text:
Q: TFS merge issues when converting CSS to LESS As part of a branched project in TFS, I've converted our static CSS files to LESS files which dynamically creates CSS on save/compile using Visual Studio Web Essentials.
However I have concerns that when merging back up into the main branch TFS will try and merge the existing CSS files with the dynamic CSS files, rather than replacing the CSS files with the LESS files.
What is the best way of avoiding this from happening?

A: If you checkin the newly generated files, they will be taken over by TFS as though you edited them yourself. Depending on your repository/workspace config, you may need to checkout the files first before regereration.
On the other hand, since the css files are now generated, you could remove them from TFS and exclude them from source control.
The downside of this is that you need to regenerate the files whenever they are needed. It may not be practical in all situations.

A: It is not recommend to store generated files under source control. You can use .tfignore or .gitignore to tell VS to ignore the .css files in that folder and only track your .less files.
If you need the .css files then run the generation...


text:
Q: Laravel select one image from every row from database I have 2 tables in my database , one with cars and one with images for cars..is a one to many relationship..A car can have multiple images , but I want to select for every car just one image. The 2 tables are
Car table:
 Schema::create('cars', function (Blueprint $table) {
        $table->id();
        $table->string('model');
        $table->integer('seats');
        $table->string('fuel');
        $table->integer('year');
        $table->string('color');
        $table->string('gearbox');
        $table->integer('price');
        $table->string('coinType');
        $table->timestamps();
    });

Images table:

    Schema::create('images', function (Blueprint $table) {
                $table->id();
                $table->integer('car_id');
                $table->string('file_name');
                $table->timestamps();
            });

    class Car extends Model
{
    protected $fillable = [
        'model',
        'seats',
        'fuel',
        'year',
        'color',
        'gearbox',
        'price',
        'coinType',
    ];

    public function images()
    {
        return $this->hasMany(Image::class);
    }

Image model:

    class Image extends Model
{
    protected $fillable = [
        'car_id',
        'file_name'
    ];

    public function car()
    {
        return $this->belongsTo(Car::class);
    }

I tried to make a join between tables like that:
$images = Image::join('cars', 'images.car_id', '=', 'car.id')
    ->select('images.file_name')
    ->first();

But I get only the first row from that table. I need some help here, Thank you


text:
Q: How to autoresize UIToolBar? I want the toolbar to automatically appear on the bottom of the screen, and I want it to resize the width so it adjusts from iPhone to iPad. The code below results in a static UIToolbar which stays in the same position. How do i make the toolbar appear at the bottom, and how do i adjust the width automatically according to screen size ?
- (UIView*)commomOverlay
{

UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0,0,400,430)];

CGRect rect = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 44, [[UIScreen   mainScreen] bounds].size.width, 44); /*
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
    rect = CGRectMake(0,0,768,1004);
}
UIImageView *FrameImg = [[UIImageView alloc] initWithFrame:rect];
[FrameImg setImage:[UIImage imageNamed:@"newGraphicOverlay.png"]];
FrameImg.userInteractionEnabled = YES;
[view addSubview:FrameImg];
[FrameImg release];*/

rect = CGRectMake(0, 0, 400, 50);

UIToolbar *myToolBar = [[UIToolbar alloc] initWithFrame:rect];
[myToolBar setBarStyle:UIBarStyleBlackTranslucent];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Finish" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelButtonPressed)];
UIBarButtonItem *flexiSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(myFunction)];
mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake (123,350,40,20)];
[mySwitch addTarget:self action:@selector(toggleFlash:) forControlEvents:UIControlEventAllTouchEvents];
UIBarButtonItem *switchBtn = [[UIBarButtonItem alloc] initWithCustomView:mySwitch];
//Order of how buttons appear or toolbar left to right.
[myToolBar setItems:[NSArray arrayWithObjects: cancelButton, flexiSpace,switchBtn, nil] animated:YES];
 myToolBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ;

[cancelButton release];
[flexiSpace release];
[switchBtn release];

[view addSubview:myToolBar];
return view;

}

A: You are setting it's frame using a constant value. However, your view's frame is already set at this point and it will not change according to your autoresizingMask. You should use the view's bounds property instead and do something like:
toolbar.frame = CGRectMake(self.view.bounds.origin.x, 0, self.view.bounds.size.width, 50);

Another option would be defining constraints for your view.


text:
Q: Error: 424 - Set json = JsonConverter.ParseJson(http.ResponseText) The goal is to query URL on a periodic to display currenccy values for a given currency.
Error 424 observed at the line: Set json = JsonConverter.ParseJson(http.ResponseText)

full VBA:
Private Sub GetCurrencyValues()
    Dim http As Object
    Dim json As Object
    Dim rate As Double
    Dim curr As String

    Set http = CreateObject("MSXML2.XMLHTTP")

    curr = "USD" ' US Dollar
    http.Open "GET", "https://api.exchangerate-api.com/v4/latest/" & curr, False
    http.Send

    Set json = JsonConverter.ParseJson(http.ResponseText)

    rate = json("rates")("JPY") ' Japanese Yen
    Range("A1").Value = rate

    rate = json("rates")("GBP") ' British Pound
    Range("B1").Value = rate

    rate = json("rates")("NOK") ' Norwegian Kroner
    Range("C1").Value = rate

    rate = json("rates")("MXN") ' Mexican Peso
    Range("D1").Value = rate

    rate = json("rates")("EUR") ' Euro
    Range("E1").Value = rate

    rate = json("rates")("PLN") ' Polish Zloty
    Range("F1").Value = rate
End Sub

Private Sub StartTimer()
    Application.OnTime Now + TimeValue("00:15:00"), "GetCurrencyValues"
End Sub

Where do I install the JSON library in order to parse the JSON response from the API?

A: Try following these steps:
Download the JsonConverter library from https://github.com/VBA-tools/VBA-JSON/releases.
Extract it and in VB editor select Tools > References.
Download the latest release
Import JsonConverter.bas into your project (Open VBA Editor, Alt + F11; File > Import File)
Add Dictionary reference/class
For Windows-only, include a reference to "Microsoft Scripting Runtime"
In the References dialog box, make sure that "Microsoft Scripting Runtime" and "Microsoft XML, v6.0" are also checked.
Click OK to close the References dialog box.


text:
Q: Getting Chrono C++ library (Boost::sandbox) to work i wanted to try out Chrono from the Boost sandbox. It seems to support a lot of stuff and should be stable.
I have Boost in version 1.44 installed on my system (incl. boost_system lib which is needed) and took the sandbox version (the download-version is older and misses for example the ratio.hpp file).
But it isn't compiling. Trying to compile the simple example from the documentation, with linking boost_system (in scons with LIBS=['boost_system']), the following error is occurring every time:
obj/main.o: In function `main':
/home/***/src/main.cpp:34: undefined reference to `boost::chrono::system_clock::now()'
scons: building terminated because of errors.

That seems to be a linker error. What did i do wrong? I have boost_system in version 1.44 linked (trough scons) and already tried the same with the older version 1.40.
Any tips? How did you setup your use of chrono?
Thanks.
sascha
Edit: This thread, which is talking about compatibility issues, let me think that the sandbox version of Chrono should be able to work with boost 1.44.

A: As described in the Installing Chrono documentation, you either need to build and link the Chrono library, or define BOOST_CHRONO_INLINED.
I had problems building Chrono from the trunk checkout, but it's probably related to the type_traits incompatibility mentioned in the Chrono docs.
I was able to build the example program with the following SConstruct (after fixing namespace errors):
env = Environment(
    CPPDEFINES = ['BOOST_CHRONO_INLINED'],
    CPPPATH = ['/.../boost_1_44_0', ],
    LIBPATH = ['/.../boost_1_44_0/stage/lib', ],
    LIBS = ['boost_system'],
)

env.Program('chrono-test', 'main.cpp')


text:
Q: How to figure out the target of a PDF outline that has only an SE dictionary The PDF reference (12.3.3, Table 153) says that an outline will either have a Dest dictionary, an A dictionary, or an SE dictionary (with an optional Dest dictionary). I have a document with outlines that only have the SE dictionary. The reference directs me to the Structure Hierarchy (14.7.2), and this is where I've become lost. Structure items may have Pg dictionaries, but mine don't (and neither do the parents, on a recursive traversal). So I need to figure out the page number, offset in page and zoom (if applicable) from the SE dictionary. Any ideas?
Thanks!

A: The structure tree has a root node that is a bit special. It contains a few entries that the rest of the nodes do not have. There is one entry called ParentTree that is used for locating structure elements that correspond to pages, annotations and XForms. See 14.7.2 Structure Hierarchy and 14.7.4.4 Finding Structure Elements from Content Items.
The references between pages and structure elements go both ways, you are supposed to have the Pg entry in one structure element or one of its recursive parents (as far as I know if this is not the case the file can be considered as corrupt), and you will have an entry called StructParents in the page dictionary that contains the index that corresponds to that page in the ParentTree structure.
If the StructParents entry is missing inside the page dictionaries and the structure tree is present, then the file is most likely corrupt. With "corrupt" I mean that the information it contains is not consistent, coherent etc.
There are two ways of using this information then. If you have a reference to a structure element, you should be able to find the page it refers to by using the Pg entry. If you have a reference to a page, you should be able to use its corresponding structure element by using the ParentTree structure. Both directions are supposed to be present in the file for the information to be consistent.


text:
Q: How to dynamically disable every field but the submit button in a Symfony form It's my understanding that the best practice regarding forms in Symfony is to reuse as much code as you can (well, it's probably best practice in general).
I've set up a bunch of actions to edit or create an entity, and both actions use the same form class and the same twig template. Now I have to make a delete form for that entity.
I want to reuse the template I used to create or edit the entity, but this time every field will be disabled. This way the user will see the content of the entity, but won't be confused by the ability to edit the field (it must be clear that by clicking the submit button everything will be deleted, not saved).
Right now that's the form class:
// AppBundle/Controller/DeleteEntityController.php
// ...
class TermType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('term', TextType::class, array('label' => 'Term'));
        $builder->add('definition', TextareaType::class, array('label' => 'Definition'));
        $builder->add('visibility_status', ChoiceType::class, array(
                'label' => 'Visibility',
                'choices' => array(
                    'Visible' => true,
                    'Invisible' => false
                ),
            ));
        $builder->add('page', EntityType::class, array(
                'label' => 'Page',
                'class' => 'AppBundle:Page',
                'query_builder' => function (PageRepository $er) {
                        return $er->getPageByType('Glossary');
                },
                'choice_label' => 'title'
            ));
        $builder->add('submit', SubmitType::class, array(
            'label' => 'Submit'
        ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Term::class,
        ));
    }
}

The first thing I tried was to call the form and set disabled as true ($form = $this->createForm(TermType::class, $term, array('disabled' => true));), but that option disables everything, included the submit button.
So I explicitly enabled the submit button thinking it would have overridden the option passed to createForm:
// AppBundle/Form/TermType.php
// ...
$builder->add('submit', SubmitType::class, array(
            'label' => 'Submit',
            'disabled' => false
        ));
// ...

But it didn't work.  The only alternative I can think of is passing a custom option and set the disabled option in every field but the submit button with that value.  Something along these lines:
// AppBundle/Controller/DeleteEntityController.php
// ...
$form = $this->createForm(TermType::class, $term, array('is_delete_form' => true));
// ...

and
// AppBundle/Form/TermType.php
// ...
$builder->add('submit', SubmitType::class, array(
        'label' => 'Submit',
        'disabled' => $options['is_delete_form']
    ));
// ...

What's the best practice in this case?  Should I disable the fields inside the template, or should it be done from the form class?

A: it's is a good question and your solution is also a sensible one. Just remember that if you go with an additional option, it's always good to set a default value for it in configureOptions function:
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Term::class,
        // Additional option default should be defined here
    ));
}

However, if you are searching for best practice: the suggestion from Symfony is separating the button from the form class or controller (if you define your form in controller). It gives developer more flexibility and make handling the form much easier. You can find what Symfony architect say about it here: http://symfony.com/doc/current/best_practices/forms.html#form-button-configuration.

A: Your issue is interesting whether you only want to use only one form to set up the edit, create and delete views. For my part, I use to generate the crud of the class to gain some time. You directly get the edit/create/delete form, functions, and views of the class that you can tailor to your needs afterward.
You can draw one's inspiration from the method they use to only get one form once the crud is generated:
You can have the method to generate it easily here: http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html
It does not really answer your question, but it may help for another time ;)


text:
Q: Output width and heigh with transposed convolution I have an input of shape torch.Size([4, 256, 1, 5] and I want to upsample it to torch.Size([4, 256, 2, 11]) using torch.nn.ConvTranspose2d(ip_sz, op_sz, kernel_size, stride, padding, output_padding)
I tried different combinations of kernel_size, stride, padding, output_padding however, I am unable to get the desired result.
import torch
import torch.nn as nn

class Dummy(nn.Module):
    def __init__(self, ip_sz, op_sz, kernel_size=3, stride=2, padding=1, output_padding=1):
        super(Dummy, self).__init__()
        self.conv1 = nn.ConvTranspose2d(ip_sz, op_sz, kernel_size=kernel_size,
                                        stride=stride, padding=padding, output_padding=output_padding)

    def forward(self, x):
        x = self.conv1(x)
        print(x.shape)
        return x

dummy_model = Dummy(256, 256)
dummy_model(torch.rand([4, 256, 1, 5]))

A: Convolution with following parameters should work:
new_dummy = Dummy(256, 256, kernel_size=(2, 3), stride=2, padding=0, output_padding=0)


text:
Q: Function by properties I am looking for a function $f(x)$, which

*

*is vertical at the origin ($f'(0)\approx -\infty$)

*goes to zero further from the origin ($f(x) \to 0$ for $x\to \infty$ and for $x\to -\infty$)

*and is rotationally symmetric ($f(x) = -f(-x)$ for all $x$)

*is finite ($\forall x: -\infty \neq f(x)\neq \infty$)

*is differentiable ($f'(x)$ is not undefined for every $x$)

(visually this will look like one heart beat on a monitor, just to give some idea)
Of course I'd like the function to be the least complex as possible. (Furthermore it would be nice if the function would have some statistical importance.)
Do you know any function satisfying these properties?
How does one go about searching for a function, which has to satisfy such properties?
Is there any application which helps you in finding the right/best function? (Mathematica?)

A: How about $-x^\frac{1}{3} \, e^{-x^2}$?

A: How about
$$
f(x)=-\text{sgn}(x)\,\frac{\sqrt{|x|}}{1+x^2}\text{ ?}
$$
Here $\text{sgn}(x)=1$ if $x>0$, $-1$ if $x<0$ and $0$ if $x=0$. It is not differentiable at $x=0$, but you wanted $f'(0)\approx-\infty$.
More general example:
$$
f(x)=-\text{sgn}(x)\,\frac{|x|^p}{1+|x|^q}\quad 0<p<1,\quad q>p.
$$


text:
Q: Javascript Architecture/Application Structure Best Practices? Do these exist?
I've been a slave to big strongly typed OO languages (Java & C#) for many years and am a devotee of Martin Fowler and his ilk. Javascript, due to it's loosely typed and functional nature seems to not lend itself to the idioms I am used to.
What are the best practices for organizing a javascript rich client? I am interested in everything from where to keep your code, (one file or multiple files) to MVC patterns to gang of four patterns to layering.
Not putting stuff in the Global namespace seems to be the only consensus.
I am using JQuery as the "Extended API."

A: For complex Javascript development, structuring your codebase it critical in my experience. Historically being a patching language, there is a great tendency that Javascript development ending up with massive script files.
I'd recommend to logically separate the functional areas of the application in to clear modules that are loosely coupled and self contained. For example as shown below your product suite might have multiple product modules and each module with multiple sub modules:

Once you have the ability to create hierachical modules, it is a mater of creating UI components in relavant sub-module. These UI components should also preferably be self contained. Meaning each with own template, css, localization, etc. like shown below:

I created a JS reference architecture with sample code to share my expierince I gained in couple of large scale JS projects. I'm the author of boilerplateJS. If you want a reference codebase where several of the critical concerns built-in, feel fee to use it as your startup codebase.
http://boilerplatejs.org

A: One thing you might want to look into is Backbone.js which gives you a nice framework for building Model classes to represent that data in your application and bind them to your HTML UI.  This is preferred to tying your data to the DOM.
More generally, here is a great article on JavaScript best practices from the Opera development blog.

A: If we are talking about javascript apps architecture then Nicholas Zakas 2011 podcast is a must see:
  Nicholas Zakas: Scalable JavaScript Application Architecture
Also Addy Osmani's online reference:
     Patterns For Large-Scale JavaScript Application Architecture

A: I like to use a sort of MVC client side architecture.

*

*I have a page CONTROLLER

*The DOM is my VIEW

*The server is my MODEL

Typically I create a singleton page controller class (with supporting classes off that is needed) that controls the ajax calls and view binding.
var pageXController = {
  init: function(param) {
    pageXController.wireEvents();
    // something else can go here
  },

  wireEvents : function() {
    // Wire up page events
  }

  // Reactive methods from page events
  // Callbacks, etc
  methodX : function() {}
}

$(document).ready( function() {
  // gather params from querystring, server injection, etc
  pageXController.init(someparams);
});

I should also add here that your MODEL in this case is your DTO's (Data Transfer Objects) which are optimised to the problem they solve. This is NOT your domain model.


text:
Q: Fine tuning PIG for local execution I'm using PIG latin for log processing because its expressiveness in a problem where the data is not big enough to worry about setting up a whole hadoop cluster. I'm running PIG in local mode but I think that it isn't using all the cores it has available (16 at the moment), monitoring the CPU shows 200% of CPU usage at maximum.
Is there any tutorial or recommendations for fine tuning PIG for local execution? I'm sure that all the mappers could use all the available cores with some easy tweaking. (In my script I have already set up the default_parallel parameter to 20)
Best regards.

A: Pig's documentation makes it clear that local operation is intended to be run single-threaded, taking different code paths for certain functions that would otherwise use distributed sort. As a result, optimizing for Pig's local mode seems like the wrong solution to the presented problem.
Have you considered running a local, "pseudo-distributed" cluster instead of investing in full cluster setup? You can follow Hadoop's instructions for pseudo-distributed operation, then point Pig at localhost. This would have the desired result, at the expense of two-step startup and teardown.
You'll want to raise the number of default mappers and reducers to consume all cores available on your machine. Fortunately, this is reasonably well-documented (admittedly, in the cluster setup documentation); simply define mapred.tasktracker.map.tasks.maximum and mapred.tasktracker.reduce.tasks.maximum in your local copy of $HADOOP_HOME/conf/mapred-site.xml.


text:
Q: Are std::strings good at random insertion / random erasing? I want to make a simple text editor using std::strings. If my text is 500,000 characters and I want to insert or remove at the 253,000th character, will this be slow, or will it be just as fast as if my text contained 10 characters? Otherwise I'm not sure what I'll do to fix it (unless I use a linked list but then reading is slow and it is sort of reinventing the wheel.
Thanks

A: I've never used it myself, but I believe this is what rope is for.

A: It will likely be slow since it has to copy the memory. It depends on the internal implementation of your operating system/processor and its memory operations.

A: In practice, it will probably be "fast enough".  However, I'd
still write a EditBuffer class, encapsulating it, and giving
this new class an interface tuned to my application.  That way,
the fact that I'm using std::string, and not something else,
becomes an implementation detail of EditBuffer, which can be
changed at any time.  (You might want to try std::vector
as well.  And one common optimization is maintaining a hole at
the cursor: the text behind the cursor is at the end of the
buffer.  Advancing the cursor means moving one character, but
insertion is normally in constant time.)

A: It's likely to be slow, though whether or not it is slow enough to be an issue is something you'll have to test. One alternate implementation is to use a list of strings, one per line of text.

A: This is the wrong type.
Insertion (not at the end) on a std::string has a complexity of O(n).
You want a structure that has average complexity for insertion/deletion/modification of O(1).
ie. the cost of insertion should not be related to the size of the data.

A: Considering that memory bandwidth is given in GB/s
http://en.wikipedia.org/wiki/DDR3_SDRAM
how long would you estimate copying 256k would take?

A: I'd seriously consider storing the text not as a single large string, but as individual lines. std::list<std::string> or std::vector<std::string> would seem appropriate. Such an approac would effectively distribute your large string over multiple smaller ones, and reallocations upon modification would only ever occur to the individual line, or to the array of lines in itself. The only tradeoff you'd have to choose is between std::vector and std::list, although I'd tend to prefer std::list here.
Another advantage of line-wise approach is when reading files, you can easily read line by line with std::getline and won't have to care about read buffers yourself.