text:
Q: Axios/Vue - Prevent axios.all() to keep executing In my application wile authenticating the user I call the fetchData function. If the user token become invalid, the application will run axios.all() and my interceptor will return a lot of errors.
How to prevent axios.all() of keep runing after the first error? And show only one notification to the user?
interceptors.js
export default (http, store, router) => {
    http.interceptors.response.use(response => response, (error) => {
        const {response} = error;

        let message = 'Ops. Algo de errado aconteceu...';

        if([401].indexOf(response.status) > -1){
            localforage.removeItem('token');

            router.push({
                name: 'login'
            });

            Vue.notify({
                group: 'panel',
                type: 'error',
                duration: 5000,
                text: response.data.message ? response.data.message : message
            });
        }

        return Promise.reject(error);
    })
}

auth.js
const actions = {
    fetchData({commit, dispatch}) {
        function getChannels() {
            return http.get('channels')
        }

        function getContacts() {
            return http.get('conversations')
        }

        function getEventActions() {
            return http.get('events/actions')
        }

        // 20 more functions calls

        axios.all([
            getChannels(),
            getContacts(),
            getEventActions()
        ]).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}

A: EDIT: @tony19's answer is much better as it allows to cancel requests still pending after first error, and does not need any extra library.

One solution would be to assign a unique identifier (I will use the uuid/v4 package in this example, feel free to use something else) to all the requests you use at the same time:
import uuid from 'uuid/v4'

const actions = {
    fetchData({commit, dispatch}) {
        const config = {
            _uuid: uuid()
        }

        function getChannels() {
            return http.get('channels', config)
        }

        function getContacts() {
            return http.get('conversations', config)
        }

        function getEventActions() {
            return http.get('events/actions', config)
        }

        // 20 more functions calls

        axios.all([
            getChannels(),
            getContacts(),
            getEventActions()
        ]).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}

Then, in your interceptor, you can choose to handle the error a single time using this unique identifier:
export default (http, store, router) => {
    // Here, you create a variable that memorize all the uuid that have
    // already been handled
    const handledErrors = {}
    http.interceptors.response.use(response => response, (error) => {
        // Here, you check if you have already handled the error
        if (error.config._uuid && handledErrors[error.config._uuid]) {
            return Promise.reject(error)
        }

        // If the request contains a uuid, you tell
        // the handledErrors variable that you handled
        // this particular uuid
        if (error.config._uuid) {
            handledErrors[error.config._uuid] = true
        }

        // And then you continue on your normal behavior

        const {response} = error;

        let message = 'Ops. Algo de errado aconteceu...';

        if([401].indexOf(response.status) > -1){
            localforage.removeItem('token');

            router.push({
                name: 'login'
            });

            Vue.notify({
                group: 'panel',
                type: 'error',
                duration: 5000,
                text: response.data.message ? response.data.message : message
            });
        }

        return Promise.reject(error);
    })
}

Additional note, you could simplify your fetchData function to this:
const actions = {
    fetchData({commit, dispatch}) {
        const config = {
            _uuid: uuid()
        }

        const calls = [
            'channels',
            'conversations',
            'events/actions'
        ].map(call => http.get(call, config))

        // 20 more functions calls

        axios.all(calls).then(axios.spread(function (channels, contacts, eventActions) {
            dispatch('channels/setChannels', channels.data, {root: true})
            dispatch('contacts/setContacts', contacts.data, {root: true})
            dispatch('events/setActions', eventActions.data, {root: true})
        }))
    }
}

A: The upvoted answer proposes a solution that requires waiting for all responses to complete, a dependency on uuid, and some complexity in your interceptor. My solution avoids all that and addresses your goal of terminating Promise.all() execution.
Axios supports request cancelation, so you could wrap your GET requests with an error handler that cancels the other pending requests immediately:
fetchData({ dispatch }) {
  const source = axios.CancelToken.source();

  // wrapper for GET requests
  function get(url) {
    return axios.get(url, {
        cancelToken: source.token // watch token for cancellation
      }).catch(error => {
        if (axios.isCancel(error)) {
          console.warn(`canceled ${url}, error: ${error.message}`)
        } else {
          source.cancel(error.message) // mark cancellation for all token watchers
        }
      })
  }

  function getChannels() {
    return get('https://reqres.in/api/users?page=1&delay=30'); // delayed 30 secs
  }
  function getContacts() {
    return get('https://reqres.in/api/users?page=2'); // no delay
  }
  function getEventActions() {
    return get('https://httpbin.org/status/401'); // 401 - auth error
  }

  ...
}

In your interceptor, you'd also ignore errors from request cancellations:
export default (http, store, router) => {
  http.interceptors.response.use(
    response => response,
    error => {
      if (http.isCancel(error)) {
        return Promise.reject(error)
      }

      ...

      // show notification here
    }
}

demo

A: As an alternative to Axios cancel, you can use Bluebird Promise Cancellation which is simpler.

The advantages of the new cancellation compared to the old cancellation are:

*

*.cancel() is synchronous.

*no setup code required to make cancellation work

*composes with other bluebird features, like Promise.all

Here is a demo. I've added some logging in axios.get(...).then(...) to track if each call completes.
Comment out the line promises.forEach(p => p.cancel()) to verify that without cancellation the non-erroring calls will run to completion.

//for demo, check if fetch completes
const logCompleted = (res) => console.log(`Promise completed, '${res.config.url}'`)

function getChannels() {
  return axios.get("https://reqres.in/api/users?page=1&delay=5").then(logCompleted)
}
function getContacts() {
  return axios.get("https://reqres.in/api/users?page=2").then(logCompleted)
}
function getEventActions() {
  return axios.get("https://httpbin.org/status/401").then(logCompleted)
}

Promise.config({ cancellation: true }); // Bluebird config
window.Promise = Promise; // axios promises are now Bluebird flavor

const promises = [getChannels(), getContacts(), getEventActions()];
Promise.all(promises)
  .then(([channels, contacts, eventActions]) => {
    console.log('Promise.all.then', { channels, contacts, eventActions });
  })
  .catch(err => {
    console.log(`Promise.all.catch, '${err.message}'`)
    promises.forEach(p => p.cancel());
  })
  .finally(() => console.log('Promise.all.finally'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js"></script>

Why does it work
Promise.all() instead of axios.all()
Looking at this old axios issue Remove axios.all and axios.spread #1042 can see

Axios uses Promise.all under the hood...

and this
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
}));

can be replaced with this
Promise.all([getUserAccount(), getUserPermissions()])
  .then(function ([acct, perms]) {
    // Both requests are now complete
});

so we can switch to working with Promises directly and still have the same functionality.

Promises fail fast
From MDN we see

Promise.all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

so in this pattern
Promise.all(...)
.then(...)
.catch(...);

.catch() will trigger when the first promise fails (contrast to then() which waits until all promises complete).

Composing Promise.all and .cancel()
The pattern is pretty simple, just cancel all the promises in .catch() (which is called on first error).
Ref this question for details Stop other promises when Promise.all() rejects

Substituting Bluebird in Vue store
This is a basic implementation in Vuex.
yarn add bluebird

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import Promise from 'bluebird';
Vue.use(Vuex);

Promise.config({ cancellation: true }); // Bluebird config
window.Promise = Promise; // axios promises are now Bluebird flavor

export default new Vuex.Store({
  actions: {
    fetchData({ dispatch }) {
      function getChannels() {
        return axios.get("https://reqres.in/api/users?page=1&delay=5");
      }
      function getContacts() {
        return axios.get("https://reqres.in/api/users?page=2");
      }
      function getEventActions() {  // 401 - auth error
        return axios.get("https://httpbin.org/status/401");
      }

      const promises = [getChannels(), getContacts(), getEventActions()];
      Promise.all(promises)
        .then(([channels, contacts, eventActions]) => {
          dispatch("channels/setChannels", channels.data, { root: true });
          dispatch("contacts/setContacts", contacts.data, { root: true });
          dispatch("events/setActions", eventActions.data, { root: true });
        })
        .catch(err => {
          promises.forEach(p => p.cancel());
        })
    }
  }
});


text:
Q: Interfaz gráfica con Gtk+ en c Es la primera vez que uso Gtk+ y hasta ahora he hecho mi primera ventana, quisiera saber como poder cambiarle el fondo de esta. ¿Alguna recomendación para aprender Gtk?
    #include <stdlib.h>
    #include <gtk/gtk.h>
    #define WIDTH 1270
    #define HEIGHT 720

    int main(int argc, char *argv[])
    {
        //Definimos una variable de tipo GtkWidget
        GtkWidget *window;

        //Iniciamos la libreria Gtk
        gtk_init(&argc, &argv);

        //Creamos una ventana utilizando la variable del tipo GtkWidge
        //Llamando a la función gtk_window_new
        //El tamaño por defecto es de 200x200
        //Solo toma otro parametro: GTK_WINDOW_POPUP
        window=gtk_window_new(GTK_WINDOW_TOPLEVEL);

        //Coloca el titulo de la ventana
        gtk_window_set_title(GTK_WINDOW(window),"Radio");

        //Dimensionar la ventana
        gtk_window_set_default_size(window, WIDTH, HEIGHT);

        //Posicion de la ventana
        //Puede tomar estos valores
        //GTK_WIN_POS_NONE
        //GTK_WIN_POS_CENTER
        //GTK_WIN_POS_MOUSE
        //GTK_WIN_POS_CENTER_ALWAYS
        gtk_window_set_position(window,GTK_WIN_POS_CENTER );

        //Mostramos la ventana con la función gtk_widget_show
        gtk_widget_show(window);

        //Coloca a la ventana en un ciclo donde intercepta eventos
        gtk_main();
        return 0;
    }

A: Creo que es sencillo. Primero define el color que quieras:
//color rojo
GdkColor color;
color.red = 0xffff;
color.green = 0;
color.blue = 0;

Modificamos la ventana (gtk 2):
gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &color);

Si tienes la versión 3+ (documentación):
gtk_widget_override_background_color(window, GTK_STATE_NORMAL, &color);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why my Firebase addvalueEventlistener won't get called? Currently, I am writing a social media app, and now I would like to retrieve the datas from my firebase database, where each user has some ratings. mUploads - it stores the uploaded items (photo, name, city, ID).
mDatabaseRef-ratings - it stores the ratings of the uploaded items, (some items don't have ratings yet). They have the same ID, just like in the mUploads->ID
It's actually a big project, and I have retrieved multiple times other type of firebase elements, but this time the addvalueventlistener won't get called, and I couldn't figure it out. Why?
It's not the whole code, but the main part is this. I tried to several ways, but nothing helped. I tried call it not only in this adapter class, but also in my other class, where I retrieve the data for the mUploads list.
...
public class ProfileAdapter extends RecyclerView.Adapter<ProfileAdapter.ImageViewHolder> implements Filterable {
    private Context mContext;
    private List<Upload> mUploads;
    private List<Upload> exampleListFull;
    private OnNoteListener mOnNoteListener;
    private ArrayList<Ratingsclass> mratings_array;
    public float sumofstars, numofratings, defaultstars;
    private DatabaseReference mDatabaseRef_ratings;

    public ProfileAdapter(Context context, List<Upload> upload, OnNoteListener onNoteListener){//, ArrayList<Ratingsclass> ratinglist){
        mContext=context;
        mUploads=upload;
        exampleListFull=new ArrayList<>(upload);
        mOnNoteListener=onNoteListener;

        for (int i = 0; i < mUploads.size(); i++){
            mDatabaseRef_ratings = FirebaseDatabase.getInstance().getReference("ratings");
            Log.d("myTag", "loop");
            /*checking if child already exists*/
            mDatabaseRef_ratings=mDatabaseRef_ratings.child(mUploads.get(i).getKey());
            Log.d("myTag", "ez az id: "+ mUploads.get(i).getKey());

            final int finalI = i;
            mDatabaseRef_ratings.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.getValue() == null) {
                        // The child doesn't exist
                        Log.d("myTag", "has no rating");
                    }else{
                        mDatabaseRef_ratings = FirebaseDatabase.getInstance().getReference("ratings").child(mUploads.get(finalI).getKey());
                        Log.d("myTag", "checking the elements of this child");
                        mDatabaseRef_ratings.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                Ratingsclass temp = new Ratingsclass();
                                numofratings = 0;
                                sumofstars = 0;
                                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                                    temp = postSnapshot.getValue(Ratingsclass.class);
                                    numofratings += 1;
                                    sumofstars += temp.getNum_of_stars();
                                    Log.d("myTag", numofratings + " es " + sumofstars);
                                }
                                if (numofratings == 0)
                                    defaultstars = 0;
                                else
                                    defaultstars = sumofstars / numofratings;
                                temp.setRatingid(mUploads.get(finalI).getKey());
                                temp.setRating_sum(defaultstars);
                                mratings_array.add(temp);
                            }

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

                            }
                        });
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    //
                }
            });

        }

    }

... etc

A: If you pass a listener to the constructor of your adapter onNoteListener you should be listening in your activity/fragment for changes that this interface does.
In your code, inside your adapter you use
mOnNoteListener=onNoteListener;

but you never call the interface to send the values to your view (inside onDataChange(...))
so, what you need to do to get these values is to call your interface to send these values to your view
so, after you fetch the data in Firebase use your callback
mOnNoteListener.yourMethod(your_value);

A: I could manage to solve, with the help of another topic. I just added this code:
mDatabaseRef_ratings.child("ratings").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (final DataSnapshot entrySnapshot : dataSnapshot.getChildren()) {
                    alreadyrated=false;
                    for (DataSnapshot propertySnapshot : entrySnapshot.getChildren()) {
                        Log.d("myTag", entrySnapshot.getKey() + " : " + propertySnapshot.getKey());

... etc
This double for loop is enough to get the id of the parent and the id of the child too, so now my rating app is working.


text:
Q: Uncountable noun becoming countable Can a word like violence, which is an uncountable noun, be made countable? For example, there are different types of violence such as physical violence, emotional violence, etc. In this instance, would violence be countable?

A: The brief answer is "yes", but this has to be qualified by a historical viewpoint.
There are many references to "these violences" in the period before the 20th Century. The use of the phrase declined thereafter and occurs little now.
Here is ngram's graph:

One of many secular examples:

Description of America
The French persisting in their claims to the country on the Ohio, as part of
Canada, strengthened themselves by erecting new forts in its vicinity, and at length began to seize and plunder every British  trader found on any part of that river. Repeated complaints of these violences being made to the Governor of Virginia, it was at length determined to send a suitable person to the French commandant near the Ohio …

One of many religious examples:

Scarce and Valuable Tracts (1751)
These Violences were done all Scotland over , in such Places where the Presbyterians were absolute Masters , but with best Success upon the South Side of the River of Forth.

and a contemporary example:

Social Work in a Globalised World
These violences care not for national boundaries and also tend to most affect those who are already the most deprived.

This all suggests that, although a little archaic, you might be justified in listing the sorts of violence (physical, emotional, financial, institutional, wartime and so forth) and then writing similar prose on the lines of "These violences constitute an affront to humanity".

A:
Can a word like violence, which is an uncountable noun, be made countable?

There are very few words that are only uncountable and probably none that are only countable. Uncountability / countability is usually, (but not always) an attribute of nouns within context. And that attribute may be present or not.


text:
Q: AspectJ - exclude inner classes from within clause I have a marker interface which has several implementations. My intention is to add an aspect for all public methods defined in any class implementing that marker interface.
I defined my aspect as follows:
@Around("within(x.y.z.MyInterface+) && execution(public * *(..))")

The problem is that this also catches inner classes, for example consider this method in one of the classes implementing that interface:
public void foo() {
  doSomething(new Request() {
    @Override
    public void do() {
      System.out.println("Hi");
    }
  });
}

For some reason, the aspect also catches that "do()" method, even though it is does not inherit from MyInterface.
How should I fix my aspect definition?

A: Instead of "within" use the "this" pointcut:
@Around("this(x.y.z.MyInterface+) && execution(public * *(..))")

Basically "this" matches joinpoints where this, the current object reference at the time, is an instance of MyInterface. Anonymous classes not implementing your interface will no longer match.
JavaWorld has a nice article on it:
http://www.javaworld.com/article/2074048/core-java/i-want-my-aop---part-2.html?page=2


text:
Q: How to maintain relation between MySQL tables downloaded via SQOOP to Hive I have an ETL pipeline that downloads multiple tables from MysqlRDS and runs hive ETL's on the top of this data. But I noticed an issue with the downloaded data. As the tables are being downloaded individually the relation between the tables was not being maintained. Is there a feature in SQOOP that allows the relationship between multiple tables to be maintained.

A: You can see the data lineage using Apache Atlas.


text:
Q: How to define resolver for dependencies from custom repository on GitHub? Play 2.3 and sbt 0.13.5 for some reason following from play's build.sbt isn't recognized. And it's not pulling down this particular dependency. Any idea?
libraryDependencies += "elasticplay" % "elastic-search-module_2.10" % "1.0.0"

resolvers += Resolver.url("My GitHub Repository", url("https://github.com/vikasdp/elasticplay/tree/master/releases/"))(Resolver.ivyStylePatterns)

And it throws the following
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.vikasdp.elasticplay#elastic-search-module_2.10;1.0.0: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
sbt.ResolveException: unresolved dependency: com.vikasdp.elasticplay#elastic-search-module_2.10;1.0.0: not found
at sbt.IvyActions$.sbt$IvyActions$$resolve(IvyActions.scala:217)
at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:126)
at sbt.IvyActions$$anonfun$update$1.apply(IvyActions.scala:125)
at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:115)
at sbt.IvySbt$Module$$anonfun$withModule$1.apply(Ivy.scala:115)
at sbt.IvySbt$$anonfun$withIvy$1.apply(Ivy.scala:103)
at sbt.IvySbt.sbt$IvySbt$$action$1(Ivy.scala:48)
at sbt.IvySbt$$anon$3.call(Ivy.scala:57)
at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:98)
at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:81)
at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:102)
at xsbt.boot.Using$.withResource(Using.scala:11)
at xsbt.boot.Using$.apply(Using.scala:10)
at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:62)
at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:52)
at xsbt.boot.Locks$.apply0(Locks.scala:31)
at xsbt.boot.Locks$.apply(Locks.scala:28)
at sbt.IvySbt.withDefaultLogger(Ivy.scala:57)
at sbt.IvySbt.withIvy(Ivy.scala:98)
at sbt.IvySbt.withIvy(Ivy.scala:94)
at sbt.IvySbt$Module.withModule(Ivy.scala:115)
at sbt.IvyActions$.update(IvyActions.scala:125)
at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1223)
at sbt.Classpaths$$anonfun$sbt$Classpaths$$work$1$1.apply(Defaults.scala:1221)
at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$74.apply(Defaults.scala:1244)
at sbt.Classpaths$$anonfun$doWork$1$1$$anonfun$74.apply(Defaults.scala:1242)
at sbt.Tracked$$anonfun$lastOutput$1.apply(Tracked.scala:35)
at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1246)
at sbt.Classpaths$$anonfun$doWork$1$1.apply(Defaults.scala:1241)
at sbt.Tracked$$anonfun$inputChanged$1.apply(Tracked.scala:45)
at sbt.Classpaths$.cachedUpdate(Defaults.scala:1249)
at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1214)
at sbt.Classpaths$$anonfun$updateTask$1.apply(Defaults.scala:1192)
at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
at sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:42)
at sbt.std.Transform$$anon$4.work(System.scala:64)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:237)
at sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:237)
at sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:18)
at sbt.Execute.work(Execute.scala:244)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:237)
at sbt.Execute$$anonfun$submit$1.apply(Execute.scala:237)
at sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:160)
at sbt.CompletionService$$anon$2.call(CompletionService.scala:30)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:744)
[error] (*:update) sbt.ResolveException: unresolved dependency:    com.vikasdp.elasticplay#elastic-search-module_2.10;1.0.0: not found

Update:
The following output is shown when running activator publishLocal in elastic-search-module project:
  elastic-search-module vpandya$ activator publishLocal
  [info] Loading project definition from /Users/vpandya/elastic-search-module/project
  [info] Set current project to elastic-search-module (in build   file:/Users/vpandya/elastic-search-module/)
 [info] Wrote /Users/vpandya/elastic-search-module/target/scala-2.10/elastic-  search-module_2.10-1.0.0.pom
 [info] :: delivering :: elasticplay#elastic-search-module_2.10;1.0.0 :: 1.0.0 :: release    :: Mon Aug 04 12:25:50 EDT 2014
 [info]     delivering ivy file to /Users/vpandya/elastic-search-module/target/scala-2.10/ivy-1.0.0.xml
 [info]     published elastic-search-module_2.10 to   /Users/vpandya/.ivy2/local/elasticplay/elastic-search-module_2.10/1.0.0/poms/elastic-search-  module_2.10.pom
 [info]     published elastic-search-module_2.10 to /Users/vpandya/.ivy2/local/elasticplay/elastic-search-module_2.10/1.0.0/jars/elastic-search-module_2.10.jar
 [info]     published elastic-search-module_2.10 to /Users/vpandya/.ivy2/local/elasticplay/elastic-search-module_2.10/1.0.0/srcs/elastic-search-module_2.10-sources.jar
 [info]     published elastic-search-module_2.10 to /Users/vpandya/.ivy2/local/elasticplay/elastic-search-module_2.10/1.0.0/docs/elastic-search-module_2.10-javadoc.jar
 [info]     published ivy to /Users/vpandya/.ivy2/local/elasticplay/elastic-search-module_2.10/1.0.0/ivys/ivy.xml
 [success] Total time: 0 s, completed Aug 4, 2014 12:25:50 PM

Running sbt "show projectId" on elastic-search-module shows the following:
elasticplay:elastic-search-module:1.0.0

Update 2
running sbt "show libraryDependencies" "show resolvers" in elasticplay module shows the following:
[info] List(org.scala-lang:scala-library:2.10.3, org.elasticsearch:elasticsearch:1.3.0,   org.scalatest:scalatest:2.1.5:test, org.scalacheck:scalacheck:1.11.3:test, org.scalatestplus:play:1.0.0:test, org.scalaz:scalaz-core:7.0.6)
[info] List()

A: tl;dr GitHub serves raw files from https://raw.githubusercontent.com (not https://github.com/) so resolvers should use the URL.
You've defined a Maven repository, but have a Ivy2 directory layout inside.
Change your repository layout to a Maven one - com/vikasdp/elasticplay/elastic-search-module_2.10/1.0.0 and place elastic-search-module_2.10-1.0.0.jar inside.
You can alternatively change the new resolver to an Ivy2 one with Resolver.ivyStylePatterns so it becomes - please note the URL https://raw.githubusercontent.com:
val url = url("https://raw.githubusercontent.com/vikasdp/elasticplay/master/releases")

resolvers += Resolver.url("My GitHub Repository", url)(Resolver.ivyStylePatterns)

See Resolvers in the official documentation of sbt.
With the build definition, sbt could resolve the dependency:
libraryDependencies += "elasticplay" % "elastic-search-module_2.10" % "1.0.0"

When you hit the issue that manifests itself as invalid sha1 use the following to disable the verification of the checksums of the downloaded file(s) with the following:
checksums in update := Nil

See Checksums in the official documentation of sbt.


text:
Q: Which SE website should I ask my question about a web design framework on? I would like a site recommendation. I want to ask a question about how to use Bootstrap 5 (a Web design framework) to implement a type of web page design. In other words, about how to use Bootstrap 5 in a common but undocumented way.
I thought that Web Applications would be the right place, but I can't find any relevant tags, and at least one is required. I guess that Bootstrap 5 is not considered an App.
I posted on Super User, but it closed the question as off-topic.
I've searched through the tags AND the list of SE websites and cannot find the proper place to post my question. Perhaps it doesn't fit anywhere in what SE has been used for so far? If this is the case, should I create a new SE site about Web Design, or perhaps Web Frameworks?

A: The problem might not be the topic itself; Stack Overflow has plenty of questions about Bootstrap 5. But the Stack Exchange network is most suitable for questions like 'I'm using [framework X] to achieve [objective Y] but I'm running into [problem Z]'. Just asking 'I'm using [framework X], how can I achieve [objective Y]' is too broad, and searching for the right site or proposing a new Stack Exchange site in Area 51 won't help.
(In particular, WebApps.SE is about using web applications, not developing/designing them; check their Help Center.)


text:
Q: Should I upload intel from Mass Effect Infiltrator immediately, or wait until I need the Galactic Readiness? I bought Mass Effect: Infiltrator to help ease ME3 single player.  Is there any advantage to uploading intel as I get it?  I know that uploading it early means that my readiness will slowly drain away, but I'm wondering if uploading a bunch at a time decreases the bang per buck, so to speak.  Also, does holding onto intel decrease its effectiveness at improving Galactic Readiness?

A: Other posts seem to indicate that readiness delays at a rate of 3% per day.  My own experiences roughly confirm this.
This means that if you don't play multiplayer for a day, you will need to collect another 12 intel in the iOS game (4 intel per 1% readiness) simply to get yourself back in the position you were in prior to taking the day off.
Since it will never go below 50% and holding onto it does not decay its value, I would recommend holding them until just prior to starting Assault the Illusive Man's Base.

A: Upload it straight away...
This is because if you play a multiplayer game, only 1 game is needed, the readiness doesnt drain for that day, i also think the same applies if 2 Intels are imported from MEI as this would equal 1% and aslong as you gain readiness in a day it won't degrade.
I would personally play multiplayer to nullify the degradation as it is fun plus you gain something like 4% per Bronze completion (with deaths)


text:
Q: Why does $(I-T)S_k-I$ equal $I-T^{k+1}-I$? Consider a Banach space, $X$, and $T\in\mathcal B(X)$ where $\|T\|\lt1$. Take as well that $S=\sum_{n=0}^\infty T^n$ so that it's $k$th partial sum is given by $S_k=\sum_{n=0}^k T^n$. Suppose as well that $\{S_k\}$ converges to $S$ in $B(X)$.
Why is it that,
$$(I-T)S_k-I=I-T^{k+1}-I$$
and not that,
$$(I-T)S_k-I=S_k-T^{k+1}-I\,?$$
(This is part of the proof of the Neumann series theorem, which says that under the above conditions, $I-T$ is an invertible operator and it's inverse is given by $\sum_{n=0}^\infty T^n$).

A: I'm going to write in lowercase.
\begin{align}
(1-t)s_k  - 1
&= s_k - ts_k - 1 \\
&= 1 + t + \ldots + t^k- t(1 + t + \ldots + t^k) - 1 \\
&= 1 + t + \ldots + t^k- (t + t^2 + \ldots + t^{k+1}) - 1 \\
&= 1 + t + \ldots + t^k- t - t^2 + \ldots - t^{k+1} - 1 & \text{cancel common terms}\\
&= 1  - t^{k+1} - 1.
\end{align}


text:
Q: All Office 365 programs go unresponsive after a short amount of time I have installed Microsoft Office 365 ProPlus on Windows 10.  I had quite a bit of difficulty with this installation, the process would always fail with a 30015-11 error, though the program would show as installed in the Control Panel.  After doing a repair operation through control panel, Office "works"
What I mean is that all Office programs will work for a few minutes, and then go unresponsive.  Restarting them makes them work again, but this is not reasonable.
This version of office apparently relies on "Click to Run" architecture and there are multiple Office Click to Run processes running at all times (even when I have no office programs open)
How do I fix this problem?

A: It sounds like a corrupt installation.  Try uninstalling and reinstalling and see if it resolves your issue.
If you have other versions of Microsoft Office installed, I would uninstall those first before reinstalling.  I've had trouble with having multiple installations of Microsoft Office on the same machine before.


text:
Q: In R, transform a character string into an operation If I have a character vector, how can I tell R to execute it as a command?
Simple example:
> a <- paste("2", "+", "3")

>a

>[1] "2 + 3"

I would like R to actually do 2+3, and not just print the content of "a".

A: The way to do it is
a <- paste("2", "+", "3")
eval(parse(text = a))

But, in general, it's not a great idea. There's usually a better way to do what you're trying to do.
> require(fortunes)
> fortune("parse")

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

There's lots of info on why eval(parse()) is considered a "bad practice" in the answers to What specifically are the dangers of eval(parse())?; in summary it is

*

*bug-prone

*harder to debug

*usually there's a more readable way to do whatever you're trying to do

*can pose a security risk
(though that last one probably doesn't apply for most R use cases)

A: eval(parse(text=paste("2", "+", "3")))


text:
Q: Problem on Hooking Keyboard Messages using SetWindowsHookEx I 'm trying to hook on Keyboard Messages without any success.
I create a test console win32 app:
int _tmain(int argc, _TCHAR* argv[])
{
HOOKPROC hHookProc;
HINSTANCE hinstDLL;
HHOOK hHook;

hinstDLL = LoadLibrary(TEXT("pathtodll\\KeyHook.dll"));
hHookProc= (HOOKPROC)GetProcAddress(hinstDLL, "HookProc");

hHook = SetWindowsHookEx(
    WH_KEYBOARD,
    hHookProc,
    hinstDLL,
    0);

    while (1) {}

return 0;
}

I've also created a test win32 dll with the HookProc function:
extern __declspec(dllexport) LRESULT CALLBACK HookProc(
  int nCode,
  WPARAM wParam,
  LPARAM lParam
)
{
   // process event
   //...
     MessageBox( NULL,
                TEXT("OK"),
                TEXT("OK"),
                MB_OK);

   return CallNextHookEx(NULL, nCode, wParam, lParam);
}

Everything compiles fine but when I'm trying to debug, it seems that HookProc is never called. Actually in Win 7 the app hangs when i press any key, while in Win Xp HookProc is not called. I do get not NULL hinstDLL, hHookProc, hHook.
What am I misssing?

A: Instead of performing a blank while loop after calling SetWindowsHookEx(), try having the loop pump the calling thread's message queue instead, via Peek/GetMessage(). Some hooks run in the context of the thread that installs them, so the OS has to be able to switch to that thread when needed.

A: Couple of issues here:
while (1) {}

Don't do this: your code now has a busy (infinite) loop that will effectively make the app unresponsive (and probably make the whole desktop seem sluggish too). The reason that GetMessage works here is simply because it hands control back to the OS, which will put the thread to sleep instead of running busily. You'll probably get the same effect just by calling Sleep(...), which will also return control back to the OS but without pumping messages. For test code, something like getchar() can work well here, it will gracefully block till you hit Enter in the console window. MessageBox() can also work here.
extern __declspec(dllexport) LRESULT CALLBACK HookProc(
{
  MessageBox( NULL,
            TEXT("OK"),
            TEXT("OK"),
            MB_OK);

Another problem: you generally never want to do anything 'complex' in a hook callback - just do the bare minimum to process the message, and return ASAP. You certainly don't ever want to block, which is what MessageBox does. For debugging purposes, OutputDebugString() or some other debug-oriented API that doesn't block is the way to go.


text:
Q: Use a dto as parameter in a native jpa query I have the following query in JPA, where I want to pass the EntityKey instead of multiple parameters to the method and use it in the where clause:
    @Query(value = "UPDATE #{#entityName} SET counter=counter+1 " +
            "WHERE id1=:key.id1 AND id2=:key.id2", nativeQuery = true)
    @Modifying
    fun incrementCounter(@Param("key") key: EntityKey)

Unfortunately the code above doesn't work and I get a Named parameter not bound : key.id1 exception.
Is it possible to pass and use a Dto in the query instead of multiple parameters?

A: One Option is to use none native queries:
    @Query(value = "UPDATE MyEntity e SET e.counter=e.counter+1 " +
            "WHERE e.id=:key")
    @Modifying()
    fun incrementCounter(@Param("key") key: EntityKey)

A: With SpEL, you can access nested parameter attributes with :#{#param.attribute} resulting in :
@Query(value = "UPDATE #{#entityName} SET counter=counter+1 " +
            "WHERE id1=:#{#key.id1} AND id2=:#{#key.id2}")
@Modifying
fun incrementCounter(@Param("key") key: EntityKey)


text:
Q: Does encrypt time less than decrypt time in RSA cryptograohy? I going to do implementation RSA cryptography. I want know . How many times encryption faster than decryption in RSA cryptography. I try compute elapsed time in java by use System.currentTimeMillis(); but give me time encrypt = 0.05 ms while time decrypt 0.55 ms mean from that 1:11. I think this result is not rational my code is the follow
//here my key has 256 bits
 for (;;) {
            long begin = System.currentTimeMillis();

            for (int i = 0; i < num; i++) {

            decrypt();
            }

            long end = System.currentTimeMillis();

            long time = end - begin;

            if (time >= 10000) {
                System.out.printf("Average Encryption takes: %.2f ms\n",
                        (double) time / num);
                break;
            }

            num *= 2;
        }

p = BigInteger.probablePrime(128, random);
q = BigInteger.probablePrime(128, random);
N = (p.subtract(one)).multiply(q.subtract(one));
e = BigInteger.probablePrime(32, random);
d = e.modInverse(N);

private void encrypt()
{
    C= M.modPow(e,N);
}

private void decrypt()
{
    RM = C.modPow(d, N);
}

please any explanation for these results

A: Please, don't implement RSA yourself, it is very easy to do it wrong and it takes months to write version which will be resistant to 3-4 older cryptographic attacks.
All the crypto code you've ever written is probably broken -- Tony Arcieri
RSA encryption is more difficult. The 'best practice' in implementing RSA is: don't implement RSA. Other people have done it better than you can. -- Matthew Green (Johns Hopkins University)
Why Cryptography Is Harder Than It Looks -- Bruce Schneier, 1997:

Most systems are not designed and implemented in concert with cryptographers, but by engineers who thought of cryptography as just another component. It's not.

In industrial implementations of RSA, encrypting using someone's public key is faster then decrypting using private key, because public key has short public exponent e, usually 65537 (0x10001). This is true, when fast exponentiation is used (method named Exponentiation_by_squaring). Time of this operation depends linearly on bit length and  linearly on 1 bits count in exponent's value, both length and count are small for 65537 (17 bit length and 2 bits are in state 1).
In your pseudocode of RSA-like operation, e is 32 bit and it is usually shorter than d, therefore operation using e exponent is faster than same with d.


text:
Q: image disappears in CSS. Background & Logo The basis for my homepage seemed finished when I altered a couple of the headings. Next thing I know, the banner/background image at the top has vanished as well as the logo that sits above it.
I'm pretty sure it's an issue with regards to the CSS. Yet, I can't see what I have changed that has caused this problem. Any help would be appreciated.
UPDATE: I've got the background image back now after utilising HTML images instead of CSS. I altered the z-index on the banner to 0 and this then displayed the banner. So naturally I have the header (white box) as z-index: 1 and the logo as z-index: 2.
So if it was all linked to the z-index then in theory my logo and header box should display above the banner now. Yet, they're still missing.

@fontface {
    font-family: Swisz;
    src: url(fonts/swisrg.ttf);
}
@fontface {
    font-family: Swiszt
    src: url(fonts/swist.ttf);
    font-weight: thin;
}

body, html {
    background-color: #d83030;
    margin: 0;
    padding: 0;
}
/* the first missing images is the background of the banner container below */
#container {
    position: fixed;
    top: 0px;
    left: 0px;
    background-image: url:"images/banner.jpg";
    min-height: 100%;
    min-width: 1024px;

    width: 100%;
    height: auto;

    content: 60px;
    padding: 0px;
    border: 5px #73008C;
    margin-left: 0px;
    margin-right: 0px;
    z-index: -3;
}

#header {
    position: static;
    background-color: rgba(255, 255, 255, 0.4);
    width: 100%;
    height: 12%;
    margin: auto;
    z-index: 1;
}
/*as well as the logo that can be found in the HTML*/
#logo {
    position: relative;
    border: 0px;
    margin-top: 9px;
    z-index: 2;
}

#nav01 {
    position: absolute;
    background-color: #374754;
    width: 100%;
    height: 40px;
    padding: 0px;
    margin-left: 0px;
    margin-top: 85px;
    margin-right: 0px;
    border-radius: 0px 0px 6px 6px
}

ul#menu {
    font-family: "Swisz";
    position: relative;
    background-color: #374754;
    padding: 0;
    margin-top: 13px;
    margin-right: 0px;
    margin-left: 0px;
    margin-bottom: 0px;
}

ul#menu li {
    display: inline;
    margin-right: 5px;
}

ul#menu li a {
    background-color: #374754;
    padding: 10px 10px;
    text-decoration: none;
    color: #ffffff;
    border-radius: 4px 4px 4px 4px;
}

ul#menu li a:hover {
    color: white;
    font-style: bold;
    background-color: #d83030;
}

#overlay {
    font-family: "Swisz";
    position: relative;
    margin-left: auto;
    margin-right: auto;
    top: 250px;
    bottom: 200px;
    width: 30%;
    height: 30%;
    background-color: #d83030;
    padding: 15px 15px;
    color: #ffffff;
    border-radius: 8px 8px 8px 8px;
}

#info {
  position: relative;
  padding-left: 450px;
  top: 410px;
}

body {
    font-family: "Swisz", Helvetica;
    font-size: 12px;
    background-color: #ffffff;
    color: #ffffff;
    text-align: center;
    padding: 0px;
}

#main {
    position: absolute;
    top: 800px;
    padding: 0;
    width: 100%;
    background-color: #d83030;
    margin: 0;
}

h1 {
    text-align: center;
    font-size: 26pt;
}

h2 {
    font: "Swiszt";
    font-variant: "thin";
    color: #ffffff;
    text-align: center;
    font-size: 14pt;
}

h4 {
    font-family: Swisz;
    color: #374754;
    text-align: center;
}

h5 {
    font-family: Helvetica, sans-serif;
    color: #374754;
    text-align: center;
    font-size: 16px;
}

#sub {
    position: relative;
    color: #374754;
    top: 920px;
    background-color: #ffffff;
    padding: 0;
    margin: 0;
    size: 40;
}

#hiddenbox {
    position: relative;
    width: 100%;
    height: 298px;
    background-image: url("hidden_bg.jpg");
    background-repeat: repeat-x;
    padding: 0;
    margin: 0;
    color: #ffffff;
}

p {
    margin-left: 200px;
    margin-right: 200px;
}

.pagedown {
    position: relative;
    width: 100%;
    padding-top: 0;
    margin: 0;
}

#footer {
    position: relative;
    color: #ffffff;
    margin-bottom: 0px;
    margin-top: 100px;
}
<!DOCTYPE html>

  <title>SITE- This is our website</title>
  <link href="Site.css" rel="stylesheet">

/* the logo is below*/

SPECTACULAR BIG HEADING

THE FUTURE IS HERE

WELCOME TO WEBSITE

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut turpis sapien. Proin tempus nibh ac rhoncus congue. Nullam pretium placerat vestibulum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed sed est vitae libero placerat tristique. Aliquam pulvinar convallis mi, vitae consequat tortor pellentesque ut. In lacinia, ex vel accumsan viverra, est ex efficitur justo, pulvinar luctus mi leo nec risus. Sed nec tellus bibendum, convallis enim at, elementum lectus. Fusce eu enim blandit, volutpat eros lobortis, auctor odio. Praesent tristique sem elit, nec consequat tortor placerat at.

  <p2>Open up new business avenues</p2>

  <p2>Review your acquisitions</p2>

  <p2>Monitor events</p2>

 How It Works

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ut turpis sapien. Proin tempus nibh ac rhoncus congue. Nullam pretium placerat vestibulum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed sed est vitae libero placerat tristique. Aliquam pulvinar convallis mi, vitae consequat tortor pellentesque ut. In lacinia, ex vel accumsan viverra, est ex efficitur justo, pulvinar luctus mi leo nec risus. Sed nec tellus bibendum, convallis enim at, elementum lectus. Fusce eu enim blandit, volutpat eros lobortis, auctor odio. Praesent tristique sem elit, nec consequat tortor placerat at. Nullam eu arcu et ex iaculis feugiat ut quis enim. Nulla quis libero placerat, accumsan nulla et, laoreet magna. Sed congue ut nunc maximus gravida.

A: Your code:
background-image: url:"images/banner.jpg";

Correct code:
background-image: url("images/banner.jpg");


text:
Q: Late binding calling to a c# DLL from a vb.net DLL I know the question above is possible as seen here, but I am struggling to understand why it is failing in my application.
I have a vb.net dll that is calling a c# dll. This is a third party dll so I have no control over it. I know it is written and compiled to .net 4.5.
If I write a simple .net 4.5 application in vb.net and late call the dll everything is working fine. The instance is created and I can make calls to the methods.
        Dim comType = Type.GetTypeFromProgID("MyDLL.MyClass", True)
        _comObject = Activator.CreateInstance(comType)

However if I make the same calls from the vb.net dll it give me the error when I try to create the instance

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.SEHException: External component has thrown an exception.
     at DesktopApi.Native.PInvoke.Init()
     at DesktopApi.DesktopApi..ctor()
     --- End of inner exception stack trace ---
     at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
     at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
     at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
     at System.Activator.CreateInstance(Type type, Boolean nonPublic)
     at System.Activator.CreateInstance(Type type)

Option Strict is off, Option Explicit is On. It is compiling to a target cpu of x86. These options are no different to the simple application I created.
Anyone any ideas? I have searched the net but not finding anything. The infuriating thing is that all this used to work until a update from the supplier. And because it works in the simple application they are not really interested.


text:
Q: Rewrite Jquery fadeIn() to use CSS3 transitions Is there a way to just rewrite the JQuery fadeIn() and fadeOut() functions to use CSS3 Transitions when the browser supports it.
I'm using jquery transit for all other animations and I'm more comfortable with the fadeIn and fadeOut functions of Jquery but they don't run as well.
Here's a link to the site I'm working on
eg;
if(CSS3TransitionsAvailable){

$.fn.fadeIn() = function(this, speed, callback){

//Fade this in Using CSS3 Transistions
}

}

Thanks

A: If you want to replace jQuery's fadeIn and fadeOut functions with jQuery Transit, you could do something like this:
$.fn.fadeOut = function(speed, callback)
{
    var transitionSpeed = typeof (speed) == "undefined" ? 1000 : speed;
    $(this).transition({opacity: 0 }, transitionSpeed, callback);

};

$.fn.fadeIn = function(speed, callback)
{
    var transitionSpeed = typeof (speed) == "undefined" ? 1000 : speed;
    $(this).transition({opacity: 1 }, transitionSpeed, callback);

};

$("div").on("click", function ()
{
    //Fade out for 4 seconds, then fade in for 6 seconds
    $(this).fadeOut(4000, myCallBackFunction);
});

function myCallBackFunction ()
{
        $(this).fadeIn(6000);

}

JS Fiddle Demo
It's not perfect, but you can tweak it to your liking.

A: Take a look at this plugin. It might help you.


text:
Q: VB.Net Threading and Saving Results I'm working on the program for work, where the user is able to search AD for a asset tag of a certain computer.  If it is found it will give them a list in a listbox.  I have all of that working, but when they do the search the UI freezes.  I'm new to VB and OO for that matter.  I understand that it is freezing because the search is running on the same thread as the UI, but I cannot for the life of me get another thread to do the work.  When I tried to do the search in another thread I can't update the listbox because its not on the same thread.  Any help would be greatly appreciated.
Function that searches AD:
   Private Function searchAd()

    'clear the results from previous entries
    ' AdResultListBox.Items.Clear()

    Try
        Dim rootEntry As New DirectoryEntry("GC://mydomaininfo")
        Dim searcher As New DirectorySearcher(rootEntry)

        'selects the Computer Name property
        searcher.PropertiesToLoad.Add("cn")

        Dim compname As String = PropertyTagTextbox.Text
        'searches using wildcards
        compname = "*" + compname + "*"

        searcher.Filter = "(&(name=" + compname + ")(objectcategory=moreADinformation))"

        Dim results As SearchResultCollection
        results = searcher.FindAll()

        Dim result As SearchResult

        For Each result In results

            'this is the part i'm having trouble with
            Me.AdResultListBox.Items.Add(result.Properties("cn")(0)

        Next

    Catch ex As Exception

    End Try
End Function

Private Sub ADSearchButton_Click(sender As Object, e As RoutedEventArgs) Handles ADSearchButton.Click
    AdResultListBox.Items.Clear()

    'create the new thread for searching
    Dim SearchThread As New Thread(AddressOf searchAd)
    SearchThread.Start()
End Sub

A: There happens to be an MSDN article "Using System.DirectoryServices to Search the Active Directory" which shows running it in another thread at http://msdn.microsoft.com/en-us/library/ms973834.aspx#dotnetadsearch_topic9.

A: This is how I typically do it. The Invoke function is part of the control and that passes a delegate to the UI thread so it can be processed in the correct thread.
Invoke(Sub
          Me.AdResultListBox.Items.Add(result.Properties("cn")(0)
    End Sub)

http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx


text:
Q: Using a fragment to display user installed apps In the android app I am creating, I have a scrollable tabs from my TabsPagerAdapter class which extends FragmentPagerAdapter. However, in my app, I am trying to display all user installed apps on the phone into a section of a tab. However the class which was able to return all of that extended FragmentActivity.
I tried to follow this, but it is not working.
How to list all downloaded android apps in a fragment
Sadly, after much research I found out that I can only put fragments in different tabs and only have one Activity displayed at any one time and the tabs themselves can only return Fragments.
I really need to put all the user installed apps into a Fragment in this case I guess but I am unsure how to implement this...I have an Adapter class and everything.
Here is my InstalledAppActivity class which extends FragmentActivity to return all user downloaded apps.
    package com.spicycurryman.getdisciplined10.app;

    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.ActivityNotFoundException;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.ApplicationInfo;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListView;
    import android.widget.Toast;

    import com.javatechig.listapps.ApplicationAdapter;

    import java.util.ArrayList;
    import java.util.List;

    public class InstalledAppActivity extends FragmentActivity {
        private PackageManager packageManager = null;
        private List<ApplicationInfo> applist = null;
        private ApplicationAdapter listadaptor = null;

        ListView InstalledAppList;

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

            InstalledAppList = (ListView) findViewById(R.id.Installed_List);
            packageManager = getPackageManager();
            new LoadApplications().execute();

            InstalledAppList.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    ApplicationInfo app = applist.get(i);
                    try {
                        Intent intent = packageManager
                                .getLaunchIntentForPackage(app.packageName);

                        if (null != intent) {
                            startActivity(intent);
                        }
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(InstalledAppActivity.this, e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        Toast.makeText(InstalledAppActivity.this, e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                }
            });
        }

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            packageManager = getPackageManager();
            new LoadApplications().execute();
            return inflater.inflate(R.layout.installed_apps, container, false);

        }

        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.block, menu);

            return true;
        }

        public boolean onOptionsItemSelected(MenuItem item) {
            boolean result = true;

            switch (item.getItemId()) {
                case R.id.main_text: {
                    displayAboutDialog();

                    break;
                }
                default: {
                    result = super.onOptionsItemSelected(item);

                    break;
                }
            }

            return result;
        }

        private void displayAboutDialog() {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.app_name));
            builder.setMessage(getString(R.string.slogan));

            builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
                    startActivity(browserIntent);
                    dialog.cancel();
                }
            });
            builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

            builder.show();
        }
  private AdapterView.OnItemClickListener OnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
            protected void onListItemClick(ListView InstalledAppList, View v, int position, long id) {
                ApplicationInfo app = applist.get(position);
                try {
                    Intent intent = packageManager
                            .getLaunchIntentForPackage(app.packageName);

                    if (null != intent) {
                        startActivity(intent);
                    }
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(InstalledAppActivity.this, e.getMessage(),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(InstalledAppActivity.this, e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            }

        };
        private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
            ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
            for (ApplicationInfo info : list) {
                try {
                    if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
                        applist.add(info);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return applist;
        }

        private class LoadApplications extends AsyncTask<Void, Void, Void> {
            private ProgressDialog progress = null;

            @Override
            protected Void doInBackground(Void... params) {
                applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
                listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
                        R.layout.snippet_list_row, applist);

                return null;
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
            }

            @Override
            protected void onPostExecute(Void result) {
                //setListAdapter(listadaptor);
                InstalledAppList.setAdapter(listadaptor);
                super.onPostExecute(result);
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
            }
        }
    }

A: Here is an example of how you would do it:
package com.spicycurryman.getdisciplined10.app;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ibc.android.demo.appslist.app.ApkAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class InstalledAppActivity extends Fragment
        implements OnItemClickListener {

//hi

    PackageManager packageManager;
    ListView apkList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        setHasOptionsMenu(true);
        View rootView = inflater.inflate(R.layout.user_installed, container, false);
        packageManager = getActivity().getPackageManager();

        /*To filter out System apps*/

        apkList = (ListView) rootView.findViewById(R.id.applist);

        new LoadApplications(getActivity().getApplicationContext()).execute();

        return rootView;
    }

    /**
     * Return whether the given PackageInfo represents a system package or not.
     * User-installed packages (Market or otherwise) should not be denoted as
     * system packages.
     *
     * @param pkgInfo
     * @return boolean
     */
    private boolean isSystemPackage(PackageInfo pkgInfo) {
        return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
                : false;
    }

    private boolean isSystemPackage1(PackageInfo pkgInfo) {
        return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
                : true;
    }

// Don't need in Fragment
/*@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.block, menu);
   // super.onCreateOptionsMenu(menu,inflater);
}*/

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //ApkAdapter apkAdapter=(ApkAdapter)apkList.getAdapter();

    }

    private class LoadApplications extends AsyncTask<Void, Void, Void> {

        Context mContext;

        private ProgressDialog pDialog;
        List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();

        public LoadApplications(Context context){
            Context mContext = context;
        }

        @Override
        protected Void doInBackground(Void... params) {

            List<PackageInfo> packageList = packageManager
                    .getInstalledPackages(PackageManager.GET_PERMISSIONS);

          /*  List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);

            for(int n = 0;n<list.size();n++){
                if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
            }*/

            for(PackageInfo pi : packageList) {
                boolean b = isSystemPackage(pi);
                boolean c = isSystemPackage1(pi);

                if(!b || !c ) {
                    packageList1.add(pi);
                }
            }

            //sort by application name

            final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);

            Collections.sort(packageList1, new Comparator<PackageInfo>() {
                @Override
                public int compare(PackageInfo lhs, PackageInfo rhs) {
                    return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
                }
            });

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
            pDialog.setMessage("Loading your apps...");
            pDialog.show();

        }

        @Override
        protected void onPostExecute(Void result) {

            apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));

            if (pDialog.isShowing()){
                pDialog.dismiss();

            }

            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }

}

A: way don't you just from youre main activity on click off the tab create a fragment with a listview in it and displays the data list there?? you can pars the list to the fragment bay saying
fragmentclass fragment = new fragmentclass(list);

fragment.show();

if youre having truble understanding fragments you can watch this great tutorial on it especialy the part on inter fragment communication is realy use full


text:
Q: delete rows where id is in a comma delimited string I need to delete all rows where id is in a comma delimited string.
$ids = '1,2,3,4,5';
$sql = "delete from images where id in(:aid)";
$st = $db->prepare($sql);
$st->execute([
    ":aid" => $ids
]);

Result - only one row is deleted.

A: use explode() along with implode()
$st->execute([
    ":aid" => "'".implode("','", explode(",",$ids))."'"
]);

Or use FIND_IN_SET()
$sql = "Delete from images WHERE FIND_IN_SET(`id`, :aid)";
$st = $db->prepare($sql);
$st->execute([
   ":aid" => $ids
]);


text:
Q: Dynamic query with PDO and FIND_IN_SET I'm using PDO to build my queries which rely on FIND_IN_SET to select certain rows. The elements of the set are passed via POST to the server and the query constructed like this:
SELECT * FROM table WHERE
(FIND_IN_SET('param1', column) > 0 OR FIND_IN_SET('param2', column) > 0)

That's, in a basic way, how the queries are constructed. Because the number of parameters to find in the set is dynamic, the FIND_IN_SET part of the query is made dynamically:
$q = implode("', column)>0 OR FIND_IN_SET('", $array);

And then applied to the query, which looks like this:
SELECT * FROM table WHERE
AND (FIND_IN_SET(:q, e.event_type)>0);

And the query eventually executed as:
$countResult->execute(array(':q' => $q);

Note that $q may take the form of:
"param1', column)>0 OR FIND_IN_SET('param2', column)>0 OR FIND_IN_SET('param3"

If I don't use PDO, the query executes correctly, but when using PDO, the query works when there is only one element in the array, but doesn't return any results when the array contains more than one element.
Is the execute method doing something to the parameter possibly?

A: You can use array_map() to create a FIND_IN_SET() expression from each array element, then implode() the results with ' OR ' as glue:
function fis($c) {
  return function($k) {return "FIND_IN_SET(:$k, $c)";}
}

$arr = array(
  'p1' => 'param1',
  'p2' => 'param2'
);
$qry = $dbh->prepare('
  SELECT *
  FROM   table
  WHERE  ('.implode(' OR ', array_map(fis('column'), array_keys($arr))).')
');
$qry->execute($arr);


text:
Q: Save a Word file using Cell Value as Filename I have a word document that allows us to merge info from an online database.  I am trying to create a macro that will take the value in a specific table cell and use that to save the file in a specific directory.
I am not proficient with VBA but try to muck about with what others have done by copying code from other resources such as here.
I have found code that allows me to select the correct cell and I was able to make it work.
I found other code to save the file and I have tried to modify it to include the cell value as the file name.
Sub SaveAsCellContent()

    Dim Invoice As String

    Dim directory As String

    Invoice = ActiveDocument.Tables(1).Cell(2, 5)

    directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"

    wordApp.DisplayAlerts = False

    WordDoc.SaveAs FileName = DIR & INV & ".docx", FileFormat:=wdFormatDocumentDefault
    WordDoc.Close
    wordApp.Quit
    Set WordDoc = Nothing
    Set wordApp = Nothing

End Sub

As written I get an error "Compile Error: Type Mismatch".
I have spent hours and hours trying to figure this out and I think it is time to solicit expert help.

What I have now, and it is working:
Sub SaveAsCellContent()

    Dim Invoice As String

    Dim Directory As String

    Invoice = ActiveDocument.Tables(1).Cell(2, 5).Range.Text

    Invoice = Left(Invoice, Len(Invoice) - 2)

    Directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"

    ActiveDocument.SaveAs Filename:=Directory & Invoice & "i.docx", fileformat:=wdFormatXMLDocument

End Sub

But I am told I need to add Debug.Print. Which is where I am at now.

A: I've included all above comments in below working code example including adding an example error handler and a debug.print statement that prints the build directory + file name to the Immediate (debug) window.
Sub SaveAsCellContent()

Dim Invoice As String
Dim directory As String

' Get the filename that is in the 1st table in the document
Invoice = ActiveDocument.Tables(1).Cell(1, 1).Range.Text

' so the Invoice string is always at least 2 characters long
' because a cell's value contains the cell boundary characters
' remove the cell boundary characters as they cannot be used for the file name
Invoice = Left(Invoice, Len(Invoice) - 2)

' no file name specified
If Len(Invoice) = 0 Then
    Invoice = "default filename"
End If

' build the directory + filename to use in the saveas
directory = "D:\Dropbox (DRYBSMT)\~ DB Forms\Word Saves\"
' adding the file extension .docx is not needed
' is determined by the FileFormat parametes
Dim fileNm As Variant
fileNm = directory & Invoice

' print to the Immediate window for testing purposes
Debug.Print ("File name: " & fileNm)

On Error GoTo saveError
ActiveDocument.SaveAs FileName:=fileNm,
FileFormat:=WdSaveFormat.wdFormatDocumentDefault

saveError:
    If Err.Number > 0 Then
        MsgBox ("Some error occurred:" & vbCrLf & Err.Number)
    End If
End Sub


text:
Q: Angular ng-repeat conditional wrap items in element (group items in ng-repeat) I'm trying to group the items in a ng-repeat using a condition.
An example condition is to group all elements with the same hour.
The data:
[
    {name: 'AAA', time: '12:05'},
    {name: 'BBB', time: '12:10'},
    {name: 'CCC', time: '13:20'},
    {name: 'DDD', time: '13:30'},
    {name: 'EEE', time: '13:40'},
    ...
]

The 'time' field is actually a timestamp (1399372207) but with the exact time the example output is easier to understand.
I am listing these items using ng-repeat:

{{r.name}}

also tried with:

{{r.name}}

A valid output is:

AAA

BBB

CCC

DDD

EEE

My last option if there isn't a simple solution for my problem would be to group the data and then assign it to the scope variable used in ng-repeat.
Any thoughts?

A: First make group in Controller:
 $scope.getGroups = function () {
    var groupArray = [];
    angular.forEach($scope.data, function (item, idx) {
        if (groupArray.indexOf(parseInt(item.time)) == -1) {
            groupArray.push(parseInt(item.time));
        }
    });
    return groupArray.sort();
};

Then Make a Filter for it:
 myApp.filter('groupby', function(){
    return function(items,group){
       return items.filter(function(element, index, array) {
        return parseInt(element.time)==group;
       });
    }
 }) ;

Then Change Template:

{{r.name}}

SEE DEMO

A: You can use groupBy filter of angular.filter module.
so you can do something like this:
usage: collection | groupBy:property
use nested property with dot notation: property.nested_property
JS:
$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},
  {name: 'Steve', team: 'gamma'},
  {name: 'Paula', team: 'beta'},
  {name: 'Scruath', team: 'gamma'}
];

HTML:

  Group name: {{ key }}

    player: {{ player.name }}

RESULT:
  Group name: alpha
    * player: Gene
  Group name: beta
    * player: George
    * player: Paula
  Group name: gamma
    * player: Steve
    * player: Scruath
UPDATE: jsbin

A: Just a simple HTML solution for static groups.

  Group name: Football

    Player Name: {{ player.name }}

  Group name: Basketball

    Player Name: {{ player.name }}

Output:
Group name: Football
 - Player Name: Nikodem
 - Player Name: Lambert
Group name: Basketball
- Player Name: John
- Player Name: Izaäk
- Player Name: Dionisia


text:
Q: Satellizer Angularjs Login with G+ and facebook getting weired response I am implementing login with fb and google using satellizer.
In my controller i have written the code .:
 $scope.authenticate = function(provider) {
        $auth.authenticate(provider).then(function (resp) {
            console.log(resp)
        });
    };

in the response i get the following date.
Expecting a token named "token
Object {data: "", status: 200, config: Object, statusText: "OK"}
config: Object
data: "Header"
headers: (name)
status: 200
statusText: "OK"
__proto__: Object
I dont think the response is right OR what should be the next step.


text:
Q: virtual address to physical address convertion in Linux user space I am able to convert virtual address to physical address mapping in kernel space ( root user). I have reused the code of the tool provided here
I want to do the same conversion in user space . Is it possible in user space (non root user ) ?
The above tool use /proc/pid/maps and /proc/pid/pagemap files in kernel mode,
EDIT :
After receiving comments, here is my updated questions.
I want to convert virtual address to physical address in non-root privilege user, and after finding the physical address, later I will use it to find mapping to L2 cache set. My task is to find out where is my data loaded into L2 cache.
Do I need to write a kernel module which will take user virtual address and will return physical address ? If so, any link in that direction will be great help.
Is phys_addr = virt_to_phys(virt_addr); correct option ? Also unable to understand how to use it/call it from my program ?


text:
Q: pandas groupby count and proportion of group total I'm trying to do the following with pandas. Counting item by state then expressing that number as a percentage of the subtotal. My dataframe has the raw data. I can get the counts but how to append another column for the percentages?
state_grp = df.groupby(by=['date', 'state','ad_type'])
state_grp.ad_type.agg(['count'])

I've wrote some sql which will do the same thing but how to do it in pandas?
with cte1 as
(
    select distinct date, state, ad_type, count(ad_type) over (partition by date, state, ad_type) as [# of Ads]
    from propertylistings
),

cte2 as
(
    select *, sum([# of Ads]) over (partition by state) as subtotal
    from dhg
)

select date, state, ad_type, [# of Ads], round(cast([# of Ads] as float)/cast(subtotal as float) * 100, 1) as [%]
from cte2
order by date, state, ad_type

A: You can do with transform + sum
state_grp = df.groupby(by=['date', 'state','ad_type'])
state_grp=state_grp.ad_type.agg(['count'])
state_grp['%']=state_grp['count']/state_grp.groupby(level=[0,1])['count'].transform('sum')


text:
Q: Heroku application on deploy fails. Cannot find modules, but locally works Pastebin with heroku logs: https://pastebin.com/MNEisZJA
let SerializedUser = require('./src/structures/models/SerializedUser.js');
let loginUser = require('./src/structures/functions/loginUser.js')
let resetPassword = require('./src/structures/functions/resetPassword.js')
let createUser = require('./src/structures/functions/createUser.js')

problem: works fine locally, is able to require the files successfully, but when i deploy to heroku it can't find the module.

A: check cases. for example having v3.js module:
require('./V3.js')

works on Mac, but doesn't work in ubuntu. So you should go with this instead
require('./v3.js')


text:
Q: Is it normal for Outlook to take 2 weeks or more to grab AD thumbnailPhoto? I've been updating user images in AD over the last few weeks. For most users, that thumbnailPhoto attribute is pulled and viewed in Outlook correctly anywhere from an hour or so to 3 days after uploading the photo. For a handful, however, Outlooks sees some photos and not others even though it's been 3 weeks or longer since the photo has been uploaded.
Is it normal for it to take that long? Is there something keeping these users from seeing the photos?
I've tried manually downloading the global address list from their machine with no change.

A: No, it's not normal; this is probably caused by cache issues in Outlook (which version, BTW?).
Try disabling cached mode in Outlook on the clients which have this problem, or re-creating the Outlook profile altogether.


text:
Q: Vulkan video backend on Intel graphics card/mesa driver on Ubuntu 16.04 I saw in Dolphin emulator that Vulkan was a video backend option, like OpenGL, I use an Intel graphics card with Mesa driver that came with my Ubuntu install. How do I check my Vulkan version, and install it if it's not there? I'm on ubuntu 16.04 LTS.

A: You can check your Vulkan version by installing vulkan-utils and running vulkaninfo. You can install Vulkan drivers by installing package mesa-vulkan-drivers.


text:
Q: How to close the socket associated with current HttpClient instance? I need to close it and create a new one, because I get socket exception when change the connection from 3g to wifi.

A: You have to retrive the ClientConnectionManager associated with the instance and call shoutdown. If I had not misunderstood you:
HttpClient mClientInstance;
ClientConnectionManager mConnectionManager = mClientInstance.getConnectionManager();
mConnectionManager.shutdown();


text:
Q: libqt4-dev cannot be installed and breaks package manager My qtcreator was not working properly and was missing things like examples, tutorials etc. So I basically decided to do a clean install of all qt5 packages. I ppa-purge the official ubuntu-sdk ppa and tried to reinstall everything.
I added the 2 ppa mentioned in developer.ubuntu.com. I installed qtcreator and now it all works. However when I tried to update my 12.04 system, I now see the error message that there is an unmet dependency.
On running sudo apt-get dist-upgrade I get the following error output,
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 libqt4-opengl-dev : Depends: libqt4-dev (= 4:4.8.1-0ubuntu4.4) but it is not installed
 libqtwebkit-dev : Depends: libqt4-dev (>= 4:4.8.0~) but it is not installed
E: Unmet dependencies. Try using -f.

So it seems that libqt4-dev is not installed. I try installing it based on the error message by sudo apt-get -f install libqt4-dev. But then I get this error message,
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
  libmysqlclient-dev libpq-dev libsqlite3-dev unixodbc-dev
The following NEW packages will be installed:
  libqt4-dev
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
39 not fully installed or removed.
Need to get 0 B/2,516 kB of archives.
After this operation, 18.0 MB of additional disk space will be used.
(Reading database ... 416905 files and directories currently installed.)
Unpacking libqt4-dev (from .../libqt4-dev_4%3a4.8.1-0ubuntu4.4_i386.deb) ...
dpkg: error processing /var/cache/apt/archives/libqt4-dev_4%3a4.8.1-0ubuntu4.4_i386.deb (--unpack):
 trying to overwrite '/usr/bin/uic3', which is also in package qtchooser 0.0.1~git20121229.g8f08405-0ubuntu1~precise1~test5
dpkg-deb (subprocess): subprocess data was killed by signal (Broken pipe)
dpkg-deb: error: subprocess <decompress> returned error exit status 2
Errors were encountered while processing:
 /var/cache/apt/archives/libqt4-dev_4%3a4.8.1-0ubuntu4.4_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

How do I fix this?
[EDIT 1]: In response to asclepix's anser, I tried removing qtchooser by sudo apt-get remove qtchooser, however the output I get is,
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libqt4-opengl-dev : Depends: libqt4-dev (= 4:4.8.1-0ubuntu4.4) but it is not going to be installed
 libqtwebkit-dev : Depends: libqt4-dev (>= 4:4.8.0~) but it is not going to be installed
 qt5-default : Depends: qtchooser but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

A: It seems it conflicts with the qtchooser package:
trying to overwrite '/usr/bin/uic3', which is also in package qtchooser 0.0.1~git20121229.g8f08405-0ubuntu1~precise1~test5

I've got qt4 and qt4-dev, but no qtchooser (perhaps because I'm in 12.10). I think this package is to choose between qt3 and qt4 or qt5. If it's possible (have you got qt3? qt5?), try to disinstall qtchooser.

A: I had the same problem on my computer after the installation of Ubuntu SDK. I foudn the solution here.
Your have to follow step with the PPA, I put the solution here but I advise you to follow the tutorial.
How do I resolve unmet dependencies after adding a PPA?
Disable/Remove/Purge PPAs:
PPAs (Personal Package Archive) are repositories hosted on Launchpad. You can use PPAs to install or upgrade packages that are not available in the official Ubuntu repositories.
One of the most common causes of unmet dependencies are PPAs, specially when used to upgrade the existing package in Ubuntu repositories. To solve the problem you have tree options, disable, purge (revert back to original package in Ubuntu repositories) or remove PPA.
Disable:

Disabling a PPA means no more updates for the packages installed from that PPA. To disable a PPA: Open Software Center > Edit > Software Sources Or,

Hit Alt+F2 and run software-properties-gtk.

Click on Other Software tab, you'll see that each PPA have two lines here, one for the compiled packages and one for the source, Uncheck both lines to disable a PPA. Hare you can also add and remove PPAs.
Purge:

Purging a PPA means, downgrading the packages in the selected PPA to the version in the official Ubuntu repositories and disabling that PPA. PPA Purge does exactly that. To install PPA Purge run the following command:

sudo apt-get install ppa-purge

But, Considering the question apt is broken so the above command will fail. So use this command
mkdir ppa-purge && cd ppa-purge && wget http://mirror.pnl.gov/ubuntu/pool/universe/p/ppa-purge/ppa-purge_0.2.8+bzr56_all.deb && wget http://mirror.pnl.gov/ubuntu//pool/main/a/aptitude/aptitude_0.6.6-1ubuntu1_i386.deb && sudo dpkg -i ./*.deb
To use PPA Purge:
sudo ppa-purge ppa:someppa/ppa
If 'ppa-purge' command fails for some reason, you can't run 'ppa-purge' again unless you re-enable the PPA (To enable the PPA follow the same steps as disabling a PPA and Check the both lines of a particular PPA to enable it).
Note: PPA Purge doesn't remove PPAs (may be in future), So you'll have to manually remove the PPA.
It's worked for me.


text:
Q: Подгружать страницу на весь экран при нажатии на кнопку Нужно, чтобы при нажатии на кнопку Ajax подгружал страницу на весь экран которая бы заменяла текущую, но на этой подгружаемой странице должна быть кнопка выхода, которая возвращает на тот адрес с которого была вызвана ajax функция.
jQuery очень приветствуется.
Я бы и сам это сделал, но я не пойму, как это описать в двух словах, что бы поискать в гугле.
A: Вот пример:
  $( "#result" ).load( "ajax/test.html" );

Думаю, что надо будет еще передать линк странички, с которой был редирект такой себе для того, чтобы можно было так же вернуться динамически назад.


text:
Q: Hosts File not working correctly I'm having some issues with my hosts file.
127.0.0.1 localhost
127.0.0.1 whatever
127.0.0.1 sub.localhost
127.0.0.1 example.com

localhost and whatever both work. However the others have weird behaviour.
Ping sub.localhost
c:\>ping sub.localhost
Pinging sub.localhost [127.0.0.1] with 32 bytes of data:

Ping example.com
C:\>ping example.com
Pinging example.com [127.0.0.1] with 32 bytes of data:

All seems ok, but browsing example.com will open the correct example.com page @ 192.0.32.10 which is not the expected behaviour... (obviously sub.localhost wont work at all)
Any ideas why this happens?
UPDATE 1:
Removing Proxy Configuration from browser solved it for sub.localhost. example.com however still not working...
UPDATE 2:
Some more info...
C:\Documents and Settings\amatos>ping example.com
Pinging example.com [127.0.0.1] with 32 bytes of data:

C:\Documents and Settings\amatos>ping www.example.com
Pinging www.example.com [127.0.0.1] with 32 bytes of data:

C:\Documents and Settings\amatos>nslookup example.com
Server:   ac1.-------.pt  (# suppose this is the router address...)
Address:  192.168.202.2

Non-authoritative answer:
Name:    example.com
Address:  192.0.32.10

Thanks to all that have tried to help so far!

A: Try opening a command line (cmd.exe) and do ipconfig /flushdns and then restart the browser.
Also, I just got to ask since it might be too obvious or sound too stupid. Have you tried rebooting (or at least logged out and then logged in)? I never cease being amazed at what problems this can solve.

A: Is your Web browser using a proxy?
Mine is (I am at work) and when I connect to a Web site it seems to use the address the proxy server thinks, not the address my computer thinks.

A:
UPDATE: Removing Proxy Configuration from browser solved it for sub.localhost. example.com however still not working...

Are you trying to visit www.example.com instead of example.com? There is a difference between both!
You should add www.example.com to the hosts file too if you want them both to forward to 127.0.0.1.

A: You said example.com opens 192.0.32.10 - it should go to 127.0.0.1, so either you wrote wrong or the hosts file is not being applied correctly.
I am not sure about the example.com issue, but for the others, I would say that if ping is working, they are working fine, so simply double check that the webserver you are using has the host headers (or whatever setting on your server) set up correctly.
Edit -
Unsure why this is happening, First thing I would try is a different browser such as Firefox as this has it's own network settings which should not be affected by other system settings. If this solves it, then go back to IE and on the last tab (Advanced), choose Reset to remove anything else that may be setting this.
next, you can try tweaking your priorities of what is checked.
Open up the Registry Editor and navigate to :
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\ServiceProvider

Look for HostPriority and make sure it is a lower number than DNSPriority. You can also change it to a lower number such as 5 to make sure it takes priority over everything else.
If it still is not working, I would just say to check things such as your spelling, but it is hard without seeing the machine in person.

A: Flush your ARP cache:

*

*Open a cmd window.

*arp -a will show all of your ARP entries.

*arp -d will delete the entries (or a specific one).

I would also flush the DNS entries:
ipconfig /flushdns
arp -d

ping <whatever>


text:
Q: measuring time between extremely fast laser beam breakage using LDRs I am conducting a scientific experiment to approximately measure the entering velocity and the leaving velocity of a magnet through an electromagnetic coil.
Beside the coil are two lasers and two LDRs as depicted by the figure below.
I expected this circuit to generate a rising edge and a falling edge, but I realized only after testing on the oscilloscope that I was not able to receive a square waveform to input to my MSP430 MCU as interrupts. My plan was to calculate the time between these two interrupts.
However, the waveforms I observed were as below.
Then I thought that I could use an LM358 in front of my voltage divider. This is described in here. But looking at my practical waveforms I observed from the oscilloscope, I am doubtful how I can tune the comparator. Is there a better way to achieve my task using better electronics? I am not limited by component costs, however, I am not willing to buy a ready-made apparatus for this purpose. My intention is to develop one.
Thank you for your views and help.

A: Consider something like this, to tolerate sunlight

simulate this circuit – Schematic created using CircuitLab

A: Complement to Jack B's answer:
BVP11 seems much faster than the phototransistor in the link I provided, although I don't know if they measured it using a simple resistor load or a cascode.
So, the phototransistor should be selected for speed.
Good idea using a filter to match laser wavelength and get rid of ambient light. You can also put the transistor inside a long enough opaque tube with blackened internal surface to block ambient light.
Now, you got 2 sensors, so when the object passes, both will generate a pulse. This pulse has 2 edges (on/off).
If the object is shorter than the distance between sensors, you'll get:

*

*
*

*sensor 1 dark

*

*sensor 1 lit

*

*sensor 2 dark

*

*sensor 2 lit

This should be pretty obvious. If the object is longer than the distance between sensors, the order of events will change, but it matters little.
I wanted to attract your attention to the fact that rise and fall times will not be identical, therefore if you measure the time between two edges, make sure they're in the same direction. For example, you can measure the time between both rising edges, or both falling edges, and if the phototransistors have the same speed (you should check) then this will not introduce error.
Now, since you want the magnet's speed, you will be measuring the length of the pulse instead (rising edge - falling edge). If both phototransistors are identical, this will work, but if their rise/fall times are not matched, pulse lengths may be different even though the speed of the magnet stays the same.
I wanted to make sure you were aware of the inconvenience.
Also, if your phototransistors are not matched, or they are at different temperatures, or if the amount of light reaching them differs, then the output current will be different. If you use two dumb comparators with the same threshold, this threshold will be crossed at different points in the two waveforms, and this will introduce an error in the measurement of flight time between sensors. Laser light output may also vary with temperature.
A simple way to solve this problem would be to calibrate the DC level out of the way, by using a circuit like this:
Feed the phototransistor output current into a transimpedance amplifier (ie, a simple opamp). This gives you a voltage and allows the phototransistor to output into a virtual ground, which will mitigate its output capacitance and make it faster. Now, AC-couple (ie, highpass) this voltage to remove the DC light level which corresponds to constant illumination by the laser. Use a hysteresis comparator to detect your pulse's edges.
analogsystemsrf's answer is also excellent! (you can even cascode the phototransistor).
You could use two pairs of sensors instead, each pair measuring speed. In this case you'd measure time between two rising edges, so rise time asymmetry would be less of a problem. Spacing them a little bit more would also improve accuracy.
Another option would be to use modulated light in the MHz range or above, but this is more complex. If you repurpose something like an IrDA or fiber optics receiver, its internal AGC could mess things up.
I would suggest calibrating the system by shooting something which has the same shape as your magnet, but is not magnetic, like a piece of black plastic. Normally it should have the same speed on entry and exit, so you can be sure you're measuring the right thing.

A: LDRs are slow.  Consider using a photodiode or phototransistor instead.
LDRs have slow response times, their resistance changes slowly, and that is probably what is causing the slow response of your system.  Photodiodes and phototransistors are both light-sensing components with faster response times.  They are a little trickier to use than LDRs, but not too bad. Have a look at some datasheets for both, they will have recommended circuits in.


text:
Q: How to create a unique user which the ftp server can use as a totally isolated unprivileged user - vsftpd? Ubuntu 16.04
Bash 4.4.20
I would like to know the steps involved in creating a unique user which the ftp server can use as a totally isolated unprivileged user.
NOTE:
In the vsftpd.conf file, there is the following:
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure

A: I tried to realize exactly that on my raspberry pi some time ago..
I dont remember exactly how I did that and cant find the "source" of my information anymore but it should roughly go in this direction:
Create a user without giving him an own home directory (ftp_user is his name, you can give him a different one):
sudo adduser ftp_user --no-create-home

(Here you should be able to give that user a password)
If you want ftp_user to be able to access a specific folder you need to
mkdir /path/to/specific/folder                    # create a folder
sudo usermod -d /path/to/specific/folder ftp_user # assign to ftp_user

Then you need to give that user the ownership of that folder
sudo chown ftp_user:ftp_user -R /path/to/specific/folder

And In general the rights for that special folder should be like this:
sudo chmod 774 -R /path/to/specific/folder    # You:rwx Group:rwx eveyone else: r--

or
sudo chmod 775 -R /path/to/specific/folder    # You:rwx Group:rwx eveyone else: r-x

In case the folder is in /var/www/.. it may be neccessary to add the user to group www-data or something like that (if I remember correctly there is a www-data group also)
What is the www-data user?
and of course chown that file respectively:
sudo usermod -G www-data ftp_user
sudo chown ftp_user:www-data -R /path/to/specific/folder

Same for your home directory, if you want to share your home folder with that ftp_user you should be able to add ftp_user in your group but then you shouldn't chown your home folder but disallow write executions for group and everyone else..
Be very cautious with the ownership of folders and permissions.


text:
Q: Get curly brackets in Windows VM I'm on a Mac and I use a Windows VM for c# programming. I'm not able to type curly brackets in Visual Studio or anywhere else in the VM.
Any ideas?

A: [: right Alt/option + 8
]: right Alt/option + 9
{: right Alt/option + 7
}: right Alt/option + 0
Software: MacOS 10.14.5, Virtual Box 5.2.30, Windows 10 Pro
Hardware: Swedish Keyboard Layout, MacBook Pro


text:
Q: Github Build and Deploy Error: No uploaded artifact was found I am trying to deploy a github.io blog but having an issue with build and deployment. I can build the files without any issue on local server, but when I try to publish it on github server by pushing it, it throws a build and deployment error saying:

Error: Error: No uploaded artifact was found!

Here's my git repo link for more info: https://github.com/dailyole/dailyole.github.io/runs/4677505925?check_suite_focus=true
I was able to publish the same files on github.io without an issue a few weeks ago, but it throws an error now.

A: In my case my problem was caused by some bad submodule references:
https://github.com/catalin-hritcu/catalin-hritcu.github.io/actions/runs/1643762494
No url found for submodule path 'teaching/epit2018' in .gitmodules

This seems to be a common issue these days:
https://github.community/t/failed-to-publish-static-site-spa-with-submodules/219880
It fixed it with some commands like this:
git rm --cached teaching/epit2018

This doesn't seem the problem for you though.

A: solved it by change the theme of blog.
methed 1: change it in web by settings.

*

*On GitHub, navigate to your site's repository.

*Under your repository name, click  Settings.
settings

*In the "Code and automation" section of the sidebar, click  "Pages",

*then, click "change theme"
change theme

*select one theme, and click "select theme"
select
methed 2: change in the file
vim  _config.yml

change the line
theme: jekyll-text-theme

to a new theme, like
theme: jekyll-theme-cayman

: sorry for I need at least 10 reputation to post images

A: Realized this issue occurs when there is an empty submodule in your GitHub repo. Removed the empty submodule and it's working now.

A: As far as I can see, your problem is different than mine though:
https://github.com/dailyole/dailyole.github.io/runs/4677504175?check_suite_focus=true
github-pages 223 | Error:  The jekyll-theme-hydejack theme could not be found.

A: I also meet the question, and my git repo is: github-pages 223 | Error:  File to import not found or unreadable: mixins/reset-filter.
Then I see the path that have the problem, I found this file isn't uploaded. The folder contains too many files and I didn't check it again. May be you need to check if some files are not uploaded.


text:
Q: Why does Sort fail in this simple example? I'm sure I'll be embarrassed by the answer, but I don't understand why I get the following result:
list = {{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}

This works:
Sort[list]
(* {{4, "a"}, {5, "w"}, {6, "k3"}, {7, "k4"}, {9, "b"}}*)

This works:
Sort[list, #1[[1]] > #2[[1]] &]
(*{{9, "b"}, {7, "k4"}, {6, "k3"}, {5, "w"}, {4, "a"}}  *)

But this fails:
Sort[list, #1[[2]] < #2[[2]] &]
(*{{9, "b"}, {4, "a"}, {7, "k4"}, {6, "k3"}, {5, "w"}}*)

Question:
Why would it work using SortBy[] and not Sort[]?

A: Leonid Shifrin has pointed out why the 3rd sample fails: Less doesn't "compare" strings.
Still, it's possible to use Sort, with the addition of OrderedQ:
Sort[list, OrderedQ[{#1[[2]], #2[[2]]}] &]

{{4, "a"}, {9, "b"}, {6, "k3"}, {7, "k4"}, {5, "w"}}

A: Another sort of short Sort is
#/@Sort[#/@list]&@Reverse

(* ==> {{4, "a"}, {9, "b"}, {6, "k3"}, {7, "k4"}, {5, "w"}} *)

This puts the strings in first position before sorting, and then puts the strings back in second place afterwards.