text:
Q: Julia language. How to beat vectorized operations? It is said that Julia for-loops are as fast as vectorized operations and even faster (if they are used properly).
I have two pieces of code. The idea is to find a sample statistic for a given 0-1 sequence, which is x (in these two examples i'm trying to find a sum, but there are more complicated examples, i'm just trying to understand a general meaning of performance pitfalls in my code). The first looks like:
S = 2 * sum(x) - n
s_obs_new = abs(S) / sqrt(2 * n)
pval = erfc(s_obs_new)

and the second is something "naive" and classical:
S = 0
for i in eachindex(x)
    S += x[i]
end
S = 2 * S - n
s_obs_new = abs(S) / sqrt(2 * n)
pval = erfc(s_obs_new)

Using @benchmark i've found that the running time of the first example is about 11.8 ms, and for the second is 38 ms.
This example is of very importance for me, because there are a lot of other places, where vectorization isn't possible, so i want to do computations in devectorized "manner" as fast as in vectorized.
Is there any ideas why devectorized code is likely 4x times slower than vectorized? The type stability is OK, there is no unnecessary big memory allocations and etc.
The code for the first function is:
function frequency_monobit_test1( x :: Array{Int8, 1}, n = 0)
# count 1 and 0 in sequence, we want the number
# of 1's and 0's to be approximately the same
# reccomendation n >= 100
# decision Rule(at 1% level): if pval < 0.01 -> non-random
if (n == 0)
    n = length(x)
end
S = 2 * sum(x) - n
s_obs_new = abs(S) / sqrt(2 * n)
pval = erfc(s_obs_new)
return pval

The second is:
function frequency_monobit_test2( x :: Array{Int8, 1}, n = 0)
# count 1 and 0 in sequence, we want the number
# of 1's and 0's to be approximately the same
# reccomendation n >= 100
# decision Rule(at 1% level): if pval < 0.01 -> non-random
if (n == 0)
    n = length(x)
end
S = 0
@inbounds for i in eachindex(x)
    S += x[i]
end
S = 2 * S - n
s_obs_new = abs(S) / sqrt(2 * n)
pval = erfc(s_obs_new)
return pval

A: This is a curious case. There seems to be a performance problem when accumulating Int8s in an Int64 variable.
Let's try these functions:
using SpecialFunctions, BenchmarkTools

function frequency_monobit_test1(x, n=length(x))
    S = sum(x)
    return erfc(abs(2S - n) / sqrt(2n))
end

function frequency_monobit_test3(typ::Type{<:Integer}, x, n=length(x))
    S = zero(typ)
    for i in eachindex(x)
        @inbounds S += x[i]
    end
    return erfc(abs(2S - n) / sqrt(2n))
end

Initializing some vectors
N = 2^25;
x64 = rand(0:1, N);
x8 = rand(Int8[0, 1], N);
xB = rand(Bool, N);
xb = bitrand(N);

Benchmarking:
For Int64 input:
julia> @btime frequency_monobit_test1($x64)
  17.540 ms (0 allocations: 0 bytes)
0.10302739916042186

julia> @btime frequency_monobit_test3(Int64, $x64)
  17.796 ms (0 allocations: 0 bytes)
0.10302739916042186

julia> @btime frequency_monobit_test3(Int32, $x64)
  892.715 ms (67106751 allocations: 1023.97 MiB)
0.10302739916042186

We see that sum and an explicit loop are equally fast, and that initializing with an Int32 is a bad idea.
For Int32 input:
julia> @btime frequency_monobit_test1($x32)
  9.137 ms (0 allocations: 0 bytes)
0.2386386867682374

julia> @btime frequency_monobit_test3(Int64, $x32)
  8.839 ms (0 allocations: 0 bytes)
0.2386386867682374

julia> @btime frequency_monobit_test3(Int32, $x32)
  7.274 ms (0 allocations: 0 bytes)
0.2386386867682374

sum and loop are similar in speed. Accumulating into Int32 saves a bit of time.
Int8 input:
julia> @btime frequency_monobit_test1($x8)
  5.681 ms (0 allocations: 0 bytes)
0.16482999123032094

julia> @btime frequency_monobit_test3(Int64, $x8)
  19.517 ms (0 allocations: 0 bytes)
0.16482999123032094

julia> @btime frequency_monobit_test3(Int32, $x8)
  4.815 ms (0 allocations: 0 bytes)
0.16482999123032094

Explicit loop if slightly faster when accumulating into an Int32, but holy cow! what's going on with Int64? That is super slow!
What about Bool?
julia> @btime frequency_monobit_test1($xB)
  9.627 ms (0 allocations: 0 bytes)
0.7728544347518309

julia> @btime frequency_monobit_test3(Int64, $xB)
  9.629 ms (0 allocations: 0 bytes)
0.7728544347518309

julia> @btime frequency_monobit_test3(Int32, $xB)
  4.815 ms (0 allocations: 0 bytes)
0.7728544347518309

Loop and sum have same speed but, accumulating into Int32 saves half the time.
Now we'll try a BitArray:
julia> @btime frequency_monobit_test1($xb)
  259.044 μs (0 allocations: 0 bytes)
0.7002576522570715

julia> @btime frequency_monobit_test3(Int64, $xb)
  19.423 ms (0 allocations: 0 bytes)
0.7002576522570715

julia> @btime frequency_monobit_test3(Int32, $xb)
  19.430 ms (0 allocations: 0 bytes)
0.7002576522570715

So, sum on a BitArray is crazy fast, because you can perform chunked additions, but extracting single elements in a loop has some overhead.
Conclusions:

*

*You can get similar or better performance with a loop than with sum, except for BitArrays which is a very special case.

*If you know the length of your array, and know that Int32 is enough to hold your sum, then that's a time saver.

*There is something very strange going on when accumulating Int8s into an Int64. I don't know why the performance is so bad.

*If you are only interested in zeros and ones, use an array of Bools, not of Int8s, and possibly accumulate into an Int32.

*BitArrays can be super fast in certain cases.

*sum on a vector of Int8s is strangely fast, twice as fast as sum(::Vector{Bool}).


text:
Q: Why cant i get data from this request and from this address "https://twin-mess-app.glitch.me/login"? var address1 = "https://twin-mess-app.glitch.me/login";
var address2 = "https://fcctop100.herokuapp.com/api/fccusers/top/recent";
$.getJSON(address1 , function (data) {
  jArray = data;
  console.log(jArray);
});

I can log data from address2 in console but i can't log data form address1. Why? How to fix it?

A: The CORS header allows cross origin request on address2 but address1's server does not have this header set.
Cross-Origin Resource Sharing (CORS)

redpajama_set_name: RedPajamaStackExchange


text:
Q: SonarQube regex security hotspot We are using regular expression which supports for MM/DD/YYYY (or) DD/MM/YYYY (or) M/D/YYYY. The regular expression is obj.matches(".*\\d+\\/\\d+\\/[0-9]{4}.*")
But recently when twe introduced sonarqube in our build and it is failing because of this regex (catastrophic backtracking regex). Is there any other regex which can be used ?
we are using java-11.

A: Any pattern that starts with indefinitely quantified patterns like .* or .+ and then containing more subpatterns can slow down code execution with very large strings due to eventual backtracking.
You need to use a method that does not anchor the search at the start and end of the string, and this way you will eliminate .* at the start and end of the pattern:
Matcher m = Pattern.compile("\\d+/\\d+/\\d{4}").matcher(obj);
if (m.find()) {
  // ....
}

Do not escape / chars, they are not special regex metacharacters.
The pattern above is the best you can shorten the pattern to, and you can safely mark the regex as reviewed and good to use.


text:
Q: 'argparse' has no 'ArgumentParser' member Python newbie question...
I am using Python3.6 on macOS and I have installed argpase using

sudo pip3 install argparse

pip3 list does not list argparse but I can see it is installed because "help("argparse") in python3 displays the documentation.
But when I write the following simple test program I receive the error: " 'argparse' has no 'ArgumentParser' member"
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

Ideas?
Thanks in advance

A: Based on the comments, we know that the issue was that the user created a file called argparse.py, which shadowed the standard library argparse.  An easy way to detect if this is the case is to print out the file path location of a module.
>>> import argparse
>>> print(argparse.__file__)
>>> # alternatively you can use inspect
>>> import inspect
>>> print(inspect.getsourcefile(argparse))

This will show where the file is located. It would be easy to debug the problem when you see the file path that is being used.


text:
Q: App not requesting permissions on install I am installing an app over ADB from my build environment.  I am deploying to a physical Nexus 7.  (When deploying to an emulator, there is no problem)
When I deploy, the install appears to succeed, but when the initial intent is lost I get a permission error.
[2012-12-02 23:24:04 - KillerAppRejji] ActivityManager: java.lang.SecurityException:
Permission Denial: starting Intent { act=android.intent.action.MAIN cat=
android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.killerapprejji/.SplashScreen }
from null (pid=6116, uid=2000) requires android.permission.NFC

EDIT: updated manifest.xml with changes to  as opposed to
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.killerapprejji"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="15" />
    <uses-feature android:name="android.hardware.NFC"
              android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.NFC"/>

<application
    android:icon="@drawable/ninjahead"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" android:allowClearUserData="true" android:logo="@drawable/ninjahead" android:persistent="true" android:permission="android.permission.NFC">
    <activity android:name=".MainActivity" android:label="@string/title_activity_main">
        <intent-filter>
          <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
          <data android:mimeType="application/com.killerapprejji.NfcHandle"/>
          <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>
    <activity android:name=".SplashScreen" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".AttackActivity" android:theme="@style/AppTheme" android:label="@string/attack_button"></activity>
    <activity android:launchMode="standard" android:screenOrientation="portrait" android:label="@string/menu_settings" android:alwaysRetainTaskState="true" android:noHistory="false" android:description="@string/menu_settings" android:configChanges="keyboard" android:theme="@style/AppTheme" android:parentActivityName="@string/title_activity_main" android:icon="@drawable/ninjahead" android:name=".SetInfo"></activity>
    <activity android:name=".DefendActivity" android:label="@string/defend_button" android:theme="@style/AppTheme"></activity>
    <activity android:name="DisplayInteractions" android:theme="@style/AppTheme" android:label="@string/Stats" android:parentActivityName="@string/title_activity_main"></activity>
    <activity android:name="NfcHandle">
        <intent-filter >
            <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:mimeType="application/com.killerapprejji.NfcHandle"/>
        </intent-filter>
    </activity>
</application>

</manifest>

A: try <uses-permission ... /> rather than <permission ... />

A: You need <uses-permission android:name="android.permission.NFC" /> in your manifest, you are instead making your own permission with the <permission> tag.

A: My issue arrises from the
<application ... **android:permission="android.permission.NFC">**

When I removed the bolded area, I was able to install the app and run the installed app.


text:
Q: sign of the determinant of a transformation in finite dimensional vector space(s) Why is the definition of the orientation of two bases in a finite dimensional vector space determined by the sign of the determinant of the transformation from one basis to the other?
The definition:

Let V be a finite-dimensional real vector space and let b1 and b2 be two ordered bases for V. It is a standard result in linear algebra that there exists a unique linear transformation A : V → V that takes b1 to b2. The bases b1 and b2 are said to have the same orientation (or be consistently oriented) if A has positive determinant; otherwise they have opposite orientations.

(copied from http://en.wikipedia.org/wiki/Orientation_(vector_space))

A: One reason this makes sense is because special orthogonal matrices (with determinant $1$) would only take bases of one orientation to another basis of the same orientation.
So for example in $3$-space , all "right handed" sets of orthonormal vectors can be rotated into all other right handed sets using a (special) orthogonal matrix.


text:
Q: AWS C# cant figure out how to upload zip stream to S3 bucket I am currently in the process of trying to put 3rd party API data into a S3 bucket via a C# AWS Lambda function. The data from the 3rd party comes in a zip file that I have been able to save locally fine so I am assuming that is working as I need it to. The next step is to upload this data to a S3 bucket but via a stream rather than saving the file locally and uploading etc.
public static async void PutObjectAsync()
    {
        try
        {
            using (var client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2))
            {

                var ms = new MemoryStream();
                GetStream().CopyTo(ms);    //GetStream() returns the api data stream (Stream object).

                var request = new PutObjectRequest()
                {
                    BucketName = "*BUCKETNAME*",
                    Key = "data.zip",
                    InputStream = ms

                };

                var response = await client.PutObjectAsync(request);

            }
        }
        catch (AmazonS3Exception e)
        {
            Console.WriteLine(
                    "Error encountered ***. Message:'{0}' when writing an object"
                    , e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine(
                "Unknown encountered on server. Message:'{0}' when writing an object"
                , e.Message);
        }

        Console.ReadKey();
    }
 }

I get a object reference not set to reference of an object error on the PutObjectAsync function call. I have inspected the request and the memory stream appears to be loaded as expected from the CopyTo method. I am aware that buckets have issues with files over 5MB but the zip file is a lot smaller than 5MB.
This is my first lambda function so any advice would be welcomed. Thanks in advance.

A: As diagnosed in the comments, AWS requires credentials to allow access to the S3 Bucket. Unfortunately it doesnt mention in the documentation that these are required, and are by default looked up from disk as described at https://stackoverflow.com/a/43243290/784908.


text:
Q: Find all the combinations of a particular column and find their frequencies My file is like this-
Pcol       Mcol
P1      M1,M2,M5,M6,M1,M2,M1.M5
P2      M1,M2,M3,M5,M1,M2,M1,M3
P3      M4,M5,M7,M6,M5,M7,M4,M7

I want to find all the combination of Mcol elements and find these combinatinatons are present in how many rows.
Expected output-
Mcol        freq
M1,M2        2
M1,M5        2
M1,M6        1
M2,M5        2
M2,M6        1
M5,M6        2
M1,M3        1
M2,M3        1
M4,M5        1
M4,M7        1
M4,M6        1
M7,M6        1

I have tried this-
x <- read.csv("file.csv" ,header = TRUE, stringsAsFactors = FALSE)
xx <- do.call(rbind.data.frame,
              lapply(x$Mcol, function(i){
                n <- sort(unlist(strsplit(i, ",")))
                t(combn(n, 2))
              }))

data.frame(table(paste(xx[, 1], xx[, 2], sep = ",")))

It doesn't give the expected output
I have also tried this as well-
library(tidyverse)
df1 %>%
   separate_rows(Mcol) %>%
   group_by(Pcol) %>%
   summarise(Mcol = list(combn(Mcol, 2, FUN= toString, simplify = FALSE))) %>%
   unnest %>%
   unnest %>%
   count(Mcol)

But it is not giving the frequency of combination that are present in number of rows.I want the frequency of row in which these combinations are present. That means if M1,M2 are present in P1  and P2 so it will calculate the frequency as 2.

A: An option in tidyverse would be to be split the 'Mcol' with separate_row, grouped by 'Pcol', get the combn of 'Mcol' and after unnesting take the count of 'Mcol' column
library(tidyverse)
df1 %>%
   separate_rows(Mcol) %>%
   group_by(Pcol) %>%
   summarise(Mcol = list(combn(Mcol, 2, FUN= toString, simplify = FALSE))) %>%
   unnest %>%
   unnest %>%
   count(Mcol)
# A tibble: 14 x 2
#   Mcol       n
#   <chr>  <int>
# 1 M1, M2     2
# 2 M1, M3     1
# 3 M1, M5     2
# 4 M1, M6     1
# 5 M2, M3     1
# 6 M2, M5     2
# 7 M2, M6     1
# 8 M3, M5     1
# 9 M4, M5     1
#10 M4, M6     1
#11 M4, M7     1
#12 M5, M6     2
#13 M5, M7     1
#14 M7, M6     1


text: Q: Thunderbird and multiple recipients I want to send a bulk message to about 300 people in a club.  My ISP only allows less than 100 at a time.  How can I configure Thunderbird to send a message to each recipient in smaller groups, or better yet to send one out and then grab the next address and send it out, then on to the next one, etc??


text:
Q: Proving divisibility $x^2\Big|\frac{(xy+1)^n-1}{(xy+1)-1}$. Let $x\in\mathbb{Z}$ be a prime number and let $y=1,2,\ldots,x-1\in\mathbb{Z}$. How to prove that $$x^2\Big|\frac{(xy+1)^n-1}{(xy+1)-1}$$ if and only if $n=x^2k,\; k\in\mathbb{Z}$? Should the binomial expansion be used?

A: Hint: Use the binomial expansion, and then get rid of every term that you know is a multiple of $x^2$.  What remains is a multiple of $x^2$ if and only if the original expansion was a multiple of $x^2$.


text:
Q: How to join a specific column of List with a comma? Instead of using foreach or for to find the last or first element to ignore the comma. I am sure there must be a way to easily concatenate a specific column of a list of DataRows.
Here what I have tried
List<DataRow> rows;

string forms = rows.Aggregate(string.Empty, (current, row) => current + row[1] + ", ");

Output : A, B, C, D,
string forms = rows.Aggregate(string.Empty, (current, row) => current + ", " + row[1]);

Output : ,A, B, C, D
Also tried this suggestion :
string forms = string.Join(", ", Array.ConvertAll(rows.ToArray(), i => i.ToString()));

Output: System.Data.DataRow, System.Data.DataRow, System.Data.DataRow, System.Data.DataRow<>
What is wanted:
Output A, B, C, D

A: you forgot to get row[1], if you do row.ToString() the output is the class name DataRow
string forms = string.Join(", ", rows.Select(row => row[1].ToString()).ToArray());

if you are on .NET > 4 you can skip the .ToArray() because there is an IEnumerable overload
string forms = string.Join(", ", rows.Select(row => row[1].ToString()));

or with ConvertAll
string forms = string.Join(", ", Array.ConvertAll(rows.ToArray(), i => i[1].ToString()));

A note: Aggregate throw System.InvalidOperationException: "Sequence contains no elements" if no elements, instead String.Join return empty string

A: string forms = rows.Select(row => row[1])
                   .Aggregate((current, next) => current + ", " + next);

This transforms into values first and concatenates them. It's easier in two steps.


text:
Q: Firebase Cloud Function Volley Post request returning Unexpected response code 500 Im trying to call a Clound function using a Volley POST request but it is returning error Unexpected response code 500. What this code does is basically request a Token string from the user and then reformat it with new info and then return the new token to the user.
Here is the Java code
        RequestQueue mRequestQueue = Volley.newRequestQueue(this);
        StringRequest mCloudRequest = new StringRequest(Request.Method.POST,
                "my_function_url_from_firebase", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                signInToFirebaseWithCustomToken(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String>  params = new HashMap<String, String>();

                params.put("id_token", huaweiAccount.getIdToken());
                params.put("uid", uid);
                params.put("name", huaweiAccount.displayName);
                if (huaweiAccount.email != null) {
                    params.put("email", huaweiAccount.email);
                } else {
                    params.put("email", "");
                }
                params.put("photoURL", "");

                return params;

            }
        };

And here is the index.js file.
const app = express();
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 5000;
const functions = require('firebase-functions');

// Firebase Admin SDK
const admin = require('firebase-admin');
const serviceAccount = require('./serviceAccountKey.json');

// For make network calls
const request = require('request-promise');

// Initialize Firebase Admin
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'my_firebase_server_url',
});

// Initialize Express and create endpoint
app
    .use(bodyParser.json()) // Parse json in request body
    .use(bodyParser.urlencoded({
      extended: true,
    }))
    .post('/createCustomToken', (req, res) => {
      if (req.body.id_token === undefined) {
        // idToken is not find
        const ret = {
          error_message: 'id_token not found',
        };
        return res.status(400).send(ret);
      }

      // Verify idToken
      // Create new user on Firebase if user doesn't exist
      // Generate custom auth token
      // Return client
      return verifyHuaweiToken(req.body)
          .then((customAuthToken) => {
            const ret = {
              firebase_token: customAuthToken,
            };
            return res.status(200).send(ret);
          }).catch((err) => {
            return res.status(400).send(err);
          });
    })
    .listen(PORT, () => console.log(`Listening on ${ PORT }`));
// Verify idToken on Huawei Server
function verifyHuaweiToken(body) {
  return request({
    method: 'GET',
    uri: 'https://oauth-login.cloud.huawei.com/oauth2/v3/tokeninfo?id_token=' + body.id_token,
    json: true,
  }).then((response) => {
    // Token invalid. Throw an error and stop process
    if (response.error !== undefined) {
      return Promise.reject(new Error('Something went wrong'));
    }
    // Get user
    return getFirebaseUser(body);
  }).then((userRecord) => {
    // After user created on Firebase, create new custom token based on user uid
    return admin.auth().createCustomToken(userRecord.uid);
  }).then((token) => {
    // Return token to client
    return token;
  });
}
function getFirebaseUser(body) {
  const firebaseUid = 'huawei_' + body.uid;

  // Find user by user uid
  return admin.auth().getUser(firebaseUid).then(function(userRecord) {
    return userRecord;
  }).catch((error) => {
    // If user is not exist on Firebase, create new one
    if (error.code === 'auth/user-not-found') {
      return admin.auth().createUser({
        uid: firebaseUid,
        displayName: body.name,
        photoURL: body.picture,
        email: body.email,
      });
    }
    return Promise.reject(error);
  });
}
exports.app = functions.https.onRequest(app);

Does anyone know what is wrong with my backend code? or is it the user side code the one causing the problem?
Please help me. Im not a Backend expert.

A: a simple example in firebase functions to create custom token would be like this one:
const functions = require('firebase-functions');
const firebaseAdmin = require('firebase-admin');
const express = require('express');
const app = express();

firebaseAdmin.initializeApp({
  serviceAccountId: 'SERVICE-ACCOUNT_EMAIL',
  databaseURL: 'https://PTOJECT-id.firebaseio.com'
});

app.post('/token', async (req, res) => {
  try {
    const token = await firebaseAdmin.auth().createCustomToken(req.body.userUID);
    res.status(200).send(token)
  } catch (error) {
    res.status(500).send("something went wrong")
  }
});
module.exports.app = functions.https.onRequest(app);

make sure that your service account has at least the iam.serviceAccounts.signBlob permission which is included in the role roles/iam.serviceAccountTokenCreator


text:
Q: Android Flavors, ContentProviders, SyncAdapters and AccountManager I have defined a few flavors and buildTypes for my android app
productFlavors {
    X {
        applicationId = "com.x.xxxx"
    }
    Y {
        applicationId = "com.y.yyyy"
    }
}

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard_rules.txt'
    }

    debug {
        applicationIdSuffix ".debug"
    }
}

That does the job of creating different flavors/buildType combinations.
Now to make sure that ContentProviders works and I do not get a Failure [INSTALL_FAILED_CONFLICTING_PROVIDER] error, I have changed the android:authorities="${applicationId}" and AUTHORITY references in code to BuildConfig.APPLICATION_ID.
That makes the ContentProvider work fine i.e it does not throw an error when I install two different types on the same phone. It lets me install them.
Next step is where the error is. I use SyncAdapter and AccountManager to control a few things. I have modified the ACCOUNT_TYPE to use the APPLICATION_ID. Because of the issue with gradle not being able to use ${applicationId} in non-manifest xml resource files, I have created a different directory structure for each flavor and copied the syncadapter.xml and authenticator.xml with corresponding authority and account type strings.
I have also tried the technique described in this blog - http://blog.jensdriller.com/android-gradle-workaround-for-missing-placeholder-support-in-resource-files/
And the top voted answers on Using build types in Gradle to run same app that uses ContentProvider on one device but things don't seem to work.
Anyone been able to get this to work recently?


text:
Q: How to check if a uiimage is blank? (empty, transparent) which is the best way to check whether a UIImage is blank?
I have this painting editor which returns a UIImage; I don't want to save this image if there's nothing on it.

A: Try this code:
BOOL isImageFlag=[self checkIfImage:image];

And checkIfImage method:
- (BOOL) checkIfImage:(UIImage *)someImage {
    CGImageRef image = someImage.CGImage;
    size_t width = CGImageGetWidth(image);
    size_t height = CGImageGetHeight(image);
    GLubyte * imageData = malloc(width * height * 4);
    int bytesPerPixel = 4;
    int bytesPerRow = bytesPerPixel * width;
    int bitsPerComponent = 8;
    CGContextRef imageContext =
    CGBitmapContextCreate(
                          imageData, width, height, bitsPerComponent, bytesPerRow, CGImageGetColorSpace(image),
                          kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big
                          );

    CGContextSetBlendMode(imageContext, kCGBlendModeCopy);
    CGContextDrawImage(imageContext, CGRectMake(0, 0, width, height), image);
    CGContextRelease(imageContext);

    int byteIndex = 0;

    BOOL imageExist = NO;
    for ( ; byteIndex < width*height*4; byteIndex += 4) {
        CGFloat red = ((GLubyte *)imageData)[byteIndex]/255.0f;
        CGFloat green = ((GLubyte *)imageData)[byteIndex + 1]/255.0f;
        CGFloat blue = ((GLubyte *)imageData)[byteIndex + 2]/255.0f;
        CGFloat alpha = ((GLubyte *)imageData)[byteIndex + 3]/255.0f;
        if( red != 1 || green != 1 || blue != 1 || alpha != 1 ){
            imageExist = YES;
            break;
        }
    }

    free(imageData);
    return imageExist;
}

You will have to add OpenGLES framework and import this in the .m file:
#import <OpenGLES/ES1/gl.h>

A: One idea would be to call UIImagePNGRepresentation to get an NSData object then compare it with a pre-defined 'empty' version - ie: call:
- (BOOL)isEqualToData:(NSData *)otherData

to test?
Not tried this on large data; might want to check performance, if your image data is quite large, otherwise if it's small it is probably just like calling memcmp() in C.

A: Something along these lines:

*

*Create a 1 px square CGContext

*Draw the image so it fills the context

*Test the one pixel of the context to see if it contains any data. If it's completely transparent, consider the picture blank

Others may be able to add more details to this answer.

A: Here's a solution in Swift that does not require any additional frameworks.
Thanks to answers in a related question here:
Get Pixel Data of ImageView from coordinates of touch screen on xcode?
func imageIsEmpty(_ image: UIImage) -> Bool {
    guard let cgImage = image.cgImage,
          let dataProvider = cgImage.dataProvider else
    {
        return true
    }

    let pixelData = dataProvider.data
    let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
    let imageWidth = Int(image.size.width)
    let imageHeight = Int(image.size.height)
    for x in 0..<imageWidth {
        for y in 0..<imageHeight {
            let pixelIndex = ((imageWidth * y) + x) * 4
            let r = data[pixelIndex]
            let g = data[pixelIndex + 1]
            let b = data[pixelIndex + 2]
            let a = data[pixelIndex + 3]
            if a != 0 {
                if r != 0 || g != 0 || b != 0 {
                    return false
                }
            }
        }
    }

    return true
}

A: I'm not at my Mac, so I can't test this (and there are probably compile errors). But one method might be:
//The pixel format depends on what sort of image you're expecting. If it's RGBA, this should work
typedef struct
{
   uint8_t red;
   uint8_t green;
   uint8_t blue;
   uint8_t alpha;
} MyPixel_T;

UIImage *myImage = [self doTheThingToGetTheImage];
CGImageRef myCGImage = [myImage CGImage];

//Get a bitmap context for the image
CGBitmapContextRef *bitmapContext =
CGBitmapContextFreate(NULL, CGImageGetWidth(myCGImage), CGImageGetHeight(myCGImage),
                      CGImageGetBitsPerComponent(myCGImage), CGImageGetBytesPerRow(myCGImage),
                      CGImageGetColorSpace(myCGImage), CGImageGetBitmapInfo(myCGImage));

//Draw the image into the context
CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(myCGImage), CGImageGetHeight(myCGImage)), myCGImage);

//Get pixel data for the image
MyPixel_T *pixels = CGBitmapContextGetData(bitmapContext);
size_t pixelCount = CGImageGetWidth(myCGImage) * CGImageGetHeight(myCGImage);

for(size_t i = 0; i < pixelCount; i++)
{
   MyPixel_T p = pixels[i];
   //Your definition of what's blank may differ from mine
   if(p.red > 0 && p.green > 0 && p.blue > 0 && p.alpha > 0)
      return NO;
}

return YES;

A: I just encountered the same problem. Solved it by checking the dimensions:
Swift example:
let image = UIImage()

let height = image.size.height
let width = image.size.height

if (height > 0 && width > 0) {
    // We have an image
} else {
    // ...and we don't
}


text:
Q: Is it possible to add/remove props of components from a method on the main Vue instance? On Vue.js, I have a v-button component with a prop named loading.
Component:
Vue.component('v-button', {
    props: ['loading'],
    template: '<button class="btn btn-info"> Loading... <slot></slot> </button>'
});

Vue:
new Vue({
    el: '#app',
    components: ['v-button'],
    methods: {
        niceMethod: function(argument) {
        console.log(argument);
        // Considering that I will have a large amount of v-buttons:
        // Is it possible to do something here to add or remove the prop "loading" ONLY on the v-button I've clicked?
    }
  }
})

Body:

<v-button @click.native="niceMethod('testing!')">Test</v-button>

<v-button @click.native="niceMethod('hello!')">Hello</v-button>

<v-button @click.native="niceMethod('vue!')">Vuejs</v-button>

Considering that I will have a large amount of v-buttons: Is it possible to do something on the Vue instance to add or remove the prop loading only on the v-button I've clicked?
Did I missed something on Vue.js docs?
Sorry if my question is not clear... If so, please check the JSFiddle I did.

A: Why not just toggle a data loading true/false inside the component ?

Vue.component('v-button', {
  template: '<button class="btn btn-info" @click="clickMe"> Loading... <slot></slot> </button>',
  data() {
    return {
      loading: false
    }
  },
  methods: {
    clickMe() {
      this.loading = !this.loading
    }
  }
});

new Vue({
  el: '#app',
  components: ['v-button'],
})

<v-button>Test</v-button>

<v-button>Hello</v-button>

<v-button>Vuejs</v-button>


text:
Q: Pandas - Create new column where values are taken from other rows in the same dataframe I have a DataFrame like this:
    message_id  reply_to_id     sender
0   1           0               Roozbeh
1   2           1               Amir
2   3           0               Neda
3   4           2               Roozbeh
3   5           2               Neda

If the message was a reply to another message, reply_to_id shows the id of the message that it was replied to, otherwise it's 0. Now I want to create another column, reply_to_sender, where it shows the name of the sender of the message that it was replied to (and if it wasn't a reply, it can show NaN)
The message_id column is unique, but reply_to_id and sender columns are obviously not.
I tried this:
data["reply_to_sender"] = data.loc[data["reply_to_id"] == data["message_id"]]["sender"]

But it obviously won't work, because it looks at each row and perform the relational operation. What I'm trying to do is to look at each row and then find the name of the sender from other rows. For the example above, the output needs to be like this:
    message_id  reply_to_id     sender    reply_to_sender
0   1           0               Roozbeh   NaN
1   2           1               Amir      Roozbeh
2   3           0               Neda      NaN
3   4           2               Roozbeh   Amir
3   5           2               Neda      Amir

How can I do that?

A: Use Series.map with Series created by message_id and sender:
df['reply_to_sender'] = df['reply_to_id'].map(df.set_index('message_id')['sender'])
print (df)
   message_id  reply_to_id   sender reply_to_sender
0           1            0  Roozbeh             NaN
1           2            1     Amir         Roozbeh
2           3            0     Neda             NaN
3           4            2  Roozbeh            Amir
3           5            2     Neda            Amir

A: First, let's see how you would do this yourself, by hand. Then we implement it in code.
If I give you a reply_to_id, you can tell me who this message was a reply to, by simply looking at the DataFrame, finding the row whose message_id is equal to that number, and then telling me the value in that row's sender column. This can be done like this, where the reply_to_id variable is the number I gave you:
data.loc[data["message_id"] == reply_to_id]["sender"]

Now this code returns a pandas.Series, but we didn't ask for a Series, we asked for a scalar value which is the name of the sender. So we need to extract that value from the Series. If there's only one value in the Series (you need to check that), we can extract it using pandas.Series.values[0]. So the code becomes like this:
reply_to_sender_values = data.loc[data["message_id"] == reply_to_id]["sender"].values
if len(reply_to_sender_values) == 1:
    return reply_to_sender_values[0]

Now what would happen if I gave you a number that you didn't find in message_id? What would you do? You'd tell me that you found nothing. That translates to this:
reply_to_sender_values = data.loc[data["message_id"] == reply_to_id]["sender"].values
if len(reply_to_sender_values) == 1:
    return reply_to_sender_values[0]
else:
    return ""

There's one more thing we need to pay attention to. As you said, the values in reply_to_id can be zero. So we need to take care of that:
if(reply_to_id != 0):
    reply_to_sender_values = data.loc[data["message_id"] == reply_to_id]["sender"].values
    if len(reply_to_sender_values) == 1:
        return reply_to_sender_values[0]
    else:
        return ""
else:
    return ""

As you can see, we've just built a function to do what you would do by hand. Let's give it a name:
def reply_to_sender(reply_to_id):
    if(reply_to_id != 0):
        reply_to_sender_values = data.loc[data["message_id"] == reply_to_id]["sender"].values
        if len(reply_to_sender_values) == 1:
            return reply_to_sender_values[0]
        else:
            return ""
    else:
        return ""

All there's left to do is to find a way to apply this function on all the rows in reply_to_id column of our DataFrame. Luckily, there's this method in Pandas that does just that. And it's called, you guessed it, pandas.DataFrame.apply. Now it all comes together with this line of code:
data["reply_to_sender"] = data["reply_to_id"].apply(lambda x: reply_to_sender(x))

One thing to notice, I tested this code in a Jupyter Notebook. If you want to run this code from a script, you need to pass the DataFrame to your reply_to_sender function. So the code changes to this:
def reply_to_sender(data, reply_to_id):
    if(reply_to_id != 0):
        reply_to_sender_values = data.loc[data["message_id"] == reply_to_id]["sender"].values
        if len(reply_to_sender_values) == 1:
            return reply_to_sender_values[0]
        else:
            return ""
    else:
        return ""

data["reply_to_sender"] = data["reply_to_id"].apply(lambda x: reply_to_sender(data, x))

A: You can do
mymap = {val: df.sender.loc[key] for key, val in df.message_id.to_dict().items()}

and then
df['reply_to_sender'] = df.reply_to_id.map(mymap)

This give you
   message_id  reply_to_id   sender reply_to_sender
0           1            0  Roozbeh             NaN
1           2            1     Amir         Roozbeh
2           3            0     Neda             NaN
3           4            2  Roozbeh            Amir
3           5            2     Neda            Amir


text:
Q: I am facing a problem in JavaScript/ReactJS I am working in ReactJS on post API. I have given a task to create some text fields in which I have to give some values and then on click of a submit button the information from text field will be submitted to POST API which I have taken from JasonPlaceHolder.
I have written a code which is given at last. Whenever I click Register button the value in last input field (which in my case is "EMAIL") overrides the values of all the input fields.
A screenshot of my problem is also attached:

Code
import React from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {
          error: null,
          isLoaded: false,
          items: [],
          inter:0,
          ID: '',
          Name: '',
          username : '',
          Email: ''
        };
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
  }
  updateInput(event){
    this.setState({ID : event.target.value})
    this.setState({Name : event.target.value})
    this.setState({username : event.target.value})
    this.setState({Email : event.target.value})
    }
  handleSubmit(){
    var dict = { id: this.state.ID, name:this.state.Name , username: this.state.username , email: this.state.Email };

    axios.post('https://jsonplaceholder.typicode.com/users', dict)
    .then(response => {
      console.log(response)
      this.setState({isLoaded:true,
                      flag:1,
                    })
    })
    .catch(error => {
      alert(error);
      console.log(error);
    })
    }

  render() {

    const { error, isLoaded, items } = this.state;

    if (this.state.inter == 0){

      return(

<form>

ID:<input type="text" name="ID" onChange={this.updateInput}/>

Name:<input type="text" name="name" onChange={this.updateInput} />

User Name:<input type="text" name="username" onChange={this.updateInput} />

Email: <input type="text" name="email" onChange={this.updateInput} />

</form>

      <button onClick={this.handleSubmit}>
      Register
      </button>

      );

    }else{

      return(

      <button onClick={this.handleSubmit} >
      Register
      </button>

 Post Request Submitted Successfully

      );
    }

  }

  componentDidMount() {

    }
}

export default App;

A: You have to update the fields like this,
updateInput({target: {name, value}}){
    this.setState({[name]: value});
  }

A: Change your updateInput logic to this.
updateInput(event){
  this.setState({[event.target.name] : event.target.value})
}

A: The issue is in the updateInput method. change it to.
const { name, value } = event.target;
this.setState(state => ({
  ...state, [name]: value,
}));

N:B You will have to make the names of the input element same as the state field.

A: Your updateInput method overrides all the other fields, that's why the last updated field (the email) is the one you are seeing on the request payload.
To solve this you can separate the updateInput method for each input field or inside updateInput check which field you're currently updating and update only that field.
You can check here for more details:
https://medium.com/@zacjones/handle-multiple-inputs-in-react-with-es6-computed-property-name-e3d41861ae46


text:
Q: Remove button border when entered When I hover over buttons on my C# form I have them highlighted yellow like how Microsoft office products but I don't want it to show the button border. I've seen people mention FlatStyle or FlatAppearance but it doesn't seem to recognize those commands. I'm looking into rendering now but I'm new to C# and I'm certain there must be a simple way to do it, It's not something I want to spend a lot of time on if possible.
I must stress I've been reading through books on windows forms programming and haven't found any answers its not that I'm lazy but I often find SO a very good source with really good input.
Tried this:
this.TSVehicleButton.BorderStyle = None;

Tried this:
this.TSVehicleButton.System.Windows.Forms.BorderStyle = None;

I tried lots of things but didn't mention it as part of my question, I'm new to C# and didn't want to come across as stupid. People get a little bitchy when people put things that they tried and isn't right.

A: Use following on
public class CustomButton : Button
{
    public CustomButton()
        : base()
    {
        // Prevent the button from drawing its own border
        FlatAppearance.BorderSize = 0;
        FlatStyle = System.Windows.Forms.FlatStyle.Flat;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // Draw Border using color specified in Flat Appearance
        Pen pen = new Pen(FlatAppearance.BorderColor, 1);
        Rectangle rectangle = new Rectangle(0, 0, Size.Width - 1, Size.Height - 1);
        e.Graphics.DrawRectangle(pen, rectangle);
    }
}

I might help you.

A: just use this.FlatStyle = FlatStyle.Flat;

A: Just set the following Button properties, for example at design time in the properties window:
FlatStyle=Flat
FlatAppearance.BorderSize=0

Or run the following code, for example for a button named button1:
button1.FlatStyle=True
button1.FlatAppearance.BorderSize=0

A: This worked perfectly for me, and it's so simple!
button.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); // transparent
button.FlatAppearance.BorderSize = 0;

Now the button has no borders, even when you enter the cursor. This worked perfectly on Visual Studio 2015.

A: there is a way of taking the border away from the button and its in the button properties.
First make sure you have clicked on the button so that the properties belong to the button.
on the properties pane go and find Flat Appearance and expand it by clicking on the + sign in front of it.
This will open more option for you, one of the option is border size which is set to 1, change this to 0,
Next, 3 lines below that there is a property called FlatStyle and its set to standard, this needs to be changed to Flat.
Flat
Job done!
Hope this helps


text:
Q: Fatal Error: 'openssl/conf.h' file not found I'm using a compiler to try to make a set of files I've been given and the line #include  breaks with the error: Fatal Error: 'openssl/conf.h' file not found.
I've already installed openssl using brew, but it doesn't seem to work. Do I need to somehow connect openssl with my folder that I'm working in?
I'm on the newest mac OS sierra.

A: Running:
brew info openssl

gives the solution :
For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include


text:
Q: A unique type of data conversion in the following code
tt=5;
   for(i=0;i<tt;i++)
    {

        int c,d,l;
        scanf("%lld%lld%lld",&c,&d,&l);
        printf("%d %d %d %d",c,d,l,tt);
    }

in the first iteration, the value of 'tt' is changing to 0 automatically.
I know that i have declared c,d,l as int and taking input as long long so it is making c,d=0. But still, i m not able to understand how tt is becoming 0.

A: Small, but obligatory announcement. As it was said in comments, you face undefined behavior, so

*

*don't be surprised by tt assigned to zero

*don't be surprised by tt not assigned to zero after insignificant code changes (e.g. reordering initialization from "int i,tt;" to "int tt, i;" or vice versa)

*don't be surprised by tt not assigned to zero after compiling with different flags or different compiler version or for different platform or for testing with different input

*don't be surprised by anything. Any behavior is possible.

You can't expect this code to work one way or another, so don't ever use it in real program.
However, you seem to be OK with that, and the question is "what is actually happening with tt". IMHO this question is really great, it reveals passion to understand programming deeper, and it helps in digging into lower layer. So lets get started.
Possible explanation
I failed to reproduce behavior on VS2015, but situation is quite clear. Actual data aligning, variable sizes, endianness, stack growth direction and other details may differ on your PC, but the general idea should be the same.
Variables i, tt, c, d, l are local, so they are stored on stack. Lets assume, sizeof(int) is 4 and sizeof(long long) is 8 which is quite common. Then one of possible data alignments is shown on picture (addresses grow from left to right, each cell represents one byte):

When doing scanf, you pass address of c (blue arrow on next pict) for filling with data. But size of data is 8 bytes, so data of both c and tt are overwritten (blue cells on the pict). For little-endian representation, you always write zeroes to tt unless really big number is entered by user, while c actually gets valid data for small numbers.

However, valid data in c will be rewritten the same way during filling d, the same will happen to d while filling l. So only l will get nonzero value in described case. Easy test: enter large number for c, d, l and check if tt is still zero.
How to get precise answer
You can get all answers from assembly code. Enable disassembly listing (exact steps depend on toolchain: gcc has -S option, visual studio has "goto disassembly" item in context menu while on breakpoint) and analyze listing. It's really helpful to see exact instructions your CPU is going to execute. Some debuggers allow executing instructions one by one. So you need to find out how variables are alligned on stack and when exactly are they overwritten. Analyzing scanf is hard for beginners, so you can start with the simplified version of your program: replace scanf with the following (can't test, but should work):
*((long long *)(&c)) = 1; //or any other user specified value
*((long long *)(&d)) = 2;
*((long long *)(&l)) = 3;


text:
Q: NAT@force error when the citation is called in different ways When compiling a .tex file that has the preamble shown at the end of this post, I get the following error:
 ! Package natbib Error: Bibliography not compatible with author-year citations.

 (natbib)                Press <return> to continue in numerical citation style.

 See the natbib package documentation for explanation.
 Type  H <return>  for immediate help.
  ...

 l.96 ...mand\NAT@force@numbers{}\NAT@force@numbers

 ?

In the .tex file, I have declared the bibliography to be read into library.bib:
\bibliographystyle{ieeetr}
\bibliography{./library}

I have analized in a very detailed way the library.bib file, removing each citation, one by one, until the above error disappear.
The problem was with this citation:
 @Article{Thermal-expansion-coefficients-Calcite-old-paper,
 author = "R. Srinivasan",
 title = "The thermal expansion of calcite form room temperature up to 400",
 journal = "Proceedings of the Indian Academy of Sciences - Section A",
 volume = "42",
 pages = "81 - 85",
 year = "1955",
 }

If you try to:
a) use my preamble,
b) copy this citation into a new .bib file: library_clean.bib,
c) and make the document to call to this file:
 This is a citation \cite{Thermal-expansion-coefficients-Calcite-old-paper}

and:
\bibliographystyle{ieeetr}
\bibliography{./library_clean}

you will get the above error.
So, this indicates that the error is related to this citation.
I have modified the citation, and the error disappears when at least one - is changed by a _, for example all these possibilities 1-5 do not produce the above error:
1)    @Article{Thermal_expansion-coefficients-Calcite-old-paper,
     ...
2)    @Article{Thermal-expansion_coefficients-Calcite-old-paper,
     ...
3)     @Article{Thermal-expansion-coefficients_Calcite-old-paper,
     ...
4)     @Article{Thermal-expansion-coefficients-Calcite_old-paper,
     ...
5)     @Article{Thermal-expansion-coefficients-Calcite-old_paper,
     ...
However, as I said, the @Article{Thermal-expansion-coefficients-Calcite-old-paper, produces that error.
I would appreciate if you could help me.
Preamble:
 \documentclass[12pt]{article}

 \usepackage[left=2.5cm,top=2.5cm,right=2.5cm,bottom=2.5cm]{geometry}

 \usepackage{graphicx}
 \usepackage[longnamesfirst]{natbib}
 \usepackage{amsmath} % Required for some math elements
 \setcitestyle{square}
 \usepackage{caption,setspace}
 \usepackage{enumerate}

 \usepackage[british]{babel}
 \usepackage[utf8]{inputenc}
 \usepackage{amssymb}

 \usepackage{datetime}                           % custom date
    \newdateformat{mydate}{\monthname[\THEMONTH] \THEYEAR}

 \usepackage{subcaption}
 \usepackage{courier}
 \usepackage{enumitem}
 \usepackage{multirow}
 \usepackage[version=3]{mhchem}
 \usepackage{rotating}
 \usepackage{subcaption}
 \usepackage{mathtools}
 \newcommand{\angstrom}{\mbox{\normalfont\AA}}
 \usepackage{adjustbox}
 \usepackage{textcomp}
 \usepackage{url}
 \usepackage{enumitem}
 \usepackage{comment}

 \setlength\parindent{0pt} % Removes all indentation from paragraphs

 \captionsetup{font={footnotesize,sf,small,stretch=1},labelfont=bf}

 \renewcommand{\labelenumi}{\alph{enumi}.} % Make numbering in the enumerate environment by letter rather than number (e.g. section 6)
 \usepackage{fancyvrb}
 \usepackage{color,soul}

 \newcommand\hb{HB}
 \newcommand\gb{GB}
 \newcommand\dd{DD}

 \DeclareMathOperator{\csch}{csch}

A: Delete the option longnamesfirst and add the option numbers when loading the natbib package. The option longnamesfirst only makes sense if you use authoryear-style citation call-outs. However, the ieeetr bibliography style can only generate numeric-style citation callouts.


text:
Q: Peer-to-peer transfer during migration extremely slow I have one 2019 MacBook and a 2021 MacBook Pro connected to each other via the Thunderbolt ports to do a migration. Given there are only about 700 files to transfer, I would expect it to take less than 2 hours tops.
Instead it is transferring at only 21 MB/s, which is dramatically slower than a WiFi download. Current estimate to complete is 49 hours.
What is going on with my connection? Is there anyway to speed this up?


text:
Q: MongoDB Error - Can't get Player Data I'm working on a Framework for a Minecraft Server and I'm running into a constant error while retrieving player data from a MongoDB database. I have both a proxy plugin and a spigot plugin that the framework is shaded into.
For the proxy plugin, I can get and store the player data in my PlayerCache (A map that assigns UUIDs to PlayerData objects), but however, for the spigot plugin, I cannot. It returns a null pointer, saying that the data is not found in the cache, even though I am sure I called the cacheData method.
I believe what is going on is that I'm not allowing enough time for the database to get the information and cache it.
Spigot code:
@EventHandler
public void onLogin(PlayerLoginEvent event)
{
    PlayerCache.getInstance().cachePlayer(event.getPlayer().getUniqueId());
}

@EventHandler
public void onJoin(PlayerJoinEvent event)
{
    event.setJoinMessage(null);
    event.getPlayer().setDisplayName(PlayerCache.getInstance().getCachedRank(
            event.getPlayer().getUniqueId()
    ).getColor() + event.getPlayer().getName()); //Throws a null pointer.

}

PlayerCache:
public void cachePlayer(UUID uuid)
{
    PlayerData PD = PlayerManager.getInstance().getPlayerData(uuid);
    this.cache.put(uuid, PD);
}

public PlayerRank getCachedRank(UUID uuid)
{
   return this.cache.get(uuid).getRank();
}

Hope someone can help.


text:
Q: How to read D.update([E, ]**F) in the docs? The docs of dict.update of Python reads as follows:
Help on method_descriptor:

update(...)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    In either case, this is followed by: for k in F:  D[k] = F[k]

How is [E, ]**F meant? Are they two separate arguments and if so, why are they not comma separated?

A: The notation [E, ]**F indicates that the positional argument E is optional (all args within [ ] are optional, ie have a default value assigned in the method declaration), and that it accepts a variable number of keyword arguments as F. (This is usually called **kwargs in docs)
Within the method, F will be a dict containing all the keyword arguments as key-value pairs.


text:
Q: Why Java will not allow to use access modifiers in loops? for(public int i=0;i<10;i++) {

        System.out.println(i);

        }
for(private int i=0;i<10;i++) {

        System.out.println(i);

    }

Eclipse says only final is permitted.

A: Firstly we need to know that what is the need of Access modifiers.
An access modifier restricts the access of a class, constructor, data member and method in another class.
But when we declare a variable or anything inside a loop their scope/use is restricted only to that loop.
That means we can use these variables only inside that loop. We can't use these variables outside of that loop.
(SUN people who wrote java have restricted it).
so if we don't use loop variables outside of loop then what is the need to use Access modifiers inside loop. That's why java doesn't allow it.


text:
Q: Context menu on custom shortcut I have a QGraphicsView in my MainWindow and I have a custom "grab" function on my canvas (which is the QGraphicsView inside my MainWindow) called when I press both mouse buttons.
So I want to activate my context menu only when I press CTRL + right click and prevent from activating only with a right click. It would be important to keep ActionsContextMenu policy.
Is there a way to do that?

A: Just check for KeyboardModifier. You can specify which modifier you want. In your case, it is the ControlModifier. Then, override the method mousePressEvent() :
void yourClass::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::RightButton &&
        event->modifiers() == Qt::ControlModifier)
    {
        // call your context menu
    }
}

If you want to use this, you'll need to call a QMenu. Just add this function in your class :
void yourClass::showMenu()
{
    QMenu contextMenu(this);

    QAction action("My Action", this);
    contextMenu.addAction(&action);

    contextMenu.exec();
}


text:
Q: having trouble installing ubuntu studio 13.04 I am currently trying to install Ubuntu Studio 13.04 along side Windows 7.
When I boot into the USB stick, I make the proper selections and it reboots.  When I boot into Windows 7 and open wubi.exe, I am given a choice to run demo or learn more (I don't get the screen that allows you to select drive size and what not). It says that I can install from the demo, so i make the proper selection, then it reboots.
How can I overcome this and install Ubuntu Studio?


text:
Q: App\Entity\Site object not found by the @ParamConverter annotation I'm trying to create a new tempate in my project in symfony to put a climbing converter. But it doesn't work. I have the error:
App\Entity\Site object not found by the @ParamConverter annotation

I put the function in the entity "site" as following :
/**
 * @Route("/site")
 */
class SiteController extends AbstractController
{

    public function upload( KernelInterface $kernel): Response
    {

       $imagesDir = $kernel->getProjectDir().'/public/uploads'; // équivalent à $this->getParameter('images_directory')
       dump($imagesDir) ;
        return $this->render('site/show.html.twig');
    }
    /**
     * @Route("/", name="site_index", methods={"GET"})
     */
    public function index(SiteRepository $siteRepository): Response
    {

        return $this->render('site/index.html.twig', [
            'sites' => $siteRepository->findAll(),

        ]);

    }

    /**
     * @Route("/new", name="site_new", methods={"GET","POST"})
     */
    public function new(Request $request): Response
    {
        $site = new Site();
        $form = $this->createForm(SiteType::class, $site);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            //on recupère les medias transmises
            $media = $form->get('site')->getData();
            //on boucle sur les medias
            foreach($media as $medi){
                //on génère un nouveau nom de fichier
                $fichier = md5(uniqid()) . '.' . $medi->guessExtension();
                //on copie le fichier dans le dossier img
                $medi->move(
                    $this->getParameter('images_directory'),
                    $fichier
                );
                //on stocke l'image dans la bdd
                $img = new Media();
                $img->setNom($fichier);
                $site->addMedium($img);

            }

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($site);
            $entityManager->flush();

            return $this->redirectToRoute('site_index');
        }

        return $this->render('site/new.html.twig', [
            'site' => $site,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="site_show", methods={"GET"})
     */
    public function show(Site $site, MediaRepository $mediarepository, $id): Response
    {
        $media = $mediarepository->findBy(
            ['site'=>$id]
        );

        return $this->render('site/show.html.twig', [
            'site' => $site,
            'media' => $media,

        ]);
    }

    /**
     * @Route("/{id}/edit", name="site_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Site $site): Response
    {
        $form = $this->createForm(SiteType::class, $site);//j'appelle le form
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            //on recupère les medias transmises
            $media = $form->get('site')->getData();
            //on boucle sur les medias
            foreach($media as $medi){
                //on génère un nouveau nom de fichier
                $fichier = md5(uniqid()) . '.' . $medi->guessExtension();
                //on copie le fichier dans le dossier img
                $medi->move(
                    $this->getParameter('images_directory'),
                    $fichier
                );
                //on stocke l'image dans la bdd
                $img = new Media();
                $img->setNom($fichier);
                $site->addMedium($img);

            }
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('site_index');
        }

        return $this->render('site/edit.html.twig', [
            'site' => $site,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}", name="site_delete", methods={"POST"})
     */
    public function delete(Request $request, Site $site): Response
    {
        if ($this->isCsrfTokenValid('delete'.$site->getId(), $request->request->get('_token'))) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($site);
            $entityManager->flush();
        }

        return $this->redirectToRoute('site_index');
    }
    /**
     * @Route("/conv", name="site_converter")
     */
    public function converter():Response
    {
        return  $this->render('site/converter.html.twig');
    }

}

I checked others answers about this problem, but I still can't find out the solution. Do you have any ideas?
I put some more code so that it would be easier to understand. I hope this would be usefull. It's the route for converter that makes me problem. Thanks

A: This happens because you have a route called /conv, you should declare it before declaring /{id} route, instead Symfony searches for a Site object with id: conv which is not found.
Move converter route and method declaration before your show route and method declaration.


text:
Q: How to compare 2 QStringList's and show the results? I want to know how can I compare 2 QStringList and display the results in the following way:
I have 2 QPlainTextEdit A and B

*

*In A I have, for example, 10 lines of 6 numbers per line;

*In B i have, for example, 100 lines of 6 numbers per line;

What I want to do is this: take each line in B and compare with all the lines in A. If, in one line-line comparison, all 6 are equal to int n6 (for example) will add 1. If only 5 are equal, the int n5 will add 1 and so on.
I've tried a few things but none of them worked. If you could give some light on this I'll appreciate.

A: Use QSet and subtract() and count() or size()
QStringList mOldList, mNewList;

  mOldList.append("1");
  mOldList.append("2");
  mOldList.append("3");
  mOldList.append("4");
  mOldList.append("5");
  mOldList.append("10");

  mNewList.append("1");
  mNewList.append("2");
  mNewList.append("3");
  mNewList.append("4");
  mNewList.append("5");
  mNewList.append("15");

QSet<QString> subtraction = mNewList.toSet().subtract(mOldList.toSet());
QSet<QString> subtraction1 = mOldList.toSet().subtract(mNewList.toSet());
foreach (const QString &filename, subtraction)
        qDebug() << " difference: "<<  filename;
foreach (const QString &filename, subtraction1)
        qDebug() << " difference: "<<  filename;

Result:
 difference:  "15"
 difference:  "10"

For example with next lists:
  mOldList.append("1");
  mOldList.append("2");
  mOldList.append("3");
  mOldList.append("4");
  mOldList.append("5");
  mOldList.append("10");

  mNewList.append("1");
  mNewList.append("2");
  mNewList.append("3");
  mNewList.append("4");
  mNewList.append("5");
  mNewList.append("15");

QSet<QString> subtraction = mNewList.toSet().subtract(mOldList.toSet());
foreach (const QString &fileName, subtraction)
        qDebug() << " difference: "<<  fileName;

Result only 15:
 difference:  "15"

It means that one element is not same.
  mOldList.append("1");
  mOldList.append("2");
  mOldList.append("3");
  mOldList.append("4");
  mOldList.append("5");
  mOldList.append("10");

  mNewList.append("1");
  mNewList.append("2");
  mNewList.append("3");
  mNewList.append("4");
  mNewList.append("115");
  mNewList.append("15");

Two elements are not same:
 difference:  "115"
 difference:  "15"

Or another way:
qSort(mNewList);
qSort(mOldList);

if(mNewList == mOldList){
    qDebug() << "same";
}
else{
    qDebug() << "not same";
}

A: Start by calculating the number of matching digits per string
int matchingDigits(QString str1, QString str2)
{
    int matches = 0;
    int minSize = str1.size() < str2.size() ? str1.size() : srt2.size();
    for (int pos = 0; pos < minSize; ++pos)
    {
        if (str1.at(pos) == str2.at(pos) ++matches;
    }
    return matches;
}

Now you compare all a strings with each other (iterating over both StringLists) and if matchingDigits() is something > 0 then you can increase your result counters.
QStringList listA;
QStringList listB;

foreach (QString a, listA)
{
    foreach (QString b, listB)
    {
        int matches = matchingDigits(a, b);
        if (matches > 0)
        {
            // do something fancy
        }
    }
}


text:
Q: Laravel session for Custom Authentication I am using one laravel 5.7 authentication with custom check and session.
I have 5 type of user types

Session::put('user_type',  $user_type);
        Session::put('user_id',  $user_id);

When I tried to check session data in constructor I am facing one issue,Please hele me to solve this,

ErrorException (E_NOTICE) Trying to get property 'headers' of
  non-object

 public function __construct()
    {
        $this->middleware(function ($request, $next) {
        $utype=Session::get('user_type');
        if($utype != 'ProjectAdmin'){
            return redirect()->route('login');
        }else{
            $this->objShareContract = shareContract::getShareContract(TRUE);
        }
    });
    }

A: Middleware must return a Response. You are not returning a Response from this custom Closure based middleware. You have 2 logical paths and only one of them is returning a Response of some sort.
There are other middleware before this one that are expecting a Response to come back through the pipeline. That is what the return $next($request); is about.


text:
Q: mysql var/lib/mysql directory doesn't exist, can't start mysql server I have read many a forum post and hopeful solution to the problem I am having with getting my own mysql server to start and work properly, but none so far have worked. Many of the forum posts I've read make reference to a /var/lib/mysql folder, as do some of the errors I receive, such as when I run
$ mysqld

on Terminal using a Mac and receive the following error
2013-06-03 00:40:46 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2013-06-03 00:40:46 1851 [Warning] Can't create test file /var/lib/mysql/Alexs-MacBook-Pro-3.lower-test
2013-06-03 00:40:46 1851 [Warning] Can't create test file /var/lib/mysql/Alexs-MacBook-Pro-3.lower-test
mysqld: Can't change dir to '/var/lib/mysql/' (Errcode: 2 - No such file or directory)
2013-06-03 00:40:46 1851 [ERROR] Aborting

2013-06-03 00:40:46 1851 [Note] Binlog end
2013-06-03 00:40:46 1851 [Note] mysqld: Shutdown complete

I have deleted everything related to MySQL and reinstalled MySQL, both from a dmg file and from an unzipped tar.gz file from the MySQL downloads page. Nothing has worked. The strange this is that I was using MySQL and the MySQL Workbench only days ago, when suddenly it started giving me this error when I ran the following command
$ mysql

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I can't even start the daemon using mysqld_safe... I need a walkthrough of what to do from here to get the MySQL server correctly running again.

A: I'd try this.
mkdir /var/lib/mysql
chown -R mysql /var/lib/mysql

I am guessing that you are running mysql as the user "mysql".  If not, either create the user mysql and run the mysqld_safe with the option --user="mysql" OR chown the folders to be owned by the user you are running as

A: On a fresh Ubuntu 16, after having done some nonsense, I removed /var/lib/mysql manually. I wanted mariadb and hoped that
sudo apt-get remove mariadb-server mariadb-client

followed by
sudo apt-get install mariadb-server mariadb-client

re-creates it, but it didn't.
What helped was
sudo apt-get remove mysql-common

as this common package seems to be responsible for the directory creation. This took me much longer than needed, as it's package I didn't install explicitly, so I didn't think about removing it (some autoremove could have helped).


text:
Q: BST recursive search keeps return None I' am searching values in a binary search tree, but the function keeps returning None, and the function is successfully finding/not finding the value
class BinaryTree():

    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

    def find(self, valueToFind, parent, vist_counter=0):
       if parent is None:
           return valueToFind, -1
           vist_counter += 1
       if parent.value == valueToFind:
           return valueToFind, vist_counter
       if valueToFind <= parent.value:
            self.find(valueToFind, parent.left, vist_counter)
       elif valueToFind > parent.value:
           self.find(valueToFind, parent.right, vist_counter)

A: Your code is not clear. However, as far as I understand, you should return the function call on the last two statements.
return self.find(valueToFind, parent.left, vist_counter)


text:
Q: Why does kendoForm fire twice when clicking submit? If in a kendoForm after domReady with setOptions the formData is set, so submit fires twice with one click.
form.setOptions({
 formData : { ID: 2, Name: "Tom", Address: "Berlin" }
});

My example code: kendoForm example
First press submit Button => submit fires ones.
Second press add FormData Button, then press submit => submit fires twice.
What is my mistake that fires twice after setOptions submit?

A: The described behavior is related to a known issue in the Form that is logged here:
https://github.com/telerik/kendo-ui-core/issues/5854
As a temporary workaround until the issue is resolved with an official fix, you can use override the _setEvents function as follows:
<script>
        kendo.ui.Form.fn._setEvents = function() {
          var that = this,
              validator = that.validator;

          validator
            .bind("validateInput", $.proxy(that._validateField, that))
            .bind("validate", $.proxy(that._validate, that));

          that.wrapper
            .on("submit.kendoForm", $.proxy(that._submit, that))
            .on("clear.kendoForm", $.proxy(that._clear, that))
            .on("click.kendoForm", ".k-form-clear", $.proxy(that._clear, that));

          that._model.bind("change", $.proxy(that._change, that));
        }
      </script>

Here is a working Dojo example for your convenience.


text:
Q: OODesign: Data Structure which calls algorithm on insert I have a data structure which has an add function.
When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure.
Thus the data structure needs to store an algorithm object (since this is called each time the add is executed). On the other hand the algorithm needs access the data structure, and thus needs to store the data structure object.
I think situations where class A has an instance of class B and class B has an instance of class A are usually undesirable.
Does anybody have an idea how to solve this recurrence here?

A: The data structure should contain a link to the algorithm, since it has exactly one algorithm.  Right?  (as I understand the requirements)
But the same algorithm, say, "normalize to the average" could work on many different instances of the data structure.  So it should not contain/store an instance of the data structure.  Instead, its method should take the datastructure as an additional argument.  e.g.
calculate(newValue, existingDataStructure);

Then, your datastructure's add() method calls
tweakedValue = this.algorithm.calculate(newValue, this);
this.add(tweakedValue);

A: One way to approach this problem without extending the tiers of your system is to implement the Command and Strategy patterns together in your design.  Encapsulate the actionable method (in your case, "add") as a Command and decorate it with a Strategy that encapsulates your algorithm.
Inside the Execute of your AbstractCommand, execute a virtual OnAfterExecute() method, which is where you state that you want your Algorithm to process. To tie the patterns together, conceptualize the responsibilities of your Context and of your Invoker as being the same.

Untested code. Typed by hand from memory.

public interface ICommand
{
    void OnBeforeExecute();
    void OnExecute();
    void OnAfterExecute();
    void Execute();
}
public abstract class Command : ICommand
{
    protected IStrategy Algorithm{ get;set; }
    public Command(IStrategy algorithm)
    {
      this.Algorithm = algorithm;
    }
    public virtual void OnBeforeExecute(){};
    public virtual void OnExecute(){};
    public virtual void OnAfterExecute(){};
    public virtual void Execute()
    {
       OnBeforeExecute();
       OnExecute();
       OnAfterExecute();
    };
}

public class AddCommand : Command
{
    private IPersistenceService PersistenceService {get;set;}
    public AddCommand(IStrategy algorithm, IPersistenceService persistenceService) :base(algorithm)
    {
       this.PersistenceService = persistenceService;
    }
    public virtual override OnExecute()
    {
       this.PersistenceService.ExecuteAddStuffs();
    }
    public virtual override OnAfterExecute()
    {
       this.Algorithm.Process();
    }
}

public interface IStrategy
{
    void Process();
}

public class HighPassFilterStrategy : IStrategy
{
    private IPersistenceService PersistenceService { get;set; }
    public void Process()
    {
       //Execute your HighPassFilter logic.
    }
}

//DomainProcess is your InvokerContext
//As an alternative design consideration, you could move the virtual 'On' methods
//up into DomainProcess and decouple the strategy from the command.
public class DomainProcess
{
    public ICommand Command{ get; protected set;}
    public DomainProcess(IStrategy strategy, ICommand command)
    {
       command.Algorithm = strategy;
       this.Command = command;
    }

    public void Run()
    {
       Command.Execute();
    }
}

public class YourDataStructure
{
   public string Foo {get;set;}
   public string Bar {get;set;}

   //List of DomainProcess. Won't accept angle brackets.
   //List"left angle bracket"DomainProcess"right angle bracket"
    private List DomainProcesses { get;set; }

    public DataStructure(List workflows)
    {
       this.DomainProcesses = workflows;

       //alternative, but indicative of poor design. **Objects should not
       //construct their own dependencies.**
       //---------------------------------------------------------
       //I'm including this so that I don't have to design all the way up to
       //Composition Root for this illustration.
       //---------------------------------------------------------
       if(!this.DomainProcesses.Any(process => process.Name.Equals("Add"))
       {
          var algorithm = new HighPassFilterStrategy();
          var command = new AddCommand();
          var add = new DomainProcess(algorithm, command);
          this.DomainProcesses.Add(add);
       }
    }

    public void AddRuntimeOperation(string name, ICommand command, IStrategy algorithm)
    {
       DomainProcess process = new DomainProcess(algorithm, command);
       process.Name = name;

       DomainProcesses.Add(process);
    }
    public void Add()
    {
       var add = this.DomainProcesses.Where(operation => operation.Name.Equals("Add'")).SingleOrDefault();

       add.Run();
    }
}

Your structure that currently has an Add method on it could instead encapsulate a DomainProcess called Add

  public void Add()
  {
    DomainProcess.Run();
  }

The OnBeforeExecute, OnExecute and OnAfterExecute methods are colloquially known as aspects.

If you are going to use an object hierarchy in your design, aspects should serve as your primary extension points of that hierarchy.

By creating the default implementation of Execute as an aggregation of these 3 aspects, you can very easily specify inside your Algorithms that you want them to be processed Before or After your main operation is executed.
More specific information about your requirements might change the recommendation.

A: If you have a cyclic dependency like this, this hints at one of two problems:

*

*the two objects should really be one object

*the two objects should really be three objects (with the inter-related parts extracted into the third)

What you have here, is highly unusual. Adding an element to a data structure is one of the primary responsibilities of a data structure, outsourcing that to the client, especially in a way that requires privileged access to the data structure's private internals, just seems wrong somehow.
This is very different from, say, a SortedSet which needs both an Ordering and an Equality algorithm, but neither of those two algorithms needs to know anything about the Set, it only needs to know how to compare two elements. Or a HashMap which needs a Hash algorithm that can hash a single element. That's the typical case for a data structure parameterized by an algorithm.

A:
I have a data structure which has an add function. When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure

This is not a good idea and besides makes not really sense.
If I get you correctly, you want to create an object which contains some elements e1, e2, e3, .... At a given point in time, you want to do a transformation of the elements so far. At a later point, you want to do another transformation on the collection as a whole.
There is no need to do a transformation in between, since it makes no difference whether the collection stores the values plain vanilla or transformed. At a given point, you need to read or change the transformed values: this is the right point to do a transformation of the colletion (so far) as a whole.
If that is, what you want, this would be a perfect use-case for the visitor pattern:
In case, you have have Python at hand or do not mind installing it, here is a nice example how to set up the visitor pattern
#!/usr/bin/env python3

class Container:
    def __init__(self, values):
        self._values = values

    def transform(self, transformator):
        self._values = transformator.transform(self._values)

    def accept(self, visitor):
        visitor.visit(self)

class Visitor:
    pass

class Transformator(Visitor):
    pass

class DoublingVisitor(Transformator):
    def visit(self, container):
        container.transform(self)

    def transform(self, values):
        return list(map(lambda x: 2*x, values))

def main():
    container = Container([1, 2, 3])
    doublingVisitor = DoublingVisitor()
    container.accept(doublingVisitor)
    print(container._values)

if __name__ == '__main__':
    main()

Anyways, the python code is easy to understand. The point is, you need one class which I called (lacking of a better name) Container, which accepts a Visitor. On the other hand, you need an object derived from Visitor, which holds as a Transformator the algorithm (which was the term you used). The Visitor needs one method visit, which has one parameter (the object, which it visits). That is the whole magic.
While visiting, the visitor calls the transform method on the object to visit, which in turn receives the Visitor / Transformator who implements a transform method. That's it.
Every time, you want to do something with your collection, you could accept another Visitor.

A: Classes A and B should not have-a instance of each other; that way lies madness.
You make no mention of what the post-add algorithms do, but since they must have access to the instance of A, they need to be methods of A, ignoring troublesome constructions like friend functions.
class A:
  member x
  member y

  constructor(x, y, post_add_func(pointer or reference or name)

  method add()
      do_add_stuff
      call_post_add_func

  method post_add_1()
  method post_add_2()

This allows an "algorithm" to be bound to an instance of A, thus giving it full access to the members and methods of A.
I don't understand what the expected purpose of class B is, I suspect it was just a container for "algorithms" and will add unnecessary complexity. B probably doesn't need to exist.


text:
Q: Processing XML With Hadoop Streaming failed i did
bin/hadoop jar contrib/streaming/hadoop-streaming-1.0.4.jar -inputreader "StreamXmlRecordReader, begin=<metaData>,end=</metaData>" -input /user/root/xmlpytext/metaData.xml -mapper /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -reducer /Users/amrita/desktop/hadoop/pythonpractise/reducerxml.py  -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py -output /user/root/xmlpytext-output1 -numReduceTasks 1

but it shows
13/03/22 09:38:48 INFO mapred.FileInputFormat: Total input paths to process : 1
13/03/22 09:38:49 INFO streaming.StreamJob: getLocalDirs(): [/Users/amrita/desktop/hadoop/temp/mapred/local]
13/03/22 09:38:49 INFO streaming.StreamJob: Running job: job_201303220919_0001
13/03/22 09:38:49 INFO streaming.StreamJob: To kill this job, run:
13/03/22 09:38:49 INFO streaming.StreamJob: /private/var/root/hadoop-1.0.4/libexec/../bin/hadoop job  -Dmapred.job.tracker=-kill job_201303220919_0001
13/03/22 09:38:49 INFO streaming.StreamJob: Tracking URL: http://localhost:50030/jobdetails.jsp?jobid=job_201303220919_0001
13/03/22 09:38:50 INFO streaming.StreamJob:  map 0%  reduce 0%
13/03/22 09:39:26 INFO streaming.StreamJob:  map 100%  reduce 100%
13/03/22 09:39:26 INFO streaming.StreamJob: To kill this job, run:
13/03/22 09:39:26 INFO streaming.StreamJob: /private/var/root/hadoop-1.0.4/libexec/../bin/hadoop job  -Dmapred.job.tracker=-kill job_201303220919_0001
13/03/22 09:39:26 INFO streaming.StreamJob: Tracking URL: http:///jobdetails.jsp?jobid=job_201303220919_0001
13/03/22 09:39:26 ERROR streaming.StreamJob: Job not successful. Error: # of failed Map Tasks exceeded allowed limit. FailedCount: 1. LastFailedTask: task_201303220919_0001_m_000000
13/03/22 09:39:26 INFO streaming.StreamJob: killJob...
Streaming Command Failed!

when i went through jobdetails.jsp there it shows
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at org.apache.hadoop.streaming.StreamInputFormat.getRecordReader(StreamInputFormat.java:77)
    at org.apache.hadoop.mapred.MapTask$TrackedRecordReader.<init>(MapTask.java:197)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:418)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:396)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
    at org.apache.hadoop.mapred.Child.main(Child.java:249)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.apache.hadoop.streaming.StreamInputFormat.getRecordReader(StreamInputFormat.java:74)
    ... 8 more
Caused by: java.io.IOException: JobConf: missing required property: stream.recordreader.begin
    at org.apache.hadoop.streaming.StreamXmlRecordReader.checkJobGet(StreamXmlRecordReader.java:278)
    at org.apache.hadoop.streaming.StreamXmlRecordReader.<init>(StreamXmlRecordReader.java:52)
    ... 13 more

my mapper
#!/usr/bin/env python
import sys
import cStringIO
import xml.etree.ElementTree as xml
def cleanResult(element):
    result = None
    if element is not None:
        result = element.text
        result = result.strip()
    else:
        result = ""
    return result
def process(val):
    root = xml.fromstring(val)
    sceneID = cleanResult(root.find('sceneID'))
    cc = cleanResult(root.find('cloudCover'))
    returnval = ("%s,%s") % (sceneID,cc)
    return returnval.strip()
if __name__ == '__main__':
    buff = None
    intext = False
    for line in sys.stdin:
        line = line.strip()
        if line.find("<metaData>") != -1:
            intext = True
            buff = cStringIO.StringIO()
             buff.write(line)
         elif line.find("</metaData>") != -1:
              intext = False
              buff.write(line)
              val = buff.getvalue()
              buff.close()
              buff = None
              print process(val)
        else:
            if intext:
                buff.write(line)

and reducer
#!/usr/bin/env python
import sys
if __name__ == '__main__':
     for line in sys.stdin:
         print line.strip()

can anyone tell me why this happens.
I am using hadoop-1.0.4 im mac.
Is there any thing wrong. Should i change any thing .
pls help me out.

A: Remove space in between comma and begin , begin=<.
The correct format is :
hadoop jar hadoop-streaming.jar -inputreader
"StreamXmlRecord,begin=BEGIN_STRING,end=END_STRING" ..... (rest of the command)

This is due to the code surrounding the following lines in org.apache.hadoop.streaming.StreamJob
for (int i = 1; i < args.length; i++) {
    String[] nv = args[i].split("=", 2);
    String k = "stream.recordreader." + nv[0];
    String v = (nv.length > 1) ? nv[1] : "";
    jobConf_.set(k, v);
  }

A: try setting the missing config variables as follows (add stream.recordreader. prefix and make sure they are the first arguments after the jar, enclosing them in double quotes):
bin/hadoop jar contrib/streaming/hadoop-streaming-1.0.4.jar \
  "-Dstream.recordreader.begin=<metaData>" \
  "-Dstream.recordreader.end=</metaData>" \
  -inputreader "StreamXmlRecordReader \
  -input /user/root/xmlpytext/metaData.xml \
  -mapper /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py \
  -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py \
  -reducer /Users/amrita/desktop/hadoop/pythonpractise/reducerxml.py \
  -file /Users/amrita/desktop/hadoop/pythonpractise/mapperxml.py \
  -output /user/root/xmlpytext-output1 \
  -numReduceTasks 1


text:
Q: Strange error with custom launcher I am trying to write a launcher for a modpack. But when I try to launch minecraft (using http://pastebin.com/yfiRpVyga) with forge and no mods I get the following http://pastebin.com/5Rt7Eq2q .
Could anyone point me in a new direction that could lead to a conclusion?
I've tried to redownload jar files to make sure that they not broken. Also verified the files as they was taken from the current MultiMC launcher as it is working there.

A:
2013-10-24 23:15:43 [SEVERE] [ForgeModLoader] There is a binary
  discrepency between the expected input class aa (aa) and the actual
  class. Checksum on disk is 7 c7533d5, in patch c7e1682c. Things are
  probably about to go very wrong. Did you put something into the jar
  file?

Try it without modifying forge maybe? The class aa looks like its throwing the error.
You might want to try using MCP or some other deobfuscation.


text:
Q: how do i count words in a text file using java I'm trying to count the total of words in a file but java is giving the total of words per line. because I'm using .hasNextLine()   it doesn't calculate the total of the lines no matter how I try it.is there a way to tell java to total each line and return the value of total word of the lines
import java.io.File;//import file class
import java.io.IOException;//import file class to handle errors
import java.util.Scanner;
import java.io.FileNotFoundException;

public class readingfromafile {
public static void main(String []args) {
{
 try{
 File myobj = new File("C:\\Users\\cse21-037\\Documents\\assighnment java\\100 words\\brain drain.txt");
 Scanner myReader  = new Scanner(myobj);
  while (myReader.hasNextLine()) {
  String data = myReader.nextLine();
  System.out.println(data);

        int count = 1;
         for (int i = 0; i < data.length() - 1; i++)
        {
            if ((data.charAt(i) == ' ') && (data.charAt(i + 1) != ' '))
            {
                count++;
            }
        }

        System.out.println(count);

    }

  }

  catch (FileNotFoundException e) {
  System.out.println("error 404");
  e.printStackTrace();
  }
  }
  }
  }

A: Use a global variable to store totalCount of words.
import java.io.File;//import file class
import java.io.IOException;//import file class to handle errors
import java.util.Scanner;
import java.io.FileNotFoundException;

public class readingfromafile {
    public static void main(String[] args) {
        {
            try {
                File myobj = new File("C:\\Users\\cse21-037\\Documents\\assighnment java\\100 words\\brain drain.txt");
                Scanner myReader = new Scanner(myobj);
                int totalCount = 0;
                while (myReader.hasNextLine()) {
                    String data = myReader.nextLine();
                    System.out.println(data);

                    int count = 1;
                    for (int i = 0; i < data.length() - 1; i++) {
                        if ((data.charAt(i) == ' ') && (data.charAt(i + 1) != ' ')) {
                            count++;
                        }
                    }
                    totalCount = totalCount + count;
                    System.out.println(count);
                }
                System.out.println(totalCount);
            } catch (FileNotFoundException e) {
                System.out.println("error 404");
                e.printStackTrace();
            }
        }
    }
}

It should work.

A: I'd do it like this:
package stackoverflow;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileWordCounter {

    public static void main(final String[] args) throws IOException {
        final String fileName = args != null && args.length > 0 ? args[0] : "/test/file";
        final String text = Files.readString(Paths.get(fileName));
        final String[] parts = text.split("\\W+"); // use \\s+ to split whole words, use \\W+ to exclude non-word characters
        System.out.println("Got parts:\t" + parts.length);

        System.out.println("Counting words...");
        long counter = 0;
        for (final String part : parts) {
            if (part != null && part.trim().length() > 0) {
                System.out.println("\t[" + part + "]");
                ++counter;
            }
        }
        System.out.println("Counted words:\t" + counter);
        System.out.println("All done.");
    }

}


text:
Q: will running laptop in hibernation mode cause problems I have DELL Inspiron 14r touch laptop with i5 processor, 2GB graphics card, Windows 8 and Ubuntu 12.04 dual boot.
Now, my question is more hardware specific, I want to know most of the time my computer is turned on. And the time when I don't use my computer I turn it into hibernation mode. So, basically my system is almost always on or else in hibernation mode, except at night.
So, will this cause any adverse effect on my hardware? Thanks.

A: No. Hibernation just means that your RAM's content is written to the hard drive and later read from there instead of booting.
What you could face is data loss. Just make sure that you always resume from the operating system from which you hibernated. There can be strange effects if one of the operating systems finds different stuff on the disk than it was seeing there just before hibernation.

A: Hibernation mode is when the OS saves it's running state to disk and powers down. To say your system is "on" when hibernating is misleading. The system is paused, with every component powered off except the CMOS.
You will not cause any damage to hardware by using hibernation mode.


text:
Q: Doesn't choose records author   id  |  name
         1       Mike
         2       Dive
         3       Stiv

book     id  |  title
         1       ABC
         2       War

book_author  id_book | id_author
             1         1
             1         2
             2         3

app/models/Book.php
public function getAuthors()
{
  return $this->hasMany(Authors::className(), ['id' => 'id_author'])->viaTable('book_author',['id_book' => 'id']);
}

In view:
    foreach (Books::findAll([1, 2]) as $book)
    {
        echo sprintf('%s | %s',
            $book->title,implode(', ',
                $book->getAuthors()));
    }

Always returned implode(): Invalid arguments passed in $book->getAuthors()));
getAuthors() - doesn't choose author, why?
Need:
ABC    |    Mike, Dive
  War    |    Stiv

A: $book->getAuthors() get object arrays. You should get simple array. Try this code:
foreach (Books::findAll([1, 2]) as $book)
    {
        $authors = ArrayHelper::toArray($book->getAuthors()->all(), [
         'app\models\Authors' => [
           'name', 'id'
         ]
        ]);
        echo sprintf('%s | %s',
            $book->title,implode(', ',
                ArrayHelper::map($authors, 'id', 'name')));
    }


text:
Q: How to get the text value of PhoneTextBox control I am asking for a user to type in what he or she would like to search for, and then I would like to pass this value to another page where the search will be performed and the results will be given. I am using a PhoneTextBox control from the WP Toolkit. On the KeyUp or ActionIconTapped event I would like to get the value entered in the PhonTextBox and pass that to my search page, although I cannot figure out how to get the text value entered?
MainPage.xaml
<toolkit:PhoneTextBox x:Name="publicSearchTextBox" HorizontalAlignment="Stretch" Margin="-10,0,12,0"
                      Hint="search for topic or name"
                      ActionIcon="/Resources/Images/search.png"
                      ActionIconTapped="publicSearchTextBox_ActionIconTapped"
                      KeyUp="publicSearchTextBox_KeyUp"/>

MainPage.xaml.cs
..get publicSearchTextBox text value and pass this to the search page?

For some reason, I cannot reference the PhoneTextBox in my code behind from setting x:Name="publicSearchTextBox" in my xaml? How is this possible?

A: Perhaps you have a typo because i made some handlers for the XAML you have above and it works fine for me. Copy paste the following in the code behind and try?
private void PrintTextboxValue()
{
    Debug.WriteLine("Value: {0}", publicSearchTextBox.Text);
}

private void publicSearchTextBox_ActionIconTapped(object sender, EventArgs e)
{
    PrintTextboxValue();
}

private void publicSearchTextBox_KeyUp(object sender, KeyEventArgs e)
{
    PrintTextboxValue();
}

If it does not work then please update your question with more information such as, where you are referencing the PhoneTextBox.


text:
Q: Set different results using same function in Jquery I am writing below code to get results below is my html which create tab

Documents
<input id="myInput" type="text" placeholder="Search..">

Below JavaScript code create results for this tab
$(function () {
      // Since there's no list-group/tab integration in Bootstrap
      $('.list-group-item').on('click', function (e) {
        var previous = $(this).closest(".list-group").children(".active");
        previous.removeClass('active'); // previous list-item
        getListData();
        $(e.target).addClass('active'); // activated list-item
      });
    });
     $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#divResults li").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
    function getListData() {
      var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Reports')/items?$select=FileLeafRef,ServerRedirectedEmbedUrl&$filter=startswith(ContentTypeId,'0x0101')";
      console.log(fullUrl);
      $.ajax({
        url: fullUrl,
        type: "GET",
        headers: {
          "accept": "application/json;odata=verbose",
          "content-type": "application/json;odata=verbose",
        },
        success: onQuerySucceeded,
        error: onQueryFailed
      });
    }

    function onQuerySucceeded(data) {
      var listItemInfo = " ";
      for (var i = 0; i < data.d.results.length; i++) {
            if (data.d.results[i].FileSystemObjectType != 1) {
        listItemInfo += "
"+data.d.results[i].FileLeafRef+"
";

            }
        }

        console.log(listItemInfo);
         $("#divResults").html(listItemInfo);
      };

    function onQueryFailed() {
      alert('Error!');
    }

Now from above getting desired results, but now like to create different tabs which call different library to get results
So using below line to get results from Reports library
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Reports')/items?$select=FileLeafRef,ServerRedirectedEmbedUrl&$filter=startswith(ContentTypeId,'0x0101')";

I know can repeat same function to get results but want to use single function and changed library name as per tab
Is it possible ?