text:
Q: UIImageJPEGRepresentation creates a white bottom bar I am using UIImageJPEGRepresentation after I capture an image with AVCaptureSession and AVCaptureStillImageOutput. For some reason when I compress my images with UIImageJPEGRepresentation the image has a thin white line at the bottom of the picture. Does anybody know how to fix this?

A: The problem was actually that I was resizing my image, but in doing so the proportions didn't line up so there is an empty pixel row on the bottom that defaults to white because the file is a jpeg. See the link below
A thin whiteline is been added when resize the image

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I tell what software and updates must be checked or unchecked? Is there a comprehensive list detailing the software and updates somewhere?
I obviously want my pc as secure as possible but also want everything running smoothly.
In Ubuntu software - everything being checked seems ok? Is that right?
In other software there are 2 unchecked boxes for canonical partners, should they be checked?
In updates everything is checked, is this OK?
I use vlc, web browser, etc that I want to keep updated...Is this the right place I should be looking/checking/unchecking?
Does every download I do add to these lists automatically? I'v just noticed a whole lot of unknown new lists on another pc that are not the same as on this pc and many(that were added) are unchecked?
Where is the best place to read up more on this information to make heads or tails from it?


text:
Q: How to restrict the index sort for an array in Z3? I'm trying to represent an array of 9 characters as an array in Z3 to enumerate all combinations of those characters that will satisfy certain constraints (which have been generated by KLEE).
The expressions that are generated are as below:
(set-logic QF_AUFBV)
(declare-fun ascii_buf () (Array (_ BitVec 32) (_ BitVec 8) ) )

(assert
    (let (
        (?B1 ((_ sign_extend 24)  (select  ascii_buf (_ bv8 32) ) ) )
        (?B2 ((_ sign_extend 24)  (select  ascii_buf (_ bv6 32) ) ) )
        (?B3 ((_ sign_extend 24)  (select  ascii_buf (_ bv7 32) ) ) )
        (?B4 ((_ sign_extend 24)  (select  ascii_buf (_ bv1 32) ) ) )
        (?B5 ((_ sign_extend 24)  (select  ascii_buf (_ bv2 32) ) ) )
        (?B6 ((_ sign_extend 24)  (select  ascii_buf (_ bv0 32) ) ) )
        (?B7 ((_ sign_extend 24)  (select  ascii_buf (_ bv5 32) ) ) )
        (?B8 ((_ sign_extend 24)  (select  ascii_buf (_ bv3 32) ) ) )
        (?B9 ((_ sign_extend 24)  (select  ascii_buf (_ bv4 32) ) ) ))

        (let (
            (?B11 (bvadd  (_ bv4294967248 32) ?B5 ) )
            (?B10 (bvadd  (_ bv4294967248 32) ?B4 ) ) )

            (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and

                (=  false (bvslt  ?B6 (_ bv48 32) ) )   # ASCII number constraints ("0" = 48, "9" = 57)
                (=  false (bvslt  (_ bv57 32) ?B6 ) ) )
                (=  false (bvslt  ?B4 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B4 ) ) )
                (=  false (bvslt  ?B5 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B5 ) ) )
                (=  false (bvslt  ?B8 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B8 ) ) )
                (=  false (bvslt  ?B9 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B9 ) ) )
                (=  false (bvslt  ?B7 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B7 ) ) )
                (=  false (bvslt  ?B2 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B2 ) ) )
                (=  false (bvslt  ?B3 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B3 ) ) )
                (=  false (bvslt  ?B1 (_ bv48 32) ) ) )
                (=  false (bvslt  (_ bv57 32) ?B1 ) ) )

                (bvslt  ?B10 (_ bv9 32) ) )             # other constraints (autogenerated)
                (=  false (bvslt  ?B11 ?B10 ) ) )
                (bvslt  (bvadd  (_ bv4294967248 32) ?B8 ) (_ bv9 32) ) )
                (=  false (bvslt  (bvadd  (_ bv4294967200 32) (bvadd  ?B4 ?B8 ) ) (bvadd  (_ bv4294967248 32) ?B6 ) ) ) )
                (=  false (bvslt  (bvadd  (_ bv4294967248 32) ?B9 ) (_ bv9 32) ) ) )
                (bvslt  (bvadd  (_ bv4294967248 32) ?B7 ) (_ bv9 32) ) )
                (=  false (bvslt  (bvadd  (_ bv4294967200 32) (bvadd  ?B4 ?B7 ) ) ?B11 ) ) )
                (=  false (bvslt  ?B11 (_ bv9 32) ) )

            ) # outer and

        ) # end inner let

    ) # end outer let

) # end assert

When I try to enumerate different solutions using the method described here, I start to get unexpected models like this (the first 2 are as expected with constrained indexes < 9):
[ascii_buf = Lambda(k!0,
                    If(k!0 == 3,
                       56,
                       If(k!0 == 0,
                          51,
                          If(k!0 == 4,
                             57,
                             If(k!0 == 1,
                                56,
                                If(k!0 == 5,
                                   56,
                                   If(k!0 == 2, 57, 50)))))))]
[ascii_buf = Lambda(k!0,
                    If(k!0 == 3,
                       56,
                       If(k!0 == 4,
                          57,
                          If(k!0 == 1,
                             56,
                             If(k!0 == 5,
                                56,
                                If(k!0 == 2, 57, 50))))))]
[ascii_buf = Lambda(k!0,
                    If(k!0 == 3,
                       56,
                       If(k!0 == 1073741824,
                          48,
                          If(k!0 == 4,
                             57,
                             If(k!0 == 1,
                                56,
                                If(k!0 == 5,
                                   56,
                                   If(k!0 == 2, 57, 50)))))))]
[ascii_buf = Lambda(k!0,
                    If(k!0 == 3,
                       56,
                       If(k!0 == 1073741824,
                          48,
                          If(k!0 == 4,
                             57,
                             If(k!0 == 1,
                                56,
                                If(k!0 == 5,
                                   56,
                                   If(k!0 == 32768,
                                      51,
                                      If(k!0 == 2, 57, 50))))))))]

I'm not too familiar with Z3 but my guess would be if I could restrict the array's index sort (instead of it being from a 32-bit bitvector), this might fix the issue. But any/all suggestions would be appreciated!


text:
Q: Is it possible to access the variables in __init__.py from the modules in the same package? I have a hello1 package that contains good.py module.
hello1
├── __init__.py
└── good.py

The init module has a variable A = 1, and I need to access the variable hello1.A in good.py.
import hello1

class Good(object):
    def __init__(self):
        print hello1.A

if __name__ == "__main__":
    g = Good()

The issue is that when I execute the python script I got ImportError: 'No module named hello1' error. I could add import sys; sys.path.append("..") at the first line of good.py for a quick fix.
However, the good.py is in hello1 package where the __init__.py is also in, so I wonder if there is a way to access the variables in __init__.py from the modules in the same package.

A: From Python: import the containing package:
Importing __init__ seems to work fine.
import __init__

class Good(object):
    def __init__(self):
        print hello1.A

A: If you don't like sys.path.append(...) you could run your script as
python -m hello1.good

in the directory containing the "hello1"-directory or use the PYTHONPATH environment variable instead of sys.path.

A: If I'm not mistaken you want to do something like:
python hello1/good.py

Since good.py is a submodule of a package you shouldn,'t run it directly; keep in mind that when directly executing it, then it isn't considered as part of the hello1 package, which prevents relative imports and the current directory is the one that contains the file, hence hello1 cannot be found if it isn't part of the PYTHONPATH. Instead you can run it using the -m switch of the python interpreter:

-m mod : run library module as a script (terminates option list)

I personally don't like using the interpreter options to execute a python file. I'd rather have an independent launcher file good.py that imports the hello1.good module and uses it to do what it has to do.

A: You have to explicit import the constants you want to use.
It's preferable to have all your constants in a "config" file (i.e. config.py) ) and then if you want them in the package namespace, import them.
init.py file:
from package.config import *

it's more clear that way

A: import __init__

...leads to: No module named 'init'


text:
Q: No module named pytube found So I've already seen that I need to do something like pip install pytube and ive already done that but when I run my code, I see a "no module named "Pytube" found" error. When I use pip install pytube in my terminal, it says that the installation was complete, but I still am getting the error. Idk if this is a dumb mistake or something deeper but any help would be appreciated.

A: probably would be easy if you show the code, but maybe you are writing "Pytube" instead of "pytube", or maybe you are executing your code in the wrong environment.


text:
Q: Faixa preta por cima da imagem
Boa Noite, como faço para fazer essa tarja preta por cima de uma imagem com bootstrap e css, se alguem puder me ajudar agradeço.

A: Fiz um exemplo no JSFiddle. Basta usar rgba para o background, ou pode usar uma imagem de 1 pixel com transparência (png), se repetindo no  background via css.


text:
Q: Find the order of the point I want to calculate the order of the point $M$ at the curve $f(x,y) \in \mathbb{R}[x,y]$, when:
$$M(0,1), f=(x^2-1)^2-y^2(3-2y)$$
That's what I have tried:
$$f(x,y)=x^4-2x^2+1-3y^2+2y^3$$
$$f_4(x,y)=x^4$$
$$f_3(x,y)=2y^3$$
$$f_2(x,y)=-2x^2-3y^2$$
$$f_0(x,y)=1$$
We check if $M$ is singular.
$$f(0,1)=0$$
$$f_x(x,y)=4x^3-4x$$
$$f_x(0,1)=0$$
$$f_y(x,y)=-6y+6y^2$$
$$f_y(0,1)=0$$
Taylor expansion of $f(x,y)$ at the point $M(0,1)$
$$f(x,y)=f(0,1)+[f_x(0,1)(x-0)+f_y(0,1)(y-1)]+ \dots$$
$$f(x,y)=-2x^2+3(y-1)^2+2(y-1)^3+x^4$$
So, the order of $M$ is $2$.
Could you tell me if it is right or if I have done something wrong?

A: I think you did right. You could use other methods also: use the linear change of co-ordinates so that the point $(0, 1)$ becomes the point $(0, 0)$. Then write $f(x, y)$ as $f = f_0 + f_1 + \cdots,$ where $f_d$ is a homogeneous polynomial of degree $d$ in $x$ and $y$. Then the order of the point $(0, 1)$ will be the least $r$ such that $f_r\neq 0.$(R. Hartshorne, Algebraic Geometry, Chapter I, Ex. 5.3)
In this case, use the co-ordinate transformation: $X = x, Y = y-1.$ Then the resulting polynomial will be $f(X, Y) = X^4 + 2Y^3 + - 2X^2 + 3Y^2$ (this is the one you got at the end). So the order of $M$ is 2.


text:
Q: Android onPause and onResume Method Am trying to implementent onPause() and onResume(), such that when am out of the activity the the text in my text view is still there, but its displaying "null" when i start the the activity please assist!
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        etPassenger.setText(""+ gotPassenger );
        etStaffNumber.setText("" + gotStaffNumber);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        etPassenger.setText(""+ gotPassenger );
        etStaffNumber.setText("" + gotStaffNumber);
    }

A: I think gotPassenger and gotStaffNumber vars are null - if you want to save them than you have to use prefs or save them to some bundle to restore later.

A: When you are minimizing your activity your variables becoming null.
Add the following code in your activity,
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putString("gotPassenger",gotPassenger);
savedInstanceState.putString("gotStaffNumber",gotStaffNumber);
}

And, in your onCreate() method, add the following,
if(savedInstanceState!=null)
{
etPassenger.setText(savedInstanceState.getString("gotPassenger"));
etStaffNumber.setText(savedInstanceState.getString("gotStaffNumber"));
}

A: When you are leaving your activity, you will loose the data stored inside gotPassenger and gotStaffNumber.
If you want to reuse them after exiting your application, you have to use SharedPreferences to save them first and retrieve them when you are back.

A: If you want to save your data even when closing your app you need to use sharedPreferences. Here's how you use them


text:
Q: Showing a subset is a subgroup Let $A$ be a subset of a finite group $G$. For any $g\in G$ we denote by $gA$ the set $\{ga : a ∈ A\}$. Assume that $e \in A$, where $e$ is the identity element of $G$, and that for any $g_1, g_2 \in G$ the sets $g_1A$ and $g_2A$ are either equal or disjoint. Show that $A$ is a subgroup of $G$.
My attempt
Use subspace test. Firstly, we already know that $e$ is in $A.$
Suppose $g_1A=g_2A$ then there exists some $a_1,a\in A$ such that $g_1*a_1=g_2*a_2$ then $g_1*e=g_1=g_2*a_2*a_1^{-1}\in gA$ which implies that $a_2*a_1^{-1}$ is an element in set A and so A is a subgroup by subgroup test.
My problem
How should I approach the disjoint part? I thought about using equivalence relations since this is essentially a partition but I am not entirely sure how to continue.
Thanks very much in advance.

A: As $G$ is finite, you might proceed by showing taht $A$ is not empty and $A$ is closed under multiplication.
$A\ne\emptyset$ follows from $e\in A$.
For closure, let $a,b\in A$. As $a=ae\in aA$, we see that $aA$ and $A=eA$ are not disjoint, hence are equal. In particular, $ab\in aA=A$.


text:
Q: where is mongo db database stored on local hard drive? I'm scraping tweets and inserting them into a mongo database for analysis work in python. I want to check the size of my database so that I won't incur additional charges if I run this on amazon. How can I tell how big my current mongo database is on osx? And will a free tier cover me?

A: I believe on OSX the default location would be /data/db.  But you can check your config file for the dbpath value to verify.

A: For posterity:
Run the mongo shell: mongo
In the shell run: db.adminCommand("getCmdLineOpts")
This will give the location of the relative files, including the db path. Here are the results from two machines I have running mongo.
"parsed": {
    "config": "/usr/local/etc/mongod.conf",
    "dbpath": "/usr/local/var/mongodb",
    "logappend": "true",
    "logpath": "/usr/local/var/log/mongodb/mongo.log"
    },

"parsed" : {
    "config" : "/etc/mongodb.conf",
    "dbpath" : "/var/lib/mongodb",
    "logappend" : "true",
    "logpath" : "/var/log/mongodb/mongodb.log",
},

A: Databases are, by default, stored in /data/db (some environments override this and use /var/lib/mongodb, however). You can see the total db size by looking at db.stats() (specifically fileSize) in the MongoDB shell.

A: > use database
switched to db database
> db.stats()
{
"db" : "database",
"collections" : 4,
"objects" : 32,
"avgObjSize" : 173.25,
"dataSize" : 5544,
"storageSize" : 24576,
"numExtents" : 4,
"indexes" : 3,
"indexSize" : 24528,
"fileSize" : 201326592,
"nsSizeMB" : 16,
"ok" : 1
}

dataSize - the size that your data consumes
fileSize - the mongo db file containing all of the collections
indexSize - is the size of any indexes you have created on that collection
nsSizeMB - a limit on how big your collection can be (this is not a mongo limitation, it is just there to stop developers bombarding collections in infinite loops)

A: if you are running node.js in windows, make sure to install the windows mongodb setup.  it does not come with node.js.
http://www.mongodb.org/


text:
Q: How can I mock the indexing operator with dart mockito? I am writing a unit test in which I need to mock a JsObject so that I don't need to do actual javascript interop in my test.  However, I'm using the indexing operator [] to access a field in my JsObject. I am using the dart mockito library https://github.com/fibulwinter/dart-mockito for mocking and I can't seem to find how I go about mocking the behavior of operators on the mocked object.

A: Mockito makes stubbing very easy, stubbing the index operator works like stubbing any other method. Imaging that you want to stub the index operator of the following class:
class IndexTest {
  operator[] (String value);
}

In the first step we create a mock for that class:
class MockIndexTest extends Mock implements IndexTest {
  noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

Now in you test you can set the return values that you expect for invocations using the index operator:
  test('Test', () {
    final t = new MockIndexTest();

    // Set return values
    when(t[any]).thenReturn(0); // 1
    when(t['one']).thenReturn(1); // 2
    when(t['two']).thenReturn(2); // 3

    // Check return values
    expect(t['one'], equals(1));
    expect(t['two'], equals(2));
    expect(t['something else'], equals(0));
  });

Without stubbing a call always returns null. With the any value provided by mockito you can set the default return value for calls with any argument (see 1). You can also set the return value for a specific set of parameters (see 2 and 3). You have to set the default value before setting the specific ones.


text:
Q: Getting this error while rendering the page I do not understand this error.
Is this a syntax error?
Is this happening because of the react-dom version?
Throwing error on this block.
getWitnessName = (witnessId) => {
    if (this.props.witnesses) {
        return this.props.witnesses.find(el => el.account_id === witnessId).account_name;
    }
}

Error is :
Uncaught TypeError: Cannot read property 'account_name' of undefined
at BlockList.__getWitnessName__REACT_HOT_LOADER__ (BlockList.js:212)
at BlockList._this.getWitnessName (BlockList.js:76)
at eval (BlockList.js:321)
at Array.map (<anonymous>)
at BlockList.render (BlockList.js:314)
at finishClassComponent (react-dom.development.js:17160)
at updateClassComponent (react-dom.development.js:17110)
at beginWork (react-dom.development.js:18620)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)

The above error occurred in the <BlockList> component:
in BlockList (created by Connect(BlockList))
in Connect(BlockList) (created by Route)
in Route
in Switch
in div
in Router (created by ConnectedRouter)
in ConnectedRouter
in Provider
in AppContainer

A: You can use Optional chaining
Add a nullish coalescing operator to complete the picture instead of the normal || which will not react to falsy values
return this.props.witnesses.find(el => el.account_id === witnessId)?.account_name ?? "N/A";
It will handle missing witness and missing account_name
Example

const props = {
  witnesses: [
  { account_id: 1, account_name: "Fred"},
  { account_id: 2, account_name: "Joe" },
  { account_id: 3 }]
};

const getName = witnessId => props.witnesses
   .find(el => el.account_id === witnessId)?.account_name ?? "N/A";

console.log(getName(1))
console.log(getName(2))
console.log(getName(3))
console.log(getName(4))

A: if you see the below code the witness var can be undefined if it doesn't find any account_id matching the given witnessId. In that case, the error is being thrown so do this
getWitnessName = (witnessId) => {
    if (this.props.witnesses) {
        const witness = this.props.witnesses.find(el => el.account_id === witnessId)
        return witness ? witness.account_name : `No witness for given id: ${witnessId}`;
    }
}

A: getWitnessName = (witnessId) => {
    if (this.props.witnesses) {
        let foundWitnesses = this.props.witnesses.find(el => el.account_id === witnessId);
        if(foundWitnesses)
             return foundWitnesses.account_name;
        else
             return 'Not found';
    }
}

A: Try to validate first at to get the property, That's happening cause it's not finding any with that validation input.  Then find returns undefined, and you can't obtain property from undefined.
For example
this.props.witnesses.find(el => el.account_id === witnessId)?.account_name ?? 'Account Not Found';


text:
Q: Scala advantages after Java having closures With closures being added to Java, what is Scala's advantage over Java as a language choice?
Can someone elaborate on any advantages?

A: Even if Java 7 [8,..] will have first-class functions one day, it still lacks for implicits, type inference, powerful Collections library, pattern matching, traits and lots of other things boosting productivity. Not talking about various Actor libraries, rich capabilities of building DSLs,...

A: Apart from closures (which Java doesn't appear all that close to having), here's a list of features in Scala that are missing from Java. I'll omit libraries here and concentrate on the features of the language itself. This is not comprehensive by any means, but I think it contains the big ticket items.

*

*Implicit parameters / conversions

*Pattern matching, case classes

*Type inferencing (some)

*Higher-kinded types (abstraction over type constructors)

*Monadic for comprehensions

*Variance annotations

*Interfaces with behavior (traits)

*Default and named arguments

*Unified methods and operators (methods can be used as infix operators, operators can be overloaded because they're just methods)

*Unified type hierarchy; no primitive types

*Properties rather than getters and setters

*Abstract values

*First-class immutable references (vals are as easy to declare as vars)

*By-name (lazy) terms (maybe Java closures would make this reasonably easy to express)

*Some tail-call recursion optimization

*Abstract types

*Type aliasing

*Self types

*Path-dependent types

*Structural types

*Type ascription, as distinguished from type casting

*Renaming imports

*First-class modules (objects)

*First-class packages

*Reified generics (manifests)

*Delimited continuations
Some cool secondary constructs that these building blocks enable:

*

*Type classes (via implicit parameters and higher-kinded types)

*The "Pimp My Library" pattern (via implicit conversions)

*Internal DSLs (via operator overloading and infix methods)

*Parser combinators (enabled by higher-order functions and made pretty by infix methods)

*Generators, coroutines, custom control structures (via delimited continuations)

*Type-level programming (via higher-kinded and abstract types)

*Obsolescence of dependency injection frameworks (via the Cake Pattern)

Lastly, I'll mention that Scala has a REPL (read-evaluate-print-loop)--not really a feature of the language itself, but it's very nice to have!

A: The latest I've heard is that closures won't make it into Java 7.
http://www.baptiste-wicht.com/2010/09/jdk-7-features-updated-plan-b-is-apparently-here/
http://openjdk.java.net/projects/jdk7/features/
The second link clearly lists project Lambda (closures) as deferred to JDK 8.


text:
Q: "Merged" dependency and constituency tree I am working on a research in which I use the CoreNlp in order to parse sentences, using the various available annotators (mainly, constituency and sentiment).
I am now trying to create a "merged" trees which include both constituency and dependency information from which I am going to extract grammar (can think about PCFG).
I am trying to get to something like the left trees in the image:

(image from Relational-Realizational Parsing (Tsarfaty and Sima'an, 2008))
Is there some "easy" way to work with the provided parser outputs (in code that is) to get to something like that?
Alternatively, is there any implementation you may know of based on the Stanford NLP library?
Would GrammaticalStructure be helpful here? Does making a GS for each node and reading it's typedDependencies() at each constituency node make sense here?

A: Here is a sketch of some code for working with the constituency and dependency parses.
Properties props = new Properties();
props.setProperty("annotators","tokenize, ssplit, pos, lemma, parse");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
String sampleDoc = "This is the first sentence.  This is the second one.";
Annotation annotation = new Annotation(sampleDoc);
pipeline.annotate(annotation);
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
  Tree tree = sentence.get(TreeCoreAnnotations.TreeAnnotation.class);
  SemanticGraph deps = sentence.get(SemanticGraphCoreAnnotations.BasicDependenciesAnnotation.class);
}

For your project you're going to need to study these two classes:
http://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/trees/Tree.html
http://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/semgraph/SemanticGraph.html
The Tree class represents the constituency parse and the SemanticGraph class represents the dependency parse.

A: Created a "snippet" (quite a lengthy one) for the code required to create a merged constituency and dependency tree which goes along the lines suggested above - traversing both trees.
Merge Constituency and Dependency
The process in high level:

*

*Get the constituency tree using parser/pipeline

*Get grammatical structure of the tree and from it, typed dependencies (note - keeping punctuation)

*Convert the typed dependencies into a dependency tree

*Merge the dependency and constituency trees based on the matching node coverage spans.
The code (classes):

*

*DependencySpan - represents a span and the nodes covering it (used for matching spans)

*DependencyTreeNode - a node in dependency tree which holds reference to a core label (which in turn, has a related word index used for getting a span)

*MergedNode - a merged constituency + dependency node.

*MergeConstituencyAndDependency - actual code to merge trees - works along the lines of algorithm above. Include the main (entry point for testing).
One thing I am not 100% sure of is why the "sentiment" annotator is required - without it creating the grammatical structure throws an error.
A disclaimer - I am not proficient with the Stanford NLP library and all it's options. The code is loosely based on other examples I've found online and there could be better ways of doing this task.


text:
Q: AngularJS: Chaining $timeouts and Promises I am struggling with chaining promises using $timeouts. I would like to have a "$timeout(myFunction,1000).then()" function that fires only when ALL chained timeouts returned by myFunction are resolved.
This code snippet contains different stuff I tried and I would like to achieve:
$timeout(myFunction,1000).then(function(myPromise) {
    console.log("I would like this message to appear when ALL chained promises are resolved, without knowing in advance how many chained promises there are. In this case this would be after 1500 ms, not 1000ms")
    myPromise.then(function()) {
        console.log("with this code patern I get a message after 1500ms, which is what I want, but this does not work anymore if myOtherFunction would return a third chained $timeout")
    }
})

myFunction = function() {
    console.log("hi, i am launching another timeout")
    return $timeout(myOtherFunction, 500)
}

myOtherFunction = function () {
    console.log("1500 ms have passed")
}

How should I fix my code? Thanks!

A: Return promises to the success handler:
$timeout(null,1000).then(function() {
    console.log("It is 1000ms");
    var delay = 500
    return myPromise(delay);
 // ^^^^^^ return promise for chaining
}).then(function() {
    console.log("this happens after myPromise resolves");
});

function myPromise(delay) {
    promise = $timeout(null, delay);
    return promise;
});

Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.
-- AngularJS $q Service API Reference -- Chaining promises;

A: Inspired by the answer of georgeawg I created my custom timeout function that returns the promise returned by fct, instead of the promise returned by $timeout. I did this to keep the $timeout syntax.
vm.customTimeout = function (fct, timeout){
    return $timeout(fct, timeout).then(function(myReturnedPromise){
        return myReturnedPromise
    });
}

This function is sufficient to solve my problem above. I can chain as much customTimeouts I want.
Example :
vm.customTimeout(myFunction,1000).then(function() {
    var activity1 = anyFunctionReturningAPromise(100);
    var activity2 = anyFunctionReturningAPromise(1000);
    return $q.all([activity1, activity2])
    console.log("Without knowing the content of myFunction, I am 100% sure that
        every single chained promise retuned by myFunction is resolved before
        executing this code, which is quite nice!")
}).then(function(){
    console.log("executes when customTimeout, activity1 & activity2 are all resolved.")
})

anyFunctionReturningAPromise = function(delay) {
    return vm.customTimeout(myFunction, delay)
}

Feel free to comment what you think of it.
I hope this will be useful for someone else :)


text: Q: Is there a way to output the current line being executed in Python? I'm making software in python which shows how variables change within a given piece of code. I therefore want it to display at what line in the code the changes happen. How could I go about doing it?


text:
Q: Setting approvers on SPWorkflowAssociation using AssociationData I'm trying to programmatically configure the out of the box Approval workflow on a document library using the following code:
SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName(workflowName,
    System.Globalization.CultureInfo.CurrentCulture);
SPWorkflowAssociation workflowAssociation =
    SPWorkflowAssociation.CreateListAssociation(workflowTemplate, workflowAssocName, workflowWorkList, workflowLogList);

workflowAssociation.AllowAsyncManualStart = false;
workflowAssociation.AllowManual = false;
var associationDataXml = XElement.Parse(workflowAssociation.AssociationData);
workflowAssociation.AssociationData = GetAssociationData(web, associationDataXml);

documentLibrary.WorkflowAssociations.Add(workflowAssociation);
workflowAssociation.Enabled = true;

documentLibrary.DefaultContentApprovalWorkflowId = workflowAssociation.Id;
documentLibrary.Update();

I believe that the GetAssociationData() method returns the correct XML. I have compared the output from the function with the XML set by configuring the workflow manually (using powershell/sharepoint manager). The XML generated GetAssociationData() is actually saved in AssociationData and I can access it after the code have run, there are no exceptions thrown in the code above.
Example of XML:
<!-- generated xml, comment added manually -->
<dfs:myFields xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <dfs:queryFields></dfs:queryFields>
    <dfs:dataFields>
        <d:SharePointListItem_RW>
            <d:Approvers>
                <d:Assignment>
                    <d:Assignee>
                        <pc:Person>
                            <pc:DisplayName>SP-GROUP</pc:DisplayName>
                            <pc:AccountId>SP-GROUP</pc:AccountId>
                            <pc:AccountType>SharePointGroup</pc:AccountType>
                        </pc:Person>
                    </d:Assignee>
                    <d:Stage xsi:nil="true" />
                    <d:AssignmentType>Serial</d:AssignmentType>
                </d:Assignment>
            </d:Approvers>
            <d:ExpandGroups>true</d:ExpandGroups>
            <d:NotificationMessage />
            <d:DueDateforAllTasks xsi:nil="true" />
            <d:DurationforSerialTasks xsi:nil="true" />
            <d:DurationUnits>Day</d:DurationUnits>
            <d:CC />
            <d:CancelonRejection>true</d:CancelonRejection>
            <d:CancelonChange>true</d:CancelonChange>
            <d:EnableContentApproval>true</d:EnableContentApproval>
            <d:ApproveWhenComplete>true</d:ApproveWhenComplete>

        </d:SharePointListItem_RW>
    </dfs:dataFields>
</dfs:myFields>

My problem is that SP-GROUP does not show up in the gui when starting the workflow. Any ideas? Do I have to update the workflow in some way after altering AssociationData? The groups I'm using exists and are working.
Image summary:

A: You need to update the workflow:
// Update Workflow Association Data
wfAssociation.AssociationData = data;
wfAssociation.Enabled = true;

// Update Workflow Association
documentLibrary.WorkflowAssociations.Update(wfAssociation);

I wrote a blogpost about this topic  with a possible solution, maybe it could be handy:
http://hevling.be/blog/change-properties-of-a-sharepoint-workflow-instance/


text:
Q: Glow buttons with a delay in between I'm trying to light up a sequence of buttons in order with a small delay in between but I just can't figure out how to glow each button separately with a small delay in between without freezing all code.
at this point I got this, which waits a second and for some reason lights up both buttons at the same time after.
The array given to the method contains values from 1-3 referencing one of the 3 buttons in order
private func showSequence(sequence: Array<Int>){

        for i in  sequence {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.buttonArray[i-1].doGlowAnimation(withColor: .white, withEffect: .big)
            }
        }
}

And the glow effect I found online, code:
extension UIView {
    enum GlowEffect: Float {
        case small = 0.4, normal = 2, big = 15
    }

    func doGlowAnimation(withColor color: UIColor, withEffect effect: GlowEffect = .normal) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowRadius = 0
        layer.shadowOpacity = 1
        layer.shadowOffset = .zero

        let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
        glowAnimation.fromValue = 0
        glowAnimation.toValue = effect.rawValue
        glowAnimation.beginTime = CACurrentMediaTime()+0.3
        glowAnimation.duration = CFTimeInterval(0.3)
        glowAnimation.fillMode = .removed
        glowAnimation.autoreverses = true
        glowAnimation.isRemovedOnCompletion = true
        layer.add(glowAnimation, forKey: "shadowGlowingAnimation")

    }
}


text:
Q: Cylinder with non circle bottom, TikZ Hi i try to plot a cylindrical domain, where the bottom of the cylinder is not a circle or ellipse.
My knowledge is very poor and all my previous attempts failed.
Failed attempt:
\documentclass{article}
\usepackage{tikz}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\begin{document}
\begin{tikzpicture}

\draw plot [smooth cycle] coordinates{(0,0) (1,-.5) (1.2,1.5) (0,1) (-.5,.5) (-.7,.2)};

\draw plot [smooth cycle] coordinates{(3,2) (4,1.5) (4.2,3.5) (3,3) (2.5,2.5) (2.3,2.2)};

\draw (1,-.5)--(4,1.5);

\draw (1.2,1.5)--(4.2,3.5);

\end{tikzpicture}
\end{document}

A: It looks like you could use pgfplots for this, e.g.:
Code
\documentclass[tikz,border=2mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}

\begin{document}

\begin{tikzpicture}
    \begin{axis}
    [ z buffer=sort,
    ]
        \addplot3[domain=0:360,y domain=0:360,surf,shader=faceted,samples=40]
        ( {cos(y)+0.1*sin(7*y)},
            {x},
            {sin(y)+0.1*cos(3*y)}
        );
    \end{axis}
\end{tikzpicture}

\end{document}

Output

A: A function for the base is also possible.
\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pst-solides3d}
\begin{document}

\psset{viewpoint=50 -20 40 rtp2xyz, Decran=50,linearc=0.2}
\begin{pspicture}(-1,-1)(4,4)
\psSolid[object=prisme,axe=0 0.5 1,
base= 0 0 1 -.5 1.2 1.5 0 1 -.5 .5 -.7 .2 ,
linecolor=red,h=4,action=draw*]
\end{pspicture}

\begin{pspicture}(-1,-1)(4,4)
\psSolid[object=prisme,axe=0 0.5 1,
base= 0 0 1 -.5 1.2 1.5 0 1 -.5 .5 -.7 .2 ,
hollow,fillcolor=red!30,incolor=blue!30,
linecolor=red,h=4,action=draw**]%
\end{pspicture}

\end{document}

A:
There are many ways to visualize such a cylinder in TeX world, here is one made by means of
extrude feature of the Asymptote using raster output.
% cyl.tex :
%
\documentclass{article}
\usepackage[inline]{asymptote}
\usepackage{lmodern}
\begin{document}
\begin{figure}
\begin{asy}
settings.outformat="png";
settings.tex="pdflatex";
settings.render=8;
size(5cm);
import graph3;
import fontsize;
defaultpen(fontsize(9pt));

currentprojection=orthographic(camera=(3,3,6),up=Z,target=O,zoom=1);

currentlight=light(gray(0.8),ambient=rgb(0.1,0.099,0.101),specular=gray(0.7),
                     specularfactor=3,viewport=true,dir(42,48));

pair[] ppair={(0,0),(1,-.5),(1.2,1.5),(0,1),(-.5,.5),(-.7,.2)};
real height=3;

guide gbase=graph(ppair, Spline)..cycle;

pen bpen=rgb(0.1, 0.1, 0.8)+opacity(0.5);
material m=material(diffusepen=0.7bpen
,ambientpen=bpen,emissivepen=0.3*bpen,specularpen=0.999white,shininess=1.0);

draw(rotate(-90,Y)*rotate(180,Z)*extrude(gbase,height*Z),m,render(merge=true));

xaxis3("$x$",-3.2,1.2,red  ,Arrow3);
yaxis3("$y$",  -2,2,green,Arrow3);
zaxis3("$z$",  -3,3,blue ,Arrow3);

\end{asy}
\end{figure}
\end{document}
%
% Process:
%
% pdflatex cyl.tex
% asy cyl-*.asy
% pdflatex cyl.tex


text:
Q: testcase is getting failed in chrome Hi I am trying to run a test case in chrome browser and that test case is getting passed in firefox but it is getting failed in chrome browser
.this is the selenium code
_driver.findElement(By.linkText("Expence_Link")).click();;
_driver.findElement(By.id("searchButton")).click();
_driver.findElement(By.id("descriptionInput")).sendKeys("Description");
_driver.findElement(By.id("saveAndNextExpenseButton")).click();

and this is the html code
<input id="searchButton" class="formSubmit" type="button" value="Search" tabindex="3">
Expence_Link
<input id="descriptionInput" name="pre.projectBudgetActualExpense.description.value" value="" size="30" style="width:300px" tabindex="4" maxlength="665">
<input id="saveAndNextExpenseButton" class="formSubmit" type="button" onclick="onSaveAndNextExpenseButtonClick(); return false;" value="Save & Next Actual" tabindex="13">

and the error it is showing is
org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=39.0.2171.95)
 (Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64) (WARNING:     The server did not provide any stacktrace information)
Command duration or timeout: 3.02 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions     /no_such_element.html
Build info: version: '2.41.0', revision: '3192d8a', time: '2014-03-27 17:17:32'
System info: host: 'ADMINIB-BHMHBF7', ip: '9.109.111.10', os.name: 'Windows 7',     os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, chrome=       {userDataDir=C:\Users\IBM_AD~1\AppData\Local\Temp\scoped_dir4692_20611},     takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=39.0.2171.95,    platform=XP, browserConnectionEnabled=false, nativeEvents=true,     acceptSslCerts=true, locationContextEnabled=true,     webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true,     cssSelectorsEnabled=true}]
Session ID: 03b44e91e408e56380c5d261b07cc97f
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:193)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:595)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:445)
at org.openqa.selenium.By$ByXPath.findElement(By.java:357)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
at uiactions.Wrappers.SendKeys(Wrappers.java:254)
at test.object.ExpencePage_Object.Description_Fn(ExpencePage_Object.java:43)
at test.function.ExpencePage_Function.Expence_Page_Test(ExpencePage_Function.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

I am unable to the send keys into the textbox with id 'descriptionInput' i tried out with name, xpath, cssSelector but nothing is working. clicking expence link and search button are working fine in chrome
please help me to get out of this issue
thanks in advance

A: Try using Explicit wait like below to wait for the visibility of the field and then send values to it:
//Waiting for 10 seconds for the presence of the description field and then entering text 'Description'
try{
    WebElement input_desc = new WebDriverWait(_driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("descriptionInput")));
    input_desc.clear();
    input_desc.sendKeys("Description");
}catch(Throwable e){
    System.err.println("Description field wasn't found. "+e.getMessage());
}

Or else increase the Implict wait to 10 seconds:
_driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


text:
Q: Error on setting custom ListView Image I want to set a custom ListView with ArrayAdapter. Every ListItem has an ImageView and two TextViews.
The layout of each Item rowlayout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
    android:id="@+id/item_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:adjustViewBounds="true"
    android:maxHeight="80dp"
    android:maxWidth="80dp"
    android:src="@drawable/logo" />

    <TextView
    android:id="@+id/item_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/item_subTitle"
    android:layout_toRightOf="@+id/item_icon"
    android:text="Titel"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/item_subTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/item_icon"
    android:layout_alignLeft="@+id/item_title"
    android:layout_marginBottom="16dp"
    android:text="Untertitel" />

</RelativeLayout>

This is how I set the ListView in my Badges Activity:
public class Badges extends ActionBarActivity{

List<Badge> myBadges = new ArrayList<Badge>();

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

    populateBadgeList();
    populateListView();

}

private void populateBadgeList() {
    myBadges.add(new Badge("Some Text", "Some further Text", R.drawable.badge1));
    //and so on
}

private void populateListView() {
    ArrayAdapter<Badge> adapter = new MyListAdapter();
    ListView list = (ListView) findViewById(R.id.listView);
    list.setAdapter(adapter);
}

private class MyListAdapter extends ArrayAdapter<Badge> {
    public MyListAdapter() {
        super(Badges.this, R.layout.rowlayout, myBadges);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View itemView = convertView;
        if(itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.rowlayout, parent, false);
        }

        Badge currentBadge = myBadges.get(position);

        ImageView itemIcon = (ImageView) findViewById(R.id.item_icon);
        //the error is on the following line:
        itemIcon.setImageResource(currentBadge.getIconID());

        TextView itemTitle = (TextView) findViewById(R.id.item_title);
        itemTitle.setText(currentBadge.getTitle());

        TextView itemSubtitle = (TextView) findViewById(R.id.item_subTitle);
        itemSubtitle.setText(currentBadge.getSubtitle());

        return itemView;
    }
}

Here is the Badge class:
public class Badge {
String title;
String subtitle;
int iconID;

public Badge(String title, String subtitle, int iconID) {
    this.title = title;
    this.subtitle = subtitle;
    this.iconID = iconID;
}

public String getTitle() {
    return title;
}

public String getSubtitle() {
    return subtitle;
}

public int getIconID() {
    return iconID;
}

}
I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

I marked the line at which the error occurs in the code. What could be the reason for this?

A: Instead of using
ImageView itemIcon = (ImageView) findViewById(R.id.item_icon);
TextView itemTitle = (TextView) findViewById(R.id.item_title);
TextView itemSubtitle = (TextView) findViewById(R.id.item_subTitle);

Use
ImageView itemIcon = (ImageView) itemView.findViewById(R.id.item_icon);
TextView itemTitle = (TextView) itemView.findViewById(R.id.item_title);
TextView itemSubtitle = (TextView)itemView.findViewById(R.id.item_subTitle);

A: Replace
ImageView itemIcon = (ImageView) findViewById(R.id.item_icon);

this with
ImageView itemIcon = (ImageView) itemView.findViewById(R.id.item_icon);

and similarly
TextView itemTitle = (TextView) itemView.findViewById(R.id.item_title);
TextView itemSubtitle = (TextView) itemView.findViewById(R.id.item_subTitle);

with
TextView itemTitle = (TextView) findViewById(R.id.item_title);
TextView itemSubtitle = (TextView) findViewById(R.id.item_subTitle);

A: the view you just inflate didn't add to your activity's layout. So with the activity method
ImageView itemIcon = (ImageView) findViewById(R.id.item_icon);
itemIcon.setImageResource(currentBadge.getIconID());

You couldn't find the view with the specific id. Instead, you should use
ImageView itemIcon = (ImageView) itemView.findViewById(R.id.item_icon);
itemIcon.setImageResource(currentBadge.getIconID());

It will work properly. Other views are similar.

A: I think your problem is in this line: ArrayAdapter adapter = new MyListAdapter();
Change to this: MyListAdapter adapter = new MyListAdapter();
Also, put item view in front of findViewById methods (ImageView itemIcon = (ImageView) itemview.findViewById(R.id.item_icon); )
I would actually recommend generalising your adapter class, so that you could pass any resource (row layout) and list to it :) (However, it is not necessary for the app to work.)
So something like this:
private class MyListAdapter extends ArrayAdapter<Badge> {

   int resource;
   public MyListAdapter(Context context, int resource, List<Badge> items) {
       super(context, resource, items);
       this.resource = resource;
   }

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View itemView = convertView;
    if(itemView == null) {
        itemView = getLayoutInflater().inflate(resource, parent, false);
    }

    Badge currentBadge = getItem(position);

    ImageView itemIcon = (ImageView) itemview.findViewById(R.id.item_icon);
    //the error is on the following line:
    itemIcon.setImageResource(currentBadge.getIconID());

    TextView itemTitle = (TextView) itemview.findViewById(R.id.item_title);
    itemTitle.setText(currentBadge.getTitle());

    TextView itemSubtitle = (TextView) itemview.findViewById(R.id.item_subTitle);
    itemSubtitle.setText(currentBadge.getSubtitle());

    return itemView;
   }
}


text:
Q: Elementary schools summation in denominator? after being lazy for a long time and being away from any fraction and equations, I am confused with a seriously ridiculous math problem, and I want to confirm my answer:
the equation is pretty simple as I followed some formula and having something like this:
$\frac{100}{100+2}=?$
is this the right answer?
enter image description here
Or did I just failed in my exam?
By the way, I know its probably the simplest and the dumbest question ever, so if that's what you think forgive me.

A: Simplifying fractions involves only multiplication, not summation. For example, if you have a fraction
$$
\frac{100}{102}
$$
and you need to simplify it, you multiply both the enumerator and denominator with the same number (Why the same number? because their ratio is exactly 1, and multiplying by 1 doesn't change the value of a number). In this case, we can multiply both by $1/2$:
$$
\frac{100}{102} \times \frac{1/2}{1/2} = \frac{(100/2)}{(102/2)} = \frac{50}{51}
$$
This is as far as we can simplify this fraction (Why? Because $50= 2\times 5^2$  and $51= 3\times 17$, and we see that they don't have any common factors).
This is all that you can do to a fraction. Don't cancel summed terms in a fraction.


text:
Q: Definition of short css transition commands? I found the following short definition of CSS transition commands, but I don't know what those stand for:
-webkit-transition: all 0.35s ease-in-out 0s;

What does the all stand for?
Why 0s ?

A: *

*all means that all animatable properties are going to be animated; it's the default, so it can be omitted; of course, you are going to see a transition only for those properties that actually change value between initial and final state;

*0s is the transition delay; can be omitted if it's 0s (there may be
issues in some browsers with writing just 0 instead of 0s)

So that code is actually equivalent to:
transition: .35s ease-in-out;

Also, the line you've written uses the -webkit- prefix which means it's only going to work only in WebKit browsers. However, all current versions of desktop browsers that support transitions support them unprefixed.

A: *

*'All' specifies the properties to transition.

*The final time parameter is a delay argument. '0s' means, as you'd expect, no delay.

If I wanted to transition just the background colour, and delay by 4 seconds, I would write:
transition: background-color 0.35s ease-in-out 4s;

A: There are some great articles detailing the use of transition -
http://css-tricks.com/almanac/properties/t/transition/
https://developer.mozilla.org/en-US/docs/Web/CSS/transition

A: transition: <property> <duration> <easing> <delay>;

A: Universal property transition is shorthand for 4 individual properties: transition-property, transition-duration,transition-delay, and transition-timing-function.
First 2 properties are required even though a default value for transition-property is all which defines that all properties that can transition will transition. The transition-timing-function property is defined by predefined functions.
Duration and delay properties are defined with seconds or milliseconds, just keep in mind that first time defined is always duration.
Source: https://kolosek.com/css-transition/


text:
Q: asp.net AutoPostBack and update Is there a way to have autopostback enabled and not have page refresh (thereofre scrolling back to the top) when a dropdownlist changes for example?
I have a few dropdownlists and the values in the subsequent ones need to change based on what is picked in the upper ones.
Whats the best way to do that? Each DDL is populated from the DB.

A: Use an update panel to accomplish this. A full overview is provide here You add items to the panel that you need to post back and only that part of the page postbacks.

A: You could maintain scroll position between postbacks pretty easily
http://msdn.microsoft.com/en-us/library/system.web.ui.page.maintainscrollpositiononpostback.aspx

A: you can put all ddl into updatepanel,and then page will not postback itself.And your ddl can be rebind without needing a full page postback.
another option is to use cascading dropdown,there is a sample in asp.net ajax toolkit samples.It uses webservices for databinding.This methot is better than using updatapanels,but its little hard to implement.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx ,check this example.

A: Us Jquery AJAX OR Simply Use ASP.net UpdatePanel Control


text:
Q: F# Lambda in Object Expression I can see people using lambdas in object expressions such as in this post, but I can't quite figure out why the following idea doesn't work.
type fooType = {flar : string; grib: int}
let boundFoo = {flar = "hello"; grib = 1}
let flack = {boundFoo with grib = fun () -> if boundFoo.flar = "hello" then 5 else 4}

From what I can gather, it doesn't like fun () ->, but fun _ -> and fun x -> don't seem to lead anywhere different?
My research on this so far at my usual spots MSDN, F# for fun and profit and google didn't lead me down any clear paths.
What am I missing here?

A: In your code grib is an int. fun () -> ... is not an int, it's a function. Therefore fun () -> ... is not a valid value for the field grib.
If grib had the type () -> int, then your code would work (except that you'd have to change grib = 1 on the previous line to grib = fun () -> 1 of course), but that doesn't really seem a useful thing to do here. Really it does not seem like a function is really appropriate here. This will work fine:
let flack = {boundFoo with grib = if boundFoo.flar = "hello" then 5 else 4}


text:
Q: jcarousel - Customization I am using jquery plugin 'jcarousel' - as i can't use it as is - i am trying to fit it to my requirements:
my code:
function mycarousel_itemLoadCallback(carousel, state)
{
  for (var i = carousel.first; i < 10; i++) {
   if (carousel.has(i)) { continue;  }
   carousel.add(i, mycarousel_getItemHTML());
  }
  }

function mycarousel_getItemHTML()
{ return '';}

-Constructing itemURL and imgSrc on a button click - right now - I am seeing the same image on 10 slots in carousal - I understood whats happening here - but in jcarousal documentation - for getting the li items dynamically they are getting it from a pre-filled list - in my case I wont have any list just gave it 10 for time being - i will have current item (any time only 1) - any ideas on how to fit it to my requirement - I want to add to carousel on button click


text:
Q: mi ubuntu dice en consola que laravel no es un comando hoy realice la instalacion de composer junto con laravel, pero lo cual termino de instalar composer y requiero el global installer de laravel, ok instalo todos sus components normal, pero al tratar de crear una nueva app de laravel , me dice en la consola que el comando laravel no lo reconoce.

A: Es porque no has exportado la ruta al ejecutable como variable global. Prueba:
export PATH="~/.composer/vendor/bin:$PATH"

Luego:
source ~/.bashrc

Para verificar:
echo $PATH

Luego reinicia tu consola y repite el último comando, el resultado debería ser el mismo:


text:
Q: Dynamic Java Bytecode Manipulation Framework Comparison There are some frameworks out there for dynamic bytecode generation, manipulation and weaving (BCEL, CGLIB, javassist, ASM, MPS). I want to learn about them, but since I don't have much time to know all the details about all of them, I would like to see a sort of comparison chart saying the advantages and disadvantages of one versus the others and an explanation of why.
Here in SO, I found a lot of questions asking something similar, and the answers normally said "you can use cglib or ASM", or "javassist is better than cglib", or "BCEL is old and is dying" or "ASM is the best because it gives X and Y". These answers are useful, but does not fully answer the question in the scope that I want, comparing them more deeply and giving the advantages and disadvantages of each one.

A: First of all it all depends on your task. Do you want to generate the new code or analyze existing bytecode and how complex analysis you may need. Also how much time you want to invest into learning Java bytecode. You can break down bytecode framework into ones that provide a high level API, that allows you to get away from learning low level opcodes and JVM internals (e.g, javaassist and CGLIB) and low level frameworks when you need to understand JVM or use some bytecode generation tools (ASM and BCEL). For analyzis BCEL historically evolved a bit more, but ASM provides a decent functionality that is easy to extend. Also note, ASM is probably the only framework that provides the most advanced support for STACK_MAP information required by the new bytecode verifier enabled by default in Java 7.

A: Analysis of bytecode libraries
As I can tell from the answers you got here and ones in the questions that you have looked at, these answers do not formally address the question in the explicit manner you have stated. You asked for a comparison, meanwhile these answers have vaguely stated what one might want based on what your target is (e.g. Do you need to know bytecode? [y/n]), or are too narrow.
This answer is a short analysis of each bytecode framework, and provides a quick comparison at the end.
Javassist

*

*Tiny (javassist.jar (3.21.0) is ~707KB / javassist-rel_3_22_0_cr1.zip is ~1.5MB)

*High(/Low)-level

*Straightforward

*Feature-complete

*Requires minimal to no class file format knowledge

*Requires moderate Java instruction set knowledge

*Minimal learning effort

*Has some quirks in the single-line/multi-line compile-and-insert-bytecode methods

I personally prefer Javassist simply because of how quickly you can get to using it and building and manipulating classes with it. The tutorial is straightforward and easy to follow. The jar file is a tiny 707KB, so it is nice and portable; makes it suitable for standalone applications.

ASM

*

*Large (asm-6.0_ALPHA-bin.zip is ~2.9MB / asm-svn-latest.tar.gz (10/15/2016) is ~41MB)

*Low(/High)-level

*Comprehensive

*Feature-complete

*Recommend a proficient knowledge of class file format

*Requires proficiency with Java instruction set

*Moderate learning effort (somewhat complex)

ASM by ObjectWeb is a very comprehensive library which lacks nothing related to building, generating, and loading classes. In fact, it even has class analysis tools with predefined analyzers. It is said to be the industry standard for bytecode manipulation. It is also the reason why I steer clear away from it.
When I see examples of ASM, it seems like a cumbersome beast of a task with the number of lines it takes to modify or load a class. Even some of the parameters to some methods seem a bit cryptic and out of place for Java. With things like ACC_PUBLIC, and plenty of method calls with null everywhere, it honestly does look like it is better suited for a low-level language like C. Why not simply just pass a String literal like "public", or an enum Modifier.PUBLIC? It's more friendly and easy to use. That is my opinion, however.
For reference, here is an ASM (4.0) tutorial: https://www.javacodegeeks.com/2012/02/manipulating-java-class-files-with-asm.html

BCEL

*

*Small (bcel-6.0-bin.zip is 7.3MB / bcel-6.0-src.zip is 1.4MB)

*Low-level

*Adequate

*Gets the job done

*Requires proficiency with Java instruction set

*Easy to learn

From what I have seen, this library is your basic class library that lets you do everything you need to—if you can spare a few months or years.
Here is a BCEL tutorial that really spells it out: http://www.geekyarticles.com/2011/08/manipulating-java-class-files-with-bcel.html?m=1

cglib

*

*Very tiny (cglib-3.2.5.jar is 295KB/source code)

*Depends on ASM

*High-level

*Feature-complete (Bytecode Generation)

*Little or no Java bytecode knowledge needed

*Easy to learn

*Esoteric Library

Despite the fact that you can read information from classes, and that you can transform classes, the library seems tailored to proxies. The tutorial is all about beans for the proxies, and it even mentions it is used by "data access frameworks to generate dynamic proxy objects and intercept field access." Still, I see no reason why you can't use it for the more simple purpose of bytecode manipulation instead of proxies.

ByteBuddy

*

*Small bin/"Huge" src (by comparison) (byte-buddy-dep-1.8.12.jar is ~2.72 MB / 1.8.12 (zip) is 124.537 MB (exact))

*Depends on ASM

*High-level

*Feature-complete

*Personally, a peculiar name for a Service Pattern class (ByteBuddy.class)

*Little or no Java byte code knowledge needed

*Easy to learn

Long story short, where BCEL is lacking, ByteBuddy is abundant. It uses a primary class called ByteBuddy using the Service Design Pattern. You create a new instance of ByteBuddy, and this represents a class that you want to modify. When you are done with your modifications, you can then make a DynamicType with make().
On their website is a full tutorial with API documentation. The purpose seems to be for rather high-level modifications. When it comes to methods, there does not appear to be anything in the official tutorial, or any 3rd party tutorial, about creating a method from scratch, apart from delegating a method (EDITME if you know where this is explained).
Their tutorial can be found here on their website. Some examples can be found here.

Java Class Assistant (jCLA)
I have my own bytecode library that I am building, which will be called Java Class Assistant, or jCLA for short, because of another project I am working on and because of said quirks with Javassist, but I will not be releasing it to GitHub until it is finished but the project is currently available to browse on GitHub and give feedback on as it is currently in alpha, but still workable enough to be a basic class library (currently working on the compilers; please help me if you can! It will be released a lot sooner!).
It will be quite bare bones with the ability to read and write class files to and from a JAR file, as well as the ability to compile and decompile bytecode to and from source code and class files.
The overall usage pattern makes it rather easy to work with jCLA, though it may take some getting used to and is apparently quite similar to ByteBuddy in its style of methods and method parameters for class modifications:
import jcla.ClassPool;
import jcla.ClassBuilder;
import jcla.ClassDefinition;
import jcla.MethodBuilder;
import jcla.FieldBuilder;

import jcla.jar.JavaArchive;

import jcla.classfile.ClassFile;

import jcla.io.ClassFileOutputStream;

public class JCLADemo {

    public static void main(String... args) {
        // get the class pool for this JVM instance
        ClassPool classes = ClassPool.getLocal();
        // get a class that is loaded in the JVM
        ClassDefinition classDefinition = classes.get("my.package.MyNumberPrinter");
        // create a class builder to modify the class
        ClassBuilder clMyNumberPrinter= new ClassBuilder(classDefinition);

        // create a new method with name printNumber
        MethodBuilder printNumber = new MethodBuilder("printNumber");
        // add access modifiers (use modifiers() for convenience)
        printNumber.modifier(Modifier.PUBLIC);
        // set return type (void)
        printNumber.returns("void");
        // add a parameter (use parameters() for convenience)
        printNumber.parameter("int", "number");
        // set the body of the method (compiled to bytecode)
        // use body(byte[]) or insert(byte[]) for bytecode
        // insert(String) also compiles to bytecode
        printNumber.body("System.out.println(\"the number is: \" + number\");");
        // add the method to the class
        // you can use method(MethodDefinition) or method(MethodBuilder)
        clMyNumberPrinter.method(printNumber.build());

        // add a field to the class
        FieldBuilder HELLO = new FieldBuilder("HELLO");
        // set the modifiers for hello; convenience method example
        HELLO.modifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL);
        // set the type of this field
        HELLO.type("java.lang.String");
        // set the actual value of this field
        // this overloaded method expects a VariableInitializer production
        HELLO.value("\"Hello from \" + getClass().getSimpleName() + \"!\"");

        // add the field to the class (same overloads as clMyNumberPrinter.method())
        clMyNumberPrinter.field(HELLO.build());

        // redefine
        classDefinition = clMyNumberPrinter.build();
        // update the class definition in the JVM's ClassPool
        // (this updates the actual JVM's loaded class)
        classes.update(classDefinition);

        // write to disk
        JavaArchive archive = new JavaArchive("myjar.jar");
        ClassFile classFile = new ClassFile(classDefinition);
        ClassFileOutputStream stream = new ClassFileOutputStream(archive);

        try {
            stream.write(classFile);
        } catch(IOException e) {
            // print to System.out
        } finally {
            stream.close();
        }
    }

}

(VariableInitializer production specification for your convenience.)
As may be implied from the above snippet, each ClassDefinition is immutable. This makes jCLA more secure, thread-safe, network-safe, and easy to use. The system revolves primarily around ClassDefinitions as the object of choice for querying information about a class in a high-level manner, and the system is built in such a way that ClassDefinition is converted to and from target types such as ClassBuilder and ClassFile.
jCLA uses a tiered system for class data. At the bottom, you have the immutable ClassFile: a struct or software representation of a class file. Then you have immutable ClassDefinitions which are converted from ClassFiles into something less cryptic and more manageable and useful to the programmer who is modifying or reading data from the class, and is comparable to information accessed through java.lang.Class. Finally, you have mutable ClassBuilders. The ClassBuilder is how classes are modified or created. It allows that you can create a ClassDefinition directly from the builder from its current state. Creating a new builder for each class is not necessary as the reset() method will clear the variables.
(Analysis of this library will be available as soon as it is ready for release.)
But until then, as of today:

*

*Small (src: 227.704 KB exact, 6/2/2018)

*Self-sufficient (no dependencies except Java's shipped library)

*High-level

*No required knowledge of java bytecode or class files (for tier 1 API, e.g. ClassBuilder, ClassDefinition, etc.)

*Easy to learn (even easier if coming from ByteBuddy)

I still recommend learning about java bytecode however. It will make debugging easier.

Comparison
Considering all of these analyses (excluding jCLA for now), the broadest framework is ASM, the easiest to use is Javassist, the most basic implementation is BCEL, and the most high-level for bytecode generation and proxies is cglib.
ByteBuddy deserves its own explanation. It is easy to use like Javassist, but appears to be lacking some of the features that make Javassist great, such as method creation from scratch, so you would need to use ASM for that apparently. If you need to do some lightweight modification with classes, ByteBuddy is the way to go, but for more advanced modification of classes while maintaining a high level of abstraction, Javassist is a better choice.
Note: if I missed a Library, please edit this answer or mention it in a comment.

A: If your interest in bytecode generation is only to use it, the comparison chart becomes rather simple :
Do you need to understand bytecode?
for javassist : no
for all others : yes
Of course, even with javassist you may be confronted with bytecode concepts at some point. Likewise, some of the other libraries (such as ASM) have a more high-level api and/or tool support to shield you from many of the bytecode details.
What really distinguishes javassist though, is the inclusion of a basic java compiler. This makes it very easy to write complex class transformations : you only have to put a java fragment in a String and use the library to insert it at specific points in the program. The included compiler will build the equivalent bytecode, which is then inserted into the existing classes.


text:
Q: How can moving my foot possibly affect electronics meters away? I'm curious about a strange effect I observed.
I was designing a device, which sleeps most of the time and can be woken up by a loud sound signal, like an opening door, a clap, etc.
The relevant part of the schematic:

simulate this circuit – Schematic created using CircuitLab
The ambient noise is picked up by an electret mic, amplified, and sent to a digital input on the MCU. The trimpot serves for sensitivity adjustment, so the user can tune the sound pressure level that should trigger the device. All this is very crude, as the pin threshold is not strictly defined, and the pot is not in the usual "divider" configuration (the gain selection is not linear), but that is not the issue.
When I soldered this, I noticed it didn't work; it wasn't picking sounds unless they were very loud, so I increased the amplification to absurd levels (trimpot turned to the limit, think of 19990 ohms on the right side and 10 ohms on the left side). Even at that levels, clapping hands only registered as 300 mV pulses.
While walking around the room, pondering on what can be wrong, I noticed that the oscilloscope was picking enormous signals on the opamp output, up to 5 volts. Thinking that must be the noise of my walking, I experimented more, and discovered that even in a completely quiet room, just lifting my foot of the ground produced that signal. It wasn't the sound of it, just the movement. And I was 2-3 meters away from the circuit. In a sense, the slight act of lifting my foot (or just altering its position) got registered by the sensor; whereas flipping a light switch, making a big noise with hands, etc. did not.
In the end I found what the problem was. The sensor I was using is a ECM30B. It has the traditional two pins, along with a metal tab protruding from the casing, that also seemed that needs to be soldered. Usually these mics have the ground pin and the casing inherently connected. But this one wasn't. When I connected them, the circuit behaved as expected, and with the huge amplification it picked even minute sound noises.
In a sense, the circuit was open at the "X" point. Not really, since the ground pin of the mic was soldered to ground, but just the casing was floating. With this in mind, what could have been the effect that captured my foot moving meters away (even considering the enormous amplification), but ignored similar movements with my hands?

A: The case of your microphone is probably electrically connected to the flexible membrane inside the microphone, and is responsible for grounding it, while the "ground pin" is only used to provide the return path for the FET preamplifier. In normal operation, both need to be grounded so that there's a complete circuit to drive the gate of the FET.
With the case "floating", the microphone is no longer senstive to sounds, but it does become very sensitive to external electric fields of any sort. Walking around, or even just lifting your foot, can create large amounts of static electricity, particularly in a dry environment, and the field associated with your body was affecting the case of the microphone. Your body might have a potential of several thousand volts, and it only takes a few mV to drive the gate of the FET.


text:
Q: moving and rotating objects along a sine wave There are a couple of problems i'm having with this - the first is how to work out how to find where the tip of each sine curve is (ie the frequency) and the second is to work out how to rotate each object so that it slides sideways along the sine wave
(note file is 800 x 600)
here's my code:
CarouselTest.as:
package
{
    import com.greensock.easing.Sine;
    import com.greensock.TweenMax;
    import com.components.CarouselItem;
    import com.theflashblog.fp10.SimpleZSorter;
    import flash.display.Sprite;
    import flash.events.Event;
    import uk.co.thereceptacle.utils.Trig;

    public class CarouselTest extends Sprite
    {
        public static const SPACING : int = 20;
        public static const XSPACING: int = SPACING * 5;
        public static const SPEED   : Number = .05;
        public static const XSPEED  : Number = 800 / 360 * 2;
        public static const RADIUS  : int = 400;

        private var _items:Array;
        private var _container:Sprite;
        private var _movePerItem:Number;
        private var _noOfItems:int;

        public function CarouselTest()
        {
            _items = new Array();
            _noOfItems = 200;
            _movePerItem = 360 / _noOfItems; // my attempt at finding how much each item must move in order to bring it to the front

            _container = new Sprite();
            _container.x = 400;
            _container.y = 300;
            _container.z = 200;
            addChild(_container);

            var item:CarouselItem = new CarouselItem();
            for (var i:int = 0; i < _noOfItems; i++)
            {
                item = new CarouselItem();
                item.radius = RADIUS;
                item.angle = (i * SPACING) % 360;
                item.x = i * XSPACING - 300;
                item.speed = SPEED;
                _container.addChild(item);
                _items.push(item);
            }

            moveItems(-1 * _movePerItem);
        }

        private function moveItems(direction:int):void
        {
            TweenMax.allTo(_items, 5, { angle:direction.toString(), x:(direction * XSPACING).toString(), ease:Sine.easeInOut } );
            TweenMax.to(this, 5, { onUpdate:SimpleZSorter.sortClips, onUpdateParams:[_container] } );
        }
    }
}

CarouselItem.as
package com.components
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import uk.co.thereceptacle.components.HTMLTextField;
    import uk.co.thereceptacle.utils.Trig;

    public class CarouselItem extends Sprite
    {
        private var _angle  : Number;
        private var _prevX  : Number;
        private var _prevZ  : Number;

        public var speed    : int;
        public var radius   : Number;

        public function CarouselItem()
        {
            graphics.beginFill(0x99ff00);
            graphics.lineStyle(1);
            graphics.drawRect( -100, -150, 200, 300);

            var tf:TextField = new HTMLTextField();
            tf.embedFonts = false;
            tf.wordWrap = false;
            tf.htmlText = "
THIS IS A TEST
";
            tf.x = -100;
            tf.y = -tf.textHeight / 2;
            addChild(tf);
        }

        public function get angle():Number { return _angle; }
        public function set angle(value:Number):void
        {
            _angle = value;

            z = Math.sin(angle) * radius;

            var deltaX:Number = x - _prevX;
            var deltaZ:Number = z - _prevZ;
            var rotate:Number = Trig.radiansToDegrees(Math.atan2(deltaZ, deltaX));
            rotationY = rotate; // this is getting close but always rotates the item away from the center and i need it to rotate towards the center on the positive side of the sine wave
// edit: i've updated this as it's much closer but still flaky - it feels like i haven't done it right

        }

        override public function set x(value:Number):void
        {
            _prevX = x;
            super.x = value;
        }

        override public function set z(value:Number):void
        {
            _prevZ = z;
            super.z = value;
        }
    }
}

hope you can help
obie

A: I assume you want to animate something like a skateboard on a rolling hill (or boat on seas, or something with similar motion).
All of the trig/calculus you need to know for this problem: The line sitting on a curve in the way you want is the tangent line. It is described by the derivative of the curve. The derivative of the sine curve is the cosine. Calculus magic: if your curve is a*sin(b*x), the tangent is a*b*cos(b*x). That gives you (rise/run). If you want this expressed as an angle, you will want the atan (or atan2) of that. Note, you will need to be consistent with your angle units. Most likely atan gives you radians and you want degrees.


text:
Q: Obtener historial de un ticket(ID) el cual esta en la misma tabla. MYSQL Buenas tardes tengo la siguiente tabla

quisiera hacer una consulta donde el resultado sea el historial del ticket Para el ejemplo que se mira sería lo siguiente
--------------------------------------------
|account     |  ticket      |comment        |
---------------------------------------------
|9962708     | 633225601    |to 633226153   |
|9962708     | 633226153    |from 633225601 |
---------------------------------------------
|9962708     |633382901     | to 633389262  |
|9962708     |633389262     | to 633389339  |
|9962708     |633389339     | to 633389451  |
|9962708     |633389451     | from 633389339|
---------------------------------------------

Actualizacion
Tengo unas consultas anidadas en mi proyecto las cuales me repiten un registro  del historial, quisiera saber si existe alguna manera de hacerlo.
$tampil = $koneksi->prepare("SELECT ticket,symbol,lot,ordertype,orderprofit,orderswap,comment FROM mt4history WHERE comment LIKE '%to%' ORDER BY ticket");
$tampil->execute();
$tampil->setFetchMode(PDO::FETCH_ASSOC);
while($data = $tampil->fetch(PDO::FETCH_ORI_NEXT))
  {
   $ticket = $data['ticket'];
   $comment = $data['comment'];
    ? >
   <tr class = "tablecell"  id = "<?php echo $data['ticket']; ?>" >
    <? php echo $data['ticket'];? >

    <? php echo $data['symbol'];? >
    <? php echo $data['lot'];? >
    <? php echo $data['type'];? >
    <? php echo $data['orderprofit'];? >
    <? php echo $data['orderswap'];? >
    <? php echo $data['comment'];? >

   < !-- SUBCONSULTA -- >
   <? php
   $coment_partial = explode(" ", $comment);
   echo $coment_partial[0];
   echo $coment_partial[1];
   $tampil1 = $koneksi->prepare("SELECT ticket,symbol,lot,ordertype,orderprofit,orderswap,comment FROM mt4history WHERE ticket = $coment_partial[1]");
   $tampil1->execute();
   $tampil1->setFetchMode(PDO::FETCH_ASSOC);
   while($data1 = $tampil1->fetch(PDO::FETCH_ORI_NEXT))
     {
       ? >
      <tr class = "tablecell "  id = "<?php echo $data1['ticket']; ?>" >
       <? php echo $ticket ? >
       <? php echo $data1['ticket'];? >
       <? php echo $data1['symbol'];? >
       <? php echo $data1['lot'];? >
       <? php echo $data1['type'];? >
       <? php echo $data1['orderprofit'];? >
       <? php echo $data1['orderswap'];? >
       <? php echo $data1['comment']; ? >

      <? php} ? >
   < !-- SUBCONSULTA -- >
//+------------------------------------------------------------------+

Se que necesito hacer esas consultas por medio de API's, lo pretendo hacer mas adelante, soy novato en esto


text:
Q: Client of web service in Perl I am the client - I wish to call methods of a web service.
I have a web service address (.svc suffix) and I have the method's name, return value and their argument.
The service is implemented with WCF (HTML end point). I wish to call those methods by SOAP::Lite. What should I write for the URI, proxy and how exactly do I call the methods?

A: You set

*

*the proxy to the endpoint and

*the uri (or in the most recent version ns) to the namespace in the method definition.

One of the easiest ways to do this is simply to use the WSDL URI and create a SOAP::Schema object with it, like so:
my $schema = SOAP::Schema->new( schema_url => $destination_URL )->parse();
my $services = $schema->services();

And dump those two objects.
You can look for
my $method_def = $service->{ $method_name };

my $uri   = $method_def->{namespace};
my $proxy = $method_def->{endpoint}->value();

And use those values, if everything is there.
I had to dig through a lot of SOAP::Lite dumps in order to get my SOAP client architecture working. You should know how to debug and dump Perl objects if you want to shoot all your troubles.
I'll show you an anonymized dump of a service:
$services = {
    ServiceName => {
        MethodName => {
            endpoint => bless( {
                _attr => {},
                _name => 'location',
                _signature => [],
                _value => [
                    # v-- This value you pass to SOAP::Lite->proxy
                    'http://some.domain.com/WebServices/SOAPEndpoint.asmx'
                ]
            }, 'SOAP::Custom::XML::Data'
            ),
            # v-- This value you pass to uri/default_ns/ns
            namespace => 'http://some.domain.com/',
            parameters => [ ... ]
            ...
        }
    }
};


text:
Q: How to get out of this infinite loop in SML Here is what my code looks like now.
I'm trying to make a multi choice question program
It's quite rudimentary as a way of proceeding but I find it difficult to structure the code in a more "professional" way.
fun readlist(filename) =
    let
        val file = TextIO.openIn filename
        val text = TextIO.inputAll file
        val _ = TextIO.closeIn file
    in
        String.tokens (fn c => c = #"\n") text
    end;

(*Get user answer from keybord*)
fun getAnswer() = (
    print "\nPlease enter your answer. Options(case sensitive): \nA-) \tB-) \tC-) \tD-)\n";
    let
        val return = valOf (TextIO.inputLine TextIO.stdIn)
    in
        return
    end
);

(*Verify if the choosen line is a new starting question block base on fact that each question block contains 7 line*)
fun getQuestionLine(t) =
    case t of
    [] => []
    |t::ts => if t mod 7 = 0 then
        t::getQuestionLine(ts)
     else
        getQuestionLine(ts);

fun toIntList(x:int) = x;
val getblockStarts = getQuestionLine(List.tabulate(List.length(readlist("questionBank.txt")), toIntList));
fun member (x, []) = false
    | member (x, y::yt) = x = y orelse member (x, yt);

fun seed () =
    let
        val aReal = Time.toReal(Time.now()) - 1.0e9
        val floorReal = Real.realFloor(aReal)
        val dec = aReal - floorReal
        val sd1 = Real.floor(dec);
        val sd2 = Real.floor(1000.0 * dec);
    in
        Random.rand(sd1,sd2)
    end;

fun randList (N) =
    let
      fun subfun (N, i) intList =
          if N = 0 then intList
          else
              let
                  val tmp = Random.randRange(1, (List.length(readlist("questionBank.txt"))))
                  val randVal = tmp i
              in
                  if member(randVal, getblockStarts) then
                      subfun (N - 1, i) (randVal :: intList)
                  else
                      subfun (N, i) intList
              end;
    in
        subfun (N, seed()) []
    end;

fun ask(questionIndexList) =
    let
      fun loop (n) =
          let
              val question = print(
                  "\n"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1))^"\n\t"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+1)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+2)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+3)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+4)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+5)^"\n"
              )
              val userAns = getAnswer()
          in
              if userAns = List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+6)^"\n" then
                (
                  print("Your answer is CORRECT.\n");
                  loop (List.length(List.take(questionIndexList, List.length(questionIndexList)-1)))
                )
              else (
                  print(
                      "Your answer is INCORRECT.\nThe correct answer is: "^
                      List.nth(readlist("questionBank.txt"), List.nth(questionIndexList, n-1)+6)
                      ^"\n\n"
                  );
                  loop (List.length(List.take(questionIndexList, List.length(questionIndexList)-1)))
                )
          end
    in
        loop (List.length(questionIndexList))
    end;

ask(randList(3));

I added a capture from my question file.

All questions follow this format
My code works the way I want it to, but the last lap in the loop is endless. The console offers me three questions that I answer and I have the right answer if I didn't find it, but the third question is asked again and again without end.
I've been looking all over the place and I don't know where my mistake lies. I would need help to get out of this loop.

A: There is no condition to take you out of loop; you recurse unconditionally in both conditional branches.
You could fix that by checking for zero, if it weren't for the fact that
List.length(List.take(questionIndexList, List.length(questionIndexList)-1))

is always the same number.
(Which is List.length(questionIndexList)-1 – if you take K elements from  a list, the result has length K. There is no need to create the list just to determine its length.)
But I would structure this differently.
You are reading the file every time you need the questions.
It is better to read the file once and pass the list around.
First, a type to represent the question and answers:
type Options = string * string * string * string;
datatype QA = QA of string * Options * string;

And a couple of functions for gathering those from the unwieldy list of strings:
fun toQAs [] = []
  | toQAs (q::o1::o2::o3::o4::a::qas) = (QA (q, (o1,o2,o3,o4), a)) :: (toQAs qas);

fun readQuestions file = toQAs (readlist file);

And a utility function for printing a question:
fun printQuestion (QA (q, (o1,o2,o3,o4), _)) = print ("\n"^ q^"\n\t"^ o1^"\n\t"^ o2^"\n\t"^ o3^"\n\t"^ o4^"\n");

The ask function just takes a list of questions and asks all of them:
fun ask [] = print "No further questions.\n"
  | ask  (q::qs) =
    let val (QA (_, _, answer)) = q
    in
        printQuestion q;
        if getAnswer() = answer^"\n" then
             print "Your answer is CORRECT.\n"
         else
             print ("Your answer is INCORRECT.\nThe correct answer is: "^ answer ^"\n\n");
        ask qs
    end;

And finally, a function that creates a random list of questions based on the file, and asks them:
fun go () =
    let
        val QAs = readQuestions "questionBank.txt"
    in
        ask (map (fn i => List.nth(QAs, i)) (randList (length QAs) 3))
    end;

A: I changed my ask function to use the number of questions to ask rather than the list of blocks of questions to display.
fun ask(n) =
    let
      fun loop (n) =
          let
              val newQues = randList(1)
              val question = print(
                  "\n"^
                  List.nth(readlist("questionBank.txt"), hd newQues)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), (hd newQues)+1)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), (hd newQues)+2)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), (hd newQues)+3)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), (hd newQues)+4)^"\n\t"^
                  List.nth(readlist("questionBank.txt"), (hd newQues)+5)^"\n"
              )
              val userAns = getAnswer()
          in
              if userAns = List.nth(readlist("questionBank.txt"), (hd newQues)+6)^"\n" then
                (
                  print("Your answer is CORRECT.\n");
                  if n > 1 then loop (n-1) else ()
                )
              else (
                  print(
                      "Your answer is INCORRECT.\nThe correct answer is: "^
                      List.nth(readlist("questionBank.txt"), (hd newQues)+6)
                      ^"\n\n"
                  );
                  if n > 1 then loop (n-1) else ()
                )
          end
    in
        loop (n)
    end;

ask(5);

So it's working as i want now.
If sommeone have optimizing ideas, i'll be happy to read them.


text:
Q: Basic Java program tune up assistance My program asks the user for their name, then asks for a number of shuffles of 3 random numbers.
When one of the shuffles adds to the desired number (which is 31) the shuffle stops. I need to happen that the program only reads the LAST SHUFFLE. E.g.

how many shuffles do you want: 3
10 + 11 + 10 = 31 congrats you are the winner!!

The current output is:

9 + 6 + 8
8 + 10 + 12
7 + 9 + 11

I need assistance in making sure the user cannot put non alphabetical characters in their name. I also need the ability to be able to print out how many shuffles the user had before the numbers were printed out.
Here is my code,
  `import java.util.InputMismatchException;
   import java.util.Scanner;
   import java.io.IOException;
   import java.util.Random;

 public class StringVariables {

public static void main(String[] args) throws NumberFormatException,
        IOException {

    // user inputs their name in this section
    Scanner user_input = new Scanner(System.in);
 //enter their first name
    String first_name;
    System.out.print("Enter Your First Name: ");
    first_name = user_input.next();
  //enter their last name
    String last_name;
    System.out.print("Enter Your Last Name: ");
    last_name = user_input.next();
 //full name printed together
    String full_name;
    full_name = first_name + " " + last_name;

    System.out.println(full_name + " Is Now Playing");

    // this is the shuffle portion as well as something to see if a number

    int numShuffles = -1;
    while (numShuffles < 0) {

        System.out.println("How many times do you want the numbers shuffled? ");

        try {
            numShuffles = user_input.nextInt();
        } catch (InputMismatchException inputException) {
            System.out.print("Please enter a valid number. \n");
            //this is the buffer that resets if the user types a letter instead of a number, or any other character
            user_input.next();
        }
    }

    // here is going to be the loop for shuffles

    // we are now going to generate their random number and add a delay
    // after completing their name fields

    delay(3000);
    System.out
            .println(" You will be given a hand of 3 random numbers between 7-13"
                    + "\n you will be drawn a the number of shuffles as you entered above ");

    delay(2000);
    System.out
            .println(" Then, the computer will add the random numbers and  if it is equal to 31, you win.");

    /*
     * end of explanation of the game, next i will create a new screen with
     * the user's name and numbers
     */

    delay(4000);
    // printing 25 blank lines
    for (int i = 0; i < 25; i++)
        System.out.println(" ");

    System.out.println("User playing: " + full_name);

    System.out.println("Your lucky numbers are...");

    // random number generator

    Random random = new Random();

    while (true) {

        // the shuffle loop
        boolean isWinner = false;
        for (int i = 0; i < numShuffles; i++) {
            int num1 = 7 + random.nextInt(7);
            int num2 = 7 + random.nextInt(7);
            int num3 = 7 + random.nextInt(7);

            System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
                    + (num1 + num2 + num3));

  // adding the numbers together

            if (num1 + num2 + num3 == 31) {
                isWinner = true;
                System.out
                        .println("Congratulations !! You are the Lucky Winner !!!!");
                break;
                //if you loose every shuffle
            }
        }
        if (!isWinner)
            System.out.println("Better Luck Next Time");

        // play again prompt
        System.out
                .println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
        String input = user_input.next();
        if (!"y".equalsIgnoreCase(input) &&  !"yes".equalsIgnoreCase(input)) {
            break;
        }
    }

    // if pressed y or yes the program will run again with the same number of shuffles entered from before
    user_input.close();
}

// delay field

public static void delay(int millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException exp) {

        // delay field

    }
}
 }`

A: Arraylist numberStore = new Arraylist();
for (int i = 0; i < numShuffles; i++) {
    int num1 = 7 + random.nextInt(7);
    int num2 = 7 + random.nextInt(7);
    int num3 = 7 + random.nextInt(7);

    System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));

    numberStore.add(num1 + num2 + num3);

}

int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
        isWinner = true;
        System.out
                .println("Congratulations !! You are the Lucky Winner !!!!");
        break;
        //if you loose every shuffle
}

to make sure that only the last shuffle can get read as a winner or loser.

Because you are initializing your num1, num 2... variables inside of your for loop then those variables are scoped to that for loop. I would suggest that if you want to make sure that only one set of numbers can be judged then you move the scope out of the loop. Adding the totals to an array would then allow you to choose as many as you want to judge.
When it comes to sterilizing your inputs you can use util.Scanner to do most of it for you with a little knowledge of regex:
while (!scan.hasNext("[A-Za-z]+")) {
    System.out.println("Nope, that's not it!");
    sc.next();
}

This will stop your scanner allowing any none alphabetical char's being entered, you can read more about Regex with this tool


text:
Q: Call Function written inside directive from another controller I have a directive as follows,
    angular.module('test.directives').directive("resize", function($window) {
      return function(scope, element) {
        var w;
        w = angular.element($window);
        scope.getWindowDimensions = function() {
          return {
            h: w.height(),
            w: w.width()
          };
        };
      };
    });

How can i call scope.getWindowDimensions() from another controller? Is it possible?
Please help,
Thanks.

A: Yes you should not but if you want it you can do it
    As shown in this example :-
You need to use two way binding by
scope: {
      control: '='//use for two way binding
    }

http://plnkr.co/edit/JPh3wZ?p=preview


text:
Q: Measuring the distance between two curves with Dynamic time wrapping (DTW) function in Tensorflow To measure the distance between two curves with Dynamic time wrapping (DTW) function  in Tensorflow 2.0, I tried to convert the following DTW python code segment into Tensorflow. But in the 2nd nested loop section, the final_val is not updating into the dtw_matrix. Trying to debug it but couldn't make it yet. What would be a good way to approach this problem?
def dtw(s, t):
'''
s,t are 1D vector,eg., 128 by 1
'''
n, m = len(s), len(t)
dtw_matrix = np.zeros((n+1, m+1))
for i in range(n+1):
    for j in range(m+1):
        dtw_matrix[i, j] = np.inf
dtw_matrix[0, 0] = 0

for i in range(1, n+1):
    for j in range(1, m+1):
        cost = abs(s[i-1] - t[j-1])
        # take last min from a square box
        last_min = np.min([dtw_matrix[i-1, j], dtw_matrix[i, j-1], dtw_matrix[i-1, j-1]])
        dtw_matrix[i, j] = cost + last_min
return dtw_matrix

I tried the tensorflow implementation in the following way:
def dtw(s, t):
n, m = s.shape[0],t.shape[0]

dtw_matrix = tf.Variable(tf.zeros([n+1, m+1], tf.float32))

for i in range(n+1):
    for j in range(m+1):
        dtw_matrix =dtw_matrix[i, j].assign(inf)
dtw_matrix =dtw_matrix[0, 0].assign(0)

for i in range(1, n+1):
    for j in range(1, m+1):

        s_ele = tf.gather(s,i-1)

        t_ele = tf.gather(t,j-1)

        cost1 = tf.math.subtract(s_ele,t_ele)
        cost  = tf.keras.backend.abs(cost1)

        # take last min from a square box
        last_min =tf.math.reduce_min([dtw_matrix[i-1, j], dtw_matrix[i, j-1], dtw_matrix[i-1, j-1]])

        final_val=tf.math.add(cost,last_min)
        dtw_matrix=dtw_matrix[i, j].assign(final_val)
return dtw_matrix

I suspect it might be due to my tensorflow coding error that I'm not aware of. Also, Is there a way to get rid of these nested loops? It's slowing down the computation.