Q:

cURL get url from redirect

I'm currently using cURL to try and get the URL from a redirect for a website scraper. I only need the url from the website. I've researched on stackoverflow and other sites for the past couple days and have been unsuccessful. The code I'm currently using is from this website:
  $url = "http://www.someredirect.com";
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  $response = curl_exec($ch);
  preg_match_all('/^Location:(.*)$/mi', $response, $matches);
  curl_close($ch);
  echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

Any help would be greatly appreciated!

A:

In your particular case, the server is checking for certain user-agent strings.
When a server checks the user-agent string, it will only respond with a 302 redirect status code when the server sees a "valid" (according to the server) user-agent. Any "invalid" user-agents will not receive the 302 redirect status code response or Location: header.
In your particular case, when the server receives a request from an "invalid" user-agent it responds with a 200 OK status code with no text in the response body.
(Note: in the code below, the actual URLs provided have been replaced with examples.)
Let's say that http://www.example.com's server checks the User-Agent string and that http://www.example.com/product/123/ redirects to http://www.example.org/abc.
In PHP your solution would be:
<?php

$url = 'http://www.example.com/product/123/';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0"); // Necessary. The server checks for a valid User-Agent.
curl_exec($ch);

$response = curl_exec($ch);
preg_match_all('/^Location:(.*)$/mi', $response, $matches);
curl_close($ch);

echo !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

And, the output of this script would be: http://www.example.org/abc.

A:

Try using this code:
function curl_last_url(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
$mr = $maxredirect === null ? 5 : intval($maxredirect);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    if ($mr > 0) {
        echo $mr;
        echo $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

        $rch = curl_copy_handle($ch);
        curl_setopt($rch, CURLOPT_HEADER, true);
        curl_setopt($rch, CURLOPT_NOBODY, true);
        curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
        curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
        do {
            curl_setopt($rch, CURLOPT_URL, $newurl);
            $header = curl_exec($rch);
            if (curl_errno($rch)) {
                $code = 0;
            } else {
                $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                echo $code;
                if ($code == 301 || $code == 302) {
                    preg_match('/Location:(.*?)\n/', $header, $matches);
                    $newurl = trim(array_pop($matches));
                } else {
                    $code = 0;
                }
            }
        } while ($code && --$mr);
        curl_close($rch);
        if (!$mr) {
            if ($maxredirect === null) {
                trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
            } else {
                $maxredirect = 0;
            }
            return false;
        }
        curl_setopt($ch, CURLOPT_URL, $newurl);
    }
return $newurl;

}


Q:

TransformJsx.proj Error

I am adding ReactJS to a new ASP.NET MVC site, that I have been working on. From NuGet, I installed the "ReactJS.Net (MVC 4 and 5)" package.  When I tried running the the code, I get errors pointing to the TransformJsx.proj on the element "TransformJsx".
    <?xml version="1.0" encoding="utf-8" ?>
    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="TransformJsx">
       <!-- ReactJS.NET - Transforms JSX to JavaScript -->
       <UsingTask AssemblyFile="$(OutputPath)\React.MSBuild.dll" TaskName="TransformJsx" />
       <Target Name="TransformJsx">
          <TransformJsx SourceDir="$(MSBuildProjectDirectory)" />
       </Target>
    </Project>

the errors are

The "TransformJsx" task failed unexpectedly. C:\Users\310171329\Documents\Visual Studio 2013\Projects\TeamManagement\TeamManagement\TransformJsx.proj    6   3   TeamManagement
React.Exceptions.JsxException: Parse Error: Line 9: Unexpected token > (at line 9 column 25) ---> JavaScriptEngineSwitcher.Core.JsRuntimeException: Parse Error: Line 9: Unexpected token > (at line 9 column 25) ---> MsieJavaScriptEngine.JsRuntimeException: Parse Error: Line 9: Unexpected token > (at line 9 column 25)    C:\Users\310171329\Documents\Visual Studio 2013\Projects\TeamManagement\TeamManagement\TransformJsx.proj    6   3   TeamManagement

any help would be greatly appreciated

A:

This normally means there's a syntax error in your JavaScript file. Did you try looking at what's at line 9 character 25 of the .js file?


Q:

User SSH into folder but can nano into any upper folder?

I did useradd -s /bin/rbash -d /var/www/html/directory USRNAME
and on ssh login with USRNAME (including ssh key), it goes to directory and cd doesnt go back. So that works... but
if they use nano /var/www/html/.env (before directory) it will say
Unable to create directory /var/www/html/directory/.local/share/nano/: Permission denied
It is required for saving/loading search history or cursor positions.

Press Enter to continue

If they press enter it will allow them to read any file with nano.. anywhere in the system!
Any help to only allow this user to that specific directory only using google cloud?

A:

rbash is not a secure method for restricting shell users. It only limits shell inputs and not filesystem access for executables. On a standard linux system there are plenty of tools accessible in the $PATH to work around those restrictions, not only nano.
Proper restricted access is done by creating a chroot environment or jail, but which also requires providing all needed executables and potentially even /dev, /sys, or /proc hardlinks.
You could modify $PATH to only include safe commands, but that's a minefield and essentially also requires you to create a separate collection of executables.
The error you're seeing is likely related to the user not being allowed to write to /var/www/html/directory, but is unrelated to the actual issue at hand.


Q:

Is a bad NFS mount preventing a clean boot?

I'm on Ubuntu server (I think it's 12.04, but not positive) and I basically ran into this problem here Unmount a nfs mount where the nfs server has disappeared
The umount command didn't work, so I tried to just use the ol' reboot. Now the machine gets an error when booting:
FS-Cache:netfs 'nfs' registered for caching
<two minutes later>
init: udevtrigger post-stop process (345) terminated with status 1

I tried booting in recovery mode so I could just comment out the bad NFS mount in my /etc/fstab file, but I wasn't able to write the changes.
I basically just want to get the machine booting properly again so that I can erase the bad mount point, either order is fine.
What are my options here?

A:

I got into recovery mode and ran mount -o remount,rw / which allowed me to get rid of my bad NFS mounts in /etc/fstab (and I prevented further issues by adding the intr option to the NFS entries), but then my boot (in non-recovery) seemingly got worse -- I got no output on the screen after selecting normal boot from the GRUB menu!
I then added nomodeset to the GRUB_CMDLINE_LINUX_DEFAULT boot option list and everything worked.
I have no idea how those two were related, but that's what fixed the issue.


Q:

How can I retrieve contacts/emails from things like MSN, Twitter, Facebook, GMail , etc...?

I'm building an application that gives users the option to send out an email notification to their friends.
The options I would like to give them for this are to:

manually write down which emails they would like to send to
choose contacts from a list of ones already in the database for that user
choose all contacts from facebook, twitter, digg, gmail, or msn to send the email to

Is there any way I can retrieve all of the email addresses for a certain contact from these different websites?
For example, if I chose the option to send out email notification and I wanted to send it to all of my friends on my facebook account, how could I do this? (Remembering that the user is interacting with a completely separate website and should not have to go onto facebook to send this emails)
Any ideas?
Thanks in advance for your help!
Matt

A:

Google contacts api: http://code.google.com/apis/contacts/
Windows Live contacts api: http://msdn.microsoft.com/en-us/library/bb463989.aspx
Facebook's apis are here: http://wiki.developers.facebook.com/index.php/API


Q:

Polite alternative to the term "bitch" when referring to a female dog

I'm writing an example of constructing logic, and I need to differentiate between an adult female dog, an adult male dog and a puppy and am searching for polite terms.
Unfortunately, the word "bitch" has impolite connotations, so I'd rather not use it, but I'm not sure of any other terms for a female dog. Likewise, I don't know of a gendered term for a a male dog, apart from 'dog'.
Given the linguistic baggage that the term 'bitch' has in non-specialist areas, is there an alternative, polite term for a 'female dog'?
For context: in the logic I'm describing, if the dog is young it is a 'puppy', otherwise if it's female it's a 'term X', or if it's male it is a 'term Y'.

A:

I think the obvious answer (the one you already know!) is the best:

You can refer to a female dog as a female dog.
You can refer to a male dog as a male dog.

Of course, if you really need to specify that they're adults, you could do that:

An adult male dog could be referred to as an adult male.
An adult female dog could be referred to as an adult female.

In circles where bitch is commonly used, I think dog is the male counterpart, believe it or not.  Those two words would be the right answer, I think, if you hadn't ruled them out.
(My apologies if you're looking for something more esoteric.)

A:

If you are referring to a breeding pair and offspring, you can use dam and sire instead of bitch and dog.

However, the best answer may be to use a different animal for your example. While many animal terms can be applied pejoratively to humans, few will provoke a visceral reaction like bitch can.
Pigs and horses make good examples because they both have separate, familiar terms for the species, adult males, adult females, and offspring, analogous to human, man, woman, and baby:
Pig: boar, sow, piglet
Horse: stallion, mare, foal
If you decide that you also need terms for young males and females, analogous to boy and girl, horses are a perfect fit with colt and filly.

A:

It is not at all impolite to refer to a female dog as a bitch if in fact you mean female dog. It will be clear that you don't mean bitch the pejorative through context.
If you don't like using male dog and female dog, you could use stud for the male. You put a male out to stud when you breed it and that word is used for other male animals.
But I believe bitch and dog are the equivalents of hen and rooster strictly speaking about analogues for sex of course (obviously they are different types of animals).


Q:

Asynchronous indexing by Hibernate Search (HS) after transaction commit

There is REST service which searches and updates data, backed by Hibernate and HS. Lucene index has more than 1.5 million documents and growing.
Problem: when service persists updated data into database (session.commit()) - same time HS performs data indexation, As result transaction is committed with a delay (2-5 seconds) - so HTTP response is delayed for data update requests. REST service has a lot of methods and the client side which exists for this service expects that after AJAX call returns - data is available for a 'GET', so committing transaction in async manner on server side - is not an option (data won't be available for client right after POST).
I'm using hibernate.search.default.worker.execution=async but this setting helps not much (improvement is about 1 second with it). The reason is that HS gathering data for updated/created documents using current session/thread and then indexing asynchronously to Lucene..
So my questions are:
1. Is there a way to perform data computation by HS asynchronously to main execution thread? So transaction commit is not frozen for the time of data collection..
2. I suppose that with my issue using JMS with Master/Slave won't help much because bottleneck is not indexing itself - but gathering of data to index?

A:

There currently isn't such an option.
In similar situations, I managed to optimise the data access of Hibernate as 2-5 seconds is not very impressive, for example  looking into 2nd level caching, make unnecessary relations lazy (and necessary relations eager). Remember to never make a cached relation eager, or it won't use the cache.
In case you're new to Hibernate, know that it might be optimised so to do operations in just a couple of milliseconds; I appreciate though that you might already be an expert and just have lots of complex data, as of course there are limits of what you can obtain with optimisations and then it's fair to look at different patterns.
We could think of making a fully async indexing process but it's quite complex: after you terminate the current transaction, we'd be reading a potentially inconsistent state. A solution would be to re-read the whole object graph in a new transaction: after your transaction is committed, open a new one in a clean session and re-load all necessary data.
It's probably an interesting option to have, but chances are high that your server and databases would suffer from all the additional work such a pattern creates.
I've filed some design thoughts as https://hibernate.atlassian.net/browse/HSEARCH-2364


Q:

adobe flash player update

I have been trying to figure out how to update the Adobe Flash player for Ubuntu 12.04. I am using Firefox 35 as a browser. I have tried to simply download the tar.gz file from the Adobe site, but there is no install file in the folder. I converted the tag.gz file to DEB and installed it and restarted Firefox with no luck. It seems as though it didnt install. I also read links about ubuntu-restricted-extras but that prompted me to remove many dependencies and other applications that I enjoy & still need. I also read about Flashaid which has been discontinued.
I have checked in about:config in Firefox and got the following results:

Shockwave Flash
File: libflashplayer.so
Path:/usr/lib/flashplugin-installer/libflashplayer.so
Version:11.2.202.425  State: Enabled (STATE_VULNERABLE_UPDATE_AVAILABLE) Shockwave Flash 11.2 r202

Is there an easy way to simply just update the Flashplayer? I tried using synaptec package manger with no success.

A:

What version of flash do you need to upgrade to? Unforunately the Adobe Flash Player about page states that only only Chrome/ium supports versions of flash higher than 11.2.
You could have a look into installing the Fresh Player Plugin. I haven't used this so I'm not 100% certain it will work for you.
As a last resort you can install Chromium from the Ubuntu Software Center by just searching for chromium and then installing it. Alternatively you can install Google Chrome by downloading the .deb file then double clicking it once it has downloaded, from there it will install in the software center. I personally use Chrome and flash works absolutely fine for me.
Hope this has helped you.


Q:

whatis similar to RotateToLeft in c#?

in java there is a function called rotatetoleft that generate a nunmber generated
int n;
n = Integer.rotateLeft(1, 5);
System.out.print(n);

output; 32
what is similar to this in c# ?

A:

It sounds like you're just after the << operator, but that only performs a left-shift; it won't rotate into the LSB. To do that, you'd have to do a mixture of shifts and ORs. For example:
static int RotateLeft(int value, int shift)
{
    return (value << shift) | (value >> (32 - shift));
}

Note that this won't quite work properly if value has its top bit set due to sign extension on the shift right. You can fix that by doing the arithmetic in uint:
static int RotateLeft(int value, int shift)
{
    unchecked
    {
        uint uvalue = (uint) value;
        uint uresult = (uvalue << shift) | (uvalue >> 32 - shift);
        return (int) uresult;
    }
}


Q:

Inserting multiple rows at once with prepared statements

I would like to know how can I insert multiple values in an array via prepared statements. I've looked at these two (this question and this other one ) questions but they don't seem to do what I'm trying. This is what I have:
$stmt = $this->dbh->prepare("INSERT INTO
t_virtuemart_categories_en_gb
(category_name, virtuemart_category_id)
VALUES
(:categoryName, :categoryId)
;");

foreach($this->values as $insertData){
    $categoryName = $insertData['categoryName'];
    $categoryId = $insertData['categoryId'];
    $stmt->bindParam(':categoryName', $categoryName);
    $stmt->bindParam(':categoryId', $categoryId);
    $stmt->execute();
}

I tried placing the prepare line inside the foreach loop and outside, but it only adds the first key in the array, and I don't understand why.
This is my Connection.php file:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';

function connectDB ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
return $dbh;
}

try {
$dbh = connectDB ($hostname, $username, $password);
} catch(PDOException $e) {
echo $e->getMessage();
}

And my Import.php file:
<?php
class Import{
public function __construct($dbh, $values) {
    $this->dbh = $dbh;
    $this->values = $values;
}

public function importData() {
    $stmt = $this->dbh->prepare("INSERT INTO
    t_virtuemart_categories_en_gb
    (category_name, virtuemart_category_id)
    VALUES
    (:categoryName, :categoryId)
    ;");

    foreach($this->values as $insertData){
        $categoryName = $insertData['categoryName'];
        $categoryId = $insertData['categoryId'];
        $stmt->bindParam(':categoryName', $categoryName);
        $stmt->bindParam(':categoryId', $categoryId);
        $stmt->execute();
    }
}

}

A:

Working principle:
Use only one INSERT sql statement to add multiple records, defined by your values pairs. In order to achieve this you have to build the corresponding sql statement in the form
INSERT INTO [table-name] ([col1],[col2],[col3],...) VALUES (:[col1],:[col2],:[col3],...), (:[col1],:[col2],:[col3],...), ...

by iterating through your values array.
Notes:

I hope you'll understand all. I commented as much as I could. I
didn't test it, but it should work. Maybe an answer I wrote a
short time ago will give you further ideas regarding structuring of
data access classes/functions as well.
Never use ";" at the end of the sql statements when you define them in PHP.
Never use one input marker to bind multiple values. For each value to bind use a unique named input marker.

Good luck.
Connection.php
<?php

$hostname = 'localhost';
$username = 'root';
$password = '';
$port = 3306;

try {
    // Create a PDO instance as db connection to a MySQL db.
    $connection = new PDO(
            'mysql:host='. $hostname .';port='.$port.';dbname=test'
            , $username
            , $password
    );

    // Assign the driver options to the db connection.
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    $connection->setAttribute(PDO::ATTR_PERSISTENT, TRUE);
} catch (PDOException $exc) {
    echo $exc->getMessage();
    exit();
} catch (Exception $exc) {
    echo $exc->getMessage();
    exit();
}

Import.php:
<?php

class Import {

    /**
     * PDO instance as db connection.
     *
     * @var PDO
     */
    private $connection;

    /**
     *
     * @param PDO $connection PDO instance as db connection.
     * @param array $values [optional] Values list.
     */
    public function __construct(PDO $connection, array $values = array()) {
        $this->connection = $connection;
        $this->values = $values;
    }

    /**
     * Import data.
     *
     * @return int Last insert id.
     * @throws PDOException
     * @throws UnexpectedValueException
     * @throws Exception
     */
    public function importData() {
        /*
         * Values clauses list. Each item will be
         * later added to the sql statement.
         *
         *  array(
         *      0 => '(:categoryName0, :categoryId0)',
         *      1 => '(:categoryName1, :categoryId1)',
         *      2 => '(:categoryName2, :categoryId2)',
         *  )
         */
        $valuesClauses = array();

        /*
         * The list of the input parameters to be
         * bound to the prepared statement.
         *
         *  array(
         *      :categoryName0 => value-of-it,
         *      :categoryId0 => value-of-it,
         *      :categoryName1 => value-of-it,
         *      :categoryId1 => value-of-it,
         *      :categoryName2 => value-of-it,
         *      :categoryId2 => value-of-it,
         *  )
         */
        $bindings = array();

        /*
         * 1) Build a values clause part for each array item,
         *    like '(:categoryName0, :categoryId0)', and
         *    append it to the values clauses list.
         *
         * 2) Append each value of each item to the input
         *    parameter list.
         */
        foreach ($this->values as $key => $item) {
            $categoryName = $item['categoryName'];
            $categoryId = $item['categoryId'];

            // Append to values clauses list.
            $valuesClauses[] = sprintf(
                    '(:categoryName%s, :categoryId%s)'
                    , $key
                    , $key
            );

            // Append to input parameters list.
            $bindings[':categoryName' . $key] = $categoryName;
            $bindings[':categoryId' . $key] = $categoryId;
        }

        /*
         * Build the sql statement in the form:
         *  INSERT INTO [table-name] ([col1],[col2],[col3]) VALUES
         *  (:[col1],:[col2],:[col3]), (:[col1],:[col2],:[col3]), ...
         */
        $sql = sprintf('INSERT INTO t_virtuemart_categories_en_gb (
                    category_name,
                    virtuemart_category_id
                ) VALUES %s'
                , implode(',', $valuesClauses)
        );

        try {
            // Prepare the sql statement.
            $statement = $this->connection->prepare($sql);

            // Validate the preparing of the sql statement.
            if (!$statement) {
                throw new UnexpectedValueException('The sql statement could not be prepared!');
            }

            /*
             * Bind the input parameters to the prepared statement
             * and validate the binding of the input parameters.
             *
             * -----------------------------------------------------------------------------------
             * Unlike PDOStatement::bindValue(), when using PDOStatement::bindParam() the variable
             * is bound as a reference and will only be evaluated at the time that
             * PDOStatement::execute() is called.
             * -----------------------------------------------------------------------------------
             */
            foreach ($bindings as $key => $value) {
                // Read the name of the input parameter.
                $inputParameterName = is_int($key) ? ($key + 1) : (':' . ltrim($key, ':'));

                // Read the data type of the input parameter.
                if (is_int($value)) {
                    $inputParameterDataType = PDO::PARAM_INT;
                } elseif (is_bool($value)) {
                    $inputParameterDataType = PDO::PARAM_BOOL;
                } else {
                    $inputParameterDataType = PDO::PARAM_STR;
                }

                // Bind the input parameter to the prepared statement.
                $bound = $statement->bindValue($inputParameterName, $value, $inputParameterDataType);

                // Validate the binding.
                if (!$bound) {
                    throw new UnexpectedValueException('An input parameter could not be bound!');
                }
            }

            // Execute the prepared statement.
            $executed = $statement->execute();

            // Validate the prepared statement execution.
            if (!$executed) {
                throw new UnexpectedValueException('The prepared statement could not be executed!');
            }

            /*
             * Get the id of the last inserted row.
             */
            $lastInsertId = $this->connection->lastInsertId();
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            // Only in development phase !!!
            // echo '
' . print_r($exc, TRUE) . '
';
            exit();
        } catch (Exception $exc) {
            echo $exc->getMessage();
            // Only in development phase !!!
            // echo '
' . print_r($exc, TRUE) . '
';
            exit();
        }

        return $lastInsertId;
    }

}


Q:

Load image into canvas using a generic handler

is it possible to load an image directly into a canvas control using a generic handler without using the image element?
This is my handler:
    public void ProcessRequest(HttpContext context)
    {
        context.Response.AddHeader("Access-Control-Allow-Origin", "*");
        context.Response.ContentType = "image/jpeg";
        var camIndex = Convert.ToInt16(context.Request.QueryString["camIndex"]);
        context.Response.BinaryWrite( Shared.Feeder[camIndex].JpegData);
    }

My JavaScript:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/Media/FrameHandler.ashx?camIndex=' + camIndex, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    var uInt8Array = new Uint8ClampedArray(this.response);
    imageData[camIndex].data.set(uInt8Array);
    ctxLiveViews[camIndex].putImageData(imageData[camIndex], 0, 0);
};
xhr.send();

which gives me this image (which is obviously wrong)

A:

Is it possible to load an image directly into a canvas control using a generic handler without using the image element?

It is, but you are in for a hand-full as you will need to manually parse the image file format yourselves (with all the various combinations of image format, color model etc. and error checks and so forth). It's doable (been there done that), but chances are, unless you need to access some special data or bitmap formats, that the browser will do the job at least faster than a manual approach in JavaScript.
Using an Image element is easy and does all these steps for you in compiled code.
This line:
var uInt8Array = new Uint8ClampedArray(this.response);

will only hold the original file bytes, uncompressed, undecoded including header, chunks and metadata. While putImageData() require a raw bitmap in the format RGBA per pixel. This is why you see the noise as the data being fed to putImageData is the file itself, not a bitmap.


Q:

Efficient foreach child evaluation in parallel

I have a list of objects, each with a bool ShouldRun() method on them.
I am currently iterating over the list of objects, and checking ShouldRun() on each object, and calling Run() on the first one to return true
foreach (child in Children)
{
   if (child.ShouldRun())
   {
      child.Run();
      break;
    }
 }

I would like to do this in parallel, because evaluating shouldRun can take a decent amount of time, and it is advantageous to let later elements in the collection start their evaluation early.
However, I cannot think of a way to do this that will satisfy these conditions :
1 Only run one item
2 Do not run a later item if an earlier item is true, or has not finished evaluating yet
3 If all "earlier" items have returned false, and a middle item returns true, do not wait on a  later item to finish evaluating because you know it can't override anything earlier.
I thought of doing a parallel "where" linq query to retrieve all the items that shouldRun() and then sorting, but this will violate condition #3
Ideas?
Background info :
The system is for a generalized robotics AI system.
Some of the higher priority tasks can be triggered by immediately known sensor variables  eg : Im falling over, fix it!
other tasks might be computationally intensive (do image recognition from the camera, and approach visible objectives)
other tasks might be database or remotely driven (look up a list of probable objective locations from a database, and then navigate there to see if you can get into visible range of one of them)
Some of the tasks themselves have child tasks, which is essentially going to start this process over recursively at a subset of tasks, and the grandchild task will be passed up through the chain

A:

I'm not a PLINQ genius, but wouldn't this simpler answer suffice?
var childToRun = Children.AsParallel().AsOrdered()
    .Where(x => x.ShouldRun()).FirstOrDefault();
childToRun.Run();


Q:

How to access Canvas.Left property of a StackPanel in code?

suppose I have the following XAML:
<Canvas Grid.Column="3" HorizontalAlignment="Right" >

    <StackPanel Name="myStackPanel" Canvas.Left="80">

    </StackPanel>
</Canvas>

How can I access/modify the Canvas.Left property of the StackPanel in code?
Simply writing
myStackPanel.Left // not a property of StackPanel

doesn't work

A:

Just figured it:
Canvas.SetLeft(myStackPanel, newValue);


Q:

Hiding output from console

My code contains a command which is essential for it to run, however it ends up showing the result of this command in the console, i have tried to use suppressWarnings(), suppressMessages(), invisible() and sink() but all of these still show the result.
Here is an example data set and where the problem originates from:
M<-c(1111,1222,1333,1444,1555,1666,1777,2223,6654,9867,1123,1456,2436,6875)
fstAdi <- ets(ts(rep(M,length = length(M)), deltat= 1/4, start = c(8,1)), model = "AAA", damped = FALSE, opt.crit = "mae", ic="aic", lower = c(0, 0, 0, 0), upper = c(0.999, 0.999, 0.999, 0.999), bounds = "admissible", restrict = FALSE)
mae11Ad<-summary(fstAdi)[,"MAE"]

The last line of the code above always shows the summary in the console, which when automating this for a report causing problems. Does anyone know of a command which can stop this happening?
Thankyou
I have found a way to hide it while automating the report, but if anyone knows how to hide it while just running the code to make the process quicker then that would be really helpful anyway :)

A:

The summary method for ets objects is a bit verbose:
> forecast:::summary.ets
function (object, ...)
{
    print(object)
    cat("\nTraining set error measures:\n")
    print(accuracy(object))
}
<bytecode: 0x161d31c8>
<environment: namespace:forecast>

This is pretty bad style, summary methods should return an object with a class and the print method for that class should produce the output.
So you could just call the accuracy method on your object:
> accuracy(fstAdi)[,"MAE"]
[1] 1971.468

which has the advantage of not needing any diversion of output and is more readable.

A:

sink does work, how exactly are you using it? Try for example
M<-c(1111,1222,1333,1444,1555,1666,1777,2223,6654,9867,1123,1456,2436,6875)
fstAdi <- ets(ts(rep(M,length = length(M)), deltat= 1/4, start = c(8,1)), model = "AAA", damped = FALSE, opt.crit = "mae", ic="aic", lower = c(0, 0, 0, 0), upper = c(0.999, 0.999, 0.999, 0.999), bounds = "admissible", restrict = FALSE)
sink(tempfile())
mae11Ad<-summary(fstAdi)[,"MAE"]
sink()


Q:

debugging long running PHP script

I have php script running as a cron job, extensively using third party code. Script itself has a few thousands LOC. Basically it's the data import / treatment script. (JSON to MySQL, but it also makes a lot of HTTP calls and some SOAP).
Now, performance is downgrading with the time. When testing  with a few records (around 100), performance is ok, it is done in a 10-20 minutes. When running whole import (about 1600 records), mean time of import of one record grows steadily, and whole thing takes more than 24 hours, so at least 5 times  longer than expected.
Memory seems not to be a problem, usage growing as it should, without unexpected peaks.
So, I need to debug it to find the bottleneck. It can be some problem with the script, underlying code base,  php itself, database, os or network part. I am suspecting for now some kind of caching somewhere which is not behaving well with a near 100 % miss ratio.
I cannot use XDebug, profile file grows too fast to be treatable.
So question is: how can I debug this kind of script?
PHP version: 5.4.41
OS: Debian 7.8
I can have root privileges if necessary, and install the tools. But it's the production server and ideally debugging should not be too disrupting.

A:

Yes its possible and You can use Kint (PHP Debugging Script)
What is it?
Kint for PHP is a tool designed to present your debugging data in the absolutely best way possible.
In other words, it's var_dump() and debug_backtrace() on steroids. Easy to use, but powerful and customizable. An essential addition to your development toolbox.
Still lost? You use it to see what's inside variables.

Act as a debug_backtrace replacer, too

you can download here or Here
Total Documentations and Help is here
Plus, it also supports almost all php framework

CodeIgniter
Drupal
Symfony
Symfony 2
WordPress
Yii
framework
Zend Framework

All the Best.... :)

A:

There are three things that come to mind:

Set up an IDE so you can debug the PHP script line by line
Add some logging to the script
Look for long running queries in MySQL

Debug option #2 is the easiest. Since this is running as a cron job, you add a bunch of echo's in your script:
<?php

function log_message($type, $message) {
    echo "[{strtoupper($type)}, {date('d-m-Y H:i:s')}] $message";
}

log_message('info', 'Import script started');

// ... the rest of your script

log_message('info', 'Import script finished');

Then pipe stdout to a log file in the cron job command.
01 04 * * * php /path/to/script.php >> /path/to/script.log

Now you can add log_message('info|warn|debug|error', 'Message here') all over the script and at least get an idea of where the performance issue lies.
Debug option #3 is just straight investigation work in MySQL. One of your queries might be taking a long time, and it might show up in a long running query utility for MySQL.

A:

Use strace to see what the program is basically doing from the system perspective. Is it hanging in IO operations etc.? strace should be the first thing you try when encountering performance problems with whatever kind of Linux application. Nobody can hide from it! ;)
If you should find out that the program hangs in network related calls like connect, readfrom and friends, meaning the network communication does hang at some point while connecting or waiting for responses than you can use tcpdump to analyze this.
Using the above methods you should be able to find out most common performance problems. Note that you can even attach to a running task with strace using -p PID.

If the above methods doesn't help, I would profile the script using xdebug. You can analyse the profiler output using tools like KCachegrind


Q:

Angular 2 RC with express server instead of lite server

I would like to create single page application with latest angular 2 rc and express server.I don't know how to link both with out bower,gulp and webpack.
There are some starter pack available but can't get the expected one.Please guide me

A:

The question is really broad but here's a github starter projects link with express and rc.1: Angular 2 starter project with express
The server identifies index.html from app.use( express.static(__dirname + '/client' ) ); line. This means look for a file that is named index.html under client directory.
You can add aditional routes for backend to routes.js. For client side, like navigating through the pages and stuff I suggest you to take a look at angular2's routing tutorial/documentation: http://angular.io/docs/ts/latest/tutorial/toh-pt5.html


Q:

Open an ASP.Net page containing a Wizard at a different WizardStep to the default starting step?

I've got an ASP.Net Forms page containing the following (simplified) <asp:Wizard /> control. I now need to modify this page so that when it is loaded, it loads showing the final step.
Is this possible to do without re-arranging the Wizard steps (Which I'd rather not do)?
<asp:UpdatePanel runat="server" ID="updpanHeader" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Wizard ID="Wizard1" runat="server" DisplaySideBar="false"
          Style="width: 100%"
          NavigationStyle-CssClass="invisible"
          OnNextButtonClick="Wizard1_NextButtonClick"
          OnActiveStepChanged="Wizard1_ActiveStepChanged">
            <WizardSteps>
                <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1"
                  StepType="Start">
                    ... wizard form controls for page 1 ...
                </asp:WizardStep>
                <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2"
                  StepType="Step">
                    ... wizard form controls for page 2 ...
                </asp:WizardStep>
                <asp:WizardStep ID="WizardStep3" runat="server" Title="Step 3"
                  StepType="Step">
                    ... wizard form controls for page 3 ...
                </asp:WizardStep>
            </WizardSteps>
        </asp:Wizard>
    </ContentTemplate>
</asp:UpdatePanel>

I've tried swapping the StepType of the first and last steps.
I've also tried changing the ActiveStepIndex in the Page_Load and Page_LoadComplete methods, which does work..
void Page_Load(object sender, EventArgs e)
{
    Wizard1.ActiveStepIndex = (Wizard1.WizardSteps.Count - 1);
}

..but causes Internet Explorer to show a script warning: "An error has occurred in the script on this page. Error: Object expected"
Thanks for your help!

A:

I could be wrong, but I think you want to activate the index using an OnInit override, otherwise all post-backs are going to trigger the Page_Load.
Also, I believe you want to use the MoveTo command instead of setting the index. The downfall is you have to use the step's object, but you can get that easily from Wizard.WizardSteps I believe.
e.g.
private override void OnInit(EventArgs e)
{
  this.Wizard1.MoveTo(this.WizardStep3);

  base.OnInit(e);
}

I may be wrong here though... Please someone correct me if I am.


Q:

InstantiationException on newInstance of generated anonymous class

Update: this is more-or-less a dupe, and it turns out to be compiler magic adding a constructor to pass in the local variable in build2.
Given an interface like such:
public interface IFoo {
     public int get();
   }
The code below prints 1, 1, 2 and then throws an exception when trying to call getClass().newInstance() on the value returned by build2, but does not when calling the same on the returned value of build1. Any ideas why?
public class Foo {

 public static IFoo build1() {
  return new IFoo() { public int get() { return 1; } };
 }

 public static IFoo build2(final int v) {
  return new IFoo() { public int get() {return v;} };
 }

 public static void main(String[] args) throws Exception {
  IFoo foo, bar;

  foo = build1();
  System.out.println(foo.get());

  bar = foo.getClass().newInstance();
  System.out.println(bar.get());

  foo = build2(2);
  System.out.println(foo.get());

  bar = foo.getClass().newInstance();
  System.out.println(bar.get());
 }
}

My debugger indicates that in the newInstance() call, getConstructor0 is throwing a NoSuchMethodException.

A:

Here's what happens:

newInstance() requires a nullary constructor
when you create an anonymous class that is accessing a final variable, a field is actually implicitly created to hold this value, which is initially passed to its implicit constructor
thus, the IFoo created in build2 does NOT actually have a nullary constructor

Here's a snippet to show what's going on:
import java.lang.reflect.*;
public class Foo {
    interface IFoo { public int get(); }

    public static IFoo build2(final int v) {
        return new IFoo() { public int get() {return v;} };
    }
    public static void main(String[] args) throws Exception {
        Class<?> klazz = build2(42).getClass();
        for (Constructor<?> c : klazz.getDeclaredConstructors()) {
            System.out.println(c);
        }
        // prints: Foo$1(int)
    }
}

It shows that Foo$1 (the assigned binary name for the anonymous IFoo class) has only one constructor, and it takes an int. This is how it can return v, because what's returned is actually whatever is assigned to the implicitly created field by this implicitly created constructor.
It is instructive to decompile the Foo$1 (using e.g. javap -c) to see what bytecode gets generated. You will see that in fact this is what happens when a final variable is accessed by an anonymous class.
Related questions

Why am I having this InstantiationException in Java when accessing final local variables?


Q:

Splitting code from form operations in C#

I have a large (at least for me - approximately 10k lines) project that is written in C#. I have a treeview object on the left of my form and i have many nodes on my treeview. When i click a node, i bring up a panel on the right side of form. Since i only do GUI item operations (filling textboxes, clicking buttons, showing images on pictureboxes etc.), i write all of my code into MainForm class. This seems not very good but on the other side, i think i have to write into MainForm class because all of my job is to evaluate form items on panels. What should i do to write a more portable or understandable code? Do i have to write into MainForm class or do i have some options or methods to implement?

A:

GUI classes can quickly grow into a ball of mud if they're not managed carefully.  Simple refactoring will do the trick.  Some tips:

Push everything that's not directly related to the GUI into separate classes.
Refactor as much of the remaining code as possible out of the event handlers into their own methods.
Use #regions to separate the event handlers from the rest of the code, and to break the rest of the code into functional areas.
Encapsulate customized behavior by subclassing controls.

A:

That kind of code would be much easier to handle if, for example, instead of having all the customizing behavior of a treeview in your MainForm, you actually had a class that extended TreeView and made all of the customization there, and your MainForm just used it.
You should do that for every control that exists in your window (or canvas).


Q:

Frama-C Neon missing C library files?

I've successfully compiled Frama-C Neon (Ubuntu) along with Why2, Why3 and Coq.
With previous versions (Nitrogen) it was possible to choose a particular heap model, by defining some symbols like:
#define FRAMA_C_MALLOC_HEAP

and so on.
The Frama-C Neon user manual suggests to include the file share/malloc.c, but I can't find it.

Frama-C Nitrogen contains both share/malloc.c andshare/libc/stdlib.c (including the latter worked fine);
Frama-C Fluorine 3 contains share/stdlib.c only;
Frama-C Fluorine 2 contains neither ;
Frama-C Neon contains neither;

Moreover the Fluorine 3 changelog lists "Add missing C library files."
Are FRAMA_C_MALLOC_* symbols deprecated or is the Neon source distribution somewhat incomplete?

A:

Yes, some files in relation to modeling dynamic memory allocation were removed from the Neon Frama-C release.


Q:

How can I join on a table twice and reference a column name differently each time?

So I have a situation where a table Partners has a one-to-one relationship with a table called Regions and also a one-to-many relationship with the same table  through an intersection table called Destinations. My nice naming conventions below should help you figure out what I mean.
        Regions
======================
 id | name
======================
  1 | "United States"
  2 | "Mother Russia"
  3 | "Belize"

             Partners
=================================
 id |    name      |  region_id
=================================
  1 |  "B Obama"   |     1
  2 |  "V Putin"   |     2

         Destinations
==============================
  partner_id  | region_id
==============================
       1      |     2
       1      |     3
       2      |     1
       2      |     3

What I want is a query that returns a result like
=======================================================
  partner_name  | partner_region  | destination_region
=======================================================
   "B Obama"    | "United States" |  "Mother Russia"
   "B Obama"    | "United States" |  "Belize"
   "V Putin"    | "Mother Russia" |  "United States"
   "V Putin"    | "Mother Russia" |  "Belize"

The problem is that I can't figure out how to join twice on the Regions table in order to make this query. I know that what I want is like
  SELECT Partners.name AS partner_name,
         Regions.name AS partner_region,
         ???          AS destination_region
  FROM
      Partners INNER JOIN Regions ON Partners.region_id=Regions.id
               INNER JOIN Destinations ON Partners.id=Destinations.partner_id

but what I'm confused on is what to fill in for ??? above because Regions is already joined to Partners.

A:

You need another join:
SELECT p.name AS partner_name,
       rd.name AS partner_region,
       rd.name AS destination_region
FROM Partners p INNER JOIN
     Regions rp
     ON p.region_id = rp.id INNER JOIN
     Destinations d
     ON p.id = d.partner_id INNER JOIN
     Regions rd
     ON d.region_id = rd.id;

Note that table aliases make the query easier to write and to read.


Q:

Aggregating a categorical table in R (With percentages)

I have the following table in R:
Sample             Cluster  CellType  Condition  Genotype  Lane
Sample1            1        A         Mut        XXXX      1
Sample2            2        B         Mut        YYYY      1
Sample3            2        A         Mut        YYYY      2
Sample4            1        A         Mut        ZZZZ      1
Sample5            2        B         Mut        YYYY      3
Sample6            1        B         Mut        YYYY      1
Sample7            1        A         Mut        XXXX      2

I would like to:

Aggregate the table by the Cluster column,
Where each other column yields the dominant value which relates to the cluster
As well as the "confidence level", as a percentage of dominance from the values related to the same cluster

Like so:
Cluster      CellType  Condition  Genotype     Lane
1            A (75%)   Mut (100%) XXXX (50%)   1 (75%)
2            B (66%)   Mut (100%) YYYY (100%)  1 (33%)

I've tried using the aggregate function as follows which yields close results, but it's not quite there yet:
Mode <- function(x) {
 ux <- unique(x)
 ux[which.max(tabulate(match(x, ux)))]
}
library(dplyr)
aggregate(. ~ Cluster, clustering_report, Mode)

A:

Here is a base R solution,
m1 <- do.call(rbind,
        lapply(split(df, df$Cluster),
               function(i) sapply(i[3:6],
                                  function(j) {
                                    t1 <- prop.table(table(j));
                                    nms <- names(t1[which.max(t1)]);
                                    paste0(nms, ' (' ,round(max(t1)*100), '%', ')')
                                    })))

cbind.data.frame(unique(df[2]), m1)

which gives,

Cluster CellType  Condition    Genotype    Lane
1       1  A (75%) Mut (100%)  XXXX (50%) 1 (75%)
2       2  B (67%) Mut (100%) YYYY (100%) 1 (33%)


Q:

getting Floating point exception (core dumped). I dont know how to fix it

In the key function is gives the error. Atleast thats what gdb says. Thanks in Advance.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>   // for cin and cout in C++
#include <cassert>    // for assert
#include <strings.h>
#include <string.h>
#include<time.h>
using namespace std;

int lcombinations=0;
int distinct=0;

linear hash function.
void linear(char *tword, int key, int n, char **lcArray)
{
int c;
while(c==0)
{
    if(key==n)
    {
        key=0;
    }
    if(strlen(lcArray[key])==0)
    {
        lcArray[key]=tword;
        c=1;
    }
    else
    {
        key++;
        lcombinations++;
    }
}
}

generates key for the hash function
void key(char *tword, int l, int n, char **lcArray)
{
int total=0;
int k;
for(int i=0; i<l; i++)
{
    total= total+tword[i];
}
total=n%total;
k=rand()%25+66;
total=total*k;
linear(tword, total, n, lcArray);
}

int counter=0;

finds all the distinct words in the test.
void distinct_words(char *tword, char **distinct, int l, int n, char **lcArray)
{
int j;
int k=0;
if(counter==0)
{
    counter++;
    distinct[0]=tword;
    key(tword,l,n,lcArray);
}
else
{
    for(j=0; j<counter; j++)
    {
        if(strcmp(distinct[j],tword)!=0)
        {
            k++;
        }
    }
    if(k==counter)
    {
        distinct[counter]=tword;
        counter++;
        key(tword,l, n, lcArray);
    }
}

}
receives and breaks the text into words
int main()
{
srand(time(NULL));
FILE *inFile;
char word[81];
char *tword;
inFile = fopen("will.txt", "r");    // Open for reading, hence the "r"
assert( inFile);            // make sure file open was OK
int i=0;
int n=65437;
int j,k;
char **distinct= (char **)malloc(sizeof(char **)*n);
char **lcArray= (char **) malloc(sizeof(char*)*n);
for(int p=0; p<n; p++)
{
    lcArray[p]= (char *) malloc(sizeof(char)*81);
}
while(fscanf(inFile, "%s",word) != EOF)
{
    i++;
    k= strlen(word);
    tword= (char *)malloc(sizeof(char)*k);
    int l=0;
    for(j=0; j<k; j++)
    {
        if(isalnum(word[j]))
        {
            word[j]=toupper(word[j]);
            tword[l]=word[j];
            l++;
        }
    }
    printf("%s ", tword);
    distinct_words(tword, distinct, l, n, lcArray);
}

}

A:

My suspicion is that your floating point exception is generated by this line:
total=n%total;

... specifically, if total is zero, that can cause a floating point exception on many systems.
You can avoid the exception by guarding against the possibility of the modulo value being zero:
if (total != 0)
{
   total=n%total;
}
else
{
   printf("Hey, modulo by zero is undefined!  (It's similar to divide-by-zero!)\n");
   total = 0;  // or something
}

By the way, one key thing you'll need to learn -- if you want to retain your sanity while programming -- is how to track down exactly where in your code a crash is occurring.  You can do this using a debugger (by single-stepping through the code's execution, and/or by setting breakpoints), or you can deduce where the crash occurred by sprinkling temporary printf()'s (or similar) throughout your code so that you can see what gets printed just before the crash, and use that to narrow down the problem location.  Either technique will work, and one or the other is usually necessary when merely eyeballing the code doesn't give you the answer.


Q:

Contact which is both Organisation & Individual

Is there a way for me to create a new contact that is both an Organisation AND an Individual sub-type?
I have a case where I have created a new Individual contact, he is a 'Lecturer' which is a sub-contact type we have created within 'Individual'. But he also Advertises with us so I want to be able to add him as an Organisation - sub-type: 'Advertiser'.
I know I can attach multiple sub-contact types within the main contact type, for example:
[Mr. John Smith] - Individual: [Member], Individual: [Lecturer]
OR [Mr. John Smith] - Organisation: [Society], Organisation: [Advertiser]
I cannot seem to mix the two: [Mr. John Smith] - Individual: [Lecturer], Organisation: [Advertiser]. Is there an easy way to do this other than creating duplicate contacts under each contact type?

A:

I would rather think like this:
Something he/she is --> contact type
Something he/she does --> group
If he is a person, then the contact type should be Individual. Maybe he works with or owns an Organization, then create a relationship.
To be a lecturer or an advertiser can change ( if he change job), but he will always be an Individual.
So to me it gives more sense to create two groups called Lecturer and Advertiser, and put this contact and the others in the corresponding groups.

A:

No, you can not mix the two. To me it does not make sense to combine the two as they should be different legal entities.
What I would do rather than create duplicate contact is create duplicate contact_sub_types? Or (if you have no specific data set for the contact_sub_type) use Tags to flag contacts as being a Lecturer?
What would also make sense to me is to create Lecturer as a relationship? I assume he/she is Lecturer at some organization? Hope this helps!

A:

What is he advertising?  If he is advertising services, perhaps those services are done under a business name-- an Organization that perhaps you might want to record.  Then it would make sense to create a relationship between his Individual record and his Organization record.


Q:

Navigate programmatically to viewcontroller inside navigationcontroller & tabbarcontroller on another storyboard

I need to go programmatically to a viewcontroller from another Storyboard. From here easy. But the problem is: that viewController is embedded in a navigation controller, and this one into a tabBarController (see image)

I've tried:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)

    let viewcontroller = storyboard.instantiateViewController(withIdentifier: "controller_id")
    let navigationController = UINavigationController(rootViewController: viewcontroller)

    self.present(navigationController, animated: true, completion: nil)

What I get with this is: I go to the correct controller, with navigation controller working, but no tabbarcontroller
Another try:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)

    let tabbar = storyboard.instantiateViewController(withIdentifier: "tab_id")
    let navigationController = UINavigationController(rootViewController: tabbar)

    self.present(navigationController, animated: true, completion: nil)

In this case, tabbar is working, but no navigationcontroller.
And... try number 3:
    let storyboard = UIStoryboard(name: "Inside", bundle: nil)
    let tabbar = storyboard.instantiateViewController(withIdentifier: "tab_id")
    let viewcontroller = storyboard.instantiateViewController(withIdentifier: "race_id")

    let navigationController = UINavigationController(rootViewController: tabbar)

    navigationController.pushViewController(viewcontroller, animated: false)

    self.present(navigationController, animated: true, completion: nil)

In this case, the behaviour is so strange... I appear in the correct controller, but with a back button. If I click I go to the same correct controller... with the tabbarcontroller... and then navigationcontroller disappear... nice :S
Any way to go programmatically to the correct controller and get working the tabbar & navigation?

A:

Try out below code:
var storyBoard = UIStoryboard(name: "SecondStoryboard", bundle: nil)
var tabbar: UITabBarController? = (storyBoard.instantiateViewController(withIdentifier: "tabbar") as? UITabBarController)
navigationController?.pushViewController(tabbar, animated: true)

I have less knowledge in swift. Objective-C code for the above is:
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:nil];
    UITabBarController *tabbar = (UITabBarController *)[storyBoard instantiateViewControllerWithIdentifier:@"tabbar"];
    [self.navigationController pushViewController:tabbar animated:YES];


Q:

SharePoint 2010: Error Mapping to Picture Hyperlink with SPMetal

Whenever I have a column of type hyperlink with the format set for pictures, I get an error whenever there is actually a value in that column.
The exception it throws is "Specified cast is not valid".
My thought is that the problem is either here (the FieldType being set to Url):
[Microsoft.SharePoint.Linq.ColumnAttribute(Name = "FOO", Storage = "FOO_", FieldType = "Url")]
public string FOO
{
    get
    {
        return this._FOO;
    }
    set
    {
        if ((value != this._FOO))
        {
            this.OnPropertyChanging("FOO", this._FOO);
            this._FOO = value;
            this.OnPropertyChanged("FOO");
        }
    }
}

Or here (it being cast to a string):
private string _FOO;

But I'd have no idea what the proper values for either of those fields should be.
Any help would be greatly appreciated.
It works whenever this field does not have data in it and I JUST used SPMetal to generate the class, so I'll get the two most obvious questions out of the way.

A:

Link to the answer:
https://mgreasly.wordpress.com/2012/06/25/spmetal-and-workflow-associations/
Turns out it is a known bug when mapping lists that have associated workflows.
SPMetal assigns it as a nullable integer when it's supposed to be an Object, hence the cast error.
Workaround: manually edit the mappings to make the type it returns an object or ignore the column by using a parameter map.


Q:

Bootstrap Carousel from JSON loading slow

I have a bootstrap carousel that is pulling its data from JSON. Our concern is how slow it is loading, and it appears to not start automatically. Here is the code.....

    ‹
    ›

A:

One of the items should be set to active in the html.


Q:

Python3 compiled App Decrease Size with zip?

I have compiled with success a rather big app ,but the size of the app is way too big(about 1 GB).I realized that almost the half (400MB) was taken from just 2 modules(PyQt5 and mpl_toolkits(basemap)).Of course the  one approach is to delete the side-services you dont need but i cant in my case as i use about all of these in my app.
Then i was thinking about ziping these modules but i don't know if this is safe or execute time viable.
So is there a suficient way to minimize the size of my app, and if the ZIP is the only answer is it viable to do this on a lib such PyQt5 witch is imported many times in my script?

A:

It is entirely possible to do this; Python has always supported "zipapps", and as of 3.5, provides a module, zipapp, to assist with creating them.
The only concern is whether your dependencies run properly zipped; most do, but some take file-system layer dependencies that zipping (and eggs and the like) don't handle (the setup.py file for these would declare zip_safe=False to tell tools not to allow it). Packages with C extensions would have to assert zip_safe=True, as the default analyzer assumes C extensions can't be safely zipped (though many can).
It will slow down startup a bit (since it has to decompress the modules), but it shouldn't dramatically slow runtime, no matter how many times you import it; the first import is the only one that really matters, since subsequent imports just pull the cached copy of the module from an internal cache (sys.modules).


Q:

Why are $\{0\}$ and $\{1\}$ open subsets of the discrete metric space $\{0,1\}$?

$\{0\}$ and $\{1\}$ open subsets of the discrete metric space $\{0,1\}$.
Let $S$ be a metric space. Then a subset $A \subseteq S$ is considered open if $\forall x \in A, \exists r>0$ such that $B_S(x,r)  \subseteq A$.
However, $\{0\}$ is a singleton. How do we define an open ball in $\{0\}$?
Then we would need to show that this open ball lies entirely in $\{0\}$.
I have a little trouble grasping this idea. Please tell me how this becomes possible?
Thank you for your help.

A:

Recall that a discrete metric space is defined by the metric
$$
d(x,y) = \begin{cases} 1 & x \neq y \\ 0 & x = y \end{cases}
$$
and so in particular, in the case of $S = \{0, 1\}$, we have that $d(0, 1) = 1$. Now, a(n open) ball of radius $r$ is given by
$$
B_r(x) = \{y \in X \mid d(x,y) < r\}
$$
and in a metric space, these are our basic open sets. So what is $B_{1/2}(0)$?


Q:

Should font-size for question text and code blocks be the same?

On StackOverflow the the font-size for text and code appears to be the same, but on CodeReview they're noticeably different.
It's a bit of an annoyance, because when the text font size is set to my preference (about 10pt.), the code appears to be 8pt. To read the code blocks comfortably, I have to adjust page zoom to make the text appear larger than I would like.
The effect becomes even more pronounced when inline code formatting is used in adjacency to a code block. Here's an example from one of my questions:

Does anyone else find this annoying? Is this something that should be changed?

A:

This was implemented as a partial quick-fix to a discussion I started a while back.
After this change, I found the average code samples a lot more readable, so I would argue to keep this change. However, more suitable (but more difficult) solutions can still be considered, which is why I didn't accept Jeff's answer.
Most modern web browser allow easy up and downscaling (e.g. ctrl + and ctrl -), which seems to be a more suitable solution for you.


Q:

Can someone help explain this jQuery code?

$('#AddMoreErrors,#AddMoreMime,#AddMoreRemote').live('click',function(){
    var newRow = $(this).closest('tr');
    $(this).closest('tr').after('
'+newRow.html()+'
').find('span').removeAttr('id').addClass('removetr').html('Del');
});

I wrote the above jquery code and this is what it does: When someone clicks on "add more" it finds the nearest tr, replicates it into another tr and appends it to the first one. Then it finds all the spans, removes its id and adds a new class and changes the text.
Now what surprised me was find('span').removeAttr('id').addClass('removetr').html('Del');
I know I could do removeAttr on span but how did addClass and html also get applied on span?

A:

jQuery returns object of element after each operation on which it is performed, and execution order are from left to right. So its .removeAttr('id') will be on span and that span object will be returned. Similarly .addClass('removetr') and .html('Del'); are performed.


Q:

Equivalence between two versions of Open Mapping Theorem

I have seen two versions of the open mapping theorem. I am trying to understand why they are equivalent.
From wikipedia:

If $X$ and $Y$ are Banach spaces and $A : X \rightarrow Y$ is a surjective continuous linear operator, then $A$ is an open map.

From Royden (paraphrased):

Let $X$ and $Y$ are Banach spaces and $T : X \rightarrow Y$ is a continuous linear operator. $T(X)$ is closed as a subspace of $Y$ iff $T$ is an open map.

How are these equivalent?
EDIT:
I've included the releveant portion in Royden. Indeed, he discusses the image as having inherited the subspace topology from $Y$ -- I missed this before the discussion in the comments, thanks!

A:

It is clear that the second result implies the first result.
If it is true the first result, we consider a map $T:X\to Y$ such that $T(X)$ is closed. Each closed subspace of a Banach Space $Y$ is also a Banach Space so $T(X)$ is a Banach Space and $T:X \to T(X)$ is a surjective continuos linear operator between Banach Spaces; so, by first result, $T:X\to T(X)$ will be an open map. In any case, it is not true that $T: X\to Y$ will be an open map because in general $T(X)$ it is not open in $Y$, infact if it is open, then $T(X)$ will be a nonempty open and closed subspace of the connected space $Y$, so $T(X)=Y$. An example can be $T:\mathbb{R}\to \mathbb{R}^2$ such that
$T(x):=(x,0)$ . The map is continuos and Linear while the two spaces are Banach, so $T:\mathbb{R}\to \mathbb{R}\times \{0\}$ is open while
$T:\mathbb{R}\to \mathbb{R}^2$ is not open because $T(\mathbb{R})= \mathbb{R}\times \{0\}$ that it is not open in $\mathbb{R}^2$.


Q:

How do I prevent an Android device from going to sleep programmatically?

How do I prevent an Android device from going to sleep programmatically?

A:

If you just want to prevent the sleep mode on a specific View, just call setKeepScreenOn(true) on that View or set the keepScreenOn property to true. This will prevent the screen from going off while the View is on the screen. No special permission required for this.

A:

One option is to use a wake lock. Example from the docs:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();

// screen and CPU will stay awake during this section

wl.release();

There's also a table on this page that describes the different kinds of wakelocks.
Be aware that some caution needs to be taken when using wake locks. Ensure that you always release() the lock when you're done with it (or not in the foreground). Otherwise your app can potentially cause some serious battery drain and CPU usage.
The documentation also contains a useful page that describes different approaches to keeping a device awake, and when you might choose to use one. If "prevent device from going to sleep" only refers to the screen (and not keeping the CPU active) then a wake lock is probably more than you need.
You also need to be sure you have the WAKE_LOCK permission set in your manifest in order to use this method.

A:

I found another working solution: add the following line to your app under the onCreate event.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

My sample Cordova project looks like this:
package com.apps.demo;
import android.os.Bundle;
import android.view.WindowManager;
import org.apache.cordova.*;

public class ScanManActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.loadUrl("http://stackoverflow.com");
    }
}

After that, my app would not go to sleep while it was open. Thanks for the anwer goes to xSus.


Q:

How do I calculate TAS from IAS in this question?

How can I calculate the answer to this EASA PPL ECQB question?

An aircraft cruises at altitude 5000 ft on a heading of 180° with an
  indicated airspeed of 100 kt. The wind vector is 180° with 30 kt.
  Neglecting instrument and position errors, which will be the
  approximate true airspeed (TAS)?

A:

Just convert 100 kt indicated to TAS at 5000 ft using your flight computer.  The wind data is a smoke screen to throw you astray if you don't really understand what you are looking for.


Q:

php redirect doesn't change the url

I know this is a very common question, but I could not find the answer
I'v a post.php, that submit a post form to controller.php
When it goes right, in controller it does:
header("Location: ./post?ok=1");

the post is actually inserted, and it goes through the line above,
but the url in the browser seems never changed, and at the end there is not the ok param,
I could use session variable to store such a success/failure param, but this way should be working
post.php:
<form action="controller" method="post">
    <input name="test" value='test' type="text" />
    <input type="submit" value="post"  />
</form>

controller.php:
<?php
    header("Location: ./post?ok=1");
?>

Edit 1:
header("Refresh:1;url=http://localhost/test/post?ok=1"); //doesn't work better

Edit 2:
in post.php top I've put
debug("post l ".count($_POST));
debug("get l ".count($_GET));

they show 0's before submit, and 0's after also
edit3: it works
was blocked by:
if ($success){
    header("Location: ./post?ok=1");
}
header("Location: ./post");

that should be:
if ($success){
    header("Location: ./post?ok=1");
} else {
    header("Location: ./post");
}

thx all

A:

Try using the HTTP status code 303 See Oter:
header("Location: your/location", true, 303);

A:

First of all you should not use $_SERVER['HTTP_REFERER'] this is unsafe. Also it is possible that the client won't send this header anyway. Right now I don't know how but I'm sure that this could be used to highjack your site for something evil.
Better you should know where the form data came from and redirect the user there back.
By the way your redirect maybe don't work like expected because the url already contain a questionmark. So you have to add more parameters with a & sign.
For the redirect I would suggest the HTTP 302 Found response status. But you have to be sure that nothing other is send out before. There must be no HTML output or empty lines before this following header line:
header("Location: http://".$_SERVER['HTTP_HOST']."/your/source.form", true, 302);


Q:

pid_t doesnt highlight by default in VIM

All datatypes like int,long,char are highlighted automatically as soon as i type them in VIM.
But, there are few exceptions like pid_t,mode_t..
How do get them highlighted by default?

A:

You can add them to syntax/c.vim in your after directory, so they complement the distributed syntax/c.vim.  For example:
syn keyword cType pid_t mode_t

See also the "Adding to an Existing Syntax File" section of the user manual.


Q:

How to update attributes of a shapefile using list values?

I am using an update cursor to update the attributes of a shapefile using values from a list. It seems very easy, but I couldn't make it run correctly. When I run the following code, it updates all rows based on the final value in the list. Please suggest how to fix it.
cur1 = arcpy.UpdateCursor(fc)
for v in cur1:
    for s in list:
        val = s
        v.Val = val
        cur1.updateRow(v)

A:

This looks like a simple logic error.  I'm assuming that you want the first feature in the cursor to be updated with the first item in the list, then the second feature with the second item, etc.  As written, you're updating the same row over and over again with each element of the list.  (Then repeating the process for each row.)
Maybe your loop should look something like this instead:
listIndex = 0
cur1 = arcpy.UpdateCursor(fc)
for c in cur1:
    if listIndex >= len(list):
        arcpy.AddMessage("More rows than items in the list.  Quitting early.")
        break
    val = list[listIndex]
    v.Val = val
    cur1.updateRow(v)
    listIndex = listIndex + 1

EDIT: Corrected logic error (needed to check array length before accessing it, not after).  Also fixed missing : on if statement.
EDIT: Following the suggestion in Paul's comment is more "Pythonic" and reduces the lines of code:
cur1 = arcpy.UpdateCursor(fc)
for tuple in enumerate(cur1):
    index = tuple[0]
    row = tuple[1]
    if index >= len(list):
        arcpy.AddMessage("More rows than items in the list.  Quitting early.")
        break
    row.Val = list[index]
    cur1.updateRow(row)


Q:

ASP.NET Membership.FindUsersByName not working. Can't search for users. 404's

When I use this action and go to Profile/Username, it gives me a 404 even though the name exists.  I've used Membership.GetNumberOfUsersOnline().ToString();  and that works just fine, returning the amount of users online correctly.  I understand that if this code worked properly, it would just return a basic webpage, but it's not even doing that, I get a 404.  What gives?  Help is greatly appreciated! :)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;

   namespace MvcMicroBlog.Controllers
   {
        public class ProfileController : Controller
       {
           //
           // GET: /Profile/

            public ActionResult Index(string Profile)
            {
                Membership.FindUsersByName(Profile);
                return View();
            }

       }
   }

A:

Unless you have a custom route defined, you should go to /Profile/?Profile=username, or you can rename your Profile parameter to id.
If you prefer the custom route approach, you can add this to your RegisterRoutes method in Global.asax.cs, before the Default route:
routes.MapRoute(
    string.Empty,
    "Profile/{Profile}",
    new { controller = "Profile", action = "Index" }
);


Q:

Button Loading react-hooks-nextjs

I am doing a loading spinner button, When I press the button, the loading icon appears but does not disappear at the marked time, and continues with the load. Here is the code:
componentOne:
import React from 'react'

function Loader(){
return(
    <>

    </>
)

}
export default Loader;
componentTwo:
import React, {useState} from 'react';

import Loader from '../components/loader'
function ButtonLoading(){
const [loading, setLoading] = useState(false)

function loadData(){
    setLoading ({loading: false})

    setTimeout(()=>{
        setLoading({loading: true});
    }, 1000);

}
return(
    <>

    <button className="btnLoading" onClick={loadData} disabled={loading}>
    {loading &&(<Loader/>)}
    {loading && Loading page}
    {!loading && Load page}
    </button>

    </>
)

}
export default ButtonLoading;

A:

I think you got the loading backwards. I believe the function should look like  `
function loadData(){
    setLoading ({loading: true})

    setTimeout(()=>{
        setLoading({loading: false});
    }, 1000);
}`

SetTimeout runs the function AFTER the timer is up


Q:

HTML +CSS +Javascript Editor

Hello I am looking for a good HTML + CSS +Javascript Editor  Microsoft Windows platform
Thank you very much !!!!
UPDATES :

1) I found an amazing one, which I use already for a while on windows and on MAC as well :
Sumblime Text 2

2)
WebStorm is another one I like.
WebStorm I use for the bigger projects, where the SublimeText is more for the files to open, or a small projects because it is very fast

A:

I prefer Netbeans 6.7 PHP , it includES CSS / JS / HTML and PHP Features. Codefolding, Syntax Highlighting, Code completion, CSS Preview...
But my Favourite function is code completion for JQuery + Dojo
Download : Netbeans Download

A:

I found an amazing Text editor on MAC/Widnows
Sublime Text
I love it, every single day like it more and more.

A:

I used both Notepad++ and Aptana, sometimes Eclipse as well.
For simple scripting or quick fix on some files, notepad++ is very good.
For large project management I prefer Aptana, which comes with debugger for PHP and I soooo need it.


Q:

Is it dangerous to rope together on an ascent of hard packed ice?

This image has recently come under considerable criticism on social media for dangerous mountaineering practices.  The location is unknown as the qualified mountain guide observer wanted to maintain the climbers' anonymity.
The terrain was described as

Hard packed solid ice
The slope quickened into a narrows with another slope leading to a boulder field
The observer described a slip as unsurvivable
The technique was also described as 'misguided Alpine thinking'
There are four individuals in the image
They are connected via rope

What specifically is wrong with the technique being applied in this image and what risks does it pose?  What should the group have been doing to ascend more safely?

A:

If the snow was hard packed enough that a self arrest is not possible, and there are no intermediate anchors, then if one person falls, they can take the whole team down with them.
If that was the case then what they should have done is to have the first person place anchors as they went up, either snow pickets or ice screws depending on the conditions. The anchors are clipped to the rope and passed by each climber in turn.
The last person in the group picks them up as they go, and when the leader is almost out of pieces, they create a bombproof anchor, bring the entire team up to it and get the pieces from the last person. Its identical to simuling while rock climbing, just on snow/ice.
Beyond that, I am not certain of what else they could have done, other than not being there. It is possible that a different time of day would have made for better conditions, but that is hard to say from the image.

A:

The most common options coming to my mind are:

Securing from anchors and building e.g. one rope-party with 2 and one with 3 members

This is slow but very safe. You do it in steep and/or difficult terrain.

Moving continuously being roped together while the first uses gear

Using e.g. a tibloc or you can use rocks to let the rope move behind them (with respect to the side so in case of somebody falling, the rope will cause friction and the weight of different rope partners slowing down the fall - this is more likely done on ridges and not on a face like in the picture)
Being comfortable and without big technical difficulties (in respect to the skills of each person in the party) this earns a lot of speed. This is often done in steep ice or on easier to medium difficult rock climbs (common e.g. on UIAA III or IV climbs)

Moving without protection being roped together

Is typically done on glacier hikes where the main risk is falling into a crevasse.
If there is no risk of crevasses, this can only make sense if you walk e.g. on a snow ridge where you have no possibility to use protection: In case one falls, the roped-in friend has to react very fast and jump on the other side of the ridge. This is very difficult and therefore needs experience. I was told this should only be done by mountain guides going behind the client.

Moving without protection not being roped together

No backups. You have to feel absolutely comfortable with the terrain you are moving in.

For me it looks very unlikely to have hidden crevasses in the terrain seen in the picture. So for option (3) it is much more likely that the roping together introduces a much higher risk here than going without rope. Especially if you tie in 5 people (!) it is not very likely that the members will hold the party if somebody falls. It will be more like a chain reaction with very fatal consequences, not only for the one who falls, but for the whole party.
I once was guided in South America on rocky terrain in a five-member party without using protection. For me this is similarly a no-go but the guide said it's OK and he does it all the time. For me this is not the way to move in the mountains, but opinions differ.
I say you use one of the options (1), (2) or (4) depending on how comfortable you feel in respect to the experience and skill level of all (!) members of the party. If you can't find a conclusion the way to react is: don't ascend further - return to a route which is safer for your group.
For me it seems that the wall is not that steep so that option (1) is too slow. Especially if you only have 1 rope for 5 people. So I would either search for spots to use mobile protection to place a camelot or nut. Or I would try to find rocks to guide the rope properly - descriped in (2). The only good alternative for me is that everybody feels safe and all are moving unroped (4).

A:

It look like they are "moving together". Very common in alpine ascents when moving over easier ground where it would take too long to pitch the climb (fixed belay). The leader would run out around 10-20 meters to the second and would look for rock features or quick placements to get some protection in. Notice the rock features on the ascent, I'm guessing there would be placements there. If the leader or the second falls they will counter one another arresting the fall. It's a good system if worked correctly and it looks like the climbers in the photo are doing everything they should given the angle and general conditions. You can move quickly and relatively safely on easier ground using this system and you don't have to stop to place a fixed belay unless the climb needs to be pitched. I have climbed like this on ice and on easy rock.


Q:

C#でThread.Sleep(1)が明らかに1ミリ秒以上かかっている現象について

以下のコードを実行すると1秒で処理が終わるはずが10秒ほどかかります。
CPU8コアのマシンで、他のプログラムはほとんど負荷がなく余裕がある状態です。
何故でしょうか？
また、意図した通り1ミリ秒だけ待機したいのですがどうしたらいいでしょうか？
(他のスレッドに処理を移すのでピッタリ1ミリ秒といかないのは理解しています。ですがCPUがほとんど使われていない状態で10倍かかるのは困っています)
    static void Main(string[] args)
    {
        int n = 0;
        while (true)
        {

            Thread.Sleep(1);
            if (n++ > 1000) break;
        }
    }

補足になりますが、秒間1000回ある処理を行うというのが目的です。
その処理自体はスレッドで行うのですが、その処理をスレッドに行ってもいいと指令をくだすのがこのメインスレッドです。
補足
回答に提示していただいた下記コードをそのまま実行し、「15000ミリ秒」ほどかかりました。
Thread.Sleep(1);をコメントアウトすると瞬時で終わります。
CPUはほとんど使われていません。
var stopwatch = Stopwatch.StartNew();
int n = 0;
while (true) {
    Thread.Sleep(1);
    if (n++ > 1000) break;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

A:

どうも以下のどちらかの条件でレイテンシが16ms程度に悪化するように思われます。

ReleaseビルドのアセンブリをVisual Studio外から起動する
Visual Studioホスティングプロセスを有効にしたうえでReleaseビルドのデバッグを行い、しばらくThread.Sleep(1)を実行し続ける (なおVsHub.exeを強制終了すると元に戻ります)

※実行環境はWindows 10/x64/Visual Studio 2015/32bit優先
Releaseで発生することから最適化による差異と思われますが、そもそもThread.Sleep(int)の精度は全く保証されておりませんので

Thread.Sleep(1)の間隔が変化することを見越したプログラムを書く
Thread.Sleep(0)に変更する（これもレイテンシが変化します）
コンテキストスイッチを行わずに1ms待機する
// Thread.Sleep(1)の代わりにwhileで時間を潰す
while (stopwatch.ElapsedMilliseconds < n + 1){}

というような方針を取った方が良いかと思います。

A:

1ms sleep × 1000回で10秒かかるとのことですが、何の時間を測定したものでしょうか？
var stopwatch = Stopwatch.StartNew();
int n = 0;
while (true) {
    Thread.Sleep(1);
    if (n++ > 1000) break;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

のように実際の所要時間を測定していないように見受けられます。
プログラムの開始～終了に長時間を要するのであれば、例えばウィルススキャン等の別要因と思われます。

なお、上記コードでは手元の環境では約1800ミリ秒となりました。これはWindowsの内部クロックが16ミリ秒辺りを基準に動作しているためです。


Q:

Line break when importing csv to mysql and sqlite

I am importing CSV data to MySQL (using 000webhost) and SQLite. I have data with line breaks in my database as such:

My first line.\nMy second line.

it should print out like this:

My first line. My second line.

I am developing for an Android app to display the results. I get from the database into a TextView and the data that is displayed is shown with \n as such:

My first line.\nMy second line.

Shouldn't it escape \n and print it as a line break instead??

A:

To get a line break, use a line break:
IDCol,TextCol
1,hello
2,"My first line.
My second line."

(The CSV format is not very well specified; not all programs might be able to import this correctly.)


Q:

Syntax error in creating a trigger in MYSQL

I wrote a trigger which get trigered after update statement of table1. If there is no row in table1 based on the conditions, then update table2.
CREATE TRIGGER trigger1
    AFTER UPDATE ON my_database.table1
FOR EACH ROW
BEGIN
DECLARE cnt int;
IF new.column1 = 1 THEN
   SELECT COUNT(1) INTO @cnt FROM my_database.table1
   WHERE userID = 1 AND isDeleted = 0;
IF cnt = 0 THEN
   UPDATE my_database.table2
   SET isDeleted = 1
   WHERE userSeqID = new.userID;
END IF

It gives me error i nline number 4, I couldn't understand the problem

A:

Every IF statement has to ended with END IF clause. Try this statement -
DELIMITER $$

CREATE TRIGGER trigger1
  AFTER UPDATE
  ON my_database.table1
  FOR EACH ROW
BEGIN
  DECLARE cnt int;
  IF NEW.column1 = 1 THEN
    SELECT COUNT(1) INTO cnt FROM my_database.table1 WHERE userID = 1 AND isDeleted = 0;

    IF cnt = 0 THEN
      UPDATE my_database.table2 SET isDeleted = 1 WHERE userSeqID = NEW.userID;
    END IF;
  END IF;
END$$

DELIMITER ;


Q:

Variable value display without page reload

I am trying to write a simple website. Here is the requirement.

The site needs to be made with Pyramid web framework
There needs to be a thread that contains 3 variables and the values of the variables will  keep on changing.
The site needs to pick these values up and display them without reloading the page.

I know I need to use some form of AJAX. Please suggest me some ways to do this. Even links to some tutorials will be appreciated.
Thanks

A:

I use long polling now and it seems like the best thing to use for me


Q:

How can I trust Wikipedia, if everyone can change it?

If everyone can change the Wikipedia, can it be trusted? Do any studies exists that show it is less trustworthy than classical encyclopedias?

A:

You are not supposed to trust it - Wikipedia itself tells you that it is not a reliable source.
Instead, you are supposed to trust the sources it cites in the articles. This  will mostly be secondary sources, e.g. newspaper or magazine articles, books or studies about a topic, provided that these meet Wikipedia's requirements for reliable sources.
The latter is also supposed to maintain overall quality of Wikipedia articles and prevent the inclusion of outright wrong information, though - anyone who adds or deletes or changes content of an article is supposed to back this up by sources, at least when their change is challenged.
This can't be guaranteed to work in all cases, though - and this is a difference to classical encyclopedias, where a number of people might be tasked with verifying the included information.
Wikipedia seems to do quite well, though, they have an article about the reliability of Wikipedia - again, you are not supposed to trust this article, but the sources cited in it.
Please note that I have added several links to Wikipedia in this answer - but not all of these links go to articles, some refer to pages in the Wikipedia: namespace. The latter is where Wikipedia's own policies are defined. You are supposed to follow those, no trust needed, or you may be sanctioned by users with the required privileges.

A:

Wikipedia has an entire article on this subject, including several studies, most famously Giles, J. (2005). "Internet encyclopaedias go head to head: Jimmy Wales' Wikipedia comes close to Britannica in terms of the accuracy of its science entries" published in Nature.
Generally, Wikipedia seems of roughly equal reliability as conventional encyclopedias.


Q:

Kotlin: How to iterate through a collection from a specific position with indexes (skip N elements with indexes)

I want to iterate a collection of items from a specific position.
Let's say we want to start from center and iterate the whole right part of the array:
int startFrom = arr.length / 2;
for (int i = startFrom; i < arr.length; i++)
{
    String.format("Index %d value %s", i, arr[i]);
}

It's important to track real indexes and values during iteration. As an example you are going to implement in-place sorting algorithm
I've tried to do so using drop().withIndexes(), but looks like drop() creates a new collection and I lose information about real indexes.
It could be fixed manually if we create a variable and calculate proper index
val startFrom = inputData.size / 2
for ((i, item) in inputData.drop(startFrom).withIndex()){
    val fixedIndex = i + startFrom
    println("Index $i, fixed index $fixedIndex value $item")
}

This solution works but I was hopping there is something that can help to avoid introducing a separate fixedIndex variable and handling this problem manually.

A:

Your original try is very close, just a small change makes it work.  Reverse the calls of withIndex() and drop(N) putting withIndex first.
If you do not want to copy the collection, you can convert it to a sequence first using asSequence().
for ((index, item) in inputData.asSequence().withIndex().drop(startFrom)) { ... }

The test code:
val sampleData = listOf("a", "b", "c", "d", "e", "f")
val startFrom = sampleData.size / 2

for ((index, item) in sampleData.asSequence().withIndex().drop(startFrom)) {
    println("[$index] => $item")
}

outputs:

[3] => d
  [4] => e
  [5] => f

That's it!  The rest of this answer just provides you with alternatives, including a more efficient and Kotlinesque solution of creating your own extension function at the end.

If the copy of the collection is acceptable, you can do the following shorter version.  The withIndex does not cause a copy, but the drop(N) does.
for ((index, item) in inputData.withIndex().drop(startFrom)) { ... }

The eager copy or the sequence could be faster, it depends on the size of the collection, your runtime environment, and CPU cache.
You can also use functional forEach instead of the for loop.
sampleData.asSequence().withIndex().drop(startFrom).forEach { (index, item) ->
    println("[$index] => $item")
}

Which then brings up the best and most efficient option.  Just write an extension function when using an Array or List so that there is no lazy evaluation using wrapper classes nor any copying.  Simply a loop calling your lambda with the index and value.  Here are the two new extensions that add a new variation of forEachIndexed:
inline fun <T> Array<T>.forEachIndexed(startFrom: Int,
                                action: (index: Int, item: T)->Unit) {
    for (i in startFrom until this.size) {
        action(i, this[i])
    }
}

inline fun <T> List<T>.forEachIndexed(startFrom: Int,
                               action: (index: Int, item: T)->Unit) {
    for (i in startFrom until this.size) {
        action(i, this[i])
    }
}

And this can be called simply for any non-primitive array or list:
sampleData.forEachIndexed(startFrom) { index, item ->
    println("[$index] => $item")
}

You could do the same if you want a withIndex(startFrom) style method as well.  You can always extend Kotlin to get what you want!


Q:

SESSION Cart adding 2 + or -2 problem

So i edited my own shop but im having some issues with it, for example it add 2 instead of 1 or it removes 2 instead of 1,
you can see how it looks on www.neobotmx.org/test/tienda.php  <<<  not opwn for the public yet >>  thats why its on a test folder
The shop code :
 <?php

    $product_id = $_GET[id];     //the product id from the URL
    $action     = $_GET[action]; //the action from the URL

    //if there is an product_id and that product_id doesn't exist display an error message
    if($product_id && !productExists($product_id)) {
        die("Error. Product Doesn't Exist");
    }

    switch($action) {   //decide what to do

        case "add":
            $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
        break;

        case "remove":
            $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
            if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
        break;

        case "empty":
            unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
        break;

    }

?>

  <?php

    if($_SESSION['cart']) { //if the cart isn't empty
        //show the cart
            echo "
";
            echo "
";
                        //show this information in table cells
                        echo "Producto	";
                        //along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
                        echo "Cantidad	";
                        echo "Costo	";

                    echo "
";//format the cart using a HTML table

            //iterate through the cart, the $product_id is the key and $quantity is the value
            foreach($_SESSION['cart'] as $product_id => $quantity) {

                //get the name, description and price from the database - this will depend on your database implementation.
                //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
                $sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
                                $product_id);

                $result = mysql_query($sql);

                //Only display the row if there is a product (though there should always be as we have already checked)
                if(mysql_num_rows($result) > 0) {

                    list($name, $description, $price) = mysql_fetch_row($result);

                    $line_cost = $price * $quantity;        //work out the line cost
                    $total = $total + $line_cost;           //add to the total cost

                        echo "
";
                        //show this information in table cells
                        echo "$name	";
                        //along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
                        echo "$quantity Borrar	";
                        echo "$line_cost	";

                    echo "
";

                }

            }

            //show the total
            echo "
";
                echo "Total	";
                echo "$total	";
            echo "
";
            echo "
";

    }else{
        //otherwise tell the user they have no items in their cart
        echo "No tiene articulos en compra.";

    }

    //function to check if a product exists
    function productExists($product_id) {
            //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
            $sql = sprintf("SELECT * FROM products WHERE id = %d;",
                            $product_id);

            return mysql_num_rows(mysql_query($sql)) > 0;
    }
?>

Seguir Comprando

<?php

and now the display of the books / items / whatever you want.
 <?php
  define('MAX_REC_PER_PAGE', 1);
  $sql = "SELECT id, name, description, price FROM products;";
    $rs = mysql_query("SELECT COUNT(*) FROM products") or die("Imposible Realizar Operacion");
  list($total) = mysql_fetch_row($rs);
  $total_pages = ceil($total / MAX_REC_PER_PAGE);
  $page = intval(@$_GET["page"]);
  if (0 == $page){
  $page = 1;
  }
  $start = MAX_REC_PER_PAGE * ($page - 1);
  $max = MAX_REC_PER_PAGE;
  $rs = mysql_query("SELECT id, name, description, price FROM products ORDER BY id
   ASC LIMIT $start, $max") or die("Imposible Realizar Operacion");
  ?>

  <?php
  while (list($id, $name, $description, $price) = mysql_fetch_row($rs)) {
  ?>

 Producto :
      <?= htmlspecialchars($name) ?>

Descripcion :

      <?= htmlspecialchars($description) ?>

Precio :
    <?= htmlspecialchars($price) ?>

  <? echo "Comprar" ?>

  <?php
  }
  ?>

  Pagina :
  <?php
  for ($i = 1; $i <= $total_pages; $i++) {
  $txt = $i;
  if ($page != $i)
  $txt = "$txt";
  ?>
  <?= $txt ?>
  <?php
  }
  ?>

I have no idea where's the error on it...
Ty for the help :)
Obiusly you have to :
<?php session_start();?>
include your database
etc

A:

You have in the style:
body {
    background-image: url();
}

which is causing the browser to request the page again, which adds it to the cart again.
Instead of rendering the cart page, Once the code has modified the cart it should send a redirect to the cart page.


Q:

UTF-8 Encoding issue in IE query parameters

I have this URL with my test-code: http://www.gruppenunterkuenfte.de/encodingtest.php?q=köln
It passes the query-parameter q to an SQL query.
The strange thing is, if the query is comming from IE, I have to utf8_encode() it. If it comes from Chrome, or Firefox, I may not.
mb_detect_encoding() Always says the query is UTF-8 (IE and Other). The query itselfe however will only work in one of the browsers.
This is my test code from the URL above:
<?php
header('Content-Type: text/html; charset=utf-8');

$config = parse_ini_file("inc/base/config.php", 1);
$link = mysqli_connect($config["database"]["server"], $config["database"]["user"], $config["database"]["passwd"]);
mysqli_select_db($link, $config["database"]["database"]);
mysqli_query($link, "SET NAMES utf8;");

echo 'mb_detect_encoding: '. mb_detect_encoding($_GET['q']) .'
';

echo 'Without utf8_encode():
';

$res = mysqli_query($link, 'SELECT SQL_CALC_FOUND_ROWS ort FROM BRDOrte
  WHERE ort LIKE \''. addslashes($_GET['q']) .'%\'
  GROUP BY BINARY ort
  ORDER BY BINARY ort
  LIMIT 5
  ');
while ($row = mysqli_fetch_array($res)) print_r($row);

echo '
With utf8_encode():
';

$res = mysqli_query($link, 'SELECT SQL_CALC_FOUND_ROWS ort FROM BRDOrte
  WHERE ort LIKE \''. utf8_encode(addslashes($_GET['q'])) .'%\'
  GROUP BY BINARY ort
  ORDER BY BINARY ort
  LIMIT 5
  ');
while ($row = mysqli_fetch_array($res)) print_r($row);

?>

The MySQL table and all its fields are utf8_general_ci.
So how do I tell IE to send the Query parameter as UTF-8?
Or how do I detect it on server side, so I can encode the right way?

A:

The generic syntax of a URI (RFC3986) requires that any characters not 7-bit ASCII are to be percent-encoded (URI Encoded). When you operate outside that standard, user agent handling will vary unpredictably. You will either have to a) encode the URL string before sending it with javascript (see encodeURIComponent), b) encode it during page render with PHP (see urlencode), or c) create a ternary statement in the request handler to deal with either situation:
$tag = strlen($_GET['q']) > 1 ? $_GET['q'] : utf8_encode($_GET['q']);

A:

Use urlencode to pass the query parameter to the browser. It will become k%F6ln Then you should be able to read it back with urldecode.
For JavaScript try encodeURIComponent or its alternatives


Q:

How can kSCNetworkReachabilityFlagsIsWWAN be true and kSCNetworkReachabilityFlagsReachable be false

In iOS reachability, synchronously checking the SCNetworkReachabilityFlags and getting a combination of flags which are:

kSCNetworkReachabilityFlagsReachable: 0
kSCNetworkReachabilityFlagsIsWWAN: 1

According to Apple's documentation (but also the reachability implementations in other libraries such as AFNetworking), kSCNetworkReachabilityFlagsIsWWAN indicates it is available by a cellular network, but when this is true, the overall kSCNetworkReachabilityFlagsReachable should be true also.
This seems to happen only when you switch from Wifi to Mobile. (When you start on Mobile, it generates, correctly both flags as true).
Any ideas how this situation might be generated (new in 10.3.2?), or is my understanding of the flag meanings wrong?

A:

I had a similar issue, and the issue was that the user had disabled Mobile Data for the app in question


Q:

Connection pool to DB with JAX-WS

I'm trying to build a JAX-WS that does a call to a database. In all the tutorials I found the WS has a static variable that holds the connection
    private static Connection connection;

This connection is then used for all the operations done in the database.
Now my question really is: Does that make sense - especially with high(er) traffic? Isn't it better to create a pool of connections and randomly pick one and use that?

A:

The tutorials probably are doing it the quick and dirty way. Always use a Managed Connection pool, else you are bound to run into issues, and don't need higher traffic for that.