Q: In DynamoDb, is there a way to atomically check a secondary index for an item before writing it? I've got an object like this:
{
     "id": (UUID generated at call time)
     "referenceId": (Foreign key for another system)
     "referenceType": (enum)
}

The primary index is just

*

*Primary key: id

And I've got a secondary index like

*

*Primary key: referenceId

*Secondary key: referenceType

So what I want to do, is query the secondary index with the referenceId and referenceType, and then if that's empty, write the record to the table.
The problem is, Conditional Expressions can only check same index you're querying. And I've looked into DynamoDb Transactions, but they say you can't have two transactions target the same item.
Is there a way to make this work?

A: If I understand your question correctly, your item has three attributes: id,
referenceId and referenceType.  You've also defined a global secondary index with a composite primary key of referenceId and referenceType.
Assuming all these attributes are part of the same item, you shouldn't need to read the secondary index before deciding to write to the table.  Rather, you could perform a PUT operation on the condition that referenceId and reference type don't yet exist on that item.
ddbClient.putItem({
    "TableName": "YOUR TABLE NAME",
    "Item": { "PK": "id" },
    "ConditionExpression": "attribute_exists(referenceId) AND attribute_exists(referenceType)"
  })

You may also want to check out this fantastic article on DynamoDB condition expressions.

A: As I understand the question, your table PK is generated "at call time" so it would be different for two different requests with the same reference ID and reference type.
That being the case, your answer is no.
If you've got a requirement for uniqueness of a key set by a foreign system, you should consider using the same key or some mashup of it for your DDB table.
Alternately, modify the foreign system to set the UUID for a given reference ID & type.


Q: Why does mapping over a DataFrame using a case class fail with "Unable to find encoder for type stored in a Dataset"? I have already imported spark.implicits._ But still I get error

Error:(27, 33) Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.

I have a case class like:
case class User(name: String, dept: String)

and I am converting Dataframe to dataset using:
val ds = df.map { row=> User(row.getString(0), row.getString(1) }

or
val ds = df.as[User]

Also, when I am trying the same code in Spark-shell I get no error, only when I run it through IntelliJ or submit the job I get this error.
Any reasons why?

A: Moving declaration of case class out of scope did the trick!
Code structure will then be like:
package main.scala.UserAnalytics

// case class *outside* the main object
case class User(name: string, dept: String)

object UserAnalytics extends App {
    ...
    ds = df.map { row => User(row.getString(0), row.getString(1)) }
}


Q: How to make first post bigger in wordpress This is probably very easy to do, but unfortunately I'm not too good with coding. I am honestly trying to learn though.
I have a theme in wordpress that makes posts tagged with "spotlight" twice the size of the rest. I would like to change this so that it's automatically the first post that is this size. I hope that makes sense.
A snippet of the code I have:
// Get blog layout setting
    $blog_layout      = get_theme_mod( 'blog_layout_setting', 'three-columns' );
    $portfolio_layout = get_theme_mod( 'portfolio_layout_setting', 'four-columns' );

    if ( is_tax( 'ct_portfolio' ) || is_page_template( 'templates/template-portfolio.php' ) ) :

        if ( 'four-columns' == $portfolio_layout ) {

            if ( has_tag( 'spotlight' ) ) {
                $classes[] = 'col-lg-6 col-md-8 col-sm-12';
            } else {
                $classes[] = 'col-lg-3 col-md-4 col-sm-6';
            }

        } else {

            if ( has_tag( 'spotlight' ) ) {
                $classes[] = 'col-md-8 col-sm-12';
            } else {
                $classes[] = 'col-md-4 col-sm-6';
            }

        }

I'm pretty sure it's just to change the "if ( has_tag( 'spotlight' )" to something i++ or i=1, or something like that. I might also be completely wrong. I feel like the answer is staring me in the face, but I just can't grasp it. I've tried searching around, but haven't found a good answer.
I would be really happy for any help, and I really do learn from this.
Thanks in advance.

A: Please refer this jsFiddle code. I hope this solves your problem.
You just needed to add the CSS to your style.css
.myspotlight{
background-color:red;
}

and
the javascript to the particular php file which runs the loop of all your articles and creates the list of articles.
 $( "article" ).first().addClass("myspotlight");

The jquery code basically appends the necessary class to the first  tag that it finds


Q: Flutter: why can't I create a DateTime object with all 0 values? So I want to make a Stopwatch in Flutter.
static void startTrip() {
  SharedPrefsHelper().setIsCurrentlyOnTrip(true);

  _elapsedTime = DateTime(
    0, //year
    0, //month
    0, //day
    0, //hour
    0, //minute
    0, //second
    0, //millisecond
    0, //microsecond
  );

  _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) {
    _elapsedTime.add(Duration(seconds: 1));
    print('new time: $_elapsedTime');
    _controller.sink.add(_elapsedTime); //same object/reference, but this is for the StreamBuilder to update
  });

  //TODO
}

As you can see I first attempted to use a DateTime object to keep track of the time.
But DateTime(0, 0, 0, 0, 0, 0, 0, 0) initializes to -0001-11-30 00:00:00.000. And the value doesn't update after I try to add 1 second, it always prints out the same.
Go and try it out your self on dartpad by running this code:
DateTime elapsedTime = DateTime(0, 0, 0, 0, 0, 0, 0, 0);
print(elapsedTime);
elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);

Does anyone know why this happens?
For now I will just use an int to keep track of the time instead and do the formatting myself.
P.S so this is how I did it, if anyone wants the code:
int hours = elapsedTime ~/ 3600;
int minutes = (elapsedTime % 3600) ~/ 60; //get rid of all additional hours, then divide by 60
int seconds = elapsedTime % 60; //get rid of all additional minutes

String h = hours > 9 ? hours.toString() : '0$hours';
String m = minutes > 9 ? minutes.toString() : '0$minutes';
String s = seconds > 9 ? seconds.toString() : '0$seconds';

A: You can try this:
DateTime elapsedTime = DateTime.utc(0);
print(elapsedTime);
elapsedTime = elapsedTime.add(Duration(seconds: 1));
print(elapsedTime);

Note: The lowest value for day and month is 1 and not 0.


Q: Loading Clojure code in Eclipse plug-in I have this kind of problem. I have Clojure code contained in Eclipse plug-in (denoted A) in *.clj files. I don't want AOT compilation. However, I need to load the clojure code from another Clojure plug-in B. This is possible when B depends on A. Clojure can easily access the classpath and everything works. But I want the plug-in A to be plugged as extension to B. But there is a problem because I could not find a way how to load a Clojure file contained in A from *.clj file contained in B. I would like to use the Clojure 'load' function which can load *.clj files from classpath but this function just cannot see contents of plug-in A event when I explicitely start the plug-in like this
 (org.eclipse.core.runtime.Platform/getBundle "A")

Reaction to Laurent's answer
Laurent, thank you very much! This is very interesting. However, I think this mayby solves a harder problem then my original one. You discribed how to call clojure code from java plug-in which is totaly awesome. I need to call clojure code from clojure plug-in which I think may be easier. I imagine that I would create extension point and provide clojure functions like this
<extension point="transforms">
  <function namespace="my.nemaspace" fn="my-transform"/>
</extension>

So I do not need any magic with IExecutableExtensionFactory. I can read the extension registry from clojure code. What I cannot do is load the function specified in the extension. Is this doable or did I just misunderstood something? I noticed that you are using clojure.osgi. This looks cool, is there any documentation for that project?

A: The problem you're having with regards to classloaders is to be expected : if the dependencies of your Eclipse plugins/OSGi bundles are A -> B, with the Clojure jar bootstraped from B, then not being able to see resources of A from B is normal.
There can be no cycles among dependencies of Eclipse plugins, so there can be no cycles among classloader hierarchies.
This is the same problem that you would face if you were to write extensions to B from A with regular Eclipse machinery : plugin B would declare an interface, and an extension point. Then plugin A could implement the interface, and declare an extension to the extension point. This last part allows the Eclipse framework to do some tricks with the bundles: it sees that A declares an extension to B, thus instanciates a class from A implementing the interface declared in B (this works since A depends on B), and gives B the implementation instance from A which is also OK since it implements the interface in B !
(Not sure this is clear).
Anyway, back to plugins written in Clojure.
With Clojure, you don't have, out of the box, such separate environments provided by classloaders, because everything gets aggregated in one "Clojure environment" living in the classloader realm of the plugin embedding the clojure jar.
So one possibility would just be, when plugin A starts, to load the relevant namespaces from A. Then they would be loaded at the right time, and available to any other Clojure code.
Another possibility would be to use the Extension Point/Extension machinery. Eclipse provides a way to use "factories" to create instances of extension points. In Counterclockwise, we leverage this feature, and have a generic factory class (written in java, so no AOT) which takes care of loading the right namespace from the right bundle.
Here are more detail concerning how to extend extension points.
An example from Counterclockwise:
There is an existing Extension Point in the Eclipse framework for contributing hyperlink detectors for the Console contents. Counterclockwise extends this extension point to add nrepl hyperlinks.
In the java world, you would have to directly declare, in your extension, some class of yours which implements interface IPatternMatchListenerDelegate.
But with CCW, for probably the same reasons as you, I try to avoid AOT at all costs, so I can't give a java class name in the extension, or I would have either had to write it in java and compile it, or write a gen-class in Clojure and AOT-compile it.
Instead, CCW leverages a hidden gem of plugin.xml's possibilities: in almost every place, when you have to provide a class name, you can instead provide an instance of IExecutableExtensionFactory whose create() method will be called by the Eclipse framework to create an instance of the desired class.
This allowed me to write a generic class for calling into the Clojure world: I just use, in place of the class name I should have written, the class name ccw.util.GenericExecutableExtension
Extract from plugin.xml :
<extension point="org.eclipse.ui.console.consolePatternMatchListeners">
<consolePatternMatchListener
   id="ccw.editors.clojure.nREPLHyperlink"
   regex="nrepl://[^':',' ']+:\d+">
    <class class="ccw.util.GenericExecutableExtension">
       <parameter
             name="factory"
             value="ccw.editors.clojure.nrepl-hyperlink/factory">
       </parameter>
    </class>
</consolePatternMatchListener>

Note the class attribute, and how I can give parameters to the factory via the parameter element (the factory has to implement interface IExecutableExtension for being able to be initialized with the parameters).
Finally, you can see that in namespace ccw.editors.clojure.nrepl-hyperlink, the function factory is rather simple and just calls the make function:
(defn make []
  (let [state (atom nil)]
    (reify org.eclipse.ui.console.IPatternMatchListenerDelegate
      (connect [this console]  (dosync (reset! state console)))
      (disconnect [this]       (reset! state nil))
      (matchFound [this event] (match-found event @state)))))

(defn factory "plugin.xml hook" [ _ ] (make))

Please note that I'm showing this as an example, and the relevant code in Counterclockwise is not ready to be released as an independant library "ready for consumption".
But you should nonetheless be able to roll your own solution (it's quite easy once you get all the pieces in place in your head).
Hope that helps,
--
Laurent

A: Another solution occured to me: it is possible, in Eclipse, despite what I said in my previous answer, to create cyclic dependencies between the classloaders!
Eclipse guys needed to introduce this so that certain types of libraries (log4j, etc.) could work in an OSGi environment (which is what Eclipse is based upon).
This requires to leverage the Eclipse-BuddyPolicy mechanism (Third Party libraries and classloading).
It's quite easy: if you want plugin B to see all classes and resources of plugin A, just add this to plugin B's META-INF/MANIFEST.MF file:
Eclipse-BuddyPolicy: dependent

The line above indicates that plugin B's classloader will be able to access what its dependents classloaders have access to.
I created a sample set of plugins named A and B where B has 2 commands (visible in the top menu) : the first applies a text transformation on the "hello" hard coded string by calling clojure code in B. The second dynamically loads an new text transformation from plugin A, so that when you invoke the first command again, you see the result of applying transformations from B and transformations from A.
In your case, it may not even be required to use Eclipse Extension Point / Extension mechanism at all, after all. It will all depend on how you intent plugin B to "discover" plugin A relevant information.
The github repository showing this in action: https://github.com/laurentpetit/stackoverflow-12689605
HTH,
--
Laurent


Q: How find this equation solution $2\sqrt[3]{2y-1}=y^3+1$ find this equation roots:
$$2\sqrt[3]{2y-1}=y^3+1$$
My try: since
$$8(2y-1)=(y^3+1)^3=y^9+1+3y^3(y^3+1)$$
then
$$y^9+3y^6+3y^3-16y+9=0$$
Then I can't.Thank you someone can take hand  find the equation roots.

A: Another approach:
Put $x=\sqrt[3]{2y-1}$ then $x^3=2y-1$. So, $x^3+1=2y$
Then we have the system of equation:
$\left\{\begin{matrix} x^3+1=2y\\y^3+1=2x \end{matrix}\right.$
Subtracting these two equations from each other, we have
$(x-y)(x^2+xy+y^2+2)=0$
which gives $x=y$ as ($x^2+xy+y^2+2>0 $  $\forall$ $x,y$)
Hence we have $y=\sqrt[3]{2y-1}$
$\Rightarrow y^3-2y+1=0$
$\Leftrightarrow(y-1)(y^2+y-1)=0$
Therefore, $y=1$ or $y=\frac{-1\pm \sqrt{5} }{2}$

A: $$y^9+3y^6+3y^3-16y+9=0\iff(y-1)(y^2 + y - 1)(y^6 + 2y^4 + 2y^3 + 4y^2 + 2y +9) = 0$$
Three real-valued roots: $$y = 1, y = \dfrac{-1 \pm \sqrt 5}{2}$$
I noticed by inspection that $y = 1$ solves the equation. Then, using polynomial division, and manipulation with the resulting quotient, was able to find the quadratic factor. The sixth degree polynomial has no real roots.
Additional tip: Sometimes it helps to graph the equation to learn how many real roots there are: look for points intersecting the x-axis. Here's the graph of your 9th-degree polynomial:

A: Let $f(y) = \frac12 (y^3+1)$, we have
$$2\sqrt[3]{2y-1} = y^3+1\quad\iff\quad f^{-1}(y) = f(y) \quad\implies\quad y = f(f(y))$$
Since $f(y)$ is a strictly increasing function in $y$, we have

*

*If $f(x) > x$, then $f(f(x)) > x$.

*If $f(x) < x$, then $f(f(x)) < x$.

This means
$$\begin{align}
y = f(f(y)) \implies & y = f(y)\\
\iff & y^3+1 - 2y = 0\\
\iff & (y^2 + y -1 )(y-1) = 0\\
\implies & y = 1\text{ or }  \frac{-1\pm \sqrt{5}}{2}
\end{align}$$


Q: Apache2: How can I get Apache2 to not respond? I didn't find a way but it can't be so hard : How make Apache2 Listen a port but not responding.
My VH:
<VirtualHost *:80>
    ServerName catchall
</VirtualHost>

I don't want to respond 403 or another status... I want the connexion failed.
Why ? Just because I have an other VH on the same port but wich is responding for a domain and I can't have this IP connection.
Thank you.

A: I believe you should just be able to block the outgoing port through iptables with something along the lines of:
iptables -A OUTPUT -p tcp --dport 403 -j DROP

Just configure it to listen, and then on response its outgoing packet should be dropped silently.
This rule would have to be before any outgoing rule that might apply that might include the
"--state ESTABLISHED -j ACCEPT"

Line.
More information can be found here: http://linuxconfig.org/collection-of-basic-linux-firewall-iptables-rules"


Q: Implement fold with for-comprehension How can a fold be implemented as a for-comprehension in Scala? I see the only way is to use some recursive call? This is a try that is failing, not sure how to do this? What is the best way to implement fold as a for-comprehension
  val nums = List(1,2,3)
  nums.fold(0)(_+_)
  def recFold(acc: Int = 0): Int = {
    (for {
        a <- nums
        b = recFold(a + acc)
    } yield b).head
  }
    recFold(0) //Stack overflow

A: If you really want to use for, you don't need recursion, but you would need a mutable variable:
val nums = List(1,2,3)

def recFold(zero: Int)(op: (Int, Int) => Int): Int = {
  var result: Int = zero
  for { a <- nums } result = op(result, a)
  result
}

recFold(0)(_ + _) // 6

Which is pretty similar to how foldLeft is actually implemented in TraversableOnce:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
  var result = z
  this foreach (x => result = op(result, x))
  result
}

A: Fold can be implemented both ways right to left or left to right. No need to use for plus recursion. Recursion is enough.
  def foldRight[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
    as match {
      case Nil => z
      case x :: xs => f(x, foldRight(xs, z)(f))
    }
  }

  @annotation.tailrec
  def foldLeft[A, B](as: List[A], z: B)(f: (A, B) => B): B = {
    as match {
      case Nil => z
      case x :: xs => foldLeft(xs, f(x, z))(f)
    }
  }


Q: Scala/Spark Apriori implementation extremely slow We are trying to implement the Apriori algorithm in Scala using Spark (you don't need to know the algorithm to answer this question).
The function computing the itemsets of the Apriori algorithm is freq(). The code is correct but it gets slower after each iteration in the while in the freq() function, up to the point of taking several seconds to perform a cross join on a table with 1 row with itself.
import System.{exit, nanoTime}
import scala.collection.mutable.WrappedArray
import org.apache.spark.sql.{Column, SparkSession, DataFrame}
import org.apache.spark.sql.functions._
import spark.implicits._

object Main extends Serializable {
  val s = 0.03

  def loadFakeData() : DataFrame = {
    var data = Seq("1 ",
                   "1 2 ",
                   "1 2",
                   "3",
                   "1 2 3 ",
                   "1 2 ")
                .toDF("baskets_str")
                .withColumn("baskets", split('baskets_str, " ").cast("array<int>"))
      data
  }

  def combo(a1: WrappedArray[Int], a2: WrappedArray[Int]): Array[Array[Int]] = {
    var a = a1.toSet
    var b = a2.toSet
    var res = a.diff(b).map(b+_) ++ b.diff(a).map(a+_)
    return res.map(_.toArray.sortWith(_ < _)).toArray
  }
  val comboUDF = udf[Array[Array[Int]], WrappedArray[Int], WrappedArray[Int]](combo)

  def getCombinations(df: DataFrame): DataFrame = {
    df.crossJoin(df.withColumnRenamed("itemsets", "itemsets_2"))
      .withColumn("combinations", comboUDF(col("itemsets"), col("itemsets_2")))
      .select("combinations")
      .withColumnRenamed("combinations", "itemsets")
      .withColumn("itemsets", explode(col("itemsets")))
      .dropDuplicates()
  }

  def countCombinations(data : DataFrame, combinations: DataFrame) : DataFrame = {
    data.crossJoin(combinations)
      .where(size(array_intersect('baskets, 'itemsets)) === size('itemsets))
      .groupBy("itemsets")
      .count
  }

  def freq() {
    val spark = SparkSession.builder.appName("FreqItemsets")
      .master("local[*]")
      .getOrCreate()

    // data is a dataframe where each row contains an array of integer values
    var data = loadFakeData()
    val basket_count = data.count

    // Itemset is a dataframe containing all possible sets of 1 element
    var itemset : DataFrame = data
                                .select(explode('baskets))
                                .na.drop
                                .dropDuplicates()
                                .withColumnRenamed("col", "itemsets")
                                .withColumn("itemsets", array('itemsets))
    var itemset_count : DataFrame = countCombinations(data, itemset).filter('count > s*basket_count)
    var itemset_counts = List(itemset_count)

    // We iterate creating each time itemsets of length k+1 from itemsets of length k
    // pruning those that do not have enough support
    var stop = (itemset_count.count == 0)
    while(!stop) {
      itemset = getCombinations(itemset_count.select("itemsets"))
      itemset_count = countCombinations(data, itemset).filter('count > s*basket_count)
      stop = (itemset_count.count == 0)
      if (!stop) {
        itemset_counts = itemset_counts :+ itemset_count
      }
    }

    spark.stop()
  }
}

A: Since Spark retains the right to regenerate datasets, at any time, that may be what's happening, in which case caching the results of expensive transformations can lead to dramatic improvements in performance.
In this case, it looks at first glance like itemset is the heavy hitter, so
itemset = getCombinations(itemset_count.select("itemsets")).cache

May pay dividends.
It should also be noted that building up a list by appending in a loop is generally a lot slower (O(n^2)) than building it by prepending.  If correctness isn't affected by the order of itemset_counts, then:
itemset_counts = itemset_count :: itemset_counts

will produce at least a marginal speed-up.


Q: Enable :active state in IE7 with jQuery? I've searched for a simple jQuery plugin to enable the active state in IE7, but I've only been able to find IE7-js, which doesn't play well with my current javascript.
I think I could build this myself, but I figure someone else has already done a better job of it than I would. Is there a solid jQuery plugin that does this already?
Thanks in advance!

A: IE7 should work just fine with :active on anchors (<a>), as long as the anchor has the href attribute (source).


Q: Three diodes in series AC detection Why, in the circuit shown here, would you put three diodes in series with one another instead of using one diode?

A: It reads in the answer. To get enough voltage to be able to turn on the optocoupler LED.


Q: Android launchin thridparty intent not working I 'm trying to launch the camera app on button click but I don't want to hav the fot
I want it to behave like it is launched by the lauc´ncher but when I call my code the application simply closes and the camera isn't starting.There isn't even an error code.
Code :
if(v == camera)
    {

        //Intent in=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // this.startActivity(in);

        Intent startupIntent = new Intent();
        ComponentName distantActivity = new ComponentName("com.android.camera","com.android.camera/.Camera");
        startupIntent.setComponent(distantActivity);
        startupIntent.setAction(Intent.ACTION_MAIN);
        startActivity(startupIntent);

        finish();
    }

A: use android.intent.action.VIEW instead of Intent.ACTION_MAIN as:
    Intent startupIntent = new Intent();

    ComponentName distantActivity= new ComponentName("YOUR_CAMRA_APP_PACKAGE","YOUR_CAMRA_APP_PACKAGE.ACTIVTY_NAME");

// LIKE IN LG  DEVICE WE HAVE AS

//ComponentName distantActivity= new //ComponentName("com.lge.camera","com.lge.camera.CameraApp");

    startupIntent .setComponent(distantActivity);

    startupIntent .setAction("android.intent.action.VIEW");

    startActivity(startupIntent);


Q: Why does Terminals.tokenizer() tokenize unregistered operators/keywords? I've just discovered the root cause of some very confusing behavior I was observing. Here is a test:
@Test
public void test2() {
    Terminals terminals = Terminals.caseInsensitive(new String[] {}, new String[] { "true", "false" });
    Object result = terminals.tokenizer().parse("d");
    System.out.println("Result: " +  result);
}

This outputs:
Result: d

I was expecting the parser returned by terminals.tokenizer() not to return anything because "d" is not a valid keyword or operator.
The reason I care is because I wanted my own parser at a lower priority than that returned by terminals.tokenizer():
public static final Parser<?> INSTANCE =
        Parsers.or(
                STRING_TOKENIZER,
                NUMBER_TOKENIZER,
                WHITESPACE_TOKENIZER,
                (Parser<Token>)TERMINALS.tokenizer(),
                IDENTIFIER_TOKENIZER);

The IDENTIFIER_TOKENIZER above is never used because TERMINALS.tokenizer() always matches.
Why does Terminals.tokenizer() tokenize unregistered operators/keywords? And how might I get around this?

A: In the upcoming jParsec 2.2 release, the API makes it more clear what Terminals does:
http://jparsec.github.io/jparsec/apidocs/org/codehaus/jparsec/Terminals.Builder.html
You cannot even define your keywords without first providing a scanner that defines "words".
The implementation first uses the provided word scanner to find all words, and then identifies the special keywords on the scanned words.
So, why does it do it this way?

*

*If you didn't need case insensitivity, you could have passed the keywords as "operators". Yes, you read it right. One can equally use Terminals.token(op) or Terminals.token(keyword) to get the token level parser of them. What distinguishes operators from keywords is just that keywords are "special" words. Whether they happen to be alphabet characters or other printable characters is just by convention.

*Another way to do it, is to define your word scanner precisely as Parsers.or(Scanners.string("keyword1"), Scanners.string("keyword2"), ...). Then Terminals won't try to tokenize anything else.

*The above assumes that you want to do the 2-phase parsing. But that's optional. Your test shows that you weren't feeding the tokenizer to a token-level parser using Parser.from(tokenizer, delim). If two-phase parsing isn't needed, it can be as simple as:        or(stringCaseInsensitive("true"), stringCaseInsensitive("false"))
More on point 3. The 2-phase parsing creates a few extra caveats in jParsec that you don't find in other parser combinators like Haskell's Parsec. In Haskell, a string is no different from a list of character. So there really isn't anything to gain by special casing them. many(char 'x') parses a string just fine.
In Java, String isn't a List or array of char. It would be very inefficient if we take the same approach and box each character into a Character object so that the character level and token level parsers can be unified seamlessly.
Now that explains why we have character level parsers at all. But it's completely optional to use the token level parsers (By that, I mean Terminals, Parser.from(), Parser.lexer() etc).
You could create a fully functional parser with only character-level parsers, a.k.a scanners.
For example: Scanners.string("true").or(Scanners.string("false")).sepEndBy1(delim)

A: From the documentation of Tokenizer#caseInsensitive:

org.codehaus.jparsec.Terminals
public static Terminals caseInsensitive(String[] ops,
                                          String[] keywords)
Returns a Terminals object for lexing and parsing the operators with names specified in
  ops, and for lexing and parsing the keywords case insensitively. Keywords and operators
  are lexed as Tokens.Fragment with Tokens.Tag.RESERVED tag. Words that are not among
  keywords are lexed as Fragment with Tokens.Tag.IDENTIFIER tag. A word is defined as an
  alphanumeric string that starts with [_a - zA - Z], with 0 or more [0 - 9_a - zA - Z]
  following.

Actually, the result returned by your parser is a Fragment object which is tagged according to its type. In your case, d is tagged as IDENTIFIER which is expected.
It is not clear to me what you want to achieve though. Could you please provide a test case ?

A: http://blog.csdn.net/efijki/article/details/46975979
The above blog post explains how to define your own tag. I know it's in Chinese. You just need to see the code. Especially the withTag() and patchTag() part.


Q: Screenshot comes out black on Wayland I found this code to take a screenshot on Ted Mielczarek's website.
/*
 * gdk-screenshot.cpp: Save a screenshot of the root window in .png format.
 *  If a filename is specified as the first argument on the commandline,
 *  then the image will be saved to that filename. Otherwise, the image will
 *  be saved as "screenshot.png" in the current working directory.
 *
 * Compile with:
 * g++ -o gdk-screenshot gdk-screenshot.cpp `pkg-config --cflags --libs gdk-x11-2.0`
 */

#include <gdk/gdk.h>
#include <gdk/gdkx.h>

int main(int argc, char** argv)
{
  gdk_init(&argc, &argv);
  GdkWindow* window = window = gdk_get_default_root_window ();
  GdkPixbuf* screenshot = gdk_pixbuf_get_from_drawable (NULL, window, NULL,
                            0, 0, 0, 0,
                            gdk_screen_width(),
                            gdk_screen_height());
  GError* error = NULL;
  const char* filename = (argc > 1) ? argv[1] : "screenshot.png";
  return TRUE == gdk_pixbuf_save (screenshot, filename, "png",
                  &error, NULL);
}

I compiled it as described and it appears to work, in that it produces an image with the correct dimensions, but the screenshot is entirely black.

This appears to be a common issue on systems running Wayland (I'm running Archlinux with Wayland), so my question is:
What modifications need to be made to this code to get it to produce a proper screenshot on Wayland (and X)?

A: I had a similar problem.
I use Xlib to take screenshots, but this method can't work on Wayland. Every time I run to xgetimage, I report an error. After looking up the data, I find Wayland doesn't allow such screenshots. However, in this way, I can still get the correct screen size.
Now I use DBUS to call the session bus of the system to take a screenshot, which I learned from reading the source code of Gnome screenshot.
This is a simple summary code:
    method_name = "Screenshot";
    method_params = g_variant_new ("(bbs)",
                                     TRUE,
                                     FALSE, /* flash */
                                     filename);

    connection = g_application_get_dbus_connection (g_application_get_default ());
    g_dbus_connection_call_sync (connection,
                               "org.gnome.Shell.Screenshot",
                               "/org/gnome/Shell/Screenshot",
                               "org.gnome.Shell.Screenshot",
                               method_name,
                               method_params,
                               NULL,
                               G_DBUS_CALL_FLAGS_NONE,
                               -1,
                               NULL,
                               &error);

The document link is here:
https://developer.gnome.org/references
The GitHub of Gnome screenshot is here:
https://github.com/GNOME/gnome-screenshot


Q: How to query a document with the highest value of a field Let's say I have a collection of documents. To make this simpler, let's say all these documents have just 2 fields, name and id, like below.
I want to get the document with the greatest value of "id". Can I use the .find({}) with some parameters? If so, I can't figure out which parameter would find me the max value of a certain field.
[
  {
    name: "name1",
    id: 1
  }
  {
    name: "name2",
    id: 2
  }
  {
    name: "name1",
    id: 3
  }
  {
    name: "name1",
    id: 0
  }
]

A:

let documents = [
  {
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

let max = documents.sort( (a, b) => a.id > b.id ? -1 : 1)[0]
console.log( max );

How about
let maxIdDocument = documents.sort( (a, b) => a.id > b.id ? 1 :  -1)[0]

A: First, sort in descending order, then get the first one:

const arr = [{
    name: "name1",
    id: 1
  },
  {
    name: "name2",
    id: 2
  },
  {
    name: "name1",
    id: 3
  },
  {
    name: "name1",
    id: 0
  }
];

const [greatest] = arr.sort(({ id: a }, { id: b }) => b - a);

console.log(greatest);

A: You can sort that array and with the function pop get the object with the greatest id.
arr.slice() // This is to avoid a mutation on the original array.

let arr = [   {     name: "name1",     id: 1   },   {     name: "name2",     id: 2   },   {     name: "name1",     id: 3   } ,  {     name: "name1",     id: 0   } ],
    greatest = arr.slice().sort(({id: a}, {id: b}) => a - b).pop();

console.log(greatest);
.as-console-wrapper { min-height: 100%; }


Q: ADB2C - How to change UI for password confirmation screen(In reset password flow) I have created sign-in user flow with reset password user flow.
I have updated UI with custom UI in both the flows. When user click on 'Forgot password' link then user is seeing new UI for 'Reset password' user flow, but after email verification when user click on continue then user is seeing default UI as below.
Any one know how can I change this UI as well with custom UI.

A: You have to add Custom page for Change password page also. I thin you have added Custom Page only for Forgot password page.


Q: Resolve @RegisteredOAuth2AuthorizedClient with the token obtained outside of spring server of Spring Security 5.2.x I have a controller method that has an argument OAuth2AuthorizedClient with annotation @RegisteredOAuth2AuthorizedClient.
ResponseEntity<String> getFoo(
            @RegisteredOAuth2AuthorizedClient("custom") OAuth2AuthorizedClient client) {
OAuth2AccessToken token = client.getAccessToken();
 ....
}

In order to resolve this, spring look for OAuth token on OAuth2AuthorizedClientService which actually stores the previously authenticated tokens in memory.
Now, I have a scenario where I obtain JWT token from OAuth server outside of this spring resource server, and trying to authenticate this server by passing token using Authorization header.
But when spring trying to resolve OAuth2AuthorizedClient it is looking for token in-memory with the principle of JWT (which will obviously not found since token is not obtained on this server). Hence send new login redirection for new token.
Overall question would be, is it possible to resolve   OAuth2AuthorizedClient with the JWT token (obtained ourside of the server) passed in Authorization header?


Q: Importing python packages, nested packages... going up, traversing, etc... doesn't appear to work - what am I doing wrong? I'm having an issue. I'm porting a lot of code to Python from various other languages of things I've coded over the years and turning it into a large package.
Because not everything fits under a single package - I am nesting packages within. The main package is AcecoolLib, which has init, all of the nested packages have it too.
Because I want to be able to import AcecoolLib - and have everything imported beneath it, all of my init files import everything within their respective folder, and any packages beneath. I only nest 1 deep at the moment - I am not sure whether or not this will change. Probably not.
I have tried absolute imports, and I have tried relative. I have tried modifying sys.modules, and sys.path. I have tried adding paths and I don't know where I can map a name to the path. I end up with a lot of the package loading properly, and some areas I end up with errors where Acecool.X doesn't exist. I fix one, and another one pops up.
One I fixed was - I thought, because I had a few packages named list / tuple / dict that since these are referenced to data-types, that changing them may be beneficial. so I put them into a nested package called array and renamed all of them to include an s on the end. lists, tuples, dicts. not a fan of this - but the error went away.
I'm getting an error in my steam directory now but I don't know of steam being a protected name.
I am using the package, right now, in Sublime Text. I will be using it there for plugins I'm writing - to replace the current system I use which is a single file Acecool.py imported as AcecoolLib in another plugin... It's ugly, hard to maintain, etc.. so I moved some of the code into packages.
In short - I am running into a lot of issues.
This is the first main attempt: https://bitbucket.org/Acecool/acecoollib/src/master/
And this is where I'm at currently: https://www.dropbox.com/s/xvaubq78hlhym9o/AcecoolLib.7z?dl=0
I have tried a lot of variation....
I have looked over other packages which import through nested packages and I haven't found anything which shows me doing anything different ( before I started adding a bunch of crap to the start to find a solution )...
There must be something which lets me set up the paths for each package, and then define they all get added to the AcecoolLib namespace, with nested namespaces within...
I want to be able to go into AcecoolLib/tests/ dir and run tests throughout by running the scripts directly from tests. I also want to be able to import from external / internal sources to have access to everything if I need it.
I also want to be able to import just nested packages or the entire. ie: import AcecoolLib means I should be able to get to Acecool.util.accessors - and so on... or if I import Acecool.util then I don't see AcecoolLib.math - but I could import it.
Right now I'm testing importing everything as my current project uses almost every single function, etc... I added a few as tests..
I have read quite a lot on the subject of importing and I have come across countless 'this is the right way' 'no this' 'nope, this', and so on... none of which work. I have come across articles which say never use this type of import, or this... etc.. most of the articles aren't very useful and are plagued with personal opinions instead of covering the material of the title. Or they cover the basic 101 level variants, or show the directory tree ( which looks identical to mine ) and say that it just works as is...
Maybe that's right - maybe Sublime Text does something differently - ie: I do know that the package is being added to sys.modules, and All of the nested ones are too - so I'm just lost....
Any help is appreciated. Thank you!


Q: Prove that any subgroup of a free Abelian group of rank $r$ is free Abelian of rank at most $r$.
Let $F$ be a free abelian group of rank $r$.
Then any subgroup $R$ of $F$ is also a free abelian group of rank at most $r$.

Proof:
Let $F$ be freely generated by $a_1,a_2,\dots,a_r$. We prove by induction on $r$.
If $r=1$ , then $F$ is infinite cyclic.
Then $R$ is either infinite cyclic or $\{0\}$.
Thus $R$ is free Abelian with rank $1$ or $0$.
Suppose the theorem is true for all free Abelian group of rank $<r$.
Let $F$ be a free abelian group of rank $r$.
Define a map $\phi:F\rightarrow \mathbb{Z}$ where $(\mathbb{Z},+)$ is the infinite cyclic group, as follows: $$\phi(k_1a_1+k_2a_2+\dots+k_ra_r)=k_1$$
Then $K=\ker \phi=\{k_2a_2+\dots+k_ra_r\;|\;k_i\in\mathbb{Z},2\leq i \leq r\}$ since $k_1=0$.
Hence $K$ is a subgroup of the free abelian group $\langle a_2,\dots,a_r\rangle$ of rank $r-1$. *(1)
By induction, $K$ is a free abelian group of rank at most $r-1$.
Note that $\phi(R)\subseteq \mathbb{Z}$
Therefore $\phi(R)$ is either infinite cyclic or $\{0\}$.
Case 1: Suppose $\phi(R)=\{0\}$
Then $R\subseteq K$, and by induction, $R$ is a free abelian group of rank at most $r-1$.
Case 2: Suppose $\phi(R)=\langle m \rangle$, $m>0$
Let $r_0\in R$ such that $\phi(r_0)=m$.
We shall prove that $R=\langle r_0\rangle\oplus K$.
Let $r\in R$. Then $\phi(r)=tm$ where $t\in \mathbb{Z}$
Now $r=tr_0+(r-tr_0)$ where $tr_0\in\langle r_0 \rangle$ and $r-tr_0\in K$
So $R=\langle r_0\rangle +K$ *(2)
Let $x\in \langle r_0 \rangle \cap K$
Then $x=qr_0$.
So $\phi(x)=qm$.
But $\phi(x)=0$ since $x\in K=\ker \phi$
This implies that $qm=0$, that is $q=0$, that is $x=0$.
Therefore $\langle r_0\rangle \cap K=\{0\}$.
Hence $R=\langle r_0\rangle\oplus K$, a direct sum of an infinite cyclic group and a free abelian group of rank at most $r-1$.
So $R$ is a free abelian group of rank at most $r$.
So far there are two questions.
For (*1), can I straight away say that $K$ is free Abelian group of rank $r-1$? since it itself satisfies the definition without using induction.
For (*2), can we conclude that $R=\langle r_0\rangle\oplus K$? since $K$ is not necessarily a subset of $R$.

A: *

*Actually, $K=\langle a_2,\ldots a_r\rangle$; this is a subset of the free generators for $F$, so the conclusion is that $K$ is free of rank $r-1$:  the induction hypothesis doesn't come into it. In general, if $F$ is free on $S$, and $T\subseteq S$, then $\langle T\rangle$ is free on $T$ (this is very easy to prove using for example the universal property, but it is also easy using the explicit description as the direct sum of copies of $\mathbb{Z}$ or any other explicit construction you have).

*To prove that $C=A\oplus B$, you need to prove two things: you need to prove that $A\cap B=\{0\}$, and that $C=A+B$. Your argument only contains a proof that $\langle r_0\rangle\cap K=\{0\}$. Even on its face, it is incomplete to establish your claimed conclusion. And in fact, you are correct to be worried: normally, in proving $C=A\oplus B$, we start with $A$ and $B$ subgroups of $C$, so that the inclusion $A+B\subseteq C$ is never mentioned (because it is obvious), and so we only need to check that $C\subseteq A+B$. Here, you do not have that $K\leq R$ (most of the time it won't be), so you cannot show that $R=\langle r_0\rangle + K$, which is the step you are missing.
What you need to prove is that $R=\langle r_0\rangle \oplus (K\cap R)$. That the intersection is trivial follows by what you've already done (or by the exact same argument). To prove that $R=\langle r_0\rangle +  (K\cap R)$, let $r\in R$. Then find a multiple of $r_0$ such that $r-mr_0\in K$ and go from there to finish it off.


Q: "__NSAutoreleaseFreedObject(): release of previously deallocated object" out of the blue I'm not sure if this is an error or not. The code compiles fine (no warnings), but when I enter a method, a local's value (an NSMutableString) displays this content in the debugger:
__NSAutoreleaseFreedObject(): release of previously deallocated object

I'm not getting an exception, it looks like the contents of the string (which is not even allocated at that time) is that NSAutoReleaseFreedObject warning.
What's going on?

A: it (likely) means that your app has executed different from usual, and exposed a bug in your ref counting of the object. this type of issue can also be related to improper multithreading.
executing your app to trigger the problem with zombies enabled should help you locate it.

A: If you don't initialize a normal local variable to anything, its value is undefined — it could be anything. In practice, it will interpret the bit pattern that happens to lie on the stack where the variable is allocated as a value of the variable's type. In this case, the "anything" that the variable contains happens to be the address of that string.


Q: stacking documents as successive versions within a library If I have 3 files of the same general type, A1, A2 and A3, already uploaded to a given document library, is there a way to "stack" them within the library such that they are treated as numbered versions of the same document?  In other words, A1 becomes version 1.0, A2 becomes V2.0 and A3 becomes 3.0?  (This assumes of course that major versioning is already active in this library).
I'm trying to speed up maintaining versioning for files that are edited outside of SP and may not maintain consistent naming, but not have to designate and upload individual versions one at a time.  Also other users occasionally drag and drop a new doc version in without stacking and ask me to "fix it".
It feels like this should be trivial but this is a point on which I am frequently very much incorrect.
thanks in advance,

A: The only way would be to do it manually, that is, check A1 out, download A2, rename it to A1 and upload it which would then become A1 2.0.  Repeat the process for A3 which would become A1 3.0 and so forth.  It isn't a lot of work but I can certainly see how it would get annoying.
You will also lose the meta information from the version history this way as it will only show you as the one who made the change and the timestamp will be the time you made the change, not the time it was actually changed.
The real "fix" is to train your users to understand how the system works and get them using it properly.  It isn't really that hard for them to do.


Q: CSV -> JSON -> PostgreSQL "Token invalid" I have a CSV file containing 1 column ("json_doc") with many rows of JSON data. I want to collect this json data and upload it to a Postgres database. The rows are in the format:
{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "description": "Agenti e rappresentanti di animali vivi"}], "founded": "1972-07-10", "legalName": "COBEM - S.R.L.", "legalForms": [{"name": "Società Di Capitale", "level": 1}, {"name": "Società A Responsabilità Limitata", "level": 2}]}, "name": "COBEM - S.R.L.", "people": {"items": [{"name": "45808b0b5b5affa871c8e91169bb10c6930fac56", "givenName": "64e4393f477394f11f6477ca76395ed469548865", "familyName": "68ee44f14dc54d664dffe63195d42a14988b69bb"}]}, "country": "it", "locations": {}}

There are millions of rows, and not all of the formatting is consistent i.e. some nested dictionaries are structurally different to others.
I've taken 5 of these rows, and applied the following Python:
import pandas as pd

df = pd.read_csv('samplecol.csv')
df = df.to_json('data.json')

I then use https://jsonlint.com to check the JSON and all is good.
I have a JSON file, data.json, and a PostgreSQL database, and want to get data.json into Postgres.
I run the following to create a table :
SN_ITA_test=# CREATE TABLE jsons(ID serial NOT NULL PRIMARY KEY, info jsonb NOT NULL);

When I try to upload the file to Postgres using :
SN_ITA_test=# \copy jsons (info) FROM 'data.json';

I get the error:
ERROR:  invalid input syntax for type json
DETAIL:  Token "id" is invalid.
CONTEXT:  JSON data, line 1: {"json_doc":{"0":"{"id...
COPY jsons, line 1, column info: "{"json_doc":{"0":"{"id": "0436d9b9305d", "base": {"ateco": [{"code": "46.11.03", "rootCode": "G", "d..."


Q: Getting Pending Request on HTTP Client Response while ataching multiple files I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
    $response = Http::withHeaders([
        'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
    ]);

    foreach($files as $k => $file)
    {
        $response = $response->attach('images['.$k.']', $file);
    }

    $response->post($this->base_url.$url, $params);

    return response()->json($response->collect());
}

The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."


Q: Security: Sending email address in a url parameter Is it considered bad security practice to include somebody's email address in a url as a parameter over http? The email address belongs to a client, and they may not want anybody to see it. The url points to my own domain, I'm just creating unique urls with email addresses as a parameter so I can detect who visited the url. Can anybody sniff http traffic to extract that info?

A: Yes, it's bad practice to put any personal information in the URL. A URL can be cached and viewed in so many ways. Even if you use SSL, URLs are still saved in your browser's history, so it just makes me cringe to pass non-public data in the URL. Usually it's not any more work to pass information in the body of a POST request, so that's what I would do.

A: Not if you do it over https, as the URL path and querystring will be encrypted along with the body.
It's not a problem for the URL to be stored in the browser history, as that is private to the user.


Q: Code not working. Dropdown menu in Android This is the java file of the code followed by xml file.
The programs shows an error "Unexpectedly stopped working"
I cannot find the error through logCat also. Can someone suggest something ?
Java file:
package com.example.ui;

import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Tp extends ListActivity implements OnItemSelectedListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tp);

    String[] technology = {"PHP", "Ruby", "Java", "SQL"};
    ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
    final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
    spinnertech.setAdapter(adp);
    spinnertech.setOnItemSelectedListener(this);

}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    int position = arg0.getSelectedItemPosition();

    if(position == 0) {
        Toast.makeText(getApplicationContext(), " 0 selected",
                   Toast.LENGTH_LONG).show();
    } else if(position == 1) {
        Toast.makeText(getApplicationContext(), " 1 selected",
                   Toast.LENGTH_LONG).show();
    }

    else {
        Toast.makeText(getApplicationContext(), " extra selected",
                   Toast.LENGTH_LONG).show();}
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {

}

}

XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

    <TextView
    android:id="@+id/textView100"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<Spinner
    android:id="@+id/spinner"
    android:layout_width="248dp"
    android:layout_height="36dp"
    android:prompt="@string/title" />

</LinearLayout>

Here's the LogCat
05-25 16:33:31.270: D/AndroidRuntime(566): Shutting down VM

05-25 16:33:31.270: W/dalvikvm(566): threadid=1: thread exiting with uncaught exception (group=0x4001d800)

05-25 16:33:31.289: E/AndroidRuntime(566): FATAL EXCEPTION: main

05-25 16:33:31.289: E/AndroidRuntime(566): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ui/com.example.ui.Tp}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.os.Handler.dispatchMessage(Handler.java:99)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.os.Looper.loop(Looper.java:123)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.main(ActivityThread.java:4627)

05-25 16:33:31.289: E/AndroidRuntime(566):  at java.lang.reflect.Method.invokeNative(Native Method)

05-25 16:33:31.289: E/AndroidRuntime(566):  at java.lang.reflect.Method.invoke(Method.java:521)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

05-25 16:33:31.289: E/AndroidRuntime(566):  at dalvik.system.NativeStart.main(Native Method)

05-25 16:33:31.289: E/AndroidRuntime(566): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ListActivity.onContentChanged(ListActivity.java:245)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.Activity.setContentView(Activity.java:1647)

05-25 16:33:31.289: E/AndroidRuntime(566):  at com.example.ui.Tp.onCreate(Tp.java:18)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

05-25 16:33:31.289: E/AndroidRuntime(566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

05-25 16:33:31.289: E/AndroidRuntime(566):  ... 11 more

05-25 16:33:33.089: I/Process(566): Sending signal. PID: 566 SIG: 9

A: I guess problem in below statement
Toast.makeText(getApplicationContext(), " 0 selected",
                   Toast.LENGTH_LONG).show();

change to
Toast.makeText(this, " 0 selected",
                   Toast.LENGTH_LONG).show();

or
Toast.makeText(tp.this, " 0 selected",
                   Toast.LENGTH_LONG).show();

Edit:--------------------------------------------------------------------------
public class Tp extends Activity implements OnItemSelectedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tp);

        String[] technology = {"PHP", "Ruby", "Java", "SQL"};
        ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology);
        final Spinner spinnertech = (Spinner) findViewById(R.id.spinner);
        spinnertech.setAdapter(adp);
        spinnertech.setOnItemSelectedListener(this);

    }

if this is not working then include listview in xml file.

A: This is your problem
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

If you are using ListActivity, your layout file R.layout.activity_tp must have a ListView with android:id="@android:id/list" attribute. Look here: http://developer.android.com/reference/android/app/ListActivity.html for example.


Q: Eclipse LDT doesn't run local Lua interpreter I have problem with Eclipse LDT. When I run my test Lua app, it executes just fine using JNLua inside JavaVM environment. But according to this tutorial, when I reference native lua.exe interpreter and set it in Run Configuration as Runtime Interpreter, Run Configuration disables Launch script: and nothing is executed. When I run a same script with a same native local Lua interpreter 5.1, everything works just fine.
So, what is the problem with LDT? Has anyone had the same experience?
EDIT
I've managed to run local lua.exe from Lua Development Tools stand-alone product, but still it doesn't work as Eclipse plug-in.

A: I'm not sure it's a bug.
I guess when you register your interpreter, you uncheck the checkbox : "Accept file as argument"
This mean LDT will not manage the file to launch (that's why the Launch script is disabled)
The standard lua interpreter support file as argument and -e option, so the two check box should be checked. (It's the default value)

A: It looks like a bug ... Would you mind filing it in the Koneki bug tracker?


Q: How do I calculate subtotals using onblur and javascript? How do I calculate subtotals for each row of a product listing by using an input text field to enter one of the numbers?
example:
colA    colB            colC

100 - [text input] = [calculated result]

880 - [text input] = [calculated result]

720 - [text input] = [calculated result]

130 - [text input] = [calculated result]
...

I'm sure this is fairly easy to do with Javascript, but I've looked and can't find a simple answer.  I'm not very familiar with Javascript so I need a simple solution.  Thanks in advance for all the help! :)

A: Welcome to StackOverflow!  In the future, you can probably get a good answer faster if you write your question more clearly.
You can use document.getElementById('id_of_text_input').value to get or set the value of any text input.  Note that you are using id, not name.
You can use parseFloat to get a read a string as a floating number value.
In order to attach a function to the onblur event, you can use the setAttribute function.
So, for example, if you have a text input with id colA and you want to subtract 100 from the value the user enters and save the result in a text input with id colB.
You could write code like this:
<html>
<head runat="server">
    <title></title>
</head>
<body>
    <input type='text' id='colA' />
    <input type="text" id='colB' />
</body>
<script type="text/javascript">
    var colA = document.getElementById('colA');
    var colB = document.getElementById('colB');
    colA.setAttribute('onblur',
    function () {
        var value = colA.value;
        var number = parseFloat(value)-100;
        colB.value = number;
    });
</script>
</html>

A: Very useful for me. Thanks, Daniel
If you want to calculate a percentage (5% for example) and use Jquery, you have to
    $(function(){
        $(".input-valorinicial").blur(function(){
            var valorinicial = document.getElementById('valorinicial');
            var fee = document.getElementById('fee');
            var value = valorinicial.value;
            var number = parseFloat(value)*5/100;
            fee.value = number;
        });
    });


Q: Manually sanitize SQL parameters I would like to run a script like:
CREATE LOGIN [me] WITH PASSWORD = @0

and run it like:
var createUserCommand = conn.CreateCommand();
createUserCommand.CommandText = script;
createUserCommand.Parameters.AddWithValue("@0", passwordDecrypted);

However, this throws:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
  Additional information: Incorrect syntax near '@0'.

From what I read online (nowhere official, just from SO answers/comments) it is not possible to use SQL parameters with DDL statements. Link to official docs for this are welcome!
OK. I do need this parametrized. As I see it, there are 2 options:

*

*I manually sanitize (.Replace("'", "''") => how can I do this best?

*I call into .NET to sanitize for me. However I assume this is not sanitized within ADO.NET, but just past to SQL Server, and sanitized there...

What would be the best approach?

A: All you need to escape is the single ' to 2 x '
commandText = string.Format("CREATE LOGIN [me] WITH PASSWORD = '{0}'", pass.Replace("'", "''"));

An alternative would be to create a stored procedure with a password parameter and use it to build a CREATE LOGIN string which you then sp_executeSQL.


Q: OpenCV. detectMultiScale() function return error I'm new to OpenCV. Took an example from official documentation. When I try to run the code, an error pops up. When you try to run the code, an error pops up when you call the function detectMultiScale ()
Mat image;
image = imread("1.jpg", CV_LOAD_IMAGE_COLOR);
imshow("cam", image);
// Load Face cascade (.xml file)
CascadeClassifier face_cascade;
face_cascade.load("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml");

// Detect faces
std::vector<Rect> faces;

Mat frame_gray;
cvtColor(image, frame_gray, COLOR_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

Tell me how to solve this problem?
enter image description here

A: It is because of your xml file path, be sure about that your path directory is true. I checked your code in my pc and worked well. Search your "haarcascade_frontalface_alt2.xml" file in your pc and copy it to your code.
The same problem was also mentioned here


Q: Java. HSSF. Apache-poi. How to modificate code
My data is stored in a format(look down): [-] means a blank cell, on the right may
  be only 10 columns, after the space. Something like this:
     [string0] [-] [string1] [string2] [string3] .. [string10] [-]

How to change this code for:
1) obtain only [string0]
2) obtain only [string1] [string2] [string3] .. [string10] [-]
    try {

    FileInputStream file = new FileInputStream("C:\\Users\\student3\\"+sfilename+".xls");

    //Get the workbook instance for XLS file
    HSSFWorkbook workbook = new HSSFWorkbook(file);

    //Get first sheet from the workbook
    HSSFSheet sheet = workbook.getSheetAt(0);

    //Iterate through each rows from first sheet
    Iterator<Row> rowIterator = sheet.iterator();
    while(rowIterator.hasNext()) {
        Row row = rowIterator.next();

        //For each row, iterate through each columns
        Iterator<Cell> cellIterator = row.cellIterator();
        while(cellIterator.hasNext()) {

            Cell cell = cellIterator.next();

            switch(cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    System.out.print(cell.getStringCellValue() + "\t\t");
                    list1.add(cell.getStringCellValue());
                    break;
            }
        }
        System.out.println("");
    }
    file.close();
    FileOutputStream out =
            new FileOutputStream("C:\\Users\\student3\\"+sfilename+".xls");
    workbook.write(out);
    out.close();

I don't know how to stop Iterator. He absorbs all..

A: If I am clear you just want to filter your first column string and rest seperately.
Why not you just use a simple counter for this:
 while(rowIterator.hasNext()) {
    Row row = rowIterator.next();
    String RowContent = null;
    Iterator<Cell> cellIterator = row.cellIterator();
    while(cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        RowContent=RowContent+cell.toString();
    }
    //Code for saving RowContent or printing or whatever you want for text in complete row
}

RowContent will give concatenation of each cells of a single row in each iteration.

A: Like you did in the switch block with "break".
But what i think you want is this:
Iterator<Cell> cellIterator = row.cellIterator();
boolean stop = false;
while(cellIterator.hasNext()) {

  Cell cell = cellIterator.next();

  switch(cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:
      System.out.print(cell.getStringCellValue() + "\t\t");
      list1.add(cell.getStringCellValue());
      stop = true;
      break;
  }

  if (stop) {
    break;
  }
}

This would stop the while loop when you found a string cell and will then operate on the next row.
Make any possible condition you need to break the while loop. For example collect string columns and when you found the desired set stop to true, to get to the next row.

A: External Link: Busy Developers' Guide to HSSF and XSSF Features
Here is an example that should work.
Maven Dependencies:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

Code:
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

public class StackOverflowQuestion18095443 {

    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("Please specify the file name as a parameter");
            System.exit(-1);
        }
        String sfilename = args[0];
        File file = new File("C:\\Users\\student3\\" + sfilename + ".xls");
        read(file);
    }

    public static void read(File file) {
        try (InputStream in = new FileInputStream(file)) {
            HSSFDataFormatter formatter = new HSSFDataFormatter();
            Workbook workbook = WorkbookFactory.create(in);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                StringBuilder rowText = new StringBuilder();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    String cellAsStringValue = formatter.formatCellValue(cell);
                    rowText.append(cellAsStringValue).append(" ");
                }
                System.out.println(rowText.toString().trim());
            }
        } catch (InvalidFormatException | IOException e) {
            e.printStackTrace();
        }
    }
}

As for terminating the iteration you can conditionally break from the loop. Or, you could also just not use an iterator. Notice that you can obtain a Cell from a Row using a named reference (this allows you to refer to a cell by name, such as "A2", just like you would in Excel) or simply by the column index within the row.


Q: How to populate additive field via JOIN with Doctrine Suppose i have an entity with a ManyToOne relation (with EXTRA_LAZY) and obviously a join column.
eg. Article (main entity) -> Author (external entity)

suppose i add  a field author_name to the Article that NOT mapped to the ORM and that in certain contexts this field should contain the article->author->name value (usually it can stay null).
When i query a list of articles, i would like to populate automatically that article-author_name without implementing a getter that perform a select on each element of the query result. I would like Doctrine to fetch and hydrate that value in with a simple JOIN in the original query...
I don't want to set fetch mode to EAGER for performance as in my project Author is a really complex entity.
Is this possible?
Thanks

A: Probably i've found a solution. Don't know if it is the best way to do it but it works.
I've added to the main class a field getter
public getAuthorName() {
  return $this->author->name
}

in my context this getter will only be called by a serializer in certain conditions.
In my repository code i have a special method (that i refactored so that any method could implicitly call it) to impose the population of the Article->author field when queried. The method simply use the querybuilder to add LEFT JOIN to the Author class and temporarily set FetchMode to EAGER on Article->author.
At the end a simple repository method could be this
public findAllWithCustomHydration() {
    $qb = $this->createQueryBuilder('obj');
    $qb->leftJoin("obj.author", "a")
       -> addSelect("a"); //add a left join and a select so the query automatically retrive all needed values to populate Article and Author entities
    //you can chain left join for nested entities like the following
    //->leftJoin("a.address", "a_address")
    //-> addSelect("a_address");

    $q = $qb->getQuery()
              ->setFetchMode(Article::class, "author", ClassMetadata::FETCH_EAGER);
   //setFetchMode + EAGER tells Doctrine to prepopulate the entites NOW and not when the getter of  $article->author is called.
   //I don't think that line is strictly required because Doctrine could populate it at later time from the same query result or maybe doctrine automatically set the field as EAGER fetch when a LEFT JOIN is included in the query, but i've not yet tested my code without this line.

    return $q->getResult();
}

The con is that you have to customize each query or better use a DQL / SQL / QueryBuilder for each method of the repo but with a good refactoring, for simple inclusion cases, you can write a generic method that inject that join on a field_name array basis.
Hope this help and add your answer if you find a better way.
PS. i've wrote the above code on the fly because now i'm not on my notebook, hope it works at first execution.


Q: class that extends AbstractGoogleJsonClient constructor expecting Builder, rather than 5 params from Android Developers  Tic Tac Toe client (Android), https://github.com/GoogleCloudPlatform/appengine-endpoints-tictactoe-android
there is....
public class Tictactoe extends AbstractGoogleJsonClient { etc}

with the constructor:
public Tictactoe(HttpTransport transport, JsonFactory jsonFactory,
      HttpRequestInitializer httpRequestInitializer) {

    super(transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer
       , false);
  }

I get compile errors on the super(), and I'm told that super expects Builder, not the 6 params,
BUT the class Tictactoe extends has a constructor that takes the 6 arguments.
(see
https://code.google.com/p/google-api-java-client/source/browse/google-api-client/src/main/java/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java?r=32555da5a2e95a90154f278184f3be9e230486b3 )
for
  protected AbstractGoogleJsonClient(HttpTransport transport, JsonFactory jsonFactory,
  String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer,
  boolean legacyDataWrapper) {
super(transport, httpRequestInitializer, rootUrl, servicePath, newObjectParser(
    jsonFactory, legacyDataWrapper));

}
So...
What's happening here?  Why does 'super' expect Builder rather than the 6 args?


Q: Android get unique firebase token and authenticate with cloud functions I'm building a multi-player Android game, and it uses Firebase Cloud Functions.
There are some tutorials that explains how to allow only users of my application to use my cloud function (link below), but I don't want to allow all the users to use all my functions, I want to give access based on Id. How to generate unique tokens for every user, from Android (Using Java not Kotlin) and how to get the Id from that token in node.js (Javascript not TypeScript)?
The tutorial link: https://firebase.google.com/docs/cloud-messaging/auth-server

A: Starting Firebase Functions 1.0+, there are 2 kinds of HTTP functions that you can use for your Android app.

*

*Call Functions directly. Via functions.https.onCall

*Call Functions through HTTP Request. Via functions.https.onRequest
I recommend you to use onCall as your functions endpoint, and call directly by using FirebaseFunctions. This way, you don't need to get FirebaseUser token, as it will be automatically included when you call using FirebaseFunctions.
And remember, TypeScript is just superset of Javascript. I will still give examples in Node.js, but it is recommended to type your Javascript code in TypeScript.
Example
index.js (CloudFunctions endpoint)
exports.importantfunc = functions.https.onCall((data, context) => {
   // Authentication / user information is automatically added to the request.
   if (!context.auth) {
       // Throwing an HttpsError so that the client gets the error details.
       throw new functions.https.HttpsError('not-authorised',
                         'The function must be called while authenticated.');
   }

   const uid = context.auth.uid;
   const email = context.auth.token.email;

   //Do whatever you want
});

MyFragment.java
//Just some snippets of code examples
private void callFunction() {
    FirebaseFunctions func = FirebaseFunctions.getInstance();
    func.getHttpsCallable("importantfunc")
            .call()
            .addOnCompleteListener(new OnCompleteListener<HttpsCallableResult>() {

                @Override
                public void onComplete(@NonNull Task<HttpsCallableResult > task) {
                    if (task.isSuccessful()) {
                         //Success
                    } else {
                         //Failed
                    }
                }
            });
}

More information about callable function, read here


Q: Getting smallest value from column that holds numbers as strings I'm saving numbers as strings because they are generally larger than the maximum limits MySQL allows for integers.
What I'm trying to get is the smallest and largest values from this column, but just comparing as strings returns very different results.
I've tried to add a CONVERT clause to my query like so:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CONVERT('end_timestamp', SIGNED INTEGER) DESC LIMIT 1"

But the result coming through is not correct. I think the CONVERT clause is not converting to integers in the way I was expecting it to.
So what is the best way to convert strings to integers and get the smallest value?

A: If you have a number as a string and it is an integer with no leading 0s, you can compare it by comparing the length first and then the value.  For instance, the following will order by col1 correctly (assuming the above):
select t.*
from t
order by char_length(col1), col1;

So, one way to get the minimum is:
select col1
from t
order by char_length(col1), col1
limit 1;

You can also get both in a group by by doing:
select substring_index(group_concat(col1 order by char_length(col1), col1), ',', 1
                      ) as mincol1,
       substring_index(group_concat(col1 order by char_length(col1) desc, col1 desc), ',', 1
                      ) as maxcol1
from t;

If you have zeros in front of the numbers and or decimal places, the ideas are the same, but the coding is a bit more complicated.

A: I don't have a MySQL instance to test on, but it looks like a workaround may solve your problem. I don't know that the issue here is the numbers are too large for conversion, but if they can't be integers in the database, why should it be possible to convert them to integers outside the database?
Try something like this:
"SELECT end_timestamp FROM ".$db_table_prefix."user_events ORDER BY CHAR_LENGTH(end_timestamp) DESC, end_timestamp DESC LIMIT 1"

That will sort by the number of characters first, which is where string sorts on numbers fall apart (as long as you don't have any leading zeros), followed by a numerical sort on numbers which are the same length. If that still doesn't work you may need to `SELECT CHAR_LENGTH(end_timestamp) AS ts_len' to calculate the value outside of the sort command. That is where I really don't know which will work because I don't have a MySQL instance available to test on.
You also may want to consider a data type more suited to timestamps, like TIMESTAMP or DATETIME, which could likely be converted to the format you need once they're outside the database.


Q: Debugger Visualizer and "Type is not marked as serializable" I am trying to create a debugger visualizer that would show control hierarchy for any Control. It's done but I'm getting the exception "Type  is not marked as serializable".
How do I overcome that? Control is a .NET Windows Forms framework type, I can't mark it as serializable.

A: You'll need to also implement a VisualizerObjectSource to perform custom serialization.
Example:
public class ControlVisualizerObjectSource : VisualizerObjectSource
{
    public override void GetData(object target, Stream outgoingData)
    {
        var writer = new StreamWriter(outgoingData);
        writer.WriteLine(((Control)target).Text);
        writer.Flush();
    }
}
public class ControlVisualizer : DialogDebuggerVisualizer
{
    protected override void Show(
        IDialogVisualizerService windowService,
        IVisualizerObjectProvider objectProvider)
    {
        string text = new StreamReader(objectProvider.GetData()).ReadLine();
    }
    public static void TestShowVisualizer(object objectToVisualize)
    {
        var visualizerHost = new VisualizerDevelopmentHost(
            objectToVisualize,
            typeof(ControlVisualizer),
            typeof(ControlVisualizerObjectSource));
        visualizerHost.ShowVisualizer();
    }
}
class Program
{
    static void Main(string[] args)
    {
        ControlVisualizer.TestShowVisualizer(new Control("Hello World!"));
    }
}

You'll also need to register the visualizer with the appropriated VisualizarObjectSource, which for this example could be something like this:
[assembly: DebuggerVisualizer(
    typeof(ControlVisualizer),
    typeof(ControlVisualizerObjectSource),
    Target = typeof(System.Windows.Forms.Control),
    Description = "Control Visualizer")]


Q: Continue on exception I get a few exceptions when I run my code.
What I want to do is, I want to continue on FileNotFoundException and NullPointerException and break on any other exception.
How can I go about it?
Thanks

A: try {
    stuff()
} catch( NullPointerException e ) {
   // Do nothing... go on
} catch( FileNotFoundException e ) {
   // Do nothing... go on
} catch( Exception e ) {
   // Now.. handle it!
}

A: You can do this as @daniel suggested, but I have some additional thoughts.

*

*You never want to 'do nothing'.  At least log the fact that there was an exception.

*catching NullPointerExceptions can be dangerous.  They can come from anywhere, not just the code where you expect the exception from.  If you catch and proceed, you might get unintended results if you don't tightly control the code between the try/catch block.

A: multiple catch block to caught exception arised in try block

try{

// Code that may exception arise.

}catch(<exception-class1> <parameter1>){

//User code

}catch(<exception-class2> <parameter2>){

//User code

}catch(<exception-class3> <parameter3>){

//User code

}

Source : Tutorial Data - Exception handling


Q: import file into skype for business calender I created a patient schedule file outside of Skype for business. I want to associate a patient with a selected physician. How can I import the file to the Skype for business calendar? What format should the imported file be?

A: Skype for Business does not support its own calendar. Instead, it gets calendar data from the Exchange account of the signed in user. You can easily add a new event to the user's calendar by using the Microsoft Graph RESTful API: https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/calendar_post_events


Q: Replace a word in a sentence using preg_replace How can I replace a string like

style="color:red;width:90%;" class="textbox"

to

style="color:red;width:65%;" class="textbox"

using preg_replace?
I just want to replace "width:90%" with "width:65%" and the rest of the string should stay as it is. What regular expression should I use to accomplish this?

A: str_replace("width:90%", "width:65%", $string)

A: $string = preg_replace("/width:90%/", "width:65%", $string);

if you want to make sure only elements with the class="textbox" are affected:
$string = preg_replace("/(style=\".+)(width:90%)(.+class=\"textbox\")/", "$1width:65%$3", $string);

having it work with any value and unit:
$string = preg_replace("/width:(\d+)(%|px)/", "width:65($2)", $string);

A: Thanks a lot jairajs
this worked for me
preg_replace("/width:\d+(%|px)/", "width:65%", $string)

and thanks to Gerald Schneider for helping me out


Q: How to multiply index values looped in a list I get this error when I run my code however I had converted the data in my list to an int
I have been working on this for weeks and cannot figure it out
ValueError: invalid literal for int() with base 10: '95.7'
How can I by pass this error to get the total ,
import csv
counter = 0
sum = 0
avg = 0
with open('sales_data_sample (3).csv','r') as csv_file: # opens the csv
    csv_reader = csv.reader(csv_file)
    next(csv_reader) # skips the header so we can work only with raw data
    for  ((lines)) in csv_reader: # loop through all data in the file
        counter =+ 1 # counter
        lines[1] = int(lines[1])
        lines[2] = int(lines[2])
        avg = avg + (lines[1]* lines[2])
    total = avg/counter

A: I think the issue is in the data maybe somewhere in your data you have 95.7 and since you are converting it into int so that's why it is breaking your code. You should try
lines[1] = int(float(lines[1]))
lines[2] = int(float(lines[2]))

A: Your problem is you're using integers (whole numbers). Either your lines in the csv are not whole numbers, or when calculating total, you are dividing into decimals.
To solve this, you have to use a floating-point number. Replace your uses of integers with floats.
eg.
lines[1] = int(lines[1]) should become lines[1] = float(lines[1])
You will however find you start getting numbers with long decimal places, so you can round them with the round() function, like this:
lines[1] = round(float(lines[1]), '.2f') Which will set it to 2 decimal places. You can change that 2 to any number of decimal places you'd like.
lines[1] = round(float(lines[1]), '.2f')
lines[2] = round(float(lines[2]), '.2f')


Q: How to use OrderBy to sort a custom object ascending by Date I have a collection of a custom object as follows:
public struct Record {
    public string Caller { get; set; }
    public DateTime Started { get; set; }
    public string Dialed { get; set; }
    public decimal Duration { get; set; }
    public decimal Cost { get; set; }
    public string Location { get; set; }
    public Switch Switch { get; set; }
}

public static List<Record> Records { get; set; }

Using LINQ, how can I sort Records in ascending order using the value stored in Record.Started ?

A: Just use the OrderBy method:
Records.OrderBy(record => record.Started)

or:
from r in Records
order by r.Started
select r

A: Could it be this easy?
records.OrderBy(r=>r.Started)


Q: Unable to extract key-value pairs from BigQuery table which has arrays and structs I have integrated Firebase analytics data with google BigQuery and everyday a new table gets created with the DATE stamp.
one sample table is "projectID.com_dev_sambhav_ANDROID.app_events_20170821"
One sample table is shown below
sample table
My requirement is to get result in the below desired format for event_dim.name="notification_received"
desired output
To get this desired output I execute the below query(standardSQL)
SELECT event.name
 (SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="notification_title") as notification_title,
 (SELECT param.value.string_value FROM UNNEST(event_dim.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"

But I got this error

Error: Each function argument is an expression, not a query. To use a
  query as an expression, the query must be wrapped with additional
  parentheses to make it a scalar subquery expression.

can anybody help me get out of this problem

A: The problem is a comma and an alias. This query works:
#standardSQL
WITH `projectID.com_dev_sambhav_ANDROID.app_events_2017` AS(
  SELECT ARRAY< STRUCT<date STRING, name STRING, params ARRAY< STRUCT<key STRING, value STRUCT<string_value STRING> > > > > [STRUCT('20170814' AS date, 'notification_received' AS name, [STRUCT('notification_title' AS key, STRUCT('Amazing Offers two' AS string_value) AS value ),
                                                                                STRUCT('firebase_screen_class' AS key, STRUCT('RetailerHomeActivity' AS string_value) AS value),
                                                                                STRUCT('notification_id' AS key, STRUCT('12345' AS string_value) AS value),
                                                                                STRUCT('firebase_screen_id' AS key, STRUCT('app' AS string_value) AS value),
                                                                                STRUCT('item_id' AS key, STRUCT('DEMO-02' AS string_value) AS value),
                                                                                STRUCT('firebase_screen' AS key, STRUCT('My Order' AS string_value) AS value)] AS params)] event_dim
)

SELECT
 event.name,
 (SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="notification_title") as notification_title,
 (SELECT param.value.string_value FROM UNNEST(event.params) AS param WHERE param.key="item_id") as item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_20*`, UNNEST(event_dim) as event
WHERE event.name = "notification_received"

If you UNNEST the field event_dim and call it event, then you should use this alias as reference in your query.
As a complement, here's another way of solving your problem as well (it's just another possibility so you have more techniques in your belt when working with BigQuery):
#standardSQL
SELECT
  (SELECT date FROM UNNEST(event_dim)) date,
  (SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'notification_title') AS notification_title,
  (SELECT params.value.string_value FROM UNNEST(event_dim) event, UNNEST(event.params) params WHERE event.name = 'notification_received' AND params.key = 'item_id') AS item_id
FROM `projectID.com_dev_sambhav_ANDROID.app_events_2017`
WHERE EXISTS(SELECT 1 FROM UNNEST(event_dim) WHERE name = 'notification_received')

When processing up to terabytes you may find this query still perform quite well.


Q: shortcut for creating an javascript object from an array of objects using lodash I often have an array of objects and want to make it into an object of objects by keying on a specific key of the contained objects.
Currently I'm doing something like:
_.zipObject(_.pluck(results, '_id'), results);
However, this is such a common thing I wondered if there's a shortcut to do this using Lodash / underscore.
Anyone?

A: You are looking for  _.indexBy() http://lodash.com/docs#indexBy
Example from the docs:
var keys = [
  { 'dir': 'left', 'code': 97 },
  { 'dir': 'right', 'code': 100 }
];

_.indexBy(keys, 'dir');
// → { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }


Q: Setting the name of cells inside a vba function While inside a VBA function I'm attempting to change the name of certain cells to flag them and use them later. I have a searching function that searches excel docs for keywords from a .txt file and need to know which cells don't include any of the search terms. To do this I was going to name each cell I query and include all unnamed cells in the results column for "Other". But whenever I try to name a cell the name doesn't get updated. I've tried the following:

ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange

and

foundRange.name = "QUERIED"

The function is here:
Function Single_word_occurrences(datatoFind As String, resultsCol As String) As Integer
    'Initializations
    Dim strFirstAddress As String
    Dim foundRange As Range
    Dim currentSheet As Integer, sheetCount As Integer, LastRow As Integer, loopedOnce As Integer, FoundCount As Integer

    FoundCount = 0
    currentSheet = ActiveSheet.Index
    sheetCount = ActiveWorkbook.Sheets.Count

    Sheets("Sheet1").Activate
    Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=Cells(2, 6), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Sheets("List Results").Cells(1, resultsCol).Value = datatoFind
    'if datatoFind is found in search range
    If Not foundRange Is Nothing Then
        'save the address of the first occurrence of datatoFind, in the strFirstAddress variable
        strFirstAddress = foundRange.Address
        Do
            'Find next occurrence of datatoFind
            Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=foundRange.Cells, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
            'Place the value of this occurrence in the next cell down in the column that holds found values (resultsCol column of List Results worksheet)
            LastRow = Sheets("List Results").Range(resultsCol & Rows.Count).End(xlUp).Row + 1
            Sheets("List Results").Range(resultsCol & LastRow).Value = foundRange.Address
            ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange
            If loopedOnce = 1 Then
                FoundCount = FoundCount + 1
            End If
            If loopedOnce = 0 Then
                loopedOnce = 1
            End If
            'The Loop ends on reaching the first occurrence of datatoFind
        Loop While foundRange.Address <> strFirstAddress And Not foundRange Is Nothing
        Msgbox(foundRange.Name)
    End If
    Single_word_occurrences = FoundCount
    Application.ScreenUpdating = True
    Sheets(currentSheet).Activate
End Function

A: You can't Define a Name in a UDF
you must use a sub
the following will fail:
Public Function qwerty(r As Range) As Variant
    qwerty = 1
    Range("B9").Name = "whatever"
End Function


Q: httplib post call error I am trying to automate few http requests where, I have following POST call data which i captured from the web :
Method: POST
Request Header :
POST /cgi-bin/auto_dispatch.cgi HTTP/1.1
Host: 10.226.45.6
Connection: keep-alive
Content-Length: 244
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhwDXAifvLs48E95A
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Referer: http://10.226.45.6/auto_dispatch.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,kn;q=0.6
Cookie: TWIKISID=dce9a6aa10e33b708f5bbc2912f781ab
payload :
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="taskid"
123
------WebKitFormBoundaryhwDXAifvLs48E95A
Content-Disposition: form-data; name="Submit"
Submit Form
------WebKitFormBoundaryhwDXAifvLs48E95A--
MY script is as follows :
  import httplib, urllib
     def printText(txt):
      lines = txt.split('\n')
         for line in lines:
           print line.strip()

     params = urllib.urlencode({'@taskid': 12524, '@Submit': 'Submit Form'})
     headers = {"Content-type": "multipart/form-data", "Accept":       "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
     conn = httplib.HTTPConnection("10.226.45.6", 80)
     conn.request("POST", "auto_dispatch.html", params, headers)
     response = conn.getresponse()
     print response.status, response.reason
     printText (response.read())
     conn.close()

I am getting the following error :
400 Bad Request

400 Bad Request
Bad Request
Your browser sent a request that this server could not understand.
Please help me to form a proper request .

A: I Tried with the curl commands which worked for me :
curl --request POST 'http://10.226.45.6/cgi-bin/auto_dispatch.cgi HTTP/1.1' --data 'taskid=111&submit=submit'
curl --request POST 'http://10.226.45.6/cgi-bin/auto_free.cgi HTTP/1.1' --data 'submit=submit'


Q: Socket connection only when needed I have a web application that needs to refresh some values often because the changes have to be available almost in real time. To do this, I run via ajax a refresh.php routine every 15 seconds, which returns the updated information. Time that increases if there is no user activity.
I thought about the possibility of creating a service-worker in the browser (since I already use it for pwa too), and in it create a web-socket, and then only when there is an update on the server, create a socket for the ip's of the users that are logged in (and saved in a db), just to send to the user's browser that there is an update, then the web-socket triggers the javascript routine that connects to the server and does the update.
I do not know if it would be possible to create the socket just to inform that there is an update, because in this case, I do not want to leave the socket open, creating the connection only when there is an update of the information, which should happen to several users.
Has anyone ever needed or done anything like this, or would you have any other ideas?


Q: Sorting in Linux I have a string "abc" and I am greping it in 15 files in my directory in shell.
When I grep "abc" in my 15 files than it returns me the whole line of the files in which its present like this:
abc 0.2  9.0
abc 0.01 8.0
abc 0.06 9.4
abc 0.02 8.7

Now I want this output to be sorted in ascending order according to the second column.
So I wrote the command like this:
grep "abc" *.txt | sort -nr -t_ -k2

but the above command is not working and I don't know why.

A: Your command is not working because you don't have underscores separating the columns; further, you wanted the data ascending but you told it to sort in reverse (descending) order.  Use:
grep "abc" *.txt | sort -n -k 2

Or:
grep "abc" *.txt | sort -k 2n

Note that if there are multiple files, your grep output will be prefixed with a file name.  You will have to decide whether that matters.  It only screws things up if there are spaces in any of the file names.  The -h option to grep suppresses the file names.

A: I suggest to delete -t_ parameter, because as I see you use spaces as separator, not underscore. After that it works for me:
$ cat t | sort -n -k2
abc 0.01 8.0
abc 0.02 8.7
abc 0.06 9.4
abc 0.2  9.0

Updated: and yes, as @jonathan-leffler said you also should omit -r option for sorting in ascending order.

A: You can replace your entire script, including the call to grep, with one call to awk
awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt

Example
$ ls *.txt
four.txt  one.txt  three.txt  two.txt

$ cat *.txt
abc 0.02 8.3
foo
abc 0.06 9.4
bar
blah blah
abc 0.2  9.0
blah
abc 0.01 8.0
blah
abc 0.02 8.7
blah blah

$ awk '/abc/{a[$2,i++]=$0}END{l=asorti(a,b);for(i=1;i<=l;i++)print a[b[i]]}' *.txt
abc 0.01 8.0
abc 0.02 8.3
abc 0.02 8.7
abc 0.06 9.4
abc 0.2  9.0

A: First problem: you've used -t_ to specify the field separator, but the output doesn't contain _ characters.
Next problem: the -k option has two arguments, start field and end field. By omitting the end field, you get end_of_line by default.
I'd suggest writing it like this:
grep "abc" *.txt | sort -nr -k2,2


Q: How to eliminate elements of a vector according to a pattern I have this vector:
a <- c("es1", "es2", "es3", "is1", "is2", "is3")

and i would like to eliminate all elements staring with "es", so it ends up looking like this:
b <- c("is1", "is2", "is3")

Thanks everyone!

A: If you want to remove all words that contain "es", try
b <- a[-grep("es", a)]

If you want to remove only the words that starts with "es", try
b <- a[-grep("\\bes\\w+", a)]


Q: Toast in not showing in asynctask I am trying to get message from the server to show in toast but it does not appear. The client receives the message from the server without any errors.I have tried opening UI thread in onpost but it didn't work
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    new test().execute();

}
public class test extends AsyncTask<String,String,String>{

    @Override
    protected String doInBackground(String... params) {

        try
        {
            socket = new Socket("ip", port);
            OutputStream outToServer = socket.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);
            Log.i(debugString, "Connected_reg!");
            out.writeUTF("3");

            InputStream inFromServer = socket.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            Log.i(debugString, in.readUTF());
            string= in.readUTF();

        }
        catch (Exception e) {
            Log.e(debugString, e.getMessage());
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {

       //super.onPostExecute(s);

                Context context = getApplicationContext();
                CharSequence text = string;
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
    }

}

A: It might be to do with the context.
I've had issues in the past with getApplicationContext not working for certain things, although can't remember what form the top of my head.
Instead of using getApplicationContext, in the activity where you call your async task put this in the constructor call. For example, assuming you are going from MainActivity change the line new test().execute(); to new test(MainActivity.this).execute();
Then in the async class create the constructor as
public test(Context context) and set a global class variable to be the value of context, and then use this in your toast.makeText instead of what is returned from getApplicationContext.
Also take a look in the logcat, see if there are any errors or exceptions being thrown, it might also be worth adding a log line in the onpostexecute method just to double check you're definetely going in there.

A: Create a constructor in the test class which receive a context and use that context in the Toast.makeText. Pass the host activity context to that constructor.
getApplicationContext() is a Context class method, AsyncTask does not inherent from that class. I suppose you are in a scope where you can invoke that method but that scope context is not valid in the scope that you are invoking the Toast.makeText method.