Q: Taking 4-5 second to visible view with big ArrayList data to RecyclerView inside NestedScrollView I have three RecyclerView in NestedScrollView, 2 RecyclerView having approx 100 items and third having approx 400 items. Then it takes 4-5 seconds to render the view after adding data to arraylist and notifiedDataSetChanged(). Every RecyclerView is in vertical. So if there any solution for this please explain
if(!itemsList.isEmpty()) {itemsList.clear();}
itemsList.addAll(itemData);
itemAdapter.notifyDataSetChanged();

A: Recyclerview inside nested scrollview does complete layout at a single load rather than usual recyclerview behaviour, try to remove nested scrollview from layout, use recyclerview with different view types.


Q: python xml elementtree wrap text by number of characters I'm wondering in xml elementtree how to wrap the text?
For instance, I have the following text
4324OO234324O234O32O423423OO23O432O4OO23O4O32O423O423O4O234OO234234O234OO324O234

And I need to make sure that it wraps the text for every 10 characters e.g.
However, I also need to preserve the tabs/whitespace that is happening after each line.
<mydata>
        4324OO2343
        24O234O32O
        423423OO23
        O432O4OO2
        3O4O32O42
        3O423O4O2
        34OO234234
        O234OO324
        O234
</mydata>

Any idea of any easy way to do this in python 2.5.2?
This is not a replicate question, because this is xml elementtree specific... It might be possible to break the chars up into chunks, but then I have to use minidom.parseString and toprettyxml, to get the tabs - but I havent found a way to do it yet –

A: The poster that voted to close this question was not correct and didn't provide help towards a solution. The duplicate thread only provided part of the solution, which is not useful in this case.
In the end I resolved it the following way:
hexerre = re.sub("(.{80})", "\1\n\t\t\t\t\t\t\t", hexer, 0)
By adding the tabs into the regex expression I was able to get the indentation needed.


Q: Sencha Extjs 6.2 : Edit object values in cell grid I have a grid and in the last two columns (Chourly and Cdaily), each cell contains an object.
Example of data :
{
    data: [{
        Date: "2018/01/11 21:00:00",
        Ahourly: "1",
        Chourly: {
            val: 2,
            status: "Low",
            color: "#ffff00"
        }
    }, ...
    success: true
}

Here is my fiddle, see Chourly and Cdaily columns.
I need to edit data of this object and display the new values.
I tried to use beforeedit end validateedit but for now no success !
Any help ?
Thanks,
mpe

A: First thing to do is to adjust your data model in the store.
Use "mapping" to accommodate all the fields in object field into individual fields,
like that:
 var store = Ext.create('Ext.data.JsonStore', {
        fields: [
            'Date',
            'Ahourly',
            {name:'ChourlyVal',mapping:'Chourly.val'},
            {name:'ChourlyColor',mapping:'Chourly.color'},
            {name:'ChourlyStatus',mapping:'Chourly.status'},
            {name:'CdailyVal' ,mapping:'Cdaily.val'},
            {name:'CdailyColor' ,mapping:'Cdaily.color'},
            {name:'CdailyStatus' ,mapping:'Cdaily.status'}
            ],
        proxy: {
            type: 'ajax',
            url: 'data1.json',
            reader: {
                type: 'json',
                rootProperty: 'data'
            }
        },
        autoLoad: true
    });

And than, adjust the column and the renderer to use the mapped fields:
 {
            text: 'Chourly',
            dataIndex: 'ChourlyVal',
            flex: 1,
            renderer: function (a, meta, record) {
                console.log(record);
                meta.tdStyle = "background-color:" + record.data.ChourlyColor + ";";
                var cellText = a + " " + record.data.ChourlyStatus;
                return cellText;
            },
            editor: 'textfield'
        }

I hope that helps

A: Thanks for your reply. I think its the good way.
Then I think I have to use the serialize function to put the object back together with the modified value(s) to send back to the server like this :
fields: ['Date', {
                name: 'Chourly',
                serialize: function (val, rec) {
                    return {
                        'val': rec.get('val'),
                        'status': rec.get('status'),
                        'color': rec.get('color')
                    };
                }
            }, {
                name: 'val',
                mapping: 'Chourly.val',
                persist: false //Do not write back to server
            }, {
                name: 'status',
                mapping: 'Chourly.status',
                persist: false

            }, {
                name: 'color',
                mapping: 'Chourly.color',
                persist: false

            },
            ...
        ]...

Now I have to do that dynamically because I don't know in advance which data the user will consult (Chourly, Dhourly, Ehourly ....). Any idea to modify the model on the load callback ?


Q: Limit root node processing in CPLEX Python I have a very large problem (1m variables, 3m constraints) that I'm trying to solve using CPLEX in Python. Obviously, solving it optimally is out of the question, so I have implemented a time limit so I could get the best solution within that time.
c.timelimit.set(7200)

However, when the time was up, it hadn't even finished processing the root node:
        Nodes                                         Cuts/
 Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

  0     0       10.0070  2177                     10.0070    65714
  0     0       10.0070  1793                    Cuts: 29    80275
  0     0       10.0070  2427                  Cuts: 6928   101277
  0     0       10.0070  2061                  Cuts: 4737   122524
Implied bound cuts applied:  485
Flow cuts applied:  68
Mixed integer rounding cuts applied:  12019
Zero-half cuts applied:  193

Root node processing (before b&c):
  Real time             = 7200.47 sec. (2762999.79 ticks)
Parallel b&c, 112 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                          ------------
Total (root+branch&cut) = 7200.47 sec. (2762999.79 ticks)
Solution status =  108 :
MIP_time_limit_infeasible
Exception raised during solve

Is there any way to limit the time spent on the root node so it at least starts the b&c method? Would that even be advantageous at all?


Q: HSQL database user lacks privilege or object not found error I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.
I created data base using the following details
Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA

I created a table named ALBUM under "MYDB" schema
In spring configuration file:
<bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dbcpDataSource" />
</bean>

<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:file:mydb" />
    <property name="username" value="SA" />
    <property name="password" value="SA" />
</bean>

And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());
And It gives me exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

If I execute same query through SQL editor of hsqldb it executes fine.  Can you please help me with this.

A: I had the error user lacks privilege or object not found while trying to create a table in an empty in-memory database.
I used spring.datasource.schema and the problem was that I missed a semicolon in my SQL file after the "CREATE TABLE"-Statement (which was followed by "CREATE INDEX").

A: As said by a previous response there is many possible causes. One of them is that the table isn't created because of syntax incompatibility. If specific DB vendor syntax or specific capability is used,  HSQLDB will not recognize it. Then while the creation code is executed you could see that the table is not created for this syntax reason. For exemple if the entity is annoted with @Column(columnDefinition = "TEXT") the creation of the table will fail.
There is a work around which tell to HSQLDB to be in a compatible mode
for pgsl you should append your connection url with that
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true"

and for mysql with
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_mys=true"

oracle
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_ora=true"

note there is variant depending on your configuration
it could be hibernate.connection.url= or spring.datasource.url=
for those who don't use the hibernate schema creation but a SQL script you should use this kind of syntax in your script
SET DATABASE SQL SYNTAX ORA TRUE;

It will also fix issues due to vendor specific syntax in SQL request such as array_agg for posgresql
Nota bene : The the problem occurs very early when the code parse the model to create the schema and then is hidden in many lines of logs, then the unitTested code crash with a confusing and obscure exception "user lacks privilege or object not found error" which does not point the real problem at all. So make sure to read all the trace from the beginning and fix all possible issues

A: If you've tried all the other answers on this question, then it is most likely that you are facing a case-sensitivity issue.
HSQLDB is case-sensitive by default. If you don't specify the double quotes around the name of a schema or column or table, then it will by default convert that to uppercase. If your object has been created in uppercase, then you are in luck. If it is in lowercase, then you will have to surround your object name with double quotes.
For example:
CREATE MEMORY TABLE "t1"("product_id" INTEGER NOT NULL)

To select from this table you will have to use the following query
select "product_id" from "t1"

A: user lacks privilege or object not found can have multiple causes, the most obvious being you're accessing a table that does not exist. A less evident reason is that, when you run your code, the connection to a file database URL actually can create a DB. The scenario you're experiencing might be you've set up a DB using HSQL Database Manager, added tables and rows, but it's not this specific instance your Java code is using. You may want to check that you don't have multiple copies of these files: mydb.log, mydb.lck, mydb.properties, etc in your workspace. In the case your Java code did create those files, the location depends on how you run your program. In a Maven project run inside Netbeans for example, the files are stored alongside the pom.xml.

A: I had similar issue with the error 'org.hsqldb.HsqlException: user lacks privilege or object not found: DAYS_BETWEEN' turned out DAYS_BETWEEN is not recognized by hsqldb as a function. use DATEDIFF instead.
DATEDIFF ( <datetime value expr 1>, <datetime value expr 2> )

A: When running a HSWLDB server. for example your java config file has:
hsql.jdbc.url = jdbc:hsqldb:hsql://localhost:9005/YOURDB;sql.enforce_strict_size=true;hsqldb.tx=mvcc
check to make sure that your set a server.dbname.#. for example my server.properties file:
    server.database.0=eventsdb
    server.dbname.0=eventsdb
    server.port=9005

A: I was inserting the data in hsql db using following script
INSERT INTO Greeting (text) VALUES ("Hello World");

I was getting issue related to the Hello World object not found and HSQL database user lacks privilege or object not found error
which I changed into the below script
INSERT INTO Greeting (text) VALUES ('Hello World');

And now it is working fine.

A: Add these two extra properties:
spring.jpa.hibernate.naming.implicit-strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl

spring.jpa.hibernate.naming.physical-strategy=
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

A: I bumped into kind of the same problem recently. We are running a grails application and someone inserted a SQL script into the BootStrap file (that's the entry point for grails). That script was supposed to be run only in the production environment, however because of bad logic it was running in test as well. So the error I got was:
User lacks privilege or object not found:

without any more clarification...
I just had to make sure the script was not run in the test environment and it fixed the problem for me, though it took me 3 hours to figure it out. I know it is very, very specific issue but still if I can save someone a couple of hours of code digging that would be great.

A: I was having the same mistake. In my case I was forgetting to put the apas in the strings.
I was doing String test = "inputTest";
The correct one is String test = "'inputTest'";
The error was occurring when I was trying to put something in the database
connection.createStatement.execute("INSERT INTO tableTest values(" + test +")";

In my case, just put the quotation marks ' to correct the error.

A: In my case the error occured because i did NOT put the TABLE_NAME into double quotes "TABLE_NAME" and had the oracle schema prefix.
Not working:
SELECT * FROM FOOSCHEMA.BAR_TABLE

Working:
SELECT * FROM "BAR_TABLE"

A: had this issue with concatenating variables in insert statement. this worked
// var1, var3, var4 are String variables
// var2 and var5 are Integer variables
result = statement.executeUpdate("INSERT INTO newTable VALUES ('"+var1+"',"+var2+",'"+var3+"','"+var4+"',"+var5 +")");

A: In my case the issue was caused by the absence (I'd commented it out by mistake) of the following line in persistence.xml:
<property name="hibernate.hbm2ddl.auto" value="update"/>

which prevented Hibernate from emitting the DDL to create the required schema elements...
(different Hibernate wrappers will have different mechanisms to specify properties; I'm using JPA here)

A: I had this error while trying to run my application without specifying the "Path" field in Intellij IDEA data source (database) properties. Everything else was configured correctly.
I was able to run scripts in IDEA database console and they executed correctly, but without giving a path to the IDEA, it was unable to identify where to connect, which caused errors.

A: You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege.
Also change the url of database in spring configuration file accordingly when running DB in server mode.
Sample command to run DB in server mode
$java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test
Format of URL in configuration file
jdbc:hsqldb:hsql://localhost/Test

A: In my case, one of the columns had the name 'key' with the missing @Column(name = "key") annotation so that in the logs you could see the query that created the table but in fact it was not there. So be careful with column names

A: For what it's worth - I had this same problem.  I had a column named 'TYPE', which I renamed to 'XTYPE' and a column named ORDER which I renamed to 'XORDER' and the problem went away.

A: Yet another reason could be a misspelt field name. If your actual table has an id column named albumid and you'd used album_id, then too this could occur.
As another anwer remarked, case differences in field names too need to be taken care of.

A: I faced the same issue and found there was more than one PersistenceUnit (ReadOnly and ReadWrite) , So the tables in HSQLDDB created using a schema from one persistence unit resulted in exception(HSQL database user lacks privilege or object not found error) being thrown when accessed from other persistence unit .It happens when tables are created from one session in JPA and accessed from another session

A: In my case the table MY_TABLE was in the schema SOME_SCHEMA. So calling select/insert etc. directly didn't work. To fix:

*

*add file schema.sql to the resources folder

*in this file add the line CREATE SCHEMA YOUR_SCHEMA_NAME;


Q: How to handle a GET request in python I have some microservices running in kubernetes, and they need to pass some data among each other, but I can't handle the GET request from the server side.
The docs I found are very focused on how to make the GET request on python, but not how to handle it.
So, this is what I tried:
from flask import Flask
from flask import request
import requests

app = Flask(__name__)

@app.route('/<trace_id>')
def root():
    return trace_id

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8080, debug=True)

From the client, I do the request like this:
>>> trace_id = '54b012b2767e7b21321ca649872913c5'
>>> requests.get('http://my-service', params=trace_id)
<Response [404]>

And on my server I get this dumped:
/# python3 app.py
 * Serving Flask app "app" (lazy loading)
 ...
10.52.2.29 - - [29/Nov/2019 18:41:23] "GET /?54b012b2767e7b21321ca649872913c5 HTTP/1.1" 404 -

I would like to know how to handle the request on the server side. Also, it would be nice to get some suggestions of what's the best way of dealing with this.

Note: there is a k8s service in front of the server that gets the
  requests on port 80 and forward them to 8080.

A: You need to pass trace_id as input argument
def root(trace_id):
    return trace_id

And trace_id is part of the url, not the query part:
requests.get('http://my-service/' + trace_id)

A: We have to look closer at your code.
@app.route('/<trace_id>')

String argument inside brackets is a path part after 'http://my_service/'.
Full path of this API endpoint will be 'http://my_service/value_of_trace_id'.
And this part 'value_of_trace_id' will be stored as 'trace_id' variable and passed to function body so you have to pass it as function (API endpoint) arg.
@app.route('/<trace_id>')
def api_endpoint(trace_id):
    return trace_id

So, you have to use:
requests.get('http://my-service/' + trace_id)

I highly recommend read that or that.


Q: modifying softmax function in tensorflow I started using tensorflow about a week ago, so I'm not sure what API can I use.
Currently I'm using basic mnist number recognition code.
I want to test how recognition precision of this code changes if I modify the softmax function from floating point calculation to fixed point calculation.
At first I tried to modify the library but it was too complicated to do so. So I  think I have to read tensors and modify(calculate) it in the form of array and change it to the tensor using tf.Session().eval() function.
Which function should I use?
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

import tensorflow as tf

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
#temp = tf.Variable(tf.zeros([784, 10]))
temp = tf.Variable(tf.matmul(x, W) + b)
#temp = tf.add(tf.matmul(x, W),b)

y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#print(temp[500])

for i in range(100):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


Q: Start Segue After Completion Of Social Sharing I want to let users share some posts from my app with the help of the social framework. But after the post button in the social framework, the segue is not starting. How can I handle this?
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)

A: You have to present the view controller in this method
var completionHandler: SLComposeViewControllerCompletionHandler!

You can use the above method like this
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
shareToFacebook.completionHandler = {
    (result:SLComposeViewControllerResult) in

    }
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)


Q: How to store HTML form value for other pages in PHP and MySQLi? I have created a database in phpMyAdmin with table for topics such as Math, Physics etc. Each topic has a topic_id as primary key in table tb_topic. Each topic can have multiple videos. Admin can add videos to each topic which requires topic_id as foreign key in table tb_video_management to store videos against a topic.
Backend:
There is a button to add videos in form.php
form.php:
<?php
    $query = "SELECT topic_id, topic_name,aid FROM tb_topic";
    $result = $con->query($query);
    while($query_row = mysqli_fetch_assoc($result)) {?>

            <form action='edit.php' method='get'>
                <button type='submit' name='edit' id = 'edit' value='<?php echo $query_row['topic_id'];?>' class='btn btn-success'>EDIT</button>

            </form>

    <?php
    } ?>

When this button is clicked, page is navigated to another page "edit.php" which has 2 buttons, one for add new video and second for viewing video gallery.
edit.php:
$id = $_GET['edit'];
echo 'topic id----> ' . $id;

<form action='add_video.php' method='get'>
    <button type='submit' name='add' id = 'add' value='<?php echo $id;?>' class='btn btn-success'>ADD NEW VIDEO</button>
</form>
<form action="video.php" method="get">
    <button type="submit" name="goback" id="goback" value="submit" class="btn btn-primary">VIEW GALLERY</button>
</form>

The class where videos are added has a form for topic name, details etc.
add_video.php
$id = $_GET['add'];
echo 'topic id----> ' . $id;

<form action="add_video.php" method="post">
        Video Title: <input type="text" name="video_name">

        Video Detail: <input type="text" name="video_detail">

        Video Question: <input type="text" name="video_question">

        Video Link: <input type="text" name="video_link">

        <input type="submit" name="submit" value = "Submit">

</form>

When "submit" button is clicked, following code executes:
if(isset($_POST['submit'])) {

    if(!(empty($_POST['video_name']) || empty($_POST['video_detail']) || empty($_POST['video_question']) || empty($_POST['video_link']))) {
        $name = $_POST['video_name'];
        $detail = $_POST['video_detail'];
        $question = $_POST['video_question'];
        $link = $_POST['video_link'];
        $insert = "INSERT INTO tb_video_management(topic_id, video_name, video_detail, video_question,video_link) VALUES ('$id','$name','$detail', '$question','$link')";
        if(!mysqli_query($con,$insert))
            echo "error";
        header('location:edit.php');
    }
}

The problem I am facing is, when I click submit button, the value in $id is lost (may be because another button (submit) is pressed) and it fails to insert the record as there is no value for "topic_id" anymore. I cannot resolve this issue of keeping foreign key value even after pressing submit button.
So far I have been creating extra table to hold value for topic_id which is definitely not the right approach.

A: To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field.
You may set the value of $id like:
<input type="hidden" name="topic_id" value="<?php echo $id?>">

Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail.
On submit look like:
if(isset($_POST['submit'])) {
    $topic_id = $_POST['topic_id'];
}


Q: Data structure and algorithms: Should one use OOP to program algorithms? I have seen people code for example, say a quicksort algorithm without using OOP. I have also seen the identical algorithm in Robert Lafore's data structure and algorithm textbook written under OOP framework.
Is it better to do it using OOP  ? What are the advantages or disadvantages?
Suppose I know how to write an algorithm in both ways, should I always do it the OOP way ? Or does it depend on the algorithm itself ? If yes, then what algorithms would using OOP be beneficial ?


Q: Can't get TinyMCE 4.0.6 to work This is driving me crazy....
I'm trying to get TinyMCE v4.0.6 to work, and I'm probably doing something very dumb, since I can't get the editor to display at all.
I could get a v3.5.8 editor to show in a page similar to what follows, but no joy with this:
<!DOCTYPE html>
<html>
<head>
<title>TinyMCE Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="tinymce/tinymce.min.js"></script>
<script type="text/javascript">
    tinymce.init({
        selector: "textarea"
    });
</script>
</head>
<body>
<form method="post" action="something">
    <textarea name="content" cols="100" rows="15">content</textarea>
    <input type="submit" value="Save" />
</form>
</body>
</html>

I've verified (using FireBug) that the path to the tinymce JavaScript file is correct, but other than that, I'm completely at a loss.
Thanks for any suggestions..

A: After your comment, I took your HTML and checked it with a CDN copy of tinyMCE and it work fine: http://codepen.io/anon/pen/mIvFg so I can only assume it's an error with your tinymce.min.js file.


Q: Problems with an extra space when redirecting variables into a text file When I run the following lines:
set "Loc=%~dp0"
echo %Loc% > C:\PLACE\LOCFILE.txt

I receive the following in the LOCFILE:
C:\BATCHLOC
           ^
       Note Space

I am trying to use %Loc% like this in a separate batch file:
(
set /p Loc=
)<C:\PLACE\LOCFILE.txt
)
call "%Loc%\FILENAME.bat"

But the space ruins the path, and so then the call command doesn't work. Does anyone know how to fix this, (Stop it from creating the space at the end)?

A: echo %Loc% > C:\PLACE\LOCFILE.txt
          ↑
     This space is written to the file.

Fix:
echo %Loc%> C:\PLACE\LOCFILE.txt

A: This is more robust.
>"C:\PLACE\LOCFILE.txt" echo(%Loc%

The redirection at the starts stops numbers like 3,4,5 in %loc% from breaking your code when redirection is directly at the end (such as shown below).
When using the technique below then constructs like test 2 in %loc% will also fail.
This is because single digit numbers at the end are interpreted as stream designators, so numerals 0 to 9 are all problems when placed directly before a redirection character (> or >>).
do not use this: echo %Loc%> C:\PLACE\LOCFILE.txt
Extra tips:
The echo( protects from other failures in the echo command and the ( character has been tested as the least problematic character when used in this way.
The double quotes around the "drive:\path\filename" also protect against long filename elements such as spaces, as well as the & character.


Q: TextView.setMaxLines not working? In my app I have a screen where I display some text and then a photo. The text is variable in length (sometimes none at all, sometimes a lot), so I wanted to have it set up so the text never takes up more than a few lines (but can be scrolled) leaving enough room for the image below.
My view component for this part is created programatically, and I've adjusted the code to have the following (currently in my text-setting method, but the same thing happens if it's in the initial view-create code)
public void SetDescription(String description)
{
    mTxtDescription.setText(Html.fromHtml(description));
    mTxtDescription.setClickable(true);
    mTxtDescription.setMaxLines(5);
    mTxtDescription.setLines(5); //this makes no difference either!
    mTxtDescription.setSingleLine(false);
    mTxtDescription.setScrollbarFadingEnabled(true);
    mTxtDescription.setScrollBarStyle(VERTICAL);
    mTxtDescription.setMovementMethod(ScrollingMovementMethod.getInstance());
    mTxtDescription.invalidate(); //adding this made no difference...
}

However it doesn't work- long text still fills the whole screen and the image has vanished due to being pushed down to a height of 0. How can I get the text to never be more than 5 lines?

A: Try removing the call to setSingleLine. And use setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE). It'd also put this call before the setMaxLines and setLines call to be sure.
Note: setLines overrides the settings of setMaxLines and setMinLines.
The TextView has many issues surrounding the various calls to how it should display multiple, ellipses, etc.

A: The setSingleLine(false) seemes to reset the setMaxLines command. Try to move the setSingleLine command before the setText. That worked for me.

A: The below code is working fine for me
   txt = (TextView)findViewById(R.id.textview);
   txt.setMaxLines(5);
   txt.setMovementMethod(new ScrollingMovementMethod());

   txt.setScrollContainer(true);
   txt.setText("Example Text");
   txt.setTextColor(Color.WHITE);
   txt.setScrollbarFadingEnabled(true);

in xml inside textview
   android:scrollbars="vertical"


Q: Variable Scopes Within PowerShell Nested Functions I was given this extensive PowerShell script from a major/reputable corporation which was supposed to work flawlessly. Well, it didn't.
The script is composed of numerous nested functions with lots of variables passed to the main parent function and then to all of its children. Children who use and modify all these variables.
Why is it that all these variables do not contain the correct data?
Here's the structure I'm talking about:
f1 {
     f2 {
          v #prints 0
          v = 1
          f3
     }
     f3 {
          v #prints 1
          v = 2
     }
     v = 0
     f2
     v #should print 2 but prints 0
}

A: Note:
This was tested with PowerShell 3.0 and 4.0.
Within nested functions, all child functions have access to all of the parent functions' variables. Any changes to the variables are visible within the local scope of the current function and all the nested child functions called afterwards. When the child function has finished execution, the variables will return to the original values before the child function was called.
In order to apply the variable changes throughout all the nested functions scopes, the variable scope type needs to be changed to AllScope:
Set-Variable -Name varName -Option AllScope

This way, no matter at what level within the nested functions the variable gets modified, the change is persistent even after the child function terminates and the parent will see the new updated value.

Normal behavior of variable scopes within Nested Functions:
function f1 ($f1v1 , $f1v2 )
{
        function f2 ()
       {
               $f2v = 2
               $f1v1 = $f2v #local modification visible within this scope and to all its children
               f3
               "f2 -> f1v2 -- " + $f1v2 #f3's change is not visible here
       }
        function f3 ()
       {
               "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
               $f3v = 3
               $f1v2 = $f3v #local assignment will not be visible to f2
               "f3 -> f1v2 -- " + $f1v2
       }

        f2
        "f1 -> f1v1 -- " + $f1v1 #the changes from f2 are not visible
        "f1 -> f1v2 -- " + $f1v2 #the changes from f3 are not visible
}

f1 1 0

Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 0
f1 -> f1v1 -- 1
f1 -> f1v2 -- 0

Nested Functions with AllScope variables:
function f1($f1v1, $f1v2)
{
    Set-Variable -Name f1v1,f1v2 -Option AllScope
    function f2()
    {
        $f2v = 2
        $f1v1 = $f2v #modification visible throughout all nested functions
        f3
        "f2 -> f1v2 -- " + $f1v2 #f3's change is visible here
    }
    function f3()
    {
        "f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
        $f3v = 3
        $f1v2 = $f3v #assignment visible throughout all nested functions
        "f3 -> f1v2 -- " + $f1v2
    }

    f2
    "f1 -> f1v1 -- " + $f1v1 #reflects the changes from f2
    "f1 -> f1v2 -- " + $f1v2 #reflects the changes from f3
}

f1 1 0

Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 3
f1 -> f1v1 -- 2
f1 -> f1v2 -- 3


Q: One to one function in R to change number to text I have quite long list of postal codes with corresponding name of city or town. I just want to write a R program that has postal code as input variable and returns the name of the location (city or town). The list will be finite in length and has about 40 different pairs of postal code and location name. What is the best way to do this?

A: myProg<-function(code) db$city[db$code==code]

A: This is a filtering question. There are a number of ways to filter data in R. Here's what you need to do:

*

*Put your data in a data.frame

*Try filtering it:

*Now make it a function (this is your program)

*Use the function

postal_codes <- data.frame(code = c(78754, 84606), location = c("Austin", "Provo"))
postal_codes[postal_codes$code %in% 78754, ]
postal_finder <- function(mycode) {
  postal_codes$location[postal_codes$code %in% mycode]
}

postal_finder(78754)


Q: ExpressJS app.use("/" router) router.get("/") Breaks I'm not sure how to phrase this, but part of the following code, for lack of an appropriate term, doesn't work. If I try to go to localhost:3000/ it doesn't send back a response. I'm using Express 4.7.4 and the latest node available on the Ubuntu Trusty repository.
app.js

///// Dependencies & config
var express = require('express');

///// Bootstrapping
//// Prepare Express
var server = express();

/// Configure Express
server.set('views', __dirname + '/views');

/// Routers
var infoR = express.Router();

// This doesn't send anything back
infoR.get("/", function(req, res) {
  res.render('common/home');
});
// This works perfectly
infoR.get("/something", function(req, res) {
  res.render('info/something');
});

// Routes that work
server.use('/admin', require('./routes/admin'));
server.use('/account', require('./routes/account'));
server.use('/', infoR); // This is where the problem starts

///// Start the server
server.listen(3000, function() {
  console.log('Server started on port 3000');
});

A: Fixed by updating Express to version 4.9.
Edit: Turns out I've been doing it wrong, as noted in the documentation.


Q: EXC_BREAKPOINT in Swift I set up a var tagTextField: UITextField in the a set up method. Later when I call a method where I want to do something with this var tagTextField: UITextField, namely:
var pos1 = tagTextField.positionFromPosition(tagTextField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 0)

I get the following Error:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1000e4280)

I tried to just see if the var tagTextField: UITextField == nil, but then I get the same Error. Any suggestions why this is? If you need more code, let me know.
Thanks in advance
edit:
here is the error. no breakpoint

A: You set a breakpoint on Xcode (probably by mistake when trying to access to a specific line).
Breakpoints are represented by blue tabs and allow you to stop the execution of your code to check some variable states for instance. Just click on it again to deactivate it (it will turn light blue).

A: You've set some sort of user-breakpoint.
All user-set breakpoints show up in the Breakpoint Navigator:

If your Xcode doesn't say "No Breakpoints" here, you have breakpoints.  Good news is, you can manage all your breakpoints from this tab.  You can delete them, or create new ones.
Click the plus sign at the bottom lets you add different sorts of breakpoints here.


Q: using #define to substitute in a continuous string I am trying to write a Macro for certain read/write functions. The functions are in the form
k_target_socket.write8(address,val);

When I tried #define Wx(add,val) k_target_socket.writex(address,val) I got   W8(0x100,0x120); for   W8(0x100,0x120); then I replace the macro with  #define W(x,add,val) & then got k_target_socket.writex(0x100,0x120); Is there a way to substitute for x in the above two examples?

A: What you need is token pasting. try the following:
#define W(x,ad,val) k_target_socket.write##x(ad,val)

The ## will paste the x with the function name.
More details here


Q: Movable Panel control using C# I'm trying to make my panel control movable using c#, but my main form moves along with the panel control when dragging. Is there a better code for this?
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCaptre();

public static void _MOVE_PANEL(IntPtr Handle, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
       ReleaseCaptre();
       SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
    }
}

private void sub_inv_pcount_edit_MouseMove(object sender, MouseEventArgs e) //panel move
{
    _MOVE_PANEL(Handle, e);
}

see sample: see screenshot

A: I'm afraid this is not an approach you can tweak to get the result you want. WM_NCLBUTTONDOWN is essentially how the window manager decides how to handle mouse events on a top-level window. It allows you to make windows that have custom chrome, but it doesn't allow you to do anything about non-top-level windows (such as your panel).
You can get a reasonably nice-working dragging doing the obvious thing - in MouseMove, handle moving the control yourself. It's not going to be as well behaved as moving the entire window, though.


Q: Error with primary key in one-to-one relationship using Entity Framework I've created a database according to which the user profile is formed by the following two classes:
public class Usr
{
    [Key()]
    public int UsrID { get; set; }

    public virtual UsrType UsrType { get; set; }

    public virtual UsrStatus UsrStatus { get; set; }

    [Required]
    [MaxLength(100, ErrorMessage = "Email can only contain {0} characters")]
    public string UsrEmail { get; set; }

    [Required]
    [MaxLength(32, ErrorMessage = "Password can only contain {0} characters")]
    [MinLength(8, ErrorMessage = "Password must be at least {0} characters")]
    public string UsrPassword { get; set; }
}

public class UsrDetails
{
    [ForeignKey("UsrID")]
    [Required]
    public virtual Usr Usr { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Name can only contain {0} characters")]
    public string UsrName { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")]
    public string UsrSurname { get; set; }

    [Required]
    [MaxLength(20, ErrorMessage = "Country can only contain {0} characters")]
    public string UsrCountry { get; set; }

    [Required]
    [MaxLength(20, ErrorMessage = "City can only contain {0} characters")]
    public string UsrCity { get; set; }

    [Required]
    [MaxLength(40, ErrorMessage = "Street can only contain {0} characters")]
    public string UsrStreet { get; set; }

    [Required]
    public int UsrNum { get; set; }

    [Required]
    public int UsrPostalCode { get; set; }
}

I want to connect them by having both as primary key the UsrID and I get an error that UsrDetails don't have a primary key because I'm using the foreign key attribute. Any ideas?

A: You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute:
public class UsrDetails
{
    [Key]
    public int UsrID{ get; set; }

    [ForeignKey("UsrID")]
    public virtual Usr Usr { get; set; }
}

All your entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.


Q: How to make a successful batch commit when some of the docs could've been deleted? Suppose i have a structure like this:
items: {
  id1: {
    likes: 123
  },
  id2: {
    likes: 456
  },
  id3: {
    sourceId: 'id1',
    likes: 123
  },
  id4: {
    sourceId: 'id1',
    likes: 123
  }
  [,...]
}

where any item can either be a source item or an item that references a source item. The purpose of referencing the source item is to keep counters consistent across all items that share the same sourceId.
Therefore, when i change a counter on a source item, i want to batch write that counter's value to all the items that have that item as their sourceId.
My concern
Suppose I read in the docs referencing some sourceId, then i commit the changes in a batch to all of them. What if a very small subset of the docs in the batch were deleted in the small window of time since the documents were read in, or a rare but possible write-rate conflict occurs? Do none of the counters get updated because 1 or 2 documents failed to be updated?
Is it possible to submit a batch that writes the changes to each of its documents independently, such that if one fails, it has no impact on if the others get written?
Or maybe for this scenario it might be better to read in the documents referencing some sourceId and then write the changes to each document in parallel such that write independence is achieved. I don't like this approach since the number of requests would be the size of the batch.
What are your thoughts?

A: Take a careful read of the API docs for BatchWrite.  It will answer your questions.  Since you're not showing your batch code (are you using set? update?), we have to look at the API docs to assess the failure cases:

create()
This will fail the batch if a document exists at its location.

It sounds like you're probably not using create(), but this is the failure case.

set()
If the document does not exist yet, it will be created.

So, a set will not fail if the documented was deleted before the batch got committed.

update()
If the document doesn't yet exist, the update fails and the entire
  batch will be rejected.

So, if you try to update a nonexistent document, the batch will fail.
If you want to decide what to do with each document, depending on its existence and contents, then control the failure cases, use a transaction.

A: If I understand your question, I had a similar scenario and here's how I did it. First, I use generated universal ID's, uid's, for all my item keys/id's. Then, what you do is on the grandchildren, simply write the uid of the parent it is associated with. Each grandchild could be associated with more than one parent.
As you create new items, you have to recursively update the parent with the uid of the item so the parent has record of all its associated child items.
    fetchPromise = [];
    fetchArray = [];
    if(!selectIsEmpty("order-panel-one-series-select") || !selectIsUnselected(orderPanelOneSeriesSelect)){
        orderPanelOneTitle.innerHTML = "Select " + orderPanelOneSeriesSelect.value.toString().toUpperCase() + " Option";
    }
    //on change we need to populate option select based on this value
    //now we need to get the particular series doc and fill get array then prmise all to get all options

    familyuid = getRecordFromList(doc.getElementById("order-panel-one-family-select"),orderPanelOneFamilySelect.selectedIndex);
    seriesuid = getRecordFromList(doc.getElementById("order-panel-one-series-select"),orderPanelOneSeriesSelect.selectedIndex);
    optionuid = getRecordFromList(doc.getElementById("order-panel-one-option-select"),orderPanelOneOptionsSelect.selectedIndex);
    optionRef = db.collection("products").doc(familyuid).collection("option");
    itemRef = db.collection("products").doc(familyuid).collection("item");
    targetRef = db.collection("products").doc(familyuid).collection("option").doc(optionuid);
    try {
        targetRef.get().then(function(snap) {
            if (snap.exists) {
                for (var key in snap.data()) {
                    if (snap.data().hasOwnProperty(key)) {
                        fetchPromise = itemRef.doc(key).get();
                        fetchArray.push(fetchPromise);
                    }
                }
                Promise.all(fetchArray).then(function(values) {
                    populateSelectFromQueryValues(values,"order-panel-one-item-select");
                    if(!selectIsEmpty("order-panel-one-item-select")){
                        enableSelect("order-panel-one-item-select");
                    }
                    targetRef.get().then(function(snap){
                        if(snap.data().name){
                            var str = snap.data().name.toString();
                            orderAsideInfo.innerHTML = "Select " + capitalizeFirstLetter(str) + " item.";
                        }
                    });
                });
            }
        }).catch(function(error) {
            toast("error check console");
            console.log("Error getting document:", error);
        });
    }


Q: Quartz CronTrigger expression between two dates Is there a way to write a Quartz CronTrigger expression that runs every day between two dates, for example starts at 11am 5th of Sep 2011 and ends at 11am 10th of June 2012?

A: Use an expression that means every day at 11:00am  e.g.  "0 0 11 * * ?".
Then set the startTime of the trigger to 5th of Sep 2011 10:59 am, and set the endTime of the trigger to 10th of June 2012  11:01 am.

A: Another solution I found is to specify a route policy (SimpleScheduledRoutePolicy) for the scheduled route and set the RouteStartDate and setRouteStopDate for this policy object.

A: A single cron expression doesn't facilitate running different schedules for the same period type, no matter which period is concerned, your differing schedule being the year period.
However other than your year difference all other periods have the same schedule. So... using these cron expressions:
cron1 = "0 0 23 5/1 SEP-DEC ? 2012"
cron2 = "0 0 23 1/1 JAN-JUN ? 2013"
you can switch the scheduler from using cron1 to cron2 sometime after 11:00.00 PM on 12/31/2012 but before 10:59.99 PM on 1/1/2013, though I wouldn't cut it so close as shown here. If you scheduler is reading its cron expression from the database or a configuration somewhere then just have it read in a new schedule every day at 11:30 PM. If you are storing your cron expressions in a database you could schedule to have a scheduler swap out the cron expression for your particular task using this chron3 below:
cron3 = "0 0 0 1 JAN ? 2013"
Silly me :o) today's date is Mar 13, 2013 so I'm sure this answer is a bit late for you!


Q: C# Console not writing object string I'm trying to get the console to write a string that is part of a object, however the console leaves the string portion blank.
This is how i am getting the information:
Console.WriteLine("Please Enter an Agent Name: ");
agent1 = (Console.ReadLine());

Console.WriteLine("Please Enter " + agent1 + "'s Number of Customers: ");
ID1 = int.Parse(Console.ReadLine());

Then passing the variable agent 1 into a class i created:
Insurance Agent1 = new Insurance(agent1, ID1);

Then im tryting to tell the console to write out the agent's name and customer number:
Console.WriteLine("Agent 1 Name: "+ Agent1.Agent +" , Agent 1 Number of Customers: " + Agent1.Customers +".");

However, the console writes the customer number, which is an int, but not the string agent.

Please Enter an Agent Name: Test Please Enter Test's Number of
  Customers: 12
Agent 1 Name:  , Agent 1 Number of Customers: 12.

Any idea on how to get this to work?
EDIT:
This is the insurance class for reference:
class Insurance
{
    private string _Agent; //String for _Agent because it will be a series of letters
    private int _Customers; //Int for _Customers because it will be a whole number

    public Insurance (string Agent, int Customers)
    {
        this.Agent = Agent;
        this.Customers = Customers;
    }

    public string Agent
    {
        get { return _Agent; }
        set { _Agent = Agent; }
    }

    public int Customers
    {
        get { return _Customers; }
        set //Only set _Customers if the value is larger or equal to zero, if less than zero (negative) set to zero
        {
            if (value >= 0)
            {
                _Customers = value;
            } else if (value < 0) {
                _Customers = 0;
            }
        }
    }
}

A: Your "set" accessor is setup incorrectly. It's setting the value of _Agent to Agent, which calls the "get" on the property itself. The "getter" for Agent returns the _Agent field which is null.
Use value instead:
public string Agent
{
    get { return _Agent; }
    set { _Agent = value; }
}

Also, if I may, here's a few other suggestions on trimming down that class. But take it with a grain of salt, especially if you're just learning.
class Insurance
{
    private int customers;

    public Insurance(string agent, int customers)
    {
        Agent = Agent;
        Customers = Customers;
    }

    public string Agent { get; set; }

    public int Customers
    {
        get { return customers; }
        set { customers = Math.Max(value, 0); }
    }
}


Q: python Discord Bot how to send messages from one channel to another async def on_message(message):
    if message.channel == (720020927668289588):
        await Bot.get_channel(703707652710072515).send(f"{message.author.name}: {message}")
    await Bot.process_commands(message)

I am trying to have the bot to when someone sends a msg in channel 1 it will send the message to channel 2
I When i type into channel 1 nothing happens and no msg is send to channel 2 and there is no errors in the console
I have got it sorted

A: message.channel returns a channel object, you're trying to get the id. You can replace message.channel with message.channel.id to get the channel id. Then the code will work.


Q: custom iOS PWA background color instead of splash screen I don't want to show any custom splash screen for every device. Instead I'd like to just change the default ios black background to my custom background color (e.g. #89CFF0) and show it on every device without long list of links <link rel="apple-touch-startup-image" media="screen and (device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" href="/assets/splash_screens/10.2_iPad_portrait.png"> ....
How can I get it?


Q: Why is my random number generator becoming an unused assignment when using it to input values for 2d array? I have been making a basic game of battleship and to get the CPU to choose ship locations on a 2d array I am making two random number generators to pick values from 1 to 8 on a separate method. For some reason, the random generators show up as unused and I don't know why. so far this is what I have. If anyone knows what I'm doing wrong please let me know.
//calls method
board3 = CPUship(board3);
//displays result of method
for (int i = 0; i < board3.length; i++) {
    for (int j = 0; j < board3.length; j++) {
        System.out.print(board3[i][j]);
    }
    System.out.println("");
}

public static String[][] CPUship(String[][] board3) {
    int rowGenerate;
    int colGenerate;
    boolean valid2 = false;
    for (int CPUships = 0; CPUships < 6; CPUships++) {
        while (!valid2) {
            rowGenerate = (int) (9 * Math.random() + 0);
            colGenerate = (int) (9 * Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase("#")) {
                board3[rowGenerate][colGenerate] = "#";
                valid2 = true;
            }
        }
        valid2 = false;
    }
    return board3;
}

A: Here should be a complete code
public static String[][] CPUship(String[][]board3){
    int rowGenerate;
    int colGenerate;

    for (int CPUships = 0; CPUships < 6; CPUships++) {
        boolean valid2=false;
        while (!valid2){ //instead of valid = false "
            rowGenerate = (int) ( 9* Math.random() + 0);
            colGenerate = (int) ( 9* Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
                board3[rowGenerate][colGenerate]="#";
                valid2=true;
            }
            //removed the valid2=false, it does not "reset" automatically
            //removed the CPUships++ ... already done by the for loop
        }
    }
    return board3;
}

or use break instead of the valid boolean
public static String[][] CPUship(String[][]board3){
    int rowGenerate;
    int colGenerate;

    for (int CPUships = 0; CPUships < 6; CPUships++) {
        while (true){ //instead of valid = false "
            rowGenerate = (int) ( 9* Math.random() + 0);
            colGenerate = (int) ( 9* Math.random() + 0);
            if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
                board3[rowGenerate][colGenerate]="#";
                break;
            }
            //removed the valid2=false, it does not "reset" automatically
            //removed the CPUships++ ... already done by the for loop
        }
    }
    return board3;
}


Q: Can I use Environment.Username and MYSQL to verify log in?         private void btnSubmitt_Click(object sender, RoutedEventArgs e)
        {
        try
        {
            i = 0;
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select * from users where  TX_EMPLOYEE='"; (Environment.UserName) & "'";
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);

            i = Convert.ToInt32(dt.Rows.Count.ToString());
        }
        catch
        {
            MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
        }
        finally
        {
            con.Close();
        }

I would like to authenticate the user with their computer login name and the exact match that is listed in the MYSQL data table. However Environment.Username is not a valid syntax in this SQL statement.

A: This line is very very wrong:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE='"; (Environment.UserName) & "'";

It should be this:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE='" + Environment.UserName + "'";

Except, it shouldn't be like that because of SQL injection. If I could make Environment.UserName into ' or 1 = 1 or TX_EMPLOYEE = ' then your final query would become this:
Select * from users where  TX_EMPLOYEE='' or 1 = 1 or TX_EMPLOYEE = ''

Which clearly isn't what you want - somebody with no credentials being able to access this. You should instead use SQL parameters:
cmd.CommandText = "Select * from users where  TX_EMPLOYEE=?userName";
cmd.Parameters.AddWithValue("?userName", Environment.UserName);

On a separate note, I'm confused by this code:
i = Convert.ToInt32(dt.Rows.Count.ToString());

DataTable.Rows.Count is already an int, so you're converting a number to a string to a number. Why?


Q: SQL Sum with non unique date I'm trying to write a SQL query that will sum total production from the following two example tables:
Table: CaseLots
DateProduced        kgProduced
October 1, 2013     10000
October 1, 2013     10000
October 2, 2013     10000

Table: Budget
OperatingDate       BudgetHours
October 1, 2013     24
October 2, 2013     24

I would like to output a table as follows:
TotalProduction   TotalBudgetHours
30000                   48

Here is what I have for code so far:
SELECT
Sum(kgProduced) AS TotalProduction, Sum(BudgetHours) AS TotalBudgetHours
FROM
dbo.CaseLots INNER JOIN dbo.Budget ON dbo.CaseLots.DateProduced = dbo.Budget.OperatingDate
WHERE
dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

It seems that the query is double summing the budget hour in instances where more than one case lot is produced in a day. The table I'm getting is as follows:
Total Production     BudgetHours
30000                72

How do I fix this?

A: Think about what the INNER JOIN is doing.
For every row in CaseLot, its finding any row in Budget that has a matching date.
If you were to remove your aggregation statements in SQL, and just show the inner join, you would see the following result set:
DateProduced    kgProduced    OperatingDate BudgetHours
October 1, 2013    10000    October 1, 2013    24
October 1, 2013    10000    October 1, 2013    24
October 2, 2013    10000    October 2, 2013    24
(dammit StackOverflow, why don't you have Markdown for tables :( )
Running your aggregation on top of that it is easy to see how you get the 72 hours in your result.
The correct query needs to aggregate the CaseLots table first, then join onto the Budget table.
SELECT DateProduced, TotalKgProduced, SUM(BudgetHours) AS TotalBudgetHours
FROM
(
    SELECT DateProduced, SUM(kgProduced) AS TotalKgProduced
    FROM CaseLots
    GROUP BY DateProduced
) AS TotalKgProducedByDay
INNER JOIN
Budget
ON TotalKgProducedByDay.DateProduced = Budget.OperatingDate
WHERE DateProduced BETWEEN '1 Oct 2013' AND '2 Oct 2013'
GROUP BY DateProduced

A: The problem is in the INNER JOIN produces a 3 row table since the keys match on all. So there is three '24's with a sum of 72.
To fix this, it would probably be easier to split this into two queries.
SELECT Sum(kgProduced) AS TotalProduction
FROM dbo.CaseLots
WHERE dbo.CaseLots.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

LEFT JOIN

SELECT Sum(BudgetHours) AS TotalBudgetHours
FROM dbo.Budget
WHERE dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'

A: This could be easily achieved by this:
SELECT
   (SELECT SUM(kgProduced) FROM dbo.CaseLots WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02') AS TotalProduction,
   (SELECT SUM(BudgetHours) FROM dbo.Budget WHERE OperatingDate BETWEEN '2013-10-01' AND '2013-10-02') AS TotalBudgetHours

There's no need for joining the two tables.

A: Try this:
select DateProduced,TotalProduction,TotalBudgetHours from
  (select DateProduced,sum(kgProduced) as TotalProduction
  from CaseLots group by DateProduced) p
  join
  (select OperatingDate,sum(BudgetHours) as TotalBudgetHours
  from Budget group by OperatingDate) b
  on (p.DateProduced=b.OperatingDate)
where p.DateProduced between '2013-10-01' AND '2013-10-02'

A: The other answers are simpler for this particular case. However if you needed to SUM 10 different values on the CaseLots table, you'd need 10 different subqueries. The following is a general, more scaleable solution:
SELECT
    SUM(DayKgProduced) AS TotalProduction,
    SUM(BudgetHours) AS TotalBudgetHours
FROM (
    SELECT
        DateProduced,
        SUM(kgProduced) AS DayKgProduced,
    FROM dbo.CaseLots
    WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02'
    GROUP BY DateProduced
) DailyTotals
INNER JOIN dbo.Budget b ON DailyTotals.DateProduced = b.OperatingDate

First you SUM the production of each CaseLot without having to SUM the BudgetHours. If you used a SELECT * FROM in the query above you'd see:
Date        DayKgProduced  BudgetHours
2013-10-01  20000          24
2013-10-02  10000          24

But you want the overall total, so we SUM those daily values, correctly producing:
TotalProduction  TotalBudgetHours
30000            48


Q: ngx-translate if a key is missing in one of the json file replace with other json file same key I have a scenario, I have two languages files en.json & es.json I have a key in en.json file which is missed in es.json file, however, I want to replace this missing key with the en.json key how would I achieve this.
I know the way we use MissingTranslationHandler for missing keys, but I do not want to show a default text for missing keys, Although I'm doing this for a missed key from both files, in my scenario its different.
Any help would be greatly appreciated, thanks in advance!

A: Inside your app module constructor, you can tell what is the default language which you're interested in
export class AppModule {

    constructor(translate: TranslateService) {
        translate.setDefaultLang('en');
        translate.use('en');
    }
}


Q: Transfer data from aprs server to symfony database I would like to connect symfony to an "aprs-is" server.
My data are received by the "aprs" server and i would like to insert them in the database i have created in the doctrine of symfony. My entities are ready but i can't figure out how to do that.
I can make an up-link on "aprs" server to redirect the data but i don't know how to architect all that link on both side.
Here is the link of aprs-is server archi: http://he.fi/aprsc/
The informations about the aprs uplink:
    $ sudo netstat -anp|grep aprsc
tcp        0      0 192.168.5.56:50002      0.0.0.0:*               LISTEN      21864/aprsc
tcp        0      0 127.0.0.1:10151         0.0.0.0:*               LISTEN      21864/aprsc
tcp        0      0 127.0.0.1:10151         127.0.0.1:46962         ESTABLISHED 21864/aprsc
tcp        0      0 192.168.5.56:50002      192.168.5.54:34070      ESTABLISHED 21864/aprsc
tcp6       0      0 :::50002                :::*                    LISTEN      21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      865809   21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      864810   21864/aprsc
unix  3      [ ]         STREAM     CONNECTE      864811   21864/aprsc

The information about apache listener
    $ sudo netstat -anp|grep apache2
tcp6       0      0 :::10150                :::*                    LISTEN      21582/apache2

The log connection on aprs:
2018/07/31 14:32:49.091674 aprsc[21864:7f5c008b1700] INFO: HTTP thread ready.
2018/07/31 14:32:49.091682 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:49.091688 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:49.091755 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:49.091832 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:49.091840 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:49.091858 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58630
2018/07/31 14:32:49.091865 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:49.091870 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:49.121688 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): closing all existing peergroup peers
2018/07/31 14:32:49.121776 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02000
2018/07/31 14:32:49.121795 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:50.989005 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request
2018/07/31 14:32:50.989070 aprsc[21864:7f5c00890700] ERROR: 127.0.0.1:10150: Uplink's welcome message is not recognized: no # in beginning
2018/07/31 14:32:50.989098 aprsc[21864:7f5c00890700] INFO: Uplink TCP 127.0.0.1:10150 (Http) closed after 2 s: Uplink server protocol error, tx/rx 70/483 bytes 0/0 pkts, dropped 0, fd 13, worker 0
2018/07/31 14:32:50.989228 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink [0] has been closed: Uplink server protocol error
2018/07/31 14:32:50.989255 aprsc[21864:7f5c00890700] DEBUG: found the link to disconnect
2018/07/31 14:32:53.096709 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:53.096795 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:53.096970 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:53.097139 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:53.097177 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:53.097275 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58632
2018/07/31 14:32:53.097305 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:53.097324 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:53.126840 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02030
2018/07/31 14:32:53.126950 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:53.663743 aprsc[21864:7f5c008b1700] DEBUG: http status [127.0.0.1] request /status.json
2018/07/31 14:32:53.664754 aprsc[21864:7f5c008b1700] DEBUG: http_compress_gzip: compressed 7656 bytes to 1743 bytes: 22.8 %
2018/07/31 14:32:54.994428 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request

$ sudo service aprsc status
● aprsc.service - LSB: start and stop aprsc
Loaded: loaded (/etc/init.d/aprsc; generated; vendor preset: enabled)
Active: active (running) since Tue 2018-07-31 16:32:48 CEST; 20min ago
Docs: man:systemd-sysv-generator(8)
Process: 21831 ExecStop=/etc/init.d/aprsc stop (code=exited, status=0/SUCCESS)
Process: 21844 ExecStart=/etc/init.d/aprsc start (code=exited, status=0/SUCCESS)
Tasks: 8 (limit: 4915)
CGroup: /system.slice/aprsc.service
       └─21864 /opt/aprsc/sbin/aprsc -u aprsc -t /opt/aprsc -f test -e             debug -o file -r logs -c /etc/aprsc.conf

systemd[1]: Starting LSB: start and stop aprsc...
aprsc[21844]:  * Preparing chroot for APRS-IS server: aprsc chroot
aprsc[21844]:    ...done.
aprsc[21844]:  *   Checking configuration 'aprsc'
aprsc[21844]:  * Starting APRS-IS server: aprsc
aprsc[21844]:  *   Starting 'aprsc'
aprsc[21844]:    ...done.
systemd[1]: Started LSB: start and stop aprsc.

A: I have progressed a little on that subject:
What's happening is the format sent from apache to aprs-is as response is badly interpreted by aprs. The apache server send a response with a header configured in apache2.conf:
ServerTokens will return HTTP/1.1 with the version of apache after that ( the verbose depending on the option next to Servertoken )
But i can't figure out how change the value "HTTP/1.1" by "#APRS"
I've tried to change it in mod_header.c but the only file i have found is mod_header.so  ...


Q: Unfortunately, AndroidFirst has stopped I am a beginner in android application & just started building first "HelloWorld" app. i followed official tutorial and designed emulator. But when i run it, the emulator says "Unfortunately, AndroidFirst has stopped". I looked around on SO but different solutions didn't help. I am a very beginner for Android, hence can't find the bug or something like wrong/error.
following is logCat:
08-29 05:16:58.629: W/dalvikvm(1934): VFY: unable to resolve static field 1864 (ActionBarWindow) in Landroid/support/v7/appcompat/R$styleable;
08-29 05:16:58.629: D/dalvikvm(1934): VFY: replacing opcode 0x62 at 0x0004
08-29 05:16:58.649: D/AndroidRuntime(1934): Shutting down VM
08-29 05:16:58.649: W/dalvikvm(1934): threadid=1: thread exiting with uncaught exception (group=0xb1daece8)
08-29 05:16:58.669: E/AndroidRuntime(1934): FATAL EXCEPTION: main
08-29 05:16:58.669: E/AndroidRuntime(1934): Process: com.example.androidfirst, PID: 1934
08-29 05:16:58.669: E/AndroidRuntime(1934): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:106)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:99)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.example.androidfirst.MainActivity.onCreate(MainActivity.java:13)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.Activity.performCreate(Activity.java:5242)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2258)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.access$800(ActivityThread.java:138)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1209)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.os.Looper.loop(Looper.java:136)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at android.app.ActivityThread.main(ActivityThread.java:5026)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at java.lang.reflect.Method.invokeNative(Native Method)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at java.lang.reflect.Method.invoke(Method.java:515)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
08-29 05:16:58.669: E/AndroidRuntime(1934):     at dalvik.system.NativeStart.main(Native Method)
08-29 05:21:58.843: I/Process(1934): Sending signal. PID: 1934 SIG: 9

MainActivity.java Code:
package com.example.androidfirst;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidfirst"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I would be very thankful to you people!

A: For that Android Support library is required
See this image:

Then just import the v7 compact library project into your work space and add it as a library to your project
you can find it in sdk\extras\android\support\v7\appcompat where your SDK is present in directory.
After importing, select your project right click ->Properties-> Android->Add->Select app compact
click ok.

A: The problem resolve when i downloaded API-19 & re-created the AVD. On a very first attempt, the AVD shows "Hello World" the default text on emulator.


Q: reset infinite scroll with ajax content I am using the ajax infinite scroll with a comment system.  It works fine until a user posts a new comment - this breaks the infinite scroll, the 'load more items' link is still there but nothing happens when you click it.
I have seen this question: Reset / disable infinite scroll after AJAX call
I have tried to implement the destroy and bind into my success method but the loadmoreitems link is unreponsive.  How can I reset the infinite scroll after a user posts a comment with the code below?
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {

$.ajax({
    url:'ajaxrequest.php',
    data:$(this).serialize(),
    type:'POST',
    dataType: 'HTML',
    success:function(data, response){

ias.destroy();

$("#posts").fadeOut(300);
$('#posts').html(data)
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');

ias.bind();

 jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});
    },
    error:function(data){
        $("#error").show().fadeOut(5000);
    }
    });

e.preventDefault();
return false;

});
});
</script>

A: When you initialize the scroll on load make sure you have stored it in a variable called ias. Something like this
var ias = jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});

And in success method call just the ias.destroy(); and ias.bind(); methods as you have done before.
Remove the initialization that is done again in your code i.e
jQuery.ias({
  container: "#posts",
  item: ".post",
  pagination: "#pagination",
  next: ".next a"
});


Q: React stop other events on that element I have a volume element that shows the volume bar when the user hovers over it. This all works great in desktop. However to get the same functionality on mobile, the user has clicks on the volume element which also toggles the mute click event.
I am wanting to stop that mute event when the user clicks (i.e taps) on that element on mobile.
I don't want to modify the Mute or VolumeBar classes to fix this because these are generic classes in my library that the developer uses.
https://jsfiddle.net/jwm6k66c/2145/

*

*Actual: The mute click event gets fired and the volume bar opens.

*Expected: The mute click event doesn't gets fired and the volume bar opens.

Open the console -> go into mobile view (CTRL + SHIFT + M on chrome) -> click the volume button and observe the console logs.
What I have tried:
Using volumeControlOnClick to stop propogation when the volume bar's height is 0 (i.e not visible), this does not cancel the onClick though.
What I want:
To cancel the mute click event if the user clicks on the volume icon for the first time in mobile. Instead it should only show the volume bar.
const volumeControlOnClick = (e) => {
  const volumeBarContainer =
    e.currentTarget.nextElementSibling.querySelector('.jp-volume-bar-container');
  /* Stop propogation is for mobiles to stop
    triggering mute when showing volume bar */
  if (volumeBarContainer.clientHeight === 0) {
    e.stopPropagation();
    console.log("stop propogation")
  }
};

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }
    render() {
    return (

        <Mute onTouchStart={volumeControlOnClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
    render() {
    return (
      <button className="jp-mute" onClick={() => console.log("mute toggled")} onTouchStart={this.props.onTouchStart}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
    render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

React.render(<Volume />, document.getElementById('container'));

A: Here's what I ended up with. It works because onTouchStart is always calld before onClick if it's a touch event and if not's then the custom logic gets called anyway. It also fires before the hover has happened. This preserves the :hover event. e.preventDefault() did not.
let isVolumeBarVisible;

const onTouchStartMute = e => (
  isVolumeBarVisible = e.currentTarget.nextElementSibling
    .querySelector('.jp-volume-bar-container').clientHeight > 0
);

const onClickMute = () => () => {
  if (isVolumeBarVisible !== false) {
    // Do custom mute logic
  }
  isVolumeBarVisible = undefined;
};

<Mute
  aria-haspopup onTouchStart={onTouchStartMute}
  onClick={onClickMute}
>
  {/* Icon set in css*/}
</Mute>

A: What you can do is use a flag to indicate you were in a touch event before being in your mouse event, as long as you are using bubble phase. So attach a listener to your container element like this:
let isTouch = false;

const handleContainerClick = () => isTouch = false;

const handleMuteClick = () => {
  if (isTouch == false) {
    console.log("mute toggled");
  }
};

const volumeControlOnClick = () => {
  isTouch = true;
};

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return (

        <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));

If you are not using bubble phase so you can register a timeout of 100ms with the same logic above, where after 100ms you make your flag variable false again. Just add to your touchStart handler:
setTimeout(() => {isTouch = false}, 100);

EDIT: Even though touch events are supposed to be passive by default in Chrome 56, you call preventDefault() from a touchEnd event to prevent the click handler from firing. So, if you can't modify the click handler of your Mute class in any way, but you can add a touchEnd event, than you could do:
const handleTouchEnd = (e) => e.preventDefault();

const volumeControlOnClick = () => console.log("volumeControlOnClick");

class Volume extends React.Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return (

        <Mute onTouchStart={volumeControlOnClick} onTouchEnd={handleTouchEnd}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onTouchEnd={this.props.onTouchEnd} onClick={() => console.log("mute toggled")}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));

A: Try this
 render() {
        return (

        <Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}></Mute>

            <VolumeBar />

    );
  }
};

class Mute extends React.Component {
  render() {
    return (
      <button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
        {this.props.children}
      </button>
    );
  }
};

class VolumeBar extends React.Component {
  render() {
    return (

 console.log("bar moved")}>
        {this.props.children}

    );
  }
};

render(<Volume />, document.getElementById('container'));


Q: Remove the Duplicate value item from 2 same format JSON objects in Java I'm looking for a way to remove the duplicate item from two JSON objects that both have the same value.
e.g.
First object:
{
 "a":true,
 "b":true,
 "c":true,
 "d":{"i":true,"ii":true,"iii":true}
}

Second object
{
 "a":false,
 "b":true,
 "c":true,
 "d":{"i":true,"ii":true,"iii":false}
}

And after removing the duplicate, I'd like to get
First object
{
 "a":true,
 "d":{"iii":true}
}

Second object
{
 "a":false,
 "d":{"iii":false}
}

I wonder if there's a tool already provides this function
(If that couldn't detect the duplicates inside the nested value, it's ok.)

A: Found way myself, I convert the json to map and then compare to remove the duplicates. Then convert the reduced map back to json


Q: Use rvest to extract html table I am a new learner for R, I am interested in using rvest to extract html table and submit html forms.
Now, I want to get some useful information from a Chinese Website.  The url is:
http://caipiao.163.com/award/cqssc/20160513.html
I am using Windows 10 Professional with RStudio Version 0.99.896, I use Google Chrome as the web browser with XPATH helper addon.
I want to extract the main html table from the Chinese site, it contains 120 groups of information about the lottery winning number.  The first one (001) is: 98446 and  the last one (120) is: 01798; I want to extract only the numbers (001) to (120) and the winning numbers: 98446 to 01798.
I used XPATH helper and Chrome web development to get the XPATH.
I think the XPATH for the information I want is:
//html/body/article[@class='docBody clearfix']/section[@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id="mainArea"]/div[1]/table/tbody/tr[2]/td[1]

But when I run the following code in RStudio, I can not get the result I want.
The following is my code:
> library(rvest)
Loading required package: xml2
> url <- "http://caipiao.163.com/award/cqssc/20160513.html"
> xp <- "//html/body/article[@class='docBody clearfix']/section    [@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id='mainArea']/div[1]/table/tbody/tr[2]/td[1]"
>
> x <- read_html(url)
> y <- x %>% html_nodes(xpath=xp)
> y
{xml_nodeset (0)}

>

Please take a look at my code and let me know if I made any mistakes.  You can simply ignore those unknown Chinese characters, they are not important, I just want to get the numbers.
Thanks!
John

A: It's not necessary to use such a precise target selector since there's only one table element (as the other answerer also pointed out). But you don't need to leave rvest behind:
library(rvest)

URL <- "http://caipiao.163.com/award/cqssc/20160513.html"

pg <- read_html(URL)
tab <- html_table(pg, fill=TRUE)[[1]]

str(tab)

## 'data.frame': 40 obs. of  39 variables:
##  $ 期号    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ 开奖号码: chr  "9 8 4 4 6" "1 8 3 1 6" "2 9 3 5 6" "1 4 5 8 0" ...
##  ....

(SO is interpreting some of the unicode glyphs as spam so I had to remove the other columns).
The second column gets compressed via post-page-load javascript actions, so you'll need to clean that up a bit if that's the one you're going for.

A: I would use the function readHTMLTable from package XML to get the whole table, as in your website there is only one <table> element:
install.packages("XML)
library(XML)
url <- "http://caipiao.163.com/award/cqssc/20160513.html"
lotteryResults <- as.data.frame(readHTMLTable(url))

Then you can just do some cleansing procedures, subsetting and using rbind to get a data.frame with 2 columns and 120 observations.


Q: Using AWS Cloudfront, should I use apache gzip module to compress files or Cloudfront itself? I'm trying to get cloudfront straight on my site.
I want to know if I should you apache module to enable gzip on my site or set Cloudfront to compress the cached files?


Q: Looking for pure Java 3D library I have a very simple scenario: given are bare 3d points and I need to connect all these points and draw a surface. And for this case I need a very basic and really pure Java library without any dependencies.
Do you know such a library?

A: Do you know (or test) Java 3D API ?
Useful link : Java 3D API or Java net link
There is also another library : jmathplot (to draw diagram or others) --> it's easier than java 3d API.
It's two diferent philosophy. With the first you have to "draw point by point", with the second (jmathplot) you can use predefined elements and mathematical functions.

A: I think Java Surface Plot might be what you're looking for.
http://javasurfaceplot.sourceforge.net/

A: In order to communicate with the hardware just about any Java 3d library is going to have some dependencies.
You might try this:
http://www.mediafire.com/download/8ui3uwduw17bnx9/OpenGL.rar
There is a video tutorial set available for it. Just drawing a surface shouldn't be a problem.
http://www.youtube.com/watch?v=V1EvbHFtjCE
If you really want to get into Java 3D I would just search around for as much info on the various competing libraries and pick one for what you want to do with it.
edit:
The surface library fron other answer looks promising. I also found https://jogamp.org/jogl/www/ the JOGL or The Java API for OpenGL.


Q: contains function for int in flutter what is the best way to figure out what number the integer contains
for example:
i have a int that is 96 and i want to see if it has 9 return something and if it has not return something else

A: // this will return true if your int contains the pattern
bool intContains(myInt,pattern){
   return myInt.toString().contains(pattern.toString());
}


Q: WPF - XAML - Call an animation in a nested style from the parent style I'm trying to modify an ItemsControl to have a watermark to indicate the behavior of content dropped into it.
I'm using a Label inside a VisualBrush to show the word "OR" as the background to the ItemsControl (The control will contain property filters which will be Or'd together). The change in background is triggered by IsMouseOver on the ItemsControl.
The problem is this: I can get my VisualBrush (see xaml) to appear/disappear if I set the opacity directly in the Label but I cannot get the Opacity to animate if I try to use the nested style for the label. I have tried several approaches without success and so any pointers as to my mistake would be gratefully received.
I have included (one commented out) both animations I have tried. I also tried setting the Foreground on the Label with a ColorAnimation without success.
Many thanks
Ian Carson
<ItemsControl x:Name="OrFilterItemsTarget"
              ItemsSource="{Binding Assets.OrFilters}"
              ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
              ItemContainerStyle="{StaticResource DraggableItemStyle}"
              BorderThickness="0,0,0,0.5"
              BorderBrush="DimGray"
              AllowDrop="True"
              IsHitTestVisible="True"
              Margin="0,2.95,15.934,77"
              HorizontalAlignment="Right"
              Width="105">
    <ItemsControl.Style>
        <Style TargetType="{x:Type ItemsControl}">
            <Style.Resources>
                <Style x:Key="LabelStyle"
                       TargetType="{x:Type Label}">
                    <Style.Resources>
                        <Storyboard x:Key="FadeUp">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                                          Storyboard.TargetProperty="Opacity"
                                                          FillBehavior="HoldEnd">
                                <SplineDoubleKeyFrame KeyTime="00:00:2"
                                                     Value="0.5" />
                            </DoubleAnimationUsingKeyFrames>
                            <!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
                                             From="0" To="0.5"
                                             Duration="0:0:2" />-->
                        </Storyboard>
                        <Storyboard x:Key="FadeDown">
                            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                                                           Storyboard.TargetProperty="Opacity"
                                                           FillBehavior="Stop">
                                <SplineDoubleKeyFrame KeyTime="00:00:2"
                                                      Value="0" />
                            </DoubleAnimationUsingKeyFrames>
                            <!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
                                             From="0.5" To="0"
                                             Duration="0:0:2" />-->
                        </Storyboard>
                    </Style.Resources>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
                                     Value="True">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource FadeUp}" />
                            </DataTrigger.EnterActions>
                        </DataTrigger>
                        <DataTrigger  Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
                                      Value="False">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource FadeDown}" />
                            </DataTrigger.EnterActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
                <VisualBrush x:Key="FilterContentType"
                             AlignmentX="Center"
                             AlignmentY="Center"
                             Stretch="None">
                    <VisualBrush.Visual>
                        <Label Content="OR"
                               Foreground="DarkGray"
                               Style="{StaticResource LabelStyle}">
                        </Label>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="IsMouseOver"
                         Value="True">
                    <Setter Property="Background"
                            Value="{StaticResource FilterContentType}" />
                </Trigger>
                <Trigger Property="IsMouseOver"
                         Value="False">
                    <Setter Property="Background"
                            Value="Transparent" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ItemsControl.Style>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"
                       Background="Transparent">
                <i:Interaction.Behaviors>
                    <ei:FluidMoveBehavior AppliesTo="Children"
                                          Duration="0:0:0.3">
                        <ei:FluidMoveBehavior.EaseY>
                            <BackEase EasingMode="EaseIn"
                                      Amplitude="0.1" />
                        </ei:FluidMoveBehavior.EaseY>
                    </ei:FluidMoveBehavior>
                </i:Interaction.Behaviors>
            </WrapPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

A: In the end I realized I was over-thinking the problem. Nested styles were unnecessary. The solution was to set the background as the VisualBrush (with its content set up as the desired final appearance) inside its own tag within the ItemsControl and then animate the opacity of the VisualBrush using EventTriggers directly on the ItemsControl. Note the various events to manage both mouse and dragging user activity.
Thanks to anyone who was thinking about this problem. The final XAML looks like this and hopefully will be useful to someone.
 <ItemsControl x:Name="OrFilterItemsTarget"
               ItemsSource="{Binding Assets.OrFilters}"
               ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
               ItemContainerStyle="{StaticResource DraggableItemStyle}"
               BorderThickness="0,0,0,0.5"
               BorderBrush="DimGray"
               AllowDrop="True"
               IsHitTestVisible="True"
               Margin="0,2.95,15.934,77"
               HorizontalAlignment="Right"
               Width="105">
     <ItemsControl.Background>
         <VisualBrush x:Name="OrFilterContentType"
                      AlignmentX="Center"
                      AlignmentY="Center"
                      Stretch="None"
                      Opacity="0">
             <VisualBrush.Visual>
                 <Label Content="OR"
                        Foreground="DarkGray"
                        Opacity="0.5" />
             </VisualBrush.Visual>
         </VisualBrush>
     </ItemsControl.Background>
     <ItemsControl.Triggers>
         <EventTrigger RoutedEvent="ItemsControl.MouseEnter">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="0" To="1"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.DragEnter">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="0"
                                          To="1"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.MouseLeave">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1" To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.DragLeave">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1"
                                          To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
         <EventTrigger RoutedEvent="ItemsControl.Drop">
             <EventTrigger.Actions>
                 <BeginStoryboard>
                     <Storyboard>
                         <DoubleAnimation Storyboard.TargetName="OrFilterContentType"
                                          Storyboard.TargetProperty="(Brush.Opacity)"
                                          From="1"
                                          To="0"
                                          Duration="0:0:0.7" />
                     </Storyboard>
                 </BeginStoryboard>
             </EventTrigger.Actions>
         </EventTrigger>
     </ItemsControl.Triggers>
     <ItemsControl.ItemsPanel>
         <ItemsPanelTemplate>
             <WrapPanel Orientation="Horizontal"
                        Background="Transparent">
                 <i:Interaction.Behaviors>
                     <ei:FluidMoveBehavior AppliesTo="Children"
                                           Duration="0:0:0.3">
                         <ei:FluidMoveBehavior.EaseY>
                             <BackEase EasingMode="EaseIn"
                                       Amplitude="0.1" />
                         </ei:FluidMoveBehavior.EaseY>
                     </ei:FluidMoveBehavior>
                 </i:Interaction.Behaviors>
             </WrapPanel>
         </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>
 </ItemsControl>