text:
Q: How to use NestedScrollView, SwipeRefreshLayout and WebView together? Using all the latest libraries. I have a simple WebView inside a CoordinatorLayout fragment. Trying to hide the toolbar when user scrolls sdown.
<android.support.design.widget.CoordinatorLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/clRootHome"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.bytefury.deliverzz.fragment.HomeFragment">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_scrollFlags="scroll|enterAlways"
    android:theme="@style/AppTheme.AppBarOverlay">

    <include layout="@layout/toolbar" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/srlHome"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

         <im.delight.android.webview.AdvancedWebView
            android:id="@+id/frag_wv_wv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbarStyle="insideOverlay" />

</android.support.v4.widget.NestedScrollView>

</android.support.v4.widget.SwipeRefreshLayout>

</android.support.design.widget.CoordinatorLayout>

However, this doesn't do anything at all. Swipe to refresh works fine.
Out of desperation, when I switch the NestedScrollView and SwipeRefreshLayout, I get a blank, white screen.

A: if you want your toolbar to be scrollable, refactor your layout into this
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/clRootHome"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.bytefury.deliverzz.fragment.HomeFragment">

        <include layout="@layout/toolbar" />

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/srlHome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

         <im.delight.android.webview.AdvancedWebView
            android:id="@+id/frag_wv_wv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbarStyle="insideOverlay" />

     </android.support.v4.widget.SwipeRefreshLayout>

Now add this to your toolbar layout.
        app:layout_scrollFlags="scroll|enterAlways"


text:
Q: Python Regex Raw: how to match new lines for each line in consecutive lines? I have the following text:
s = """
{
    "list-of-stuff": "{
        (analog-input, 1), (analog-input, 2), (analog-input, 3),
        (analog-input, 4), (analog-input, 5), (analog-input, 6),
        (analog-input, 7), (analog-input, 8), (analog-input, 9),
        (analog-input, 10), (analog-input, 11), (analog-input, 12),
        (analog-input, 13), (analog-input, 14), (analog-input, 15),
        (analog-input, 16), (analog-input, 17), (analog-input, 18),
        (analog-input, 19), (analog-input, 20), (analog-input, 21),
        (analog-input, 22), (analog-input, 23), (analog-input, 24),
        (analog-input, 25), (analog-input, 26), (analog-input, 27),
        (analog-input, 28), (analog-input, 29), (analog-input, 30),
        (analog-input, 31), (analog-input, 32), (analog-output, 1)
    }"
},
{
    "identifier": "(analog-input, 0)",
    "name": "AI 00",
    "type": "analog-input",
    "value": "?",
    "description": "Temp",
    "flags": "{false,false,false}",
    "state": "normal",
    "service": "FALSE",
    "reliability": "?"
}
"""

And I want to convert all newline characters in the second string ({...}) from \n to \\n. (I am trying to make this JSON readable) How can I do this?
Here are my attempts:
s = re.sub(r'^[^"}]+,(\s*)\n', r'\1,\2\\n', s, flags=re.MULTILINE)
s = re.sub(r'^[^"}]+,(\s*)$', r'\1,\2\\n', s, flags=re.MULTILINE)

Unfortunately, neither works. The closest I get produces the following output:
s = """
{
    "list-of-stuff": "{
        (analog-input, 1), (analog-input, 2), (analog-input, 3),
        (analog-input, 4), (analog-input, 5), (analog-input, 6),
        (analog-input, 7), (analog-input, 8), (analog-input, 9),
        (analog-input, 10), (analog-input, 11), (analog-input, 12),
        (analog-input, 13), (analog-input, 14), (analog-input, 15),
        (analog-input, 16), (analog-input, 17), (analog-input, 18),
        (analog-input, 19), (analog-input, 20), (analog-input, 21),
        (analog-input, 22), (analog-input, 23), (analog-input, 24),
        (analog-input, 25), (analog-input, 26), (analog-input, 27),
        (analog-input, 28), (analog-input, 29), (analog-input, 30),\n        (analog-input, 31), (analog-input, 32), (analog-output, 1)
    }"
},
{
    "identifier": "(analog-input, 0)",
    "name": "AI 00",
    "type": "analog-input",
    "value": "?",
    "description": "Temp",
    "flags": "{false,false,false}",
    "state": "normal",
    "service": "FALSE",
    "reliability": "?"
}
"""

It seems that re.MULTILINE mode makes one match on all consecutive lines. However, I need to match EACH line. Unfortunately I need re.MULTILINE or else the \n's do not get matched. Any suggestions?
Update
I updated my question to better reflect my situation. The string has other properties that I needed to meet, which is shown in my regex. For example, I need to exclude }, from my matches, as well as other lines that are not inside a JSON string. Thus, I cannot simply replace all \n with \\n.
Sorry for the confusion.

A: The MULTILINE thing isn't the right way to tackle this; there's a much simpler issue with a much simpler solution.
In regular expressions, repetition is greedy by default. So [^"}]+ will match as many characters as it can while still making the rest of the pattern match. The last \n in the input ends up matching the \n in your pattern, with the intervening \ns matching as part of the [^"}]+.
But you can make it non-greedy just by using +? instead of +, in which case it will match as few characters as it can while still making the rest of the pattern match. So the first \n in the input ends up matching the one in your pattern, so each line is a separate match.
^[^"}]+?,(\s*)$

Debuggex Demo

A: ErlVolton Solution fit the best what you wan to do. But if you still want to use string manipulations or regexes to do this. You can simply do :
s = s.replace('\n','\\n')

A: Fortunately no regex-fu is needed to escape something so it is valid JSON.  The json module will do it for you, specifically json.dumps().  I'm not going to use your example text because it's not valid python, you have a multiline string with no triple quotes and no continuation.
>>> import json
>>> x = "foo\nbar"
>>> json.dumps(x)
'"foo\\nbar"'

To answer your literal question, I think re.sub("\n","\\\\n", your_text) would work fine:
>>> import re
>>> y = "foo\nbar\njaz"
>>> re.sub("\n","\\\\n",y)
'foo\\nbar\\njaz'

A: you need to use multi-line string like this:
s= '''
"list-of-stuff": "{
(analog-input, 1), (analog-input, 2), (analog-input, 3),
(analog-input, 4), (analog-input, 5), (analog-input, 6),
(analog-input, 7), (analog-input, 8), (analog-input, 9),
(analog-input, 10), (analog-input, 11), (analog-input, 12),
(analog-input, 13), (analog-input, 14), (analog-input, 15),
(analog-input, 16), (analog-input, 17), (analog-input, 18),
(analog-input, 19), (analog-input, 20), (analog-input, 21),
(analog-input, 22), (analog-input, 23), (analog-input, 24),
(analog-input, 25), (analog-input, 26), (analog-input, 27),
(analog-input, 28), (analog-input, 29), (analog-input, 30),
(analog-input, 31), (analog-input, 32), (analog-output, 1)
}"'''

s.replace('\n','\\n')

Now replace will work

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to assign ACL permissions to uploaded file when using S3FS node js lib I am using S3FS lib (in node.js app) to upload files to my AWS S3 directory. (referring documentation https://www.npmjs.com/package/s3fs) and  stackoverflow answer here
s3fs object init
s3fsImpl = new s3fs(bucketPath, {
            accessKeyId: xxxxx,
            secretAccessKey: xxxxx,
            ACL: 'public-read'
        })

method writeFile: s3fsImpl.writeFile(fileName, stream)
file is uploaded successfully and I am getting "ETag" in response. However, uploaded file is not accessible publicly.
How can I give proper ACL permissions to make it accessible for public-read?

A: You can provide the ACL as the third option in writeFile method as
s3fsImpl.writeFile(fileName, stream,{ ACL: 'public-read'})

A: Actually I was able to get this working with following approach in node
Step 1:
Install and include "aws-sdk" to access aws resources (I used it for S3)
var AWS = require('aws-sdk')
var s3 = new AWS.S3()

Step 2:
s3.putObject({
            Bucket: AWS_BUCKET_NAME, // bucket name on which file to be uploaded
            Key: uploadKey,  // file name on s3
            ContentType: file.type, // type of file
            Body: new Buffer(fileData, 'binary'), // base-64 file stream
            ACL: 'public-read'  // public read access
        }, function (err, resp) {
            if (err) {  // if there is any issue
                console.error('failed file upload to S3:: ', err)
                callback(err, null)
            }
            console.log('response from S3: ', resp)
            callback(null, 'Success')
        }
    )

ACL: 'public-read' will assign public-read access to your media/file on S3


text:
Q: Sending successive HTTP requests from Android to HTTP server I want to send two successive HTTP requests from my Android Application to the HTTP server, first request is for Login and second request is for retrieving the XML data on successful login. I have trying the following piece of code.
 public class XMLParser {
  public String getXmlFromUrl(String url) {

    String xml = null;

    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost1 = new HttpPost(url);   //post for login
    HttpPost httpPost2 = new HttpPost(url);   //post for xml data

   // Building post parameters, key and value pair
    List<NameValuePair> nameValuePair1 = new ArrayList<NameValuePair>(3);
    nameValuePair1.add(new BasicNameValuePair("action", "login"));
    nameValuePair1.add(new BasicNameValuePair("username", "admin"));
    nameValuePair1.add(new BasicNameValuePair("secret", "admin"));

    // Building post parameters, key and value pair
    List<NameValuePair> nameValuePair2 = new ArrayList<NameValuePair>(1);
    nameValuePair2.add(new BasicNameValuePair("action", "sippeers"));

    try {
        httpPost1.setEntity(new UrlEncodedFormEntity(nameValuePair1));

        httpPost2.setEntity(new UrlEncodedFormEntity(nameValuePair2));

        }
    catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
        }

    try {

                //executing first http post
        HttpResponse httpResponse1 = httpClient.execute(httpPost1);

                //executing second http post
        HttpResponse httpResponse2 = httpClient.execute(httpPost2);
        HttpEntity httpEntity2 = httpResponse2.getEntity();
        xml = EntityUtils.toString(httpEntity2);

    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }

    return xml;

}

I want to execute first httpPost1 and afterwards on successive login I want to retrieve the string xml from second HttpPost request. On executing the above code I am getting the error saying Permission Denied. I think I must maintain some kind of session while sending two HttpPost requests and should send second HttpPost request only on successful execution of first request.
Will be really thankful if someone can guide me solving this problem.

A: My opinion, you save login data in cookie. """https://hc.apache.org/httpclient-3.x/cookies.html""" this article show how to set cookie http request.


text:
Q: DRY jsx render method I wonder if it is a better way to DRY this code, have you guys any ideas?
The props are the same, just the component change...
render() {
    const { input: { value, onChange }, callback, async, ...rest } = this.props;

    if (async) {
      return (
        <Select.Async
          onChange={(val) => {
            onChange(val);
            callback(val);
          }}
          value={value}
          {...rest}
        />
      );
    }

    return (
      <Select
        onChange={(val) => {
          onChange(val);
          callback(val);
        }}
        value={value}
        {...rest}
      />
    );
  }

A: With:
let createElement = function(Component) {
    return (
        <Component onChange={(val) => {
            onChange(val);
            callback(val);
            }}
            value={value}
        {...rest}
      />
    );
};

you can do
let selectAsync = createElement(Select.Async);
let select = createElement(Select);

You can render them in the jsx part with {{select}} and {{selectAsync}}
P.S.: I didnt test this directly, but did something very similar a few days ago, so this approach should work. Note that Component must start with a capital letter.


text:
Q: Sonar Runner : Windows 7 : Throwing error against jdbc on start I'm going slowly mad.
I'm on windows 7 64 bit, using the latest SonarQube and runner 2.3.
I have SonarQube running against port 9000.
When I try to run sonar-runner.bat I get:
C:\myRoot\SonarQube\SonarQubeRunner\sonar-runner-dist-2.3\sonar-runner-2.3
SonarQube Runner 2.3
Java 1.7.0_45 Oracle Corporation (64-bit)
Windows 7 6.1 amd64
INFO: Runner configuration file: C:\myRoot\SonarQube\SonarQubeRunner\sonar-runner-dist-2.3\sonar-runner-2.3\conf\sonar-runner.properties
INFO: Project configuration file: NONE
INFO: Default locale: "en_US", source code encoding: "windows-1252" (analysis is platform dependent)
INFO: Work directory: C:\myRoot\SonarQube\sonar_examples\sonar-examples-master\projects\languages\php\php-sonar-runner\src\.sonar
INFO: SonarQube Server 4.0
14:18:52.103 INFO  - Load batch settings
14:18:52.196 INFO  - User cache: C:\Users\myName\.sonar\cache
14:18:52.212 INFO  - Install plugins
14:18:52.602 INFO  - Install JDBC driver
14:18:52.602 INFO  - Create JDBC datasource for jdbc:mysql://localhost:3306/sonar
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
Total time: 1.700s
Final Memory: 4M/74M
INFO: ------------------------------------------------------------------------
ERROR: Error during Sonar runner execution
ERROR: Unable to execute Sonar
ERROR: Caused by: Fail to connect to database
ERROR: Caused by: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
ERROR: Caused by: com.mysql.jdbc.Driver
ERROR:
ERROR: To see the full stack trace of the errors, re-run SonarQube Runner with the -e switch.
ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.

When I collect the debug info I get:
        yadda, yadda ...
        ... 32 more
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)
        ... 37 more

I have a file called mysql-connector-java-5.1.26.jar at:
C:\myRoot\SonarQube\sonarqube-4.0\sonarqube-4.0\extensions\jdbc-driver\mysql

I can't think why it's not being found.
My .properities file is fairly simple.
ANY advice would be much appreciated.
Thanks for reading.

A: I had the same error message on my Jenkins setup using Linux Mint Debian Edition. I used SonarQube Runner 2.3 and SonarQube Server 4.1.1
ERROR: Unable to execute SonarERROR: Caused by: Fail to connect to database
ERROR: Caused by: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
ERROR: Caused by: com.mysql.jdbc.Driver

Here I read to restart the SonarQube server, which solved the issue for me.
I know it's trivial but that's all there was to it in my case and it's easy to overlook the little things.

A: if you are trying with your local Mysql data base then use these codes in your sonar.properties file of sonarcube.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
sonar.jdbc.username=root
sonar.jdbc.password=root

#----- MySQL 5.x
# Comment the embedded database and uncomment the following line to use MySQL
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonardb?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
sonar.jdbc.driverClassName: com.mysql.jdbc.Driver
sonar.jdbc.validationQuery: select 1

the last two line code is not specified in any of the sonar tutorials for Mysql.
And finally make sure you have created SONAR_RUNNER_HOME with proper value and the path variable entry up to the bin directory.


text:
Q: What is the simplest way to access data of an F# discriminated union type in C#? I'm trying to understand how well C# and F# can play together. I've taken some code from the F# for Fun & Profit blog which performs basic validation returning a discriminated union type:
type Result<'TSuccess,'TFailure> =
    | Success of 'TSuccess
    | Failure of 'TFailure

type Request = {name:string; email:string}

let TestValidate input =
    if input.name = "" then Failure "Name must not be blank"
    else Success input

When trying to consume this in C#; the only way I can find to access the values against Success and Failure (failure is a string, success is the request again) is with big nasty casts (which is a lot of typing, and requires typing actual types that I would expect to be inferred or available in the metadata):
var req = new DannyTest.Request("Danny", "fsfs");
var res = FSharpLib.DannyTest.TestValidate(req);

if (res.IsSuccess)
{
    Console.WriteLine("Success");
    var result = ((DannyTest.Result<DannyTest.Request, string>.Success)res).Item;
    // Result is the Request (as returned for Success)
    Console.WriteLine(result.email);
    Console.WriteLine(result.name);
}

if (res.IsFailure)
{
    Console.WriteLine("Failure");
    var result = ((DannyTest.Result<DannyTest.Request, string>.Failure)res).Item;
    // Result is a string (as returned for Failure)
    Console.WriteLine(result);
}

Is there a better way of doing this? Even if I have to manually cast (with the possibility of a runtime error), I would hope to at least shorten access to the types (DannyTest.Result<DannyTest.Request, string>.Failure). Is there a better way?

A: A really nice way to do this with C# 7.0 is using switch pattern matching, it's allllmost like F# match:
var result = someFSharpClass.SomeFSharpResultReturningMethod()

switch (result)
{
    case var checkResult when checkResult.IsOk:
       HandleOk(checkResult.ResultValue);
       break;
    case var checkResult when checkResult.IsError:
       HandleError(checkResult.ErrorValue);
       break;
}

EDIT: C# 8.0 is around the corner and it is bringing switch expressions, so although I haven't tried it yet I am expecting we will be able to do something like this this:
var returnValue = result switch
{
    var checkResult when checkResult.IsOk:     => HandleOk(checkResult.ResultValue),
    var checkResult when checkResult.IsError   => HandleError(checkResult.ErrorValue),
    _                                          => throw new UnknownResultException()
};

See https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/ for more info.

A: How about this?  It's inspired by @Mauricio Scheffer's comment above and the CSharpCompat code in FSharpx.
C#:
MyUnion u = CallIntoFSharpCode();
string s = u.Match(
  ifFoo: () => "Foo!",
  ifBar: (b) => $"Bar {b}!");

F#:
  type MyUnion =
    | Foo
    | Bar of int
  with
    member x.Match (ifFoo: System.Func<_>, ifBar: System.Func<_,_>) =
      match x with
      | Foo -> ifFoo.Invoke()
      | Bar b -> ifBar.Invoke(b)

What I like best about this is that it removes the possibility of a runtime error.  You no longer have a bogus default case to code, and when the F# type changes (e.g. adding a case) the C# code will fail to compile.

A: You can use C# type aliasing to simplify referencing the DU Types in a C# File.
using DanyTestResult = DannyTest.Result<DannyTest.Request, string>;

Since C# 8.0 and later have Structural pattern matching, it's easy to do the following:
switch (res) {
    case DanyTestResult.Success {Item: var req}:
        Console.WriteLine(req.email);
        Console.WriteLine(req.name);
        break;
    case DanyTestResult.Failure {Item: var msg}:
        Console.WriteLine("Failure");
        Console.WriteLine(msg);
        break;
}

This strategy is the simplest as it works with reference type F# DU without modification.
The syntax C# syntax could be reduced more if F# added a Deconstruct method to the codegen for interop. DanyTestResult.Success(var req)
If your F# DU is a struct style, you just need to pattern match on the Tag property without the type. {Tag:DanyTestResult.Tag.Success, SuccessValue:var req}

A: Working with discriminated unions is never going to be as straightforward in a language that does not support pattern matching. However, your Result<'TSuccess, 'TFailure> type is simple enough that there should be some nice way to use it from C# (if the type was something more complicated, like an expression tree, then I would probably suggest to use the Visitor pattern).
Others already mentioned a few options - both how to access the values directly and how to define Match method (as described in Mauricio's blog post). My favourite method for simple DUs is to define TryGetXyz methods that follow the same style of Int32.TryParse - this also guarantees that C# developers will be familiar with the pattern. The F# definition looks like this:
open System.Runtime.InteropServices

type Result<'TSuccess,'TFailure> =
    | Success of 'TSuccess
    | Failure of 'TFailure

type Result<'TSuccess, 'TFailure> with
  member x.TryGetSuccess([<Out>] success:byref<'TSuccess>) =
    match x with
    | Success value -> success <- value; true
    | _ -> false
  member x.TryGetFailure([<Out>] failure:byref<'TFailure>) =
    match x with
    | Failure value -> failure <- value; true
    | _ -> false

This simply adds extensions TryGetSuccess and TryGetFailure that return true when the value matches the case and return (all) parameters of the discriminated union case via out parameters. The C# use is quite straightforward for anyone who has ever used TryParse:
  int succ;
  string fail;

  if (res.TryGetSuccess(out succ)) {
    Console.WriteLine("Success: {0}", succ);
  }
  else if (res.TryGetFailure(out fail)) {
    Console.WriteLine("Failuere: {0}", fail);
  }

I think the familiarity of this pattern is the most important benefit. When you use F# and expose its type to C# developers, you should expose them in the most direct way (the C# users should not think that the types defined in F# are non-standard in any way).
Also, this gives you reasonable guarantees (when it is used correctly) that you will only access values that are actually available when the DU matches a specific case.

A: Probably, one of the simplest ways to accomplish this is by creating a set of extension methods:
public static Result<Request, string>.Success AsSuccess(this Result<Request, string> res) {
    return (Result<Request, string>.Success)res;
}

// And then use it
var successData = res.AsSuccess().Item;

This article contains a good insight. Quote:

The advantage of this approach is 2 fold:

*

*Removes the need to explicitly name types in code and hence gets back the advantages of type inference;

*I can now use . on any of the values and let Intellisense help me find the appropriate method to use;

The only downfall here is that changed interface would require refactoring the extension methods.
If there are too many such classes in your project(s), consider using tools like ReSharper as it looks not very difficult to set up a code generation for this.

A: I had this same issue with the Result type.  I created a new type of ResultInterop<'TSuccess, 'TFailure> and a helper method to hydrate the type
type ResultInterop<'TSuccess, 'TFailure> = {
    IsSuccess : bool
    Success : 'TSuccess
    Failure : 'TFailure
}

let toResultInterop result =
    match result with
    | Success s -> { IsSuccess=true; Success=s; Failure=Unchecked.defaultof<_> }
    | Failure f -> { IsSuccess=false; Success=Unchecked.defaultof<_>; Failure=f }

Now I have the choice of piping through toResultInterop at the F# boundary or doing so within the C# code.
At the F# boundary
module MyFSharpModule =
    let validate request =
        if request.isValid then
            Success "Woot"
        else
            Failure "request not valid"

    let handleUpdateRequest request =
        request
        |> validate
        |> toResultInterop

public string Get(Request request)
{
    var result = MyFSharpModule.handleUpdateRequest(request);
    if (result.IsSuccess)
        return result.Success;
    else
        throw new Exception(result.Failure);
}

After the interop in Csharp
module MyFSharpModule =
    let validate request =
        if request.isValid then
            Success "Woot"
        else
            Failure "request not valid"

    let handleUpdateRequest request = request |> validate

public string Get(Request request)
{
    var response = MyFSharpModule.handleUpdateRequest(request);
    var result = Interop.toResultInterop(response);
    if (result.IsSuccess)
        return result.Success;
    else
        throw new Exception(result.Failure);
}

A: I'm using the next methods to interop unions from F# library to C# host. This may add some execution time due to reflection usage and need to be checked, probably by unit tests, for handling right generic types for each union case.

*

*On F# side

type Command =
     | First of FirstCommand
     | Second of SecondCommand * int

module Extentions =
    let private getFromUnionObj value =
        match value.GetType() with
        | x when FSharpType.IsUnion x ->
            let (_, objects) = FSharpValue.GetUnionFields(value, x)
            objects
        | _ -> failwithf "Can't parse union"

    let getFromUnion<'r> value =
        let x = value |> getFromUnionObj
        (x.[0] :?> 'r)

    let getFromUnion2<'r1,'r2> value =
        let x = value |> getFromUnionObj
        (x.[0] :?> 'r1, x.[1] :? 'r2)

*On C# side

        public static void Handle(Command command)
        {
            switch (command)
            {
                case var c when c.IsFirstCommand:
                    var data = Extentions.getFromUnion<FirstCommand>(change);
                    // Handler for case
                    break;
                case var c when c.IsSecondCommand:
                    var data2 = Extentions.getFromUnion2<SecondCommand, int>(change);
                    // Handler for case
                    break;
            }
        }


text:
Q: Coin tossing game. Consider the following game.
You're given a coin that has a 4/5 chance of landing on heads and 1/5 on tails. Each time the coin lands on heads you will win 10000 dollars. Before each toss you can decide to withdraw from the game with the money you've won or keep tossing to win more, however if the coin lands once on tails you will lose all. What would be the winning strategy here? More precisley, if $Y$ is the random variable "Total prize won", what is the number of tosses that maximizes $E[Y]$?
This seems kind of simple, but maybe I am wrong so that's why I'm asking. Isn't this just finding $n$ such that $n10000(\frac{4}{5})^n$ is maximized? Though I find it weird that 4 and 5 attain the same (and maximum) value.


text:
Q: OneDrive upload via php I'm looking for a code example for uploading a file to Microsoft OneDrive via php.
I have created a microsoft account and created an app.
Thanks allot
Avi

A: Try use https://github.com/lovattj/php-skydrive
Upload example:
<?php
require_once 'functions.inc.php';
$token = skydrive_tokenstore::acquire_token(); // Call this function to grab a current access_token, or false if none is available.

if (!$token) { // If no token, prompt to login. Call skydrive_auth::build_oauth_url() to get the redirect URL.
    echo "
";
    echo "&nbsp";
    echo "Login with SkyDrive";
    echo "
";
} else {
    $sd = new skydrive($token);
    try {
        $response = $sd->put_file($_GET['folderid'], '/file/to/put');
        // File was uploaded, return metadata.
        print_r($response);
    } catch (Exception $e) {
        // An error occured, print HTTP status code and description.
        echo "Error: ".$e->getMessage();
        exit;
    }
}

A: Reference : http://www.onlinecode.org/onedrive-file-upload-using-php/
Code for onedrive upload file rest api
$real_uploadfile = $_FILES["uploadfile"]["name"];
$temp = explode(".", $_FILES["uploadfile"]["name"]);
$temp_ral = $temp[0];
$newfilename = date("Ymd").round(microtime(true)) .$temp_ral. '.' . end($temp).$file_name;
$file_tmp = $_FILES['uploadfile']['tmp_name'];
// check folder is exist in over system
if (!file_exists('uploads')) {
    // create new folder
    mkdir('uploads', 0777, true);
}
$target_dir = "uploads/";
$uplode_path = $target_dir.$newfilename;
move_uploaded_file($file_tmp,$uplode_path);
$skydrive = new skydrive($token);
// onedrive upload file using php
$folderid = $_POST['folderid'];

try {
    $response_data = $skydrive->put_file($_GET['folderid'], $uplode_path);
    // File was uploaded, return metadata.
    print_r($response_data);
}
catch (Exception $exception)
{
    // An error accrue for onedrive file upload using php
    echo "Error: ".$exception->getMessage();
    exit;
}


text:
Q: Problema al mostrar tabWidget con QMainWindow Estoy trabajando con PyQt, con el tipo de ventana QMainWindow, al usar un tabWidget no me da error en absoluto pero cuando ejecuto el programa no me lo muestra. Sin embargo cuando cambio QMainWindow por QWidget y ejecuto, si lo muestra. Este es el script de prueba:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QGridLayout()
        self.setLayout(layout)

        label1 = QLabel("Example content contained in a tab.")
        label2 = QLabel("More example text in the second tab")
        textEdit = QTextEdit()

        tabwidget = QTabWidget()
        tabwidget.addTab(label1, "Tab 1")
        tabwidget.addTab(label2, "Tab 2")
        tabwidget.addTab(textEdit, "TextEdit")

        layout.addWidget(tabwidget, 0, 0)

app = QApplication(sys.argv)

screen = Window()
screen.show()

sys.exit(app.exec_())

Con cambiar class Window(QWidget) por class Window(QMainWindow) ya no muestra el tabWidget en la app.
Como puedo solucionarlo?
Gracias de antemano.

A: Qt Main Window Framework

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()                                                       # !

        self.centralwidget = QWidget()                                           # +
        self.setCentralWidget(self.centralwidget)                                # +

        layout = QGridLayout(self.centralwidget)                       # + self.centralwidget
#        self.setLayout(layout)

        label1 = QLabel("Example content contained in a tab.")
        label2 = QLabel("More example text in the second tab")
        textEdit = QTextEdit()

        tabwidget = QTabWidget()
        tabwidget.addTab(label1, "Tab 1")
        tabwidget.addTab(label2, "Tab 2")
        tabwidget.addTab(textEdit, "TextEdit")

        layout.addWidget(tabwidget, 0, 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())


text:
Q: SQL Server Stored Procedure reports successful execution but query(s) within it do not execute We use a suite of stored procedures to fulfill one of our ETL pipelines, which relies on linked servers using a push strategy. The stored procedures are run one-per-step in a SQL Server Agent job. The servers exist in the same VLAN and have a 10GBPS connection.

We realize a pull strategy is ideal, and are working to apply this approach across our workloads.

The ETL agent is typically successful and has been a working solution for quite some time. Intermittently one or more of the stored procedures will report a successful execution but in truth it does not execute. I have verified this scenario on numerous occassions.

The agent history indicates no errors have occurred and our custom error table (populated by our error handler stored procedure) shows no errors for the migration. All stored procedures have been verified to be working correctly and are free of logic bugs, as evidenced by the fact that in most cases data is INSERT|UPDATE|DELETE(ed) successfully.

Manually executing the failed stored procedure does not produce different results. The confusing part about the situation is that if a query contained within the stored procedure is extracted and executed manually, it succeeds in INSERT|UPDATE|DELETE(ing) the data.
My best guess is that this is perhaps being caused by a cached query plan. Though, I'm entirely unsure.

Our stored procedures for this use case always contain a try/catch to handle and log any errors. In structure, they usually resemble something like the following:
CREATE PROCEDURE dbo.some_etl_proc
AS
  BEGIN
    SET NOCOUNT ON;

    SET XACT_ABORT ON;

    BEGIN TRY

      ---------
      -- delete
      ---------
      DELETE  at
      FROM    LINKED_SERVER.ANOTHER_DB.dbo.another_table AS at
              LEFT JOIN SOME_DB.dbo.some_table AS st
                ON st.some_table_id = at.some_table_id
      WHERE   st.some_table_id IS NULL;

      ---------
      -- update
      ---------
      UPDATE  at
      SET     col_1 = st.col_1
            , col_2 = st.col_2
      FROM    LINKED_SERVER.ANOTHER_DB.dbo.another_table AS at
              JOIN SOME_DB.dbo.some_table AS st
                ON st.some_table_id = at.some_table_id;

      ---------
      -- insert
      ---------
      INSERT INTO LINKED_SERVER.ANOTHER_DB.dbo.another_table (col_1, col_2)
      SELECT  st.col_1
            , st.col_2
      FROM    SOME_DB.dbo.some_table AS st
              LEFT JOIN LINKED_SERVER.ANOTHER_DB.dbo.another_table AS at
                ON at.some_table_id = st.some_table_id
      WHERE   at.some_table_id IS NULL;

    END TRY
    BEGIN CATCH
      IF @@TRANCOUNT > 0
        ROLLBACK TRAN;

      -- we log the error here using a custom sproc
      EXEC dbo.error_handler

      RETURN 55555;
    END CATCH;
  END;

Our error handler looks like:
CREATE PROCEDURE dbo.error_handler
AS
  DECLARE @errmsg NVARCHAR(2048)
        , @severity TINYINT
        , @state TINYINT
        , @errno INT
        , @proc sysname
        , @lineno INT;

  SELECT  @errmsg = ERROR_MESSAGE()
        , @severity = ERROR_SEVERITY()
        , @state = ERROR_STATE()
        , @errno = ERROR_NUMBER()
        , @proc = ERROR_PROCEDURE()
        , @lineno = ERROR_LINE();

  IF @errmsg NOT LIKE '***%'
    BEGIN
      SELECT  @errmsg = N'*** ' + COALESCE(QUOTENAME(@proc), '<dynamic SQL>') + N', Line ' + LTRIM(STR(@lineno)) + N'. Errno ' + LTRIM(STR(@errno)) + N': ' + @errmsg;
    END;

  INSERT INTO dbo.db_error
  SELECT  GETDATE()
        , SYSTEM_USER
        , @errno
        , @severity
        , @state
        , @lineno
        , @errmsg
        , @proc;

  RAISERROR('%s', @severity, @state, @errmsg);


text:
Q: C# function calling a different method I created a WCFService and a WindowsFormApp. In the service, I have 3 functions. Two of them takes an integer as parameter and returns a integer. The other takes a string and returns a string.
When I try to call the two functions (in WindowsFormApp) that takes an integer , the program thinks I'm trying to call some other function in "Reference.cs" and not from the service I created. The string function doesn't have this problem and works fine, but the 2 int functions calls some other void function in "Reference.cs".
These are the functions mentioned and the ones I want to call. This file is "Service1.svc.cs"
`
    public int c2f(int c)
    {
        int num = c * 9 / 5 + 32;
        return num;
    }

    public int f2c(int f)
    {
        int num = (f - 32) * 5 / 9;
        return num;
    }

    public string sort(string s)
    {
        String str = String.Join(",", s.Split(',').Select(x => int.Parse(x)).OrderBy(x => x));
        return str;
    }

This is the function that it's calling (which is not what I want). This is in "Reference.cs"
    public void f2c(int f, [System.Xml.Serialization.XmlIgnoreAttribute()] bool fSpecified, out int f2cResult, [System.Xml.Serialization.XmlIgnoreAttribute()] out bool f2cResultSpecified) {
        object[] results = this.Invoke("f2c", new object[] {
                    f,
                    fSpecified});
        f2cResult = ((int)(results[0]));
        f2cResultSpecified = ((bool)(results[1]));
    }

I spent a good couple hours trying to fix the problem, but no avail. Could someone please help?
How I'm calling the functions: After adding a button to the WindowsFormApp and double-clicking it, in the button method, I have Service1 serv = new Service1();. Then if I were to write serv.sort("some string"), it would refer to the function in the first code block, which is what I wanted. If I were to write serv.f2c(0), an error comes up saying I'm missing parameters and upon closer inspection, it tells me that I'm referring to the function in the second code block, which is NOT what I wanted. Hopefully, this gives a little more insight.

A: Use "Add Service Reference" instead of "Add Web Reference".
This question helped fix my issue.


text:
Q: SqlClient.SqlException: Invalid column name ClassNameId While fetching data from Fluent API I am new to this EF,I am tring to fetch data from Sql Db table, and it gives me error like invalid classNameId error.
public class ClassName
{
        [Key]
        [Display(Name = "Id:")]
        public int Id { get; set; }

        [Display(Name = "Created By:")]
        [Required(ErrorMessage = "Please enter created by.")]
        [StringLength(5, MinimumLength = 2)]
        public string CreatedBy { get; set; }
        public List<OtherClass> OtherClassList{ get; set; }
}

public class OtherClass
{

        [Column("Control")]
        [Display(Name = "Control:")]
        public String Control { get; set; }

        [ForeignKey("PID")]
        [Column("PID")]
        [Display(Name = "PID:")]
        public int PID{ get; set; }
}

DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<ClassName>()
                .HasKey(p => p.Id);

            modelBuilder.Entity<OtherClass>()
            .HasKey(p=> new { p.Control, p.PID});
}

I have use Fluent API for get data from MSSql.

A: The problem is the invalid ForeignKey annotation here
[ForeignKey("PID")]
[Column("PID")]
[Display(Name = "PID:")]
public int PID{ get; set; }

ForeignKey is confusing attribute because it changes the meaning of the argument depending on where it is applied. When applied on FK property it indicates the name of the navigation property. And when applied on navigation property it indicates the name of the FK property.
In your case, it is applied on FK property, but specifies the same property name, so it is simply ignored and EF uses the default conventional name for the FK property associated with the List<OtherClass> OtherClassList relationship, which is why you are getting the non existing column.
To fix the problem, either apply the attribute on the navigation property of the other class (because you have no navigation property in the class that needs FK):
[ForeignKey(nameof(OtherClass.PID))]
public List<OtherClass> OtherClassList{ get; set; }

or (preferably) configure it with fluent API:
modelBuilder.Entity<ClassName>()
    .HasMany(e => e.OtherClassList)
    .WithOne()
    .HasForeignKey(e => e.PID);

In case you have reference navigation property, in addition to the above data annotation solution, you could also use
    [ForeignKey(nameof(ClassName))]
    [Column("PID")]
    [Display(Name = "PID:")]
    public int PID{ get; set; }

or
    [ForeignKey(nameof(PID))]
    public ClassName ClassName { get; set; }

or the fluent API .WithOne() must be changed to .WithOne(e => e.ClassName).


text:
Q: how to enable/disable gpio-keys autorepeat in runtime I am new here.
I am not a professional programmer. I am actually HW guy.
It just ended up that I had to deal with these things.
So my terms may not be correct or clear. Please understand.
This is about embedded device with Linux version 3.10.14.
My device has two buttons and I mapped them to gpio-keys or KEYBOARD_GPIO.
So it seems that setting the value of 'rep' in struct gpio_keys_platform_data will enable or disable the autorepeat function.
But can I enable or disable the autorepeat function from console?
or from user program?
And another question came to me just now.
Can I enable autorepeat for one key and disable it for the other?
Maybe assigning each key to two different gpio-keys device?
Thanks for reading.


text:
Q: Pure CSS hover resulting in a color-overlay with text This is my first post on Stack Overflow, but I've been finding answers on here for years. This is one I can't seem to find though.
I'm wondering if there is a way to do the following using only HTML and CSS.
I have a fluid layout, and I want to keep the images fluid. I currently have each image set up to fill their respective divs by using the max-height:100% and max-width:100% properties.
On hover, I would like the image to have a slightly transparent color overlay, and reveal some text and a button.
I'm able to do this if I define the image/div width, but I cannot figure out how to do it while keeping the image so it re-sizes dynamically.
Here's a Fiddle of 4 images in a fluid layout. Any help would be GREATLY appreciated, I feel like I'm overlooking something.
And the code:
HTML

CSS
body { margin:0;}
#container { width:100%; font-size:0;}
img { max-width:100%; max-height:100%;}
.span4 { width:25%; display:block;}
.red { background-color: red; float:left; overflow:hidden;}
.blue { background-color: blue; float:left; overflow:hidden;}
.green { background-color: green; float:left; overflow:hidden;}
.purple { background-color: purple; float:left; overflow:hidden;}

A: Try using the :after pseudo selector (note browser compatability)
http://jsfiddle.net/HGWPZ/1/
.span4 {
    width:25%;
    display:block;
    position: relative;
}

.span4:hover:after
{
    content: '';
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
}

.red:hover:after
{
    background: RGBA(255, 0, 0, .3);
}

.blue:hover:after
{
    background: RGBA(0, 0, 255, .3);
}

.green:hover:after
{
    background: RGBA(0, 255, 0, .3);
}

.purple:hover:after
{
    background: RGBA(230, 230, 250, .3);
}

idk what the RGB value for purple is though :p so play around with it

A: DEMO
html

        Text text text
        <button>Button</button>

css
.span4 {
    width:25%;
    display:block;
    position:relative; /*added*/
}

/*added*/
.overlay {
    position:absolute;
    top:0;
    width:0;
    width:100%;
    height:100%;
    background-color:rgba(0, 0, 0, 0.3);
    display:none;
}
.red:hover .overlay {
    display:block;
}


text:
Q: Saving multiple images in MayaVi I want to render around 500 images and save them to different png files, therefore I wrote a small class which contains my dataset and a renderfunction
from mayavi import mlab
mlab.options.offscreen=True

class Dataset(object):
    def __init__(self):
        some init stuff etc

                 .
                 .
                 .
                 .

    def save_current_frame_to_png(self, filename):
        mlab.contour3d(self.frame_data, contours =30, opacity=0.2)
        mlab.savefig(filename)
        mlab.clf()
        mlab.close()
        gc.collect()

    def create_movie_files(self):
        folder_name = "animation"
        try:
            os.makedirs(folder_name)
        except OSError:
            raise OSError("Directory already exists.")

        self.__go_to_first_frame()

        for i in range(self.frames):
            filename = "".join([folder_name, "/%.5i" % i, ".png"])
            print filename
            self.save_current_frame_to_png(filename)
            self.read_single_frame()

        self.__go_to_first_frame()

So everything seemed to work fine but than I had a look at the memory usage which goes up
until the system crashes. So i tried to use mlab.clf() and gc.collect() to keep my memory low which didn't work. I found a solution with mlab.close() which seems to work for memory usage but this brings a new problem.
Everytime a new image is rendered there is also a new window created by mayavi, so after
around 200 windows the programm crashes. Maybe is there a possibilty to disable the windows completely ? It seems to me that mlab.options.offscreen=True only disable drawing inside the current window.
EDIT:
self.frame_data is a numpy array of shape (100,100,100) and self.read_single_frame() just reads the next frame from a textfile and stores it in self.frame_data. This functions do not increase the ram, if I turn the rendering off the memory usage stays at 1.2%.

A: you should hide mlab.show() while you keep mlab.close(). then It will work


text:
Q: Testing isinstance(PosixPath) using pytest with pyfakefs In my code, I test if config_location is an instance of PosixPath or None:
if isinstance(self.config_location, (PosixPath, type(None))):
    ...

This works fine when run with the normal python interpreter, but fails during my pytest tests using pyfakefs, as the pyfakefs object is of type pyfakefs.fake_pathlib.FakePathlibModule.PosixPath. The obvious solution here would be to import pyfakefs into the tested code and add pyfakefs.fake_pathlib.FakePathlibModule.PosixPath to the isinstance tuple, but this approach seems very clunky to me.
There has to be a better way ?

A: Testing for PurePath instead works.


text:
Q: xml XPath count I'm working on an xml and xslt project and I have a problem; the question asked is count the number of open ports having a given number this is the path used
liste_hotes --)
    hote --)
        liste_ports --)
            port num_port="80" --)
                Etat etat="open"

count(liste_hotes/hote/liste_ports/port[@num_port='80']/Etat[@etat='open'])

A: XML is case-sensitive: count(expression) is not the same as Count(expression), and there is no Count() function.


text:
Q: Spinning iphone based on ground I am rotate iphone based on the ground
But the UIAcceleration values of (x&y&z) are same . Can you tell me exactly what happens here ?
Also i want know how to its  calculate UIAcceleration values of(x&y&z) ?
I am really interested to work with UIAcceleration values.
Can anyone help me?
Thanks in advance.....

A: The UIAcceleration value can only detect acceleration relative to the orientation of the device.
By rotating the iPhone, in its frame of reference there is a constant gravity force (along the z axis) and a constant centrifugal force (on the xy-plane), so the UIAcceleration will not change.
You cannot distinguish acceleration due to gravity or linear acceleration or rotation by the accelerometer. You need other devices e.g. the compass (magnetometer) to detect a rotational change.


text:
Q: Uploading a new version of a Python file to Azure Databricks requires cluster restart I am playing with Azure Databricks. I uploaded a Python file and added it to the spark context with
spark.sparkContext.addPyFile('/location/to/the/file/model.py')

Everything works fine when I run my Python code in the notebook. But when I make a change to the model.py file and uploaded it with --overwrite, the code in the notebook does not pick up the new version of the file, instead still uses the old one until I restart the cluster.
Is there a way to avoid cluster restart whenever I overwrite a file?

A: Unfortunately it doesn't work this way - when file is added, it's distributed to all workers and used there.
But you may do it differently - you can use feature of the Repos called arbitrary files (don't forget restart cluster after enabling it), so when you clone your repository into Repos, then you can use Python files (not notebooks) from that repository as Python packages.  And then in the notebook, you can use following directives to force reload of changes into notebook environment:
%load_ext autoreload
%autoreload 2

You can see an example of such usage in this demo - Python code from my_package directory is used in the notebook.


text:
Q: php Laravel adding inputs with name as an array I am trying to create a form where the names of the inputs are an array. I am going through an array sent from another view to get fields to show. in this example I want to show 3 fields.
$someResult = array('0','1','2');

$fields = array(0=>'fName',1=>'mName',2=>'lName');

@foreach($someResult as $k){

      {!! Form::text($fields[$k][],$someVal) !!}

@endforeach

I tried simplifing it to straight php:
  foreach ($someResult as $k){
    echo "
<input type='text' name='".$fields[$k][]."' value='".$someVal."'>
";
    }

Either way, i get the error "Cannot use [] for reading"
How can i declare name argument as an array?
My goal is something like:

       <input type='text' name='fName[]' value='someVal'>

       <input type='text' name='mName[]' value='someVal'>

  //etc.....

A: The square bracket should be used as a string in your dom.
@foreach ($someResult as $k)

            <input type="text" name="{{ $fields[$k] }}[]" value="{{ $someVal }}">

@endforeach


text:
Q: Bootstrap button inside an input group appears detached from input Problem description
I got a simple code where I want to display two buttons on the right of an input. But the button appears "detached" from the input. I don't want to play with negative margin.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

    <input type="text" class="form-control" />

      <button type="button" class="btn btn-default"></button>
      <button type="button" class="btn btn-default"></button>

Here is the result

Attempted solution
I tried to put the input inside the span.input-group-btn. It then make the buttons stick to the input, but I loose the benefit of input auto sizing, and at mobile resolution, I get something like:

A: Although when I ran your code it was working fine for me. But I am including another templete for you. This is the way I do it.
working  example

<meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

           <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

        <input type="text" class="form-control" style="height: 54px;"/>

    <button type="button" class="btn btn-default"></button>
            <button type="button" class="btn btn-default"></button>

A: This is quite old but I just ran into this issue and wanted to post in the case someone comes here first rather than heading to https://getbootstrap.com/docs/4.0/components/input-group/

       @

        <input type="text" class="form-control"
          placeholder="Username" aria-
          label="Username" aria-
          describedby="basic-
          addon1">


text:
Q: Java Swing game has poor performance when many sprites are on screen I'm making a simple tower defense game in Swing and I've run into a performance problem when I try to put many sprites (more than 20) on screen.
The whole game takes place on a JPanel which has setIgnoreRepaint(true).
Here is the paintComponent method (con is the Controller):
public void paintComponent(Graphics g){
    super.paintComponent(g);
    //Draw grid
    g.drawImage(background, 0, 0, null);
    if (con != null){
        //Draw towers
        for (Tower t : con.getTowerList()){
            t.paintTower(g);
        }
        //Draw targets
        if (con.getTargets().size() != 0){
            for (Target t : con.getTargets()){
                t.paintTarget(g);
            }
            //Draw shots
            for (Shot s : con.getShots()){
                s.paintShot(g);
            }
        }
    }
}

The Target class simple paints a BufferedImage at its current location. The getImage method doesn't create a new BufferedImage, it simply returns the Controller class's instance of it:
public void paintTarget(Graphics g){
    g.drawImage(con.getImage("target"), getPosition().x - 20, getPosition().y - 20, null);
}

Each target runs a Swing Timer to calculate its position. This is the ActionListener it calls:
public void actionPerformed(ActionEvent e) {
    if (!waypointReached()){
        x += dx;
        y += dy;
        con.repaintArea((int)x - 25, (int)y - 25, 50, 50);
    }
    else{
        moving = false;
        mover.stop();
    }
}

private boolean waypointReached(){
    return Math.abs(x - currentWaypoint.x) <= speed && Math.abs(y - currentWaypoint.y) <= speed;
}

Other than that, repaint() is only called when placing a new tower.
How can I improve the performance?

A:
Each target runs a Swing Timer to calculate its position. This is the ActionListener it calls:

This may be your problem - having each target/bullet (I assume?) responsible for keeping track of when to update itself and draw itself sounds like quite a bit of work. The more common approach is to have a loop along the lines of
while (gameIsRunning) {
  int timeElapsed = timeSinceLastUpdate();
  for (GameEntity e : entities) {
    e.update(timeElapsed);
  }
  render(); // or simply repaint in your case, I guess
  Thread.sleep(???); // You don't want to do this on the main Swing (EDT) thread though
}

Essentially, an object further up the chain has the responsibility to keep track of all entities in your game, tell them to update themselves, and render them.

A: I think what might be at fault here is your whole logic of the games setup (no offense intended), As stated in another answer you have different timers taking care of each entities movement, this is not good. I'd suggest taking a look at some gaming loop examples, and adjusting yours to this, you'll notice a great readability and performance improvement a few nice links:

*

*http://www.java-gaming.org/index.php/topic,24220.0

*http://www.cokeandcode.com/info/tut2d.html

*http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/

A: I was initially wary of the too-many-timer theory. Instances of javax.swing.Timer use "a single, shared thread (created by the first Timer object that executes)." Dozens or even scores are perfectly fine, but hundreds typically start to become sluggish. Depending on period and duty cycle, the EventQueue eventually saturates. I agree with the others that you need to critically examine your design, but you may want to experiment with setCoalesce(). For reference, here's an sscce that you may like to profile.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;

/**
* @see http://stackoverflow.com/a/11436660/230513
*/
public class TimerTest extends JPanel {

    private static final int N = 25;

    public TimerTest() {
        super(new GridLayout(N, N));
        for (int i = 0; i < N * N; i++) {
            this.add(new TimedLabel());
        }
    }

    private static class TimedLabel extends JLabel {

        private static final Random r = new Random();

        public TimedLabel() {
            super("000", JLabel.CENTER);
            // period 100 to 1000 ms; frequency 1 to 10 Hz.
            Timer timer = new Timer(r.nextInt(900) + 100, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    TimedLabel.this.setText(next());
                }
            });
            timer.setCoalesce(true);
            timer.start();
        }

        private String next() {
            return String.valueOf(r.nextInt(900) + 100);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(640, 480);
    }

    private void display() {
        JFrame f = new JFrame("TimerTet");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JScrollPane(this));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TimerTest().display();
            }
        });
    }
}

A: *

*for painting in the Swing is better (in all cases >= Java5) use Swing Timer exclusivelly

*this painting proccess required only one Swing Timer

*example about bunch of Stars and one Swing Timer

A: Try to use one timer for all the targets.
If you have 20 targets then you will also have 20 timers running simultaneously (think about 1000 targets?). There is some expense and the most important thing is each of them is doing the similar job -- to calculate the position -- You don't need to split them. I guess it is a simple task, which will not take you a blink, even running 20 times.
If I got the point, What you want to do is trying to change the positions of all the targets at the same time. You can achieve this by changing all of them in one single method running in one thread.


text:
Q: Binding different collections to datagrid I have some collections. For example, List 1 and List 2. Both are List<Object>.
What I need to do:
1) Insert them into Datagrid:

2) Add new items for Lists. For example, there is some button on form. I click it and new item is adding to first list. Datagrid now look like this:

3) In some way. When I want to pass content of Datagrid to my class object, program must know that List 1 now contain 2 items, but List 2 - 1 item.
How can I in best way perform such features?

A: Here's a sample...
public class ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<SomeItem> VmList { get; set; }
    List<SomeItem> List1 = new List<SomeItem>();
    List<SomeItem> List2 = new List<SomeItem>();
    public ViewModel()
    {
        // VmList is the item source for the grid
        VmList = new ObservableCollection<SomeItem>();
        // create two lists
        for (int i = 0; i < 10; i++)
        {
            List1.Add(new SomeItem{ID = "1", Name = "Name " + i});
        }
        for (int i = 0; i < 10; i++)
        {
            List1.Add(new SomeItem { ID = "2", Name = "Name (2) " + i });
        }
        // merge the two separate lists
        VmList.AddRange(List1);
        VmList.AddRange(List2);
        // get the view
        var lcv = CollectionViewSource.GetDefaultView(VmList);
        // apply a filter
        lcv.Filter = o =>
            {
                var someItem = o as SomeItem;
                if (someItem != null)
                {
                    return someItem.ID == "2";
                }
                return false;
            };
    }
    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string name)
    {
        var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}
public class SomeItem:INotifyPropertyChanged
{
    private string _id;
    public string ID
    {
        [DebuggerStepThrough]
        get { return _id; }
        [DebuggerStepThrough]
        set
        {
            if (value != _id)
            {
                _id = value;
                OnPropertyChanged("ID");
            }
        }
    }
    private string _name;
    public string Name
    {
        [DebuggerStepThrough]
        get { return _name; }
        [DebuggerStepThrough]
        set
        {
            if (value != _name)
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
    }
    #region INotifyPropertyChanged Implementation
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string name)
    {
        var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}
public static class Extensions
{
    public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> list)
    {
        foreach (T t in list)
        {
            collection.Add(t);
        }
    }
}

In this example (which is contrived), the View Model constructor creates two lists and adds them to the observable collection which is bound to the data grid.
The underlying collection view source is then retrieved and a filter is attached to it.
In your application, the filter would be applied in a button event handler instead of the Vm constructor.  This is just a sample to explain how it works.  In my original comment, I noted that you could also use a LINQ zip operator, but instead I included an extension method which is probably more valuable at the moment.  It's called "AddRange".
This approach will allow you to present two lists as a single collection while maintaining their separate identities behind the scenes.  It also shows how to use a filter.
The docs for Collection View Source are here http://msdn.microsoft.com/en-us/library/System.Windows.Data.CollectionViewSource.aspx

A: You can use CompositeCollection  it give an easy ability to bind to multiple collections.
CompositeCollection doesn't have DataContext so if you want to databind one of of your collections, you must reference a FrameworkElement with the desired DataContext.
fo example you can create  CollectionViewSource and bind is a source like that:
<DataGrid.ItemsSource>
    <CompositeCollection>
       <CollectionContainer Collection="{Binding Source={StaticResource Collection1}}" />
       <CollectionContainer Collection="{Binding Source={StaticResource Collection2}}"/>
     </CompositeCollection>
</DataGrid.ItemsSource>


text:
Q: Calling ffmpeg kills script in background only I've got a python script that calls ffmpeg via subprocess to do some mp3 manipulations.  It works fine in the foreground, but if I run it in the background, it gets as far as the ffmpeg command, which itself gets as far as dumping its config into stderr.  At this point, everything stops and the parent task is reported as stopped, without raising an exception anywhere.  I've tried a few other simple commands in the place of ffmpeg, they execute normally in foreground or background.
This is the minimal example of the problem:
import subprocess

inf = "3HTOSD.mp3"
outf = "out.mp3"

args = [    "ffmpeg",
            "-y",
            "-i",   inf,
            "-ss",  "0",
            "-t",   "20",
            outf
        ]

print "About to do"

result = subprocess.call(args)

print "Done"

I really can't work out why or how a wrapped process can cause the parent to terminate without at least raising an error, and how it only happens in so niche a circumstance.  What is going on?
Also, I'm aware that ffmpeg isn't the nicest of packages, but I'm interfacing with something that has using ffmpeg compiled into it, so using it again seems sensible.

A: It might be related to Linux process in background - "Stopped" in jobs? e.g., using parent.py:
from subprocess import check_call

check_call(["python", "-c", "import sys; sys.stdin.readline()"])

should reproduce the issue: "parent.py script shown as stopped" if you run it in bash as a background job:
$ python parent.py &
[1] 28052
$ jobs
[1]+  Stopped                 python parent.py

If the parent process is in an orphaned process group then it is killed on receiving SIGTTIN signal (a signal to stop).
The solution is to redirect the input:
import os
from subprocess import check_call
try:
    from subprocess import DEVNULL
except ImportError: # Python 2
    DEVNULL = open(os.devnull, 'r+b', 0)

check_call(["python", "-c", "import sys; sys.stdin.readline()"], stdin=DEVNULL)

If you don't need to see ffmpeg stdout/stderr; you could also redirect them to /dev/null:
check_call(ffmpeg_cmd, stdin=DEVNULL, stdout=DEVNULL, stderr=STDOUT)

A: I like to use the commands module. It's simpler to use in my opinion.
import commands
cmd = "ffmpeg -y -i %s -ss 0 -t 20 %s 2>&1" % (inf, outf)
status, output = commands.getstatusoutput(cmd)
if status != 0:
    raise Exception(output)

As a side note, sometimes PATH can be an issue, and you might want to use an absolute path to the ffmpeg binary.
matt@goliath:~$ which ffmpeg
/opt/local/bin/ffmpeg

A: From the python/subprocess/call documentation:

Wait for command to complete, then return the returncode attribute.

So as long as the process you called does not exit, your program does not go on.
You should set up a Popen process object, put its standard output and error in different buffers/streams and when there is an error, you terminate the process.
Maybe something like this works:
proc = subprocess.Popen(args, stderr = subprocess.PIPE) # puts stderr into a new stream
while proc.poll() is None:
     try:
        err = proc.stderr.read()
     except: continue
     else:
        if err:
            proc.terminate()
            break


text:
Q: Add thousands separator for view count Question view counts can be hard to read when over 1,000. For example:

*

*"viewed 10000 times" would be clearer as "viewed 10,000 times":

*

*"viewed 298513 times" would be clearer as "viewed 298,513 times":

*

*Thousands separators are used elsewhere, for reputation:

*

*For question counts:


text:
Q: Facebook Canvas login - session not created? So I'm re-writing our old Facebook app (from 2011), bring it up to snuff. It's a straight Canvas app - I just want it to run in the iFrame, it doesn't need any special permissions. I am trying to work from the sample in the PHP SDK docs, and I get no FacebookSession. Here's what I'm working with:
// initialize the FacebookSession with our app and secret
FacebookSession::setDefaultApplication($this->fbapp_settings['appId'], $this->fbapp_settings['secret']);

// create a canvas login helper to deal with login stuff
$this->loginHelper = new FacebookCanvasLoginHelper($this->fbapp_settings['appId'], $this->fbapp_settings['secret']);

try
{
    $this->facebookSession = $this->loginHelper->getSession();
    if (empty($this->facebookSession) )
    {
        throw new Exception("Error, no facebook session created");
    }

    // this is where my code will do something cool

}
catch (FacebookRequestException $ex)
{
    throw new Exception("FacebookException: " . $ex->getMessage() );
}
catch ( Exception $ex)
{
    throw new Exception("Elite Exception: " . $ex->getMessage() );
}

I tried with with "Client OAuth Login" both on and off. Looking in the code for FacebookCanvasLoginHelper->getSession, the problem is that the signedRequest that I get has no OAuthData. Weirdly, it seemed to be working fine early yesterday.
Any thoughts?
Thanks,
Andy
Addendum: Per the previous comment, I re-added the login dialog. So my flow is:
a) Facebook calls my app with a signed_request, which I use to create a FacebookSession, which doesn't have OAuth credentials, so I invoke the Login dialog (created via the FacebookRedirectLoginHelper->getLoginUrl function). The login dialog comes up. I press ok, and Facebook invokes my app again, with a code this time instead of a signed_request. I try to create a FacebookSession - first I need an AccesToken, so I invoke AccessToken::getAccessTokenFromCode, which throws an exception:
'Facebook\FacebookAuthorizationException' with message 'Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request'

Once my app is given permission (through the login dialog) by the user, if I want to get the UID, is this the correct way to do it (i.e., using the "code" to create an AccessToken and use that to create a FacebookSession)?  There is no place in the flow that I can see where i can input the redirect_uri - GetAccessTokenFromCode explicitly sets it to an empty string, I'm guessing that is the problem here.
thanks for your help,
andy

A: Well, I decided to take a leap of faith, and now things have progressed. I:
a) set up a FacebookRedirectLoginHelper at the top of my app
b) get the loginUrl from that, using a pointer to my app (mydomain.com/myapp), and present that for authorization
c) user clicks on that link, gets the Facebook OAuth screen, if they say ok, then Facebook goes back into my app via the redirectUrl embedded in the loginUrl. Using the FacebookRedirectLoginHelper, I get the Facebook Session, and I'm good, I can make a FacebookRequest to get the userProfile and the UID.
There is still a problem, going to open a new ticket for that one.
thanks to the commenters.


text:
Q: Gradle dependency between subprojects I am trying to figure out the proper way to declare a project dependency in gradle, i have this two subprojects:
A java app
apply plugin: 'java'

sourceSets {main {java {srcDirs = ['./']}}}
dependencies{compile project(':p2')}

jar {manifest.attributes(
        'Class-Path': configurations.runtime.files.collect { it.name }.join(''),
        'Main-Class': 'Main'
    )
}

and a java library:
apply plugin: 'java-library'

sourceSets {main {java {srcDirs = ['./']}}
}

jar {
   manifest.attributes(
    'Class-Path': configurations.runtime.files.collect { it.name }.join(' ')
)
}

The root project is empty and the settings just include the subprojects.
The dependencies in the p1 project only tells that p2 must be built before p1, but what about configuring p2 as a lib for p1? Right now if a run p1 i got:
Exception in thread "main" java.lang.NoClassDefFoundError: StaticClass
Gradle build is fine:
C:\...>gradle build
BUILD SUCCESSFUL in 1s
4 actionable tasks: 4 up-to-date

I have to copy and paste p2.jar to the p1.jar directory for it to run properly, how can i get gradle to do it for me?

A: If you're trying to pack the classes from p2 into the p1 jar, try adding this to p1's build.gradle:
jar {
    from project(':p2:').sourceSets.main.output
}

This is a bit unusual, though. Normally, if you've set up a separate library project, you pack it in a separate jar and add it to the classpath of dependent projects, so it's reusable.
Setting the Class-Path on the jar's manifest won't work the way you've written it. The manifest attribute interprets each entry as a file path relative to the working dir of the JVM, but you're just giving it the name of each jar, and Gradle doesn't do any copying or moving of files when setting up configuration classpaths. It's generally not a good idea to rely on the manifest to set the classpath, as it will only work if your jars are arranged on the filesystem exactly as as the manifest expects it. If this is really what you want, then you need to set up an 'installation' directory containing all the required jars arranged as expected. The Gradle Application Plugin can probably help you to achieve this, or something equivalent, but I've never used it.

A: Depending on your exact needs, you should have a look at the java-library-distribution plugin or the application plugin.

*

*The first one will package a jar and its dependencies in an archive.

*The second one will do the same and allow you to configure the main jar to be executable.


text:
Q: Grouping Windows Forms Radiobuttons with different parent controls in C# I've got a Windows Forms application in which I have a number of RadioButtons. These RadioButtons are placed within a FlowLayoutPanel which automatically arranges them for me. All RadioButtons that are directly added to the FlowLayoutPanel are grouped, meaning I can select only one of them. However, some of these RadioButtons are paired up with a TextBox so I can supply some argument there. But to have all this arranged properly, I add a Panel control to the FlowLayoutPanel so I can control the alignment of the RadioButton and TextBox relatively to each other myself.
These RadioButtons now have their own respective Panels as parent controls and thus are no longer included in the radio group with the other RadioButtons. I read that the the RadioButtons that are in the System.Web.UI namespace have a GroupName property, but unfortunately their System.Windows.Forms counterparts lack this property. Is there some other way I can group these radio buttons are am I going to have to handle onClick events myself?
Thanks,
Jerry

A: I agree with @JonH - using tags is the cleanest way to do that (imho)
  private void FormLoad(object sender, EventArgs e)
  {
     radioCsv.Tag = DataTargetTypes.CsvFile;
     radioTabbed.Tag = DataTargetTypes.TxtFile;
     radioSas.Tag = DataTargetTypes.SasFile;
  }

  private void RadioButtonCheckedChanged(object sender, EventArgs e)
  {
     var radio = (RadioButton) sender;
     this.DataDestinationType = (DataTargetTypes)radio.Tag;
  }

A: I'm afraid you'll have to handle this manually... It's not so bad actually, you can probably just store all the RadioButton in a list, and use a single event handler for all of them:
private List<RadioButton> _radioButtonGroup = new List<RadioButton>();
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    if (rb.Checked)
    {
        foreach(RadioButton other in _radioButtonGroup)
        {
            if (other == rb)
            {
                continue;
            }
            other.Checked = false;
        }
    }
}

A: @Jerry, I'm not too familiar with Windows Forms, but I will take a shot. If there a property called Tag, you could tag each radio button with a unique tag.

A: Here is a little improvement over the first answer: create a RadioGroup class that encapsulates the grouping functionality and adds support for standard keyboard navigation (up/down keys) and makes tabbing work.
To use it, simply declare a RadioGroup member in your form and new it (after InitializeComponent()), passing all the radio buttons you want in the group in proper order.
public class RadioGroup
{
    List<RadioButton> _radioButtons;

    public RadioGroup(params RadioButton[] radioButtons)
    {
        _radioButtons = new List<RadioButton>(radioButtons);
        foreach (RadioButton radioButton in _radioButtons)
        {
            radioButton.TabStop = false;
            radioButton.KeyUp += new KeyEventHandler(radioButton_KeyUp);
            radioButton.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
        }
        _radioButtons[0].TabStop = true;
    }

    void radioButton_KeyUp(object sender, KeyEventArgs e)
    {
        e.Handled = true;
        RadioButton radioButton = (RadioButton)sender;
        int index = _radioButtons.IndexOf(radioButton);

        if (e.KeyCode == Keys.Down)
        {
            index++;
            if (index >= _radioButtons.Count)
            {
                index = 0;
            }
            e.Handled = true;
        }
        else if (e.KeyCode == Keys.Up)
        {
            index--;
            if (index < 0)
            {
                index = _radioButtons.Count - 1;
            }
            e.Handled = true;
        }

        radioButton = _radioButtons[index];
        radioButton.Focus();
        radioButton.Select();
    }

    void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton currentRadioButton = (RadioButton)sender;

        if (currentRadioButton.Checked)
        {
            foreach (RadioButton radioButton in _radioButtons)
            {
                if (!radioButton.Equals(currentRadioButton))
                {
                    radioButton.Checked = false;
                }
            }
        }
    }
}

One caveat: the up/down keys won't work well with the existing RadioButton class because it already handles the up/down keys. One easy way to fix it to subclass RadioButton and turn off handling of up/down keys:
public class RadioButtonEx : RadioButton
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Up || keyData == Keys.Down)
        {
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}


text:
Q: Negative of a power of a norm. I have one silly doubt if $\|.\|$ is a norm on a Hilbert space, then is it correct that $$\|x\|^{\mu} = \|-x\|^{\mu}, \qquad \mu \in (0, 1)$$
Please help me to understand the above concept.
According to me, it must be correct as $\|\alpha x \| = |\alpha|\|x\|$, for any scaler $\alpha$.

A: By definition of a norm (see https://en.wikipedia.org/wiki/Norm_(mathematics)#Definition) it is absolutely scalable as you wrote $\|\alpha x\|=|\alpha|\cdot\|x\|$. Therefore it is true to conclude
$\|-x\|=\|x\|$. So, this holds even in normed spaces and further the exponent $\mu$ is totally irrelevant.

A:
We have for a norm $\|.\|$ in a Hilbert-space and $\mu\in(0,1)$
  \begin{align*}
 \color{blue}{\|-x\|^{\mu}}=\|(-1)\cdot x\|^{\mu}=\left(|-1|\|x\|\right)^{\mu}=\color{blue}{\|x\|^{\mu}}
\end{align*}


text:
Q: Setting up a loop to detect keypress in discord.py I am trying to use keypress detection in my code these days and it seems hard to push a keypress detection function to the discord.py bot loop function
Apparently this is what I have been trying to do
    import pyscreenshot as ps
    import keyboard
    from PIL import Image
    from discord.ext import commands
    client=commands.Bot("!")
    async def keypress_detector():
        while True:
            try:
                if keyboard.is_pressed('['):#if key '[' is pressed
                    im=ps.grab()
                    im.save("screenie.png")
                    image_obj = Image.open("screenie.png")
                    cropped_image = image_obj.crop((130, 445, 580, 812))
                    cropped_image.save("updated.png")
                    await client.send_file(client.get_channel('id-here'), "updated.png")
                else:
                    pass
            except Exception as ex:
                return print(str(ex))
    if __name__ == "__main__":
       client.loop.create_task(keypress_detector())
       client.run("TOKEN")

The function works pretty well if i just want to run it normally(outside the bot loop, although it doesnt send the screenshot to the channel), i want the bot to send a screenshot to the chat when i press a certain key. If there is any other way, please tell me.
UPDATE
Got it fixed, didnt work for the first few times but now it does.

A: Due to while True causing an infinite loop that is not asynchronous (discord.py relies on this) you will run into problems. I'm not sure if what you are trying to achieve is actually possible in the realms of python, or any language for that matter. I'm not sure what you're trying to achieve here either, none the less correct me if you know I'm wrong.


text:
Q: extract information from a data frame I have a data frame like below
df<- structure(list(s1 = structure(1:3, .Label = c("3-4", "4-1", "5-4"
    ), class = "factor"), s2 = structure(1:3, .Label = c("2-4", "3-15",
    "7-16"), class = "factor")), .Names = c("s1", "s2"), row.names = c(NA,
    -3L), class = "data.frame")

Looks like below
> df
#   s1   s2
#1 3-4  2-4
#2 4-1 3-15
#3 5-4 7-16

what I want to do is to first search and find those values that are similar after -
for example here 4 is in first row of s1, first row of s2 and third row of s1

-The second column indicates how many times those values were found
-The third column shows how many of them are from first column of df
-The fourth column shows how many of them are from second column of df
-The fifth is which strings are from the first columns
-The sixth is which strings are from teh second columns

the output looks like this
Value    repeated     s1N   s1N   ss1    ss2
4           3         2      1    3,5     2
1           1         1      -     4      -
15          1         -      1     -      3
16          1         -      1     -      7

A: First thing you will need to do is extract the numbers from your strings. Running:
newdfstring <- apply(df,1:2, function(v) unlist(strsplit(v,"-")))
newdf <- apply(newdfstring,1:3, as.numeric)

splits the strings in the first line, and converts them to numeric values in the second. The result is a 3-dimensional matrix which you can use to extract your values.
First create a new dataframe:
#length of the columns in the new frame = number of unique values
dflength <- length(unique(array(newdf[2,,])))
dfout <- data.frame(Value=rep(0,dflength),repeated=rep(0,dflength),s1N=rep(0,dflength),s2N=rep(0,dflength),ss1=rep(0,dflength),ss2=rep(0,dflength))

The most obvious way (yet maybe not the most efficient) would then be to loop and match whatever it is you need:
dfout$Value <- unique(array(newdf[2,,]))
for(i in 1:dflength){
  getID <- which(as.data.frame(table(newdf[2,,]))$Var1==dfout$Value[i])
  dfout$repeated[i] <- as.data.frame(table(newdf[2,,]))$Freq[getID]
  dfout$s1N[i] <- as.data.frame(table(newdf[2,,1]))$Freq[getID]
  if(is.na(dfout$s1N[i])){
    dfout$s1N[i] <- 0
  }
  dfout$s2N[i] <- as.data.frame(table(newdf[2,,2]))$Freq[getID]
  if(is.na(dfout$s2N[i])){
    dfout$s2N[i] <- 0
  }
  getID <- which(newdf[2,,1]==dfout$Value[i])
  if(length(getID)>0){
    dfout$ss1[i] <- toString(newdf[1,,1][getID])
  } else {
    dfout$ss1[i] <- 0
  }
  getID <- which(newdf[2,,2]==dfout$Value[i])
  if(length(getID)>0){
    dfout$ss2[i] <- toString(newdf[1,,2][getID])
  } else {
    dfout$ss2[i] <- 0
  }
}
dfout
#  Value repeated s1N s2N  ss1 ss2
#1     4        3   2   1 3, 5   2
#2     1        1   1   1    4   0
#3    15        1   0   1    0   3
#4    16        1   0   0    0   7

EDIT to loop n amount of s values
newdfstring <- apply(df,1:2, function(v) unlist(strsplit(v,"-")))
newdf <- apply(newdfstring,1:3, as.numeric)
dflength <- length(unique(array(newdf[2,,])))
#find the number of s variables
slength <- length(newdf[1,1,])
#create a matrix of appropriate size
dfout <- matrix(data=NA,nrow=dflength,ncol=(2+2*slength))
#create a (near)-empty names array, we will fill it in later
names <- c("Value","repeated",rep("",2*slength))
#fill in the Values column
dfout[,1] <- unique(array(newdf[2,,]))
#loop for every s variable
for(j in 1:slength){
  #get their names, paste N or s and add them to the names array
  names[2+j] <- paste(names(df)[j],"N",sep="")
  names[2+j+slength] <- paste("s",names(df)[j],sep="")
  #loop to get the other values
  for(i in 1:dflength){
    getID <- which(as.data.frame(table(newdf[2,,]))$Var1==dfout[i,1])
    dfout[i,2] <- as.data.frame(table(newdf[2,,]))$Freq[getID]
    dfout[i,2+j] <- as.data.frame(table(newdf[2,,j]))$Freq[getID]
    if(is.na(dfout[i,2+j])){
      dfout[i,2+j] <- 0
    }
    getID <- which(newdf[2,,j]==dfout[i,1])
    if(length(getID)>0){
      dfout[i,2+j+slength] <- toString(newdf[1,,j][getID])
    } else {
      dfout[i,2+j+slength] <- 0
    }
  }
}
colnames(dfout)<-names
as.data.frame(dfout)
#  Value repeated s1N s2N  ss1 ss2
#1     4        3   2   1 3, 5   2
#2     1        1   1   1    4   0
#3    15        1   0   1    0   3
#4    16        1   0   0    0   7

A: Surprisingly tough problem. It's good to break it down into several logical steps:
## 1: split into (val,ss) pairs, and capture ci (column index) association
res <- setNames(do.call(rbind,lapply(seq_along(df),function(ci)
    do.call(rbind,lapply(strsplit(as.character(df[[ci]]),'-'),function(x)
        data.frame(x[2L],x[1L],ci,stringsAsFactors=F)
    ))
)),c('val','ss','ci'));
res;
##   val ss ci
## 1   4  3  1
## 2   1  4  1
## 3   4  5  1
## 4   4  2  2
## 5  15  3  2
## 6  16  7  2

## 2: aggregate ss (joining on comma) by (val,ci), and capture record count as n
res <- do.call(rbind,by(res,res[c('val','ci')],function(x)
    data.frame(val=x$val[1L],ci=x$ci[1L],n=nrow(x),ss=paste(x$ss,collapse=','),stringsAsFactors=F)
));
res;
##   val ci n  ss
## 1   1  1 1   4
## 2   4  1 2 3,5
## 3  15  2 1   3
## 4  16  2 1   7
## 5   4  2 1   2

## 3: reshape to wide format
res <- reshape(res,idvar='val',timevar='ci',dir='w');
res;
##   val n.1 ss.1 n.2 ss.2
## 1   1   1    4  NA <NA>
## 2   4   2  3,5   1    2
## 3  15  NA <NA>   1    3
## 4  16  NA <NA>   1    7

## 4: add repeated column; can be calculated by summing all n.* columns
## note: leveraging psum() from <http://stackoverflow.com/questions/12139431/add-variables-whilst-ignoring-nas-using-transform-function>
psum <- function(...,na.rm=F) { x <- list(...); rowSums(matrix(unlist(x),ncol=length(x)),na.rm=na.rm); };
res$repeated <- do.call(psum,c(res[grep('^n\\.[0-9]+$',names(res))],na.rm=T));
res;
##   val n.1 ss.1 n.2 ss.2 repeated
## 1   1   1    4  NA <NA>        1
## 2   4   2  3,5   1    2        3
## 3  15  NA <NA>   1    3        1
## 4  16  NA <NA>   1    7        1

With regard to the NAs, you can fix them up afterward if you want. However, I would advise that the proper type of the n.* columns is integer, since they represent counts, therefore the use of '-' (as in your sample output) to represent null cells is inappropriate. I would suggest zero instead. The dash is fine for the ss.* columns, since they are strings. Here's how you can do this:
n.cis <- grep('^n\\.[0-9]+$',names(res));
ss.cis <- grep('^ss\\.[0-9]+$',names(res));
res[n.cis][is.na(res[n.cis])] <- 0L;
res[ss.cis][is.na(res[ss.cis])] <- '-';
res;
##   val n.1 ss.1 n.2 ss.2 repeated
## 1   1   1    4   0    -        1
## 2   4   2  3,5   1    2        3
## 3  15   0    -   1    3        1
## 4  16   0    -   1    7        1

A: I have totally rewritten all the codes based on your real data, and I have tested it on my machine. Since it is a pretty big dataframe, it takes some time to run, and the loops are not avoidable in my opinion.
# function to split the strings
myfun<-function(x){
  x<-strsplit(as.character(x), '-')
  x1<-unlist(x)
  x.new<-as.data.frame(matrix(x1, byrow = T, length(x)))
  return(x.new)
}

# this returns a list of dataframes
list.v<-lapply(df[1:dim(df)[2]], myfun)
# like this
head(list.v[[17]])

# try to combine all the dfs, produced an error of mismatching # of columns
df2<-do.call(rbind, list.v)

# some of the dfs in list.v are all NA's, they should be dropped
sum<-summary(list.v)
list.v<-list.v[-which(sum[,1] != "2")]  # this excludes those all-NA datafrmes in list.v

# now combine all dfs for indexing purposes
df2<-do.call(rbind, list.v)

# create "value", "repeated" column in the desired result df.
# These codes are same as my previous answer
value<-names(table(df2[,2]))
repeated<-as.vector(table(df2[,2]))

# create an empty list to store the counts columns
list.count<-vector("list", length = length(list.v))

# every df in list.v has same number of rows, get the row number
rownum<-nrow(list.v[[1]])

# use a for loop to fill out list.count
for(i in 0:(length(list.count)-1)){
  row.start<-i*rownum+1   # it is kind of tricky here
  row.end<-(i+1)*rownum   # same as above
  list.count[[i + 1]]<-as.vector(table(df2[,2][row.start:row.end]))
}

# combine the vectors in list.count and assing names
count.df<-do.call(cbind, list.count)
count.df<-as.data.frame(count.df)

# create & assign colum names in the format of "s_n", and "_" is filled with corresponding original column name
names.cnt<-character()
for(i in 1:length(names(list.v))){
  names.cnt[i]<-paste("s", names(list.v)[i], "n", sep="")
}
names(count.df)<-names.cnt

# this is a very long loop to concatenate the strings and store them into a matrix, but it gets the job done here.
ss.store<-matrix(,nrow = length(value), ncol = length(list.v), byrow = FALSE)
for(i in 1:length(list.v)){
  for(j in 1:length(value)){
  ss.store[j,i]<-paste(list.v[[i]][,1][which(list.v[[i]][,2] == value[j])], collapse =",")
  }
}

# create a df for strings
string.df<-as.data.frame(ss.store, stringsAsFactors = FALSE)

# create & assign names to the df
names.str<-character()
for(i in 1:length(names(list.v))){
  names.str[i]<-paste("s", "s", names(list.v)[i], sep="")
}
names(string.df)<-names.str

# combine everything and form the new data frame
new.df<-cbind(value, repeated, count.df, string.df, stringAsFactors = FALSE)

new.df[1:10, 1:15]
   value repeated sAn sF1n sF2n sF3n sF4n sF5n sF6n sF7n sF8n sF9n sF10n sF11n sF12n
1    100      155   3    0    0    0    0    0    0    0    0    0     0     0     0
2   1005       14   1    0    0    0    0    0    0    0    0    0     0     0     0
3   1006       50   1    0    0    0    0    0    0    0    0    0     0     0     0
4   1023        1   1    0    0    0    0    0    0    0    0    0     0     0     0
5   1025       38   1    0    0    0    0    0    0    0    0    0     0     0     0
6   1030      624   1    0    1    2    0    0    0    0    0    0     1     0     0
7   1035        1   1    0    0    0    0    0    0    0    0    0     0     0     0
8    104      165   2    0    0    0    0    0    0    0    0    0     0     0     0
9   1076      186   2    0    0    0    0    0    0    0    0    0     0     0     0
10  1078      333   3    0    0    0    0    0    0    0    0    0     0     0     0

A: df <-
  structure(
    list(
      s1 = structure(1:3, .Label = c("3-4", "4-1", "5-4"), class = "factor"),
      s2 = structure(1:3, .Label = c("2-4", "3-15", "7-16"), class = "factor"
      )
    ), .Names = c("s1", "s2"), row.names = c(NA,-3L), class = "data.frame"
  )

library(tidyr)
library(dplyr)

# Split columns at "-" and add to data.frame
splitCols <- function(df) {
  new_headers <- paste("s1", c("1st", "2nd"), sep = "_")
  split_1 <- (separate(df, s1, into = new_headers, sep = "-"))[,new_headers]
  split_1$s1_1st <- as.integer(split_1$s1_1st)
  split_1$s1_2nd <- as.integer(split_1$s1_2nd)

  new_headers <- paste("s2", c("1st", "2nd"), sep = "_")
  split_2 <- (separate(df, s2, into = new_headers, sep = "-"))[,new_headers]
  split_2$s2_1st <- as.integer(split_2$s2_1st)
  split_2$s2_2nd <- as.integer(split_2$s2_2nd)
  cbind(df, split_1, split_2)
}

# given a df outputted from splitCols return final df
analyzeDF <- function(df) {
  target_vals <- unique(c(df$s1_2nd, df$s2_2nd)) # for each uniq val compute stuff
  out_df <- data.frame(Value = integer(0),
                       repeated = integer(0),
                       s1N = integer(0),
                       s2N = integer(0),
                       ss1 = character(0),
                       ss2 = character(0))

  # iterate through target_vals, create a row of output,
  # and append to out_df
  for (val in target_vals) {
    s1_match <- val == df$s1_2nd
    s2_match <- val == df$s2_2nd
    total_cnt <- sum(s1_match, s2_match)
    s1_firstcol <- paste(df$s1_1st[s1_match], collapse = ",")
    s2_firstcol <- paste(df$s2_1st[s2_match], collapse = ",")
    # coerce empty string to "-"
    if (s1_firstcol == "") s1_firstcol <- "-"
    if (s2_firstcol == "") s2_firstcol <- "-"

    row_df <- data.frame(Value = val,
                         repeated = total_cnt,
                         s1N = sum(s1_match),
                         s2N = sum(s2_match),
                         ss1 = s1_firstcol,
                         ss2 = s2_firstcol)
    out_df <- rbind(out_df, row_df)
  }
  return(out_df)
}

(df_split <- splitCols(df))
analyzeDF(df_split)

## Value repeated s1N s2N ss1 ss2
## 1     4        3   2   1 3,5   2
## 2     1        1   1   0   4   -
## 3    15        1   0   1   -   3
## 4    16        1   0   1   -   7


text:
Q: Testing series for convergence I have the following series:
$$\sum_{n=1}^\infty\frac{\sqrt[3]{n}-1}{n(\sqrt n+1)}$$
I have tried comparing with the limit comparison test to a $p$-series. But the limit is hard to evaluate. Any suggestions to prove convergence?

A: You can write:$$\frac {\sqrt [3] {n}-1}{n(\sqrt n+1)}\sim_{\infty}\frac {\sqrt [3] {n}}{\sqrt n\cdot n}\sim_{\infty}\frac {1}{n^{\frac {7}{2}}}$$ that converges

A: Let $N = n^{1/6}$, then we have $$\frac{\sqrt[3]{n}-1}{n(\sqrt n+1)} = \frac {N^2 - 1} {N^6 (N^3 + 1)} = \frac {N + 1} {N^6 (N^2 + N + 1)} < \frac {1} {N^7} = \frac {1} {n^{7/6}},$$ hence $$\sum_{n = 1}^{\infty} \frac{\sqrt[3]{n}-1}{n(\sqrt n+1)} < \sum_{n = 1}^{\infty} \frac {1} {n^{7/6}} = \zeta (\frac {7} {6}) = 6.589\cdots$$


text:
Q: Choosing users for A/B testing I have a table with userid's (int increment) about 4M records.
I would like to show a new feature to only 25% of the users.
What would be the best way to choose those 25% users?

A: you could use some sort of Fisher Yates shuffle algorithm to randomly choose the 'first' 25% of user ids.
ie, pick a random number between 1 and 4M. that's your first user, add it to a collection somewhere. repeat until you have 1M (25%) users in your collection.
Once you have all the users, mark them somehow in your table.

A: How about this?
if (user.Id <= (maxId * 0.25))
{
    // Show a new feature
}

A: Another idea is that you could set a browser cookie which was 'myAwesomeFeature=A' or 'myAwesomeFeature=B'. If the cookie isn't set yet, set it to 'B' if a random number between 0-100 is 25 or less. 'A' otherwise. If the cookie is already set, just use it.
Has the added benefit of being easily testable since you can easily force yourself to be in whichever group you want. And it'll work for multiple features since you just need to change the cookie name. And the same user will get the same group as long as the cookie doesn't expire.


text:
Q: React-Native how to get ID from SVG i am new in react-native and i am trying to programm an Android app there I have the following problem, I have a svg  thats shows all states from germany and I want to get the ID of a state if I press on it.
my code
import React, { useState } from 'react';
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native'
import Germany from '../assets/Karte_Bundesrepublik_Deutschland.svg'

const StatesScreen = () => {

    const handlePress = (stateName) => {
        console.log(stateName.id)
    };

    return (
        <View style={styles.container}>
            <Germany onPress={(e) => handlePress(e)} />
        </View>
    );
};
export default StatesScreen

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
});

Link to the svg:
https://upload.wikimedia.org/wikipedia/commons/2/2c/Karte_Bundesrepublik_Deutschland.svg