text:
Q: Nodejs - async/await - nested async calls without await is still blocking? I would expect the saveData() call in datafx not block anything as there is no "await" but when i check the logs and timestamps i notice that the "main done" log is delayed even though "retrieved data" is not.
async function mainCaller(){
  // do something and then trigger call to get data
  let id = 13;
  let data = await datafx( id );  <-- this gets blocked for saveData() - why?
  LOG( `main done` );
}

async function datafx( id ){
  // get data
  let data = await getData( id );
  // cleanup data
  // save data but don't wait for it
    // datafx does not wait for it as expected
    // however, mainCaller() is somehow "delayed" by it based on log timestamps
  saveData(id, data );
  LOG( `retrieved data` );
  return data;
}

async function getData(id){ return await dbRead(id); }
async function saveData(id, data){ return await dbSave(id, data); }

*

*Is the "await" in the mainCaller() awaiting all async calls, including the nested ones?

*Is that correct?

*Is there a better way to implement the nested async call to avoid the delay on the caller?

*i can confirm that the "saveData()" call is impacting as i removed it and i see the mainCaller continue without delay as soon as datafx returns.

A: Consider the following code -
function timeoutPromise(interval) {
  return new Promise((resolve, reject) => {
    setTimeout(function () {
      resolve("done");
    }, interval);
  });
};

async function timeTest1() {
  await timeoutPromise(3000);
  await timeoutPromise(3000);
}

async function timeTest3() {
 await timeoutPromise(3000);
}

async function timeTest2() {
  await timeoutPromise(3000);
  timeTest3();
}

async function test1() {
  let startTime = Date.now();
  await timeTest1();
  let finishTime = Date.now();
  let timeTaken = finishTime - startTime;
  console.log("Time taken for test1 in milliseconds: " + timeTaken);
}

async function test2() {
  let startTime = Date.now();
  await timeTest2();
  let finishTime = Date.now();
  let timeTaken = finishTime - startTime;
  console.log("Time taken for test2 in milliseconds: " + timeTaken);
}

async function test3() {
  let startTime = Date.now();
  timeTest1();
  let finishTime = Date.now();
  let timeTaken = finishTime - startTime;
  console.log("Time taken for test3 in milliseconds: " + timeTaken);
}

test1();
test2();
test3();

The output of this program is as follows -
Time taken for test3 in milliseconds: 0
Time taken for test2 in milliseconds: 3004
Time taken for test1 in milliseconds: 6008

Answers to your questions are as follows -

Is the "await" in the mainCaller() awaiting all async calls, including the nested ones?

Consider function test2 in the example code mentioned above, the answer is no.

Is there a better way to implement the nested async call to avoid the
delay on the caller?

Yes, you need to remove await from mainCaller while calling datafx function, same as described in function test3


text:
Q: Integration of msbotframework using directline with react native mobile app I am trying to integrate the chatbot that is build in Microsoft bot framework with react-native mobile app.
I am able to integrate with the WebChat for ReactJS web app but I'm unable to integrate with the react-native mobile app.
I found only this blog for the msbotframework and react-native integration but it doesn't worked.
Anyone have any idea on this, please share your thoughts on this. It will be helpful
Thank you in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it safe to store an Object in a hash within a static class, using the Thread Id to retrieve values for that specific thread? I am making some changes to some code I have written to try and change it into a multi-threaded solution. Some of the elements from my main class were originally static, and have had to be changed as part of the changes I am making. I had the idea to store them in a HashMap, using the Id of the Thread as the key for retrieving the items - that way I could store a reference to the Runnable class in the hash and access the desired attributes for the given thread by using getters/setters. I defined the below code to do this:
import java.util.HashMap;

public class ThreadContext {

    private static HashMap<String, HashMap<String, Object>> tContext;

    static {
        initThreadContext();
    }

    public static void initThreadContext() {
        String id = String.valueOf(Thread.currentThread().getId());
        tContext  = new HashMap<>();
    }

    public static void setObject(String key, Object o) {
        String id = String.valueOf(Thread.currentThread().getId());
        HashMap<String, Object> hash = tContext.get(id);

        if( hash == null ) {
            hash = new HashMap<>();
            tContext.put(id, hash);
        }

        hash.put(key, o);
    }

    public static Object getObject(String key) {
        String id = String.valueOf(Thread.currentThread().getId());
        HashMap<String, Object> hash = tContext.get(id);

        if( hash == null ) {
            hash = new HashMap<>();
            tContext.put(id, hash);
        }

        Object o = hash.get(key);

        return o;
    }
}

My question is: is it safe to do this, or should I try and find another way to do this? My example appears to work OK, but I'm unsure of any other side effects which may come about because of this.
EDIT: Example usage:
Foo foo = ((Foo)ThreadContext.getObject(Foo.CLASS_IDENTIFIER));

foo.doStuff();

A: There is already a way to do this using the JDK's ThreadLocal, which stores distinct references for each (local) thread.

A: Not sure what you are trying to do, however some of the points you should think are :

*

*HashMap is not a synchronized object and has to be used in places where you don't need to worry about threads

*In your case you seem to assume Thread Id will be unique which will not be when running on application servers. Some of the Application servers reuse thread ids and even use thread pool to reuse threads.

If you want to have data associated to a thread alone, use ThreadLocal. Again ThreadLocal should be used with Caution as there is no way JVM can clear the contents of ThreadLocal once your thread completes execution, if there is a thread pool. You will have to set the data and clear the data yourself.

A: The ThreadLocal is certainly a better approach.
But you want feedback on this code, so here it is.
The static block and the init can all be inlined on the static declaration.
You could use an IdentityHashMap and store thread instance themselves, avoiding the unclear risks around the thread id value stated above.
You could certainly use some static method synchronization for thread safety, but that would create contention. So a ConcurrentHashMap would locate the sub map for each thread, which in turn doesn't need synchronization (since only one thread could access it).
Regarding the safety (visibility to other unintended stackframes) when using a thread pool or executor and the likes, you can code yourself a try/finally or a closure (java87 lambda) to make sure you cleanup when you leave your code stackframes. No harder than the lock/unlock discipline.
BIG WARNING: if your code needing this custom threadlocal (or ANY thread local) will be inside a ForkJointTask.compute() subject to a ForkJoinPool during and calling a ForkJoinTask.join(), your thread will possibly run other identical ForkJoinTask.compute() (because of the thread continuation emulation) and your custom threadlocal could be initialized again and again (meaning, it will be clobbered) before even leaving the initial ForkJoinTask.compute(). This means you would need a stack of initial values managed in your try/finally... to tolerate re-entrance.


text:
Q: How to get a Window in visual studio having all prototypes of a class I am making a CString class having a lot of functions in it.I have made it but when I call any func and navigate up and down to see it's def it's so time cosuming. Please tell me How can I get a Window having all prototypes of a function in a class ,so that I click and it would show me its def

A: You can use the class view window. To open it, go to the view menu and then select Class View. In the class view window you can select the class you are interested in. You can then see al its members and methods, wich you can double click to immediately go the definition.


text:
Q: Is the sheafication of a "presheaf of $\mathcal{O}_X$-modules" an $\mathcal{O}_X$-module? Let $(X,\mathcal{O}_X$) be a ringed space. A presheaf of $\mathcal{O}_X$-modules is a presheaf $\mathcal{F}$ of abelian groups on $X$ such that $\mathcal{F}(U)$ is an $\mathcal{O}_X(U)$-module for each open $U\subseteq X$, and each restriction map of $\mathcal{F}$ is linear with respect to the corresponding restriction map of $\mathcal{O}_X$. More precisely, the latter condition says: if $V\subseteq U\subseteq X$ are open, then $\alpha(rm)=\beta(r)\alpha(m)$ for all $r\in\mathcal{O}_X(U)$ and $m\in\mathcal{F}(U)$, where $\alpha:\mathcal{F}(U)\to\mathcal{F}(V)$ and $\beta:\mathcal{O}_X(U)\to\mathcal{O}_X(V)$ are the restriction maps.
Is the sheafication of a presheaf of $\mathcal{O}_X$-modules necessarily an $\mathcal{O}_X$-module?

A: Let $\mathcal{F}$ be a presheaf of $\mathcal{O}$-modules, and let
$$K=\coprod_{P\in X}\mathcal{F}_P$$
be the disjoint union of the stalks of $\mathcal{F}$. Now let $\mathcal{H}$ be the $\mathcal{O}$-module given by
$$\mathcal{H}(U)=\{f:U\to K\mid \forall P\in U,\ f(P)\in\mathcal{F}_P\}$$
for all open $U\subseteq X$, with restriction maps as in the usual sense.
Then we identify $\mathcal{F}$ with a subpresheaf $\mathcal{G}$ of $\mathcal{H}$. In particular, we take $$\mathcal{G}(U)=\{f:U\to K \mid \mbox{$\exists s\in \mathcal{F}(U)$ such that, $\forall P\in U$, $f(P)=s_P$}\}$$
for all open $U\subseteq X$; $s_P$ is the germ of $s$ at $P$. The sheafication of $\mathcal{G}$ is given by
\begin{align*}\mathcal{G}^+(U) = \{f:U\to K \mid \mbox{$\forall$ $P\in U$, $\exists V\in N_U(P)$ and $t\in\mathcal{F}(V)$ such that, $\forall Q\in V$, $f(Q)=t_Q$}\}\end{align*}
for all open $U\subseteq X$; $N_U(P)$ is the set of all open neighbourhoods of $P$ in $U$. Since $\mathcal{G}^+$ is a subsheaf of $\mathcal{H}$, it suffices to show that $\mathcal{G}^+(U)$ is an $\mathcal{O}(U)$-submodule of $\mathcal{H}(U)$ for all open $U\subseteq X$. Fix an open $U\subseteq X$. Observe that the $0$ function is in $\mathcal{G}^+(U)$. Now let $r\in\mathcal{O}(U)$, let $f$ and $g$ be in $\mathcal{G}^+(U)$, and fix $P\in U$. Then there exist $V$ and $W$ in $N_U(P)$, $s\in\mathcal{F}(V)$ and $t\in\mathcal{F}(W)$ such that $f(Q)=s_Q$ for all $Q\in V$, and $g(R)=t_R$ for all $R\in W$. Therefore, $(rf+g)(Q)=rs_Q+t_Q=(rs+t)_Q$ for all $Q\in V\cap W$, and thus $rf+g\in \mathcal{G}^+(U)$. Hence, $\mathcal{F}^+\simeq\mathcal{G}^+$ is an $\mathcal{O}$-module.

A: An $\mathcal O_X$-module structure on an abelian pre-sheaf is the same thing as a morphism of abelian pre-sheaves $\rho_F\colon \mathcal{O}_X\times F\to F$, making the associativity-diagram commute. Take associated sheaves and the induced morphism: $\rho^a_F\colon a(\mathcal{O}_X\times F)\to aF$ and observe that the natural morphism $a(\mathcal{O}_X\times F)\to \mathcal{O}_X\times aF$ is an isomorphism since it is an isomorphism on stalks and both are sheaves. Composing $\rho^a_F$ with the inverse, we get a morphism of abelian sheaves $\mathcal{O}_X\times aF\to aF$ which makes the associativity-diagram commute since it commutes on stalks. Thus, we find the induces module-structure on the associated sheaf simply by sheafifying the action morphism.


text:
Q: For Loop Returns Last Value In Loop I am learning about For Loops in Java AND Android but I've hit a wall.
My Code:
    //01
for (String FilesToDownload : Download)
    {
         myFILEposter = FilesToDownload;
         fileP();
    }

//02
private void fileP() {
// TODO Auto-generated method stub

System.out.println("Downloading Poster: " +myFILEposter);
new DownloadFileFromURL2().execute(file_url2 +myFILEposter);

}

//03
class DownloadFileFromURL2 extends AsyncTask<String, String, String> {
    ...

@Override
protected String doInBackground(String... f_url) {

    System.out.println("Downloading Poster: " +myFILEposter);

    ...

Note that I have two out prints, one in //02 and the other in //03 which should print the same output, it works in //02 but not in //03. This is what it prints to output:
//02

file1
file2
file3

AND
//03

file3
file3
file3

The output in doInBackground is taking the last value in the loop therefore downloading the last file 3 times.

A: This code is fairly horrible, no offense. First off, variables are lower-case while class-names are upper case. Secondly, methods can take parameters. Assigning a global variable to access in a function is just plain silly. But then you propagate that error into your AsyncTask and that's why the whole thing is failing. Cleaning up this mess, you'd get something along the lines of:
// oh, please-oh-please, change Download to filesToDownload
for( String aFile : Download ) {
    downloadFile( aFile );
}

private void downloadFile( String whichFile ) {
    System.out.println( "Downloading Poster: " + whichFile );
    new DownloadFileFromURL2().execute( file_url2 + whichFile );
}

class DownloadFileFromURL2 extends AsyncTask<String, String, String> {
    ...

@Override
protected String doInBackground( String... url ) {

    System.out.println("Downloading Poster: " + url[0] );

    ...

So, first you pass the file to download to your downloadFile() method as a string. Then you pass that string into your AsyncTask... and then actually use that parameter by accessing url[0].


text:
Q: Execute Python definition only if variable ==1 I wrote several definitions and I want the user to choose what definitions to run, but the definition always prints how can I turn on and of the definition?
if the user chooses 2 it should not print. what am I missing?
Senerio = 0
while Senerio not in (1, 2, 3, 4):
    Senerio = int(input("choose a commission/Aggregation senerio number \n"
                        "1. put in car \n"
                        "2. put in plane \n"
                        "3. put on boat \n"
                        "4. put on fire "))

if Senerio == 1:
Car = 1
Plane = 0
boat = 0
fire = 0

def incar():
    print('Im putting this in a car')
incar()

if car == 1:
    incar

A: This should solve it
Senerio = 0
while Senerio not in (1, 2, 3, 4):
    Senerio = int(input("choose a commission/Aggregation senerio number \n"
                        "1. put in car \n"
                        "2. put in plane \n"
                        "3. put on boat \n"
                        "4. put on fire "))

if Senerio == 1:
    car = 1
    plane = 0
    boat = 0
    fire = 0

def incar():
    print('Im putting this in a car')

if car == 1:
    incar()

A: I found that wrapping my if statement around the definition gave me what I wanted
Like this:
if car == 1:
    def incar():
        print('Im putting this in a car')
    incar()
    incar


text:
Q: How does Reactive's Monad instance handle simultaneous events? In Push-Pull Functional Reactive Programming by Conal Elliot, Reactives are given a Monad instance in section 7.1.3. What happens if both the inner and outer reactive fire that the same time for join?
never :: Event a
MkFuture :: Time -> a -> Future a
pure :: a -> Future a -- at time zero
MkReactive :: a -> Event a -> Reactive a
MkEvent :: Future (Reactive a) -> Event a

join (MkReactive (MkReactive "foo" never) (MkEvent (pure (MkReactive "bar" never)))

Should "foo" be ignored or included in the result on the join?

A: Here is the (slightly paraphrased) join definition from section 7.1.3:
-- urr is the outer Reactive; ur is the inner one.
joinR :: Reactive (Reactive a) -> Reactive a
joinR ((a `Stepper` Ev ur) `Stepper` Ev urr) = a `Stepper` Ev u
    where
    u = ((`switcher` Ev urr) <$> ur) <> (join <$> urr)

The Monoid instance being used in the definition of u is the one for Futures, defined in section 4.5, which in case of simultaneous firings picks the left one. That being so, the inner firing is not discarded if there is a simultaneous firing in join. For the specific example in your question, sampling at time zero should still give out "foo". (I believe the monad law join . fmap return = id would be violated if that wasn't the case)


text:
Q: How to add ID attribute with indexed I have a list with a class and I need add id attribute incremented, by example:
$('li.myClass').attr('id', 'sliderWeb-'+ Number++);

Some have any idea?

A: jQuery's attr supports a function.

$('li').attr('id', function (i) { return "sliderWeb-" + i } );
// $('li').attr('id', i => 'sliderWeb-' + i );
li::after {
    content: attr(id);
    color: #999;
}

A-

B-

C-

D-

A: $('li.myClass').each((i, node)=>node.id = "sliderWeb-" + i);

A: Using the function each will help you.

$.each($('li.myClass'), function(idx, obj) {
  $(obj).attr('id', 'sliderWeb-'+ idx).html('id = sliderWeb-' + idx);
});

A: Should be more like:
$('li.myClass').each(increment, element){
  $(element).attr('id', 'sliderWeb-'+increment);
});

A: var listItems = $('li.myClass');
for(var i = 0; i < listItem.length; i++) {
listItems[i].setAttribute('id', 'sliderWeb-' + i);

}


text:
Q: Dynamic Media Queries I'm currently using a js/jq resize event to apply a css rule to a horizontal menu (of variable width) when it becomes too large for the screen. The menu however wraps momentarily before the new rule is applied.
Ideally I'd like to measure the menu width and change the break point of a media query!
@media screen and (min-width: THIS-VALUE){
    New Rules
}

Is this possible??
Thanks in advance.
Chris GW Green

A: You can create a media query rule programatically - activated by measuring the width of your menu (using js/jQuery):
  document.querySelector('style').textContent +=
     "@media screen and (min-width:400px) { div { color: red; }}"

Media queries aren't designed to activate on the changing width of an element within a page or screen though - more by changes to the viewport/window itself and other factors. (A full list can be found here)
You've not posted your menu code so it's hard to understand the 'wrapping' you're experiencing, but if your horizontal menu is going 'off screen', then you might be better off setting the menu as a percentage(%) width of viewport and using a series of media queries that re-draw the menu and change/remove child elements etc at certain screen widths.

A: Try meta tags, instead of media queries. In meta tag you can use also the min-width property.
As if meta is a html tag you can then change the value how you like it:
var element = document.getElementByTagName('meta')[0];

element.setAttribute('content','Value');

Example use of meta tag

A: You can accomplish this with matchMedia.
I gave a usage example in this answer.
I assume you only need to measure the menu width once. This solution should accommodate that easily.


text:
Q: How to search for a specific string in .c file using Python I have to search for a specific string in a generated .c file, once the string is matched. Rest of the function should be imported into an Excel sheet.
Example:
FUNCTION(int, char) import_speed_information(ptr(int, char, char) Data) /* current speed */
{
    /* Dont care */
}

string to be searched : FUNCTION(int, char)
Rest of the information in that line as shown below
"import_speed_information(ptr(int, char, char) Data)"

Has to be copied in excel sheet in a Tabular format (note: comments should be excluded).
How to proceed?


text:
Q: Javascript gallery, adding images with "for" loop I'm creating gallery in my project, but i don't want to spam clear html  and repeat it 20 times in my code. I want to create loop in javascript to get the numbers of images from my folder and later add this into one div. I've created code but i don't know how to step it.
Code:
function addingImages() {

    for (var i = 0; i <= ***; i++) {
        var image = document.createElement("img");
        image.setAttribute("src", "images/1.jpg");
        document.querySelector(".gallery").appendChild(image);
    }
}

*** - i don't know what should be there. and i know i need variable to increment later numbers of images like 1.jpg , 2.jpg, 3.jpg etc.

A: You need to loop from 1 to 20, so set loop count to 20. Then use index from loop in setAttribute function like this:
   function addingImages() {
    for (var i = 1; i <= 20; i++) {
        var image = document.createElement("img");
        image.setAttribute("src", "images/" + i + ".jpg");
        document.querySelector(".gallery").appendChild(image);
   }
}

A: With Jquery, you can also use this:
function addImages(img_count) {
   var images='';
   for (var i = 1; i <= img_count; i++) {
    image = '<img src="images/'+i+'.jpg">';
   }
   $(".gallery").html(image);
}

A: You need to add this jquery(Ajax) function Instead of for loop because you need to check images inside your folder before include it in the gallery
        $.ajax({
      url: "images/",
      success: function(data){
         $(data).find("a:contains(.jpg)").each(function(){
            var filename = this.href.replace(window.location.host,          "").replace("http://", "");
            $("gallery").append("");
         });
      }
    });


text:
Q: Android dynamic feature access fragment from main app with proguard enabled I have one dynamic feature. And when i enable proguard and i try to access fragment
if (splitManager.installedModules.contains(name)) {
            val fragment = "com.xxx.xxx.xxxx.AAFragment"
            val fr = activity!!.classLoader.loadClass(fragment)
            childFragmentManager.beginTransaction()
                .replace(R.id.frameLayoutContainer, (fr as Class<Fragment>).newInstance())
                .commit()
        }

Error:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.xxx.xxx.xxxx.AAFragment" on path: DexPathList

If i try with disable proguard it works.
I try to keep class fragment in dynamic feature but it does not work.
How can i reach dynamic feature fragment? Thanks


text:
Q: Fragment Navigation Drawer Initializes as Open I am trying to create a Navigation Drawer (it's outdated I know) with a custom layout.  I am using a fragment within the NavDrawer to accomplish this.
The problem I am having is that when I run my app, my navigation drawer is automatically opening and I have no way to close it / no idea how.  I suspect it has to do with the .commit() method at the end of my fragment transaction.
So my question is how do I get the nav drawer, housing a fragment, to operate like a normal nav drawer that only contains a ListView where it can be dragged in and out?  Or if a fragment causes too many difficulties in a nav drawer is there another way for a super custom layout inside of a nav drawer?  Thanks in advance!
Here is what it looks like. Code is below picture...

in MapsActivity.java:
//Instantiates Fragment inside of our Nav Drawer
    NavigationDrawerFragment navDrawerFragment = new                    NavigationDrawerFragment();
    getFragmentManager().beginTransaction()
            .add(R.id.navDrawer_container,
navDrawerFragment).addToBackStack(null).commit();

activity_maps.xml:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorMapToolbar"
        android:minHeight="?attr/actionBarSize"
        app:contentInsetEnd="0dp"
        app:contentInsetStart="0dp">
        <!-- contentInsert is the initial padding that is added by the system at the start -->

        <RelativeLayout
            android:id="@+id/topLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize">

            <ImageView
                android:id="@+id/back_action"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginLeft="6dp"
                android:layout_marginStart="6dp"
                android:gravity="center_vertical"
                android:padding="6dp"
                android:src="@drawable/icon_goleft" />

            <ImageView
                android:id="@+id/locker"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginEnd="6dp"
                android:layout_marginRight="6dp"
                android:gravity="center_vertical"
                android:padding="6dp"
                android:src="@drawable/lock_open" />

        </RelativeLayout>

    </android.support.v7.widget.Toolbar>

    <View
        android:id="@+id/dropshadow"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@drawable/dropshadow_dark" />

    <ImageButton
        android:id="@+id/floatingActionImageButton"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="15dp"
        android:background="@drawable/circle"
        android:focusable="true"
        android:src="@drawable/icon_location" />

    <LinearLayout
        android:id="@+id/markerLayout"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:background="@color/colorMapToolbar"
        android:orientation="horizontal"
        android:weightSum="2">

        <TextView
            android:id="@+id/markerCancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/cancel"
            android:textColor="@android:color/white"
            android:textSize="@dimen/abc_text_size_large_material" />

        <TextView
            android:id="@+id/markerMark"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/mark"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/abc_text_size_large_material"
            android:textStyle="bold" />

    </LinearLayout>
</RelativeLayout>
<!-- FRAGMENT CONTAINER -->
<FrameLayout
    android:id="@+id/navDrawer_container"
    android:layout_width="240dp"
    android:layout_height="match_parent" />

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

fragment_navigation_drawer.xml: (accompanied by a .java for Fragment but it is not relevant here)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="200dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="2"
android:background="@android:color/white">

<RelativeLayout
    android:id="@+id/topRowLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="8dp">

    <TextView
        android:id="@+id/userTitleBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:padding="8dp"
        android:text="@string/userTitle"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/alertTitleBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:padding="8dp"
        android:text="@string/alertTitle"
        android:textStyle="bold" />

    <TextView android:id="@+id/lastFlamText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:gravity="center_horizontal"
        android:text="@string/lastFlameTitle"
        android:layout_below="@+id/userTitleBtn" />

    <TextView
        android:id="@+id/scoreTextNavDrawer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal|bottom"
        android:padding="16dp"
        android:textSize="100sp"
        android:textStyle="bold"
        android:layout_below="@+id/lastFlamText" />

</RelativeLayout>

<ListView
    android:id="@+id/navList"
    android:layout_width="240dp"
    android:layout_height="0dp"
    android:layout_gravity="left|start"
    android:layout_weight="1" />
</LinearLayout>

A: The android:layout_gravity="left|start" attribute needs to go on the navDrawer_container FrameLayout in the activity_maps layout. This attribute lets the DrawerLayout know that this View is the drawer. The fact that it's missing would explain why your drawer is "open" on startup, and immovable.
<FrameLayout
    android:id="@+id/navDrawer_container"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="left|start" />

You don't necessarily need that attribute now on the ListView in the fragment_navigation_drawer layout.

A: Add this Code in your activity or Fragment
@Override
      public void onStart() {
             super.onStart();
             if (drawer_layout.isDrawerOpen(Gravity.LEFT)) {
                 drawer_layout.closeDrawer(Gravity.LEFT);
             }
         }


text:
Q: boolean if record is first 10 post of the month i have a very tough mysql statement question.
i have a table with the following structure.
post_id, date_time, category_id

i want to sort this table by date_time and also to have a true or false Boolean that indicates if this record is the first 10 record of the month of each category.
for example first 10 record of Oct 2011 for category a will be true, first 10 record of the Oct 2011 for category b is also true, first 10 record of Nov 2011 for category c will be true, first 10 record of the Nov 2011 for category b is also true.
Please guide me along. thanks!

A: You just apply query for select date_time from tablename oder by date_time desc
OR
You can do like get all the data_time field column data in array.
and apply substring logic to get the only date number.
After you can sort that according to value
and append again remaing part ..
like
10-11-2011 15:30:46
take String date=substring(0,2)
so you got 10
and String remainingDatepart=(3,length)
after you just sort according to date.
and after you can append reminingDatapart string in sorted date..
This is logic you can apply them.

A: Something like this should od the trick, I've only tested it in my head.
SELECT
  s.*
  , CASE WHEN s.rank < 10
         THEN TRUE
         ELSE FALSE
         END AS top10
FROM (
  SELECT
    t1.post_id, t1.date_time, t1.category_id
    ,CONCAT(year(t1.date_time), month(t1.date_time)) as yearmonth
    ,@prevyearmonth:= CONCAT(year(t1.date_time), month(t1.date_time)) as yearmonth
    ,CASE WHEN (@prevyearmonth = CONCAT(year(t1.date_time), month(t1.date_time)))
          THEN @rank:= @rank + 1
          ELSE @rank:= 1
     END as rank
  FROM (SELECT * FROM table1 ORDER BY date_time DESC) t1
  CROSS JOIN (SELECT @rank:= 0, @prevyearmonth:= null)
  ORDER BY date_time DESC
  ) s
/* HAVING top10 = TRUE */
ORDER BY s.date_time, s.top10


text:
Q: Issues in Deployment.yaml file I got an error in my Deoloyment.ysml file. I have made env in this file and assign values in values file. I got a syntax error in this file
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}
  labels:
    app.kubernetes.io/instance: {{ .Release.Name }}
    app.kubernetes.io/name: {{ include "name" . }}
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/instance: {{ .Release.Name }}
      app.kubernetes.io/name: {{ include "name" . }}
  template:
    metadata:
      labels:
        app.kubernetes.io/instance: {{ .Release.Name }}
        app.kubernetes.io/name: {{ include "name" . }}
    spec:
      containers:
        - name: {{ .Release.Name }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          resources: {}
          env:
            - name: MONGODB_ADDRESS
              value: {{ .Values.mongodb.db.address }}
            - name: MONGODB
              value: "akira-article"
            - name: MONGODB_USER
              value: {{ .Values.mongodb.db.user | quote }}
            - name: MONGODB_PASS
              valueFrom:
                secretKeyRef:
                  name: {{ include "name" . }}
                  key: mongodb-password
            - name: MONGODB_AUTH_DB
              value: {{ .Values.mongodb.db.name | quote }}
            - name: DAKEN_USERID
              value: {{ .Values.mongodb.db.userId | quote }}
            - name: DAKEN_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: {{ include "name" . }}
                  key: daken-pass
            - name: JWT_PRIVATE_KEY
              valueFrom:
                secretKeyRef:
                  name: {{ include "name" . }}
                  key: jwt-Privat-Key
            - name: WEBSITE_NAME
              value: {{ .Values.website.Name }}
            - name: WEBSITE_SHORT_NAME
              value: {{ .Values.website.shortName }}
            - name: AKIRA_HTTP_PORT
              value: {{ .Values.website.port }}
          ports:
            - containerPort: {{ .Values.service.port }}

I got this error:

Error: Deployment in version "v1" cannot be handled as a Deployment:
  v1.Deployment.Spec: v1.DeploymentSpec.Template:
  v1.PodTemplateSpec.Spec: v1.PodSpec.Containers: []v1.Container:
  v1.Container.Env: []v1.EnvVar: v1.EnvVar.Value: ReadString: expects "
  or n, but found 8, error found in #10 byte of
  ...|,"value":8080}],"ima|..., bigger context
  ...|,"value":"AA"},{"name":"AKIRA_HTTP_PORT","value":8080}],"image":"dr.xenon.team/websites/akira-fronte|...

A: Answer to your problem is available in Helm documentation QUOTE STRINGS, DON'T QUOTE INTEGERS.

When you are working with string data, you are always safer quoting the strings than leaving them as bare words:
name: {{ .Values.MyName | quote }}

But when working with integers  do not quote the values.  That can, in many cases, cause parsing errors inside of Kubernetes.
port: {{ .Values.Port }}

This remark does not apply to env variables values which are expected to be string, even if they represent integers:
env:
 - name: HOST
   value: "http://host"
 - name: PORT
   value: "1234"

I'm assuming you have put the port value of AKIRA_HTTP_PORT inside quotes, that's why you are getting the error.
You can read the docs about Template Functions and Pipelines.

A: With AKIRA_HTTP_PORT: "8080" in values.yaml, in the env variables write:
env:
  - name:  AKIRA_HTTP_PORT
    value: {{ .Values.website.port | quote }}

It should have to work


text:
Q: Why do the Borg only assimilate at close range? Ever since the Borg evolved to include the nanoprobe-injecting tubules in First Contact (at least, I assume they had only recently developed them since we never saw that method of assimilation before), why did they not take it a step further and develop a ranged version of this?
I mean, even 20th-Century humans have tranquilizer darts, which inject a liquid into a target from range. Regardless of the Collective's disdain for caring about the safety of individual drones, one would think that being able to shoot Insta-Assimilate darts at your enemies would be an even quicker and more efficient method of assimilation than hoping to get close enough to poke the tubules into flesh.
Taking it a step farther, depending on exactly how tiny the nanoprobes are, could they not even be misted into the atmosphere? How screwed would a planet be if a cube basically crop-dusted them with probes?
As frequently is the case, I'm looking for in-universe speculation (I know there are no facts on this one, but I don't want to just hear "the writers couldn't make them literally invincible"). Is there some reason that either of these methods of delivery would be infficient enough to be dismissed by the Collective/Queen?

A: The Borg only do a very small amount of "innovation", which is basically combining the best bits from what they have already assimilated. I would assume that they have either not assimilated a tribe with blow-darts (they would be too primitive), or more likely, they have not assimilated a culture that used blow-darts or tranquilizers that contained nanites.
So while there is little doubt that the Borg have all of the information needed to create something like what you've described, they simply lack the capability to combine the ideas into a product.
There is also (of course) the issue that if this were possible, then they would also create torpedoes and other methods of distributing the nanites, and would easily assimilate the galaxy (and thus no show).

A: Mass infection of organics would likely lead to Borg cats, dogs and lizards as the nanites most likely cannot determine the level of inteligence / distinctiveness the Borg are interested in assimilating. Highly inefficent, and therefore would not be contemplated.

A: There is no in-Universe canon to support the Borg DID NOT have the ability to deliver nanoprobes to a species en masse.
We might make the assumption they did not since they were unable to assimilate or stop Species 8472 until they were aided by Voyager. But the help Voyager gave was not JUST the photon torpedoes modified with nanites loads. It was Voyagers stealth nanoprobes that the Borg lacked the creativity or research capacity to create.
Borg nanoprobes are highly infectious and very efficient at transforming an individual in a very short time, but the Borg would not assimilate entire species one specimen at a time. It would be inefficient and illogical.
In events with the Borg, we see them assimilating individuals, but the Borg only assimilate individuals, ships or small colonies for study and analysis at close range. It is more likely when they are assimilating a species, they use their Borg nanoprobes to infiltrate a natural resource required by the species and have the infected specimens return to a single collection point once they have been properly adapted.
While the Borg are likely to have the physical manpower to do overcome a species one planet and one individual at a time, it makes more sense to allow the potential species to infect themselves and then collect them afterward for processing. Their capacity for nanite production would basically allow them to seed entire worlds with nanites and return once their transformation was complete.
Nanites are perfect for concealing in food and water supplies due to their size. Only a species that knows what they are looking for, or perhaps has a technology designed to recognize inactive nanites would even know they are there.
Consider, the Borg only sent one ship to conquer the Federation after they decided to attack it. The confrontation at Wolf 359 indicated, one ship may have been enough.
Just because we have not seen a multi-person delivery system, it does not mean they do not have one.
Once they have a specimen of the species they are going to absorb, they adapt the nanoprobes to make the transformation as efficient as possible. This does not take research, using strictly trial and error has worked for the Borg since very few species have the immunological response to resist the nanoprobes. To date, only Species 8472 have been biologically capable of resistance.
Their previous process of mass assimilation (whatever that process was) would not have worked against Species 8472, and they lacked the expertise to research why they were unsuccessful.
Voyager was successful in weaponizing the Borg nanoprobes because they were able to research why Species 8472 was resistant and, using creativity, make a process that would make the nanoproves invisible to Species 8472's hyper-efficient immune system. The weaponized versions of the Borg nanoprobes were redesigned by the Voyager crew to be ignored by the powerful immune system of Species 8472 until the process was unable to be stopped.
The innovation was not the torpedoes (though they certainly helped), it was the stealth nanoprobes that won the day. There is no reason to believe the Borg don't already possess a means of transforming a population, even if it is as prosaic as a flying vehicle dropping nanoprobes on a city. I would suspect they are more efficient than that. It's in their nature.

A: Summary: Insta-Assimilate darts can't do the job.  They could inject the nanites, but the Borg implants still need to be installed so the Borg would have to be onsite in some form.
In the Star Trek: Voyager episode "Dark Frontier", Seven of Nine and the Borg Queen have the following exchange:

Queen: Species 5618, human. [...] Our previous attempts to assimilate them were all direct assaults.  They failed.  So we've created a more surreptitious strategy.
Seven: You intend to detonate a biogenic charge in Earth's atmosphere.
Queen: It would infect all life forms with nanoprobe viruses.  Assimilation would be gradual. By the time they realised what was happening, half their population would be drones.
Seven: Inefficient. The virus would take years to proliferate.
Queen: We've waited this long.

From this exchange we learn that the Borg are willing to use weapons of mass assimilation, but generally choose not to do so because 1) it is a slower process than what they normally do, and 2) such stealthy pacification is typically not needed.
(2) is easy to understand.  The Borg technology level is very high even by Federation standards, so it is likely that most species cannot put up meaningful resistance.  Shock troops are sent in, the natives fight back, but resistance is futile.  Those the Borg cannot initially outfight, they outlast.  (Think driver ants.)
(1) makes sense if assimilation is mostly a macro process.  Infusing a host with regenerative nanobots is not enough; Borg implants also have to be installed.  The implants could be grown using the nanites but installing ready-made implants will always be faster, and it gets the newly created drone functional sooner.  A new drone can then go out and start assimilating more of the populace.  Cumulatively this produces an exponentially growing army of Borg drones that would overwhelm any remaining resistance.

A: Considering what the Doctor was able to do with activated probes it's not worth firing ranged probe torpedoes which may be "captured" and reverse engineered

A: The Borg as originally portrayed on TNG had no nanotechnology (at least none relevant to assimilation and combat). I tend to think of these guys as the necro-Borg. They emphasize the pale skin and cadaverous appearance. All assimilation is done with vivisectiony and surgical prosthesis.
Later on, Michael Okuda must have read a Time magazine article on nanotechnology/nanorobots and they changed the idea behind this villain. It wasn't well-conceived. If anything, it makes them less menacing. What this means for the question though is that the implications were just never realized by the writers.


text:
Q: Node.js and faceted search What is your recipe for faceted search in Node.js?
In my previous, Drupal-based site all data was stored in Mysql database. During cron calls all new/modified/deleted nodes were synchronized with Solr which provided nice faceted search in quick manner.
How to do the same in Node.js? By "the same" I mean nice and fast faceted search.
Initially I was thinking about MongoDB with manual synchronization with Elasticsearch.
Personally I would prefer to avoid Sphinx (it's not a definitive decision).

A: You can use in-memory-faceted-search npm package to scan an array of objects and generate a faceted search index with all possible levels and combinations.
Example:
const data = require("./sample.json")
const facetedSearch = require("in-memory-faceted-search")

const facets = [
  { name: "Colors", field: "color" },
  { name: "Sizes", field: "size" },
  { name: "Status", field: "active", map: (item) => (item.active ? "Active" : "Disabled") },
  { name: "Ages", field: "age", map: (item) => (item.age > 25 ? "Over 25" : "Under 25") }
]

const tree = facetedSearch({ data, facets })
console.log(JSON.stringify(tree, null, 4))

Output:
{
    "count": 100,
    "Colors": {
        "red": {
            "count": 27
        },
        "blue": {
            "count": 25
        },
        "green": {
            "count": 23
        },
        "brown": {
            "count": 25
        }
    },
    "Sizes": {
        "big": {
            "count": 29
        },
        "small": {
            "count": 34
        },
        "medium": {
            "count": 37
        }
    },
    "Status": {
        "Disabled": {
            "count": 56
        },
        "Active": {
            "count": 44
        }
    },
    "Ages": {
        "Over 25": {
            "count": 72
        },
        "Under 25": {
            "count": 28
        }
    }
}

Check the README file to get more examples and deeper levels

A: Node.js is completely irrelevant here. What you need is a datastore and/or indexing technology that can do faceted search. Hooking any number of those up with Node.js is just plumbing. Why not just go with MySQL if that works for you?


text:
Q: What is a "trivial implication"? This is a philosophical question.
Most often when a certain axiom or proposition implies another proposition, this implication is not trivial, or "immediate". That is, you need a proof consisting of some number of steps to reach the second proposition.
So in that case we can say, proposition A implies but does not trivially imply proposition B.
My (philosophical) question is: what does it mean for a proposition to trivially imply another, or in other words, that it follows "immediately"? Is there a way to objectively determine whether an implication is trivial? Does a trivial implication only rely on an appeal to an intuition about "primitive notions"?
Perhaps we should exclude from this analysis cases where a theorem is implicitly used but simply not explicitly stated for the sake of brevity.

A: "Trivial" is a subjective, not an objective term. It is also a risky term to use, but the rule of thumb would be

You are only ever allowed to use the word "trivially" if you are certain that your reader (and you) is capable of proving the implication with no real cognitive effort.

I wrote cognitive effort because often, the word trivial is used when the proof of a statement is essentially over, but writing the entire thing out would take a lot of time, even though each step would be very simple.

A:
It is trivial to see that P.

Whenever this occurs in a proof, it is essentially making a (meta-logical) claim that the statement "P" is easily implied by the preceding statements. This is usually one of the following types:

*

*The implication can be proven by a standard or commonly used argument.

*The reader who understands the rest of the proof is likely to be able to fill in the gap.
Example of the first type

It is easy to see that by symmetry we can assume P.

One usually verifies this by observing (meta-logically) that the preceding statements are invariant under a symmetry (usually a permutation of variables) and P is true in one of the cases under the symmetry. For example, if we have reals $x,y$ such that every statement we have proven still holds when we swap $x,y$, then we know that we can choose whether to swap or not such that $x \le y$. So we can say "By symmetry we can assume $x \le y$".
If you think about it, this reasoning about symmetry is not at all a short deduction in the sense that you have to check every single preceding statement. But yet it is such a standard technique that it is not worth writing out all the details to avoid the symmetry argument. An alternative is to show one case and state that the other is similar, which is essentially the same claim of triviality.
Example of the second type

It is trivial to check that P(0) holds.

This is often used in an induction argument, regardless of what P is, since usually it is the case that the intended audience can easily figure out how to prove it on their own and it would be a waste of space and time to write out the details.
Example of both types

A uniformly continuous function on $[0,1]$ is trivially continuous.

The triviality comes down to the basic meta-logical fact that an "$\exists \forall$" statement always implies the corresponding "$\forall \exists$" statement where the quantifiers are swapped. Every reader trained in basic mathematics is expected to know this, and so it is fine to consider it trivial.

A: As a supplementary remark, a trivial implication could be an implication of the form $P \Rightarrow Q$ where $P$ is a false statement and $Q$ is a statement; just note that $P \Rightarrow Q$ is equivalent to $\sim P$ or $Q$.


text:
Q: appcfg.py and pre-release sdk issue Downloaded python v 1.6.4  of sdk and get following message when running local devserver:
INFO     2012-04-01 20:08:10,177 appcfg.py:582] Checking for updates to the SDK.
INFO     2012-04-01 20:08:11,660 appcfg.py:616] This SDK release is newer than the advertised release.
Re-installed after unistalling both sdk and python 2.7 used fresh download multiple times issue repeats. Also unable to upload an application using appcfg.py
Command typed appcfg.py update appdrectory/
and it spits out standard text
Usage: appcfg.py [options]
Action must be one of:
  backends: Perform a backend action.
  backends configure: Reconfigure a backend without stopping it.
.....
Suspect is linked to fact that have pre-release appcfg.py
How to un-isntall pre-release sdk and put in latest release sdk  Is something special to be done.?

A: Your syntax should be: python appcfg.py update <directory>.
Is this what you have done?


text:
Q: "Exception TDBXError in module xxx.exe at xxx. Unable to load dbxmys.dll (errorCode126). It may be missing from the system path." I have installed MySQL on a client machine, created and populated the databases – MySQL is up and running. I then copied dbxmys.dll and libmysql.dll from my machine to the Windows/system32 folder of the client and copied the compiled project EXE file. On executing the project I get the error

"Exception TDBXError in module xxx.exe at yyy. Unable to load
  dbxmys.dll (errorCode126). It may be missing from the system path."

I have also tried to copy dbxmys.dll and libmysql.dll to the same folder as the executable but that did not work either.

A: Most plausible explanation, as so often has been the case, is that your have a 32 bit process on a 64 bit machine. In that case the file system redirector means that 32 bit processes that access System32 get redirected to the 32 bit system directory, SysWOW64. That's where you should put the files, if indeed the system directory is where they need to go.
Another possible failure mode could be that you have 64 bit DLLs and a 32 bit process. Or vice cersa.
That said, the system directory is for, well, system files. And applications should not modify it. So, putting the DLLs in the application directory would seem to be the right thing to do. You tried that without success. Hard to say why it failed. Perhaps there are further dependencies. Debug this using Dependency Walker in Profile mode.


text:
Q: Is possible to reduce the code having too many for loops and if statements using list comprehension? whitelist = [{'name':'str_1','place':'plc_1','rail':['private','protected'],'port':[100,101,102,103]},
{'name':'str_2','place':'plc_2','rail':['protected'],'port':[201,202]},
{'name':'str_3','place':'plc_3','rail':['private'],'port':[303]}]
for index, row in df.iterrows():
for wl_list in whitelist:
    if wl_list['name'] in row['name']:
        variable = request.get("link",headers=headers).json()
    else:
        variable = None

if row['services'] !=0 :
    for t_service in row['services']:
        if wl_list['name'] != 'global' and variable != None:
            for var in variable :
                if (var['status']== 'active' and var['id] in service['id']) and ('private' in var['rail'] or 'protected' in var['rail'] ):
                    if wl_list['place'] in var['place']:
                        for wl_rail in wl_list['rail']:
                            if wl_rail in var['rail'] and 'ports' in var.keys():
                                for v_port in var['ports']:
                                    if len(v_port) != 0:
                                        if v_port['from'] == v_port['to']:

                                            if 'private' in wl_rail:
                                                if v_port['from'] in wl_list['port']:
                                                    n_private = 0
                                                else:
                                                    n_private = 1
                                            if 'protected' in wl_rail:
                                                if v_port['from'] in wl_list['port']:
                                                    n_protected = 0
                                                else:
                                                    n_protected = 1
                                        else:
                                            for wl_port in wl_list['port']:
                                                if wl_port > v_port['from'] and wl_port < v_port['to']:
                                                    if 'private' in wl_rail:
                                                if v_port['from'] in wl_list['port']:
                                                    n_private = 0
                                                else:
                                                    n_private = 1
                                            if 'protected' in wl_rail:
                                                if v_port['from'] in wl_list['port']:
                                                    n_protected = 0
                                                else:
                                                    n_protected = 1

                    else:
                        if 'private' in var['rail']:
                            n_private = 1
                        if 'protected' in var['rail']:
                            n_protected = 1

How to reduce the code and time complexity?

A: The code is a bit complex, and I am not getting the meaning of this code. But you could try something like,
# if-else shorthand
<do this> if <condition> else <do this>

# checking condition from a list
if <something> in [item1, item2, ..., item n]:
    <do something>

#list comprehension
lst =  [expression for item in iterable if condition == True]


text:
Q: check if item in array1 exist in array2 Having some problems here with arrays. I basically want to loop through array1, check which elements in that array exist in array2 and then return a new array containing all matches.
How would one do that?

A: This code is in pure javascript not with library
var fruits1 = ["Banana", "Pear"];
var fruits2 = ["Banana", "Orange", "Apple", "Mango"];
var fruits3 = [];

for (i=0; i< fruits1.length; i++)
   if (fruits2.indexOf(fruits1[i]) > -1)
     fruits3.push(fruits1[i]);

A: Vanilla Javascript
for(var x=0;x<array1.length;x++){
    for(var y=0;y<array2.length;y++){
        if ( array1[x] == array2[y] ) array3.push(array1[x]);
    }
}

Jquery version
$.each(array1, function(k,v){
    $.each(array2, function(k2,v2){
       if ( v == v2 ) array3.push(v2);
    });
});

A: If you have unsorted arrays with different lengths, this will work too.
Create a function called intersect for example:
function intersect(arr1,arr2){
    //We need to know which array is the shortest to avoid useless loops
    if(arr2.length<arr1.length){
        var temp = arr1;
        arr1 = arr2;
        arr2 = temp;
    }
    // Now, we are sure arr1 is the shortest
    var result = [];
    for(var i = 0; i<arr1.length; i++){
        if(arr2.indexOf(arr1[i])>-1) result.push(arr1[i]);
    }
    return result;
}

This function takes 2 arrays as parameters, and no need to worry about their order.
Then you can call it and see the results:
var arr1 = [1,2,3,4,5];
var arr2 = [4,5,6,7,8,9,10,12];

var inter = intersect(arr1,arr2);
alert(inter);

JS Fiddle Demo


text:
Q: Prove that $\sec x \geq 1+\frac{x^2}{2}$ on $(-\frac\pi2,\frac\pi2)$.
Prove that $\sec x \geq 1+\dfrac{x^2}{2}$ on $(-\frac\pi2,\frac\pi2)$.

We have that $\sin x < x$ on $(0,\frac\pi2)$. Hence $x- \sin x > 0$ on $(0,\frac\pi2)$. Let $f(x) = \dfrac{x^2}{2}+\cos x.$ Then $f'(x) = x- \sin x$. By the MVT, $\exists x_1\in (0,x)$ such that $f'(x_1) = \dfrac{\frac{x^2}{2}+\cos x - 1}{x}>0\Rightarrow\cos x -1+\dfrac{x^2}{2}>0.$ Now let $g(x) =  \sin x -x +\dfrac{x^3}{6}.$ Then $g'(x) = \cos x - 1 +\dfrac{x^2}{2}$. By the MVT, $\exists x_2 \in (0,x)$ such that $g'(x_2) = \dfrac{\sin x -x + \frac{x^3}{6}}{x} >0\Rightarrow \sin x -x + \dfrac{x^3}{6} > 0$ on $(0,x)$. Let $h(x) = -\cos x - \dfrac{x^2}{2}+\dfrac{x^4}{24} .$ Then $h'(x) = \sin x - x + \dfrac{x^3}{6}$. Since $h(x)$ is continuous, by the MVT, $\exists x_3 \in (0,x)$ such that $h'(x_3) = \dfrac{-\cos x - \frac{x^2}{2}+\frac{x^4}{24} +1}{x} >0\Rightarrow \cos x < 1-\dfrac{x^2}{2}+\dfrac{x^4}{24} $ on $(0,x)$. Since $\cos (x) = \cos (-x)$, and $x \in (0,\frac\pi2)$, $\cos x < 1-\dfrac{x^2}{2}+\dfrac{x^4}{24}$ on $(-\frac\pi2,\frac\pi2)$. Hence $\sec x =\dfrac{1}{\cos x} >  \dfrac{1}{1-\frac{x^2}{2}+\frac{x^4}{24}}=1+\dfrac{x^2}{2}+\dfrac{x^4}{8}+O(x^6) > 1+\dfrac{x^2}{2}$ on $(-\frac\pi2,\frac\pi2)$.

I'm quite sure the proof above is correct, but it's way too long for a simple question like this one, so I was wondering if there was a much cleaner, shorter proof?

A: It is enough to prove this for $0 \leq x \leq \pi /2$. Note that $\tan x \geq x$ in this interval because the inequality holds for $x=0$ and the derivative of $tan x -x$, which is $\sec^{2}x-1$ is non-negative. We can now conclude that $\tan x \sec x \geq x$ because $\sec x \geq 1$. Finally Note that the derivative of $\sec x -(1+\frac {x^{2}} 2)$ is non-negative and this function vanishes at $0$. Hence it is non -negative.

A: Taylor series of $\sec(x)$ around zero is $1+x^2/2 + 5\xi^4/24$ for some $\xi\in [0,x]$ by Taylor's Remainder Theorem. For $x\in (-\pi/2,\pi/2)$, $\xi\in (-\pi/2,\pi/2)$ and $ 5\xi^4/24>0$. Therefore, $$\sec(x) = 1+x^2/2 + 5\xi^4/24 >1+x^2/2.$$
Note that, this argument is only valid in this interval, because $\sec$ may not be analytic in other intervals.

A: Let $\displaystyle f(x)=\frac{\left(2+x^{2}\right)\cos x}{2}$. Then, $f'(x)=\left(x\cos x-\sin x\right)-\frac{x^{2}\sin x}{2}$. Since $\sin x$ is monotonic and has the same sign as $x$ for $\frac{-\pi}{2}\le x\le \frac{\pi}{2}$, we have $-x\sin x\le0$ and $-\frac{x^2}{2}\sin x$ is monotonically decreasing. But $-x\sin x$ is also the derivative of $\left(x\cos x-\sin x\right)$, so that is monotonically decreasing too and so is the sum, $f'(x)$. Then, $f'(x)$ is nonnegative over over $\frac{-\pi}{2}\le x\le 0$, has a root at $0$ and nonpositive over $0\le x\le \frac{\pi}{2}$. Then, $f(x)$ is monotonically increasing over $\frac{-\pi}{2}\le x\le 0$, maximal at $(0,1)$ and decreasing over $0\le x\le \frac{\pi}{2}$. Therefore, $f(x)\le 1$, so $\displaystyle 1+\frac{x^{2}}{2}\le{\sec x}$.

A: Note that
$$ \sec x-1=\int_0^x\sec t\tan tdt.$$
So what one has to show that
$$ \int_0^x\sec x\tan tdt\ge\frac {x^2}2=\int_0^x tdt.$$
Suppose $0\le x\le\frac{\pi}{2}$ and $t\in[0,x]$. Let
$$ f(t)=\sin t-t\cos^2t $$
and then
$$ f'(t)=\cos t-\cos^2t+t\sin(2t)\ge0. $$
This means that $f(t)$ is increasingin in $[0,x]$ and so
$$ f(t)\ge f(0)=0$$
which implies
$$ \sec t\tan t\ge t $$
Therefore
$$ \sec x-1=\int_0^x\sec t\tan tdt\ge \int_0^xtdt=\frac{x^2}{2} $$
or
$$ \sec x \ge 1+\frac{x^2}{2}. $$

A: Due to symmetry, consider $x\ge0$ below,
$$\sec x -1-\dfrac{x^2}{2}=\int_0^x (\tan u\sec u - u)du\ge \int_0^x (\tan u - u)du
=\int_0^xdu \int_0^t (\sec^2 t-1)dt\ge0$$


text:
Q: Integrating an exponential times an error function I have...
$$
I = \int_{\sqrt{R^{2}-\left(R-\epsilon\right)^{2}}}^{R}dxe^{-\beta x^{2}}Erf\left[\sqrt{\beta}\left(R-\epsilon-\sqrt{R^{2}-x^{2}}\right)\right]\
$$
(everything's a constant except $x$)
...and someone told me that differentiating $I$ could help evaluate it.
Can someone explain? Or help evaluate this? I've never really seen this kind of integral before, but I heard it's do-able.
Cheers!

A: The integrand seems not to depend on $y$. Why is that?
Anyway, I'll give you a hint:
$$ I = \int \text{Erf}(x) e^{-{x^2}} dx =  \frac{\sqrt{\pi}}{2} \text{Erf}^2(x)  - \frac{\sqrt{\pi}}{2} \int  \frac{2}{\sqrt{\pi}} e^{-x^2} \text{Erf}(x) dx = \frac{\sqrt{\pi}}{2} \text{Erf}^2(x) - I,$$
then:
$$ I = \frac{\sqrt{\pi}}{4} \text{Erf}^2(x).$$
I hope this may help you.
Cheers!

To evaluate the integral I often use this "trick" (chain rule):
$$\int f g \, dx = F g - \int F g' \, dx,$$
where $F = \int f \, dx$ is a primitive of $f$. Subsitute $f = e^{-x^2}$ and $g = \text{Erf}(x)$ and take into account that: $\int e^{-x^2} \, dx = \sqrt{\pi} \, \text{Erf}(x)/2$.


text:
Q: How to validate infix notation in javascript? I have an infix expression: ((attribute1*attribute2)/attribute3+attribute4)
It may vary according to the user input. I want to check whether the expression is valid.
Valid example: ((attribute1*attribute2)/attribute3+attribute4)
Invalid example: (attrribute1*attribute2+*(attribute3)
The second one has no closing parenthesis; also the * operator is not needed. How can I perform this sort of validation in javascript?
Now this is my regex:
/ *\+? *\-? *[a-zA-Z0-9]+ *( *[\+\-\*\/\=\<\>\!\&\|\%] *\+? *\-? *[a-zA-Z0-9]+ *)*/

I need a regex for comparison operators like <= , >= , != , == etc. How can I implement this?

A: You could try something like this:
function validateInfix(infix) {
    var balance = 0;
    // remove white spaces to simplify regex
    infix = infix.replace(/\s/g, '');

    // if it has empty parenthesis then is not valid
    if (/\(\)/.test(infix)) {
        return false;
    }

    // valid values: integers and identifiers
    var value = '(\\d+|[a-zA-Z_]\\w*)';
    // the unary '+' and '-'
    var unaryOper = '[\\+\\-]?';
    // the arithmetic operators
    var arithOper = '[\\+\\-\\*\\/]';
    // the comparison operators
    var compOper = '(\\<\\=?|\\>\\=?|\\=\\=|\\!\\=)';

    // if it has more than one comparison operator then is not valid
    if (infix.match(new RegExp(compOper, 'g')).length > 1) {
        return false;
    }

    // the combined final regex: /[\+\-]?(\d+|[a-zA-Z_]\w*)(([\+\-\*\/]|(\<\=?|\>\=?|\=\=|\!\=))[\+\-]?(\d+|[a-zA-Z_]\w*))*/
    var regex = new RegExp(unaryOper + value + '((' + arithOper + '|' + compOper + ')' + unaryOper + value + ')*');

    // validate parenthesis balance
    for (var i = 0; i < infix.length; i++) {
        if (infix[i] == '(') {
            balance++;
        }
        else if (infix[i] == ')') {
            balance--;
        }

        if (balance < 0) {
            return false;
        }
    }

    if (balance > 0) {
        return false;
    }

    // remove all the parenthesis
    infix = infix.replace(/[\(\)]/g, '');

    return regex.test(infix);
}

The idea is to check first the parenthesis balance, then remove them all given that we only want to validate and not evaluate, and then match the remaining expression to a regex (which may not be perfect, I'm not a regex expert). And... just in case: infix argument must be a string.
Edit
I noticed a couple of details and changed the code a bit:

*

*Added the operators you needed the regex to match too.

*Removed white spaces to get rid of regex junk.

*Checked if the expression had empty parenthesis.

*Checked if the expression had more than one comparison operators.

*Changed this \+?\-? by this [\+\-]?.

*Changed string match method by regex test method where possible.

*Changed this [a-zA-Z0-9] by this (\d+|[a-zA-Z_]\w*) since the first one matches wrong identifiers like 53abc.

*For better understanding and clarity, extracted pieces of regex into separate variables and built the final one from these.

Hope this is ok for you now :)


text:
Q: Getting file names in archive of an ArchiveInputStream Is there a way to get the just the filenames inside a archive with org.apache.commons ArchiveInputStream?
At the moment i'm using
while ((archiveEntry = archiveInputStream.getNextEntry()) != null) {
  inputNames.add(archiveEntry.getName());
}

But to iterate over the whole stream when i just need the name of the files is very slow. Especially for large amounts of data .


text:
Q: How to use Future.wait with flutter? Actually, I have many sublists and I have to display it one by one after recieving a signal (list contains[170,204]).
that's why I have to use Future.wait. But this didn't work for me. what happens actually is that I send the first sublist then I resend the same sublist and after this there was no sublist sended.
But when I tried to change the future.wait by Future.delayed it worked as expected. so the problem is on how I used the Future .wait
this is my code :

  getValue() {
    _characteristic42?.value.listen(
        (notification) async => {print("Notification Value : $notification")});
  }
if (notification[0] == 170 && notification[1] == 204)
                  {
                    await Future.forEach(chun, (ch) async {

                      await Future.delayed(const Duration(seconds: 4));
                      await c.write(ch, withoutResponse: true);
                      await c.read();
                      await Future.wait(getValue());
                    })

I would be very thankful if you can help me resolving this issue

A:  await Future.wait([
  FirstFutureFunction(),
  secondFutureFunction(),
]);

A: there are 2 approach to handle Future function. with await and with then.
here an article i wrote to explain it: await vs then in Flutter
actually without Future.wait, your current code its already interupt the process before execute next function. because you are using await.
i think you missed this meaning:   this => syntax means your function return 1 argument.in your code,it will return the print notification value.
solution:
getValue() {
  _characteristic42?.value.listen(
        (notification) async {
 print("Notification Value : $notification"));

if (notification[0] == 170 && notification[1] == 204)
{
  await c.write(yoursublist, withoutResponse: true);
  await c.read();
  });
 }
}

with the code above, its already execute line by line.
in that article i had explain the detail by example.


text:
Q: Doom 4 (Doom 2016) Multiplayer: What's the difference between red and yellow hit numbers? When I hit an enemy player, a number pops up showing how much damage I've done to the player. But sometimes the number is red and sometimes it's yellow. What's the red for and what's the yellow for?

A: The yellow indicator shows normal hits to any bodypart except the head and the red indicators are for headshots , so normaly the red indicator shows a higher number due to the fact that headshots deal more damage.

A: Red - Normal hits.
Yellow - Critical hits, like headshots with Vortex rifle, or well-placed close-range shot with a shotgun.


text:
Q: sql Group by and max() doesn't get the right results I have the following table
mes_id | user_a | user_b | message | room | time
------------------------------------------------------
1      | 23     | 24     | hello   | 1    | 5676766767

user_a sent a message for user_b in room 1
I want to get the all the last messages received for a specific user (for example user_b) per room, I have tried few queries but I didn't get the right one.
This solution didn't work for me: sql_group_by_max
An update
I am using 5.5.18 MySQL Server
ok
this gave me the result thanks
SELECT *
FROM messeges C
JOIN (
       SELECT room, user_a, MAX( messeges.date ) AS max_time
       FROM messeges
       GROUP BY room, user_a
      )a
ON a.room = c.room

AND a.user_a = c.user_a
AND a.max_time = c.date

WHERE c.user_b =  '396'

A: try this:
select * from chat C join
(select  room,user_b,MAX([time]) as max_time
from chat
group by room,user_b)a
on a.room=c.room
and a.user_b=c.user_b
and a.max_time=c.[time]

If you want multiple rows, (In sql server)
with cte as (select *,ROW_NUMBER ()
     over (partition by room,user_b order by [time] desc) as rownum from chat)
select * from cte order by rownum

A: try this:
   Select *
FROM chat a
INNER JOIN ( Select  user_a, user_b , room ,MAX(time) as max_time
    FROM chat
    group by user_a, user_b , room) b on a.user_a=b.user_a and a.user_b=b.user_b and a.room=b.room


text:
Q: Why do I get a borrow error when using Option::map, but not when manually matching? I have this working function:
fn clear_job(state: State<MyState>) -> Option<String> {
    let mut guard = state.job.lock().unwrap();
    let maybe_job: &mut Option<Job> = &mut *guard;
    // Job is not Copy nor Clone

    match maybe_job {
        None => None,
        Some(job) => match job {
            Job::InProgress { .. } => Some("Can't clear in progress job".into()),
            _ => {
                *maybe_job = None;
                Some("Job cleared".into())
            },
        },
    }
}

I return None if I have None and Some if I have Some, which is… exactly what Option::map() is !
I tried to rewrite this function:
fn clear_job(state: State<MyState>) -> Option<String> {
    let mut guard = state.job.lock().unwrap();
    let maybe_job: &mut Option<Job> = &mut *guard;

    maybe_job.as_ref().map(|job| match job {
        Job::InProgress { .. } => "Can't clear in progress job".into(),
        _ => {
            *maybe_job = None;
            "Job cleared".into()
        },
    })
}

This gets me this error:
error[E0500]: closure requires unique access to `maybe_job` but it is already borrowed
   --> src/main.rs:113:28
    |
113 |     maybe_job.as_ref().map(|job| match job {
    |     ---------          --- ^^^^^ closure construction occurs here
    |     |                  |
    |     |                  first borrow later used by call
    |     borrow occurs here
...
116 |             *maybe_job = None;
    |              --------- second borrow occurs due to use of `maybe_job` in closure

I kinda understand why the error is there; what I don't understand is how I don't get an error in the match version, because semantically I'm doing the same thing: reading into maybe_job, getting a borrow on job (so supposedly on maybe_job too), but still writing into *maybe_job.
Why am I allowed in the first version but not in the second? Is there a way to use Option::map in this situation?

A:
I kinda understand why the error is there; what I don't understand is how I don't get an error in the match version, because semantically I'm doing the same thing: reading into maybe_job, getting a borrow on job (so supposedly on maybe_job too), but still writing into *maybe_job.

In the match case, the compiler helps you out by dropping the borrow on job before you write to *maybe_job. You can test this yourself - use job after you do *maybe_job = None, and you'll explicitly borrow job for too long, and the compiler will error.
In the map case, the borrow which is the argument to the closure |job| is an immutable borrow on maybe_job. Accessing a variable from a closure is also a borrow (of the variable in the stack) so trying to assign to *maybe_job requires taking a mutable borrow on an already borrowed value.
The reason the compiler allows one and not the other is simply a question of how complex the analysis can be - to automatically drop the borrow in |job|, the compiler would have to detect and ensure that maybe_job.as_ref() is the only borrow on maybe_job - which is very tricky. What happens if you do maybe_job.as_ref().my_function().map(...) - and my_function() copies the immutable reference?


text:
Q: React router & Phonegap - First page not found I have a react app using react router.
When i bundle this up into phonegap and connect to it using the phonegap app on my iPhone, i go straight to my 404 (not found) page.
From my 404 page i am then able to navigate to the rest of my app (if i include the menu on the page)
Below is my react router code, has anyone faced a similar issue?
ReactDOM.render(
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Directory} />
            <Route path="feed" component={Feed} />
            <Route path="page">
                <Route path="about" component={About}/>
            </Route>
            <Route path="*" component={Four04Page}/>
        </Route>
    </Router>,
    document.getElementById('app')
);

A: I recently had a similar issue and was able to resolve it by using the routerHistory instead of the default browserHistory.
How this is specifically implemented depends on which version of React Router you are on.
I followed the v2.0 migration guide to implement it:
https://github.com/reactjs/react-router/blob/095ed6cf51d3c4755f13b428182e8ec2df593277/upgrade-guides/v2.0.0.md#using-custom-histories


text:
Q: Eclipse Code Corrupted after Crash I closed Eclipse because I had a feeling my PC was gonna crash (been acting funny today), and it said it saved my workspace and closed normally.
But when I went back in after reboot, my workspace wasn't loading - even after selecting the right one my projects wouldn't show and the layout was reverted to default....not such a big deal, just re-imported.
But... One of the source files I was working on seems to have been corrupted, replaced with one continuous line of squares, which is kind of a big deal :/
Any thoughts on what caused this? I know there's probably no chance of getting that file back, but if anyone has had a similar experience or knows what the jaysus happened that'd be cool! Ideally I'd like if this never happened again...

A: Problem was related to my SSD: Weird bug where after 5184 hours of use it would shutdown.
Firmware update fixes the problem.
More here: http://www.tomshardware.com/news/Crucial-m4-Firmware-BSOD,14544.html


text:
Q: how to accessing my web application on netbeans and glassfish server from my phone I'm working on ejb project using netbeans,glassfish server and java db.
The project work nice on my localhost and I can put my ip address instead of my localhost and it work prefect also.
192.168.1.156:8080/project/ work well from my PC.
LOCALHOST:8080/PROJECT/ work well from my PC.
Now I'm trying to access this project from my phone using my local ip address and 8080 port but it doesn't work.
How can I access my project from remote machine on the same LAN?
I work on windows 7 OS.
Thank you.


text:
Q: Significantly different LAN transmit speed I have two machines, one Mac and one Linux, in the same local network. I tried to transfer files by using one of them as an HTTP server, it turned out the download speeds were quite different based on which one was the server. If I use Mac as the server, the download speed was around 3MB/s, but in the opposite way, it's about 12MB/s. Then I used iperf3 to test the speed between them and got a similar result:
When Mac was the server and Linux the client:
[ ID] Interval           Transfer     Bitrate         Retr
[  5]   0.00-10.00  sec  28.7 MBytes  2942 KBytes/sec  1905             sender
[  5]   0.00-10.00  sec  28.4 MBytes  2913 KBytes/sec                  receiver

When Linux was the server and Mac the client:
[ ID] Interval           Transfer     Bandwidth
[  4]   0.00-10.00  sec  162 MBytes  16572 KBytes/sec                  sender
[  4]   0.00-10.00  sec  161 MBytes  16526 KBytes/sec                  receiver

I asked a friend to do the download test for me and he told me the speeds were both around 1MB/s on his two Mac, which was far from the router's capacity. How could this happen?

A: This isn't going to be much of an answer, but it will probably be long enough that it is not going to fit into a comment.
Your observation of "bogus TCP header length" is very interesting; I have never seen it in a capture before, so I wanted to check out exactly what it means.  Here you can see that it means that the wireshark TCP protocol dissector can't make any sense of the segment, because the TCP header length is less than the minimum TCP header length.
So it seems you have an invalid TCP segment.  Only two causes I know are that it was somehow erroneously constructed (i.e. a bug or intrusion attempt) or that it was corrupted.
I have certainly created plenty of invalid segments when working with raw sockets, and I have seen plenty of forged segments that were not standards conforming, but this doesn't seem likely to be the case in your situation.
So, based on my experience, it seems most likely that it has been somehow corrupted.  Although if it was a transmitted packet in the capture, then you are actually sending a invalid segment.  So in what follows, I'm assuming it was a received segment.
So where could it have been corrupted?  The first mystery is that you are seeing it at all in a capture.  If it had been corrupted in the network, the Frame Check Sequence (FCS, a CRC) shouldn't match, and it should have been discarded.
However, it is possible to configure your NIC/Driver to deliver segments with an invalid FCS.  On linux you would check/configure these settings with ethtool and the relevant parameters are rx-fcs and rx-all (sorry, I don't know how to do this on a Mac).  If those are both "off," your NIC/Driver should not be sending you segments with an invalid FCS and hence they wouldn't appear in a capture.
Since you are seeing the segments with an invalid TCP header length in your capture, and assuming your NIC/Driver is configured to drop segments with an invalid FCS, then your NIC saw a valid segment on the wire, and the segment was either corrupted before the FCS was calculated by a transmitter (usually done in the NIC), or corrupted after the FCS was validated by the receiving NIC.
In both these cases, there is a DMA transfer over a bus (e.g. PCI-e) between CPU memory and the NIC.  I'm guessing there is a hardware problem causing corruption here, but I'm not so confident in this guess as I have little information to go on.
You might try getting a capture on both ends to compare what is transmitted to what is received (particularly in the case of segments with invalid TCP header lengths).  You can match segments in the captures using the ID field in the IP header (assuming that doesn't get corrupted as well).
Good luck figuring it out!


text:
Q: How to contain fullscreen.js slides in a div of fixed height and fixed width By default, any example of fullpage.js is written to render the slides at maximum height and width of the screen (full screen).
However, I am trying to contain the slides in one fixed-sized div in my html page. I have a div of fixed height and fixed width and would wish the fullpage.js slides to play within that div. I tried but I cannot get the height to be reduced to prescribed fixed height. The fixed width works fine.

Responsive

This example will turn to normal scroll when the window size gets smaller than 600px height

Ideal for small screens

This example uses responsiveHeight: 600

Keep it simple!

A: As stated here:

This is a FULL PAGE plugin. There's no such option.

but is possible to hack it via CSS.
Code:
$('#fullpage').fullpage({
    sectionsColor: ['#1bbc9b', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'],
    anchors: ['firstPage', 'secondPage', '3rdPage', '4thpage', 'lastPage'],
    css3: true,
    verticalCentered:false
});

CSS:
#section0, #section1, #section2 {
    height: auto !important;
}

And don't forget the verticalCentered: false option. Othewise you would also need to overwrite another wrapper fp-table
Demo: http://jsfiddle.net/IrvinDominin/o46332j6/
Update
Some time ago fullpage.js included an option to create smaller or bigger sections by using fp-auto-height class.
Ref: https://github.com/alvarotrigo/fullPage.js#creating-smaller-sections
Demo: http://jsfiddle.net/IrvinDominin/o46332j6/2/


text:
Q: Some native keyboard accent shortcuts not working since OS X 10.11.3 Update I have a Qwerty keyboard on my MacBook Pro late-2015, set to the standard US layout, that I sometime use to write French accentuated characters.
However, since the last OS X update, some accent shortcuts are not working anymore. More specifically, Option6 (+ some vowel), which used to produce circumflex accents now writes §, and Optionc, used for c cedilla, is now used for capitalising the last written word. I can still write these characters using the press and hold method, but it's pretty inefficient.
How can I re-enable these accent shortcuts?

A: Go to system preferences/keyboard/input sources and make sure that only the item called "US International PC" is on the list, or the item called "ABC Extended" (known as "US Extended" prior to OS X 10.11).
(The standard US layout does not use Option 6 for circumflex, it uses Option i. The US International PC layout uses Shift 6, while ABC Extended uses Option 6. I suspect you were using one of these layouts rather than "US".)

A: The standard US keyboard layout always yields a § if alt6 is pressed.
To get your desired results enable the US extended (or ABC Extended in OS X 10.11) keyboard layout:

*

*alt6 -> ˆ

*alt6+e -> ê

*altc+c -> ç

A: I realise that you probablyuse the command shortcuts for increased speed, but it may be helpful to you (and others) to consider the slightly longer method of holding down a character until the "pop up" choice list appears.  For example, holding down c or e on my (British English) system yields:

This has the added benefit that the list can be customised to a certain extent (if you are happy messing with the plist files)


text:
Q: New-SPSite User cannot be found - SharePoint 2013 Remote PowerShell I am using Remote PowerShell Session to create SharePoint Site. The client computer is not part of AD forest.
I have used the following PowerShell commands to enter into the remote session.
$cred = Get-Credential
$session = New-PSSession -ComputerName "SPServerName" -Credential $cred
Enter-PSSession $session
Add-PSSnapin Microsoft.SharePoint.PowerShell

and following commands to create SharePoint Site
$w = Get-SPWebApplication http://SPServerName:8000/

New-SPSite http://sp.test.com -OwnerAlias "ad\spuser" -HostHeaderWebApplication $w -Name "Test Site"

And I am getting the following error

New-SPSite : User cannot be found.
  At line:1 char:1
  + New-SPSite http://sp.test.com -OwnerAlias "ad\spuser" -HostH ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidData: (Microsoft.Share...SPCmdletNewSite:SPCmdletNewSite) [New-SPSite], SPException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSite

However, I am able to create SharePoint Site successfully from within SharePoint server using same PowerShell commands.

A: You can follow below article to configure remote PowerShell on SharePoint Server.
https://blogs.technet.microsoft.com/anneste/2014/09/17/how-to-enable-remote-powershell-for-sharepoint-2013-for-non-administrators/
Since you are doing remote PowerShell you need to make sure PowerShell Process is running under SharePoint Farm Admin or SharePoint Managed Account.


text:
Q: How long does the battery last on mid-2011 MacBook Airs? I know that one of the big innovations in the MacBook Air was in the battery (which gets most of the internal volume of the computer!)
What is a normal loss of battery life (change in usable time on battery starting from a full charge) for a mid-2011 13" MacBook Air? After how many charge cycles does one expect to see a substantial reduction in usable time? Is there any recommended course of action for someone to take to slow or reverse this degradation once it begins?

A: I don't know what the expected life is (although the specs on the Apple website are always pretty accurate for me) - but of course it depends on your usage.
As far as I understand it, the MBA batteries are of a similar design to the MBP ones of the same generation. I always link to this page (which is on the Apple Discussions site) about preserving battery life - as I've followed it as closely to the letter as I can, and I still get a good 85-90% of the life out of my two-year old pro. I've quoted some below.

Do's & Don'ts
DO use your battery frequently and lightly, ideally completing 1-2
  charge cycles per week (minimum one charge cycle per month).
DO properly calibrate your battery when new and approximately every
  2-3 months thereafter.
DON'T fully discharge your battery frequently (the infrequent,
  periodic calibration is an exception).
DON'T store your battery (or your computer) in a high temperature
  environment, such as the trunk of a car, especially a fully-charged
  battery.
DON'T run your MacBook or MacBook Pro on AC power with the battery
  removed.

Note: I had a quick look and the pro and air batteries are the same material, so the above instructions will work well for them too.

A: Battery Life
Apple's documentation states that the battery of the Macbook Air performs just like the batteries of the Macbook Pro:

*

*The built-in battery of your MacBook, MacBook Pro or MacBook Air is
designed to deliver up to 1000 full charge and discharge cycles before
it reaches 80 percent of its original capacity.

*In addition, Adaptive
Charging reduces the wear and tear on the battery giving it a lifespan
of up to 5 years.

*During this lifespan the batteries will have a fast charge to 80% of the current battery capacity (2-3 hours). [source]

Battery Maintenance

*

*Do not leave your Macbook plugged in all the time. The battery juices need to move from time to time. It's recommended that you charge and discharge the battery at least once per month.

*Temperature: Keeping your Mac at room temperature (22°C/72°F) is ideal.

*Long Term Storage: Apple recommends that you store the battery with a 50% charge, if you are not planning on using it for at least half a year.
The innovation in the design of the battery of the Macbook Air was not about increasing capacity, but about the ability to manufactures them very thin. The batteries of the Macbook Air are located towards the thin end of the Macbook Air.

A: I believe this question will probably tell you a lot about the Macbook's battery.
And, however this movie is about the 2009 MacBook Pro, the same technique is used in the 2011 MacBook Air. Which will allow you to charge your MacBook Air about a 1000 times before the battery is dead. (Which in that case, you probably could use it anyway, but not on the 8h lifespan)

A: Based on my personal experience with my wife's MacBook Air 13" i5, and my 11" i5, I would say, on average (just browsing the web, typing, email, watch a few YouTube videos, etc.), the 13" models will get 5-6 hours, while the 11" models will get 3-4 hours.
One thing that has helped both of us keep getting an extra hour or two is the installation of FlashBlock in Chrome. Every time you load a site with flash ads or videos (besides YouTube), the fans go on after a minute, and processor activity jumps to 50-100%. Just leaving the window open, and doing nothing else, battery life is usually halved.
I would dump flash altogether, but there are one or two sites I visit that only use flash for video :(


text:
Q: Get id of recipient of each conversation I have a table like this.
| id-AI | from    | to    | text         |created_date
+----+---------+-------+-------------+-------------
| 1  | 7       | 1     | from 7 to 1  |2015-11-06 04:59:14
| 2  | 1       | 2     | from 1 to 2  |2015-11-06 04:57:06
| 3  | 7       | 1     | from 7 to 1  |2015-11-06 04:25:45
| 4  | 1       | 6     | from 1 to 6  |2015-11-06 04:25:32
| 5  | 1       | 5     | from 1 to 5  |2015-11-06 04:25:16

I want a list like this.A list of users who knocked me or I knock him/her or we had a long conversation. the list I want should be in latest order just like facebook messaging.
| users |
+-------+
| 7
| 2
| 6
| 5

1 is main user_id. get list where 1 is involved(either in to or in from) then this is called conversation.

A: You can use the following query:
SELECT IF (`from` = 1, `to`, `from`)
FROM mytable
WHERE 1 IN (`from`, `to`)
ORDER BY created_date DESC

This will return either the creator or the recipient of each conversation in which user_id = 1 is involved.
Demo here
The get an ordered set of distinct user_id values use this query:
SELECT IF (`from` = 1, `to`, `from`)
FROM mytable
WHERE 1 IN (`from`, `to`)
GROUP BY IF (`from` = 1, `to`, `from`)
ORDER BY MAX(created_date) DESC

Demo here

A: Using UNION:
SELECT user
FROM (SELECT to AS user, created_date
      FROM mytable
      WHERE from = 1)
      UNION
      SELECT from AS user, created_date
      FROM mytable
      WHERE to = 1) x
GROUP BY user
ORDER BY MAX(created_date) DESC


text:
Q: accessing facebook private messages using access token using Facebook API We have angularJs & C# web aplication.
We are planning to use our facebook page to handle our customer issues and complaints.
We will show facebook visitor posts in our website so our representative notice it and reply on same. (may be new comment or reply existing)
Our representative ask customer to send private message and then user initiate message to us and then we can see that message in our website and reply to that message through our website.
By this way we will able to sort out problems of our customer through our application.
public static FacebookClient GetClientApplicationAccessToken(FacebookClient client)
{
    dynamic accessToken = client.Get("oauth/access_token", new
    {
        client_id = "my_ApplicationId",
        client_secret = "my_AppSecretKey",
        grant_type = "client_credentials"
    });
    client.AccessToken = accessToken.access_token;
    return client;
}

public static dynamic GetFacebookPosts(string pageId)
{
    var client = new FacebookClient();
    GetClientApplicationAccessToken(client);
    dynamic postObject = client.Get("/" + pageId + "/feed?fields=message,from,created_time,full_picture");
    dynamic postJson = JsonConvert.DeserializeObject(posts);
    return postJson;
}

By this access token we are able to fetch Facebook post, but not possible when we try to fetch conversation between Our Facebook page & our customers through private messages.
dynamic postdaObject = newclient.Get("me?fields=conversations{messages{created_time,message}}");

I think when we use access token from above method i.e.GetClientApplicationAccessToken() it is not working. but if I replace hard coded user access token then it's working. As our application end user will see Facebook messages and will reply to them, it does not require FaceBook Login button. We need some permanent access token by which we can fetch private messages from Facebook without any login button. Kindly help me to solve this issue.


text:
Q: How to get the number of total results when there is LIMIT in query? I have a query like this:
select * from table where id <= 10 limit 5;  // table has +10 rows

The number of result in the above query ^ is 10 rows. Now I want to know, how can I get the number of total result in this query:
select * from table where col = 'anything' limit 5;

How to calculate the number of all results (regardless of limit) in this ^ ?
Actually I want this number:
select count(*) as total_number from table where col = 'anything'

Now I want to know how can I get the number of total results without another query.

A: You need the SQL_CALC_FOUND_ROWS option in your query and FOUND_ROWS() function to do this:
DECLARE @rows int
SELECT SQL_CALC_FOUND_ROWS * from table where col = 'anything' limit 5;

SET @rows = FOUND_ROWS(); --for a later use

A: Add a column, total, for example:
select t.*
     , (select count(*) from tbl where col = t.col) as total
from tbl t
where t.col = 'anything'
limit 5

As stated by @Tim Biegeleisen: limit keyword is applied after everything else, so the count(*) still returns the right answer.

A: Use sub-query
select *, (select count(*) from table where col = 'anything') as total
from table where col = 'anything' limit 5;


text:
Q: Jenkins: How to execute shell script in a Windows slave I have a Windows slave, with bash installed. I'm trying to run a shell script on it as a pre-build step. Any ideas on how I can do this?

A: You need to run bash with the script as an argument:
bash yourscript <arguments to your script here>

You may also need to supply the complete path to bash depending on your environment.

A: If your bash on Windows is part of a Cygwin install, the cygpath plugin will allow you to use 'Execute Shell' and do #!/bin/bash at the top of it, just like you would do for unix slaves.


text:
Q: Code not working when adding 1 day to date I have this code, which generates timeslots between $start and $end, with lengths of the $interval variable.
$schedule = [];
$start = strtotime('04/09/2019 09:00');
$end = strtotime('04/09/2019 19:00');
$interval = '30';

while ($start < $end) {

    $next = strtotime("+{$interval} minutes", $start);
    $schedule[] = [
            'startTime' => date('H:i', $start),
            'endTime' => date('H:i', $next)
        ];
    $start = $next;
};

print_r($schedule);

It returns the following:
Array
(
    [0] => Array
        (
            [startTime] => 09:00
            [endTime] => 09:30
        )

    [1] => Array
        (
            [startTime] => 09:30
            [endTime] => 10:00
        )

    ...

    [18] => Array
        (
            [startTime] => 18:00
            [endTime] => 18:30
        )

    [19] => Array
        (
            [startTime] => 18:30
            [endTime] => 19:00
        )

)

However when I add 1 day to the $start and $end variables, like:
$start = strtotime('04/10/2019 09:00');
$end = strtotime('04/10/2019 19:00');
It returns an empty array, why does this happen?