text:
Q: AngularJS Multiselect checkbox dropdown Issue I have a pop-up with multi-select drop down.
Multi-Select Dropdown Code
<select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple=""
   required ng-model="article_selected" ng-options="article_service as article_service.name for article_service in article_services">
</select>

There is an array article_services which is used in multi-select, I am fetching this array from below code.
$http.get(url + 'service_provided').
     then(function (response) {
         $scope.article_services = response.data.service_provided;
         //$scope.article_selected = [$scope.article_services[0], $scope.article_services[1]];
});

Now I want that when I click on Edit Button with ng-click="advisor_article_edit()" to open pop-up, my multi-select checkbox comes with some selection.
I want that Select must be work in below function but unfortunately it doesn't work.
$scope.advisor_article_edit = function () {
        // I need selection work from here. But it doesn't.
        $scope.article_selected = [$scope.article_services[3]];
 }

A: I believe you need to trigger the click:
var cb = angular.element('some-selector');
cb.triggerHandler('click');

This should be done in a directive as it's dom manipulation

A: It should work, like in the snippet.:-

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.cars = [{id:1, name: 'Audi'}, {id:2, name: 'BMW'}, {id:1, name: 'Honda'}];
  $scope.advisor_article_edit = function () {
        $scope.article_selected = [$scope.cars[1]];
  }
});
<!DOCTYPE html>

<select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple=""
   required ng-model="article_selected" ng-options="car as car.name for car in cars">
</select>

<button ng-click="advisor_article_edit()">Edit</button>

Selected : {{article_selected}}

Working Plunkar Link


text:
Q: SSHJ and the Maven shade plugin Testing SSHJ in Eclipse and everything looks good. But When I use the Maven shade plugin to package SSHJ I get the following error:
Exception in thread "main" net.schmizz.sshj.userauth.UserAuthException: Exhausted available authentication methods
at net.schmizz.sshj.SSHClient.auth(SSHClient.java:217)
at net.schmizz.sshj.SSHClient.authPublickey(SSHClient.java:316)
at net.schmizz.sshj.SSHClient.authPublickey(SSHClient.java:365)
at net.schmizz.sshj.SSHClient.authPublickey(SSHClient.java:295)
at no.f12.SshRepository.executeTaskOnHost(SshRepository.java:23)
at no.f12.SshService.serviceCommand(SshService.java:22)
at no.f12.App.main(App.java:29)

Adding
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

changes the error message to:
Exception in thread "main" net.schmizz.sshj.transport.TransportException: Unable to reach a settlement: [] and [aes128-ctr, aes192-ctr, aes256-ctr, arcfour256, arcfour128, aes128-gcm@openssh.com, aes256-gcm@openssh.com, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour, rijndael-cbc@lysator.liu.se]
at net.schmizz.sshj.transport.Proposal.firstMatch(Proposal.java:165)
at net.schmizz.sshj.transport.Proposal.negotiate(Proposal.java:147)
at net.schmizz.sshj.transport.KeyExchanger.gotKexInit(KeyExchanger.java:239)
at net.schmizz.sshj.transport.KeyExchanger.handle(KeyExchanger.java:364)
at net.schmizz.sshj.transport.TransportImpl.handle(TransportImpl.java:478)
at net.schmizz.sshj.transport.Decoder.decode(Decoder.java:127)
at net.schmizz.sshj.transport.Decoder.received(Decoder.java:195)
at net.schmizz.sshj.transport.Reader.run(Reader.java:72)

Any idea how to get around this?
A bit of background to why I want to use shade... I am trying to get to a point where usage of Java and distribution of small utils is dead simple. So I create a really executable jar using this: https://github.com/brianm/really-executable-jars-maven-plugin . That enables me to create one, executable file to distribute and add to the path of the user. A bit like how Go has one binary file with all dependencies.

A: I had this exact problem. I finally gave up on trying to put everything in a big "uberjar".
Instead I assembled all the jars using maven-assembly-plugin, and then extract and add them to the classpath in order to execute, e.g. 'java -cp all-needed-libs/* com.company.MainClass'.

A: Another approach that might work is to add bouncycastle to the JRE extension library.
E.g put 'bcprov-jdk15on-1.49.jar' in folder '$JAVA_HOME/jre/lib/ext/' on the host.

A: You have to sign jar, it's required by Javax.security. I got similar problem and there's stacktrace from my test:
Cannot init Cipher factory: blowfish-cbc
java.lang.SecurityException: JCE cannot authenticate the provider BC
    at javax.crypto.Cipher.getInstance(Cipher.java:642)
    at javax.crypto.Cipher.getInstance(Cipher.java:580)
    at net.schmizz.sshj.common.SecurityUtils.getCipher(SecurityUtils.java:96)
    at net.schmizz.sshj.transport.cipher.BaseCipher.init(BaseCipher.java:88)
    ....
Caused by: java.util.jar.JarException: file:/test-jar-with-dependencies.jar has unsigned entries - library.properties
    at javax.crypto.JarVerifier.verifySingleJar(JarVerifier.java:462)
    at javax.crypto.JarVerifier.verifyJars(JarVerifier.java:322)
    at javax.crypto.JarVerifier.verify(JarVerifier.java:250)
    at javax.crypto.JceSecurity.verifyProviderJar(JceSecurity.java:161)
    at javax.crypto.JceSecurity.getVerificationResult(JceSecurity.java:187)
    at javax.crypto.Cipher.getInstance(Cipher.java:638)
    at javax.crypto.Cipher.getInstance(Cipher.java:580)
    at net.schmizz.sshj.common.SecurityUtils.getCipher(SecurityUtils.java:96)
    at net.schmizz.sshj.transport.cipher.BaseCipher.init(BaseCipher.java:88)
    at net.schmizz.sshj.DefaultConfig.initCipherFactories(DefaultConfig.java:152)
    at net.schmizz.sshj.DefaultConfig.<init>(DefaultConfig.java:107)

redpajama_set_name: RedPajamaStackExchange


text:
Q: launchOptions are nil after using custom actions on Push Notification I'm using push notifications with custom actions on my iOS app.
It all works well when the app is in foreground/background, with my code inside - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler being called as expected.
However, if the app is not running, clicking on one of the custom actions will make the app open, but the call to - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions is being done with launchOptions set as nil.
If I click the notification itself, instead of one of the actions, it works as expected as well!
Any idea what is going on here?


text:
Q: 'java.util.Iterator java.util.List.iterator()' on a null object reference when code run into (IConnectivityManager$Stub$Proxy.getActiveNetworkInfo) java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
    at android.os.Parcel.readException(Parcel.java:1552)
    at android.os.Parcel.readException(Parcel.java:1499)
    at android.net.IConnectivityManager$Stub$Proxy.getActiveNetworkInfo(IConnectivityManager.java:1058)
    at android.net.ConnectivityManager.getActiveNetworkInfo(ConnectivityManager.java:658)
    at com.inmobi.commons.core.utilities.b.b.b(DeviceInfo.java:50)
    at com.inmobi.commons.core.utilities.b.b.a(DeviceInfo.java:115)
    at com.inmobi.ads.i.c(AdUnit.java:50471)
    at com.inmobi.ads.i.b(AdUnit.java:1835)
    at com.inmobi.ads.i.a(AdUnit.java:869)
    at com.inmobi.ads.ac.a(InterstitialAdUnit.java:566)
    at com.inmobi.ads.i$8.run(AdUnit.java:1631)
    at android.os.Handler.handleCallback(Handler.java:815)
    at android.os.Handler.dispatchMessage(Handler.java:104)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5637)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

A: @Alex You must be calling iterator() method on a null List, to avoid this you can have a
list != null check and do your work inside it and handle the else condition with some smooth flow of printing error log or a toast.


text:
Q: How to return the value of a reference field of a struct that is no longer used without copy? Code like this:
pub fn sample_from_categorical_logits(prob_logits: Tensor) -> (Tensor, Tensor) {
    let prob_obj = match prob_logits.size().len() {
        3 => Categorical::from_logits(prob_logits),
        2 => Categorical::from_logits(prob_logits.unsqueeze(1)),
        _ => panic!("illegal..."),
    };
    (prob_obj.sample(&[]), (*prob_obj.probs()).copy())//TODO: can copy be avoided?
}

I can get an immutable reference on a field of object prob_obj through prob_obj.prob(). Now I need to return the value of it, because I need to read(only) this value for some calculation, and return this value and calculated value further.
Tensor is a 3rd struct doesn't implement Copy trait.
I know I can't return a reference of a local object.  But in this case, since I no longer need the whole prob_obj object, I wonder if there is a more efficient way other than copying the field, like move in C++.
I googled, found something like Cow, Mem::take, and UnSafe, but they seem to be not the use case here.

A:
I wonder if there is a more efficient way other than copying the field, like move in C++.

Well yes, moving. But moving requires having ownership of the object, meaning you need a version of probs() which consumes the object in order to return its bits.
Or one which returns a mutable reference in order to use mem::take or mem::swap.
Like you would in C++, really, it's not like you can just move stuff out of a const reference (at best that's going to perform a copy).


text:
Q: How to initialize an array of structs in MATLAB? How can I preallocate an array of structs in MATLAB? I want to preallocate "a" in this example so that it does not resize several times.
a = []
for i = 1:100
  a(i).x = i;
end

A: Using repmat is by far the most efficient way to preallocate structs :
N = 10000;
b = repmat(struct('x',1), N, 1 );

This is ~10x faster using Matlab 2011a than preallocating via indexing, as in
N      = 10000;
b(N).x = 1

The indexing method is only marginally faster than not preallocating.
No preallocation:            0.075524
Preallocate Using indexing:  0.063774
Preallocate with repmat:     0.005234

Code below in case you want to verify.
        clear;
        N = 10000;

    %1) GROWING A STRUCT
        tic;
        for ii=1:N
            a(ii).x(1)=1;
        end
        noPreAll = toc;

    %2)PREALLOCATING A STRUCT
        tic;
        b = repmat( struct( 'x', 1 ), N, 1 );
        for ii=1:N
            b(ii).x(1)=1;
        end;
        repmatBased=toc;

    %3)Index to preallocate
        tic;
        c(N).x = 1;
        for ii=1:N
            c(ii).x(1)=1;
        end;
        preIndex=toc;

        disp(['No preallocation:        ' num2str(noPreAll)])
        disp(['Preallocate Indexing:    ' num2str(preIndex)])
        disp(['Preallocate with repmat: ' num2str(repmatBased)])

Results in command window:
No preallocation:        0.075524
Preallocate Indexing:    0.063774
Preallocate with repmat: 0.0052338
>>

P.S.  I'd be interested to know why this is true, if anyone can explain it.

A: The way this is supposed to be done, and the simplest is
a=struct('x',cell(1,N));

If you fix the missing "tic" and add this method to the benchmarking code presented by jerad, the method I propose above is a bit slower than repmat but much simpler to implement, here is the output:
No preallocation:        0.10137
Preallocate Indexing:    0.07615
Preallocate with repmat: 0.01458
Preallocate with struct: 0.07588

The reason that repmat is faster is because a value to each 'x' field is assigned during the pre-allocation, instead of leaving it empty. If the above pre-allocation technique is changed so we start with all the x fields with a value (one) assigned, like this:
    a=cell(1,N);
    a(:)={1};
    d=struct('x',a);

Then, the benchmarking improves a lot, been very close or some time faster than repmat. The difference is so small that every time I run it it changes which one is faster. Here an output example:
No preallocation:        0.0962
Preallocate Indexing:    0.0745
Preallocate with repmat: 0.0259
Preallocate with struct: 0.0184

Conversely, if the repmat pre-allocation is changed to set the field empty, like this
b = repmat( struct( 'x', {} ), N, 1 );

All the speed advantage is lost

A: There's a nice discussion about this in Loren on the Art of MATLAB blog.
If I understand you correctly, here's a ways to initialize the struct you want:
a(100).x = 100;

With this method, we can see that elements are filled in with empty arrays.

A: There's a bunch of ways you can initialize a structure. For example, you can use the struct command:
a(1:100) = struct('x',[]);

which sets all fields x to empty.
You can also use deal to create and fill the structure if you know what data should go in there
xx = num2cell(1:100);
[a(1:100).x]=deal(xx{:});
a(99).x
ans =
    99

Or you can use struct again (note that if a field of the structure should be a cell array, the cell needs to be enclosed in curly brackets!)
a = struct('x',xx)

A: using cell2struct is by far the fastest method I could figure out. Just check the following code to make a comparison:
clear;
N = 10000;

cel2s=0;
repm=0;

for i=1:100
a=0.0; b=0.0;

tic;
a = cell2struct(cell(1,N), {'x'}, 1 );
cel2s = cel2s + toc;

tic;
b = repmat(struct('x',1), N, 1 );
repm = repm + toc;
end

disp(['cell2struct preallocation: ', num2str(cel2s/100)]);
disp(['repmat preallocation     : ', num2str(repm/100)]);
disp(['speedup                  : ', num2str(fix( repm/cel2s ) ) , ' X']);

Typical results show a mean speedup around 19 times! wrt repmat method:
cell2struct preallocation: 1.4636e-05
repmat preallocation     : 0.00028794
speedup                  : 19 X

A: According to this answer, there's also another way to do it:
[a.x] = deal(val);

where val is the value you want to assign to every element of the struct.
The effect of this command is different from those of the others, as every x field of every structure a will be assigned the val value.

A: Instead of pre-allocating the array of structs it may be easier to reverse the loop. In this way the array is allocated in the first iteration and the rest of the iterations are used to fill the structs.
a = []
for i = 100:-1:1
    a(i).x = i;
end


text:
Q: Android wear notification I want to create a notification, with list of options, but list has to be pretty long, lets say numbers from 1 to 60. I want to have a list like in a timer app, so I was thinking do I have to create a separate wear app for that, or is it possible to display that sort of notification from device only? Thank you

A: This is covered under voice replies with predefined text responses.
Voice Replies wearable documentation
you can ignore the idea that is a voice reply.
this is the easiest option for using only the notifications without building an app specific for it.


text:
Q: How can I read a text file with binary values, where each row is a binary vector itself using Numpy? The idea is that the text file has 150 rows where each row is a string of 1024 bits (a representation of a 32x32 image).
What i want to achieve is to have an array of 150 elements where every element is an array of size 1024.
By trying the code below i get an array of 150 elements with inf value.
Is there a way to convert those values to vectors using numpy's loadtxt directly.
Thank you in advance!
import numpy as np

data = np.loadtxt("digits.txt")

A: If each line is exactly the same length and contains only the characters 0 and 1, you can use numpy.genfromtxt, with delimiter=1.  When the argument delimiter is a single integer, genfromtxt treats each line as a sequence of fixed-width fields.  The value given to delimiter specifies the field width.
For example, suppose the file 01.txt contains
0001
1010
1111
0000
1001

Here's how you can use genfromtxt to read that into a NumPy integer array with shape (5, 4):
In [2]: import numpy as np

In [3]: data = np.genfromtxt('01.txt', delimiter=1, dtype=np.int8)

In [4]: data
Out[4]:
array([[0, 0, 0, 1],
       [1, 0, 1, 0],
       [1, 1, 1, 1],
       [0, 0, 0, 0],
       [1, 0, 0, 1]], dtype=int8)

A: supposed your text file contains 128 characters in each line (excluding newline character), each character representing 1 byte / 8 bits, you could use
data = np.loadtxt(file, dtype=np.str)
bits_arr = []
for line in data:
    byte_arr = np.frombuffer(line.encode('UTF-8'), dtype=np.uint8) # UTF-8 assumed
    bits_arr.append(np.unpackbits(byte_arr).reshape(32,32))

bits_arr will then contain 1 "32x32 bitmap" for each line. Note that reshape(32,32) will fail if an invalid number of bytes (!=128) is read in a line.
Sidenote: it is probably more efficient here to use a simple readlines() instead of carrying around all the overhead of np.loadtxt since you actually don't use what this function can do for you. The code could therefore be simplified to
bits_arr = []
with open(file, 'rb') as binfile:
    line = binfile.readline().strip() # strip to remove newline char
    byte_arr = np.frombuffer(line, dtype=np.uint8)
    bits_arr.append(np.unpackbits(byte_arr).reshape(32,32))


text:
Q: keeping track of injected variables when using string interpolation in kotlin I'm looking for a way to keep track of variables used when doing a string interpolation without parsing the string. For example, if I have a string:
val expStr = "${var1} some other useless text ${var2}"

I want to be able to identify the order of the variables used, again without parsing the string. In this case [var1, var2] would be an expected output. So far I've thought of defining a class where I pass it all of the variables. Then reference said variables through the class function grab.
val wrapper = ContainerClass(var1, var2)
val expStr = "${wrapper.grab(var1)} some other useless text ${wrapper.grab(var2)}"

inside ContainerClass is a array, each time a variable is referenced it is added to the array and outputted through getReferenceCalls
val whatIWant = wrapper.getReferenceCalls() // [var1, var2]

This works great until I introduce the injection of strings into strings.
val wrapper = ContainerClass(var1, var2, var3)
val snippet = "${wrapper.grab(var1)} some other useless text ${wrapper.grab(var2)}"
val expStr = "${wrapper.grab(var3)} ${snippet}"

val notWhatIWant = wrapper.getReferenceCalls() // [var1, var2, var3]

Here, I want to identify the order of the injected variables in the final expStr ie. [var3, var1, var2]. My question is, is this possible without parsing expStr? I did also think of a not so elegant solution of allowing my class to define any given "snippet" and the class identifies the variables referenced in the snippet. This works but becomes convoluted fast. What I really need is an eligant solution...if it exists.

A: I have implemented a "ContainerClass" to achieve your goal. I uses String.format instead of string templates so that I don't need prior information of the input.
class StringNode(private val format: String, vararg args : Any) {
    private val argv = args

    override fun toString() : String = String.format(format,*argv)

    fun getFlatArgs() : List<Any> = argv.flatMap {
        if(it is StringNode){
            it.getFlatArgs()
        } else{
            listOf(it)
        }
    }
}

Usage:
fun main(){
        val sn1 = StringNode("1:%s 2:%s 3:%s","abc",123,"def")
        println(sn1)
        println(sn1.getFlatArgs())

        val sn2 = StringNode("foo:%s bar:%s","foo",sn1);
        println(sn2)
        println(sn2.getFlatArgs())

        val sn3 = StringNode("sn1:%s, sn2:%s",sn1,sn2);
        println(sn3)
        println(sn3.getFlatArgs())
}

Output:
1:abc 2:123 3:def
[abc, 123, def]
foo:foo bar:1:abc 2:123 3:def
[foo, abc, 123, def]
sn1:1:abc 2:123 3:def, sn2:foo:foo bar:1:abc 2:123 3:def
[abc, 123, def, foo, abc, 123, def]

A: val var1 = "abc"
val var2 = "def"

val list = mutableListOf<String>()

val expStr = "${var1.also { list.add(it) }} some other useless text ${var2.also { list.add(it) }}"

println(expStr)   // Output: "abc some other useless text def"
println(list)     // Output: [abc, def]

Or:
val var1 = "abc"
val var2 = "def"

val list = mutableListOf<String>()
fun String.addTo(list: MutableList<String>) = this.also { list.add(it) }

val expStr = "${var1.addTo(list)} some other useless text ${var2.addTo(list)}"

println(expStr)   // Output: "abc some other useless text def"
println(list)     // Output: [abc, def]


text:
Q: Add fragment to abstract activity I'm trying to add a fragment to an abstract activity. This is a base activity and all other activities in my app extend from it.
My problem: when I add the fragment to base activity it gives me the following error.
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f09011d (com.musicplayer.musicana:id/nowPlayingScreensContainer) for fragment SlidingUpPanelFragment{961e486 #0 id=0x7f09011d}

I'm pretty sure I'm using the framelayout's id present in base activity while adding the fragment.
XML of baseActivity:
<com.sothree.slidinguppanel.SlidingUpPanelLayout

    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoPanelHeight="70dp"
    sothree:umanoShadowHeight="10dp"
    android:background="#000"
    sothree:umanoFadeColor="#b2000000"
    >

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        />

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/nowPlayingScreensContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</com.sothree.slidinguppanel.SlidingUpPanelLayout>

There are two framelayouts in this, first one for adding activities and second for adding fragments.
Code for adding fragments(written in onCreate):
 SlidingUpPanelFragment fragment = SlidingUpPanelFragment.newInstance();
         FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.nowPlayingScreensContainer, fragment);
    fragmentTransaction.commit();

Full log:
Failed to capture application
06-21 14:54:22.002 2601-2601/com.musicplayer.musicana E/FragmentManager: No view found for id 0x7f09011d (com.musicplayer.musicana:id/nowPlayingScreensContainer) for fragment SlidingUpPanelFragment{961e486 #0 id=0x7f09011d}
    Activity state:
06-21 14:54:22.014 2601-2601/com.musicplayer.musicana E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.musicplayer.musicana, PID: 2601
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.musicplayer.musicana/com.musicplayer.musicana.splash}: java.lang.IllegalArgumentException: No view found for id 0x7f09011d (com.musicplayer.musicana:id/nowPlayingScreensContainer) for fragment SlidingUpPanelFragment{961e486 #0 id=0x7f09011d}
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2699)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6236)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
     Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f09011d (com.musicplayer.musicana:id/nowPlayingScreensContainer) for fragment SlidingUpPanelFragment{961e486 #0 id=0x7f09011d}
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1422)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)
        at android.app.Activity.performStart(Activity.java:6701)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2662)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6236)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)

OnCreate of base activity:
 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_activity);

        slidingUpPanelLayout = findViewById(R.id.sliding_layout);
        slidingUpPanelLayout.addPanelSlideListener(this);
        storageUtil = new StorageUtil(getApplicationContext());

        pref = getSharedPreferences(TAG,MODE_PRIVATE);
        registerSelectScreenReceiver();

         SlidingUpPanelFragment fragment = SlidingUpPanelFragment.newInstance();
         FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.nowPlayingScreensContainer, fragment);
    fragmentTransaction.commit();

        }

Will be glad to provide more codes. How to solve this?


text:
Q: Link to a page with modal opened already I have a web page with a gallery of products, and each product opens a modal with it's specific information. Each product modal has a unique id; however, when the modal is opened there is no change in the URL. Therefore, I have no way of linking someone to a specific opened product modal, only the page with the entire gallery.
I have looked into modifying the url to include the id, as well as attempting to create hyperlinks with onClick events that would trigger the opening of the modal upon clicking link. I am not sure if either method is possible.
Here is an example of my modal code:

Modal 1

Modal 2

CT8002
×

FF310
×

A: Use different UNIQUE Model ID for different products!
For example:
Model Call

Model Data

 Data A
×

 Data B
×

 Data C
×

In the example above, There are three different IDs. 1a, 2b and 3c because it will load data with respect to ID defined to it and to that data.
I hope this helps you!


text:
Q: Thymeleaf inserting new item in database generates error Property or field cannot be found on null I'm in the process of learning spring. I'm using thymeleaf to create a simple web app that adds, edits and removes users from a database.
I'm using an html page to display the database and two separate pages for editing and adding new users.
Edit and remove work perfectly but whenever i try to add a user i get an error in new.html (new.html contains the form to add a new user)
Property or field xxxx cannot be found on null

The error shows up in the from at th:text="@{user.name}" .From what I've found online thymelaf does not take null values, however as this is a new object I am trying to add all values are null.
Is there any way to solve this. Code.
new.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>New User</title>

<form method="post" name="comment_form" id="comment_form" th:action="@{/create}" role="form">
    Name:

    <input type="text" name="name" th:text="${user.name}">

    Age:

    <input type="text" name="age" th:text="${user.age}">

    Email:

    <input type="text" name="email" th:text="${user.email}">

    <button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>

Controller
    @Autowired
UserService service;
    @RequestMapping(value="user/new", method = RequestMethod.GET)
public String newUser(Long id, Model md) {
    Users user = service.findOne(id);
    md.addAttribute("user", user);
    return "new";
}

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@RequestParam("id") Long id, @RequestParam("name") String name, @RequestParam("age") int age,
                     @RequestParam("email") String email, Model md) {
    md.addAttribute("users", service.addOrUpdate(new Users(id, name, age)));
    return "redirect:/user";
}

Service class
@Autowired
JdbcTemplate template;
public Users findOne(Long id)
{
    String sql = "select * from people where id=" +id;
    return template.query(sql, new ResultSetExtractor<Users>() {
        @Override
        public Users extractData(ResultSet resultSet) throws SQLException, DataAccessException {
            if (resultSet.next()) {
                Users user = new Users(resultSet.getLong("id"),
                        resultSet.getString("name"),
                        resultSet.getInt("age"));
                String email = resultSet.getString("email");
                if (email != null) {
                    user.setEmail(email);
                }
                return user;
            }
            return null;
        }
    });

}

public int addOrUpdate(Users user){
        if (user.getId() > 0) {
            String sql = "UPDATE people SET name=?, age =?, email=? WHERE id=" +user.getId();
            System.out.println(sql);
            return template.update(sql, user.getName(), user.getAge(), user.getEmail());

        } else {
            String sql = "INSERT INTO people ( name, age, email) VALUES ( ?, ?, ?)";
            System.out.println(sql);
            return template.update(sql, user.getName(), user.getAge(), user.getEmail());

        }
}

Users (Model)
package ro.database.jdbcTest.model;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Users {

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
private String name;
private int age;
private String email;

public Long getId() {
    return id;
}

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

public String getEmail() {
    return email;
}

public void setId(Long id) {
    this.id = id;
}

public void setName(String name) {
    this.name = name;
}

public void setAge(int age) {
    this.age = age;
}

public Users(Long id, String name, int age){
    this.id=id;
    this.name=name;
    this.age=age;
}

public void setEmail(String email){
    this.email=email;
}
}

A: Since your user object is null you are getting that error.
All you need to do is send a new User() object every time a request with a new user comes.
@RequestMapping(value="user/new", method = RequestMethod.GET)
public String newUser(Long id, Model md) {
    Users user = null;
    if(id > 0) { // Id is present, fetch from the database.
        user = service.findOne(id);
    } else { // Create a new user.
        user = new User();
    }
    md.addAttribute("user", user);
    return "new";
}

Using the above way you will never have a null user in new.html


text:
Q: Declare and use variable in JSF2 xhtml page I am using <s:set var="buttonText" value="getText('person.button.add')"/> in JSTL to use buttonText variable to set text.
Someone tell me how to accomplish this in JSF EL please?
Question asked here IF-ELSE condition in JSF form. Need to know right approach but told to ask as a separate question.
EDITED:
I already added a link above for detail but here is again.
I am using JSTL like in struts2 project
 <s:if test="person==null || person.id==null || person.id==''">
                <s:set var="buttonText" value="getText('person.button.add')"/>
            </s:if>
            <s:else>
                <s:set var="buttonText" value="getText('person.button.edit')"/>
            </s:else>

I want to use same approach in JSF2 but with Expression Language. I am saving value in a variable called buttonText and accessing it below somewhere like #{buttonText}. I need solution to how to write variable in EL and use it. Hope its clear.
I need solution to <s:set var="buttonText" value="getText('person.button.add')"/> line of code only.
Thanks

A: You can use ui:param
In the following ways:
<ui:param name="buttonText" value="#{myBean.MyValue}" />

or
<ui:param name="buttonText" value="someText" />

or
<ui:param name="buttonText" value="someText#{myBean.MyValue}" />

and use later on like this
<h:outputText value="#{buttonText}"/>

Another option would be using <c:set in the following way
<c:set var="buttonText" value="#{myBean.MyValue}" />

But note that <c:set is a JSTL tag,

JSTL tags runs during building the view (when the XHTML file is converted to
  JSF component tree)

Also you might want to read this JSTL in JSF2 Facelets… makes sense?


text:
Q: Upgrade from 20.04 LTS to 22.04 ends in Terminal screen - What do I do now? Have tried to upgrade my HP Z620 Workstation from 20.04 LTS to 22.04. Upgrade appeared to run normally but on reboot it ends in a Terminal screen.
Display reads thus:
   [   0.563747] ipmi:dmi: Base address is zero, assuming no IPMI interface
   [   0.940276] ata_piix 0000:00:1f.2: can't enable device: BAR 1 [io size 0x0001] not    assigned
   [   2.433384] pata_acpi 0000:00:1f.2: can't enable device: BAR 1 [io size 0x0001] not assigned
   Gave up waiting for root file system device. Common problems: - Boot args (cat /proc/cmdline)
      - Check rootdelay= (did the system wait long enough?)
      - Missing modules (cat /proc/modules; ls /dev)
   ALERT! UUID=7e6575b2-8e89-4e7f-abb4-3c78412721f1 does not exist. Dropping to a shell!

   BusyBox v1.30.1 (Ubuntu 1:1.30.1-7ubunti3) built-in shell (ash)
   Enter 'help' for a list of built-in commands.

   (initramfs)_

I'm sorry but it's all gobbledegook to me! Can anyone out there help please?


text:
Q: Image-text change color when hover an image I have an image and some text. What I want is when hover the image, the image will have opacity and the color of the text change. My problem is when the image has opacity, the text also have opacity so it seem I can't see the text. How can I solve that problem? Note: I use image instead of background-image in this case because of some problem, so just help me solve this with image. Thanks a lots!
This picture is exactly what I want:
Here is my code

.categories {
  height: 450px;
  position: relative;
  width: 256px;
  cursor: pointer;
  color: white;
}

.categories:hover {
  opacity: 35%;
  color: black;
}

.categories__text {
  font-size: 2.5rem;
  position: absolute;
  bottom: 1%;
  left: 20%;
  width: 50%;
  line-height: 50px;
}

HERE IS THE TEXT

A: You have to separate the image and text styles:

.categories {
  height: 450px;
  position: relative;
  width: 256px;
  cursor: pointer;
  color: white;
}

.categories:hover {
  color: black;
}

.categories:hover img {
  opacity: 35%;
}

.categories__text {
  font-size: 2.5rem;
  position: absolute;
  bottom: 1%;
  left: 20%;
  width: 50%;
  line-height: 50px;
}

HERE IS THE TEXT


text:
Q: Listen remote database changes How do I make my server to notify client about something? For example a change in database ? I already know about FCM. But what if I don't want to use it ? How do I code that networking logic myself?
I currently don't need it. But i am very curious about how that push system works

A: In case you want to push your data from the server to your Android clients and don't want to use FCM:
You could always use web sockets, which can be a pain to implement manually on both Android and the server. For this the app should either be in the foreground or you could use a Service. We started with this library for Android: https://github.com/koush/AndroidAsync
Now, we use Pubnub for our projects, which builds on top of web sockets and gives you a way easier way to handle those. You would still need to have the receiving part in foreground or a Service. But it also gives you the possibility to use FCM (or Apples Push Service) as a fallback, which is the easiest way to receive pushed data in the background.
It starts out free but then will cost you when your usage goes up. You can take a look here: https://www.pubnub.com/

A: PubNub for Realtime Messaging
You should read this article on how to publish a message via a database trigger.
For details, see How PubNub Works here.
But to summarize for you, you simply have your clients subscribe to a channel(s) and your server publishes messages to those channels. You decide on channel names and what data to publish on them and when to publish the data.
PubNub takes care of delivering those messages to the subscribers of those channels in less 1/4 second.
You can subscribe from any platform:

*

*Android

*iOS

*JavaScript/Web
That's just three of over 70 platforms that you can choose from. Free account allows up to 100 daily active devices (forever) so that you can play before you pay, if you decide to scale your app to the masses.


text:
Q: Is there any point of using CDI @Named CDI without any value? Is there any point of using CDI @Named without a value? Isn't it then simply equivalent of using @Qualifier and @Default together?
@Named
public class GifFileEditor implements ImageFileEditor {

A: If I remember right, @Named with no value element value, when applied to a managed bean, does three things:

*

*It applies the @Named qualifier with an effective value of the simple class name.

*It sets the beanName of the bean in question to the simple class name.

*It (is the one qualifier that) does not cause the implicit @Default qualifier to be removed.

Now, if you apply it programmatically using, for example, BeanConfigurator#addBean, then you are in charge of deciding which of these behaviors to implement yourself.


text:
Q: Show helper texts to understand the functionality of a function in Swift I don't know the exact name of this features.
So, take a loot at this images:

After hitting "return" button,

I want to do the same things with my own methods.

*

*I want to show a short note along with my function (when someone type function name partially)

*I want to show clear texts like "condition", "code" instead of "xxx:Int", "yyy:String" with my custom function

Thanks in Advance.

A: this is very simple. just type _ before the explanation word. Have a look at this example:
func testExample(_ someExplanation: String){
}

and when you call this function it will look like:

testExample(someExlanation)

UPDATE
There are a few nuances to different use cases, but generally an underscore means "ignore this".
When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing. A fuller function declaration looks like this:
func myFunc(label name: Int) // call it like myFunc(label: 3)

"label" is an argument label, and must be present when you call the function. (And since Swift 3, labels are required for all arguments by default.) "name" is the variable name for that argument that you use inside the function. A shorter form looks like this:
func myFunc(name: Int) // call it like myFunc(name: 3)

This is a shortcut that lets you use the same word for both external argument label and internal parameter name. It's equivalent to func myFunc(name name: Int).
If you want your function to be callable without parameter labels, you use the underscore _ to make the label be nothing/ignored. (In that case you have to provide an internal name if you want to be able to use the parameter.)
func myFunc(_ name: Int) // call it like myFunc(3)


text:
Q: Symfony app: For each HTTP GET, there are 2 HTTP HEAD: why? I've juste realised that on my new project on symfony 2.6, each time I'm doing a GET on an url, automatically after, there are 2 HEAD on the same request.
But I can't manage to figure why? Neither where to start to fing where does come that issue from?
Does someone know where I can start digging from on that one ?
Here is an extract off my access log :
::1 - - [05/Feb/2015:02:06:31 +0100] "GET /tvjp/demande/lister HTTP/1.1" 200 49930
::1 - - [05/Feb/2015:02:06:34 +0100] "HEAD /tvjp/demande/lister HTTP/1.1" 200 -
::1 - - [05/Feb/2015:02:06:37 +0100] "HEAD /tvjp/demande/lister HTTP/1.1" 200 -
::1 - - [05/Feb/2015:02:07:02 +0100] "GET /tvjp/ws/requests HTTP/1.1" 200 201
::1 - - [05/Feb/2015:02:07:05 +0100] "HEAD /tvjp/ws/requests HTTP/1.1" 200 -
::1 - - [05/Feb/2015:02:07:07 +0100] "HEAD /tvjp/ws/requests HTTP/1.1" 200 -
::1 - - [05/Feb/2015:02:12:33 +0100] "GET /tvjp/demande/editer HTTP/1.1" 200 1080
::1 - - [05/Feb/2015:02:12:42 +0100] "HEAD /tvjp/demande/editer HTTP/1.1" 500 -
::1 - - [05/Feb/2015:02:12:45 +0100] "HEAD /tvjp/demande/editer HTTP/1.1" 500 -
::1 - - [05/Feb/2015:02:12:49 +0100] "GET /tvjp/ws/requests/136 HTTP/1.1" 200 39
::1 - - [05/Feb/2015:02:12:54 +0100] "HEAD /tvjp/ws/requests/136 HTTP/1.1" 200 -
::1 - - [05/Feb/2015:02:12:56 +0100] "HEAD /tvjp/ws/requests/136 HTTP/1.1" 200 -

A: This is not connected with Symfony Framework. What web-browser are you using ?? Have You maybe opened developer console in your web-browser ?? Have you installed any plugins in browser?? Try another browser and check your access log.


text:
Q: Stackmob push notification logs? I am sending push notification through stackmob . It first gives log as
"Pushed to [2384740BD0B06EAA8635B33CF58B6E2693E8EAC41B6E7F085DE4DA6955D47098]"
then after certain time it says
"No push tokens found while pushing to 1 tokens with payload {"alert":"New alert(s) available","badge":"1","type":"1"}."
It gave me the headbang . Can anybody please help in lightening up the logs meaning ?
Also its not pushing notification to device ....


text:
Q: Custom Insert/Update on Entity Framework and ASP.NET Dynamic Data I need to customize the insert/update methods for an entity on a CRUD application using ASP.NET Dymanic Data and Entity Framework. I found a solution for an application using Linq To SQL on http://extremedev.blogspot.com.es/2011/03/custom-insertupdate-on-linqtosql-and.html .
The customization is for add some business logic.
I didn't find any method to overload on EF or something similar, any suggestion? Is it possible without using triggers or modifing the methods ItemInserted or ItemUpdated on the forms in template pages?
Thx

A: The method you referenced above is good, another I have seen is this one:
You can override the SubmitChanges method of your data context and check the set of changes and trap each object and each change type (insert, update, delete)
public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
    ChangeSet changeset = GetChangeSet();

    foreach (var f in changeset.Inserts.OfType<Foo>())
    {
        DoSomethingSpecial(f);
    }

    private void DoSomethingSpecial(Foo instance)
    {
    ... // do something with another datacontext instance
    }
}

A: Try the next link. I think this is what you need
http://csharpbits.notaclue.net/2008/05/dynamicdata-automatic-column-update.html


text:
Q: Python SciPy is 'RuntimeWarning: invalid value encountered in sqrt' bad? I wanted to fit some astronomical data (made up data mostly), using a gaussian function on a line. I took the residual of the gaussian+line function on x-axis so I only had to fit the gaussian. Here's how I defined it:
def gaussian_only(x, amp,  mean, std):
    curve = amp*np.exp(-(x-mean)**2 /( 2*std**2 ) ) * np.sqrt(std)/np.sqrt(std) * np.sqrt(amp)/np.sqrt(amp) * np.sqrt(mean)/np.sqrt(mean)
    return curve

I multiplied and divided by sqrt of the values as the curvefit (defined in another function) was returning me negative values for standard deviation, mean and amplitude. So this kind of forced it to return me only positive values.
Here's the function:
def gaussian_only_fit(arr, curve_residual, initial_guess):
    amp, mean, std = initial_guess
    fit = scipy.optimize.curve_fit(gaussian_only, arr[0], curve_residual, [amp,mean,std])
    return fit

Is there something "wrong" or "bad" with what I did?
EDIT:
I did try "bounds" argument for curve_fit. It gives me worse fit values than before.

A: curve_fit() probably attempted to evaluate your function with a negative value of std.
You can use the bounds argument of curve_fit() to avoid this. You should probably also avoid fitting with 0 standard deviation, so set a very small positive value as the lower bound:
fit = scipy.optimize.curve_fit(gaussian_only, arr[0], curve_residual, [amp,mean,std], bounds=([0, -inf, 1e-15],[inf, inf, inf]))

Given your application, I've also set the minimum value for amp to 0 here. Depending on what the data represents you might also want to set limits on mean.
Note the bounds argument was only introduced in scipy version 0.17. If you are using an older version of scipy, you could use a variable transformation like
def gaussian_only(x, log_amp,  log_mean, log_std):
    amp = np.exp(log_amp)         # Guarantees 0 < amp < infinity
    mean = np.exp(log_mean)
    std = np.exp(log_std)
    curve = amp*np.exp(-(x-mean)**2 /( 2*std**2 ) )
    return curve

Of course you will have to adjust your starting guess to account for the transformation.


text:
Q: Creating a python Rectangle object class that can print the corner coordinates I am new to python. I need to create a python Rectangle object class that when called upon one can print the coordinates of the corners as well as have the area and perimeter. I am having issues when I try to run my code that says:
<__main__.Rectangle instance at 0x02F20030>

I was told to add the __str__ as well but then I get:
TypeError: __str__ returned non-string (type int)

Any help would be appreciated, thanks!
class Rectangle:
    def __init__(self, topLeft, topRight, bottomLeft, bottomRight):
        self.tL = topLeft
        self.tR = topRight
        self.bL = bottomLeft
        self.bR = bottomRight
    def perim(self):
            return (2 * (self.tL + self.tR)) + (2 * (self.bL + self.bR))
    def area(self):
            return (self.tL + self.tR) * (self.bL + self.bR)
    def position(self):
        return self.tL
        return self.tR
        return self.bL
        return self.bR
def __repr__(self):
        return self.tL
        return self.tR
        return self.bL
        return self.bT

r1 = Rectangle (5, 5, 10, 10)
print r1

A: try this:
    def __repr__(self):
        return 'tL = '+str(self.tL) + ', tR ='+ str(self.tR)+', bL ='+ str(self.bL) + ', bR =' +str(self.bR)

notes:

*

*make only one return statement execute in a function, in your code your function only returns self.bT (the last).

*In the provided code def __repr__(self) is not indented.

*you don't need 4 points to define a rectangle.

*your Rectangle corners shouldn't just be integers, they have to be sequences of two coordinates (x, y) for instance (3, 7) is a point, implement a point as a 2 integers tuple or list.

edit:
as the OP asked, here's how to change your __init__ method to work with cartesian coordinates:
class Rectangle:
    def __init__(self, tL, bR):  #tL and bR should be passed as tuples
        self.tL = tL
        self.tR = (bR[0], tL[1])  #access tuple elements with tuple[index]
        self.bL = (bR[1], tL[0])
        self.bR = bR

        self.width = bR[0]- tL[0]
        self.height = bR[1] - tL[1]
    def area(self):
        #get area
        #...
    def perim(self):
        #get perim
        #...

r1 = Rectangle((5,5), (30, 20))
print r1.tL   #output (5, 5)
print r1.tR   #output (30, 5)
print r1.width #output 25
print r1.area() #output 375

of course you can create a Point class instead of that, and then you pass two Points to  __init__ to define the rectangle.
I hope that helped you!

A: First of all, functions cannot have more than one return statement.
Also, def __repr__(self): is not correctly indented (it belongs to the Rectangle class).
You might prefer __str__ over __repr__, see https://docs.python.org/2/reference/datamodel.html#object.repr for more details.
class Rectangle:
    def __init__(self, topLeft, topRight, bottomLeft, bottomRight):
        self.tL = topLeft
        self.tR = topRight
        self.bL = bottomLeft
        self.bR = bottomRight
    def perim(self):
        return (2 * (self.tL + self.tR)) + (2 * (self.bL + self.bR))
    def area(self):
        return (self.tL + self.tR) * (self.bL + self.bR)
    def position(self):
        return (self.tL, self.tR, self.bL, self.bR)
    def __str__(self):
        return "Rectangle(%s, %s, %s, %s)" % (self.tL, self.tR, self.bL, self.bR)

r1 = Rectangle (5, 5, 10, 10)
print r1
print "Perimeter: %s" % r1.perim()
print "Area: %s" % r1.area()
print "Position: (%s, %s, %s, %s)" % r1.position()


text:
Q: jquery ajax callback not working please helppp :/
I swear to GOD this things was working yesterday pretty well. Just broke today, dont know why.
but the done callback from $.ajax is not firing.
function check() {
                $.ajax({
                    url: "/statistics/setup-Table",
                    dataType : "json",
                    success: function(data){
                        alert("check "+data['total']);
                    }
                }).done(function(){
                    alert("done");
                }).fail(function(){
                    alert("fail");
                }).always(function(){
                    alert("always");
                });
            }

i only get one alert >> "check 24"
no alerts from done, fail or always pops up. even for the other $.ajax calls, callback functions are not getting fired.
The url is fine too.
Thanks in advance.

A: It was the version I was using of Jquery that messed things up. the CDN that is.
Kevin B - thank you much .that really helped.
Thank you to all the rest as well who looked into it for me .
You guys r amazing, i love this community. i hope i can help back as well ..
later guys. :)


text:
Q: Avoid permission denied error while copying file using Ansible The purpose of this exercise / requirement is that I should do a precheck so that I'm informed before getting "Permission Denied" error while transferring file from source to destination.
I try to copy a file from local ansible host to a remote server using synchronize module with user user1 as below:
   - name: "Copying files from local ansible host tmp to target Destination server"
     synchronize:
       src: "/tmp/hello.txt"
       dest: "/var/"
       mode: push

Here is user1 details:
id
uid=600000208(user1) gid=64688(admingrp) groups=64688(amdingrp)

My requirement is to do a precheck validation where I should check the following.
If the file on the destination /var/hello.txt pre-exists then the validation should fail unless the below conditions are met.
1.
If the file on the destination /var/hello.txt is owned by the same user user1 and
/var/hello.txt should have write permission --w- --- ---
2.
If the file on the destination /var/hello.txt is owned by a different user belonging to the same group admingrp then the file
/var/hello.txt should have write permission ---- -w- ---
3.
If the file on the destination /var/hello.txt is owned by a different user belonging to a different group then the file
/var/hello.txt should have write permission ---- --- -w-
This way I can make sure I will never get "Permission Denied" error while transferring the file and I can highlight the problem before the rsync in executed in the pre-check or validation phase.
My approach may not be ideal thus any other solution would also be appreciated.
I will appreciate if the solution works for folders as well.


text:
Q: Understanding executing PowerShell inside batch with parameters I've been digging in this for a while, but I could not understand how this works. What I need is:

*

*Be able to run a batch file

*The batch file should have parameters

*The parameters should be passed from the batch file to the PowerShell script that is in the same file

Why I need this? Because I need to run a simple batch file to do some stuff, but I need advanced functionality that works only from PowerShell. Specifically: I need a SaveFileDialog for some application.
The following is what I have right now, where I stripped the complicated parts of SaveFileDialog, and left a simple batch + PowerShell part:
<# :

@echo off
setlocal

powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

#>

Write-Host "Hello, I'm PowerShell!"

If I put all this in a batch file, say, myfile.bat. It runs and calls PowerShell and writes that message.
My question/request: How can I run myfile.bat param1 param2 param3, and get these arguments/parameters be passed to my PowerShell script? I'd really appreciate a minimal example that just prints the parameters through PowerShell's write-host.

A:
How can I run myfile.bat param1 param2 param3, and get these arguments/parameters be passed to my PowerShell script?

Build a Batch Script to Accept Arguments
You'd obviously need to scale the batch arguments up with subsequent SET arg#=%~#
I made the example batch script show arguments setting variables up top and have those passed to a PS script that will tie in with a final result later to help clarify more at the end of this answer hopefully.
Example Batch Script
@ECHO ON

SET arg1=%~1
SET arg2=%~2
SET arg3=%~3
SET arg4=%~4

SET PSScript=C:\Users\User\Desktop\Test.ps1

SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0
CD /D "%PowerShellDir%"
Powershell -ExecutionPolicy Bypass -Command "& '%PSScript%' '%arg1%' '%arg2%' '%arg3%' '%arg4%'"
EXIT /B

Build a PowerShell Script to Accept Arguments
You'd obviously need to scale the PowerShell arguments up with subsequent $arg#=$args[#]
Example PowerShell Script
$arg1=$args[0]
$arg2=$args[1]
$arg3=$args[2]
$arg4=$args[3]

Write-Host "$arg1 is a beauty!!"
Write-Host "$arg2 is cool!!"
Write-Host "$arg3 has body odor!!"
Write-Host "$arg4 is a beast!!"

Tying it Together

*

*Pass arguments to the batch script:

*

*c:\users\user\desktop\test.cmd "Selena" "Justin" "Donald" "Bernie"

*Pass arguments to the PowerShell script:

*
Powershell -ExecutionPolicy Bypass -Command "& 'C:\Users\User\Desktop\Test.ps1' 'Selena' 'Justin' 'Donald' 'Bernie'

*Full results echo on:

*
c:\users\user\desktop\test.cmd "Selena" "Justin" "Donald" "Bernie"

SET arg1=Selena

SET arg2=Justin

SET arg3=Donald

SET arg4=Bernie

SET PSScript=C:\Users\User\Desktop\Test.ps1

SET PowerShellDir=C:\Windows\System32\WindowsPowerShell\v1.0

CD /D "C:\Windows\System32\WindowsPowerShell\v1.0"

Powershell -ExecutionPolicy Bypass -Command "& 'C:\Users\User\Desktop\Test.ps1' 'Selena' 'Justin' 'Donald' 'Bernie'"
Selena is a beauty!!
Justin is cool!!
Donald has body odor!!
Bernie is a beast!!

Further Resources

*

*Command Line arguments (Parameters)

%* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4
  %5 ...%255)  only arguments %1 to %9 can be referenced by number.

*PowerShell Parameters / Arguments

A: Passing Multiple Arguments to a PowerShell Script via Batch Script
You may be able to use something like the below method since I was able to get the batch script to pass arguments to the PS script using that syntax.
It does have to build a dynamic PS script up top (The :DynamicPSScriptBuild routine) and it'll delete it if it already exists then and it will also delete it once it's done processing all executions.
I had to use the PS -file rather than the -iex (the reason the PS1 file needs to exist and the dynamic build of it) but it works as expected when I tested it passed the applicable arguments to the script one-by-one with each argument being one PS script execution iteration.
I wasn't sure if you needed all arguments passed to the PS script one after the other or all being passed at once or how you're PS script logic would handle multiple arguments passed to it during the same execution but perhaps this will give you enough detail to adjust accordingly.
The part of the below script that has FOR %%A IN ("Hello I'm PowerShell!", "Goodbye I'm Leaving", "Come with it and get some more" will be the part you put each string to use as an argument to be passed to the PS script one after the other per execution iteration where each string value is in the double quotes and separated by commas.

Script Example
(You might want to turn @ECHO OFF and take out the pause command since I used those to help show everything per iteration to confirm all worked as expected)
<# :

@ECHO ON
SETLOCAL

:DynamicPSScriptBuild
SET PSScript=%~f0.ps1
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
ECHO param($a)        >>"%PSScript%"
ECHO Write-Host "$a"  >>"%PSScript%"

:SetPSScriptArguments
FOR %%A IN (    "Hello I'm PowerShell!",
                "Goodbye I'm Leaving",
                "Come with it and get some more"
) DO CALL :Powershell "%%~A"
IF EXIST "%PSScript%" DEL /Q /F "%PSScript%"
GOTO :EOF

:PowerShell
PowerShell -NoProfile -ExecutionPolicy Bypass -file "%PSScript%" "%~1"
pause
GOTO :EOF

Further Resources

*

*FOR

*CALL

A: Pass the batch variable directly to your Powershell line from within the batch file. To test this, I passed the Write-Host cmdlet as the argument.
foo.bat:
@echo off

set arg1=%1

powershell.exe %1 "this is from powershell"

pause

Launching the .bat with an argument,
.\foo.bat Write-Host

Output:
this is from powershell
Press any key to continue . . .

A: *

*Save arguments to the batch to some environment variable (_args_ in example below)

*Read the batch file into a string: ${%~f0} | out-string

*Create a ScriptBlock from the string

*Unpack arguments: @(iex('&{$args} ' + $env:_args_))

*Invoke the ScriptBlock with the arguments array

Step 1 and 4 are necessary if you want to pass quoted arguments. (ex. myfile.bat param1 "param2 with spaces" param3)
<# :
@echo off
setlocal
set _args_=%*
powershell -noprofile "[ScriptBlock]::Create((${%~f0} | out-string)).Invoke(@(iex('&{$args} ' + $env:_args_)))"
goto :EOF
#>

Write-Host "Hello, I'm PowerShell!"
Write-Host "And these are arguments: "
Write-Host $args[0]
Write-Host $args[1]
Write-Host $args[2]


text:
Q: Swapping strings WITHOUT using double pointers This is actually just a small part of the original assignment I have in algorithms and data structure. At some point I'm supposed to write a function that swaps two elements in an array of strings.
The prototype we have to use is:
void swap(char *a, char *b);

To me it makes much more sense passing double pointers to this function (if swapping strings). In fact, I don't know how to make their prototype work without using double pointers. Am I missing something or is this wrong?
I've done my research on this a while ago and there are many answered questions here, I'm just wondering whether the person who was designing this assignment made a mistake.

A: You can swap two strings by creating a temporary char array of length equal to either one of the two strings, and by using strcpy().
Of course, you need to make sure that swapping does not overflow one of the two strings/arrays. Here is a sample example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swap(char *a, char *b)
{
    char *tmp = malloc(strlen(a) + 1);

    strcpy(tmp, a);
    strcpy(a, b);
    strcpy(b, tmp);

    free(tmp);
}

int main(void)
{
    char str_a[50] = "Hello world";
    char str_b[50] = "What's up";

    swap(str_a, str_b);

    puts(str_a);
    puts(str_b);

    return 0;
}

Another approach is to use a loop with a single char variable, thus avoiding dynamic memory allocation:
void swap(char *a, char *b)
{
    char tmp;

    while (*a && *b)
    {
        tmp = *a;
        *a++ = *b;
        *b++ = tmp;
    }

    if (!*a)
    {
        size_t n = 0;
        while (b[n])
        {
            *a++ = b[n++];
        }
    }
    else if (!*b)
    {
        size_t n = 0;
        while (a[n])
        {
            *b++ = a[n++];
        }
    }
    *a = '\0';
    *b = '\0';
}


text:
Q: issue with running Django server When I run Django in local mode using the runserver command video files can not be loaded in the browser. All other static files, such as images, javascript and css, serve fine.

A: Duplicate to Django runserver - can't serve video files
The answer it that  Django's runserver does not support byte range requests. See this thread:
https://groups.google.com/forum/#!msg/django-developers/NZ1qTkZ6vok/fhdz7rTtL1EJ
And this ticket:
https://code.djangoproject.com/ticket/22479


text:
Q: PowerShell from Batch File on Network Folder using Admin Accounts: Cannot Find Drive Specified I have a batch file that will run a PS script from my floating desktop after prompting for Admin credentials, however when I place the batch and PS file on the network to run, it says
N:\folder\folder2\folder3\Powershell.bat
The System cannot find the drive specified, and lists my mapped N:\ drive and directory.

Strangely, when I log into Windows on the same Admin AD account. Not requiring me to prompt the password because I am already Admin, it fixes this issue. Here is my code:
@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
write-output "Enter your ADMIN credentials to continue..."
EXIT

I'm fairly new to scripting, so please help me out, I tried to list the exact directory but it didn't work. I believe it MUST be with some issues with using my Admin account. This domain must require my Admin account before I can run the scripts. It was working last week so I'm pretty lost...


text:
Q: Python Scrapy Xpath not following url I am new at python and I am having a bit of trouble getting scrapy to follow urls. I suspect that it may be with the xpath specification, however after doing several tutorials on the topic, I am no closer to resolving this. It loops over the urls in the referenced table and scrapes the content from the starting page repetitively. What am I doing wrong?
Code attached:
import scrapy
from scrapy.selector import Selector
from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.http import Request

class MySpider(CrawlSpider):
    name = 'unespider'
    allowed_domains = ['https://my.une.edu.au/']
    start_urls = ['https://my.une.edu.au/courses/']
    rules = Rule(LinkExtractor(canonicalize = True, unique = True), follow = True, callback = "parse"),

    def parse(self, response):
        hxs = Selector(response)
        for url in response.xpath('//*'):
        yield {
            'title': url.xpath('//*[@id="main-content"]/div/h2/a/text()').extract_first(),
            'avail': url.xpath('//*[@id="overviewTab-snapshotDiv"]/p[3]/a/text()').extract_first(),
               }

        for url in hxs.xpath('//tr/td/a/@href').extract():
            yield Request(response.urljoin(url), callback=self.parse)

A: ** update I see what you wanted and updated code, it now follows for each year and outputs correct**
I apologize that I'm not sure what your trying to follow and scrape from the start page as well as what this is //*[@id="overviewTab-snapshotDiv"]. I wasn't able to find that xpath. I'd like to help you out more since I'm fairly new as well to programming and scrapy was hard at first, I ended up making my own class scraper later so I could do it my way, even though I'm sure scrapy is better :)
I've done the code to scrape your titles and URLs, I commented out Rule since I don't know what your trying to follow or why.
import scrapy
from scrapy.spiders import Rule

from scrapy.linkextractors import LinkExtractor

from overflowQuestion2 import items #make sure to import items.py

class DavesimSpider(scrapy.Spider):

    name = 'daveSim'
    allowed_domains = ['my.une.edu.au']
    start_urls = ['http://my.une.edu.au/courses/2007', ] #start at 2007
    rules = Rule(LinkExtractor(canonicalize=True, unique=True), follow=True, callback="parse")

def parse(self, response): #This will scrape links and follow

    #Grab the main Div wrapping the links
    divLinkWrapper = response.xpath('//div[@class="pagination"]')
    for links in divLinkWrapper: #for every element extract links
        theLinks = links.xpath('ul/li/a/@href').extract()
        for i in theLinks: #for every link, follow link
            yield scrapy.Request(i, callback=self.ContentParse)

def ContentParse(self, response): #scrape content you want

    #Grab main Div wrapper for content
    divMainContent = response.xpath('//div[@id="main-content"]')

    for titles in divMainContent:
        #create Item object from items.py function
        Item = items.Overflowquestion2Item()
        theTitles = titles.xpath('div[@class="content"]//a/text()').extract()

        #set Item to the scrapy.Field in items.py
        Item['title'] = theTitles
        yield Item #yield Item through pipeline

    for URLs in divMainContent:
        Item = items.Overflowquestion2Item()
        theURLs = URLs.xpath('//table/tr/td/a/@href').extract()
        Item['URL'] = theURLs
        yield Item

Now for items.py:
import scrapy

class Overflowquestion2Item(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    URL = scrapy.Field()

    pass

Also remember in settings to uncomment the items pipeline,
ITEM_PIPELINES = {
    'overflowQuestion2.pipelines.Overflowquestion2Pipeline': 300,
}

I'm positive this could be coded better and I hope someone here will refine it ;)


text:
Q: Xamarin Android: How to increase max jdk memory for layout renderer in Visual Studio I'm developing a rather complex user interface in Xamarin Android for Visual Studio 2012.  There are four versions of this interface, Normal, Small, Large and Landscape.  When I added the Landscape layout (the last one), the JDK that runs the renderer run up to 890 Mb usage and I assume is thrashing the garbage collector as it's using 50% of the CPU on a quad-core system.  Sometimes the layouts will load, but more often I get a blank white box in the middle of the layout and have to shut down both visual studio and kill the jvm that's run amok.
Is there a way to tell the SDK to use 2G of memory instead of 1G for the renderer?

A: In Visual Studio, you can now go to:
Project Properties > Android Options > Advanced (tab) > Java Max Heap Size
2g will give you 2GB


text:
Q: Counting how many times a value occurs in a json file how do i read count how many times each "type" and "key" occurs in a  json file with data like below
{"method":"GET","UDID":"26:90:A4:46392970","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/04track12netics2015/reverseGeocode/-28.45818,24.39608.xml?returnSpeedLimit=true","key":"04track12netics2015","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":5,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T23:59:52.975Z"}
{"method":"GET","UDID":"26:90:A4:46392915","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/04track12netics2015/reverseGeocode/-25.96607,28.14167.xml?returnSpeedLimit=true","key":"04track12netics2015","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":96,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T23:59:53.011Z"}
{"method":"GET","UDID":"26:90:A4:46393163","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/04track12netics2015/reverseGeocode/-28.45818,24.39608.xml?returnSpeedLimit=true","key":"04track12netics2015","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":7,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T23:59:53.170Z"}
{"method":"GET","UDID":"26:90:A4:81986956","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/tile/1185/1176/11.png?settings=russian-river&res=mdpi","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":438,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T06:06:27.394Z"}
{"method":"GET","UDID":"26:90:A4:81987014","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/tile/1185/1177/11.png?settings=russian-river&res=mdpi","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":390,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T06:06:27.404Z"}
{"method":"GET","UDID":"26:90:A4:81986884","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/tile/1183/1175/11.png?settings=russian-river&res=mdpi","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":533,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T06:06:27.417Z"}
{"method":"GET","UDID":"26:90:A4:41422853","dataset":"TomTom","production":true,"type":"SEARCH","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/search/0A%20Schoonder%20Stree,.json?countrySet=ZA","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":824,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T22:37:03.677Z"}
{"method":"GET","UDID":"26:90:A4:88284444","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/reverseGeocode/-33.92456,18.54727.json","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":170,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T07:51:24.615Z"}
{"method":"GET","UDID":"26:90:A4:10992447","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN/tile/18063/19670/15.png?transparent=true&settings=russian-river&res=hdpi","key":"CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":407,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-21T20:23:12.854Z"}
{"method":"GET","UDID":"26:90:A4:10992826","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN/tile/18060/19670/15.png?transparent=true&settings=russian-river&res=hdpi","key":"CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":219,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-21T20:23:13.046Z"}
{"method":"GET","UDID":"26:90:A4:46392970","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/04track12netics2015/reverseGeocode/-28.45818,24.39608.xml?returnSpeedLimit=true","key":"04track12netics2015","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":5,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T23:59:52.975Z"}
{"method":"GET","UDID":"26:90:A4:46392915","dataset":"deCarta","production":true,"type":"REVERSEGEOCODE","path":"/v1/04track12netics2015/reverseGeocode/-25.96607,28.14167.xml?returnSpeedLimit=true","key":"04track12netics2015","cost":1,"vendorCost":{"dataProvider":1,"trafficProvider":0},"roundTripTime":96,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T23:59:53.011Z"}
{"method":"GET","UDID":"26:90:A4:81986949","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo/tile/1182/1175/11.png?settings=russian-river&res=mdpi","key":"fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":472,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-12T06:06:27.421Z"}
{"method":"GET","UDID":"26:90:A4:10992826","dataset":"tomtom-world","production":true,"type":"TILE","path":"/v1/CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN/tile/18060/19670/15.png?transparent=true&settings=russian-river&res=hdpi","key":"CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN","cost":1,"vendorCost":{"dataProvider":0.03125,"trafficProvider":0},"roundTripTime":219,"nonCompQuery":0,"level":"request","message":"Processing Request","timestamp":"2016-08-21T20:23:13.046Z"}

A: from collections import Counter
import json
from pprint import pprint

with open('logs.txt') as infile:
    data = (json.loads(line) for line in infile)
    counter = Counter((row['type'], row['key']) for row in data)

pprint(dict(counter))

Output:
{(u'REVERSEGEOCODE', u'04track12netics2015'): 5,
 (u'REVERSEGEOCODE', u'fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo'): 1,
 (u'SEARCH', u'fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo'): 1,
 (u'TILE', u'CxIQlYBhwykcIxtYwrrbltCDiJ4xUxfN'): 3,
 (u'TILE', u'fpOgtLY1ZF22m3va4FLkU52tsLmpaNyo'): 4}

A: Use the following approach, the keys and types hold the number of times each key and type occurs. good luck.
from collections import defaultdict
keys,types = defaultdict(int), defaultdict(int)
for jline in yourjsonfile.readlines():
    line=json.loads(jline)
    keys[line['key']] += 1
    types[line['type']] += 1


text:
Q: Binding ninject via name I have a ninject problem where I am using the same interface on multiple types to provide a config class for my application.
The entry point classes (below) that start that application are returned from the ninject kernel and I have a named Config dependency on that class.
    public ProcessA(ILogger logger, [Named("TypeA")] IConfigProvider configProvider)
    {
        _logger = logger;
        _configProvider = configProvider;
    }

    public ProcessB(ILogger logger, [Named("TypeB")] IConfigProvider configProvider)
    {
        _logger = logger;
        _configProvider = configProvider;
    }

And then in my bindings
        Bind<IConfigProvider>().To<ProcessA>().Named("TypeA");
        Bind<IConfigProvider>().To<ProcessB>().Named("TypeB");

Further down the processing line ProcessA and ProcessB share some classes that need an IConfigProvider but when the ProcessA or ProcessB gets to that point ninject cannot resolve the dependancy. I can't make it a named dependency at that point because the classes are used by both processors.
I could pass the concrete Config class down from ProcessA and ProcessB removing the constructor dependency but that doesn't seem the right way to do it.
EDIT 1 (from BatteryBackupUnit's answer)
I removed the named references and added the below which seems to do the trick. Found a method on the following question Ninject Bind When Ancestor Of Type T but I had to add in a check for request.Target == null else it wouldnt work when I got an instance of ProcessA and ProcessB from the ninject kernel.
    public override void Load()
    {
        Bind<IConfigProvider>()
            .To<TypeAConfigProvider>()
            .When(request => HasAncestorOfType<ProcessA>(request));

        Bind<IConfigProvider>()
            .To<TypeBConfigProvider>()
            .When(request => HasAncestorOfType<ProcessB>(request));
    }

    private static bool HasAncestorOfType<T>(IRequest request)
    {
        if (request == null || request.Target == null)
            return false;

        if (request.Target.Member.ReflectedType == typeof(T))
            return true;

        return HasAncestorOfType<T>(request.ParentRequest);
    }

A: You can use the contextual binding mechanism to achieve that.
See IBindingWhenSyntax.cs for all available methods.
How about WhenAnyAncestorNamed?
Alternatively, there's the WhenInjectedInto<> binding which would be used like:
Bind<IConfigProvider>().To<ConfigA>()
    .WhenInjectedInto<ProcessA>();

Now since you don't actually want to inject it directly into ProcessA you'd have to use a When condition like WhenInjectedIntoAncestor<Process>(). You can create this yourself - as an extension method extending from the WhenAnyAncestorMatches extension method. Also see here


text:
Q: Where to find Ubuntu equivalent packages on Mac OS X I using Mac (Sierra OS). As part of a rails project I installed libwebkitgtk-1.0-0 and libmagickwand-dev packages (using apt-get) on ubuntu and was looking to do the same on Mac but I can't find them. I tried brew search but that didn't yield anything. How do I go about finding and installing the equivalent packages on my MAC device?

A: I searched:
❯ brew search webkitgtk

webkitgtk was deleted from homebrew/core in commit cc9be4ac:
  webkitgtk: migrate to boneyard
  Repeatedly breaks/causes issues & consequently sits there stuck on
  versions with publicly-known CVEs frequently.
  Closes https://github.com/Homebrew/homebrew-core/issues/9053.

To show the formula before removal run:
  git -C "$(brew --repo homebrew/core)" show cc9be4ac^:Formula/webkitgtk.rb

If you still use this formula consider creating your own tap:
  http://docs.brew.sh/How-to-Create-and-Maintain-a-Tap.html

❯ brew search magickwand
homebrew/php/php53-magickwand                     homebrew/php/php55-magickwand
homebrew/php/php54-magickwand                     homebrew/php/php56-magickwand


text:
Q: Android-Expected a List while deserializing, but got a class java.util.HashMap I want to get all list of restaurants from Firebase in android.

Here is my code:
boolean delivery;
String openTime, closeTime, restaurantName;
long likes;
List<String> utilities;

List<RestaurantModel> listRes;

DatabaseReference dataResReference;

public RestaurantModel(){
    dataResReference = FirebaseDatabase.getInstance().getReference().child("restaurants");
}

public List<RestaurantModel> getallRestaurant(){

    listRes = new ArrayList<>();
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataValues : dataSnapshot.getChildren()){
                    RestaurantModel restaurantModel = dataValues.getValue(RestaurantModel.class);
                    listRes.add(restaurantModel);
                }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    dataResReference.addListenerForSingleValueEvent(valueEventListener);
    return  listRes;
}

But i get an exception
Expected a List while deserializing, but got a class java.util.HashMap

at  RestaurantModel restaurantModel = dataValues.getValue(RestaurantModel.class);
Update:
Base on Alex Mamo answser, i changed my code is:
public void getAllRestaurant(final WhereInterface whereInterface){
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //go to node restaurant because datasnapshot is parent node
            DataSnapshot dataSnapshotRes = dataSnapshot.child("restaurants");
            //

            for (DataSnapshot valueRes : dataSnapshotRes.getChildren()){
                RestaurantModel restaurantModel = valueRes.getValue(RestaurantModel.class);
                whereInterface.getAllRestaurantModel(restaurantModel);

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    databaseReferenceRoot.addListenerForSingleValueEvent(valueEventListener);
}

But i still got this exception (:.
Anyone can know why?
And are there solution?
Thank you so much!

A: There are two problems in your code. The first one would be this error:

Expected a List while deserializing, but got a class java.util.HashMap

Which can be solved using the following lines of code:
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        List<RestaurantModel> listRes = new ArrayList<>();

        for (DataSnapshot dataValues : dataSnapshot.getChildren()){
            RestaurantModel restaurantModel = dataValues.getValue(RestaurantModel.class);
            listRes.add(restaurantModel);
        }

        //Do what you need to do with listRes
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); //Don't ignore errors
    }
};
dataResReference.addListenerForSingleValueEvent(valueEventListener);

And the second problem is that you cannot return something now that hasn't been loaded yet. Firebase APIs are asynchronous, meaning that onDataChange() method returns immediately after it's invoked, and the callback from the Task it returns will be called sometime later. There are no guarantees about how long it will take. So it may take from a few hundred milliseconds to a few seconds before that data is available. Because that method returns immediately, your listRes list you're trying to return, will be empty due to the asynchronous behavior of this method.
Basically, you're trying to return a value synchronously from an API that's asynchronous.  That's not a good idea.  You should handle the APIs asynchronously as intended.
A quick solution to this problem would be to use the listRes list only inside the onDataChange() method (as in the above lines of code), otherwise I recommend you see the last part of my answer from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
Edit:
public void getAllRestaurant(){
    ValueEventListener valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            List<RestaurantModel> listRestaurant = new ArrayList<>();

            for (DataSnapshot valueRes : dataSnapshot.getChildren()){
                RestaurantModel restaurantModel = valueRes.getValue(RestaurantModel.class);
                Log.d("Test", restaurantModel.getRestaurantName());
                listRestaurant.add(restaurantModel);
            }

            //Do what you need to do with listRes
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException();
        }
    };
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    rootRef.child("restaurants").addListenerForSingleValueEvent(valueEventListener);
}

A: I know this can be too late, but I wish my answer could help somebody. I know 2 ways to solve this problem. Once I have time I'll update my answer .
#Solution 1
First of all I copy & paste your code. It is not clear for me how did you add data to firebase, but I feel you added data directly to firebase.
so this is My MainActivity code :
public class MainActivity extends AppCompatActivity {

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

        RestaurantModel rm;
        List<String> utils;

        //restaurant 1
        rm = new RestaurantModel();
        rm.closeTime = "12:00am";
        rm.openTime = "12:00pm";
        rm.delivery = true;
        rm.likes = 300;
        rm.restaurantName = "KFC";
        utils = new ArrayList<>();
        utils.add("free wifi");
        utils.add("free Parking");
        utils.add("free water");
        rm.utilities = utils;

        //write first restaurant to Firebase
        rm.addRestaurantToFirebase(rm);

        //restaurant 2
        rm = new RestaurantModel();
        rm.closeTime = "5:00am";
        rm.openTime = "12:00pm";
        rm.delivery = false;
        rm.likes = 500;
        rm.restaurantName = "SubWay";
        utils = new ArrayList<>();
        utils.add("free wifi");
        utils.add("free Parking");

        rm.utilities = utils;

        //write Second restaurant to Firebase
        rm.addRestaurantToFirebase(rm);

        rm.getallRestaurant();

    }

}

and this is RestaurantModel :
public class RestaurantModel {
    public boolean delivery;
    public String openTime;
    public String closeTime;
    public String restaurantName;
    public long likes;
    public List<String> utilities;

    public List<RestaurantModel> listRes;

    DatabaseReference dataResReference;

    public RestaurantModel() {
        dataResReference = FirebaseDatabase.getInstance().getReference().child("restaurants");
    }

    public List<RestaurantModel> getallRestaurant() {
        listRes = new ArrayList<>();

        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot dataValues : dataSnapshot.getChildren()) {
                    RestaurantModel restaurantModel = dataValues.getValue(RestaurantModel.class);
                    listRes.add(restaurantModel);

                    Log.d("restaurantModel", restaurantModel.restaurantName);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };
        dataResReference.addListenerForSingleValueEvent(valueEventListener);
        return listRes;
    }

    public void addRestaurantToFirebase(RestaurantModel rm) {
        dataResReference.child(restaurantName).setValue(rm);
    }

}

here the result in firebase

A: I'm not sure if this is the case, but may help others: Do not store null's on List's

*

*Firebase stores List's as Map's with index as keys, when deserialized back it detects the correlative keys and it treats it as a 'List'

*Null values are not stored, nulls delete the field

So a List with a null value won't have all indexes and, when parsed, Firebase thinks that it's a Map.
Store some kind of "empty" value instead of null and it'll work.
Side note: if you have a map with correlative indexes it'll happen a similar error, just add some not numeric prefix on keys.

A: Kotlin Example
This is a example to get all your nested data out of firebase real time database.
There are many tokens in this example and every token contains list of notes

 val noteListener = object : ValueEventListener {

            override fun onDataChange(dataSnapshot: DataSnapshot) {
                // For each loop will run until all notes are fetched
               for (snapshot in dataSnapshot.children){
                   val note = snapshot.getValue(Note::class.java)
                   Log.e("Note",note?.title)
               }
            }

            override fun onCancelled(databaseError: DatabaseError) {
                // On failed, log a message
                Log.e("Debug", "loadPost:onCancelled", databaseError.toException())
            }
        }

        //You can use the addListenerForSingleValueEvent() method to simplify this scenario: it triggers once and then does not trigger again.
        //ref.child(token) is the path for reach notes for each unique user , in your case it can be ref only
        ref.child(token).addListenerForSingleValueEvent(noteListener)

A: Pre-requisit: We are setting the Snapshot response to our model class objects.
In our Model class. there must be one or more objects which we are setting as list.
Now in response, the ArrayList inside the Snapshot is coming to us as hashmap but we need list.
So the Solution i find is:
set the first layer of data to model objects as it is using limited parameter constructor.
Then the ArrayList object - Get it as a separate object of that specific class and then add it into the model class by getter.
Follow the below code sample.
Lets suppose you have Object Model class. And InnterList as an array list. My solution is to take innerList as a seperate object and then add it to model class using constructors.
If this list is not comming in response. You can handle them using limited constructor parameters.
    Object object;
    FirebaseDatabase.getInstance().getReference().getRoot().child("yourKey").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot temp : snapshot.getChildren()) {

                if (temp.hasChild("InnerList")) {
                    List<InnerList> innerList = new ArrayList<InnerList>();
                    DataSnapshot yourInnerArrayListSnapShot = temp.child("InnerList");

                    for (DataSnapshot innerTemp : yourInnerArrayListSnapShot.getChildren()) {
                        InnerList yourInnerArrayListObject = innerTemp.getValue(InnerList.class);
                        innerList.add(yourInnerArrayListObject);
                    }

                    object = new Object(a, b, innerList);
                } else {
                    object = new Object(a, b);
                }
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Log.d(TAG, "onCancelled error is : " + error.getMessage());
            pd.dismiss();
        }
    });

Enjoy !!


text:
Q: Add elements to the maximum values of a list Hi i have a list of n elements and i want to know the 30 maxim values of list without changing his order. And suppose that i have a second list with n elements and i want to add this elements to the previous list but just to the 30 ones that have the maximum values, and also without changing his order. How i can do this? This is the code that i use to add elements to other list but i don´t know how to do it in the way that i explain before.
plotData = Partition[Riffle[informacion1, desvi], 2]

Any suggestions?

A: To find the 30 largest of your first list, we'll call it list1, use
TakeLargest[lis1,30]

To then add only to these largest from the second list, let's call it list2, we can use Ordering to identify the positions where the 30 largest are.
list3=list1;
(list3[[#]] = list1[[#]] + list2[[#]]) &@Ordering[list1, -30]

Then list3 will contain a copy of list1 with only the desired elements changed.

Edit: A small demo.
list1 = RandomInteger[1000, 10]
list2 = RandomInteger[1000, 10]
list3 = list1;
(list3[[#]] = list1[[#]] + list2[[#]]) &@Ordering[list1, -4];
list3

Sort[list1]
Sort[list3]

{383, 226, 192, 397, 565, 60, 184, 535, 423, 77}
  {667, 297, 386, 866, 625, 881, 233, 327, 288, 411}
  {383, 226, 192, 1263, 1190, 60, 184, 862, 711, 77}
{60, 77, 184, 192, 226, 383, 397, 423, 535, 565}
  {60, 77, 184, 192, 226, 383, 711, 862, 1190, 1263}

Notice only the 4 largest in list1 see their values change in list3, while the order is retained.

A: As  N.J.Evans hinted you can do the first part with Ordering.  I'll take the largest seven instead of 30 for brevity, and use n = 20.  First generate sample data:
n = 20;
p = 7;
SeedRandom[0]
list = RandomInteger[99, 20]

{83, 66, 4, 21, 71, 67, 16, 67, 76, 28, 21, 43, 17, 46, 53, 84, 85, 17, 50, 15}

Find the places of the largest seven values:
m = Ordering[list, -p]

{6, 8, 5, 9, 1, 16, 17}

Sort that list of places to keep them in order:
m = Sort[m]

{1, 5, 6, 8, 9, 16, 17}

Extract the values from list:
list[[m]]

{83, 71, 67, 67, 76, 84, 85}

I am not sure I follow the second part of the question but I think this does what you want:
SeedRandom[1]
list2 = RandomInteger[99, 20]

{80, 14, 0, 67, 3, 65, 23, 97, 68, 74, 15, 24, 4, 90, 83, 70, 1, 30, 48, 25}

m2 = Sort @ Ordering[list2, -p]

{1, 8, 9, 10, 14, 15, 16}

list2[[m2]]

{80, 97, 68, 74, 90, 83, 70}

list3 = list;
list3[[m]] = {list3[[m]], list2[[m2]]}\[Transpose];

list3

{{83, 80}, 66, 4, 21, {71, 97}, {67, 68}, 16, {67, 74}, {76, 90},
  28, 21, 43, 17, 46, 53, {84, 83}, {85, 70}, 17, 50, 15}

Flatten if desired:
list3 // Flatten

{83, 80, 66, 4, 21, 71, 97, 67, 68, 16, 67, 74, 76, 90,
 28, 21, 43, 17, 46, 53, 84, 83, 85, 70, 17, 50, 15}


text:
Q: Errors when trying to update using apt-get I get errors when I try to install any software. The errors are
Reading package lists... Error!
E: Could not open file /var/cache/apt/pkgcache.bin - open (22: Invalid argument)
E: Failed to truncate file - ftruncate (9: Bad file descriptor)
E: The package lists or status file could not be parsed or opened.

When I try to update a system with sudo apt-get update, I encounter other errors like
W: Failed to fetch http://tz.archive.ubuntu.com/ubuntu/dists/precise-backports/main/binary-i386/Packages  404  Not Found [IP: 91. 189. 92. 192 80]

and many others.
I am new to Ubuntu.

A: Try this:

*

*Run gksudo gedit /etc/apt/sources.list

*Add these  lines to it
deb http://it.archive.ubuntu.com/ubuntu/ precise main universe restricted multiverse
deb-src http://it.archive.ubuntu.com/ubuntu/ precise main universe restricted multiverse

deb http://security.ubuntu.com/ubuntu precise-security main universe restricted multiverse
deb-src http://security.ubuntu.com/ubuntu precise-security main universe restricted multiverse

deb http://it.archive.ubuntu.com/ubuntu/ precise-updates main universe restricted multiverse
deb-src http://it.archive.ubuntu.com/ubuntu/ precise-updates main universe restricted multiverse

*Save the file and quit the text editor.

*Run sudo apt-get update.


text:
Q: Why this returns an empty array? I have a parent component of many components that I switch between them by clicking at  elements. These files are Vue files.
What I want is make them active whenever the component is being used.
As example:
When I click at Home from navbar, the component switches to Home's component(Already done that) AND makes it have a border so that it is marked as the active component(active tab as some say)
I wanted to do that by these steps:
First) I get the collection of all  elements
Second) I keep the elements that have class = current data(which is the data that I use to switch them between) by using filter. Which should be only 1 item which is the active one.
Third) Apply the CSS style to that element...etc
This is the parent component's code(I cut down CSS style btw to make it shorter):
<template>

{{navbar.Home}}

{{navbar.Reservation}}

{{navbar.About}}

{{navbar.Contact}}

        Sign Up

      <keep-alive>
        <transition name="component-fade" mode="out-in">
          <component v-bind:is="current"></component>
        </transition>
      </keep-alive>

Copyright © All Rights Reserved

</template>

The problem is that the array returns empty and the style doesn't apply. Any help?

A: Same problem. With Vue template and script you are composing virtual DOM. Vue just doesn't work the way you are expecting. Try this:
...
export default {
  ...
  data() {
    return {
      navbar: {
        Home: "Home",
        Reservation: "Reservation",
        About: "About us",
        Contact: "Contact"
      },
      current: "Home"
    };
  },
  methods: {},
  // this method, lifecycle hook, is executed
  // after the Browser DOM is patched with
  // Virtual DOM you composed from template
  mounted () {
    let nodlist = document.getElementsByTagName("a");
    console.log(nodlist);
    let active = Array.from(nodlist).filter(
      element => element.className == this.data.current
    );
    console.log(active);
    active.cssText = "border-bottom: 5px solid #5fb0e4;";
  }
};

Now your array will be not empty. But you achieved ... nothing. Vue have no idea you changed the Browser DOM and your changes will be lost with next DOM patching. Sorry bro, you just don't get the Vue idea. You have to learn more about Vue principles.


text:
Q: How to connect locahost with my outside Database i to want to connect from my Computer to my outside Database .
SSH information from my Web-Host
SSH IP:   .224.138.
SSH Port:   65002
SSH Username:   2907*****
SSH Password:   ***********
I have a File on /var/www/html/provess.php  which connect to my Database on my Host (it is outside from my Computer) , the code here
With
ssh -p 65002 2907***** @***.224.138.***

Can connect to my Host .
When try,
In my Firefox , give on SOCKS-Host -> 127.0.0.1 Port: 8080 , to connect .
on Terminal write,
ssh -D 8080 -C -N -p 65002 2907*****@***.224.138.***

asked from my password
and on the Browser write,

localhost:8080/provess.php

I to come, Not connection....
I have same to try in localhost (all on my computer , Datebase too..) , and all working gut , Screenshot from the Browser , when write localhost/provess.php (but here the name File is prove_comment..) , here
How have my File sshd_config here
With these Code Check if the remote host allow tunneling.
ssh -p 65002 -v -L 3333:***.224.138.***:65002 2907*****@***.224.138.***

the tunnel is established correctly .
I want , when write on my Browser localhost/provess.php  , it Display the Table with inside the content from my Database(name , email and message) .In a connection with SSH and Tunnel .
Can Please anyone Help me , Thanks !

A: So , People tell me , it is possible easy to making....
I to let my File provess.php  on my Website , than Write on my Browser ,
https://myWebsite/provess.php
and....
Screeshot