text:
Q: How to migrate a Room database from one encryption passphrase to another? I ran into an issue where an application I'm working on has encryption enabled for the Room database, using SQLCipher, but the actual passphrase was not formed securely. I have the new, secure method of setting up new databases up and running, but there's a problem: how to migrate the existing database to use the new passphrase?
I have set up a method to check whether or not the database uses the unsecure passphrase, like so:
if (DatabaseEncryptor.isUnsecure()) {
    // Old, unsecure database in use; should migrate to a secure one
}

// All should be good now, set up the secure support factory
builder.openHelperFactory(DatabaseEncryptor.getSupportFactory(context))
    .fallbackToDesctructiveMigration()

Is it possible to just change the passphrase for the existing database? If not, how can the data be transferred from the old, unsecure database to the new, secure database?

A: Found out that re-keying the database is rather straight-forward. Here's the solution I ended up using:
val dbFilePath = context.getDatabasePath(DATABASE_NAME)
if (dbFilePath.exists()) {
    SQLiteDatabase.loadLibs(context)
    val db = SQLiteDatabase.openDatabase(
        dbFilePath.absolutePath,
        OLD_PASSPHRASE,
        null,
        SQLiteDatabase.OPEN_READWRITE
    )

    if (db.isOpen) {
        db.rawExecSQL("PRAGMA key = '${OLD_PASSPHRASE}'")
        db.rawExecSQL("PRAGMA rekey = '${NEW_PASSPHRASE}'")
        db.close()
    }
}


text:
Q: Limit of an absolute function I'm currently studying for my Analysis exam, but can't seem to get the proof for the following limit.
Let $f : ℝ→ ℝ$ be defined by:
$$f(x) = x^2 − |x|, x ∈ ℝ$$
Using the definition of limit of a real function at a point,
show that :
$$\lim_{x \to c} f(x) = c^2 - |c|,c∈ ℝ$$
I have been able to use the delta-epsilon proofs in other examples but am struggling with this one.

A: Choose $c\in \mathbb{R}$ and choose $\varepsilon >0$. Then
$$|f(x)-f(c)|=|x^2-c^2+|c|-|x||\leq |x^2-c^2|+||c|-|x||\leq |x-c||x+c|+|x-c|$$ for all $x$. Here we used the triangle inequality and the reverse triangle inequality. If $|x-c|< \delta$, we see that $$|f(x)-f(c)|< \delta(|x+c|-1).$$
I'll leave the rest up to you. Use the $|x-c|<\delta$ to find an upperbound of $|x+c|$ in terms of $\delta$. Then choose $\delta$ appropriately to make $|f(x)-f(c)|<\varepsilon$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: escape all punctuation characters in R Consider having the string: string<- "The qu!ck, brown fox jumps over thelazyd*g!" and you wish to escape all punctuation. Thus:
escaped_string<-"The qu\\!ck\\, brown fox jumps over the \\`lazy\\` d\\*g"

I have unsuccessfully tried:
>gsub(pattern = "[[:punct:]]",replacement="\\1",string)
[1] "The quck brown fox jumps over the lazy dg

Thoughts? Ideas?

A: You need to use a capturing group and use
string <- "The qu!ck, brown fox jumps over the `lazy` d*g!"
gsub(pattern = "([[:punct:]])",replacement="\\\\\\1",string)
[1] "The qu\\!ck\\, brown fox jumps over the \\`lazy\\` d\\*g\\!"

See the online R demo
The pair of unescaped parentheses in ([[:punct:]]) creates a capturing group that you may access with \1 backreference from the replacement pattern. The replacement pattern should be defined as "\\\\\\1", since to replace with a literal backslash you need to escape the literal backslash (thus, "\\\\" denotes one replacing backslash) and the backreference should be defined with "\\1" (also needs a literal backslash).


text:
Q: Smallest $k$ so that $k$-wise independence guarantees a constant expected minimum Imagine you sample $n$ numbers with replacement uniformly from the integers $1,\dots, n$ (we can assume $n$ is large).  Let $X$ be the minimum of these samples.  I am interested in $\mathbb{E}(X)$ but with a twist. All I know is that the samples are uniform and $k$-wise independent for some $k$.

What is the smallest $k$ so that there is a constant upper bound for $\mathbb{E}(X)$?

We know from the very nice answer of Will Sawin at Expected value of the minimum with limited independence that for pairwise independence, that is for $k=2$, $ \mathbb{E}(X)$ can be as large as approximately $\log {n}$.  Obviously if $k=n$ then there is a constant upper bound on the expected minimum. What can we say for $k$ between $2$ and $n$?

A: I can do $k\geq 4$. This is done using a method similar to the upper bound from last time. Let $N_m$ be the number of samples that are at most $m$. Then we wish to upper bound the probability that $N_m=0$. We can do this using the fourth moment method, because the first four moments are the same as for a totally independent and uniform distribution.
$E(N_m-m)^4=3m^2(n-m)^2(n-1)/n^3 + (m^3+(n-m)^3) m(n-m)/n^4= O(m^2)$
So the probability that $N_m-m= -m$ is $O(1/m^2)$. Summing over all $m$ and adding $1$  to find the expectation of the minimum gives something $O(1)$. (Close to $1+ \pi^2/2$, I think.)
I'm not sure about $k=3$, but I'll think about it


text:
Q: gridview and sqldatasource control in asp.net i have a gridview which is populating from sql datasource defined at designed, i have configured sqldatasource to select, update and delete, i have a title field in my table which is primary key, it was working fine and updating the records too. until i removed the boundfields and placed templatefield and itemtemplate. after that i gets an error saying:

You have specified that your update command compares all values on SqlDataSource 'SqlDataSource1', but the dictionary passed in for oldValues is empty.  Pass in a valid dictionary for update or change your mode to OverwriteChanges.

if i make the ConflictDetection = "OverwriteChanges" it works fine but does not update..
the requirement for the itemtemplate is because i want to display footer template for new records and change the default edit and delete button to imagebutton...
How should i make it work using itemtemplate...

A: you can add the columns you want persisted by adding them to the gridview datakeynames collection.


text:
Q: How to get nodes using xpath When I have 2 set of nodes with same element name for ex :
<contacts>
    <names>
      ...
    </names>
    <names>
      ...
    </names>
</contacts>

Normally I'd use //contacts/names to get the node, but how do I do if they have the same name how do I get second or first or nth?

A: For the provided XML document use:
/contacts/names[1]

the above selects the first names element.
/contacts/names[2]

the above selects the second names element.
Try to avoid using the // abbreviation as much as possible, because it is usually grossly inefficient, causes all the (sub)tree roted in the context node to be traversed.

A: Use //contacts/names[n] to get the nth names node. For example: //contacts/names[1] gets the first names node while //contacts/names[2] gets the second names node, etc.

A: You can do this to get the first and/or second specifically:
//contacts/names[1]
//contacts/names[2]


text:
Q: Trouble reading data in Firebase Cloud Function Trying to read a pushToken from a given user in the users collection (after an update operation on another collection) returns undefined

exports.addDenuncia = functions.firestore
  .document('Denuncias/{denunciaID}')
  .onWrite((snap, context) => {
    const doc = snap.after.data()
    const classificadoId = doc.cid
    const idTo = doc.peerId

    db.collection('Classificados').doc(classificadoId)
      .update({
        aprovado: false
      })
      .then(r => {
        getToken(idTo).then(token => {
          // sendMsg...
        })
      }).catch(updateErr => {
        console.log("updateErr: " + updateErr)
      })

    async function getToken(id) {
      let response = "getTokenResponse"
      console.log("id in getToken: " + id)
      return db.collection('users').doc(id).get()
        .then(user => {
          console.log("user in getToken: " + user.data())
          response = user.data().pushToken
        })
        .catch(e => {
          console.log("error get userToken: " + e)
          response = e
        });
      return response
    }

    return null
  });

And this is from the FB console log:
-1:43:33.906 AM Function execution started
-1:43:36.799 AM Function execution took 2894 ms, finished with status: 'ok'
-1:43:43.797 AM id in getToken: Fm1RwJaVfmZoSgNEFHq4sbBgoEh1
-1:43:49.196 AM user in getToken: undefined
-1:43:49.196 AM error get userToken: TypeError: Cannot read property 'pushToken' of undefined
-1:43:49.196 AM returned token: undefined
And we can see in this screenshot from the db that the doc does exist:

Hope someone can point me to what I'm doing wrong here.
added screenshot of second example of @Renaud as deployed:

A: As Doug wrote in his comment, you need to "return a promise from the top level function that resolves when all the async work is complete". He also explains that very well in the official video series: https://firebase.google.com/docs/functions/video-series/ (in particular the 3 videos titled "Learn JavaScript Promises"). You should definitely watch them, highly recommended!
So, the following modifications to your code should work (untested):
exports.addDenuncia = functions.firestore
    .document('Denuncias/{denunciaID}')
    .onWrite(async (snap, context) => {   // <- note the async keyword

        try {

            const doc = snap.after.data()
            const classificadoId = doc.cid
            const idTo = doc.peerId

            await db.collection('Classificados').doc(classificadoId)
                .update({
                    aprovado: false
                });

            const userToSnapshot = await db.collection('users').doc(idTo).get();
            const token = userToSnapshot.data().pushToken;

            await sendMsg(token);  // <- Here you should take extra care to correctly deal with the asynchronous character of the sendMsg operation

            return null;  // <-- This return is key, in order to indicate to the Cloud Function platform that all the asynchronous work is done

        } catch (error) {
            console.log(error);
            return null;
        }

    });

Since you use an async function in your code, I've used the async/await syntax but we could very well write it by chaining the promises with the then() method, as shown below.
Also, I am not sure, in your case, that it adds any value to put the code that gets the token in a function (unless you want to call it from other Cloud Functions but then you should move it out of the addDenuncia Cloud Function). That's why it has been replaced by two lines of code within the main try block.
Version with chaining promises via the then() method
In this version we chain the different promises returned by the asynchronous methods with the then() method. Compared to the async/await version above, it shows very clearly what means "to return a promise from the top level function that resolves when all the asynchronous work is complete".
exports.addDenuncia = functions.firestore
    .document('Denuncias/{denunciaID}')
    .onWrite((snap, context) => {   // <- no more async keyword

        const doc = snap.after.data()
        const classificadoId = doc.cid
        const idTo = doc.peerId

        return db.collection('Classificados').doc(classificadoId)  // <- we return a promise from the top level function
            .update({
                aprovado: false
            })
            .then(() => {
                return db.collection('users').doc(idTo).get();
            })
            .then(userToSnapshot => {
                if {!userToSnapshot.exists) {
                   throw new Error('No document for the idTo user');
                }
                const token = userToSnapshot.data().pushToken;

                return sendMsg(token);   // Again, here we make the assumption that sendMsg is an asynchronous function
            })
            .catch(error => {
                console.log(error);
                return null;
            })

    });


text:
Q: Implementing search result for searching inside dictionary? I have a dictionary like,
var DataDict:[String:[String]] = [String:[String]]()

DataDict["fruits"] = ["apple","orange","pineapple","grape"]
DataDict["vehicle"] = ["car","cycle / scooter","bike"]
DataDict["colours"] = ["black","white","yellow","green","blue"]

so when I search in the search bar, if the searchText is fruits then the tableview should display the full array of fruits, or else whatever the searchText matches to the single object inside each key of DataDict?
So how will I achieve that to display the tableview. I need to implement that in searchBar textDidChange delegate.
Finllay I need to the display the result as, DataDict object as title and It's respective key as Subtitle.
ex:
apple
fruits

pineapple
fruits

A: You can do like this,
var DataDict:[String:[String]] = [String:[String]]()

DataDict["fruits"] = ["apple","orange","pineapple","grape"]
DataDict["vehicle"] = ["car","cycle / scooter","bike"]
DataDict["colours"] = ["black","white","yellow","green","blue"]

let filterarray = Array(DataDict.keys).filter { $0.contains("searchText")}

print("\(filterarray)")

for string in filterarray {

    print("\(DataDict[string]!)")
}

Now you can display the as your requirement with filterarray

A: try below method for searchingtext. Result can be displayed to table

func searchText(string:String) -> [String] {
        let text = string
        var DataDict:[String:[String]] = [String:[String]]()

        DataDict["fruits"] = ["apple","orange","pineapple","grape"]
        DataDict["vehicle"] = ["car","cycle / scooter","bike"]
        DataDict["colours"] = ["black","white","yellow","green","blue"]
        var searchedItems = [String]()
        for key in DataDict.keys {
            if text == key {
                if let items = DataDict[key]  {
                    searchedItems.removeAll()
                    searchedItems.append(contentsOf: items)
                }
                break;
            }
            else {
                if let items = DataDict[key]  {
                    let filterd = items.filter({ (x) -> Bool in
                        return x.lowercased().contains(text.lowercased())
                    })
                    if filterd.count > 0 {
                        searchedItems.append(contentsOf: filterd)
                    }
                }
            }
        }

        print("SearchedItems: \(searchedItems)")
        return searchedItems
    }

A: You may get array in this way also for faster response..
let arrTemp = Array(DataDict.keys).filter { $0.contains(searchBar.text!)}
print(DataDict[arrTemp[0]])

Hope it will work for you.. :)

A: I know its kind of late , but wanted to post an improved answer with the use of flatMap and filter.
var DataDict:[String:[String]] = [String:[String]]()

DataDict["fruits"] = ["apple","orange","pineapple","grape"]
DataDict["vehicle"] = ["car","cycle/scooter","bike"]
DataDict["colours"] = ["black","white","yellow","green","blue"]

let searchText = "orange"

func search() {
    var resultsArray = [String]()
    if DataDict[searchText] != nil {
        resultsArray = DataDict[searchText] ?? []
    }else {
        resultsArray = DataDict.flatMap{$0.1}.filter{ $0 == searchText}
    }

    print(resultsArray)
}

With the use of flat map you do not need to iterate each array of string as it flattens your nested dict into one. For more info on flatMap https://medium.com/@abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8
Hope this helps.

A: Create Empty array and initialize it will first key of the DataDict and make it the dataSource of the tableView
then every search replace it's contents with the new one that matches the search and reload the tableView


text:
Q: Detecting composite child items deleted Given a parent that contains child collection, attributed with:

[Include, Composition]
public virtual ICollection<FieldValue> FieldValues {get;set;}

and doing a load:

Context.Load(Context.GetQuery(),LoadBehavior.RefreshCurrent,true);

I see that FieldValues deleted by another user or a background process don't get removed from the client context. I can see how this could be by design, but how do I work around this? Is there a way to plug into load process to handle the deleted items?
Load callback happens too late, by the looks of it - everything has been merged already, there's nothing to compare.

A: Figured it out. Given a parent class Root, this is the way to run the load:
var originalValues = Context.EntityContainer
    .GetEntitySet<FieldValue>()
    .ToList(); // <-- make the pre-load copy of the child entities

Context.Load(Context.GetQuery(),
    LoadBehavior.RefreshCurrent,
    (LoadOperation<Root> o) =>
    {
        (from v in originalValues
        join nv in o.AllEntities.OfType<FieldValue>() on v equals nv into g
        from existing in g.DefaultIfEmpty()
        where existing == null
        select v)
        .ToList()
        .ForEach(Context.EntityContainer.GetEntitySet<FieldValue>().Detach);
    },
    null);

Note: FieldValue implements IEquatable<>, use PK if your child doesn't


text:
Q: Can I run multiple logic app from single master logic app Hi I have 16 logic app which load file from share point but I need to run all those separately.
Is there any way can I run all those 16 logic app from one master logic app.

A: Yes you could, the logic app support create the "child" Logic App. Then you could call nested Logic Apps directly from Logic Appps Designer.
If you want to run them in parallel, you could choose Add a parallel branch then call child Logic Apps.
Firstly ,your child Logic Apps need to be set with Manual – When an HTTP request is received trigger. Then go to the parent logic app add an action and search Logic App, then choose the Logic Apps you want.

About the details you could refer to this doc:Azure Logic Apps: Call nested Logic Apps directly from Logic Apps Designer.
Hope this could help you, if you still have other questions,please let me know.


text:
Q: Laravel scheduler task does not log the command's output in telescope I have a custom Laravel 6 command, and a scheduled task to execute that command. I expect that the command output get's logged in telescope (section "Scheduler" and details about a specific task), but actually only the command invocation is logged without any output.
The logging of output works well for a scheduled task of the built-in telescope:prune command.
Invoking my custom command from cli gives me the expected output.
This is my custom command:
<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;

class FixBulkBillGraphicTicketsWorkaround extends Command
{
    protected $signature = 'workarounds:fixBulkBillGraphicTickets';
    protected $description = 'Command description';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        $this->info('Moo foo');
    }
}

The $this->info() call is what the telescope-prune command implementation does as well. And as expected, it works fine from the cli:
$ php artisan workarounds:fixBulkBillGraphicTickets
Moo foo

The scheduler task definition:
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('telescope:prune --hours=168')
            ->everyMinute();

        $schedule->command('workarounds:fixBulkBillGraphicTickets')
            ->everyMinute();
    }

The Moo foo is not logged in telescope, but the output of the telescope:prune command is.
This question here might look similar to Laravel Schedule Task Output but there they talk about logging to log files.


text:
Q: 'video' is not defined Adding YouTube Comment In Python I'm trying to add a comment on a youtube video using youtube.commentThreads().insert,
and I can't figure out why this is happening:

videoId": video,
NameError: name 'video' is not defined

This happens after I entered my Google authentication key
here's my code:
import os

import requests
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "client_secret.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="id",
        maxResults=3,
        regionCode="US",
        relevanceLanguage="en",
        type="video",
        videoCategoryId="20"
    )

    youtube.commentThreads().insert(
        part="snippet",
        body={
            "snippet": {
                "videoId": video,
                "topLevelComment": {
                    "snippet": {
                        "textOriginal": text
                        }
                    }
                }
            }
    )
    response = request.execute()
    print(response)
    print ("comment added")

if __name__ == "__main__":
    main()


text:
Q: Finding partial derivative given $x,y,z$ related by $yx = \ln(x+z)$
We are given that $x, y, z$ are related by the equation $yx = \ln(x + z)$.
What is the partial derivative of $z$ with respect to $x$ at the point $(\frac e2, \frac 2e, \frac e2)$?

I'm sorry I don't have any work on this problem; I'm just really confused where to start because I just started learning partial derivatives.

A: Well, first we need to isolate $z$:
\begin{align}yx&=\ln(x+z)\\
e^{yx}&=e^{\ln(x+z)}\\
e^{yx}&=x+z\tag{$\dagger$}\\
z&=e^{yx}-x\end{align}
Now we compute the partial derivate with respect to $x$ (treating $y$ as a constant): \begin{align}\frac{\partial z}{\partial x}&=\frac{\partial}{\partial x}\left(e^{yx}-x\right)\\
&=ye^{yx}-1\end{align}
Finally we compute the value of this at $(x,y,z)=(\frac e2, \frac 2e, \frac e2)$:
\begin{align}ye^{yx}-1&=\frac 2e\times e^{\frac 2e\times\frac e2}-1\\
&=\frac 2e\times e^1-1\\
&=\frac{2e}{e}-1\\
&=2-1\\
&=1\end{align}

$(\dagger)$ Note that $e^{\ln(a)}=a$

A: Another way using implicit differentiation.
Deriving both sides of $yx=\ln(x+z)$    with respect to $x$ we have:
$$
x\frac{\partial y}{\partial x}+y=\frac{1}{x+z}\left( \frac{\partial z}{\partial x} +1\right)
$$
So:
$$
1+\frac{\partial z}{\partial x}=\left(x\frac{\partial y}{\partial x}+y \right)(x+z)
$$
and, since $(x+z)=e^{xy}$,
$$
\frac{\partial z}{\partial x}=\left(x\frac{\partial y}{\partial x}+y \right)e^{xy}-1
$$
If $y$ is independent from $x$ than $\frac{\partial y}{\partial x}=0$ and the derivative at $(\frac e2, \frac 2e, \frac e2)$ is
$$
\frac{\partial z}{\partial x}=ye^{xy}-1=\frac 2e \cdot e -1=1
$$

A: Express $z$ as a function of $x$ and $y$ and calculate the derivata of $z$ as a function of $x$, as if $y$ was a constant.


text:
Q: Notifications go crazy when using dual monitors with an ATI Radeon When you configure the system with dual monitor xinerama, everything works fine exept the notification area, goes crazy when I try to raise or lower the volume for example that flashes across the systray appears on both screens.
I use: ATI Radeon HD 5670, With Ubuntu 11.10 x64 clean, not any strange soft or theme, only ATI driver configured in dual monitor with xinerama.
*Note: Sorry, for my bad english.

A: Have you tried this driver:
http://www.upubuntu.com/2011/12/how-to-install-amd-catalyst-1112-linux.html


text:
Q: How to set opacity in parent div and not affect in child div? Hey i am searching in google but i can't fine any perfect answer
I want to Opacity in parent DIV but not Child  DIV
Example
HTML

Hello I am child

Css
.parent{
background:url('../images/madu.jpg') no-repeat 0 0;
}
.child{
Color:black;
}

Note: -- I want to background-image in Parent Div not Color

A: You can't. Css today simply doesn't allow that.
The logical rendering model is this one :

If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is .

Reference : css transparency
The solution is to use a different element composition, usually using fixed or computed positions for what is today defined as a child : it may appear logically and visualy for the user as a child but the element doesn't need to be really a child in your code.
A solution using css : fiddle
.parent {
    width:500px;
    height:200px;
    background-image:url('http://canop.org/blog/wp-content/uploads/2011/11/cropped-bandeau-cr%C3%AAte-011.jpg');
    opacity: 0.2;
}
.child {
    position: fixed;
    top:0;
}

Another solution with javascript : fiddle

A: May be it's good if you define your background-image in the :after pseudo class. Write like this:
.parent{
    width:300px;
    height:300px;
    position:relative;
    border:1px solid red;
}
.parent:after{
    content:'';
    background:url('http://www.dummyimage.com/300x300/000/fff&text=parent+image');
    width:300px;
    height:300px;
    position:absolute;
    top:0;
    left:0;
    opacity:0.5;
}
.child{
    background:yellow;
    position:relative;
    z-index:1;
}

Check this fiddle

A: You can do it with pseudo-elements: (demo on dabblet.com)

your markup:

 Hello I am child

css:
.parent{
    position: relative;
}

.parent:before {
    z-index: -1;
    content: '';
    position: absolute;

    opacity: 0.2;
    width: 400px;
    height: 200px;
    background: url('http://img42.imageshack.us/img42/1893/96c75664f7e94f9198ad113.png') no-repeat 0 0;
}

.child{
    Color:black;
}

A: As mentioned by Tom, background-color: rgba(229,229,229, 0.85) can do the trick.
Place that on the style of the parent element and child wont be affected.

A: I know this is old, but just in case it will help someone else.

child

Where rgba is: red, green, blue, and a is for transparency.

A: I had the same problem and I fixed by setting transparent png image as background for the parent tag.
This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

A: You can't do that, unless you take the child out of the parent and place it via positioning.
The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!


text:
Q: Css child selector on .row not working? I am totally not sure it has to do with my selector. I am using bootstrap and I am trying to make the three buttons of .row be on same line even after width< 576px. I tried changing the flex-wrap property to nowrap. But it is not working.
HTML:

                    <button type="button" class="btn btn-outline-primary active" id="all">All</button>

                    <button type="button" class="btn btn-outline-primary" id="online">Online</button>

                    <button type="button" class="btn btn-outline-primary" id="offline">Offline</button>

CSS:
 @media screen and (max-width: 576px) {
    .container{
        width: 100%;
    }
    .btn{
        width: 100px;
    }
    #button-container>row{
        flex-wrap: nowrap;
    }
 }

A: Use col-xs-4 instead of col-xm-4.
No need to write media query

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <button type="button" class="btn btn-outline-primary active" id="all">All</button>

        <button type="button" class="btn btn-outline-primary" id="online">Online</button>

        <button type="button" class="btn btn-outline-primary" id="offline">Offline</button>

And as a alternate if you are not able to change HTML part use below media query (you have not used . before row in your media queries)
@media screen and (max-width: 576px) {
  #button-container>.row {
    display: flex;
  }
  #button-container>.row>div {
    flex: 1;
  }
}


text:
Q: On delete in Microsoft access 2010( SQL) I have a problem with microsoft access 2010 in SQL. It gives me an syntax error and it highlights "DELETE" when I try to run this SQL statement.
CREATE TABLE nextOfKindonorAuth(
    name CHAR(30),
    licenseNo INTEGER,
    phone INTEGER,
    PRIMARY KEY(name, licenseNo),
    FOREIGN KEY(licenseNo)
    REFERENCES Driver
    ON DELETE CASCADE
)

Any help would be appreciated.

A: Without knowing your exact error, it looks like you are missing the reference to which column from the Driver table.
CREATE TABLE nextOfKindonorAuth(
  name CHAR(30),
  licenseNo INTEGER,
  phone INTEGER,
  PRIMARY KEY(name, licenseNo),
  FOREIGN KEY(licenseNo)
  REFERENCES Driver(COLUMN)
  ON DELETE CASCADE
)


text:
Q: Making human readable representations of an Integer Here's a coding problem for those that like this kind of thing. Let's see your implementations (in your language of choice, of course) of a function which returns a human readable String representation of a specified Integer. For example:

*

*humanReadable(1) returns "one".

*humanReadable(53) returns "fifty-three".

*humanReadable(723603) returns "seven hundred and twenty-three thousand, six hundred and three".

*humanReadable(1456376562) returns "one billion, four hundred and fifty-six million, three hundred and seventy-six thousand, five hundred and sixty-two".

Bonus points for particularly clever/elegant solutions!
It might seem like a pointless exercise, but there are number of real world applications for this kind of algorithm (although supporting numbers as high as a billion may be overkill :-)

A: There was already a question about this:
Convert integers to written numbers
The answer is for C#, but I think you can figure it out.

A: import math

def encodeOnesDigit(num):
   return ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][num]

def encodeTensDigit(num):
   return ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'][num-2]

def encodeTeens(num):
   if num < 10:
      return encodeOnesDigit(num)
   else:
      return ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'][num-10]

def encodeTriplet(num):
   if num == 0: return ''
   str = ''
   if num >= 100:
      str = encodeOnesDigit(num / 100) + ' hundred'
   tens = num % 100
   if tens >= 20:
      if str != '': str += ' '
      str += encodeTensDigit(tens / 10)
      if tens % 10 > 0:
         str += '-' + encodeOnesDigit(tens % 10)
   elif tens != 0:
      if str != '': str += ' '
      str += encodeTeens(tens)
   return str

def zipNumbers(numList):
   if len(numList) == 1:
      return numList[0]
   strList = ['', ' thousand', ' million', ' billion'] # Add more as needed
   strList = strList[:len(numList)]
   strList.reverse()
   joinedList = zip(numList, strList)
   joinedList = [item for item in joinedList if item[0] != '']
   return ', '.join(''.join(item) for item in joinedList)

def humanReadable(num):
   if num == 0: return 'zero'
   negative = False
   if num < 0:
      num *= -1
      negative = True
   numString = str(num)
   tripletCount = int(math.ceil(len(numString) / 3.0))
   numString = numString.zfill(tripletCount * 3)
   tripletList = [int(numString[i*3:i*3+3]) for i in range(tripletCount)]
   readableList = [encodeTriplet(num) for num in tripletList]
   readableStr = zipNumbers(readableList)
   return 'negative ' + readableStr if negative else readableStr

A: Supports up to 999 million, but no negative numbers:
String humanReadable(int inputNumber) {
  if (inputNumber == -1) {
    return "";
  }
  int remainder;
  int quotient;
  quotient = inputNumber / 1000000;
  remainder = inputNumber % 1000000;
  if (quotient > 0) {
    return humanReadable(quotient) + " million, " + humanReadable(remainder);
  }
  quotient = inputNumber / 1000;
  remainder = inputNumber % 1000;
  if (quotient > 0) {
    return humanReadable(quotient) + " thousand, " + humanReadable(remainder);
  }
  quotient = inputNumber / 100;
  remainder = inputNumber % 100;
  if (quotient > 0) {
    return humanReadable(quotient) + " hundred, " + humanReadable(remainder);
  }
  quotient = inputNumber / 10;
  remainder = inputNumber % 10;
  if (remainder == 0) {
    //hackish way to flag the algorithm to not output something like "twenty zero"
    remainder = -1;
  }
  if (quotient == 1) {
    switch(inputNumber) {
    case 10:
      return "ten";
    case 11:
      return "eleven";
    case 12:
      return "twelve";
    case 13:
      return "thirteen";
    case 14:
      return "fourteen";
    case 15:
      return "fifteen";
    case 16:
      return "sixteen";
    case 17:
      return "seventeen";
    case 18:
      return "eighteen";
    case 19:
      return "nineteen";
    }
  }
  switch(quotient) {
  case 2:
    return "twenty " + humanReadable(remainder);
  case 3:
    return "thirty " + humanReadable(remainder);
  case 4:
    return "forty " + humanReadable(remainder);
  case 5:
    return "fifty " + humanReadable(remainder);
  case 6:
    return "sixty " + humanReadable(remainder);
  case 7:
    return "seventy " + humanReadable(remainder);
  case 8:
    return "eighty " + humanReadable(remainder);
  case 9:
    return "ninety " + humanReadable(remainder);
  }
  switch(inputNumber) {
  case 0:
    return "zero";
  case 1:
    return "one";
  case 2:
    return "two";
  case 3:
    return "three";
  case 4:
    return "four";
  case 5:
    return "five";
  case 6:
    return "six";
  case 7:
    return "seven";
  case 8:
    return "eight";
  case 9:
    return "nine";
  }
}

A: using System;

namespace HumanReadable
{
    public static class HumanReadableExt
    {
        private static readonly string[] _digits = {
                                                       "", "one", "two", "three", "four", "five",
                                                       "six", "seven", "eight", "nine", "eleven", "twelve",
                                                       "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
                                                       "eighteen", "nineteen"
                                                   };

        private static readonly string[] _teens = {
                                                      "", "", "twenty", "thirty", "forty", "fifty",
                                                      "sixty", "seventy", "eighty", "ninety"
                                                  };

        private static readonly string[] _illions = {
                                                        "", "thousand", "million", "billion", "trillion"
                                                    };

        private static string Seg(int number)
        {
            var work = string.Empty;

            if (number >= 100)
                work += _digits[number / 100] + " hundred ";

            if ((number % 100) < 20)
                work += _digits[number % 100];
            else
                work += _teens[(number % 100) / 10] + "-" + _digits[number % 10];

            return work;
        }

        public static string HumanReadable(this int number)
        {
            if (number == 0)
                return "zero";
            var work = string.Empty;

            var parts = new string[_illions.Length];

            for (var ind = 0; ind < parts.Length; ind++)
                parts[ind] = Seg((int) (number % Math.Pow(1000, ind + 1) / Math.Pow(1000, ind)));

            for (var ind = 0; ind < parts.Length; ind++)
                if (!string.IsNullOrEmpty(parts[ind]))
                    work = parts[ind] + " " + _illions[ind] + ", " + work;

            work = work.TrimEnd(',', ' ');

            var lastSpace = work.LastIndexOf(' ');
            if (lastSpace >= 0)
                work = work.Substring(0, lastSpace) + " and" + work.Substring(lastSpace);

            return work;
        }
    }

    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine(1.HumanReadable());
            Console.WriteLine(53.HumanReadable());
            Console.WriteLine(723603.HumanReadable());
            Console.WriteLine(1456376562.HumanReadable());
            Console.ReadLine();
        }
    }
}

A: There's one huge problem about this function implementation. It is it's future localization. That function, written by english native speaker, most probably wouldn't work right for any other language than english. It is nearly impossible to write general easy localizable function for any human language dialect in a world, unless you really need to keep it general. Actually in real world you do not need to operate with huge integer numbers, so you can just keep all the numbers in a big (or even not so big) string array.

A: agreed that there are a number of real world applications.
as such there's already a number of real world implementations.
it's been part of bsdgames since pretty much forever...
> man number


text:
Q: Token does not recognize '&' and single quote I was trying to match everything between parentheses. I met an error that it won't recognize '&' and '''. However, in IntelliJ antlr preview, it works fine. Please help me with the error. Thank you so much.
line 1:0 token recognition error at: '&'
line 3:23 token recognition error at: '&'
line 3:30 token recognition error at: '''

//test cases
&
""
{"pattern": "\\:(\\s+)[&\\\"\\']"}

grammar g;

start   : root+ EOF ;

root    : expr
        | LPARAM
        | RPARAM
        ;

expr    : list
        | atom
        ;

list    : LPARAM expr+ RPARAM
        ;

atom    : INT |' ';
//anybutp:

INT     : [\u0000-\u0019]*|[\u0021-\u0027]* | [\u002a-\uffff]*;
LPARAM  : '(';
RPARAM  : ')';
WS: [ \t\n\r]+ -> skip;

When in put is
&
''
line 1:0 token recognition error at: '&'
line 2:0 token recognition error at: '''
line 2:1 token recognition error at: '''
line 2:2 mismatched input '' expecting {'+', '-', '*', '', '/', '[', ']', '.', '^', '$', '{', '}', '|', '#', '@', '<', '?', '=', ',', '"', ':', '!', '>', ';', '`', '~', '_', '%', '()', INT, '(', ')'}

import org.antlr.v4.runtime.CharStream;

import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import static org.antlr.v4.runtime.CharStreams.fromFileName;
import java.io.IOException;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.Trees;

public class AntlerParser {
    public static void main (String[] args) throws IOException{
        String src = "C:\\Users\\vicky\\IdeaProjects\\regex\\src\\text.txt";

        CharStream charStream = fromFileName(src);
        gLexer lexer = new gLexer(charStream);
        CommonTokenStream commonTokenStream= new CommonTokenStream(lexer);
        gParser parser = new gParser(commonTokenStream);
        ParseTree tree = parser.start();

        MyVisitor visitor = new MyVisitor();
        visitor.visit(tree);
/*print out lists*/
        MyListener listener = new MyListener();
        ParseTreeWalker walker = new ParseTreeWalker();
        walker.walk(listener,tree);

        int count = tree.getChildCount();
        System.out.println("done"+count);
    }
}

A: Tested with ANTLR 4.9.
The code:
String source =
        "&\n" +
        "\"\"\n" +
        "{\"pattern\": \"\\\\:(\\\\s+)[&\\\\\\\"\\\\']\"}";

gLexer lexer = new gLexer(CharStreams.fromString(source));
gParser parser = new gParser(new CommonTokenStream(lexer));
ParseTree root = parser.start();

System.out.println(root.toStringTree(parser));

prints:
(start (root (expr (atom &))) (root (expr (atom \n))) (root (expr (atom ""))) (root (expr (atom \n))) (root (expr (atom {))) (root (expr (atom "))) (root (expr (atom pattern))) (root (expr (atom "))) (root (expr (atom :))) (root (expr (atom  ))) (root (expr (atom "))) (root (expr (atom \\:))) (root (expr (list ( (expr (atom \\s+)) )))) (root (expr (atom [))) (root (expr (atom &))) (root (expr (atom \\\))) (root (expr (atom "))) (root (expr (atom \\))) (root (expr (atom '))) (root (expr (atom ]))) (root (expr (atom "))) (root (expr (atom }))) <EOF>)

without any error messages.
If you get error mssages, it is most likely because you have not regenerated your lexer- and parser classes from your (new) grammar. Every time you update your grammar, you must regenerate the lexer- and parser classes.


text:
Q: Issue with AVPlayer in Swift application I get a mp4 video with AVCaptureMovieFileOutput class and save it under the Documents folder of the application, but when I try to play the video with a AVPlayer class, I see nothing in the custom UIView. Below the code:
player = AVPlayer(url: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = videoView.bounds
videoView.layer.addSublayer(playerLayer)
player.play()

I tried to save the video in Camera Roll and I can see the video under the gallery correctly.
EDIT:
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = NSURL(fileURLWithPath: path.absoluteString)
if let pathComponent = url.appendingPathComponent("video.mp4") {
  let filePath = pathComponent.path
  let fileManager = FileManager.default
  if fileManager.fileExists(atPath: filePath) {
     print("FILE AVAILABLE")
  } else {
     print("FILE NOT AVAILABLE")
  }
} else {
  print("FILE PATH NOT AVAILABLE")
}

I tried the code above and the output is "FILE AVAILABLE". The file is stored under this path: /var/mobile/Containers/Data/Application/27BDD2E1-815B-422B-96A9-E166BE154950/Documents/video.mp4
Some can help me to find a solution about this problem?

A: Try using Apple's own example - use following PlayerView class:
import AVFoundation
import UIKit

class PlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

    // Override UIView property
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}

Then set it for the videoView property:
let videoView = PlayerView()

And then use it:
videoView.player = AVPlayer(url: videoURL)
videoView.player?.play()


text:
Q: Not able to display all Buttons on JFrame Below is my code. I am not able to add all the 6 buttons. Only Button1 - 3 or Button4-6 are getting displayed at a time.
Kindly let me know where I am going wrong.
// This class contains the main method and launches the Main screen
import javax.swing.*;
import java.awt.*;

public class LearningHome{
    public static void main(String[] args){
        JFrame mainFrame = new JFrame("Welcome to the Learning! ");

        try {

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(800, 800);
        mainFrame.setVisible(true); // Without this property the frame will not be visible

        FlowLayout mainLayout = new FlowLayout();
        JPanel mainPanel = new JPanel();

        mainPanel.setLayout(mainLayout);

        mainPanel.add(new JButton(" Button 1 "));
        mainPanel.add(new JButton(" Button 2 "));
        mainPanel.add(new JButton(" Button 3 "));

        JPanel subPanel = new JPanel();

        subPanel.setLayout(mainLayout);

        subPanel.add(new JButton(" Button 4 "));
        subPanel.add(new JButton(" Button 5 "));
        subPanel.add(new JButton(" Button 6 "));

        mainFrame.add(mainPanel, mainLayout.LEFT);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.add(subPanel, mainLayout.RIGHT);
    }
}

A: You did not mention the exact layout you seek, and there is a wide number of way to go about arranging components, but to address your specific comment

I am not able to add all the 6 buttons. Only Button1 - 3 or Button4-6 are getting displayed at a time

*

*Add all elements to the JFrame before it becomes visible (eg. move the mainFrame.setVisible(true) after you add components to mainFrame. This way the LayoutManager can arrange the components as needed

*Consider calling mainFrame.pack(); prior to calling setVisible (see What does .pack() do? )

*The default LayoutManager for the content pane of a JFrame is BorderLayout (default for a JPanel is FlowLayout - so no need to explicitly set the Layout as such)...if you wish to add the two panels so they layout in a line, consider using an appropriate combination of BorderLayout parameters.

For example:
mainFrame.add(mainPanel, BorderLayout.WEST);
mainFrame.add(mainPanel, BorderLayout.EAST);
mainFrame.pack();//call these methods after adding components
mainFrame.setVisible(true);

You can alternatively stack them into two lines using the appropriate BorderLayout parameters. For example:
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.add(mainPanel, BorderLayout.SOUTH);


text:
Q: Rename files in a directory I have the files names as below in a directory
example1.1.timestamp(.1457644337)
example1.2.timestamp
example1.3.timestamp

and so on about 100 files. I need to rename all the files by removing the .timestamp(.1457644337) at the end.
I managed to do it for a single file
ls -l filename | sed 's/\.[^.]*$//'

A: Using rename (prename):

*

*If the timestamp is same for all files, from the directory containing the files you can do:
rename -n 's/\.1457644337$//' example1.*.*

*For varying timestamps:
rename -n 's/\.\d+$//' example1.*.*

Recursively:
find . -type f -name 'example1.*.*' -exec rename -n 's/\.\d+$//' {} +

Remove -n (dry-run) if you are satisfied with the changes to be made.
Note that, this will remove the last portion containing digits including .. So if you have just any random number apart from timestamp that will be removed too.

Using shell parameter expansion:

*

*If the timestamp is same for all files:
for file in *.*; do mv -i "$file" "${file%.1457644337}"; done

*For varying timestamps, assuming bash (other advanced shells have similar options) :
shopt -s extglob; for file in *.*; do mv -i "$file" "${file%.+([0-9])}"; done

Recursively:
find . -type f -name 'example1.*.*' -exec \
    bash -ic 'shopt -s extglob; mv -i "$1" "${1%.+([0-9])}"' _ {} \;

Here i have used extglob shell option to match the digits after last . by using pattern +([0-9]) hence the replacement parameter expansion pattern becomes ${file%.+([0-9])}.
Again this does not strictly matches a timestamp. Although you can modify the pattern to get robustness if you have any precise format for the timesatmps.

A: interactive way, with visual inspecting commands:
ls | vim -

inside vim:
:%s/.*/mv \0 \0/        ...move filename filename
:%s/\.[^.]*$//          ...same as your sed regex
:w !sh                  ...run buffer with shell
:q!                     ...close without saving


text:
Q: Pandas: selecting dates that are multiples of a day frequency in a grouped dataframe? I need to make a very specific selection in a DataFrame containing dates. I have a "Lead Time" column that contains an integer, and I need to select every X dates that correspond to this integer in the DataFrame. For example:
select row with every 15 days in date_range('2019-05-01', '2019-07-01') for each group. Here is a sample code of what I need to do:
import pandas as pd

df = pd.DataFrame({'ITEM': ['A', 'B', 'C'] * 3, 'GROUP': [i+1 for i in range(3) for _ in range(3)],
                    'MONTH': [i+1 for i in range(3) for _ in range(3)],
                   'LEAD_TIME': [i for i in [15, 20, 10] for _ in range(3)]})
months = 2
start_date = pd.to_datetime('2019-01-01')
dates = pd.DataFrame({'DATE': pd.date_range(start_date, start_date + pd.offsets.MonthBegin(months + 1), closed="left")})
dates['MONTH'] = dates['DATE'].dt.month
df = df.merge(dates, on='MONTH')

# df.loc[every LEAD_TIME days after start_date, 'check'] = True

A: Inefficient solution
For each value in LEAD_TIME column You could get the values in the following way:
init_date = '2019-05-01'
div_res = pd.to_datetime(init_date).dayofyear % lead_time

df['day_of_year'] = df.DATE.apply(lambda x: x.dayofyear)
df['day_of_year_div_ts'] = df.day_of_year.apply(lambda x: x%lead_time)
result_dates = df.DATE[df.day_of_year_div_ts==div_res].tolist()

You can generalize it by making a function out of it and using .apply() to a dataframe target column.
Elegant solution
lead_time = 15
start_date = pd.to_datetime('2019-01-01')
end_date = pd.to_datetime('2019-10-01')
result_dates = pd.date_range(start = start_date, end = end_date, freq=pd.DateOffset(lead_time))


text:
Q: Flow react native import image error cannot resolve module RelativeImageStub I'm quite new to flow, I'm getting a flow error importing an image in react-native:
import EditIcon from '../../../../../assets/images/edit-icon.png';

<Image
   style={imageStyle}
   source={EditIcon}
/>

I get this error:

"cannot resolve module RelativeImageStub"

This is my flowconfig where I have the RelativeImageStub
module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'

A: Instead of matching the whole module name, you can use extension matcher.
Change:
module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'

To:
module.name_mapper.extension='\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)' -> 'RelativeImageStub'

A: This is happening because there is no flow definition file.
A work-around to remove the error is to create a stub.
With flow-typed installed (e.g. npm i -g flow-typed), execute the following in your project's root directory:
flow-typed create-stub RelativeImageStub@x.x.x


text:
Q: How to implement DSL in groovy way? I  have successfully written apis for converting the below DSL:
testCase
            {
                name = 'test'
                params {
                    name = "var"
                    value = 'randomValue'
                }
}

to
<testCase name='test'>
     <params name='var' value='randomValue' />
</testCase>

This works perfectly. But I want to do this too ( similar to Spock). If user gives this one:
testCase
            {
                name = 'test'
                params {
                    name  |  value
                       1       |     2
                       3       |    5
                }
}

so that this turns into :
<testCase name='test'>
     <params name='1' value='2' />
</testCase>

<testCase name='test'>
     <params name='3' value='5' />
</testCase>

note that here both name and value can be any string.  How shall I do this? The problem which I face now is I need to create separate testCase when I see a param like this. And testCase can have other embed tags like this:
testCase {
      someTag {
        someTag2 {
             params {
                    name  |  value
                       1       |     2
                       3       |    5
            }
       }
}

So this to be generated like
<testCase>
     <someTag>
        <someTag2>
                   <params name='1' value='2' />
        </someTag2>
     </someTag>
</testCase>

<testCase>
     <someTag>
        <someTag2>
                   <params name='3' value='5' />
        </someTag2>
     </someTag>
</testCase>

So in groovy world, how should I solve this problem?


text:
Q: Reproducing ARIMA model outside R I've got an ARIMA(1,1,4) model using external regressor with acceptable output but I'm not able to reproduce it outside the R.
this is the result for the model:
Coefficients:
         ar1      ma1     ma2      ma3     ma4  XRegressor[1:39, ]_coeff
      0.9500  -1.0202  0.3977  -0.8283  0.6030                0.0084
s.e.  0.1106   0.1999  0.1953   0.2003  0.1526                0.0059

sigma^2 estimated as 9619542:  log likelihood=-360.56
AIC=735.11   AICc=738.84   BIC=746.57

The formula I'm using is as follows:
x(t) = x(t-1)(1+ar1) - ar1*x(t-2) + XRegressor[1:39, ]_coeff*
  [xreg(t) - (1+ar1)*xreg(t-1) + ar1*xreg(t-2)] +
  ma1*e(t-1) + ma2*e(t-2) + ma3*e(t-3) + ma4*e(t-4)

I'm using residuals as error term in above formula. I could get right result in one step ahead forecast and for further steps, I won't have residuals to substitute in formula. Even by deleting MA part from model, it's not working. Do I miss something here? Can I say by deleting MA part, I'm erasing residual effects?
Thanks a lot for your help in advance.

A: R uses regression with an ARIMA error, as explained in the help file for arima().
So an ARIMA(1,1,4) model can be written as
$$
x_t = \beta z_t + n_t
$$
where $z_t$ is your regression variable and $n_t$ is an ARIMA(1,1,4) model:
$$
(n_t - n_{t-1}) = \phi_1 (n_{t-1}-n_{t-2}) + e_t  + \theta_1 e_{t-1} + \theta_2 e_{t-2} + \theta_3 e_{t-3} + \theta_4 e_{t-4}.
$$
Equivalently,
$$
x_t = (1+\phi_1)x_{t-1} - \phi_1x_{t-2} + \beta z_t - (1+\phi_1)\beta z_{t-1} + \beta\phi_1 z_{t-2} + e_t  + \theta_1 e_{t-1} + \theta_2 e_{t-2} + \theta_3 e_{t-3} + \theta_4 e_{t-4}.
$$
So that's the same as your model except that you've omitted the $e_t$ term.
For forecasting, substitute in the residuals if they are available, and set them to zero when they are not. For example, for the two-step forecast, you won't have available $e_{T+2}$ or $e_{T+1}$, but you will have $e_T$, $e_{T-1}$ and $e_{T-2}$, where $T$ is the time of the last observation.


text:
Q: Automatic resizing in a navigation bar of a segmented control built dynamically A controller adds a UISegmentedControl to a navigation bar. The segmented control is added to the navigation bar in the viewDidLoad method of the controller but the actual segments are created dynamically after viewDidLoad is called.
I can't get the segments to be resized automatically when the view is shown. They are all squished, like in this post, though the resolution doesn't apply here. If the segments are added before the segmented control is added to the right item of the navigation bar (breaking the dynamic nature of the code), they are resized automatically and look fine when the view is shown.
Here's a stripped down version of my code, below. What am I missing?
@implementation MyController

- (void)viewDidLoad {

    // segmentedControl is an ivar
    segmentedControl = [UISegmentedControl alloc] initWithItems:[NSArray array]];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
    self.navigationController.navigationBar.topItem.rightBarButtonItem = barButtonItem;

}

- (void)someMethodCalledAfterViewDidLoad {

    [segmentedControl insertSegmentWithTitle:@"a title"
                                     atIndex:0
                                    animated:NO];
}

@end

A: After calling insertSegmentWithTitle call
[segmentedControl sizeToFit];

A: I had the same problem today - the UISegmentedControl segments were initially displayed with the proper variable widths, but did not expand or contract to fit the length of new, dynamically updated titles.
Sending the segmented control a setNeedsLayout message after each update solved the problem.
[segmentedControl setNeedsLayout];


text:
Q: UnhandledPromiseRejectionWarning: MongoWriteConcernError and ValidationError My code is showing the following MongoWriteError once I open it, and after some time, then the ValidationError when I add data to my to-do list application.
UnhandledPromiseRejectionWarning: ValidationError: User validation failed: username: Path username is required.

UnhandledPromiseRejectionWarning: MongoWriteConcernError: No write concern named 'majority/todolistDB'

This is the itemsSchema part:
  var itemsSchema = new Schema({
  username:  {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3
  },
},
{
  timestamps: true
});

This saved me from the MongoWriteError but it tends to work for a while.
This is the server part:
mongoose.connect("mongodb+srv://cluster0-hjbfj.mongodb.net/test?
  retryWrites=true&w=majority/todolistDB", {
  dbName: 'todolistDB',
  user: 'USERNAME',
  pass: 'PASSWORD',
  useNewUrlParser: true,
  useUnifiedTopology: true,
    useCreateIndex: true
   })
 .then(() => {
 console.log("MongoDB Connected");
 })
  .catch((error) => {
 assert.isNotOk(error,'Promise error');
  });

...
app.post("/", function(req, res){

 const itemName = req.body.newItem;
 const listName = req.body.list;

 const item = new Item({
 name:itemName
  });
     if(listName === "Today"){
      item.save();
      res.redirect("/");
    }else{
    List.findOne({name: listName}, function(err, foundList){
    foundList.items.push(item);
    foundList.save();
      res.redirect("/" + listName);
    });
    }
      });


text:
Q: Why isn't my service running? (As judged by displaying Toast message.) I am trying to make a service in the background so I can run a loop that requests a page every x minutes. This is my service in the manifest:
<service android:name=".webToSMS" android:enabled="true" />

And here is my service being started (in the main activity):
Intent intent = new Intent(this, webToSMS.class);
startService(intent);

And finally, this is my service class:
public class webToSMS extends IntentService {

  public webToSMS() {
      super("webToSMS");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
      Context context = getApplicationContext();
      CharSequence text = "Hello toast!";
      int duration = Toast.LENGTH_SHORT;

      Toast toast = Toast.makeText(context, text, duration);
      toast.show();
  }
}

I was following the guide at Android and this is what it told me to do. What I am expecting is a toast to pop up saying "Hello toast!" when this service is run. Eventually when this works I will put a loop which will request a page every x minutes.

A: Your service is running, it's just not displaying the toast because you are not on the UI thread.
If you want to see a toast try this instead
Handler HN = new Handler();

private class DisplayToast implements Runnable {

  String TM = "";

      public DisplayToast(String toast){
          TM = toast;
      }

      public void run(){
         Toast.makeText(getApplicationContext(), TM, Toast.LENGTH_SHORT).show();
      }
}

@Override
protected void onHandleIntent(Intent intent) {

   HN.post(new DisplayToast("New Toast on UI Thread"));
}


text:
Q: RPA-Blueprism - Global Send Keys - Input text which has '(' is not working RPA-Blueprism - Global Send Keys - Input text which has '(' is not working. Only the text gets entered without brackets, please assist.
Ex: 'Paste (Text)' is the text I want to send, however the text is sent to the field as 'Paste Text'

A: Global Send Keys internally uses System.Windows.Forms.SendKeys so characters like braces or parentheses must be escaped.
One way of doing it is using a Calculation stage with several Replace instructions, replacing the problematic characters with the escaped version.
For more information about System.Windows.Forms.SendKeys check the following MSDN link
https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys(v=vs.110).aspx

A: You can use "Paste {(}Text{)}".

A: RPA-Blueprism - Global Send Keys for '(' then
{<SHIFT>9}</SHIFT> - Key down Shift button and press 9 releases the shift key, indirectly it does SHIFT + 9

Let's consider - If needed to write "("  manual key stroke would be SHIFT + 9
So if you have to send Global send key for the same, then use the above code
You can refer the blow link for more understanding
[https://seleniumsuite.blog/2017/11/07/global-send-keyglobal-send-key-events-in-blueprism/]

NOTE: Before sending any global send key event the application must be activated prior

A: You can use "utility-string" VBO and call the "Escape special character string" for example if you pass "paste(text)" as input , it will give output as "paste{(}text{)}". You can then use the output dataitem for global send keys action.


text:
Q: Convert result json to different format javascript I am working on the application where i need to convert the response json into different format and pass it to different API . I am finding it hard to convert the desired structure.
Input :
var value = `[
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S98",
    "MATERIAL": "300154",
    "MATERIAL_DESC": "BLOCKS",
    "PP_AD": 45.7,
    "PP_DISC_OLD": 34.7
    },
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S98",
    "MATERIAL": "000000000000300155",
    "MATERIAL_DESC": "PALLET",
    "PP_AD": 123.7,
    "PP_DISC_OLD": 43.7
    },
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S99",
    "MATERIAL": "300155",
    "MATERIAL_DESC": " WOODEN",
    "PP_AD": 23.7,
    "PP_DISC_OLD": 23.7
    }
    ]`;

I need to convert this to Result mentioned below.
OUTPUT:
{
    "categoreies": [{
            "PRODUCT_GROUP": "Accessories",
            "MATERIAL_GROUP": "S98",
            "categoreies": [{
                "MATERIAL": "300154",
                "MATERIAL_DESC": "BLOCKS",
                "PP_AD": 45.7,
                "PP_DISC_OLD": 34.7
            }, {
                "MATERIAL": "000000000000300155",
                "MATERIAL_DESC": "PALLET",
                "PP_AD": 123.7,
                "PP_DISC_OLD": 43.7
            }]
        },
        {
            "PRODUCT_GROUP": "Accessories",
            "MATERIAL_GROUP": "S99",
            "categoreies": [{
                "MATERIAL": "300155",
                "MATERIAL_DESC": " WOODEN",
                "PP_AD": 23.7,
                "PP_DISC_OLD": 23.7
            }]
        }
    ]
}]

I tried to loop the code and form an object but getting the desired result.
Kindly help.
value=JSON.parse(value);
let firstobj={},arr1=[],secobj={},arr2=[],finalobj={};
value.forEach((items)=>{
    firstobj.PRODUCT_GROUP=items.PRODUCT_GROUP;
    firstobj.MATERIAL_GROUP=items.MATERIAL_GROUP;

    arr1.push(firstobj);

    secobj.MATERIAL=items.MATERIAL;
    secobj.MATERIAL_DESC=items.MATERIAL_DESC;

    arr2.push(secobj);

    finalobj.CATEGORIES=arr2;

     console.log(finalobj)
})

Could you please help me in converting the input json to result json

A: You could create a key for each entry that is the combination of the product and material group (for example as JSON). Then create a Map with those keys and with arrays as values, initially all empty. Then iterate over the data to populate those arrays. Finally convert that Map to the target structure.

let value = `[{"PRODUCT_GROUP": "Accessories","MATERIAL_GROUP": "S98","MATERIAL": "300154","MATERIAL_DESC": "BLOCKS","PP_AD": 45.7,"PP_DISC_OLD": 34.7},{"PRODUCT_GROUP": "Accessories","MATERIAL_GROUP": "S98","MATERIAL": "000000000000300155","MATERIAL_DESC": "PALLET","PP_AD": 123.7,"PP_DISC_OLD": 43.7},{"PRODUCT_GROUP": "Accessories","MATERIAL_GROUP": "S99","MATERIAL": "300155","MATERIAL_DESC": " WOODEN","PP_AD": 23.7,"PP_DISC_OLD": 23.7}]`;

let arr = JSON.parse(value).map(({PRODUCT_GROUP, MATERIAL_GROUP, ...rest}) =>
    ({ group: JSON.stringify({PRODUCT_GROUP, MATERIAL_GROUP}), rest})
);
let map = new Map(arr.map(({group}) => [group, []]));
arr.forEach(({group, rest}) => map.get(group).push(rest));
let result = Array.from(map.entries(), ([group, categories]) =>
    ({...JSON.parse(group), categories})
);

console.log(result);

A: Try this:

var value = `[
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S98",
    "MATERIAL": "300154",
    "MATERIAL_DESC": "BLOCKS",
    "PP_AD": 45.7,
    "PP_DISC_OLD": 34.7
    },
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S98",
    "MATERIAL": "000000000000300155",
    "MATERIAL_DESC": "PALLET",
    "PP_AD": 123.7,
    "PP_DISC_OLD": 43.7
    },
    {
    "PRODUCT_GROUP": "Accessories",
    "MATERIAL_GROUP": "S99",
    "MATERIAL": "300155",
    "MATERIAL_DESC": " WOODEN",
    "PP_AD": 23.7,
    "PP_DISC_OLD": 23.7
    }
    ]`;

value = JSON.parse(value);

let outputobj = {};
outputobj.categories = [];

let tmpdict = {};

value.forEach((items)=>{

 if (!tmpdict[items.MATERIAL_GROUP]){
  tmpdict[items.MATERIAL_GROUP] = {
   "PRODUCT_GROUP" : items.PRODUCT_GROUP,
   "MATERIAL_GROUP" : items.MATERIAL_GROUP,
   "categories" : []
  }
 }
 let tmpobj = {
  "MATERIAL" : items.MATERIAL,
  "MATERIAL_DESC" : items.MATERIAL_DESC,
  "PP_AD" : items.PP_AD,
  "PP_DISC_OLD" : items.PP_DISC_OLD

  }

 tmpdict[items.MATERIAL_GROUP].categories.push(tmpobj);

})

for (let key in tmpdict){
 outputobj.categories.push(tmpdict[key]);
}

console.log(outputobj);
newJSON = JSON.stringify(outputobj);

console.log(newJSON);


text:
Q: How do I get rid of all caps ribbon titles in Office 2013? Installed Office 2013 on Windows 8 today. It's great, except for one thing, the all caps ribbon titles are inconsistent with the title case titles everywhere else in Windows 8. Is there a registry setting that will let me change this?

A: You can also try unOFFIC (http://unoffic.migeel.sk/). It's a small in-memory patch for all Office 2013 apps that fixes ALL CAPS not only on the ribbon, but also in the status bar and a few other spots. It doesn't modify the Office EXEs in any way, so it should be pretty safe and update resilient.

A: Of course, it can be fixed. Simply put a space before or after the Tab title. I prefer putting it after.

*

*Right click the tab heading > Customize the ribbon > Click on the tab you want to rename.
Either right click and select "Rename" or click the "Rename" button below.

*Then put a space before or after the tab title.

*The tab title will now appear in sentence case.

A: The all-caps is a software feature. The new release of Visual Studio 2012 uses all-caps as well. Microsoft is probably testing if users accept this new look. Depending on how things turn out, they'll probably release a patch (service packs) to either change all-caps to normal (Office, Visual Studio, etc) or normal to all-caps (File Explorer, etc).

A: right click on the tab title, choose customize ribbon, click rename and put a blank space in front of the tab title. Click OK. Do the same for all the other titles.

A: A Microsoft MVP has complete menu customization files available for download, here:
http://answers.microsoft.com/en-us/office/wiki/office_2013_release-office_install/proper-case-for-office-2013-ribbon-menus/d28ad27b-a727-4b63-a6e1-46deb15696a8
These can be safely imported into Office 2013 apps through the "Import/Export" feature in the ribbon customization menus, and they will proper-case the entire menu.

A: No, apparently, there isn't. Here is what seems to be an official answer from Microsoft (thread):

The development team discussed changing the tabs to proper case, but made a firm decision that they would leave them all caps as designed. There is no way to change them in the registry, but if you have an add-in that creates new tabs, they will be whatever case you specify in your custom ribbon file.

There is a registry setting to disable all caps menu in the Visual Studio 2012 (discussed here, for example):

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General
  DWORD: SuppressUppercaseConversion
  Value: 1

But this does not work for the new Office 2013. Just in case I have tried these settings (of course, none of them worked):

HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\SuppressUppercaseConversion
  HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\General  \SuppressUppercaseConversion

If you need more information on this choice, here is a good thread at ux.stackexchange.com, where you can find a designer's opinion on that.


text:
Q: how to search for a specific word index delimited by a space ? in Perl Regex I have a logfile like
field1 field2 field3 field4withvariablelength ... field5with...
Is there a way to extract for example field 5 using perl regex, like
"Delimit with spaces" and "Give me index 5" ??

A: Sure, you can use split to delimit by space:
my (@fields) = split /\s+/;
print $fields[4];

Here's a full test script:
#!/usr/bin/perl -w
use strict;

while (<DATA>) {
    my (@fields) = split /\s+/;
    print $fields[4];
}

__DATA__
field1 field2 field3 field4withvariablelength... field5with...

A: or like so:
my $str = "field1 field2 field3 field4withvariablelength ... field5with...";
$str =~ m/field5(.*)$/i;
print $1; # type with...

if u have to other field:
$str =~ m/\s+field4(.*)\s+/i;
print $1; # type withvariable...


text:
Q: How to play NSData in AVPlayer? I have downloaded video NSData from AWS server using cognate poolid. Trying to play NSData in AVPlayer after converting NSData to NSURL. But it is not playing.
In interface, I have defined
@property (nonatomic, strong) AVPlayer *avPlayer;

Here is the code
NSData *data = [UserProfileInfo getVideoData];
NSLog(@"%lu", (unsigned long)data.length);

NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
_avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:dataString]];

_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
videoLayer.frame = videoPreviewView.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[videoPreviewView.layer addSublayer:videoLayer];
[videoPreviewView.layer setOpacity:1.0];
[_avPlayer play];

Actually I am getting data here but when I am converting it into NSString
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Then I am getting nil in dataString.
Please someone help.

A: You need to save the NSDATA in your Document Directory and give its path to AVPlayer for playing it.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:@"myVideo.mp4"];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            BOOL isFileWriteComplete = [yourNSdata writeToFile:myPathDocs atomically:YES];
    if(isFileWriteComplete)
    {
_avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:myPathDocs]];
_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
videoLayer.frame = videoPreviewView.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[videoPreviewView.layer addSublayer:videoLayer];
[videoPreviewView.layer setOpacity:1.0];
[_avPlayer play];
    }


text:
Q: How to create copy of one column in same table mysql I have a table with one columns of integer data type. I want to add another columns with string data type.
Finally I want to copy the values in first column to the second columns.
That means I want to copy the integer data from column one and copy that to second column in string format.

A: Casting the column to a CHAR will do what you want:
UPDATE `table` SET column2 = CAST(column1 AS CHAR)

A: Use ALTER TABLE to add columns. Syntax for adding is
ALTER TABLE tablename ADD column_name datatype;

To transfer:
UPDATE tablename SET second_column = CAST(first_column AS CHAR);


text:
Q: TYPO3 upgade error - 6.2 LTS to 7.6 LTS I have a TYPO3 website version 6.2.32 LTS and I want to upgrade it to the version 7.6 LTS.
I downloaded the package from Github and I did :

*

*change the symlink of the new /typo3/ folder

*change the symlink of the new index.php file

*execute the rm -rf typo3temp/* command

Problem : I get a 500 Error message when I navigate to "www.mywebsite.com/typo3/install" and I don't have access to the Apache logs to help me debugging. But when I open the /typo3/install/index.php file I notice :
require __DIR__ . '/../../vendor/autoload.php';

I do not use composer in my website then there is no /vendor/ folder.
Is this my issue ? How to solve it ?

A: From Github you've downloaded the composer-version.
Delete the downloaded version and replace it by this one:
https://get.typo3.org/version/7


text:
Q: Wagtail: Searching page and parent with backend db I am new to Wagtail/Django. Getting start was quite easy and I got my application up and running quite easily. However I ran into a problem when I was searcing. The application is quite small and I would like to use the backend db (or MSSQL).
I have search all around but suprisingly not managed to find  solution. Hope to get one her :-)
I have a page with inline elements. Simplified below
class BlockPage(Page):
    content = RichTextField()

    content_panels = Page.content_panels + [
        FieldPanel('content'),
        InlinePanel('rel_page_blocks', label="Markup blocks"),
    ]

    search_fields = [
        index.SearchField('content', partial_match=True),
        index.RelatedFields('rel_page_blocks', [
            index.SearchField('block_content', partial_match=True),
        ]),
        index.FilterField('live'),
    ]

The inline panel is defined like this
class Blocks(index.Indexed, Orderable):
    page = ParentalKey(BlockPage, related_name='rel_page_blocks')
    block_content = RichTextField()

    panels = [
        FieldPanel('block_content'),
   ]

So far so good. Now I would like to search the page with its inline Blocks. I have successfully searched the page but the Blocks are not searched. I know that this issue is solved using Elastic search but it is not an option for me.
Her is the views.py
def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        blocks_results = BlockPage.objects.live().search(search_query)
        blocks_result_ids = [p.page_ptr.id for p in blocks_results]

# I get a result using this but I would like it to be attached to the
# parent so when viewing the result I can refere/show the parent BlockPage
# The question is how to attach "r" to the parent result?
 r = get_search_backend().search(search_query, Blocks)

    page_ids = blocks_result_ids + **other page ids**
    search_results = Page.objects.filter(id__in=page_ids)

    query = Query.get(search_query)
    # Record hit
    query.add_hit()
else:
    search_results = Page.objects.none()

return render(request, 'search/search.html', {
    'search_query': search_query,
    'search_results': search_results,
})

Any hint would be greatly appreciated. I am a only a couple of days old here so please bear that in mind if you have a solution.


text:
Q: How to pass parameter from bash and string comparison in awk? How to pass a parameter to awk to compare the string with pipe input?
For example, followings are used to filter files created before Aug 2011 under specific folder
#!/bin/bash
$FILTER_DIR=$1

# file date before it should be listed.
FILTER_BEFORE="2011-08"

# $6 in awk statement is date of file name($8)
find $1 -type f | \
    sed 's/^/ls -l /g' | \
    sh | \
    awk ' if ( $6 le $FILTER_BEFORE ) { print $8 }'

The result list all files under $FILER_DIR without filtering.
It seems AWK didnot receive $FILTER_BEFORE from bash properly.
Any comment is appreciated!!

A: if using gawk, pass it as a parameter
find $1 -type f |
sed 's/^/ls -l /g' |
sh |
awk -v filter_before=${FILTER_BEFORE} '{ if ( $6 <= filter_before ) { print $8 } }'

A: You will need to use double quotes and escape the other AWK variables so they don't get interpreted by bash.
find $1 -type f | \
    sed 's/^/ls -l /g' | \
    sh | \
    awk " if ( \$6 le \"$FILTER_BEFORE\" ) { print \$8 }"

Alternatively you can break out just the variable into double quotes so you can avoid escaping.
find $1 -type f | \
    sed 's/^/ls -l /g' | \
    sh | \
    awk ' if ( $6 le "'"$FILTER_BEFORE"'" ) { print $8 }'

A: I'd go with:
touch -t 201107302359 30_july_2011
find . -type f ! -newer 30_july_2011

Or this (GNU find only):
find . -type f ! -newermt '2011-07-30 23:59'

A: Following statements seem work properly.
Thanks for everybody's help.
find $1 -type f | \
sed 's/^/ls -l /g' | \
sh | \
awk -v filter_before=${FILTER_BEFORE} '{ if ( $6 < filter_before ) { print $8 } }'


text:
Q: How to solve sonar issue Absolute Path Traversal in SonaQube? In a web application the file path is stored in properties file.
The path is read from the file, and is passed as a parameter in the URL to call a servlet. while this path is used in creating a File object, sonar reports issue of Absolute Path Traversal.

A: Please try encoding the path that is read from the properties file, before sending it as a parameter in servlet call. And Decode it before using it in the file object.
Like: String encodedURL= URLEncoder.encode(pathfromfile,"UTF-8")


text:
Q: Integration testing with dependency on outside service I am currently writing integration/functional tests for my system. Part of the functionality is to hit a web service via http (another system I run).
How should I set up a test instance of the web service to allow for good functional testing? I want to have my system run against this service with live production data.
Should the web service be an independent instance that always has the live production data that I reload manually (maybe reset every time I start an instance of it)?
Should the web service be setup and teared down with every test?
What are some common practices to deal with situations like this?

A: As first thing please make sure you know difference between Functional Testing and Integration Testing. You can do a pretty good functional tetsing wthout major efforts which are required by integration testing (instantiating web services, accessing a data base). Basically Mocking technique works pretty well even to simulate the Data Layer responses and web service behaviour (I believe such details like HTTP as transport could be ignored for most test cases)
For such integration testing I would suggest having a separate SIT environment which includes a separate Web service and a Data Base as well.

Should the web service be an independent instance that always has the live production data
  that I reload manually (maybe reset every time I start an instance of it)?

Yep, it should be completely separate but data could be manually generated/prepared. For instance, you can prepare some set of data which allows testing some predefined test cases, this could be test data sets which are deployed to the SIT DB instance before the actual test run and then cleaned up in test TearDown.

Should the web service be setup and teared down with every test?

Yep, tests should be isolated one from each other so should not affect each one in any way.


text:
Q: Producing multiple graph objects in igraph from lists of dataframes I have two lists of around 80 dataframes- one for nodes and another for edges. I would like to use the igraph function graph_from_dataframe to join the nodes and edges dataframes make a single list of igraph objects. At the moment I have been trying this:
glst <- mapply(graph_from_data_frame,
           d=ListOfEdgeDfs,
           vertices=ListOfNodeDfs,
            SIMPLIFY = FALSE,
           directed =F)

However, this gives the error message:
Error in (function (d, directed = TRUE, vertices = NULL)  :
  Some vertex names in edge list are not listed in vertex data frame

Does anyone have any ideas as to how I could do this?

A: The following works (for list of 2 graphs, the same should work for any number of graphs, can you make sure that the data frame structures are similar):
ListOfEdgeDfs <- list(data.frame(from=letters[1:3], to=c('b', 'c', 'd')),
                      data.frame(from=rep('a',3), to=c('b', 'c', 'd')))
ListOfEdgeDfs
#[[1]]
#  from to
#1    a  b
#2    b  c
#3    c  d
#[[2]]
#  from to
#1    a  b
#2    a  c
#3    a  d

ListOfNodeDfs <- list(data.frame(node=letters[1:4]), data.frame(node=letters[1:4]))
ListOfNodeDfs
#[[1]]
#  node
#1    a
#2    b
#3    c
#4    d
#[[2]]
#  node
#1    a
#2    b
#3    c
#4    d

library(igraph)
glst <- mapply(graph_from_data_frame,
               d=ListOfEdgeDfs,
               vertices=ListOfNodeDfs,
               SIMPLIFY = FALSE,
               directed =F)
par(mfrow=c(1,2))
#plot(glst[[1]])
#plot(glst[[2]])

[EDITED]
Try this:
n <- 2 # number of graphs
par(mfrow=c(2,1)) # if you have 100 graphs, try par(mfrow=c(10,10)) e.g.
invisible(sapply(1:n, function(i) plot(glst[[i]], vertex.size=50)))


text:
Q: Should Xcode Storyboard support segues from a UITableView with 'dynamic prototype' cells? I can't get this working. If I drop the master UITableView to use Static cells I can get the segues working, such that when you click on a row in the master it automatically pushes the Child controller on. But with 'dynamic prototype' cells, I click on one of the cells and nothing happens...
Am I supposed to programmatically push the child controller within the prepareForSegue method or something? In which case I'm not sure what advantage a segue here would have over the old way of just using

A: No, you don't have to manually push the child controller. Did you connect a segue in your storyboard file from the dynamic cell to the child controller? Also did you give your dynamic cells an identifier? You can also check out this tutorial:
http://maniacdev.com/ios-5-sdk-tutorial-and-guide/xcode-4-storyboard/
Scroll down to "Beginning iOS storyboards" and have a look at part 1 and part 2. I found them most helpful.

A: Use prepareForSugue: instead, [table indexPathForSelectedRow prepareForSugue will be called before the next scene's loadView.

A: Maybe you forgot to set the reuse identifier of Table View Cell.


text:
Q: Find all items whose collection property contains items in another list I have an collection of object Foo with an ICollection property containing a list of People objects.
public class Foo
{
  public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Person> People { get; set; }
}

I have another list of Person.
ICollection<Person> OtherPeople

I need to find all objects Foo where People contains any Person from OtherPeople.
Is there a version of .Contains that accepts a collection?
Something like:
var result = from f in FooCollection
             where f.People.Contains(otherPeople)
             select f;

I am using this with Entity Framework if that matters.

A: Your referring to using C# Linq's Any method.
The Any method basically states if Any of the elements within that collection (Enumerable) satisfy a condition, in your case the condition is if another collection contains one of the elements.
ex.
public bool HasPeople(ICollection<Person> original, ICollection<Person> otherPeople)
{
    return original.Any(p => otherPeople.Contains(p));
}

However the Any method returns a boolean to state if the collection has Any elements that satisfy a condition - this doesn't give us which elements.
Another method in Linq that's worth noting is Where giving us all the elements that satisfy a condition.
ex.
public IEnumerable<Person> GetPeople(ICollection<Person> original, ICollection<Person> otherPeople)
{
    return original.Where(p => otherPeople.Contains(p));
}

I hope that gets you going in the right direction. Entity Framework shouldn't matter because they are Enumerable. Almost forgot to mention that the Linq methods are rather simple so theirs really no need for these to be in their own methods.

A: I've ended up implementing a helper method like this:
    public static bool HasElement<T>(ICollection<T> original, ICollection<T> otherCollection)
    {
        return original.Any(otherCollection.Contains);
    }

Hope it helps!


text:
Q: Finder not responding to [NSRunningApplication activateWithOptions] on secondary display I'm trying to bring the Finder window to front:
NSRunningApplication *finder = [NSRunningApplication runningApplicationWithProcessIdentifier:finderPID];
[finder activateWithOptions:NSApplicationActivateIgnoringOtherApps];

This works on the primary, built-in display. But on my external display, the Finder window doesn't get focus after calling -activateWithOptions. Is that the expected behaviour? Is it a bug?


text:
Q: Check Image view is empty or not? i want to stop uploading photos,other data if image view is empty. i'm already set the image as source in image view. but if i'm not capturing image using camera it should not upload. how to do that?

A: Hope this code helps:
if (yourImageView.getDrawable()==null){
//your code for stopping uploading here!
}
Good luck!


text:
Q: Add a custom taxonomy filter after product category filter in Woocommerce Admin products list In my woocommerce storefront child theme, I have added several taxonomies.  Now I would like to add a few category filters for those custom taxonomies.
I have added such a filter using this code (credit: Rodolfo Melogli)
add_filter( 'woocommerce_product_filters', 'admin_filter_products_by_din' );
function admin_filter_products_by_din( $output ) {

  global $wp_query;

  $output .= wc_product_dropdown_categories( array(
    'show_option_all' => 'All DIN/ISO/ANSI',
    'taxonomy' => 'din-iso-ansi',
    'name' => 'din-iso-ansi',
    'order' => 'ASC',
    'tab_index' => '2',
    'selected' => isset( $wp_query->query_vars['din-iso-ansi'] ) ? $wp_query->query_vars['din-iso-ansi'] : '',
  ) );

  return $output;
}

The new category filter displays, but now I want the placement of my new taxonomy filter (DIN/ISO/ANSI) to go after the Product Categories filter.
product admin:

A:
Important notes:

*

*wc_product_dropdown_categories() function output is echoed by default, and not convenient in a filter hook where all filtered data is always returned, so we will use the argument 'echo' set to false.

*wc_product_dropdown_categories() function uses in fact wp_dropdown_categories() which is more convenient instead, for a custom taxonomy like yours.

To test your code I have used product_tag Woocommerce custom taxonomy to be sure that it works.

The following code will place your custom filter dropdown just after Product category filter:
add_filter( 'woocommerce_product_filters', 'admin_filter_products_by_din' );
function admin_filter_products_by_din( $output ) {
    global $wp_query;

    $taxonomy      = 'din-iso-ansi';
    $selected      = isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '';
    $info_taxonomy = get_taxonomy($taxonomy);

    $custom_dropdown = wp_dropdown_categories(array(
        'show_option_none' => __("Select a {$info_taxonomy->label}"), // changed
        'taxonomy'         => $taxonomy,
        'name'             => $taxonomy,
        'order'            => 'ASC',
        'echo'             => false, // <== Needed in a filter hook
        'tab_index'        => '2',
        'selected'         => $selected,
        'show_count'       => true,
        'hide_empty'       => true,
        'value_field'      => 'slug',
    ));

    $after = '<select name="product_type"'; // The start of the html output of product type filter dropdown.

    $output = str_replace( $after, $custom_dropdown . $after, $output );

    return $output;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

A: I figured this out with a lot of help from LoicTheAztec, essentially using most of his code, but it appears that we cannot substitute wp_dropdown_categories for wc_product_dropdown_categories so easily. After reviewing the function make-up of wc_product_dropdown_categories, I implemented another way to avoid having this function echo out the results by way of a little php.
add_filter( 'woocommerce_product_filters', 'admin_filter_products_by_din' );
function admin_filter_products_by_din( $output ) {

    global $wp_query;

    $taxonomy  = 'din-iso-ansi';
    $selected      = isset( $wp_query->query_vars[$taxonomy] ) ? $wp_query->query_vars[$taxonomy] : '';
    $info_taxonomy = get_taxonomy($taxonomy);

    ob_start(); // buffer the result of wc_product_dropdown_categories silently
    wc_product_dropdown_categories( array(
        'show_option_none' => __("Select a {$info_taxonomy->label}"), // changed
        'taxonomy'         => $taxonomy,
        'name'             => $taxonomy,
        //'echo'             => false, // <== Needed for in filter hook
        'tab_index'        => '2',
        'selected'         => $selected,
        'show_count'       => true,
        'hide_empty'       => true,
    ));
    $custom_dropdown = ob_get_clean();

    $before = '<select name="product_type"'; //

    $output = str_replace( $before, $custom_dropdown . $before, $output );

    return $output;
}


text:
Q: Infection rate summation series in Python
I'm having trouble coding this up. Can somebody please help me?
The code when expanded would look like:
infection_0 = ((1 - )**0)*D[0]
infection_1 = ((1 - )**1)*D[0] + ((1 - )**0)*D[1]
infection_2 = ((1 - )**2)*D[0] + ((1 - )**1)*D[1] + D[2]
infection_3 = ((1 - )**3)*D[0] + ((1 - )**2)*D[1] + ((1 - )**1)*D[2] + D[3]
infection_4 = ((1 - )**4)*D[0] + ((1 - )**3)*D[1] + ((1 - )**2)*D[2] + ((1 - )**1)*D[3] + D[4]
...

where D is the number of cases at time n, and  = 1/14
Thanks in advance!

A: Use sum
I[n] = sum([(1-)**(n-i)*D[i] for i in range(n+1)])

A: Something like this?
def infection(iteration, y):
    base = 1-y
    res = 0
    for expo in range(iteration+1):
        idx = iteration - expo
        res += base**expo * D[idx]
    return res


text:
Q: Can I display a TV channel from TV tuner card using NodeJS for an Electron APP? Basically a TV tuner card is connected to the PC and i have to display the TV channel in an electron App.

*

*Is there any module in node.js that will help me get this done (in
C# Directx.DataCapture Class does the job.)

*If not in node.js then I need to use the DirectX capture class of C# in an
electron app with node.js. is this possible ?


text:
Q: How do I wait for mysqli_multi_query to resolve? Suppose I have code like this:
mysqli_multi_query('<first query>');
include_once 'secondQuery.php';

This is an enormous simplification, and hopefully I haven't simplified the error out, but secondQuery.php relies on <first query> to be completed in order to execute properly. When I run the two manually, in the correct order, everything works perfectly. But when I run this, the error I get is consistent with them either executed in the wrong order, or simultaneously.
How would I write the middle line of:
mysqli_multi_query('<first query>');
wait for mysqli_multi_query to conclude;
include_once 'secondQuery.php';

in correct PHP syntax?

A: Every time you use mysqli_multi_query() you need to execute a blocking loop after it, because this function sends SQL queries to be executed by MySQL asynchronously. An example of a blocking loop which waits for MySQL to process all queries asynchronously is this:
$mysqli->multi_query(/* ... */);
do {
    $result = $mysqli->use_result();
    if ($result) {
        // process the results here
        $result->free();
    }
} while ($mysqli->next_result()); // Next result will block and wait for next query to finish
$mysqli->store_result(); // Needed to fetch the error as exception

It is always a terrible idea to use mysqli_multi_query() in your PHP code. 99.99% of the time there are better ways to achieve what you want. This function has so many downsides that using it should be avoided at all cost.
What you need are database transactions. If your queries depend on each other then you need to switch off implicit commit and commit when all of them execute successfully. You can't achieve this with mysqli_multi_query().


text:
Q: How to keep and disable the y scrollbar while a popup is displayed with the navigation bar on top As illustrated by this pen, I want to make a popup while retaining access to the navigation bar (that's why I'm not using Bootstrap's Modal). The problem is that I want to keep the scrollbar at all times, but also want to disable scrolling of the background while the popup is active.
I tried a lot of things so far, and pretty much the only one worth mentioning is setting overflow: hidden to the body (to remove the scrollbar and prevent scrolling) and forcing the scrollbar on .popup, but this doesn't account for the navigation bar, which still jumps.
The only thing I haven't tried yet is including an identical navigation bar in the popup over the original one. But to me that is asking for trouble, is there another way?
If know how to calculate the width of the scrollbar or, more specifically, whether there is a scrollbar or it's hidden (like in OS X), so that won't be a problem. This technique seems reliable.
I'm aware that similar questions have been answered before, but I didn't manage to find the solution to this specific situation.

A: Because the navigation bar is positioned over the popup, it hides the scrollbar. The solution is simply to move the navigation bar away from the right edge to account for the scrollbar, by the width measured using the method mentioned in the question.
.popup-open .navbar {
  right: 15px;
}


text:
Q: code structure for streamWrite Is there a much better way for me to streamWrite without needing to repeat the code for every button I press? Below is an example I am working on where one button does it's own thing and writes accordingly to vowels and the other does the same thing except it writes accordingly for no alpha characters:
        private void btnVowels_Click(object sender, EventArgs e)
        {
            string wholeText = "";
            string copyText = richTextBox1.Text;

            if (System.IO.File.Exists(Second_File) == true)
            {

                System.IO.StreamWriter objWriter;
                objWriter = new System.IO.StreamWriter(Second_File);

                string vowels = "AaEeIiOoUu";
                copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());
                wholeText = richTextBox1.Text + copyText;

                objWriter.Write(wholeText);
                richTextBox2.Text = wholeText;
                objWriter.Close();
            }
            else
            {

                MessageBox.Show("No file named " + Second_File);
            }
        }

private void btnAlpha_Click(object sender, EventArgs e)
        {
            string wholeText = "";
            string copyText = richTextBox1.Text;

            if (System.IO.File.Exists(Second_File) == true)
            {

                System.IO.StreamWriter objWriter;
                objWriter = new System.IO.StreamWriter(Second_File);

                string nonAlpha = @"[^A-Za-z ]+";
                string addSpace = "";
                copyText = Regex.Replace(copyText, nonAlpha, addSpace);

                objWriter.Write(wholeText);
                richTextBox2.Text = wholeText;
                objWriter.Close();
            }
            else
            {

                MessageBox.Show("No file named " + Second_File);
            }
        }

A: You could use a common function that will take care of writing the contents to the file and updating the second textbox:
private void btnAlpha_Click(object sender, EventArgs e)
{
    string nonAlpha = @"[^A-Za-z ]+";
    string addSpace = "";
    string copyText = richTextBox1.Text;
    copyText = Regex.Replace(copyText, nonAlpha, addSpace);
    WriteToFile(Second_File, wholeText);
}

private void btnVowels_Click(object sender, EventArgs e)
{
    string vowels = "AaEeIiOoUu";
    string copyText = richTextBox1.Text;
    copyText = new string(copyText.Where(c => !vowels.Contains(c)).ToArray());

    string wholeText = richTextBox1.Text + copyText;
    WriteToFile(Second_File, wholeText);
}

private void WriteToFile(string filename, string contents)
{
    if (File.Exists(filename))
    {
        File.WriteAllText(filename, contents);
        richTextBox2.Text = wholeText;
    }
    else
    {
        MessageBox.Show("No file named " + filename);
    }
}

A: why not doing it this way?
private void Write(string file, string text)
{
    if (File.Exists(file))
    {
        using (StreamWriter objWriter = new StreamWriter(file))
        {
            objWriter.Write(text);
        }
    }
    else
    {
        MessageBox.Show("No file named " + file);
    }
}

private void btnAlpha_Click(object sender, EventArgs e)
{
    string wholeText = "";
    string copyText = richTextBox1.Text;

    string nonAlpha = @"[^A-Za-z ]+";
    string addSpace = "";
    copyText = Regex.Replace(copyText, nonAlpha, addSpace);

    wholeText = richTextBox1.Text + copyText;

    Write(Second_File, wholeText); // same for the second button

    richTextBox2.Text = wholeText;
}


text:
Q: Maximum length of [NSXMLNode stringValue] I have an XML document which contains an element that is over 90,000 characters in length*.
NSXMLNode* node = ...;
NSString* val = [node stringValue]; // this is not the full contents of the node!

The second line only gives me 80k or so. This is obviously not what I want, so I'd appreciate some suggestions. Is NSXMLNode broken? I'd guess that I'm doing something wrong.
Thanks in advance!
* i know that 90kbytes in an element is not great, this is out of my hands.

A: What does [node objectValue] give you?


text:
Q: Asynchronous "for" loop when there is no array Like the OP from this question, I want to do a for loop, and do something when all the actions have finished.
I checked the answer, and the async library, but all the solutions involve iterating over an array. I don't want to do something "forEach" element of an array, I don't have an array.
What if I just want to do an operation n times ? For example, say I want to insert n random entries in my database, and do something afterwards ? For now I'm stuck with something like :
function insertMultipleRandomEntries(n_entries,callback){
    var sync_i=0;
    for(var i=0;i<n_entries;i++){
        insertRandomEntry(function(){
            if(sync_i==(max-1)){
                thingDoneAtTheEnd();
                callback(); //watched by another function, do my stuff there
            }
            else{
                sync_i++;
                console.log(sync_i+" entries done successfully");
                thingDoneEachTime();
            }
        });
    }
}

Which is absolutely horrendous. I can't find anything like a simple for in  async, how would you have done this ?

A: You can use Promises, supported without a library in node.js since version 4.0.
If the callback function of insertRandomEntry has a parameter, you can pass it to resolve. In the function given to then, you receive an array of parameters given to resolve.

function insertMultipleRandomEntries(n_entries,callback){
    var promises = [];
    for(var i=0;i<n_entries;i++) {
        promises.push(new Promise(function (resolve, reject) {
          insertRandomEntry(function (val) {
            thingDoneEachTime(val);
            resolve(val);
          });
        }));
    }

    Promise.all(promises).then(function (vals) {
      // vals is an array of values given to individual resolve calls
      thingDoneAtTheEnd();
      callback();
    });
}