Q:

Selecting different and common values in arrays - php function

What is the best way to do this. You have 2 arrays for input, let's say:
$current = array('strawberry', 'apple', 'banana', 'peach');
$new = array('apple', 'blackberry', 'mango', 'banana');

Now write a class/function that returns two arrays like:
$add = array('blackberry', 'mango');
$del = array('strawberry', 'peach');

What is the best way / the most efficient way to write function/class that performs that task?
I figured something like this:
function replaceTags($new, $current) {
    $tmp = array_intersect($new, $current);
    $add = array_diff($new, $tmp);
    $del = array_diff($current, $tmp);

    return array($add, $del);
}

Im wondering if PHP built-in functions are best for that task?
Any suggestion would be appreciate ;)

A:

array_diff($array1, $array2) returns the values in $array1 that are not in $array2.
Therefore, you could get the values that have been added using:
$add = array_diff($new, $current)

and the values that were removed using:
$del = array_diff($current, $new)


Q:

Can you... get it on... with anyone or just certain characters?

In Dragon Age: Origins, is it possible to seduce anyone or are there only certain characters that each character is able to seduce?
I noticed that my female mage was able to start flirting with a female rogue, for example.  Are any of the NPC characters fair game or will the the dialogue just turn me down?

A:

Female characters have romance options available with Alistair, Zevran, and Leliana.
Male Wardens trade in Allistair for Morrigan, and can also romance Zevran and Leliana.
Basically, the rogues swing both ways.


Q:

jboss interceptor api 1.1 not found when added as sbt dependency

I'm trying to set jboss-interceptor-api-1.1 as a dependency via sbt, but it can't be found. I've searched on Maven Repository and this version is there, can anyone help me?
Actually, I'm trying to use sbt-assembly. Removing the plugin dependency and adding the dependency to libraryDependencies still shows that error.
Stack trace:
[info] Resolving org.jboss.interceptor#jboss-interceptor-api;1.1 ...
[info] Resolving org.jboss.interceptor#jboss-interceptor-api;1.1 ...
[warn] problem while downloading module descriptor: https://repo1.maven.org/maven2/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom: invalid sha1: expected=453b712ff6cda3a3f10f46a9ab9b9a42fc9bc021 computed=56da14e5a3e7e5656fe2ed1942d9fc0c1f3b054b (122ms)
[warn]  module not found: org.jboss.interceptor#jboss-interceptor-api;1.1
[warn] ==== typesafe-ivy-releases: tried
[warn]   https://repo.typesafe.com/typesafe/ivy-releases/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== sbt-plugin-releases: tried
[warn]   https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== local: tried
[warn]   /Users/vicaba/.ivy2/local/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom
[warn] ==== activator-launcher-local: tried
[warn]   /Users/vicaba/.activator/repository/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== activator-local: tried
[warn]   /Applications/activator-dist-1.3.12/repository/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== typesafe-releases: tried
[warn]   http://repo.typesafe.com/typesafe/releases/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom
[warn] ==== typesafe-ivy-releasez: tried
[warn]   http://repo.typesafe.com/typesafe/ivy-releases/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[info] Resolving javax.annotation#jsr250-api;1.0 ...
[info] Resolving javax.inject#javax.inject;1 ...
[info] Resolving org.eclipse.sisu#org.eclipse.sisu.inject;0.3.0 ...
[info] Resolving org.codehaus.plexus#plexus-component-annotations;1.5.5 ...
[info] Resolving org.codehaus.plexus#plexus-classworlds;2.5.2 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: org.jboss.interceptor#jboss-interceptor-api;1.1: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[info] Resolving com.typesafe.scala-logging#scala-logging_2.11;3.4.0 ...
[info] Resolving org.scala-lang#scala-library;2.11.8 ...
[info] Resolving org.slf4j#slf4j-api;1.7.21 ...
[info] Resolving ch.qos.logback#logback-core;1.1.7 ...
[info] Resolving ch.qos.logback#logback-classic;1.1.7 ...
[info] Resolving org.scala-lang#scala-reflect;2.11.8 ...
[info] Resolving org.scala-lang.modules#scala-parser-combinators_2.11;1.0.4 ...
[info] Resolving org.scala-lang#scala-compiler;2.11.8 ...
[info] Resolving org.scala-lang.modules#scala-xml_2.11;1.0.4 ...
[info] Resolving jline#jline;2.12.1 ...
[trace] Stack trace suppressed: run 'last *:updateSbtClassifiers' for the full output.
[error] (*:updateSbtClassifiers) sbt.ResolveException: unresolved dependency: org.jboss.interceptor#jboss-interceptor-api;1.1: not found
[error] Total time: 5 s, completed Feb 1, 2017 9:51:26 AM

A:

LCartwright is correct that this is due to the SHA-1 hash file differring from the hash of the POM on maven central.
To get around this you can add the JBoss maven repository, where the hash matches, to your resolvers in the global sbt config ~/.sbt/0.13/global.sbt
resolvers += "JBoss" at "https://repository.jboss.org/"

A:

I have the same issue in IntelliJ. When opening a project, it fails on jboss-interceptor-api. This is part of the log:
[info] Resolving org.apache.maven#maven-artifact;3.2.2 ...
[info] Resolving org.apache.maven#maven-plugin-api;3.2.2 ...
[info] Resolving org.eclipse.sisu#org.eclipse.sisu.plexus;0.0.0.M5 ...
[info] Resolving javax.enterprise#cdi-api;1.0 ...
[info] Resolving org.jboss.interceptor#jboss-interceptor-api;1.1 ...
[info] Resolving org.jboss.interceptor#jboss-interceptor-api;1.1 ...
[warn] problem while downloading module descriptor: https://repo1.maven.org/maven2/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom: invalid sha1: expected=453b712ff6cda3a3f10f46a9ab9b9a42fc9bc021 computed=56da14e5a3e7e5656fe2ed1942d9fc0c1f3b054b (108ms)
[warn]  module not found: org.jboss.interceptor#jboss-interceptor-api;1.1
[warn] ==== typesafe-ivy-releases: tried
[warn]   https://repo.typesafe.com/typesafe/ivy-releases/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== sbt-plugin-releases: tried
[warn]   https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== local: tried
[warn]   /Users/jessedobbelaere/.ivy2/local/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom
[warn] ==== Typesafe repository: tried
[warn]   http://repo.typesafe.com/typesafe/releases/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom
[warn] ==== bintray-kamon-io-sbt-plugins: tried
[warn]   https://dl.bintray.com/kamon-io/sbt-plugins/org.jboss.interceptor/jboss-interceptor-api/1.1/ivys/ivy.xml

I noticed that when unchecking "Download Sources for SBT and plugins" in IntelliJ, everything works perfectly fine

A:

Seems like the culprit is this line
[warn] problem while downloading module descriptor: https://repo1.maven.org/maven2/org/jboss/interceptor/jboss-interceptor-api/1.1/jboss-interceptor-api-1.1.pom: invalid sha1: expected=453b712ff6cda3a3f10f46a9ab9b9a42fc9bc021 computed=56da14e5a3e7e5656fe2ed1942d9fc0c1f3b054b (108ms)

reporting an incorrect SHA-1 for the pom file.

pom: jboss-interceptor-api-1.1.pom
pom SHA-1: jboss-interceptor-api-1.1.pom.sha1

The SHA-1 for the pom is 56da14e5a3e7e5656fe2ed1942d9fc0c1f3b054b however the accompanying pom.sha1 file is 453b712ff6cda3a3f10f46a9ab9b9a42fc9bc021
As suggested above, unchecking "Download Sources for SBT and plugins" will solve your issue for now. Not sure who to contact to update the pom.sha1


Q:

In Jenkins scripted pipeline getting Result from a job which was not directly triggered by the pipeline

We have a Jenkins-Job (Job A) which pushes some artifacts to a git repository. This push triggers a different Jenkins-Job (Job B) which tests the newly pushed artifacts.
Job A sends a message which tells if everything was fine or if an error happened. But to have the information for the notification complete, Job A need to know at least if Job B was successful (having the log would be even better).
I now want to know if there is a possibility to retrieve the result of a finished job even if this job was not triggered by the job which needs the information?
Also is there a possibility to block Job A during Job B is running? I found the Block Build Plugin but this blocks a job only from starting until the specified jobs are finished.

A:

That's a very strange setup. Looks like those should be stages not separate jobs. Still it's possible to get any job's status by using the jenkins json API
jenkins_url/job/${job_name}/lastBuild/api/json?tree=result,timestamp,estimatedDuration

Interesting question would be - how would you know which other job's number to check if those are triggered independently?


Q:

Can CSS box-shadow distance be overridden without re-setting the color?

I'd like to override the distance on box-shadow without having to set the color again.
Use case here is I have a .button class with this:
.button {
  color: white;
  background: blue;
  padding: 8px 15px;
  font-size: 1.2em;
  border: 3px solid black;
  box-shadow: 0 3px 0 black;
}

Then I have a .button-small class that is effectively a child of .button that makes some minor tweaks to things.
.button.button-small {
  padding: 4px 10px;
  font-size: 1em;
  border-width: 2px;
  box-shadow: 0 2px 0 black;
}

As you can see, I can easily change the border-width without redefining the entire border property.
Is there a way to do that with box-shadow? Some sort of box-shadow-distance property?

A:

Use CSS variables:

.button {
  color: white;
  background: blue;
  padding: 8px 15px;
  font-size: 1.2em;
  border: 3px solid black;
  box-shadow: 0 var(--d, 5px) 0 black; /* 5px is the fallback/default value until you set the variable */
}

.button.button-small {
  --d: 2px;
}
button

button

button


Q:

Lenovo C930 WiFi card not recognized. Fix?

I just installed Ubuntu 18.10 on my Lenovo C930. It doesn’t recognize its WiFi card in Ubuntu.
Fix was identified as:
sudo modprobe -r ideapad-laptop
But this needs to be done every time I boot into Ubuntu.  Where to I place this to take effect every boot?
Thanks!
Note this is not a duplicate of This Thread.  This question addresses how to avoid the need to modprobe every time I boot which is not covered.

A:

modprobe -r removes a [kernel] module, so you can blacklist it to avoid it's being loaded in the future.
add the line

blacklist ideapad-laptop

to /etc/modprobe.d/blacklist.conf so it doesn't get as a kernel module.


Q:

XMLBeans get_store() method returns null

I am developing a Axis2 based WebServices with XMLBeans binding. I have generated the code by using WSDL2Java generator and tried testing it with sample values set in the request.
In one of the setter methods (auto-generated code) I found the below code. The method get_store() returns a null value and hence I get a NullPointerException.
target = (org.apache.xmlbeans.SimpleValue)
    get_store().find_element_user(TRANSACTIONTYPE$0, 0);

I tried Google to find the solution and found similar issue with no solution specified.
Is there any work around for this issue?? Kindly help me

A:

This issue got resolved!!
I was actually trying to instantiate a response object in a normal Java way and hence i got the above mentioned exception while running my WebServices.
Wrong way - ResponseType responseType = new ResponseType();
Correct way - ResponseType responseType = ResponseType.Factory.newInstance();


Q:

Combine Regexp and set of values (hash/array) to compare if a string matches in ruby

I have the following pattern to check:
"MODEL_NAME"-"ID"."FORMAT_TYPE"

where, for example:
MODEL_NAME = [:product, :brand]
FORMAT_TYPE = [:jpg, :png]

First I wanted to check if the regexp is something like:
/^\w+-\d+.\w+$/

and I have also to check if the part of my string is part of my arrays. I want something more flexible than:
/^(product|brand)-\d+.(jpg|png)$/

which I could manage through my arrays. What is a good solution to do it?

A:

/^(#{MODEL_NAME.join '|'})-\d+\.(#{FORMAT_TYPE.join '|'})$/
# => /^(product|brand)-\d+\.(jpg|png)$/


Q:

Язык Core GHC.Num.$fNumInteger

Что означает GHC.Num.$fNumInteger в данном коде?
main =
     print
     @ Integer
     GHC.Show.$fNumInteger
     (+ @ Integer GHC.Num.$fNumInteger 10 11)

A:

Ограничения на класс типов (Num a => ... в данном случае) в результате компляции превращаются в дополнительный аргумент функции. Этот аргумент представляет собой структуру данных, содержащую реализацию методов класса для данного конкретного типа. Что-то вроде vtable в С++.
Т.е. если у нас есть класс Foo
class Foo a where
  foo :: a -> String

и есть функция, принимающая тип класса Foo
bar :: Foo a => a -> Int

то в Core вызов этой bar для конкретного типа a превратится в функцию двух аргументов - словаря Foo, содержащего реализацию foo для указанного a и самого a.
В твоем случае ты вызвал print (10 + 11), и в этом выражении числовые константы имеют тип Num Integer, а + как раз является методом класса Num.


Q:

Show Form2 on Excel event BeforeSave

In Visual Studio 2017 I'm creating a Windows Form Application with a Form1 where the user picks an opened Excel workbook to listen to its BeforeSave event.
Once that workbook is saved, it gets detected by the program which then colects some specific data from the sheets and opens Form2 with that data.
The issue I'm having is that when I load Form2 on the BeforeSave event, its controls (like Labels, buttons, textboxes, etc) don't show correctly. They appear like boxes with a background color.
Here's my code reduced and changed to the part that matters:
' Reference:
' Microsoft Excel 15.0 Object Library
Imports Microsoft.Office.Interop
Public Class Form1
    Private xlApp As Excel.Application
    Public Shared WithEvents xlBook As Excel.Workbook
    Private Shared Sub Workbook_BeforeSave(SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles xlBook.BeforeSave
        Form2.Show()
        'Form1.Close()
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            xlApp = Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
            xlBook = xlApp.Workbooks(1)
        Catch
            MsgBox("Excel isn't opened.")
            Close()
        End Try
    End Sub
End Class

Edit: Using Application.Run(Form2) works (don't know why) but then I also can't close Form1 with Form1.Close().

A:

The BeforeSave event like the other Interop.Excel events is raised on a different thread. Therefore, you can't access the GUI thread directly from it. In order to access the GUI thread (e.g., access form controls, create a form on the main thread, etc.), you need to call the Invoke method with a delegate.
Replacing Form2.Show() with the following would solve the problem:
Invoke(Sub() Form2.Show())

However, you should create a new instance of the form that you want to load. So, instead of the previous line,  you should use something like the following:
Private Sub Workbook_BeforeSave(SaveAsUI As Boolean,
                                ByRef Cancel As Boolean) Handles xlBook.BeforeSave
    Invoke(Sub()
               Dim frm As New Form2
               frm.Show()
           End Sub)
End Sub

To learn more about WinForms thread-safe calls, check the first article in the references.

References:

How to: Make Thread-Safe Calls to Windows Forms Controls
Why is there a default instance of every form in VB.Net?


Q:

Hive join optimization

I have two sets of data both stored in an S3 bucket which I need to process in Hive and store the output back to S3. Sample rows from each datasets are as follows:
DataSet 1: {"requestId":"TADS6152JHGJH5435", "customerId":"ASJHAGSJH","sessionId":"172356126"}

DataSet2: {"requestId":"TADS6152JHGJH5435","userAgent":"Mozilla"}

I need to join these two data sets based on the requestId and output a combined row as:
Output:  {"requestId":"TADS6152JHGJH5435", "customerId":"ASJHAGSJH","sessionId":"172356126","userAgent":"Mozilla"}

The requestIds in dataset 1 is a proper subset of of the requestids in dataset 2. I am using a LEFT OUTER JOIN to get my output. Here is a simplified version of my Hive script:
CREATE EXTERNAL TABLE dataset1 (
     requestId string,
     customerId string,
     sessionId string
 )
LOCATION 's3://path_to_dataset1/';

CREATE EXTERNAL TABLE dataset2 (
     requestId string,
     userAgent string
 )
LOCATION 's3://path_to_dataset2/';

CREATE EXTERNAL TABLE output (
     requestId string,
     customerId string,
     sessionId string,
     userAgent string
 )
LOCATION 's3://path_to_output/';

INSERT OVERWRITE TABLE output
  SELECT d1.requestId, d1.customerId, d1.sessionId, d2.userAgent
  FROM dataset1 d1 LEFT OUTER JOIN dataset2 d2
  ON (d1.requestId=d2.requestId);

My question is:
Are there opportunities to optimize this join? Can I use partitioning/bucketing of the tables to run the join faster? I have set hive.auto.convert.join to true in my script. What other hive properties should I set to gain better performance for the above queries?

A:

1. Optimize Joins

We can improve the performance of joins by enabling Auto Convert Map Joins and enabling optimization of skew joins.
Auto Map Joins

Auto Map-Join is a very useful feature when joining a big table with a small table. if we enable this feature, the small table will be saved in the local cache on each node, and then joined with the big table in the Map phase. Enabling Auto Map Join provides two advantages. First, loading a small table into cache will save read time on each data node. Second, it avoids skew joins in the Hive query, since the join operation has been already done in the Map phase for each block of data.
Skew Joins

We can enable optimization of skew joins, i.e. imbalanced joins by setting hive.optimize.skewjoin property to true either via SET command in hive shell or hive-site.xml file.
  <property>
    <name>hive.optimize.skewjoin</name>
    <value>true</value>
    <description>
      Whether to enable skew join optimization.
      The algorithm is as follows: At runtime, detect the keys with a large skew. Instead of
      processing those keys, store them temporarily in an HDFS directory. In a follow-up map-reduce
      job, process those skewed keys. The same key need not be skewed for all the tables, and so,
      the follow-up map-reduce job (for the skewed keys) would be much faster, since it would be a
      map-join.
    </description>
  </property>
  <property>
    <name>hive.skewjoin.key</name>
    <value>100000</value>
    <description>
      Determine if we get a skew key in join. If we see more than the specified number of rows with the same key in join operator,
      we think the key as a skew join key.
    </description>
  </property>
  <property>
    <name>hive.skewjoin.mapjoin.map.tasks</name>
    <value>10000</value>
    <description>
      Determine the number of map task used in the follow up map join job for a skew join.
      It should be used together with hive.skewjoin.mapjoin.min.split to perform a fine grained control.
    </description>
  </property>
  <property>
    <name>hive.skewjoin.mapjoin.min.split</name>
    <value>33554432</value>
    <description>
      Determine the number of map task at most used in the follow up map join job for a skew join by specifying
      the minimum split size. It should be used together with hive.skewjoin.mapjoin.map.tasks to perform a fine grained control.
    </description>
  </property>

2. Enable Bucketed Map Joins

If tables are bucketed by a particular column and these tables are being used in joins then we can enable bucketed map join to improve the performance.
  <property>
    <name>hive.optimize.bucketmapjoin</name>
    <value>true</value>
    <description>Whether to try bucket mapjoin</description>
  </property>
  <property>
    <name>hive.optimize.bucketmapjoin.sortedmerge</name>
    <value>true</value>
    <description>Whether to try sorted bucket merge map join</description>
  </property>

.
3. Enable Tez Execution Engine

Instead of running Hive queries on venerable Map-reduce engine, we can improve the performance of hive queries at least by 100% to 300 % by running on Tez execution engine. We can enable the Tez engine with below property from hive shell.
hive> set hive.execution.engine=tez;

.
4. Enable Parallel Execution

Hive converts a query into one or more stages. Stages could be a MapReduce stage, sampling stage, a merge stage, a limit stage. By default, Hive executes these stages one at a time. A particular job may consist of some stages that are not dependent on each other and could be executed in
parallel, possibly allowing the overall job to complete more quickly. Parallel execution can be enabled by setting below properties.
  <property>
    <name>hive.exec.parallel</name>
    <value>true</value>
    <description>Whether to execute jobs in parallel</description>
  </property>
  <property>
    <name>hive.exec.parallel.thread.number</name>
    <value>8</value>
    <description>How many jobs at most can be executed in parallel</description>
  </property>

.
5. Enable Vectorization

Vectorization feature is introduced into hive for the first time in hive-0.13.1 release only. By vectorized query execution, we can improve performance of operations like scans, aggregations, filters and joins, by performing them in batches of 1024 rows at once instead of single row each time.
We can enable vectorized query execution by setting below three properties in either hive shell or hive-site.xml file.
hive> set hive.vectorized.execution.enabled = true;
hive> set hive.vectorized.execution.reduce.enabled = true;
hive> set hive.vectorized.execution.reduce.groupby.enabled = true;

.
6. Enable Cost Based Optimization

Recent Hive releases provided the feature of cost based optimization, one can achieve further optimizations based on query cost, resulting in potentially different decisions: how to order joins, which type of join to perform, degree of parallelism and others.
cost based optimization can be enabled by setting below properties in hive-site.xml file.
  <property>
    <name>hive.cbo.enable</name>
    <value>true</value>
    <description>Flag to control enabling Cost Based Optimizations using Calcite framework.</description>
  </property>
  <property>
    <name>hive.compute.query.using.stats</name>
    <value>true</value>
    <description>
      When set to true Hive will answer a few queries like count(1) purely using stats
      stored in metastore. For basic stats collection turn on the config hive.stats.autogather to true.
      For more advanced stats collection need to run analyze table queries.
    </description>
  </property>
  <property>
    <name>hive.stats.fetch.partition.stats</name>
    <value>true</value>
    <description>
      Annotation of operator tree with statistics information requires partition level basic
      statistics like number of rows, data size and file size. Partition statistics are fetched from
      metastore. Fetching partition statistics for each needed partition can be expensive when the
      number of partitions is high. This flag can be used to disable fetching of partition statistics
      from metastore. When this flag is disabled, Hive will make calls to filesystem to get file sizes
      and will estimate the number of rows from row schema.
    </description>
  </property>
  <property>
    <name>hive.stats.fetch.column.stats</name>
    <value>true</value>
    <description>
      Annotation of operator tree with statistics information requires column statistics.
      Column statistics are fetched from metastore. Fetching column statistics for each needed column
      can be expensive when the number of columns is high. This flag can be used to disable fetching
      of column statistics from metastore.
    </description>
  </property>
  <property>
    <name>hive.stats.autogather</name>
    <value>true</value>
    <description>A flag to gather statistics automatically during the INSERT OVERWRITE command.</description>
  </property>
  <property>
    <name>hive.stats.dbclass</name>
    <value>fs</value>
    <description>
      Expects one of the pattern in [jdbc(:.*), hbase, counter, custom, fs].
      The storage that stores temporary Hive statistics. In filesystem based statistics collection ('fs'),
      each task writes statistics it has collected in a file on the filesystem, which will be aggregated
      after the job has finished. Supported values are fs (filesystem), jdbc:database (where database
      can be derby, mysql, etc.), hbase, counter, and custom as defined in StatsSetupConst.java.
    </description>
  </property>


Q:

Resolving promises synchronously with Q.all(promises)

I am using the Kriskowal Q library to handle promises.
I wrote the following function to wait until all promises have been resolved.
function multiplePromises(targetArray) {
    var promises = {};
    for (var i=0; i<targetArray.length; i++) {
        var promise = singlePromise(); // any async. function
        promises[i] = promise;
    };
    return Q.all(promises);
};

and I call it as follows:
multiplePromises(targetArray).then(
     function(success){
         console.log("success");
     },
     function(error){
        console.log("error", error);
     }
);

I was wondering however whether there is an order in which the promises are resolved (e.g. is it synchronous?). I.e. does the function wait to trigger the next promise i+1 until promise i is resolved? Or alternatively is it like with all other async. methods, that it actually fires all the single promises and just waits until they are all done?
If the second is the case, how would one rewrite this function to make sure that promise i+1 is ONLY triggered once promise i has been resolved?
Update: test
I did a test and put:
promises[i] = i;

to check whether it resolves sycnhronously and it seems the case. However, it could be just that my async function is fast enough to actually resolve it that quick. Does this seem right?

A:

there are several ways to achieve what you want
Minimal change to your code would be
function multiplePromises(targetArray) {
    var promises = [];
    var p = Promise.resolve(); // I don't know the Q equivalent of this
    for (var i=0; i<targetArray.length; i++) {
        p = p.then(function() {
            return singlePromise();
        });
        promises[i] = p;
    };
    return Q.all(promises);
};


Q:

Python IDLE shell - How to make multiline strings

ANSWERED (But if for some reason you want to read it you can)

I am a beginner at Python and I know how to type the correct syntax but when I repeat it, it comes out with no extra lines, it just says "\n"
DETAILS ON EXAMPLE BELOW:
My variable is fred and I set it to what it says below, and then on the 3rd line I made it print the text.
Please tell me if I didn't describe it correctly, keep in mind I'm a beginner.
EXAMPLE:
>>> fred = '''How do dinosaurs pay their bills?
With tyrannosaurus checks!'''
>>> fred
'How do dinosaurs pay their bills?\nWith tyrannosaurus checks!'

A:

The \n in that string represents the new line symbol. For pretty much all purposes, it is a new line.
What you're doing is correct.
To print the lines on separate lines:
for line in jack.split("\n"):
    print(line)


Q:

How does object focus work in VBA?

Worksheet and Workbook objects can have their properties accessed in two ways.

Explicitly ➔ Sheet1.cells(1,2)
Implicitly ➔ Cells(1,2)

What I'm curious about is how does VBA know which object to use when a property is called implicitly? And are there more objects that are compatible with these implicit calls?
Here is a simple experimentation I threw together, it shows some cases where object focus changes and when it doesn't:
'Sheet1 has 2 row in column A
'Sheet2 has 5 rows in column A
Sub test()
    Dim obj As Object
    Set obj = Sheet1

    'focus is set when a sheet is called directly
    row1 = Sheet2.Range("A" & Rows.Count).End(xlUp).Row

    'focus is set when a sheet is called through reference
    row2 = obj.Range("A" & Rows.Count).End(xlUp).Row

    'focus is not set by with
    With Sheet2
        row3 = Range("A" & Rows.Count).End(xlUp).Row
    End With

    'output = 5 : 2 : 2
    MsgBox row1 & " : " & row2 & " : " & row3
End Sub

A:

All Excel object references work like this:
Workbook -> Worksheet -> Range
If you leave out the previous node, Excel substitutes the "Active" object for the omitted ones.  Examples:
Sheet1.Cells(1,1) is the same as ThisWorkbook.Sheets("Sheet1").Cells(1,1)
Cells(1,1) is the same as ActiveWorksheet.Cells(1,1)


Q:

Dashboard for displaying widgets with lots of similar output

I am trying to create a dashboard to be displayed in an office on a TV screen which allows staff to quickly see relevant statistics. For each statistic it needs to show the current value as well as a comparison to a prior value - for example, show signups today and compare to signups yesterday with colours indicating better, worse or same.
There also needs to be some element of trending so it shows today, last 7 days and last 30 days - again each with a comparison to the prior period.
Additionally there is other data to be shown like charts for web traffic, server performance metrics and so on.
There isn't really a viable way to allow to click for more as the screen is shared with
multiple users and one person clicking would then impact everyone's display.
The charts etc are not an issue but the widgets to show statistics (there are 8 of these sets of statistics which need to be shown) are taking up too much space and are too hard to be able to read (and therefore be useful) mainly as they are so small and they all blur into one making easy distinction between signups and conversions, for example, almost impossible.

Is there a better way to show lots of widgets of this type and also can the historic and trending etc be better facilitated which, in itself, may make it easier to display the data as it could reduce the number of boxes?

A:

A few thoughts:
Time-multiplex the data. You can cycle through the sets of statistics, displaying each set for about 10 seconds. That way, you can use the entire screen to show only one set. This is only good if it’s not particularly important for users to see every statistic all the time (e.g., the TV is intended to provide an occasional motivation boost or to give the workplace a high-tech real-time emotional feel). It’s also only good if the TV is placed such that the constantly changing screen doesn’t annoy or distract users from their work, but is nonetheless noticeable (e.g., it’s in the elevator lobby, where the users have little else to look at anyway).
Multiple TVs. You can show different sets of statistics on different screens. This is especially desirable if different users are interested in different statistics or time periods. You can arrange the TVs in one full-wall matrix, or (better) you can distribute the different TVs around the workplace so each group of users can most easily see the data it uses the most (assuming the users themselves are located around the workplace by function at more-or-less fixed workstations). This, of course, means greater hardware expense, and wall space consumption, which may not be available.
Eliminate low-priority data. You can review your user research and eliminate the statistics that are least useful for the purpose the TV serves. For example, for at-a-glance look, maybe the monthly data are not useful to see all day long, day after day, because they change so slowly. Let users access those data a different way (e.g., by subscribing to a monthly tweet). On the other hand, maybe the daily data are not useful without more context because they’re subject to so much random variation. Maybe those are better left to an interactive desktop app. Maybe weekly data say pretty much the same thing that monthly data say (they’re only separated by a factor of four), so one can be eliminated from the TV.
Create a combined metric. You can combine several related statistics into a single metric of performance. For example, you can take the weighted average of sign-ups, conversions, and downloads to represent the general activity level. Review your user research to see how users mentally combine statistics to get an idea of what would make useful combined metrics. This, of course, can mean training and educating users on a new metric.
Reduce display redundancy. Rather than label each statistic like you’ve done in your mockup (e.g., “Signups today”), you can provide row and column headers (e.g., Today, This Week, This Month across the top, and each statistic name down the left margin). This means fewer characters to fit in the same space so each character can be larger. If the statistics widgets show information related to the charts, integrate the statistics with the charts, reusing as many elements as possible (e.g., statistic names).
Consider graphic representation.  Rather than displaying a grid of 48 individual numbers, you can combine related numbers into a single graphic. For example, you could show each statistic as a line graphic of the daily quantity over two months. You can superimpose on this graph the weekly and/or monthly moving average. This would show the daily and weekly/monthly relative levels and trends more clearly and precisely than six individual numbers (even with your color coding). Because the graphs will be small, with the y-axis values hard to read, this only works if users are primarily interested in relative levels and trends, not absolute values. That is, a line graph is better for seeing how much higher Statistic A has gotten (e.g., versus Statistic B); the grid it better if users are looking for a single precise numeric value (e.g., 210). There may be helpful ways to combine multiple related statistics into a single graphic too. Other graphic representations depend on the details of how the data are used.


Q:

Is it possible make a button to change customer group?

I have 3 customer groups and my store already sets the customer to their group automaticly.
What I'm trying to do is allow the customer in group 2 change their group to 3 (and vice-versa) clicking a button in the cart page. Is it possible?
I'm trying to use:
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setData( 'group_id', 3 );
$customer->save();

But how can I save this changes?
I'm using version 1.9.3

A:

You have to create a controller then you put your code inside.
You call your controller in a button like this: $this->getUrl('modulefontname/modulename/action');
Your button should look like this:
<button type="button" onclick="setLocation('<?php echo Mage::getUrl('modulefontname/modulename/action'); ?>')"><?php echo $this->__('Change customer group') ?></button>


Q:

How to read EMV chip data from the IDTECH spectrum pro device in C#?

I have a requirement to read the EMV supported credit/debit card details from the IDTech Spectrum Pro card reader.
The problem is I should not use the IDTECH EMV related APIS for this. Since the customer have some restriction.
So is there any APDU command to read the encrypted card data from the CHIP directly using the IDTECH card reader?
Also
What are the things I need to try/check before starting the implementation since i am new to this?
Hope i will not get downVote!

A:

No 1:
IDTECH Spectrun Pro device come up with their own protocol. So you cant speak with Reader device unless you dontknow the IDTECH Protocol.
So you cant pass the APDU Commands to the reader (in my knowledge)
No 2:
So ask your IDTECH support about the reading PAN (EMV tag- 5A) data of the card and Track 2 data (EmV tag - 57) Since normally the reader will return as a Masked/Encrypted data.
No 3:
There is one option called "PrePANCtrlData"(0~6) and "PostPANCtrlData"(0~4), So ask them how to set this bit using their dll and ask them Is it possible to get the unmasked data if you set the value to 0 to the same.
Hope this helps.
Thanks


Q:

How to close previous activities when activity launch by intent-filter happens?

I have an Activity, that launches from browser by this intent-flter:
   <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="myapp" />
            <data android:host="someaction"/>
            <data android:path="/" />
        </intent-filter>

But if i have other activities of my app not destroyed, they will appear behind launched activity. I need somehow use CLEAR_TOP flag but with intent filter. Activity's launchMode was set to singleTop
and i can't use singleInstance or singleTask. So how can launch only my desirable activity and not the others?

A:

Solution 1
I'd try this with some BroadCast event. Send one from the Activity you start, and add BroadcastReceivers to the ones you'd like to close.
Check this answer, I think it should help you.
Solution 2
I would also give this a try: set you activity's intent flag as FLAG_ACTIVITY_CLEAR_TOP. Also you can consider using the following intent flags: FLAG_ACTIVITY_CLEAR_TASK FLAG_ACTIVITY_NEW_TASK


Q:

I can't remove items from FlatList by useState hook

I am trying to remove items in FlatList by clicking on each, But it doesn't work for me, when i click on each item nothing happen and i don't get any error.
How can i fix this?
This is my code:(I removed unnecessary codes and styles)
const FoodList = () => {

  const data=  [

        { text: 'test' },
        { image: 'https://via.placeholder.com/200x100' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },
        { text: 'test' },

    ]

    let [itemState, setitemState] = useState(data);

    return (

        <View>
            <FlatList
                data={data}
                keyExtractor={(item, index)=>index}
                renderItem={({ item }) => (
                    <TouchableOpacity>

                <View>
                        <Text>{item.text}</Text>
                        <Image source={{ uri: item.image}}
                        />
                    </View>
                    <Icon
                 onPress={(index)=>setitemState(itemState=itemState.filter(item=>item.index!==index))} />
                    </TouchableOpacity>
                )}
 />
 </View>
    )}

A:

Firstly, as mentioned by @Hamza Khattabi, you will need to use itemState in the data prop to actually use the updated state, otherwise there is no point of using setitemState, which modifies only the itemState state.
Secondly, I don't think item.index will return anything at all, and I'm pretty confident that the onPress={(index) => {...}} in your Icon element is not returning any index either. You will have the use the index from the renderItem prop, as mentioned in the docs at this link.
Once you account for those changes, you can then simply filter out the itemState state to remove the element at the index. There are many different ways to remove the element at an index, but here is a possible solution:
<FlatList
  data={itemState} // Note the use of itemState
  keyExtractor={(item, index) => index}
  renderItem={({ item, index }) => ( // Note the use of index
    <TouchableOpacity>
      <View>
        <Text>{item.text}</Text>
        <Image source={{ uri: item.image }} />
      </View>
      <Icon
        onPress={() => { // Note that here you can use any function to remove the element at index from the itemState list
          let _itemState = itemState.filter(
            (_item, _index) => _index !== index
          );
          setitemState(_itemState);
        }}
      />
    </TouchableOpacity>
  )}
/>

Let me know if this helps you by commenting below.


Q:

How to set the scroll speed of apple magic mouse?

How to set the scroll speed of apple magic mouse?
I only found the moving speed.

A:

At the moment only way is setup it directly in hid_magicmouse driver.
For testing run:
sudo rmmod hid_magicmouse
# scroll-speed value from 0 (slow) to 63 (fast):
sudo modprobe hid_magicmouse scroll-speed=45 scroll-acceleration=1

For permanent settings put to the /etc/modprobe.d/magicmouse.conf this:
options hid_magicmouse scroll-speed=45 scroll-acceleration=1

A:

You can also write to the parameters via the /sys kernel interface:
$ ls /sys/module/hid_magicmouse/parameters/
emulate_3button  emulate_scroll_wheel  report_undeciphered  scroll_acceleration  scroll_speed
$ cat /sys/module/hid_magicmouse/parameters/scroll_speed
45
$ echo N | sudo tee /sys/module/hid_magicmouse/parameters/scroll_acceleration
N

You can ogle the source here: http://lxr.free-electrons.com/source/drivers/hid/hid-magicmouse.c


Q:

VB 14 missing from Visual Studio 2015

I have Visual Studio 2015, but can't get the new VB language features to work. Or to show up. It's like the product came without it.  The null-coalescing operator doesn't work, read-only auto-properties aren't allowed, etc.  This is true even when I set up a brand new project, targeting any version of the framework (which shouldn't matter, but I'm trying everything I can think of).
I've got Resharper 9 installed.  Following a suggestion in this question, if I select the project, the VB Language Level dropdown list doesn't show anything more recent than "Visual Basic .NET 12".
There are no LangVersion tags anywhere in the .vbproj files. If I add them it seems to make no difference.
I was under the impression that you didn't have to install anything separately for VB 14, just use VS 2015 and you'll have it (C# 6 actually is available and working in C# projects) but it's not there.
Anybody have any ideas what else I can look for?

A:

It's Resharper.
I'm using Resharper 9.2 Ultimate.  Resharper is what's putting all the error messages into the code editor.  If I suspend it, all the problems go away, and the code compiles and runs exactly as it should.
I should have taken a cue from the fact that the VB Language Level isn't showing the latest version of VB.
Off to contact technical support.


Q:

MongoDB upsert an array field in a document or simply use objects

For example, we have collection of people, each like this.
{name : 'john'}

Now I want to add an array field called girlsfriends, so like
{name : 'john', girlfriends: ['Stacy']}

How is this generally done? Do it in two steps in application code?

Check if girlfriends field exists on person document?
a. if not exists: $set person girlsfriends to ['Stacy']
b. if exists: push element to array?

So either do this or
simply initialize the array field to [] on each document creation? Or some just use objects? generate a random ID as key?
Is there benefit to use array over object? Seems like quite a hassle with the queries..
Edit:
Alright never mind. I shoulda just tried the $push method.. For anyone that comes across, the MongoDB doc is a bit ambiguous when it says

If the field is not an array, the operation will fail.

If the field doesn't exist, it will create it for you... ofc it will.. its mongo..

A:

You can directly use the $push or $addToSet operators in an update query.
If the array doesn't exist it will be created by these operators.
The $addToSet will keep only unique elements in your array, so that you don't need to check if it's already inside the array.
Here's the full query:
db.<your_collection>.updateOne({name:'John'},{$addToSet:{girlfriends:'Stacy'}})

Proof:
> db.toto.insertOne({name:"John"})
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5d2f325cf1789f14256be87a")
}
> db.toto.find()
{ "_id" : ObjectId("5d2f325cf1789f14256be87a"), "name" : "John" }
> db.toto.updateOne({name:"John"},{$addToSet:{girlfriends:"Stacy"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.toto.find()
{ "_id" : ObjectId("5d2f325cf1789f14256be87a"), "name" : "John", "girlfriends" : [ "Stacy" ] }

Is there benefit to use array over object?

Well, that's a long subject. But long story short, the only time you might be tempted to use an object instead of an array is in case of a Map. For example:
"map": {
  "id1": "value1",
  "id2": "value2",
  "id3": "value3"
}

I would definitely recommend NOT to use this structure as it's really hard to maintain and index.
Instead I would recommend using this structure:
"map": [
  { key:"id1", value: "value1" },
  { key:"id2", value: "value2" },
  { key:"id3", value: "value3" }
]

You can then index each field separately.


Q:

Content-Length is being stripped

I'm using webpy 0.34, python 2.6.6. I'm also using mimerender. I am trying to include the content-length in my http response, but for some reason the header is being removed. I say removed because I can create custom headers just fine, and I can see those headers on the client. But when I try to set content-length, the header never makes it to the client. I've tried including the header in the web.created object (as shown) and I've also tried using
web.header('Content-Length', len(data))

What am I doing wrong and/or not understanding about how this code works?
render_json = lambda **args: json.JSONEncoder().encode(args)

class MyHandler:
    @mimerender(
            default = 'json',
            json = render_json,
            )
    def POST(self):
        data = "abcd"
        raise web.created(data, headers={'Content-Length': len(data)})

A:

If the data is sent as chunked (Transfer-Encoding: chunked), then the Content-Length header must be omitted, as per RFC 2616:

[snip]
If a Transfer-Encoding header field (section 14.41) is present and
   has any value other than "identity", then the transfer-length is
   defined by use of the "chunked" transfer-coding (section 3.6),
   unless the message is terminated by closing the connection.
If a Content-Length header field (section 14.13) is present, its
   decimal value in OCTETs represents both the entity-length and the
   transfer-length. The Content-Length header field MUST NOT be sent
   if these two lengths are different (i.e., if a Transfer-Encoding
   header field is present). If a message is received with both a
   Transfer-Encoding header field and a Content-Length header field,
   the latter MUST be ignored.


Q:

Represent format of the date 2018-01-01T17:11:11.111+06:00 in string

How can I represent format of 2018-01-01T17:11:11.111+06:00 in string?
I've tried yyyy-MM-dd'T'HH:mm:ss.SSS+HH:mm, but it didn't work.
It is needed for range query in elasticsearch using elastic4s.

A:

Let' try:
YYYY-MM-dd'T'HH:mm:ss.SSSz

I suggest to you this app for check the format:
https://esddd.herokuapp.com/


Q:

What is the proper way to change a Text View's default content on iOS 6?

I asked a question about the "following the tutorial" app at http://jonathanscorner.com/project/Quotes.tgz, and a couple of people pointed out where the loose wire was; I had not connected the IBOutlet correctly.
I thought, somewhat playfully, that I would replace the Text View's lorem ipsum from the storyboard with "Hello, Australia!", when I met an unexpected behavior. Every single change I made from the iPhone storyboard by clicking on the Text View and editing and saving the text results with a black screen on the simulator. If I undo the storyboard edit and restore the original state, and I save it, the app displays the original lorem ipsum (which is replaced by a quote if you click on the button), but that's all I've gotten it to display at start.
Is there some extra work involved in replacing the text initially displayed in a view? I could probably change it with duct tape by invoking a similar call to the one that pulls the quotes, but I'd like to know what is broken about my approach of "Update it from the storyboard WYSIWYG." I'd like to know what the best engineering way is to make that Text View initially display "Hello, Australia!" or some such string besides the "free with each install" lorem ipsum.
Thanks,

A:

I don't think that there is any way to change the default placeholder for the UIText view, although I probably hate seeing that "lorem ipsum..." crap more than you do!
As to why your simulator displayed a black screen is quite mysterious. There should have been no reason it would have done that (using the data you gave). I would try editing the text in the Attributes inspector and see if that gives the same results. But as the other answer says, you could also just double click on the text in the UITextView, replace it, and hit enter. and it should work.
So no, no way to change the default placeholder (grrrrrrrr...).


Q:

jQuery freezes between show and hide

see this fiddle it shows #red on hover over #btn and hide it on mouse leave, simple.
$(function() {
    $('#btn').hover(function(){
        $('#red').stop().show(2000);
    }, function(){
        $('#red').stop().hide(2000);
    });
})

but just try to Hover, Leave, and Hover again in less than two seconds, #red freezes somewhere in between.
as last method called on hover line is show(), why doesn't it show completely again?
thanks

A:

I can easily reproduce the problem when I test it in Chrome, IE 11 and Firefox. Apparently the show doesn't work when the element isn't completely hidden. Adding a hide before the show makes it behave nicely:
$('#btn').hover(function(){
    $('#red').stop().hide().show(2000);
}, function(){
    $('#red').stop().hide(2000);
});

Demo: http://jsfiddle.net/Guffa/9k3b2cp1/2/


Q:

php wordpress query

I had posted this earlier on Stack Overflow, but couldn't get a positive result. I thought I should do this again.
<?php require_once 'news/wp-config.php';
$howMany = 0;
$query ="SELECT `ID`, `post_title`,'post_category', `guid`,SUBSTRING_INDEX(`post_content`, ' ', 100) AS `post_excerpt` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_type` = \"post\" AND post_category != \"1\" ";
$posts = $wpdb->get_results($query);
$posts = array_reverse($posts);
foreach($posts as $post)
{
    if($howmany<10)
    {
        $link = $post->guid;
        echo "
$post->post_title
";
        $howmany++;
    }

}
?>

I want the above code not to display posts from Category 1. I think I have done everything right, but still I can't get the result that I want.
One more thing is if I even explicitly ask the query to display the posts from category 3 or 4, it doesn't happen. It ends up displaying posts from all categories.

A:

You should use the query_posts() function.  If not, at least get rid of that $howMany variable and instead append "LIMIT 10" to your sql query.
Here is an example of getting a category prepped for the loop:
<?php
     // Borrowed heavily from link above...
     $categoryvariable=1; // assign the variable as current category
     $numposts = 10;
     // Set up the query
     $query= 'cat=' . $categoryvariable. '&orderby=date&order=ASC&showposts='.$numposts;
     query_posts($query); // run the query

//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
     // Do all your echo stuff here
endwhile; else:

endif;

//Reset Query
wp_reset_query();

?>


Q:

React form not filling out with fetched data

I am currently building a react application with a .net core back end. My current issue lies in a view that is meant to edit an article (which is made up of only a title and description). On componentDidMount, I am getting the route param id from the route and retrieving the article from the server with it (I've verified that this works correctly). My issue is that my form is not filling out with the fetched data. I'm of the understanding that since the form fields set to this.state... then they should update as the state updates however this is not what I'm seeing. I believe the issue is may lie with the warning I'm receiving in console:

index.js:2177 Warning: A component is changing a controlled input of
  type hidden to be uncontrolled. Input elements should not switch from
  controlled to uncontrolled (or vice versa). Decide between using a
  controlled or uncontrolled input element for the lifetime of the
  component.

I've read the documentation the warning points to and am not seeing how my component violates this.
My component is below in full:
import React, { Component } from 'react';
import CKEditor from 'react-ckeditor-component';

export class ArticlesEdit extends Component {
  displayName = ArticlesEdit.name

  constructor(props) {
    super(props);
    this.state = {
        title: '',
        description: ''
     };

     this.handleSubmit = this.handleSubmit.bind(this);
  }

   componentDidMount () {
    const { id } = this.props.match.params;
    fetch(`https://localhost:44360/api/articles/${id}`)
      .then((article) => {
        this.setState({
            title: article.title,
            description: article.description
        });
      });
  }

  updateDescription(event){
    this.setState({description: event.target.value});
  }

  render() {
    return(
        <form onSubmit={this.handleSubmit} >

                    Title

                        <input className="form-control" type="text" id="title" name="title" defaultValue={this.state.title} required />

                <CKEditor activeClass="editor" content={this.state.description} events= {{"change": this.onEditorChange.bind(this) }} />
                <input type="hidden" id="description" name="description" value={this.state.description} onChange={this.updateDescription}/>

                    <button type="submit" className="btn btn-default">Save</button>

            </form >
      );
  }

  onEditorChange(evt){
    var newContent = evt.editor.getData();
    this.setState({
      description: newContent
    });
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    console.log(this.state.title);
    // POST request for Add employee.
        fetch('https://localhost:44360/api/articles/', {
            method: 'PUT',
            body: data
        }).then((response) => response.json())
            .then((responseJson) => {
                this.props.history.push("/articles");
            })

}
}

A:

You are not parsing the JSON you get as response to your fetch in componentDidMount. If you add .then((response) => response.json()) it should work as expected.
componentDidMount () {
  const { id } = this.props.match.params;

  fetch(`https://localhost:44360/api/articles/${id}`)
    .then((response) => response.json())
    .then((article) => {
      this.setState({
        title: article.title,
        description: article.description
      });
    });
}

You also need to use the value prop instead of the defaultValue prop on your input so that it will have the value of title in your state.
<input
  className="form-control"
  type="text" id="title"
  name="title"
  value={this.state.title}
  required
/>


Q:

Xcode 4.4.1 code signing issue

I have this code signing issue that came up only recently when I tried to submit my Mac application (not iOS) with Xcode 4.4.1
When I tried to validate my app's archive, validation fails with these two errors:

Invalid Code Signing Entitlements. The entitlements in your app bundle signature do not match the  ones that are contained in the provisioning profile. According to the provisioning profile, the bundle contains a key value that is not allowed: 'com.(mycompany).(myapp)' for the key 'com.apple.application-identifier' in 'MyAppBundle.app/Contents/MacOS/MyAppExecutable'
Invalid code signing entitlements. Your application's bundle signature contains code signing entitlements that are not supported on Mac OS X. Specifically, value 'com.(mycompany).(myapp)' for key 'com.apple.application-identifier' in 'MyAppBundle.app/Contents/MacOS/MyAppExecutable' is not supported. This value should be a string starting with your TEAMID, followed by a dot '.' followed by the bundle identifier.
This bundle is invalid. Apple is not currently accepting applications built with this version of the OS.

I've tried the following but none of them worked:

re-downloading and re-generating code signing certificates.
Specifying my team ID in the code signing parameters:
    -i "(TEAMID).com.(mycompany).(myapp)" --entitlements "(MyAppEntitlementFile).entitlements"

Anybody can help? Thanks in advance.

A:

I've fixed this by editing my entitlements file using Xcode's property list editor (not the fancy-looking GUI in the target's Summary tab) and remove the key named com.apple.application-identifier along with its value.
I'm not sure how that key-value pair got there in the first place because I'm quite confident that I didn't put it in there myself. This project was originally coded for Snow Leopard without sandboxing and went through a number of Xcode versions. Perhaps an old version of Xcode put it there and it conflicted with the newer one.


Q:

What books should I bring with me to my first gaming session?

I am interested in joining the role-playing scene, and have an interest in joining a campaign-particularly a Dungeons and Dragons campaign.  But, with little experience,  I'm not sure what I should bring to my first session.
What should I be prepared to bring as a new player to my first ever role-playing session?  What books should I bring so that I'm not caught in the dark?
The system I'll be playing in is 3.5e, with a group of four other players who have all been on this rodeo before.  I haven't created my character yet, but the GM says he'll help me with that.  He says it's not required, but that we're allowed to use 'non-core books'.

A:

Ideally? You don't need to buy anything at all.
You should ask your GM ahead of time if there's anything they specifically want you to bring, but here is the important thing to remember about the books, or any gaming kit really:
It can and should all be shared by players and GM alike
I can think of very few items in a gaming system that cannot be borrowed from another person or easily produced for free. Dice can be lent (most experienced players will have a collection anyway), books can be borrowed (as a beginner, you may want someone else to help you make your character anyway), and character sheets can be printed off the web or simply fabricated with paper and pencil/pen. The Game Master is usually the one responsible for bringing books to a gaming session, so unless you plan on being the Game Master right away (not recommended—experience playing is the best way to learn good game master practice), you can count on the game master for your gaming tools.
Now don't feel like if you've bought a few 3.5e books already that you need to return those books right away.  It's easier to make your own character as you see fit when you've got your own copy of the rules. But, don't feel like you must have any particular book to play a game either—a good Game Master will provide for new players, and good players will help new players along.

A:

A set of dice, a pen, a pencil, a rubber, a pencil sharpener, and a name for your character. They will help you to create it, but you'll have to give it a name!

A:

I wouldn't worry about bringing books.
I would print out one or more character sheets (most games have one available online), have your own dice, a couple of pencils and a sharpener (or mechanical pencils), some paper for notes, and a smile.  If you're 100% new the dice are even optional.
Also, inquire of your gamemaster or, if going with a friend, have them give you the lay of the land.  Some groups expect everyone to bring a bag of chips, something to drink, or money for pizza.
The key thing to remember is gaming is a social activity.  Imagine going to a new poker night or to see a friend who always has people over for football.  Approach a gaming session the same way.


Q:

Getting rid of binary code from string before inserting row in MySQL database

I am fetching tweets from Twitter and storing them in a database for future use. I am using UTF-8 encoding in my driver, utf8_mb4_bin in my VARCHAR fields and utf8mb4_general_ciserver collation. The problem with that is that when inserting a value in a VARCHAR field, if the text has any binary code then it will throw an exception since VARCHAR utf8 does not accept binary.
Here is an example, I am fetching the text from here and try inserting it in my database and I get the error:
Incorrect string value: '\xF0\x9F\x98\xB1\xF0\x9F...' for column 'fullTweet' at row 1

My guess is that the two emoticons are causing this. How do I get rid of them before inserting the tweet text in my database?
Update:
Looks like I can manually enter the emoticons. I run this query:
INSERT INTO `tweets`(`id`, `createdAt`, `screenName`, `fullTweet`, `editedTweet`) VALUES (450,"1994-12-19","john",_utf8mb4 x'F09F98B1',_utf8mb4 x'F09F98B1')

and this is what the row in the table looks like:

A:

You can remove non ascii characters from tweet string before inserting.
tweetStr = tweetStr.replaceAll("[^\\p{ASCII}]", "");


Q:

Correct way of viewing a (1,1)-tensor returning a vector

I am currently watching this excellent video series building up to general relativity. We have finally started looking at tensors and a question came up from the audience which (to my understanding) was asking why tensors are defined as multi-linear maps from sets of vectors and covectors to the real numbers yet (1,1)-tensors are often viewed as linear maps from vectors to vectors.
He says that the two ways of viewing the (1,1)-tensor contain the same information, but I don't understand how. If anyone could provide another explanation for why this is true I would really appreciate it.

A:

This kind of trick is common when thinking about tensors.
Let $v$ be a vector, $\alpha$ a one-form, and $c$ a number. A vector gives a map from one-forms to numbers,
$$\alpha \mapsto v(\alpha)$$
but it also gives a map from numbers to vectors,
$$c \mapsto c v.$$
Similarly, a $(1, 1)$ tensor $T$ gives a map from a vector and covector to numbers,
$$(\alpha, v) \mapsto T(\alpha, v).$$
But it also gives a map from vectors to vectors,
$$v \mapsto T(\cdot, v).$$
To see that the output here is a vector, note that it gives a map from one-forms to numbers,
$$\alpha \mapsto T(\alpha, v).$$
By continuing with this, you can also use a $(1, 1)$ tensor to define a map from covectors to covectors, or numbers to a vector and covector, and so on.
To avoid having to associate the exact same object with a ton of different maps, physicists use index notation. In this notation, the five preceding maps take the form
$$\alpha_i \mapsto v^i \alpha_i, \quad c \mapsto c v^i, \quad (\alpha_i, v^j) \mapsto T^i_j \alpha_i v^j, \quad v^i \mapsto T^i_j v^j, \quad \alpha_i \mapsto (T^i_j v^j) \alpha_i.$$
From this you can get the general pattern, which is that a $(n, m)$ tensor can act on a $(n', m')$ tensor to yield a $(n+n'-k, m+m'-k)$ tensor where $k$ is the number of upstairs/downstairs index pairs that are contracted.


Q:

Print calculated values with headers after comparison

How can I print the header of values after I compare them?
I have some calculated values stored as per below:
Value1 12
Value2 6
Value3 7
Value4 5

How can I print the max among four values with the header?
I can only get the max among the values but not the header/description
For e.g.:
"print(max(Value1,Value2,Value3,Value4))"

gives me:
"12"

but I need the output as:
"Max. value is Value1 = 12"

Is this possible?

A:

Assuming the values are stored as single numeric objects as below, and named with some pattern "ValueX", we can put them all into a list, then get index for max/min and paste:
# example data
Value1 <- 12
Value2 <- 6
Value3 <- 7
Value4 <- 5

# put all in a named vector
x <- mget(ls()[ grepl("^Value", ls()) ])

# then paste
ix <- which.max(x)
paste("Max. value is", names(x[ ix ]), "=", x[ ix ])
# [1] "Max. value is Value1 = 12"


Q:

splitting comma separated mixed text and numeric string with strsplit in R

I have many strings of the form name1, name2 and name3, 0, 1, 2 or name1, name2, name3 and name4, 0, 1, 2 and would like to split the vector into 4 elements where the first one would be the whole text string of names. The problem is that strsplit doesn't differenciate between text and numbers and split the string into 5 elements in the first case and into 6 elements in the second example. How can I tell R to dynamically skip the text part of the string with variable number of names?

A:

You have two main options:
  (1) grep for the numbers, and extract those.
  (2) split on the comma, then coerce to numeric and check for NAs
I prefer the second
splat <- strsplit(x, ",")[[1]]
numbs <- !is.na(suppressWarnings(as.numeric(splat)))

c(paste(splat[!numbs], collapse=","), splat[numbs])
# [1] "name1, name2 and name3" " 0" " 1" " 2"


Q:

Select two table and put ordering priority

I have two tables,
ir1_police is included messages that reported to admin.
ir1_police_flag, admin can flag reporters from 1 to 2. (1 means medium 2 means low and nothing means high priority).
If someone try to report something that is not real. Admin will flag it as 1 or 2 .
So I would make a list of report that shows first high priority, second medium and at last low.
I use the mysql statement but there is a problem. if there was nothing ir1_police_report nothing will be shown. or if exist only shows they are on ir_police_flags.
I have no idea to select them if no record exists on ir1_police_flags
SELECT * FROM ir1_police
JOIN ir1_police_flags on ir1_police_flags.uid = `ir1_police.uid
WHERE
ir1_police.status=0 AND ir1_police.parent_id=0
ORDER BY ir1_police.time DESC

A:

Replace JOINwith LEFT JOIN. The former only selects rows from the tables where a match is found, whereas the latter selects all rows from the first table, even when there is no match in the other table.
Then you can add a second field to ORDER BY:
SELECT * FROM ir1_police
LEFT JOIN ir1_police_flags ON ir1_police_flags.uid = ir1_police.uid
WHERE ir1_police.status=0 AND ir1_police.parent_id=0
ORDER BY
    ir1_police_flags.flag ASC,
    ir1_police.time DESC

Notice the LEFT JOIN produces results where all ir1_police_flags's fields are NULL where there is no match in this table. This is perfect in your case, because NULL is considered smaller than any value, as far as ORDER BY is concerned.

Your application might justify this structure, but you should ask yourself whether this flag shouldn't be just a column in the table ir1_police altogether.


Q:

How to find the optimal decoder that minimizes the probability of error?

Suppose that the signal $X$ is drawn as...
$$
X =
\begin{cases}
1 & \style{font-family:inherit}{\text{with probability 1/2}} \\
0 & \style{font-family:inherit}{\text{with probability 1/2}}
\end{cases}
$$
& the conditional pmf $P\left[Y = y\;|\;X = x\right]$ of $Y$ given $X$ is specified by...
$$
\begin{array}{l}
P\left[Y = 1\;|\;X = 1\right] = 1 \\
P\left[Y = 1\;|\;X = 0\right] = 1/2
\end{array}
$$

Find the optimal decoder $d\left(y\right)$ that minimizes the
probability of error $P\left[X \ne d\left(Y\right)\right]$.
Find the associated probability of error.

Based on the information given, I constructed the following probability table...
$$
\begin{array}{c|c|c|c}
   & X = 0       & X = 1       & \style{font-family:inherit}{\text{Total}} \\\hline
 Y = 1 & \frac{1}{4} & \frac{1}{2} & \frac{3}{4} \\\hline
 Y = 0 & \frac{1}{4} & 0           & \frac{1}{4} \\\hline
 \style{font-family:inherit}{\text{Total}} & \frac{1}{2} & \frac{1}{2} & 1
\end{array}
$$
Using the table, I have the answers to every conditional probability...

$P\left[X = 0 | Y = 0\right] = 1$.
$P\left[X = 0 | Y = 1\right] = 1/3$.
$P\left[X = 1 | Y = 0\right] = 0$.
$P\left[X = 1 | Y = 1\right] = 2/3$.
$P\left[Y = 0 | X = 0\right] = 1/2$.
$P\left[Y = 0 | X = 1\right] = 0$.
$P\left[Y = 1 | X = 0\right] = 1/2$.
$P\left[Y = 1 | X = 1\right] = 1$.

From here, could you explain how to find $d\left(y\right)$ for this problem &, if you're feeling generous, any problem like it?

FYI: This is not hw; I am practicing for a qualification exam.

A:

In this context, a decoder maps observed $Y$'s to guessed $X$'s, i.e. $d: \{0,1\} \rightarrow \{0, 1\}$.  Or in other words, you are choosing $d(0)$ (what $X$ to guess when seeing $Y=0$) and $d(1)$ (what $X$ to guess when seeing $Y=1$).  And you want to minimize the prob of guessing wrong, i.e. when $d(Y)$ (i.e. the guess) $\neq X$ (i.e. the actual signal).
At this point, if you stare at the $2 \times 2$ probability table, it should be "really obvious" that you should guess $d(0) = 0$, because if you see $Y=0$ then it is certain that $X=0$.  The question is what to guess when seeing $Y=1$, but it should also be "somewhat obvious" :) that in that case you should guess $d(1) = 1$.  We will prove these rigorously now.
$$
\begin{align}
P(d(Y) \neq X) &= P(d(Y) \neq X | Y = 1) P(Y=1) + P(d(Y) \neq X | Y=0) P (Y=0)\\
&=P(d(1) \neq X | Y=1)P(Y=1) + P(d(0) \neq X | Y=0) P(Y=0)
\end{align}$$
Note that, as far as the minimization is concerned, $P(Y=1), P(Y=0)$ are constants.  Since we can choose $d(0), d(1)$ independently, we can minimize each term separately.  Formally we're doing this:
$$d(i) = \arg\min_{j \in \{0,1\}} P(j \neq X | Y = i) = \arg \max_{j \in \{0,1\}} P(j = X | Y = i)$$
I.e. for each case of $Y=i$, simply find the most probable $X$ (conditioned on $Y=i$).  I would say this is a general feature of all kinds of decoding.
First, $P(d(0) \neq X | Y = 0)$: Conditioned on $Y=0$, we have $X=0$ with certainty.  Nothing is more probable than certainty.  So we choose $d(0) = 0$.
Next, $P(d(1) \neq X | Y = 1)$: You can easily calculate that $P(X=1 | Y = 1) = {2 \over 3}$, and $P(X=0 | Y = 1) = {1 \over 3}$.  Since $X=1$ is more probable (conditioned on $Y=1$), we choose $d(1) = 1$.
With these optimal choices of $d(0) = 0, d(1) = 1$, the overall error prob is:
$$
\begin{align}
P(d(Y) \neq X) &= P(d(1) \neq X | Y=1)P(Y=1) + P(d(0) \neq X | Y=0) P(Y=0) \\
&= P(1 \neq X | Y=1)P(Y=1) + P(0 \neq X | Y=0) P(Y=0) \\
&=  {1 \over 3} \cdot {3 \over 4} + 0 \cdot {1 \over 4} = {1 \over 4}
\end{align}$$
Another way to find the overall error prob is to augment your table with your choices (remember that $d()$ is a deterministic function, depending on $Y$ only), and then realize the red entries are the cases when you guess wrong:
\begin{array}{c|c|c|c}
   & X = 0       & X = 1       & \style{font-family:inherit}{\text{Total}} \\\hline
 Y = 1 \iff d(Y) = 1 & \color{red}{\frac{1}{4}} & \frac{1}{2} & \frac{3}{4} \\\hline
 Y = 0 \iff d(Y) = 0 & \frac{1}{4} & \color{red}{0}           & \frac{1}{4} \\\hline
 \style{font-family:inherit}{\text{Total}} & \frac{1}{2} & \frac{1}{2} & 1
\end{array}


Q:

How to build a simple offline form submission app?

I'm a Webdev beginner, have been learning some Python/PHP/Javascript and want to help a friend of mine with a project.
She's conducting a large scale survey of old houses/windows, and fills in forms (similar to Google Forms). However, she doesnt always have 3G coverage on her phone, so she wants some way of uploading the data when she gets online, and she wants to be able to upload photos and attach these to the forms.
I've found a javascript-library which makes use of html5 localstorage, but I havent understood if localstorage also accepts file uploads? Also, when you have submitted one form you would need internet access to open up the form again to submit another form.
Are there libraries or projects around that would help me with some of this, so I dont have to reinvent the wheel?

A:

This is going to be very difficult to do with a web app. Your going to have to rely on something like AJAX to send the data and if it times out store in local storage and keep retrying every few minutes, because a web app has no access to anything like checking the wifi status etc.
Also that there is a limit to the size you can use in html5 local storage:
What is the max size of localStorage values?
, this is not going to work if you want to hold onto photos.
This would require a native or minimum a hybrid app (like phonegap) to store the data on the actual device in a file or SQLite database. This way you can store what you like, have access to the status of the internet connection and even have prompts to appear on the screen (when the app is in the background) to remind her that there are still some that need to be uploaded.
It will be much more reliable and stable this way


Q:

Column titles not appearing in JTable

Any thoughts as to why the following code would display column titles?  I have tried with and without a scollpane.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JScrollPane scrollpane = new JScrollPane(table);

contentPane.add(scrollpane, "wrap, span");

tableModel = new DefaultTableModel(new Object[]{"Name","Instrument Type","Channel","Number of Channels"},0);

table = new JTable();
table.setBounds(6, 6, 697, 172);
tableModel = new DefaultTableModel(new Object[]{"Fixture Name","Fixture Type","Fixture Channel","Number of Channels"},0);
        table.setModel(tableModel);
        contentPane.add(table);

A:

Use a layout manager
Add the scroll pane to the frame, not the table...

You're code snippet is either missing it, or you example is wrong.
JScrollPane scrollpane = new JScrollPane(table);

This either means you've already created the table, in which case, you're double creating it, or it's going to generate a NullPointerException
Your code should look more like...
table = new JTable();
tableModel = new DefaultTableModel(new Object[]{"Fixture Name","Fixture Type","Fixture Channel","Number of Channels"},0);
table.setModel(tableModel);
contentPane.add(new JScrollPane(table));

Have a look through How to use Tables for more details


Q:

Is ice harder than steel?

While trying to fix our garburator, I found a couple sites claiming that you can sharpen the blades of your garburator by forcing it to process ice.
From my understanding though, that would only be possible if ice was harder than steel.
Obviously ice is far more brittle than steel, but is it harder?
I'm assuming the garburator uses stainless steel, and the ice is at a standard freezer temperature of - 18°C.

A:

Ice has hardness 1.5 on Mohs scale, while steel is 4 to 4.5; see https://en.wikipedia.org/wiki/Mohs_scale_of_mineral_hardness
In the usual course of events one uses a harder substance to sharpen a softer one: corundum sharpening stones work great on steel.  It is possible to cut away steel with water, but at ordinary pressure the rate of wear is quite slow, but a high pressure water jet can be used to cut steel and other materials such as your quartz or granite counter tops.
Conclusion: grinding ice in the garbage disposal is, as CuriousOne mentioned, a simple and effective technique for cleaning the blades. This keeps the working surface "sharp" as opposed to covered with gunk.


Q:

How to call .fail() from inside .done() to handle general errors?

jQuery's AJAX .fail() is a nice error handler that handles "404 Not Found" errors and such, but how can we call it deliberately from inside .done() to handle general error cases, for example when data provided by user is incorrect?

A:

You can use a common function that's called on error in each case.
$.ajax( 'url' )
    .done( function( data, textStatus, jqXHR ) {
        if( data == 'Invalid' ) {
            ajaxError( jqXHR, "usererror" );
        }
    })
    .fail( ajaxError );

function ajaxError( jqXHR, textStatus, errorThrown ) {
    console.log( 'Ajax error: ' + textStatus );
}

A:

@Juhana's code will be good for most eventualities.
If, however, errors might arise that cannot be reliably predicted by inspection of data alone, then consider this variant :
$.ajax( 'url' ).done( function( data, textStatus, jqXHR ) {
    try {
        var dataLooksGood = ......;//(boolean) Test data for predictable data errors here
        if( !dataLooksGood ) throw( new Error("data invalid"); )
        //Handle data here.
        //Any naturally-ocurring errors or further manually-thrown errors will be caught below.
    }
    catch(err) {
        ajaxError( jqXHR, "AJAX successful but: " + err.message );
    }
}).fail( ajaxError ).always(function() {
    //Here do whatever is necessary after success or error
});

function ajaxError( jqXHR, textStatus, errorThrown ) {
    console.log( 'AJAX error: ' + textStatus );
}

By catching errors, the always handler will be allowed to fire even if an unpredicted error occcurs. Thus you could better guarantee that a "loading..." message or spinner graphic was killed regardless of an error having occurred.


Q:

How to insert/pass NULL value into Date field

I am trying to insert a null value into a field of type Date (in SalesForce) using a PHP Script.
Here is my logic.
$Date = '',
$createField['Date__c'] = $Date;

I tried the following, but none of them work.
$Date = '';
$Date = null;
$Date = NULL;
$Date = 'NULL';
$Date = 'null';

A:

You need to use the fieldsToNull attribute, as noted in the update documentation.
$createField["fieldsToNull"] = array("Date__c");


Q:

How can I undo "always allow" in keychain item

By mistake, I clicked on "always allow" on a file in my keychain on the Mac. How do I undo this and restrict access? I tried to correct it by clicking on Access Control. There I selected "confirm before allowing access" but it didn't work. I can still see the password for that file without entering a password.

A:

You should be able to clear out any white listed programs and then reset the default behavior from Keychain Access.

First select Fantastical (or any apps that are cleared) and then press the -
Second, choose Confirm and Ask as needed.
Third, select Attributes and make sure the changes are saved (you should probably have to authenticate as well at this step)
Go back to Access Control to verify the settings have been saved properly

If this doesn't work, you might need to repair that keychain containing that item, also using Keychain Access menu to open the Keychain First Aid tool.


Q:

Running injuries when competing

I have a history of injuries, and am no stranger to dealing with them. I had shin splints that developed into stress fractures a year ago. After healing, I have so far managed to prevent their re-occurrence, but at times, I can feel random pain in my tibia. I have been doing careful warm-ups and stretching, and so hope to continue prevention.
I have a strange pain in my left calf, along the back side. It is always in the same exact place, and normally subsides after a while. It hurts the worst when I take a step, and have never noticed it when running, only after running. I don't notice it when standing or sitting. I can't figure out what is causing this. It feels like muscle pain.
I have two runners knees, and this is developing into quite a serious issue. Two weeks ago I went into complete rest, took a lot of painkillers, and iced multiple times a day. After a week I felt like I was at about 95%, weaned myself off painkillers, and went back to training. For the next week for training I continued icing, and rarely took painkillers. This week the pain is back. It has changed to cover a larger area, travelling into my thighs at times, and sometimes the pain is so great I have difficulty distinguishing where it is coming from.  I am not uncomfortable, I can still walk and run, I PR'd last night on my 200m, but I am in constant pain. I've heard that runner's knee is basically just swelling caused by rubbing of the patella against the thighbone. It is not a worrisome pain, it is just painful. I have always had weak knees that popped or bothered me when doing lunges and split squats, and I can no longer do either with a very heavy weight. I have only a month to go before the biggest competition of my life, and I refuse to miss out on this. What should I do?
I have looked into k-tape and braces for competition, but don't feel like either would be very helpful. The only thing that makes me feel better is ice and painkillers.

A:

Do not do any self-diagnosis. Consult a musculoskeletal specialist and get yourself diagnosed. Never assume anything, as similar symptoms may be because of different reasons.If given proper attention at the right time, any issue can be fixed.


Q:

Repeat two different animations infinitely in android one after the other

I am trying the following code in Andorid for animations
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lay);
        rel = (LinearLayout) findViewById(R.id.rel);
        rel.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_background));

        animation = new AlphaAnimation(1, 0);
        animation.setDuration(500);
        animation.setInterpolator(new LinearInterpolator());
        animation.setRepeatCount(3);
        rel.startAnimation(animation);

        animation1 = new AlphaAnimation(1, 0);
        animation1.setDuration(1500);
        animation1.setInterpolator(new LinearInterpolator());
        animation1.setRepeatCount(3);

        animationchala();

    }

   public void  animationchala(){
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            public void onAnimationEnd(Animation animation) {
                animation.setAnimationListener(null);

                rel.startAnimation(animation1);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        animation1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation1) {

            }

            public void onAnimationEnd(Animation animation1) {
                animation1.setAnimationListener(null);
                rel.startAnimation(animation);

            }

            @Override
            public void onAnimationRepeat(Animation animation1) {
            }
        });
    }

the code works for the first time.
when animation ends animation1 is started , then animation1 ends and animation is started again, but now when animation1 has to start again it stops, how can I repeat the animations one after the other infinitely

A:

The problem is in your case that you are setting your animationListeners to null when you started new animation. This makes them stop after you started animation. Just re-arrange your codes like this;
public void  animationchala(){
    animation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        public void onAnimationEnd(Animation animation) {

            rel.startAnimation(animation1);

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

    animation1.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation1) {

        }

        public void onAnimationEnd(Animation animation1) {
            rel.startAnimation(animation);

        }

        @Override
        public void onAnimationRepeat(Animation animation1) {
        }
    });
}


Q:

Is the verb "Go" always followed by "to" when talking about a place/location?

Other than the phrase

Go home.

I can't find other uses of go without to when talking about a specific destination/physical place.

I am going to California.
She went to Milan.

The other uses of go (go crazy, go shopping, and so on) shouldn't be taken into consideration here.

A:

The verb GO can be used with many  prepositions, including the preposition home and the preposition to. When the verb GO indicates to travel, it usually takes a Locative Complement. This is usually in the form of a preposition phrase. The preposition phrase may consist just of an intransitive preposition (these are regarded by some traditional grammars as 'adverbs'), or it many consist of a preposition phrase taking another preposition phrase as Complement. It it may, of course, consist of a preposition taking a noun phrase as Complement:

He went north. (intransitive preposition)
He went out of the building. (preposition with preposition phrase complement)
He went into the shed. (preposition with noun phrase complement)

The Original Poster's question
The Original Poster asks if the verb GO is always followed by the preposition to when the sentence mentions a specific location or destination. The answer is NO! Here are some examples:

He went inside the cinema.
He went aboard the ship.
He went into the maze.


Q:

UITableView Not Scrolling

I have a tableview which will not budge when touched. It is very confusing to me. It is the most recently added subview (I checked - it is the last entry in my view's subviews array) and for some reason it just won't scroll up or down. If I tap multiple fingers wildly on the tableview it will one in a while highlight the cell under one of my fingers, but it will not scroll even a little. I have set the number of rows to 100 (many more than are visible on screen) and I have set the 'bounces', 'scrollEnabled', and 'userInteractionEnabled' properties to YES.
I know that I have not provided much to go on here, but if anyone could at least give some tips on how to go about debugging this I would be very grateful. Can I log from within the tableView gestureRecognizer handling method? Can I test where my touches are going?
Please help!
Thanks.

A:

A TableView is basically a specialized ScrollView.  If it's not scrolling, it seems to me it could be one of two things.  Either something is on top of the TableView and is capturing the gesture events before the TableView can get them, or You have set the bounds and contentSize incorrectly.  For a TableView or ScrollView, the bounds of the view should be the visible area, and the contentSize (should be handled by the TableView without you needing to do anything) is the size of all the cells in the Table.
So I would check the bounds of the table view and make sure you are setting that to the contentSize, since that would cause it nor to scroll.
Just to make sure it's on the top, try calling
[view bringSubviewToFront:tableView];


Q:

<?php and <?= tags in PHP templates

I am learning to build a templating system. In the view folder i have a page that has this code
Hello <?= $data["name"]; ?>

If i enter this page I see that the code works just with <?= ?> tags. I tried <?php ?> but it doesn`t work. I thought that the tags have the same functionality. What is the explanation ?

A:

That's a shortener for
<?php echo $data['name']; ?>


Q:

Difference between an Object and its Prototype

Why does:
console.log(Object.hasOwnProperty("hasOwnProperty"));

return a false, But:
console.log(Object.prototype.hasOwnProperty("hasOwnProperty"));

return a true statement?
I realize that hasOwnProperty is a pre-built method in the Object but I guess my question is what is the difference between the Object and the prototype of an Object.
Aren't they one and the same?
When we refer to the Object in the first line of code, aren't we referring to the same line of code in the second line of code above?
EDIT: fixed above 2 lines of code from:
console.log(Object.hasOwnProperty);

and:
console.log(Object.prototype.hasOwnProperty);

A:

Both Object.hasOwnProperty and Object.prototype.hasOwnProperty reference the same function. Object.prototype contains that function as an own property, while Object contains it as an inherited property.
So, in other words, the hasOwnProperty function is defined (as a method) on the Object.prototype object. Then, the Object constructor (like almost all other native objects) inherits (all methods) from Object.prototype.
Btw, the inheritance chain (prototype chain) of Object is:
Object -> Function.prototype -> Object.prototype -> null

So, Object inherits all methods from both Function.prototype, and Object.prototype.


Q:

Jquery maintain table column count of 10 move columns to new table

I have a dynamic html table that is being printed and need to maintain a column count of 10 to avoid truncation. I was trying to limit the column count to 10 and move any columns above that to a new table then append the new table to a div (id="divTtableContainer").
I also need to maintain all the attributes associated with the TR and TD elements. If anyone could help it would be greatly appreciated.
Example:
For simplicity I reduced the number of columns to 2 in this example.

1
2

1
2

1
2

The end result would be as follows

1

1

1

2

2

2

A:

This should give you a good start :
http://jsfiddle.net/XxqRK/1/
The main trick here is : .append($('>:gt('+limit+')',this));. Basicly, it takes the td greater after the two firsts (for limit = 1) of the row and moves them to the new one.
Change the limit = 1 to limit = 9 to limit to 10 columns. Here, the new created table is inserted just after the other.


Q:

Not Able to drag and drop the text in canvas image

Actually i have tried to drag and drop the canvas text which was created in javascript . But I am not able to drag it properly because selecting the text is not working properly. I kept my code in below snippet.
please help me on this. Thanks in advance.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// variables used to get mouse position on the canvas
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

// variables to save last mouse position
// used to see how far the user dragged the mouse
// and then move the text by that distance
var startX;
var startY;

// an array to hold text objects
var texts = [];

// this var will hold the index of the hit-selected text
var selectedText = -1;

// clear the canvas & redraw all texts
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(window.imageSrc, 0, 0, canvas.width, canvas.height);
    for (var i = 0; i < texts.length; i++) {
        var text = texts[i];
  ctx.strokeText(text.text, text.x, text.y);
        ctx.fillText(text.text, text.x, text.y);
    }
}

// test if x,y is inside the bounding box of texts[textIndex]
function textHittest(x, y, textIndex) {
    var text = texts[textIndex];
    return (x >= text.x && x <= text.x + text.width && y >= text.y - text.height && y <= text.y);
}

// handle mousedown events
// iterate through texts[] and see if the user
// mousedown'ed on one of them
// If yes, set the selectedText to the index of that text
function handleMouseDown(e) {
    e.preventDefault();
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);
    // Put your mousedown stuff here
    //alert(texts.length);

    for (var i = 0; i < texts.length; i++) {
        if (textHittest(startX, startY, i)) {
            selectedText = i;
        }
    }
}

// done dragging
function handleMouseUp(e) {
    e.preventDefault();
    selectedText = -1;
}

// also done dragging
function handleMouseOut(e) {
    e.preventDefault();
    selectedText = -1;
}

// handle mousemove events
// calc how far the mouse has been dragged since
// the last mousemove event and move the selected text
// by that distance
function handleMouseMove(e) {
    if (selectedText < 0) {
        return;
    }
    e.preventDefault();
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);

    // Put your mousemove stuff here
    var dx = mouseX - startX;
    var dy = mouseY - startY;
    startX = mouseX;
    startY = mouseY;

    var text = texts[selectedText];
    text.x += dx;
    text.y += dy;
    draw();
}

// listen for mouse events
$("#canvas").mousedown(function (e) {
    handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
    handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
    handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
    handleMouseOut(e);
});

$("[id^='memeText']").change(function () {
    // calc the y coordinate for this text on the canvas
    var y = texts.length * 20 + 100;
  var position = $(this).attr('name');

    position = position - 1;
    // get the text from the input element
    var text = {
        text: $(this).val(),
        x: 250,
        y: y
    };

    // calc the size of this text for hit-testing purposes
    ctx.font = "32px verdana";
    ctx.textAlign = 'center';
 ctx.lineWidth = 3;
 ctx.fillStyle = "#fff";
 ctx.strokeStyle = "#000";
    text.width = ctx.measureText(text.text).width;
    text.height = 16;
  if(texts[position]==""||texts[position]==null||texts[position]==undefined){
     texts.push(text);
    } else {
     console.log(texts[position].text);
     texts[position].text = $(this).val();
    }
    // put this new text in the texts array

    // redraw everything
    draw();

});

function handleFileSelect(evt) {
      //var canvasWidth = 500;
     // var canvasHeight = 500;
      var file = evt.target.files[0];
      var reader = new FileReader();
      reader.onload = function(fileObject) {
       var data = fileObject.target.result;
       var image = new Image();
       image.onload = function() {
        window.imageSrc = this;
        ctx.drawImage(window.imageSrc, 0, 0, canvas.width, canvas.height);

       };
       document.getElementById('box2').style.display = "block";
       image.src = data;
       // console.log(fileObject.target.result);
      };
      reader.readAsDataURL(file);
     }

          document.getElementById('file').addEventListener('change',
       handleFileSelect, false);

        <input id="file" type="file" autocomplete="off">

        <input id="memeText" name="1" autocomplete="off">

        <input id="memeText" name="2" autocomplete="off">

        <canvas id="canvas" width="500" height="500"></canvas>

        Download Meme!

        Make Another Meme!

A:

There is a couple of problems with this.
Firstly, look at how to Get the coordinates of a mouse click on Canvas. Currently your offsets are both 0. Try calling canvas.offsetLeft and canvas.offsetTop - note: canvas, NOT $canvas.
Secondly, text position is set to the middle of the text, not to the top left or bottom left corner. So in your textHittest function, you want this return statement:
return (x >= (text.x - 0.5*text.width) && x <= (text.x + 0.5*text.width) && y >= (text.y - 0.5*text.height) && y <= (text.y + 0.5*text.height));

More on text properties here.
Once that's sorted, double check if the events are registering exactly as you want them to. Hope that's enough to get you started :)


Q:

Question put on hold as opinion based; how can I change it?

@Daft and @Richard have marked my post, What were James Dashner's motivations for killing off this character?, as off-topic, as it is more based on opinion than fact. Is there any way I can rephrase the question or otherwise alter it such that it fits the criteria to be on-topic on this forum? When I wrote my question, I was hoping that answers would provide ideas/opinions as to why she should have died, with textual evidence to back things up, though in retrospect, I didn't explicitly state that in the body of the question.

A:

When you ask a question like "Why such-and-such happen in some novel?", there are only two ways for it to be on-topic and get an answer:

You want to know if there was anything written in the story that explains why the event happened from an in-universe perspective. ("She died because in Chapter 45 she gets bitten by a poisonous bug and no one noticed".)
You want to know if the author has ever made any specific comments about why he/she chose to write the story that way. ("I wrote her death because I felt like it gave symmetry to so-and-so's rebirth story.")

Your question doesn't really look like either of those is what you want. Instead, you've listed a bunch of subjective reasons for and against having the author kill off the character in question, things like:

Her death was so... disappointing.

or

the reader could easily distance him/herself from her.

Those are not facts, they are your personal impressions of the character from your reading of the novel. None of those bullet points are helpful in providing an objective answer to your question. Instead, they seem designed to invite speculation and debate over which "side" makes more sense, the "pro" or "con" side. And, unfortunately, we don't allow debate or discussion questions on this site.
In fact, there isn't actually a question in the body of your question until the very end:

Could this have any significance?

and it's not even the main question you wanted to ask.
To fix this question, you'd probably need to gut it. It's probably OK to keep much of the information intact, to explain why you're asking in the first place, but you'll need to summarize it a lot more succinctly. And, most importantly, you need to ask the question you really want an answer to: from what you've written, you're really asking is "Did James Dashner ever explain why he killed off this character?"

A:

As you mentioned on the question itself:

I do realize it's very opinion based, but only realized that after posting it. It's more a debate than a question with a factual answer. –  Jenguinie

How do we fix this? Come up with a related question that can have a factual answer. For instance:

Did the author ever explain why they chose to end the story this way?
Why did [character] go to the trouble of killing her, given that...?
Do we know how her death affected [other character]?

In general, any question that could potentially have a definitive answer in some interview, spin-off, crossover, or sequel is one that you can ask here.
We definitely do not do discussions or debates. Only questions and answers. But all that other stuff is welcome in chat, as others have pointed out.