text:
Q: How to tell LLVM that it can optimize away stores? Background (there may be a better way to do this):
I am developing a Julia library in which I manually manage memory; I mmap a large block, and then mostly treat it like a stack: functions receive the pointer as an argument, and if they allocate an object, they'll return an incremented pointer to the callee.
That callee itself will likely not increment the pointer, and just return the original pointer it received, if it returns the pointer at all.
Whenever a function returns, as far as my library is concerned, anything beyond the current position of the pointer is garbage. I would like LLVM to be aware of this, so that it can optimize away any unnecessary stores.
Here is a test case demonstrating the problem: taking the dot product of two vectors of length 16. First, a few preliminary loads (these are my libraries, and are on GitHub: SIMDPirates, PaddedMatrices):
using SIMDPirates, PaddedMatrices
using SIMDPirates: lifetime_start, lifetime_end
b = @Mutable rand(16);
c = @Mutable rand(16);
a = FixedSizeVector{16,Float64}(undef);
b' * c # dot product
# 3.9704768664758925

Of course, we'd never include stores if we wrote a dot product by hand, but that's a lot harder to do when you're trying to generate code for arbitrary models. So we'll write a bad dot product that stores into a pointer:
@inline function storedot!(ptr, b, c)
    ptrb = pointer(b)
    ptrc = pointer(c)
    ptra = ptr
    for _ ∈ 1:4
        vb = vload(Vec{4,Float64}, ptrb)
        vc = vload(Vec{4,Float64}, ptrc)
        vstore!(ptra, vmul(vb, vc))
        ptra += 32
        ptrb += 32
        ptrc += 32
    end
    ptra = ptr
    out = vload(Vec{4,Float64}, ptra)
    for _ ∈ 1:3
        ptra += 32
        out = vadd(out, vload(Vec{4,Float64}, ptra))
    end
    vsum(out)
end

Instead of looping once and accumulating the dot product with fma instructions, we loop twice, first calculating and storing products, and then summing.
What I want is for the compiler to figure out the correct thing.
Here are two versions calling it below. The first uses the llvm lifetime intrinsics to try and declare the pointer contents to be garbage:
function test_lifetime!(a, b, c)
    ptra = pointer(a)
    lifetime_start(Val(128), ptra)
    d = storedot!(ptra, b, c)
    lifetime_end(Val(128), ptra)
    d
end

and the second, instead of using a preallocated pointer, creates a pointer with alloca
function test_alloca(b, c)
    ptra = SIMDPirates.alloca(Val(16), Float64)
    storedot!(ptra, b, c)
end

Both of course get the correct answer
test_lifetime!(a, b, c)
# 3.9704768664758925
test_alloca(b, c)
# 3.9704768664758925

But only the alloca version is optimized correctly.
The alloca's assembly (AT&T syntax):
# julia> @code_native debuginfo=:none test_alloca(b, c)
        .text
        vmovupd (%rsi), %ymm0
        vmovupd 32(%rsi), %ymm1
        vmovupd 64(%rsi), %ymm2
        vmovupd 96(%rsi), %ymm3
        vmulpd  (%rdi), %ymm0, %ymm0
        vfmadd231pd     32(%rdi), %ymm1, %ymm0 # ymm0 = (ymm1 * mem) + ymm0
        vfmadd231pd     64(%rdi), %ymm2, %ymm0 # ymm0 = (ymm2 * mem) + ymm0
        vfmadd231pd     96(%rdi), %ymm3, %ymm0 # ymm0 = (ymm3 * mem) + ymm0
        vextractf128    $1, %ymm0, %xmm1
        vaddpd  %xmm1, %xmm0, %xmm0
        vpermilpd       $1, %xmm0, %xmm1 # xmm1 = xmm0[1,0]
        vaddsd  %xmm1, %xmm0, %xmm0
        vzeroupper
        retq
        nopw    %cs:(%rax,%rax)
        nopl    (%rax,%rax)

As you can see, there are no moves into memory, and we have one vmul and three vfmadds to calculate the dot product (before doing the vector reduction).
Unfortunately, this is not what we get from the version trying to use lifetimes:
 # julia> @code_native debuginfo=:none test_lifetime!(a, b, c)
        .text
        vmovupd (%rdx), %ymm0
        vmulpd  (%rsi), %ymm0, %ymm0
        vmovupd %ymm0, (%rdi)
        vmovupd 32(%rdx), %ymm1
        vmulpd  32(%rsi), %ymm1, %ymm1
        vmovupd %ymm1, 32(%rdi)
        vmovupd 64(%rdx), %ymm2
        vmulpd  64(%rsi), %ymm2, %ymm2
        vmovupd %ymm2, 64(%rdi)
        vmovupd 96(%rdx), %ymm3
        vaddpd  %ymm0, %ymm1, %ymm0
        vaddpd  %ymm0, %ymm2, %ymm0
        vfmadd231pd     96(%rsi), %ymm3, %ymm0 # ymm0 = (ymm3 * mem) + ymm0
        vextractf128    $1, %ymm0, %xmm1
        vaddpd  %xmm1, %xmm0, %xmm0
        vpermilpd       $1, %xmm0, %xmm1 # xmm1 = xmm0[1,0]
        vaddsd  %xmm1, %xmm0, %xmm0
        vzeroupper
        retq
        nopw    %cs:(%rax,%rax)
        nop

Here, we just get the loops as written: vmul, store into memory, and then vadd. One of the 4 however has been replaced with a fmadd.
Also, it does not read from any of the stores, so I'd think the dead store elimination pass should have no trouble.
The associated llvm:
;; julia> @code_llvm debuginfo=:none test_alloca(b, c)

define double @julia_test_alloca_17840(%jl_value_t addrspace(10)* nonnull align 8 dereferenceable(128), %jl_value_t addrspace(10)* nonnull align 8 dereferenceable(128)) {
top:
  %2 = addrspacecast %jl_value_t addrspace(10)* %0 to %jl_value_t addrspace(11)*
  %3 = addrspacecast %jl_value_t addrspace(11)* %2 to %jl_value_t*
  %4 = addrspacecast %jl_value_t addrspace(10)* %1 to %jl_value_t addrspace(11)*
  %5 = addrspacecast %jl_value_t addrspace(11)* %4 to %jl_value_t*
  %ptr.i20 = bitcast %jl_value_t* %3 to <4 x double>*
  %res.i21 = load <4 x double>, <4 x double>* %ptr.i20, align 8
  %ptr.i18 = bitcast %jl_value_t* %5 to <4 x double>*
  %res.i19 = load <4 x double>, <4 x double>* %ptr.i18, align 8
  %res.i17 = fmul fast <4 x double> %res.i19, %res.i21
  %6 = bitcast %jl_value_t* %3 to i8*
  %7 = getelementptr i8, i8* %6, i64 32
  %8 = bitcast %jl_value_t* %5 to i8*
  %9 = getelementptr i8, i8* %8, i64 32
  %ptr.i20.1 = bitcast i8* %7 to <4 x double>*
  %res.i21.1 = load <4 x double>, <4 x double>* %ptr.i20.1, align 8
  %ptr.i18.1 = bitcast i8* %9 to <4 x double>*
  %res.i19.1 = load <4 x double>, <4 x double>* %ptr.i18.1, align 8
  %res.i17.1 = fmul fast <4 x double> %res.i19.1, %res.i21.1
  %10 = getelementptr i8, i8* %6, i64 64
  %11 = getelementptr i8, i8* %8, i64 64
  %ptr.i20.2 = bitcast i8* %10 to <4 x double>*
  %res.i21.2 = load <4 x double>, <4 x double>* %ptr.i20.2, align 8
  %ptr.i18.2 = bitcast i8* %11 to <4 x double>*
  %res.i19.2 = load <4 x double>, <4 x double>* %ptr.i18.2, align 8
  %res.i17.2 = fmul fast <4 x double> %res.i19.2, %res.i21.2
  %12 = getelementptr i8, i8* %6, i64 96
  %13 = getelementptr i8, i8* %8, i64 96
  %ptr.i20.3 = bitcast i8* %12 to <4 x double>*
  %res.i21.3 = load <4 x double>, <4 x double>* %ptr.i20.3, align 8
  %ptr.i18.3 = bitcast i8* %13 to <4 x double>*
  %res.i19.3 = load <4 x double>, <4 x double>* %ptr.i18.3, align 8
  %res.i17.3 = fmul fast <4 x double> %res.i19.3, %res.i21.3
  %res.i12 = fadd fast <4 x double> %res.i17.1, %res.i17
  %res.i12.1 = fadd fast <4 x double> %res.i17.2, %res.i12
  %res.i12.2 = fadd fast <4 x double> %res.i17.3, %res.i12.1
  %vec_2_1.i = shufflevector <4 x double> %res.i12.2, <4 x double> undef, <2 x i32> <i32 0, i32 1>
  %vec_2_2.i = shufflevector <4 x double> %res.i12.2, <4 x double> undef, <2 x i32> <i32 2, i32 3>
  %vec_2.i = fadd <2 x double> %vec_2_1.i, %vec_2_2.i
  %vec_1_1.i = shufflevector <2 x double> %vec_2.i, <2 x double> undef, <1 x i32> zeroinitializer
  %vec_1_2.i = shufflevector <2 x double> %vec_2.i, <2 x double> undef, <1 x i32> <i32 1>
  %vec_1.i = fadd <1 x double> %vec_1_1.i, %vec_1_2.i
  %res.i = extractelement <1 x double> %vec_1.i, i32 0
  ret double %res.i
}

It elided the alloca and stores.
However, trying to use lifetimes:
;; julia> @code_llvm debuginfo=:none test_lifetime!(a, b, c)

define double @"julia_test_lifetime!_17839"(%jl_value_t addrspace(10)* nonnull align 8 dereferenceable(128), %jl_value_t addrspace(10)* nonnull align 8 dereferenceable(128), %jl_value_t addrspace(10)* nonnull align 8 dereferenceable(128)) {
  980 top:
  %3 = addrspacecast %jl_value_t addrspace(10)* %0 to %jl_value_t addrspace(11)*
  %4 = addrspacecast %jl_value_t addrspace(11)* %3 to %jl_value_t*
  %.ptr = bitcast %jl_value_t* %4 to i8*
  call void @llvm.lifetime.start.p0i8(i64 256, i8* %.ptr)
  %5 = addrspacecast %jl_value_t addrspace(10)* %1 to %jl_value_t addrspace(11)*
  %6 = addrspacecast %jl_value_t addrspace(11)* %5 to %jl_value_t*
  %7 = addrspacecast %jl_value_t addrspace(10)* %2 to %jl_value_t addrspace(11)*
  %8 = addrspacecast %jl_value_t addrspace(11)* %7 to %jl_value_t*
  %ptr.i22 = bitcast %jl_value_t* %6 to <4 x double>*
  %res.i23 = load <4 x double>, <4 x double>* %ptr.i22, align 8
  %ptr.i20 = bitcast %jl_value_t* %8 to <4 x double>*
  %res.i21 = load <4 x double>, <4 x double>* %ptr.i20, align 8
  %res.i19 = fmul fast <4 x double> %res.i21, %res.i23
  %ptr.i18 = bitcast %jl_value_t* %4 to <4 x double>*
  store <4 x double> %res.i19, <4 x double>* %ptr.i18, align 8
  %9 = getelementptr i8, i8* %.ptr, i64 32
  %10 = bitcast %jl_value_t* %6 to i8*
  %11 = getelementptr i8, i8* %10, i64 32
  %12 = bitcast %jl_value_t* %8 to i8*
  %13 = getelementptr i8, i8* %12, i64 32
  %ptr.i22.1 = bitcast i8* %11 to <4 x double>*
  %res.i23.1 = load <4 x double>, <4 x double>* %ptr.i22.1, align 8
  %ptr.i20.1 = bitcast i8* %13 to <4 x double>*
  %res.i21.1 = load <4 x double>, <4 x double>* %ptr.i20.1, align 8
  %res.i19.1 = fmul fast <4 x double> %res.i21.1, %res.i23.1
  %ptr.i18.1 = bitcast i8* %9 to <4 x double>*
  store <4 x double> %res.i19.1, <4 x double>* %ptr.i18.1, align 8
  %14 = getelementptr i8, i8* %.ptr, i64 64
  %15 = getelementptr i8, i8* %10, i64 64
  %16 = getelementptr i8, i8* %12, i64 64
  %ptr.i22.2 = bitcast i8* %15 to <4 x double>*
  %res.i23.2 = load <4 x double>, <4 x double>* %ptr.i22.2, align 8
  %ptr.i20.2 = bitcast i8* %16 to <4 x double>*
  %res.i21.2 = load <4 x double>, <4 x double>* %ptr.i20.2, align 8
  %res.i19.2 = fmul fast <4 x double> %res.i21.2, %res.i23.2
  %ptr.i18.2 = bitcast i8* %14 to <4 x double>*
  store <4 x double> %res.i19.2, <4 x double>* %ptr.i18.2, align 8
  %17 = getelementptr i8, i8* %10, i64 96
  %18 = getelementptr i8, i8* %12, i64 96
  %ptr.i22.3 = bitcast i8* %17 to <4 x double>*
  %res.i23.3 = load <4 x double>, <4 x double>* %ptr.i22.3, align 8
  %ptr.i20.3 = bitcast i8* %18 to <4 x double>*
  %res.i21.3 = load <4 x double>, <4 x double>* %ptr.i20.3, align 8
  %res.i19.3 = fmul fast <4 x double> %res.i21.3, %res.i23.3
  %res.i13 = fadd fast <4 x double> %res.i19.1, %res.i19
  %res.i13.1 = fadd fast <4 x double> %res.i19.2, %res.i13
  %res.i13.2 = fadd fast <4 x double> %res.i19.3, %res.i13.1
  %vec_2_1.i = shufflevector <4 x double> %res.i13.2, <4 x double> undef, <2 x i32> <i32 0, i32 1>
  %vec_2_2.i = shufflevector <4 x double> %res.i13.2, <4 x double> undef, <2 x i32> <i32 2, i32 3>
  %vec_2.i = fadd <2 x double> %vec_2_1.i, %vec_2_2.i
  %vec_1_1.i = shufflevector <2 x double> %vec_2.i, <2 x double> undef, <1 x i32> zeroinitializer
  %vec_1_2.i = shufflevector <2 x double> %vec_2.i, <2 x double> undef, <1 x i32> <i32 1>
  %vec_1.i = fadd <1 x double> %vec_1_1.i, %vec_1_2.i
  %res.i = extractelement <1 x double> %vec_1.i, i32 0
  call void @llvm.lifetime.end.p0i8(i64 256, i8* %.ptr)
  ret double %res.i
}

The lifetime start and lifetime ends are there, but so are three of the four stores.
I can confirm that the 4th store is gone:
julia> fill!(a, 0.0)'
1×16 LinearAlgebra.Adjoint{Float64,FixedSizeArray{Tuple{16},Float64,1,Tuple{1},16}}:
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

julia> test_lifetime!(a, b, c)
3.9704768664758925

julia> a'
1×16 LinearAlgebra.Adjoint{Float64,FixedSizeArray{Tuple{16},Float64,1,Tuple{1},16}}:
 0.157677  0.152386  0.507693  0.00696963  0.0651712  0.241523  0.129705  0.175321  0.236032  0.0314141  0.199595  0.404153  0.0  0.0  0.0  0.0

While without specifying lifetime all four must of course happen:
julia> function teststore!(a, b, c)
       storedot!(pointer(a), b, c)
       end
test_store! (generic function with 1 method)

julia> fill!(a, 0.0); test_store!(a, b, c)
3.9704768664758925

julia> a'
1×16 LinearAlgebra.Adjoint{Float64,FixedSizeArray{Tuple{16},Float64,1,Tuple{1},16}}:
 0.157677  0.152386  0.507693  0.00696963  0.0651712  0.241523  0.129705  0.175321  0.236032  0.0314141  0.199595  0.404153  0.256597  0.0376403  0.889331  0.479269

Yet, unlike with the alloca, it was not able to elide all 4 stores.
For reference, I built Julia with LLVM 8.0.1.
I'm not using alloca in place of my stack pointer for two reasons:
a) I got bugs when calling non-inlined functions with alloca-created pointers. Replacing those pointers with others made the bugs disappear, as did inlining the functions. If there is a way to resolve that, I could at least use alloca in a lot more places.
b) I couldn't find out how to get Julia to have more than 4MB of stack per thread available to alloca. I think 4MB is plenty for many of my use cases, but not all. A limit like that isn't great if I'm aiming to write fairly general software.
My questions:

*

*Is there any way I can get LLVM to replicate the behavior it shows with alloca?

*Did I do things correctly, and allow LLVM allowed to show the desired behavior, but the optimizer is for some reason more limited compared to alloca?

*And could therefore be expected to improve with future versions.

*Any advice on how to handle this, better enable the optimizers, or things I'm missing in general?

*Given that only the last is elided, is the problem that it assumes they may alias?

A: I edited in the following bullet after originally posting the question:

*

*Given that only the last is elided, is the problem that it assumes they may alias?

Turns out it was exactly this problem. If ptra did alias b or c, eliding the stores would have been invalid.
Writing instead:
a = @Mutable rand(48);
a[Static(1:16)]' * a[Static(17:32)]
# 2.5295415040590425

function test_lifetime!(a)
    ptra = pointer(a)
    b = PtrVector{16,Float64,16}(ptra)
    c = PtrVector{16,Float64,16}(ptra + 128)
    ptra += 256
    lifetime_start(Val(128), ptra)
    d = storedot!(ptra, b, c)
    lifetime_end(Val(128), ptra)
    d
end

test_lifetime!(a)
# 2.5295415040590425

Does in fact elide all the stores:
# julia> @code_native debuginfo=:none test_lifetime!(a)
        .text
        vmovupd 128(%rdi), %ymm0
        vmovupd 160(%rdi), %ymm1
        vmovupd 192(%rdi), %ymm2
        vmovupd 224(%rdi), %ymm3
        vmulpd  (%rdi), %ymm0, %ymm0
        vfmadd231pd     32(%rdi), %ymm1, %ymm0 # ymm0 = (ymm1 * mem) + ymm0
        vfmadd231pd     64(%rdi), %ymm2, %ymm0 # ymm0 = (ymm2 * mem) + ymm0
        vfmadd231pd     96(%rdi), %ymm3, %ymm0 # ymm0 = (ymm3 * mem) + ymm0
        vextractf128    $1, %ymm0, %xmm1
        vaddpd  %xmm1, %xmm0, %xmm0
        vpermilpd       $1, %xmm0, %xmm1 # xmm1 = xmm0[1,0]
        vaddsd  %xmm1, %xmm0, %xmm0
        vzeroupper
        retq
        nop

So the answer is: LLVM knows the alloca pointer cannot alias one of the inputs, therefore it is safe not to store.
The behavior I wanted in my question (without an alias check) would have been unsafe / liable to get incorrect results: one of the stores into ptra could change the contents of b or c. Hence, all but the very last store actually do have to be performed.
In this last test, I defined each of a, b, and c at different offsets from the same pointer, so that stores into a are guaranteed not to change b or c, letting LLVM actually eliminate the stores. Perfect!


text:
Q: Google Maps android get longitude-latitude by moving a marker in the map Hi i am developping an android application in which i need the user to choose a location by mouving a parker so i can get the informations i need exactly like this but in an android application.
I did some researchs but i'm still new so i couldn't find anything close to this.
Can anyone point me to the right direction ?
What i need to do is to create a mouving cursor in a simple google map that could give me long+lat data. all i coud do is put some static locations in my map.

A: Are you looking something like in the images below..

Here, if we drag marker on map it will automatically update the current lat, longs..
Here is the full complete solution with the code.
1.) Create a class AppUtils
public class AppUtils {

public class LocationConstants {
    public static final int SUCCESS_RESULT = 0;

    public static final int FAILURE_RESULT = 1;

    public static final String PACKAGE_NAME = "your package name";

    public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";

    public static final String RESULT_DATA_KEY = PACKAGE_NAME + ".RESULT_DATA_KEY";

    public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME + ".LOCATION_DATA_EXTRA";

    public static final String LOCATION_DATA_AREA = PACKAGE_NAME + ".LOCATION_DATA_AREA";
    public static final String LOCATION_DATA_CITY = PACKAGE_NAME + ".LOCATION_DATA_CITY";
    public static final String LOCATION_DATA_STREET = PACKAGE_NAME + ".LOCATION_DATA_STREET";

}

public static boolean hasLollipop() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}

public static boolean isLocationEnabled(Context context) {
    int locationMode = 0;
    String locationProviders;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);

        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return locationMode != Settings.Secure.LOCATION_MODE_OFF;
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return !TextUtils.isEmpty(locationProviders);
    }
}

}

2.) create another class FetchAddressIntentService
This class will fetch the address and point to that particular location which user is going to type on Google AutocompleteTextView..
public class FetchAddressIntentService extends IntentService {
private static final String TAG = "FetchAddressIS";

/**
 * The receiver where results are forwarded from this service.
 */
protected ResultReceiver mReceiver;

/**
 * This constructor is required, and calls the super IntentService(String)
 * constructor with the name for a worker thread.
 */
public FetchAddressIntentService() {
    // Use the TAG to name the worker thread.
    super(TAG);
}

/**
 * Tries to get the location address using a Geocoder. If successful, sends an address to a
 * result receiver. If unsuccessful, sends an error message instead.
 * Note: We define a {@link ResultReceiver} in * MainActivity to process content
 * sent from this service.
 * <p>
 * This service calls this method from the default worker thread with the intent that started
 * the service. When this method returns, the service automatically stops.
 */
@Override
protected void onHandleIntent(Intent intent) {
    String errorMessage = "";

    mReceiver = intent.getParcelableExtra(AppUtils.LocationConstants.RECEIVER);

    // Check if receiver was properly registered.
    if (mReceiver == null) {
        Log.wtf(TAG, "No receiver received. There is nowhere to send the results.");
        return;
    }
    // Get the location passed to this service through an extra.
    Location location = intent.getParcelableExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA);

    // Make sure that the location data was really sent over through an extra. If it wasn't,
    // send an error error message and return.
    if (location == null) {
        errorMessage = getString(R.string.no_location_data_provided);
        Log.wtf(TAG, errorMessage);
        deliverResultToReceiver(AppUtils.LocationConstants.FAILURE_RESULT, errorMessage, null);
        return;
    }

    // Errors could still arise from using the Geocoder (for example, if there is no
    // connectivity, or if the Geocoder is given illegal location data). Or, the Geocoder may
    // simply not have an address for a location. In all these cases, we communicate with the
    // receiver using a resultCode indicating failure. If an address is found, we use a
    // resultCode indicating success.

    // The Geocoder used in this sample. The Geocoder's responses are localized for the given
    // Locale, which represents a specific geographical or linguistic region. Locales are used
    // to alter the presentation of information such as numbers or dates to suit the conventions
    // in the region they describe.
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());

    // Address found using the Geocoder.
    List<Address> addresses = null;

    try {
        // Using getFromLocation() returns an array of Addresses for the area immediately
        // surrounding the given latitude and longitude. The results are a best guess and are
        // not guaranteed to be accurate.
        addresses = geocoder.getFromLocation(
                location.getLatitude(),
                location.getLongitude(),
                // In this sample, we get just a single address.
                1);
    } catch (IOException ioException) {
        // Catch network or other I/O problems.
        errorMessage = getString(R.string.service_not_available);
        Log.e(TAG, errorMessage, ioException);
    } catch (IllegalArgumentException illegalArgumentException) {
        // Catch invalid latitude or longitude values.
        errorMessage = getString(R.string.invalid_lat_long_used);
        Log.e(TAG, errorMessage + ". " +
                "Latitude = " + location.getLatitude() +
                ", Longitude = " + location.getLongitude(), illegalArgumentException);
    }

    // Handle case where no address was found.
    if (addresses == null || addresses.size() == 0) {
        if (errorMessage.isEmpty()) {
            errorMessage = getString(R.string.no_address_found);
            Log.e(TAG, errorMessage);
        }
        deliverResultToReceiver(AppUtils.LocationConstants.FAILURE_RESULT, errorMessage, null);
    } else {
        Address address = addresses.get(0);
        ArrayList<String> addressFragments = new ArrayList<String>();

        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
            addressFragments.add(address.getAddressLine(i));

        }
        deliverResultToReceiver(AppUtils.LocationConstants.SUCCESS_RESULT,
                TextUtils.join(System.getProperty("line.separator"), addressFragments), address);
        //TextUtils.split(TextUtils.join(System.getProperty("line.separator"), addressFragments), System.getProperty("line.separator"));

    }
}

/**
 * Sends a resultCode and message to the receiver.
 */
private void deliverResultToReceiver(int resultCode, String message, Address address) {
    try {
        Bundle bundle = new Bundle();
        bundle.putString(AppUtils.LocationConstants.RESULT_DATA_KEY, message);

        bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_AREA, address.getSubLocality());

        bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_CITY, address.getLocality());
        bundle.putString(AppUtils.LocationConstants.LOCATION_DATA_STREET, address.getAddressLine(0));

        mReceiver.send(resultCode, bundle);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

3.) Create your MapActivity in this we are going to display our map
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static String TAG = "MAP LOCATION";
Context mContext;
TextView mLocationMarkerText;
public LatLng mCenterLatLong;

/**
 * Receiver registered with this activity to get the response from FetchAddressIntentService.
 */
private AddressResultReceiver mResultReceiver;
/**
 * The formatted location address.
 */
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
Toolbar mToolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    mContext = this;
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mLocationMarkerText = (TextView) findViewById(R.id.locationMarkertext);
    mLocationAddress = (EditText) findViewById(R.id.Address);  //sss
    mLocationText = (TextView) findViewById(R.id.Locality);    //sss
    mToolbar = (Toolbar) findViewById(R.id.toolbar);           //sss
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    getSupportActionBar().setTitle(getResources().getString(R.string.app_name));

    mLocationText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            openAutocompleteActivity();

        }

    });
    mapFragment.getMapAsync(this);
    mResultReceiver = new AddressResultReceiver(new Handler());

    if (checkPlayServices()) {

        if (!AppUtils.isLocationEnabled(mContext)) {
            // notify user
            AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
            dialog.setMessage("Location not enabled!");
            dialog.setPositiveButton("Open location settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            });
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    // TODO Auto-generated method stub

                }
            });
            dialog.show();
        }
        buildGoogleApiClient();
    } else {
        Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
    }

}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d(TAG, "OnMapReady");
    mMap = googleMap;

    mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
        @Override
        public void onCameraChange(CameraPosition cameraPosition) {
            Log.d("Camera postion change" + "", cameraPosition + "");
            mCenterLatLong = cameraPosition.target;

            mMap.clear();

            try {

                Location mLocation = new Location("");
                mLocation.setLatitude(mCenterLatLong.latitude);
                mLocation.setLongitude(mCenterLatLong.longitude);

                startIntentService(mLocation);
                mLocationMarkerText.setText("Lat : " + mCenterLatLong.latitude + "," + "Long : " + mCenterLatLong.longitude);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }

}

@Override
public void onConnected(Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        changeMap(mLastLocation);
        Log.d(TAG, "ON connected");

    } else
        try {
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);

        } catch (Exception e) {
            e.printStackTrace();
        }
    try {
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection suspended");
    mGoogleApiClient.connect();
}

@Override
public void onLocationChanged(Location location) {
    try {
        if (location != null)
            changeMap(location);
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
protected void onStart() {
    super.onStart();
    try {
        mGoogleApiClient.connect();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected void onStop() {
    super.onStop();
    try {

    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            //finish();
        }
        return false;
    }
    return true;
}

private void changeMap(Location location) {

    Log.d(TAG, "Reaching map" + mMap);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    // check if map is created successfully or not
    if (mMap != null) {
        mMap.getUiSettings().setZoomControlsEnabled(false);
        LatLng latLong;

        latLong = new LatLng(location.getLatitude(), location.getLongitude());

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLong).zoom(15).tilt(70).build();

        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

      mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
        startIntentService(location);

    } else {
        Toast.makeText(getApplicationContext(),
                "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                .show();
    }

}

/**
 * Receiver for data sent from FetchAddressIntentService.
 */
class AddressResultReceiver extends ResultReceiver {
    public AddressResultReceiver(Handler handler) {
        super(handler);
    }

    /**
     * Receives data sent from
     * FetchAddressIntentService and updates the UI in MainActivity.
     */
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {

        // Display the address string or an error message sent from the intent service.
        mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);

        mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);

        mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
        mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);

        displayAddressOutput();

        // Show a toast message if an address was found.
        if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
            //  showToast(getString(R.string.address_found));

        }

    }

}

/**
 * Updates the address in the UI.
 */
protected void displayAddressOutput() {
    //  mLocationAddressTextView.setText(mAddressOutput);
    try {
        if (mAreaOutput != null)
           // mLocationText.setText(mAreaOutput+ "");

        mLocationAddress.setText(mAddressOutput);
        //mLocationText.setText(mAreaOutput);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Creates an intent, adds location data to it as an extra, and starts the intent service for
 * fetching an address.
 */
protected void startIntentService(Location mLocation) {
    // Create an intent for passing to the intent service responsible for fetching the address.
    Intent intent = new Intent(this, FetchAddressIntentService.class);

    // Pass the result receiver as an extra to the service.
    intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);

    // Pass the location data as an extra to the service.
    intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);

    // Start the service. If the service isn't already running, it is instantiated and started
    // (creating a process for it if needed); if it is running then it remains running. The
    // service kills itself automatically once all intents are processed.
    startService(intent);
}

private void openAutocompleteActivity() {
    try {
        // The autocomplete activity requires Google Play Services to be available. The intent
        // builder checks this and throws an exception if it is not the case.
        Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                .build(this);
        startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
    } catch (GooglePlayServicesRepairableException e) {
        // Indicates that Google Play Services is either not installed or not up to date. Prompt
        // the user to correct the issue.
        GoogleApiAvailability.getInstance().getErrorDialog(this, e.getConnectionStatusCode(),
                0 /* requestCode */).show();
    } catch (GooglePlayServicesNotAvailableException e) {
        // Indicates that Google Play Services is not available and the problem is not easily
        // resolvable.
        String message = "Google Play Services is not available: " +
                GoogleApiAvailability.getInstance().getErrorString(e.errorCode);

        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }
}

/**
 * Called after the autocomplete activity has finished to return its result.
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Check that the result was from the autocomplete widget.
    if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
        if (resultCode == RESULT_OK) {
            // Get the user's selected place from the Intent.
            Place place = PlaceAutocomplete.getPlace(mContext, data);

            // TODO call location based filter

            LatLng latLong;

            latLong = place.getLatLng();

            //mLocationText.setText(place.getName() + "");

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLong).zoom(15).tilt(70).build();

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling

                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

        }

    } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
        Status status = PlaceAutocomplete.getStatus(mContext, data);
    } else if (resultCode == RESULT_CANCELED) {
        // Indicates that the activity closed before a selection was made. For example if
        // the user pressed the back button.
    }
}

}
4.) Changes in Manifest
  provide all the necessary internet permissions.
Don't forget to add these two things
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="Your google map api key" />

and,
      <service
        android:name=".FetchAddressIntentService"
        android:exported="false" />

That's it, You're done with the code part!!
Just Run it..

A: Utilize draggable markers, via the onMarkerDragEnd method
@Override
public void onMarkerDragEnd(Marker marker) {
    // TODO Auto-generated method stub
}

Within that method you could do something like
LatLng position = marker.getPosition();
double latitude = position.latitude;
double longitude = position.longitude;

There you have it. .........

A: @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener()
        {
            @Override
            public void onCameraChange(CameraPosition cameraPosition)
            {

                mCenterLatLong = cameraPosition.target;
                mMap.clear();

                try
                {

                    Location mLocation = new Location("");
                    mLocation.setLatitude(mCenterLatLong.latitude);
                    mLocation.setLongitude(mCenterLatLong.longitude);

                    startIntentService(mLocation);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Чат-боты, запоминание последней темы Хоть здесь и не приветствуются вопросы-обсуждения, решил все-таки создать подобный. Как лучше сделать запоминание темы для чат-бота на PHP.
Пока такие мысли:
Попадается ключевое слово - добавляется тема, дальнейшие сообщения записываются к ней, и уже анализируются только они, как этакая память. Но как можно было бы в целом сделать лучше этот механизм?


text:
Q: Configure log4net for asp.net MVC3 project Ok, so I'm understood how to configure the log4Net in my application, But now
First I want to improve the configuration by differencing the level of the logs if the application it's a release or a debug, how can I do this?.
Second, If I had a folder in my project called LOG how can I set the configuration, to not used the physical folder of my application??
for example Instead of:
<file value="C:\physicalpath\LOG\Log.log" />

used
<file value="\LOG\Log.log" />

or
<file value="%some_variable%\LOG\Log.log" />

A: Remember maybe you should to add in Global.asax.cs the follow code:
protected void Application_Start()
{
    log4net.Config.XmlConfigurator.Configure();
    //...more code
}

A: The documenation is straight forward:

file: the full or relative path to the log file.

So all you need to have is the full path like C:\physicalpath\LOG\Log.log or the ralative one, this needs to start with the dot char . like .\App_Data\Log4Net.Logs
you can also use the folder name in the file attribute, then you must use the datePattern attribute to specify the file name, for example:
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
  <file value=".\\App_Data\\Log4Net.Logs\\backend"/>
  <datePattern value=".yyyy-MM-dd'.log'"/>
  <appendToFile value="true"/>
  <maximumFileSize value="256KB"/>
  <maxSizeRollBackups value="2"/>
  <rollingStyle value="Date"/>
  <staticLogFileName value="false"/>
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%level %thread %logger - %message%newline"/>
  </layout>
</appender>

Also remember to add the
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>

So you can avoid that log4net lock the file and you can't used it to append your messages.
If you're not used to log4net, don't forget to add the <root> node, this is the the one that let's log4net know what you want to use and not the <appender> nodes, for example, you can have 10 <appender> nodes and use only one, the <root> node is then only configured with the one you want to use...

here is a full configuration with 2 Mongo Appenders and 1 File Appender, the <root> specifies that only the file appender is in use:
  <log4net>
    <appender name="MongoAppender" type="log4net.Appender.MongoDBAppender, log4mongo-net">
      <!-- MongoDB 1 connection options -->
      <host value="staff.mongohq.com"/>
      <port value="10077"/>
      <databaseName value="myApp_2011"/>
      <collectionName value="logs_net"/>
      <userName value="myself"/>
      <password value="123456"/>
    </appender>
    <appender name="MongoAppenderAppHarbor" type="log4net.Appender.MongoDBAppender, log4mongo-net">
      <!-- MongoDB 2 connection options -->
      <host value="staff.mongohq.com"/>
      <port value="10048"/>
      <databaseName value="d1741d63-46b1-4a44-9c49-8c28cecae36b"/>
      <collectionName value="logs_net"/>
      <userName value="myself"/>
      <password value="123456"/>
    </appender>
    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
      <!-- Local file options -->
      <file value=".\\App_Data\\Log4Net.Logs\\backend"/>
      <datePattern value=".yyyy-MM-dd'.log'"/>
      <appendToFile value="true"/>
      <maximumFileSize value="256KB"/>
      <maxSizeRollBackups value="2"/>
      <rollingStyle value="Date"/>
      <staticLogFileName value="false"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level %thread %logger - %message%newline"/>
      </layout>
    </appender>
    <root>
      <!--
         <level value="DEBUG" />
         <appender-ref ref="MongoAppender" />
         <appender-ref ref="MongoAppenderAppHarbor" />
      -->
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>

A: Below is a sample app.config section, with the Path being defined through the <file value="somepath"/> tag.
This link is a good resource for documentation
<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
   <file value="C:\\SOMEPATH\\SOMELOG.log"/>
   <appendToFile value="true"/>
   <rollingStyle value="Size"/>
   <maxSizeRollBackups value="10"/>
   <maximumFileSize value="10MB"/>
   <layout type="log4net.Layout.PatternLayout">
     <conversionPattern value="%date [%thread] %-5level %logger – %message%exception%newline"/>
   </layout>
 </appender>
 <root>
   <level value="ALL"/>
   <appender-ref ref="RollingFileAppender"/>
 </root>
</log4net>


text:
Q: TypeError: sequence item 0: expected str instance, float found My code-
out = []
for _, row in df.iterrows():
    name = " ".join(row[0:4])

    entities = []
    i = 0
    for n in row.index[0:4]:
        entities.append([i, i + len(row[n]), n])
        i += len(row[n])+1
    out.append([name, {"entities": entities}])

My Dataframe-
             house                  road                        sub_area
0         726/30/3                 road 10                         abcd
1              977                 road 16                         efgh

I am getting the error
line 12, in <module>
    name = " ".join(row[0:4])
TypeError: sequence item 0: expected str instance, float found

How do I resolve this issue?

A: Without having knowing what df is, we can only guess. But usually the problem is that one is trying to str.join something else than strings. So try this instead:
name = " ".join(map(str, row[0:4]))


text:
Q: Internet connection slower than network connection speed I've got a computer connected to a wireless router on a different floor. When I look at the network connection, I'm told the signal strength is low, and that I've got a connection of about 26mbps (often higher). However, my internet connection on that machine is very slow. Speedtests show it at about 1-2mbps, and it really shows when loading pages and video. I have fiber optic internet access, and the machine that's connected to the router/modem via cable gets the 20mbps on speed tests, and is extremely fast in every day use.
My question is, is the advertised 26mbps+ connection speed perhaps inaccurate, and that my wireless bandwidth is the likely bottleneck here? Or is the signal strength what's key here? And what might I do about this? Power cycling the router helped a bit, a speed test went as high as 6mbps after doing that.

A: There are a number of reasons why you might be experiencing problems with your wireless network speeds:

*

*A neighboring wireless network might be using the same channel

*There might be too much interference between the access point and your computer

*Your router might be incompatible with your ISP's fiber modem

Likely it's either the first or the second. Network strength is a likely cause due to dropped packets. If there is a weak signal, the communications on both sides are hindered and each device will send out a packet, wait for a response from the destination; if that times out, it will resend the same packet. Once that is successful it will send the next packet and wait again... You can see how this could dramatically slow down network performance.
The way I see it, you can do a couple of things:

*

*Move either the router or the computer closer to each other.

*Check to make sure any networks close by are not using the same channel. If they are, change your own to something that's at least 2 channels away.

*Try upgrading to Wireless-N (802.11n)

*Get a more powerful antennae. Do a Google search for an 8 ohm antennae that is compatible with your router. A note of warning here: I did this with one of my wireless networks and I had some angry neighbors because my signal was drowning out theirs.

A: 26mbps is an unrealistic number. We made tests at the university during my time there and if I remember correctly the real throughput was about half of it. Which means about 13Mbps.
(And I hope you mean bit per second in both cases.).
Secondly: If the connection is bad data must be repeated due to losses in the wireless transmission.
At home I made an observation: I have about 13 Routers in my neighbourhood. With 12 available channels there is no chance that they do not disturbe each other. Most of current routers have adaptive signal strength, which means if they don't get their throughput, they increase the signal strength.
Now, when I was downloading something, everything went fine for the first 10-20 seconds. After that my throughput went down to just 1-2mbps. My guess is, that through my constant transmission other routers powered up to still be able to send. This results in more collisions (i.e. data not received correctly) which results in a repeated transmission which results in decrease of transmission speed (seen on a received data basis).


text:
Q: Looping through images in directory: ioslides I'm automating a presentation and want to create a slide for each image in a directory (the image filenames are all .png files with three-character names).
This works as desired to test that the slide with title and image will render:
```{r, results="asis", out.width="900px"}
plot_files <- list.files(paste0(mydir, "/plots"))
i <- 1
cat("\n\n##", substr(plot_files[i], 1, 3), "\n\n", sep="")
knitr::include_graphics(paste0(dir, "/plots/", plot_files[i]))
```

But when I wrap the above into a for loop...
```{r, results="asis", out.width="900px"}
plot_files <- list.files(paste0(mydir, "/plots"))
for (i in 1:length(plot_files)) {
  cat("\n\n##", substr(plot_files[i], 1, 3), "\n\n", sep="")
  knitr::include_graphics(paste0(dir, "/plots/", plot_files[i]))
}
```

...each of the slides is correctly generated with the title, but the images no longer render. Any ideas why wrapping the code in the loop would cause the image rendering to fail?

A: Instead of knitr::include_graphics(), I think you can use the (Pandoc) Markdown syntax for images, e.g.
cat('![](', paste0(dir, "/plots/", plot_files[i]), '){width=900px}\n\n', sep = '')


text:
Q: Not able to connect mysql with python 2.7 in django 1.11 getting error while installing mysqlclient and MySQL-python both i am trying to install mysql client to connect mysql with python 2.7 for django project but getting error, even i tried MySQL-python connector to install but getting error there also.
C:\Users\syedabdul\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dve
rsion_info=(1,3,12,'final',0) -D__version__=1.3.12 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include" -Ic:\python27\include -Ic:\pyt
hon27\PC /Tc_mysql.c /Fobuild\temp.win32-2.7\Release\_mysql.obj /Zl
    _mysql.c
    _mysql.c(29) : fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
    error: command 'C:\\Users\\syedabdul\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\cl.exe' failed with
exit status 2

    ----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\syedab~1\\appdata\\local\\temp\\pip-build-xgy30p\\mysqlc
lient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))
" install --record c:\users\syedab~1\appdata\local\temp\pip-rs9dvc-record\install-record.txt --single-version-externally-managed --compile" fail
ed with error code 1 in c:\users\syedab~1\appdata\local\temp\pip-build-xgy30p\mysqlclient\

A: I would suggest you use the appropriate official python wheel for your system from pypi.python.org then install it by pip install MySQLConnector2.7.whl assuming MySQLConnector2.7.whl is the file name


text:
Q: tsearch2 add resultset to index How can I add a resultset (more than one entry) to a tsvector? I use postgres 8.3.
I have an m-n relationship and I'd like to have all values from one column of the n-side in the tsvector of the m-side.
This statement will work if I have an limit to one the subselect. But not without the limit.
UPDATE mytable
    SET mytsvector=to_tsvector('english',
        coalesce(column_a, '') ||' '||
        coalesce((SELECT item FROM other_table WHERE id = other_id LIMIT 1), '')
    )

ERROR:  more than one row returned by a subquery used as an expression

A: Under Postgres 8.3 at first I have to create an aggregate function to generate an array from an select.
CREATE AGGREGATE array_accum (
   sfunc = array_append,
   basetype = anyelement,
   stype = anyarray,
   initcond = '{}'
);

Since 8.4 there is the function array_agg().
The hole statement looks like this:
UPDATE mytable
SET mytsvector=to_tsvector('english',
    coalesce(column_a, '') ||' '||
    coalesce(
        (SELECT array_to_string(array_accum(item), ' ')
         FROM mytable m, other_table o
         WHERE o.id = m.other_id AND m.id = id GROUP BY m.id), '')
)


text:
Q: Eclipse with ADT plugin - layout editor doesn't show content (stuck on "Loading editor") I'm facing a very strange issue on Eclipse with Android ADT plugin.
When I try to open an XML layout file, the result is the one in the screenshot.
The Layout editor doesn't show the file name and no content is loaded. The editor stuck on "Loading editor" and if I switch to view, the XML is loaded fine.
This issue is raising up with every layout file and with every project I open.
I tried to:

*

*restart Eclipse

*update the ADT plugin

*install all the packages and updates from the Android SDK Manager

no errors are shown in the console.

UPDATE
Now Eclipse is showing a pop-up error "An error has occurred. See error log for more details.java.lang.NullPointerException" when I try to open any Layout XML file.

A: Solution 1
At the right side of the image you attached click the android logo with 19 a drop down list will open select some different version...
selecting 20 works for me
Solution 2
right click layout file in the Package Explorer view and click
Open With -> Android Layout Editor

A: *

*Right-click on your project and close all unrelated projects. Keep only one project opened at any one time.

*Close all your perspectives and then open only a Java perspective.

*Ensure that there is indeed a UCApplicationTheme that it has access to, otherwise change it to a different theme.

*Restart Eclipse. Then restart your computer.

*Then try opening a default layout from a newly generated blank Android project. Do not open the layout of a web view, even if you normally develop on Phone Gap/Cordova. Let's eliminate the web view as a possible problem.

*When all else fails, reinstall Eclipse, the SDK, and ADT, completely from scratch.
And if you do get a NullPointerException, please be specific. Cut and paste on here the exact error it's giving you.

A: The Problem is you did update only android development tools from developer tool..
so you need to update the whole packages which are provided by the eclipse market..
Go to help-->install new software-->add the Repository-->and select all check boxes which are available in the developer tool...
Its works for me..


text:
Q: How can I get the foreground color in Photoshop with AppleScript? How can I get the foreground color in Photoshop with AppleScript? Preferably in hex format.

A: Get the color using foreground color. See here (PDF link), pages 12 and 13, for examples on how to use it.
Convert using convert color (page 188).
It should work with something like the following; I don't have PS to test it though:
tell application "Photoshop"
    set fgColor to foreground color
    set fgHexColor to convert color fgColor to RGB Hex
end tell

A: Usually tell app "Adobe Photoshop CS5" to foreground color should work.
There's a bug in CS5 where most of the Applescript terminology doesn't get loaded under some conditions: Adobe Forums: Changes to Photoshop CS5 and Applescript. I'm also experiencing it, but some of the suggested fixes (Opening PS in 32 bit mode, opening PS before ASE) didn't work for me. I didn't try reinstalling.
There's also an AppleScript Reference for CS5, see Adobe Photoshop Scripting | Adobe Developer Connection.


text:
Q: how to find out the full name of Java class in DropWizard logs We are using DropWizard in a Java based micro-service. In the logs, we have lines like:
[dw-1000 - POST myservice/endpoint] c.s.x.m.s.c.p2p - my error message

My question is: how can I find out the full names of the Java class path represented as "c.s.x.m.s.c.p2p" in the above log message?
Thanks.

A: You need to change the default configuration in your yaml:
The logFormat is the key to your solution - %c displays the full logger name, and if there is no number followed, it's the full name with no name-cuts:
logging:
  appenders:
    - type: file
      ...
      logFormat: '[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%c] [%thread] [-[%msg]-] %n'


text:
Q: Group by count zero rows not displaying I want to count the amount of rows of every componistId. When I run the following SQL statement it works fine:
SELECT C.componistId, COUNT(*)
FROM Componist C LEFT JOIN Stuk S ON S.componistId = C.componistId
GROUP BY C.componistId

Now I want only the rows where stukNrOrigineel is null
SELECT C.componistId, COUNT(*)
FROM Componist C LEFT JOIN Stuk S ON S.componistId = C.componistId
WHERE S.stuknrOrigineel IS NULL
GROUP BY C.componistId

But when I do this, all the rows with a result of 0 disappear. Only the rows with at least 1 row are displayed. How can I make this work?

A: You need to include the condition in the on clause:
SELECT C.componistId, COUNT(C.componistId)
FROM Componist C LEFT JOIN
     Stuk S
     ON S.componistId = C.componistId AND
        S.stuknrOrigineel IS NULL
GROUP BY C.componistId;

Note:  I changed the COUNT() to count from the second table.  This is normally what you want when combining LEFT JOIN with COUNT().
On some databases, I think the above might not quite work as expected (the question is whether the condition on S is evaluated before or after the LEFT JOIN).  This should always work:
SELECT C.componistId, COUNT(s.componistId)
FROM Componist C LEFT JOIN
     (SELECT S.* FROM Stuk S WHERE S.stuknrOrigineel IS NULL
     ) s
     ON S.componistId = C.componistId AND
GROUP BY C.componistId;

Another generic solution is move the condition into the aggregation function:
SELECT C.componistId,
       SUM(CASE WHEN S.stuknrOrigineel IS NULL THEN 1 ELSE 0 END)
FROM Componist C LEFT JOIN
     Stuk S
     ON S.componistId = C.componistId
GROUP BY C.componistId;


text:
Q: Pushing data from a server to Web based UI elements I want to connect a bunch of weather sensors to a Raspberry PI. Writing the daemon that reads the sensors and writes the data to a database will be the easy part since I'm a systems programmer. I also want a simple cross platform UI for this device so I'd like to set my Raspberry Pi up as a WIFI hotspot that people can connect to and then just entering a URL like 'weather.local' into a browser which would take them to a web page where the weather sensor data is continually updated. I.e. I want the sensor daemon to 'push' updates to the web page.
The problem is that I'm no web developer. The solutions I can think of off the top of my head are:

*

*Flash, which is out because I want this to work on mobile browsers.

*Using Java script and hanging HTTP requests to a web service.

*HTML5 socket.io which is presumably the same as WebSocket.

If I go with option (2) even if it's a kind of polling, I'll have to incorporate some form of HTTP server into my sensor daemon and I have a fair idea of how to code that. My question, however, regards the HTML5 socket IO. Can I use this to connect directly to a TCP/IP binary socket or do I need a server side WebSocket library? Also how widely is HTML5 socket.io/WebSocket implemented on mobile browsers?

A: WebSocket always begins with an upgrade handshake over HTTP, so you do need to have basic HTTP capability. It's simple enough that you can hand-code it.
WebSockets is basically supported by all modern browsers. It is not used that widely because it's a pain to set up on traditional HTTP servers and messes up with many proxies, but that's not a problem for you. As long as the client is a recent version of anything, it'll work.
A note about option 2: browsers have a native implementation of it — that means you don't need so much JavaScript on the client. You just create the EventSource object and listen to its events.


text:
Q: Application not working after submitting to the play store When i build and when i signed apk its working fine in my phone but after the upload in google play store something happened and it won't start. Once i open the application i face the error unfortunately app has stopped working! i'm really confused! any suggestion?And i thought this is Pro-guard rules issue can some one suggestion me please.
Error Log
Caused by java.lang.ClassNotFoundException
Didn't find class "com.google.android.gms.measurement.AppMeasurementInstallReferrerReceiver" on path: /data/app/com.karvyinnotech.nba-1.apk
android.app.ActivityThread.handleReceiver

Gradle:
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.karvyinnotech.nba"
        minSdkVersion 16
        targetSdkVersion 27
        versionCode 1
        versionName "1.1"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            minifyEnabled true
            //shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            // shrinkResources false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    useLibrary 'org.apache.http.legacy'
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }

    dexOptions {
        javaMaxHeapSize "4g"
        preDexLibraries = false
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.mcxiaoke.volley:library-aar:1.0.0'
    implementation 'com.google.code.gson:gson:2.7'
    testImplementation 'junit:junit:4.12'
    //noinspection GradleCompatible
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.cocosw:bottomsheet:1.+@aar'
    implementation 'com.android.support:multidex:1.0.1'
    implementation('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
    }
    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5'
    //google services
    implementation 'com.google.android.gms:play-services-location:15.0.1'
    implementation 'com.google.firebase:firebase-core:11.4.2'
    implementation 'com.google.firebase:firebase-messaging:17.1.0'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.2'
    implementation 'com.google.firebase:firebase-crash:15.0.2'
    implementation 'com.google.android.gms:play-services-analytics:15.0.2'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.weiwangcn.betterspinner:library-material:1.1.0'
}
apply plugin: 'com.google.gms.google-services'

proguard-rules.pro
-dontwarn org.**
-dontwarn okio.**
-dontwarn com.squareup.**
##---------------Begin: proguard configuration common for all Android apps ----------
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-repackageclasses ''
-allowaccessmodification
-optimizations !code/simplification/arithmetic
-keepattributes *Annotation*

-keep class java.io.** { *; }
-keep class com.google.** { *; }
-keep class org.apache.** { *; }
-keep public class org.apache.commons.io.**
#volley
-keepclasseswithmembernames  interface com.android.volley.** { *; }
-keep class org.json.** {*;}
-keep class android.accounts.**{*;}
-keep class java.io.**{*;}
-keep class android.net.**{*;}
-keep class org.apache.http.**{*;}
-keep class android.net.http.AndroidHttpClient{*;}
-keep class com.android.volley.** {*;}
-keep class com.android.volley.toolbox.** {*;}
-keep class com.android.volley.Response$* { *; }
-keep class com.android.volley.Request$* { *; }
-keep class com.android.volley.RequestQueue$* { *; }
-keep class com.android.volley.toolbox.HurlStack$* { *; }
-keep class com.android.volley.toolbox.ImageLoader$* { *; }
-keep class org.apache.commons.logging.**
-keep class com.karvyinnotech.nba.models.** { *; }
-keep class android.support.v7.app.** { *; }
-keep interface android.support.v7.app.** { *; }

##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-dontwarn sun.misc.**
#-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }

# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
##---------------End: proguard configuration for Gson  ----------

-keep public class * extends android.app.Activity
-keep public class * extends android.app.AppCompatActivity
-keep public class * extends android.app.Fragment
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.app.IntentService
-keep public class * extends com.google.firebase.messaging.FirebaseMessagingService
-keep public class * extends com.google.firebase.iid.FirebaseInstanceIdService
-keep public class * extends android.content.BroadcastReceiver
-keep public class com.android.vending.licensing.ILicensingService
-keep public class * implements java.io.Serializable

-keep public class * extends android.view.View {
    public <init>(android.content.Context);
    public <init>(android.content.Context, android.util.AttributeSet);
    public <init>(android.content.Context, android.util.AttributeSet, int);
    public void set*(...);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * implements android.os.Parcelable {
    static android.os.Parcelable$Creator CREATOR;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keepattributes InnerClasses
-keep class **.R
-keep class **.R$* {
    <fields>;
}

# Keep subscribe-methods from deletion
-keepclassmembers class ** {
  @com.google.common.eventbus.Subscribe <methods>;
}

# ================ Google Play Services ================
-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}
# ======================================================

#-keepclassmembers class **.R$* {
#    public static <fields>;
#}

-ignorewarnings

A: I suggest put following tow line in your pro guard file
-dontwarn com.google.android.gms.**
-keep class com.google.android.gms.** { *; }
-keep class com.google.firebase.** { *; }


text:
Q: Using jQuery $.each with Json erroring with 1 result Basically I am transforming a JSON result into html and using $.each it iterate through multiple keys. For example, I am pulling back facebook posts and iterating through the likes in that post.
The problem lies in the fact that when there are multiple "likes" everything works great! although when there is only 1 "like" the "source" key is removed from the result set and my javascript breaks because I expect it to be there. Any idea why the $.each is skipping a level for single nodes? The following is my code:
* JQUERY **
          $.each(post.likes.item, function(i, like){
             $(currentpost).find('div.cc_likes').append(like + ',');
             console.log(like)
          });

* JSON RESULT **
* Single Like
       likes": {
            "item": {
                "source": {
                    "cta": "Mary Smith",
                    "url": "http:\/\/www.facebook.com\/",
                    "photo": {
                        "image": "https:\/\/graph.facebook.com\/"
                    }
                }
            },

Result in console:
    Object
      cta: "MaryAnn Smith"
      photo: Object
      url: "http://www.facebook.com/"

* Multiple Likes
        "likes": {
            "item": [
                {
                    "source": {
                        "cta": "Bobby Carnes Sr.",
                        "url": "http:\/\/www.facebook.com",
                        "photo": {
                            "image": "https:\/\/graph.facebook.com\"
                        }
                    }
                },
                {
                    "source": {
                        "cta": "Jenna Purdy",
                        "url": "http:\/\/www.facebook.com\",
                        "photo": {
                            "image": "https:\/\/graph.facebook.com\"
                        }
                    }
                },
                {
                    "source": {
                        "cta": "Kevin Say",
                        "url": "http:\/\/www.facebook.com\",
                        "photo": {
                            "image": "https:\/\/graph.facebook.com\"
                        }
                    }
                }
            ],
            "count": "10",
            "count_display": "10"
        },

Result in console:
    Object
      source: Object
        cta: "Kevin Smith"
        photo: Object
        url: "http://www.facebook.com/"

A: Since $.each() needs an array or array like object as argument, before using the object post.likes.item check if it is an array of not.
Following code will always pass an array to jQuery -
     $.each([].concat(post.likes.item), function(i, like){
         $(currentpost).find('div.cc_likes').append(like + ',');
         console.log(like)
      });

Explanation
[] is an empty array in JavaScript. Every array in JavaScript has a concat method.
[].concat(obj) concats obj to the empty array and returns an array.

*

*if obj is not an array, result is [obj] which is an array with one item.

*if obj is an array, then result is a deep copy of obj which is already an array.

More about concat method

A:         if ( isArray ) {
        for ( ; i < length; i++ ) {
                value = callback.call( obj[ i ], i, obj[ i ] );

                if ( value === false ) {
                    break;
                }
            }
        } else {
            for ( i in obj ) {
                value = callback.call( obj[ i ], i, obj[ i ] );

                if ( value === false ) {
                    break;
                }
            }
        }

That is the jquery code being run on your JSON return. What's happening is, when you are looking at multiple results, it is looping through the array, return each base level object. However, when you are running it on a single return, it is looping through the object properties(in this case, "source"), and returning the value of that property.
You have two choices here. You can either make sure single items are still put in an array, or you can do a check for single items on the client side. The way Moazzam Khan suggests is the best way to do it in most cases.


text:
Q: Are `|` and `mknod pipe p` doing the same thing? So obvious thing here the | being referred to as the pipe operator.
It got me wondering if the pipe operator is just an anonymous pipe.
Whereas mknod pipe p is just a named pipe.
Am I correct in thinking this or is there more at work here? Does Linux just create an anonymous hidden pipe file under the covers when you use the pipe operator?

A: A named pipe is a entity in the filesystem (type "p", in front of the file permission) that allows you to transfer data between unix processes. It has a filename and sits in a directory
The pipe operator | just connects left stdout to right stdin, basically.
There's no need for an entry in the filesystem.


text:
Q: Does passing objects as props interfere with componentWillReceiveProps? My React app needs to keep track of a configuration object with dynamic keys, so I pass it to a component like this:
<Component configuration={this.state.configuration}>

While this works, when I am in the Component's componentWillReceiveProps(nextProps) I cannot discern configuration changes, because this.props has already been updated to nextProps.
If this isn't a known issue, perhaps it has to do with the way I handle updates to configuration state in the parent?  Here's how I update configuration state:
  handleConfigurationChangeForKey(newOption, key) {
    const configObject = this.state.configuration;
    configObject[key] = newOption;
    this.setState({configuration: configObject});
  }

Thanks in advance for any help.

A:
I cannot discern configuration changes, because this.props has already been updated to nextProps.

This is not true. this.props will have the current props, nextProps the upcoming ones.
The way you set the state could be the problem. Try creating a new configuration object, using Object.create or a deep copying function (such as the one provided by lodash).
const newConfig = Object.create(oldConfig)
# or
const newConfig = _.cloneDeep(oldConfig)

newConfig[key] = newValue

This way, the object won't be equal by reference to the old version. If copying brings a performance problem, you can try the Immutable.js library for your state objects.

A: When you're updating the config object, you're mutating it: you can't tell the difference between nextProps.configuration and this.props.configuration because they're the same object.
The way to get around this is to basically clone the original config object, mutate that, and then use setState to make configuration point to that new object.
handleConfigurationChangeForKey(newOption, key) {
  const nextConfiguration = {
    ...this.state.configuration,
    [key]: newOption
  };
  this.setState({ configuration: nextConfiguration });
}

Using only older language features
handleConfigurationChangeForKey(newOption, key) {
  var nextConfiguration = {};
  nextConfiguration[key] = newOption;
  nextConfiguration = Object.assign(
    {},
    this.state.configuration,
    nextConfiguration
  );
  this.setState({ configuration: nextConfiguration });
}


text:
Q: Multiple makers and type conversion Vector<Medicine*>* Controller::sortByStockAsc(){
    Vector<Medicine*>* all =repo->getAll();
    qsort(all, all->getSize(),sizeof(Medicine*), (comparefunction) compareNA);
    return all;
}

So,I have the function above which should sort an array of objects.I get the error
cannot convert 'Vector<Medicine*>' to 'Vector<Medicine*>*' in initialization

But if I write it as Vector<Medicine*> all =repo->getAll();  I get a bunch of new errors for the 3rd line(which aren't there if I have the previous error on the 2nd line):
Multiple markers at this line
    - Method 'getSize' could not be resolved
    - Invalid arguments ' Candidates are: void qsort(void *, unsigned int, unsigned int, int (*)(const void *, const
     void *)) '
    - base operand of '->' has non-pointer type 'Vector<Medicine*>'

What's wrong with this and how can I fix it?

A: Try this instead:
Vector<Medicine*> Controller::getMedicinesSortedByStockAsc() {
    Vector<Medicine*> all = repo->getAll();
    std::sort(all.begin(), all.end(), compareNA);
    return all;
}

Notes:

*

*You didn't provide a definition of Vector so I assume it is STL-compatible.  Judging by the rest of the code this may be an incorrect assumption.

*You didn't provide a description of compareNA but I've chosen to assume that it can be made compatible with STL-style algorithms.


text:
Q: EGit wrong parent after commit (Eclipse Git) Assuming I have a synchronized working copy, local Git repository and remote Git repository.
I'm not totally sure if the working copy and the local repository are really synchronized. But they do have the same files and I have "no changes" denoted between working copy and local repository.
My initial state of the repository looks like this (I'm working on a Branch called "GenerateContent"):

Now I make some changes to my working copy and commit them to the local "GenerateContent" branch.
Now the problem occurs: Instead of using the current commit-state as a parent, an earlier state is used as a parent. You can see this in the screenshot:

From this emerge many problems. For example I have to merge my changes with an older version.
This problem does occur only in EGit (Eclipse Git). When I do the same changes in eclipse, but do the commit from another software (SourceTree), then the tree stay's linear.
What do I do wrong in EGit? How can I fix this issue?

A: Can you file an EGit bug for this and attach your sample repository? If you can't publish the repository, the output of git log --oneline --graph --all --decorate may help to understand the situation before and after the commit.


text:
Q: Tilde in listings using lineskip and a command breaks "onehalfspace" I'm trying to produce an inline code snippet that starts with a ~.
Using onehalfspacing per university requirement and lineskip=-1pt for subjectively better legibility, packing the \lstinline inside a command shortcut destroys the spacing in all future sections.
Why does this occur? How is the command version parsed differently than what the command is supposed to be a shortcut for? I suspect it has something to do with how ~ is parsed inside a command?
Removing the lineskip or placing any character in front of the ~ fixes this issue, but isn't desirable for me.
MWE:
\documentclass{scrreprt}
\usepackage{listings}
\usepackage{blindtext}
\usepackage[onehalfspacing]{setspace}

\lstset{
    lineskip=-1pt,
    literate={~} {$\sim$}{1}
}

\newcommand{\code}[1]{\lstinline{#1}}

\begin{document}

\section{Inline}
\lstinline{~1}\\
\blindtext

\section{No tilde}
\code{FIX ~1}\\
\blindtext

\section{Tilde breaks everything}
\code{~1}\\
\blindtext

\end{document}

A: Not completely sure why, but
\newcommand{\code}{\lstinline}

with no change in the document code fixes the problem.
Well, there are some clues: with your definition, ~ is tokenized before being passed to \lstinline and this is probably the issue.


text:
Q: Set NavigationBar title Font I've been searching for a way to change title font in navigationBar and have made below attempt however nothing happens, the font works fine on UILabel and so on.
UINavigationBar.appearance().titleTextAttributes = [
    NSFontAttributeName: UIFont(name: "SourceSansPro-Regular", size: 18) ?? UIFont.systemFontOfSize(18)
]

A: [[UINavigationBar appearance] setTitleTextAttributes:@{
    UITextAttributeTextColor : [UIColor whiteColor],
    UITextAttributeTextShadowColor : [UIColor blackColor],
    UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetMake(1, 0)],
    UITextAttributeFont : [UIFont fontWithName:@"System" size:25.0]
}];

in swift
        UINavigationBar.appearance().titleTextAttributes = [UITextAttributeTextColor: UIColor.whiteColor(),
    UITextAttributeTextShadowColor: UIColor.blackColor(),
    UITextAttributeTextShadowOffset: NSValue(UIOffset: UIOffsetMake(1, 0)),
UITextAttributeFont: UIFont(name: "System", size: 25.0)]


text:
Q: How to make the textview content HORIZONTAL I need dynamic create the texview, it works just the text content show VERTICAL but  HORIZONTAL
TextView tv = new TextView(this.theContext);
    tv.setText(this.getTip(0));
    tv.setBackgroundColor(Color.BLUE);
    tv.setGravity(Gravity.CENTER_HORIZONTAL);

    tv.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
    LinearLayout.LayoutParams params =
            new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        params.gravity = Gravity.CENTER;
        this.addView(tv, params);

    mLeftLabel = tv;

also, I set the layout :
tv.layout(l,t,r,b); . but I think that this statement should not effect the text Direction, is it right ?
please give help or tip, thanks.

A: try to follow the example below:
TextView tv = new TextView(this);
tv.setText("text");
LinearLayout.LayoutParams params =
    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 0, 0);
params.gravity = Gravity.CENTER;
mainLayout.addView(tv, params);

A: try changing LayoutParams as
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

setting gravity to center when you are using WRAP_CONTENT for textview does not seem to make sense, though I am not sure.


text:
Q: Applying advanced logic to modify a list I have two lists
copy_from = ['2.02,1.91', '1.9,2.06', '1.86,1.98']
copy_to = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

The net result should be:
fixed = [('-0.25', '2.02,1.91', '2.02,1.91'), ('-1.50', '1.9,2.06', '1.86,1.98')]

All I want to do is take 2nd item from each tuple (list copy_to) eg. '2.02,1.91' and  check its location within list copy_from. Once we have localized it, I want to take the next item from list copy_from ('1.9,2.06') and copy it back to the approperiate tuple in list copy_to. BUT, copy_from is sometimes missing the approperiate next item. This is when copy_to' tuple items are neighbours within copy_from. And in the above they are.
When this is the case I must not take the next item, I have to duplicate the item instead (as shown in fixed 1st tuple). If there were no neighbours, like this:
copy_from = ['2.02,1.91', '2, 1.89', '1.9,2.06', '1.86,1.98']
copy_to = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

then the result should be:
fixed = [('-0.25', '2.02,1.91', '2, 1.89'), ('-1.50', '1.9,2.06', '1.86,1.98')]

There will be both - neighbouring and not neighbouring items.
I'm aware the explanation got confusing quite a bit, hope you can understand where I'm coming from. I know, this is a complex task, so any hints like where to look, which library may be useful welcome as well!

A: Your question is pretty confusing, and confused. But I think whatever your actual problem is, your first step should be to create a dict. When your problem is "I need to look up a key and get the corresponding value, or get some default value if it's not present", the answer is usually dict.get.
For example, you could create a dict mapping each member of copy_from to its succeeding member:
copy_from = ['2.02,1.91', '1.9,2.06', '1.86,1.98']
dict_from = dict(zip(copy_from, copy_from[1:]))

Now, to get the next value for any value in copy_from, or the key itself if not present:
value = dict_from.get(value, value)

In particular:
>>> v = '1.9,2.06'
>>> dict_from.get(v, v)
'1.86,1.98'
>>> v = '1.86,1.98'
>>> dict_from.get(v, v)
'1.86,1.98'

I think that's at least on the road to what you want?

A: This is a whole lotta bad... but I think this does what you're looking for... but clean your input instead as per all the comments!
copy_from = ['2.02,1.91', '1.9,2.06', '1.86,1.98']
copy_to = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

fixed = []
for ct in copy_to:
    if ct[1] in copy_from:
        idx = copy_from.index(ct[1])
        if idx < len(copy_from):
            ct += (copy_from[idx+1], )
        else:
            ct += (copy_from[idx], )
    fixed.append(ct)

A: Check this:
>>> result=[]
>>> copy_from_max_idx = len(copy_from) -1
>>> copy_to_max_idx = len(copy_to)-1
>>> for i,e in enumerate(copy_to):
    try:
        idx = copy_from.index(e[1])
    except:
        idx = -1
    if idx >=0:
        #check neighbours (next item actually)
        next_copy_from = e[1] if idx >= copy_from_max_idx else copy_from[idx + 1]
        next_copy_to = '' if i >= copy_to_max_idx else copy_to[i+1][1]
        if next_copy_to == next_copy_from:
            result.append(e + (e[1],))
        else:
            result.append(e + (next_copy_from,))

A: First to destination list is a list of tuples, an tuples are immutable, so I had to do a tricky conversion to a list of lists.
This is what I came up with:
def doStuff(ref, dest):

    tmp = [list(x) for x in dest]
    search_keys  = [l[1] for l in tmp]

    ref_pairs  = [ref[n:n+2] for n in range(0, len(ref), 1) if len(ref[n:n+2]) > 1]
    dest_pairs = [search_keys[n:n+2] for n in range(0, len(search_keys), 1)]

    for index,pair in enumerate(dest_pairs):

        if pair in ref_pairs:
            tmp[index].append(pair[0])
        else:
            candidate_pair = [p for p in ref_pairs if p[0] == pair[0]]

            if candidate_pair:
                tmp[index].append(candidate_pair[0][1])
            else:
                tmp[index].append(None)

    return [tuple(l) for l in tmp]

# Test case 1
copy_from = ['2.02,1.91', '1.9,2.06', '1.86,1.98']
copy_to   = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

copy_to = doStuff(copy_from, copy_to)
print 'Case1:\n', copy_to

# Test case 2
copy_from = ['2.02,1.91', '2, 1.89', '1.9,2.06', '1.86,1.98']
copy_to = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

copy_to = doStuff(copy_from, copy_to)
print 'Case2:\n',  copy_to

# Test case 3
copy_from = ['2.02,1.91', '2, 1.89', '1.9,2.06']
copy_to = [('-0.25', '2.02,1.91'), ('-1.50', '1.9,2.06')]

copy_to = doStuff(copy_from, copy_to)
print 'Case3:\n',  copy_to

Output of the 3 test cases:
Case1:
[('-0.25', '2.02,1.91', '2.02,1.91'), ('-1.50', '1.9,2.06', '1.86,1.98')]
Case2:
[('-0.25', '2.02,1.91', '2, 1.89'), ('-1.50', '1.9,2.06', '1.86,1.98')]
Case3:
[('-0.25', '2.02,1.91', '2, 1.89'), ('-1.50', '1.9,2.06', None)]


text:
Q: jquery/Ajax get value of data-id from a text link I have A VERY OLD SCRIPT that I need to modify. You will notice from the code it is using mysql_query() which is outdataed however that is not my issue.
I have a text link in a file named surveycommentslist.php. The link opens a jquery model window that I need to capture a user inputed text in and then save it to a mysql along with the value of the links data-id which tells me which unique user ID to connect the comment to. My issue is I am not able to get the value of data-id using the code I have below.
Here is my code

    <?php
         //lets list comments
          $scommentsql = mysql_query("SELECT * FROM survey_comments
                       WHERE surveyid=$surveyid  ORDER BY commentdate asc");
          while($scrows = mysql_fetch_array($scommentsql))
            {
                extract($scrows);
                $the_comment = stripslashes($the_comment);
                $commentdate = date("m/d/Y h:ia", strtotime($commentdate));
                if($touid > 0) { $indent = "margin-left:35px"; }

                //get name of person making the comment
                  $nsql = mysql_query("SELECT fname, lname, userlevel, id AS scommentid FROM users WHERE id=$uid LIMIT 1");
                  $namerow = mysql_fetch_array($nsql);
                  $commenters_fname = stripslashes($namerow['fname']);
                  $commenters_lname = stripslashes($namerow['lname']);

                  if($namerow['userlevel'] > 19)
                    {
                       $adminicon = "";
                    }

                 echo "

                               $the_comment

                               $adminicon $commenters_fname $commenters_lname
                               $commentdate";

                               if($touid == 0)
                                 {
                                    echo " REPLY";
                                 }
                    echo "

";
          }

A: $(document).on('click', '.reply', function(e)
    {
      e.preventDefault();
       //get acommentuid
       var val = $(this).data('id');

       $.post('surveycommentslist.php', {acommentuid: val}, function(data)
        {
          console.log(data);
        });
    });

A: Maybe there's just an issue with the single and double quote in the REPLY. You said $scommentid has a value, so I assume there's just an echo problem. Try these:
//codes
.
.

//RE-POSITION class values from id value
echo "REPLY";

//or by concatenation if I am wrong with the above solution
echo "REPLY";

//or by using the " if I am wrong with the above solutions
echo "REPLY";

.
.
//codes

A: Class attribute is not closed properly. Quotes issue.
Change this
echo " REPLY";

to
echo "REPLY";

A: When I copy-paste your code in a file & execute that in a browser, it shows the "data-id" attribute as blank: http://screencast.com/t/pasXI14dp0x . That is due to the incorrect HTML pointed out in earlier messages.
Even after the corrections, there is still the 'btn-small' text which is not in any attribute.
The incorrect HTML is:
echo " REPLY";
The correct HTML should be:
echo " REPLY";
Another alternative you could try is hardcode some value in the "data-id" attribute & find out if it's being passed. If that works, then the issue is with the HTML & should be fixed with above corrected HTML code.

A: Your HTML markup is wrong

You can check that by doing a view source

Change the following code
echo " REPLY";

with
echo "REPLY";

A: I would suggest to you to return the data from MySQL as JSON using return json_encode($data) which $data is an array of key-value pairs and when you get the data in your script tag / JavaScript, just build the HTML there and add it to a div instead of returning HTML from the server.
When you build your HTML in your script tag / JavaScript, you add the data from the JSON response and loop over the comments.
Maybe that's just me but I like clean code :)


text:
Q: "'Applying'/'If we apply'/'Given' those principles"
Applying those principles here, it is clear that the sections in question are unambiguous in their application and ...
www.nycourts.gov/courts/.../knight.pdf

What is the sense of the above sentence, 1 or 2?

*

*If we apply those principles here, it becomes clear that ...

*Given those principles, the sections in question ...
Also, if "1" is the correct interpretation, can we replace "Applying" with "The application of"—i.e., "The application of those principles here makes clear that ..."?

A: Although there is little meaningful difference in effect (between the choices), the first is a truer echo of the original because it too expresses an action  – the application or act of applying principles  – unlike the second choice, which takes them as in place and not in need of application.  Either might work, depending on context and purpose.


text:
Q: Guice - How to bind a type determined in a program runtime? SHORT ANSWER: to bind to Object instance bind() method should be provided with Class<Object> parameter.
That said:
Class<?> type = got_a_type(); Object object = got_an_object();
// Illegal - compilation error because of type check comparing ? to Object
bind(type).toInstance(object);
// Legal and working
bind((Class<Object>)type).toInstance(object);

LONG STORY:
I'm having json configuration files from old system in the following format:
{
    "$type": "test_config.DummyParams",
    "$object": {
        "stringParam": "This is a string",
        "integerParam": 1234,
        "booleanParam": false
    }
}

The test_config.DummyParams is the class available during program runtime and looking like this:
package test_config;

public class DummyParams {
    public String stringParam;
    public int integerParam;
    public boolean booleanParam;
}

There's some class which I want to be created by guice which is having constructor parameter (need to be injected) of DummyParams type:
@Inject
public class DummyService(DummyParams params) { ... }

Now, since DummyParams class is something provided only in runtime (through json config file) and can't be known at the time of compilation I can't use this type in guice bindings:
// Can't do this because DummyParams type should come from config file
Object object = ...; // Getting object somehow
bind(DummyParams.class).toInstance((DummyParams)object);

I have some old code which gives me pairs of Class and Object (type and instance) read from all json config files:
class ConfigObject {
    Class<?> type;
    Object instance;
}

I have tried simply to bind them:
ConfigObject obj = config.read(); // Getting pairs from config files walker
bind(obj.type).toInstance(obj.instance);

But this isn't compilable: "java: toInstance(capture#189 of ?) in com.google.inject.binder.LinkedBindingBuilder cannot be applied to (java.lang.Object)".
So here's a question: how to bind the instance of a type which is determined in the runtime? Am I breaking IoC concepts and shouln'd be doing what I'm trying to do?

A: I think you can safely use typecasts here. Here is a complete example:
public class Main {
    public static void main(String[] args) {
        final Holder holder = new Holder("abcd", String.class);

        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind((Class<Object>) holder.type).toInstance(holder.instance);
            }
        });

        System.out.println(injector.getInstance(String.class));  // Prints "abcd"
    }

    public static class Holder {
        public final Class<?> type;
        public final Object instance;

        public Holder(Object instance, Class<?> type) {
            this.instance = instance;
            this.type = type;
        }
    }
}

Or you can move the problem to the upper level and change your config object to contain Class<Object>; then you will have to cast the class in your config reader:
public class Main {
    public static void main(String[] args) {
        final Holder holder = new Holder("abcd", (Class<Object>) (Class<?>) String.class);

        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(holder.type).toInstance(holder.instance);
            }
        });

        System.out.println(injector.getInstance(String.class));
    }

    public static class Holder {
        public final Class<Object> type;
        public final Object instance;

        public Holder(Object instance, Class<Object> type) {
            this.instance = instance;
            this.type = type;
        }
    }
}

This will require casting through a wildcard type or something like this, though.
However, the whole situation is really strange. If your configuration classes do not have common supertype, how they will be used at all? If you do not know in advance which class your object belongs to, you cannot (almost) use it without reflection or instanceofs.

A: Using and abusing of raw types, implicit unchecked casts and some guava libraries:
public class RuntimeParams {
  public static void main(String[] args) throws ClassNotFoundException, IOException {

    // reads from config and bind in runtime
    final ConfigReader config = new ConfigReader();
    final ConfigObject configObject = config.read();
    final Injector injector = Guice.createInjector(new AbstractModule() {
      @Override protected void configure() {
        bind(configObject.type).toInstance(configObject.instance);
      }
    });

    // use the binded instance
    final DummyParams instance = injector.getInstance(DummyParams.class);
    System.out.println("DummyParams' stringParam: " + instance.stringParam + "\nDummyParams' integerParam: "
        + instance.integerParam + "\nDummyParams' booleanParam: " + instance.booleanParam);
  }
}

class ConfigObject<T> {
  private static final Gson gson = new Gson();

  final T instance;
  final Class<T> type;

  ConfigObject(final String json, final Class<T> type) {
    this.instance = gson.fromJson(json, type);
    this.type = type;
  }
}

class ConfigReader {
  private static final Gson gson = new Gson();

  ConfigObject read() throws ClassNotFoundException, IOException {
    try (final FileReader reader = new FileReader(new File("src/main/resources/runtimeClazzNParams.json"));) {
      final Map<String, Object> configMap = gson.fromJson(reader, Types.mapOf(String.class, Object.class));
      final Class<?> clazz = Class.forName((String) configMap.get("$type"));
      return new ConfigObject<>(gson.toJson(configMap.get("$object")), clazz);
    }
  }
}

It is similar to Vladimir's solution, but with the casts implicit and raw types instead of direct Object references.
I also wrote a new way of parsing the JSON using the Gson guava class methods.


text:
Q: Five months ago, I {decided/have decided} to learn how to play the piano
Five months ago, I {decided/have decided} to learn how to play the
piano.

Is "Five months ago" a definite time?
I have read that when there is a definite time, I should use the simple past tense. For example:

I ate my dinner two hours ago.

When there is no definite time, I should use the present perfect tense. For example:

I haven't seen my best friend for a long time.

A: Well, if you accept the definition the dictionaries give of AGO, like for example Merriam-Webster:

earlier than the present time (that is, earlier than NOW, the time of speech),

then your expression of time five months ago is very definite.
So your sentence should be:

Five months ago (which is in August 2020), I decided to learn (how) to play the piano. (Gngram prefers learn to play the piano rather than learn how to play the piano.)