text:
Q: how to import already built database to android app I am new to android and i have to built an android app which will be a quiz, in this i have to pick random question from a given table everytime.I have already built a database can anybody help me how can i import it to my app.
I am going to use an intent that will call the same activity everytime and each time in an activity an random no. is generated it will check if it is generated earlier or not, if not then it will pick tht question from database.
any other suggestions to implement retrieval of question from database or to implement this app are also welcome.

A: As @rwilliams  said you can just copy database from asset to app dir.. u just need to check weather u already copied it or not..
here's how i do it.
just put your database in asset dir.
public class DatabaseHelper extends SQLiteOpenHelper {

    public static String DB_PATH = "/data/data/com.aavid.advance.alarm.clock/databases/";
    private String dbName = "world_time.db";
    protected SQLiteDatabase theDatabase;
    private final Context context;

    public DatabaseHelper(Context c, String dbName){
        super(c,dbName, null, 1);
        this.dbName = dbName;
        this.context = c;
    }

    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }else{
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        try{
            String path = DB_PATH + dbName;
            checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){
        }
        if(checkDB != null){
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException{

        File f = new File(DB_PATH);
        f.mkdirs();

        InputStream myInput = context.getAssets().open(dbName);
        String outFileName = DB_PATH + dbName;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException{
        String myPath = DB_PATH + dbName;
        theDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    }

    @Override
    public synchronized void close() {
        if(theDatabase != null)
            theDatabase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

A: What Nasser answered is right, but let me add some annotate :
If you change your DB(add field, change data type,...),
please DO REMEMBER to change your DB file name.
If you didn't do this, your APP wouldn't read newest DB file until you uninstall APP and install again.

A: Users can clear data if they want. So you can not make your database static.
But, If you want to keep your database, you can copy your database to assets folder and when app invoke method onCreate of SQLiteHelper, you will copy from assets folder to device.
Def.DBNAME = "youdb.sqlite";

Here is the sample:
DBHelper
package vn.mve.db;

import java.util.List;

public interface DBHelper<T> {
    boolean insert(T val);
    boolean update(T val);
    boolean delete(T val);
    List<T> getList(int type);
    T getChild(Object val);
}

DBHandler
public class DBHandler extends SQLiteOpenHelper {
    private static final String TAG = DBHandler.class.getSimpleName();
    protected SQLiteDatabase db;
    private final Context context;
    private static String PACKAGE_NAME = "";
    private static int DATABASE_VERSION = 1;

    public DBHandler(Context context) {
        super(context, Def.DBNAME, null, DATABASE_VERSION);
        this.context = context;
        PACKAGE_NAME = this.context.getPackageName();
        Def.FOLDER_DB = "/data/data/" + PACKAGE_NAME + "/databases/";
        Log.d(TAG, Def.FOLDER_DB);
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        context.deleteDatabase(Def.DBNAME);
        onCreate(db);
    }

    public void createDataBase() throws IOException{
        // for first database;
        boolean dbExist = checkDataBase();
        if(!dbExist){
            try {
                copyDataBase("db/" + Def.DBNAME);
            } catch (Exception e) {
                Log.e(TAG, "createDatabse -> Copy failed!");
                throw new Error("Error copying database");
            }
        } else {
            open();
            boolean isExist = false;
            Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = 'config'", null);
            if (cursor != null) {
                isExist = true;
                cursor.close();
            } else {
                isExist = false;
            }
            close();
            Log.d(TAG, isExist + "");
            if (!isExist) {
                this.context.deleteDatabase(Def.DBNAME);
                try {
                    Log.d(TAG, "createDatabase when database has existed");
                    copyDataBase(Def.DBNAME);
                } catch (Exception e) {
                    Log.e(TAG, "createDatabse -> Copy failed!");
                    throw new Error("Error copying database");
                }
            }
        }
    }
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase(String DB) {
        //Open your local db as the input stream
        InputStream myInput = null;
        //Open the empty db as the output stream
        OutputStream myOutput = null;
        try {
            myInput = context.getResources().getAssets().open(DB);

            // Path to the just created empty db
            String outFileName = Def.FOLDER_DB + Def.DBNAME;
            myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0){
                myOutput.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "copyDatabase -> File not found.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "copyDatabase");
        } finally {
              //Close the streams
            try {
                myOutput.flush();
                myOutput.close();
                myInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private boolean checkDataBase(){
        boolean checkDB = false;
        try{
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            File dbFile = new File(myPath);
            checkDB = dbFile.isFile();
            Log.d(TAG, "checkDatabase: " + String.valueOf(checkDB));
            try {
                File fTmp = new File(Def.FOLDER_DB);
                if (!fTmp.exists()) {
                    fTmp.mkdir();
                }
            } catch (Exception e) {
                Log.e(TAG, "checkDatabase" + e.getMessage());
            }
        }catch(SQLiteException e){}
        return checkDB;
    }
    public void open() {
        try {
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void close() {
            if(db != null)
                db.close();
            super.close();
    }
    public SQLiteDatabase getSqlDb() {
        return db;
    }
    public void setSqlDb(SQLiteDatabase sqlDb) {
        this.db = sqlDb;
    }
}

And here:
public class MVideo extends DBHandler implements DBHelper<Video> {
    public static final String TAG = MVideo.class.getSimpleName();
    public MVideo(Context context) {
        super(context);
    }

    @Override
    public boolean insert(Video val) {
        open();
        ContentValues cValues = new ContentValues();
        cValues.put(Def.Video.ID, val.getId());
        cValues.put(Def.Video.TITLE, val.getTitle());
        cValues.put(Def.Video.THUMBNAIL, val.getThumbnail());
        cValues.put(Def.Video.DESCRIPTION, val.getDescription());
        cValues.put(Def.Video.ENGLISH, val.getEnglish());
        cValues.put(Def.Video.VIETNAMESE, val.getVietnamese());
        cValues.put(Def.Video.ISVIEW, val.getIsView());
        long result = db.insert(Def.Video.NAME, null, cValues);
        close();
        return result > 0;
    }

    public boolean insertList(List<Video> list) {
        open();
        db.execSQL("BEGIN IMMEDIATE TRANSACTION");
        for (Video v : list) {
            db.execSQL(String.format("INSERT INTO " + Def.Video.NAME + " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") VALUES" +
                    " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",
                    Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION,
                    Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW,
                    v.getId(), v.getTitle(), v.getThumbnail(), v.getDescription(), v.getEnglish(), v.getVietnamese(), v.getIsView() + ""));
            Log.d(TAG, "insertList -> " + v.toString());
        }
        db.execSQL("COMMIT TRANSACTION");
        close();
        return true;
    }

    @Override
    public boolean update(Video val) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean delete(Video val) {
        open();
        db.delete(Def.Video.NAME, Def.Video.ID + "=?", new String[]{val.getId()});
        close();
        return false;
    }

    @Override
    public List<Video> getList(int type) {
        List<Video> list = new ArrayList<Video>();
        open();
        Cursor c = db.rawQuery(Def.Video.GET_ALL, null);
        if (c.moveToFirst()) {
            while (c.moveToNext()) {
                String ID = c.getString(0);
                String title = c.getString(1);
                String thumbnail = c.getString(2);
                String description = c.getString(3);
                String english = c.getString(4);
                String vietnamese = c.getString(5);
                boolean isView = Boolean.parseBoolean(c.getString(6));
                list.add(new Video(ID, title, thumbnail, description, english, vietnamese, isView));
            }
        }
        close();
        return list;
    }

    @Override
    public Video getChild(Object val) {
        open();
        Cursor c = db.query(Def.Video.NAME, new String[]{
                Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION,
                Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW
        }, Def.Video.ID + "=?", new String[]{val.toString()}, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        Video v = new Video(c.getString(0), c.getString(1),
                c.getString(2), c.getString(3), c.getString(4),
                c.getString(5), Boolean.parseBoolean(c.getString(6)));
        close();
        return v;
    }
}


text:
Q: Android does interface method called in which thread ? sync or async? I know it is a very question. I am trying to implement a callback mechanism.
I have a java Class in Android  and inside i have an interface
public interface MyInterface {

        public void cb1(Integer id);
        public void cb2(Integer id);
    };

User can use my Interface and implement, and whenever i need to inform to the user  , i will invoke cb1() or cb2().
Question:
Let's say user have provided me implementation of interface mInterface,
 while (1) {
     mInterface.cb1()
 }

1) In which thread cb1() will get invoked ? sync call or async call ?
2) if async call, what if the implementation of cb1() blocks for some time? Will all the cb1() calls delivered to the user one by one ?

A: In the code above it will be a synchronous call. If you want it to be async, you should create a new Thread to perform the callback on.

A: Odd question. The code will be async relative to the main thread if it is not executed on the main thread. Otherwise it will be sync and is executed on the main thread

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot adjust size of legend key values I am having problems finding a way to adjust the value of key legends. In the example below count ranges from 3 to 500, however the legend only ranges from 100 to 500. This is understandable, though I would like to change the values of the legend so there is a size that corresponds with a count of 3.
So in sum I would like to find a way to adjust the key values to correspond with count values I select. Is this possible?
library(ggplot2)
df <- data.frame(x = c(1, 2, 3, 4, 5, 6),
             y = c(4, 2, 6, 1, 7, 7),
             count = c(3, 100, 200, 300, 400, 500))

plt <- ggplot() +
  geom_point(data = df,
         aes(x = x, y = y, size = count))

A: Credit to this answer goes to aosmith.
Below is the correct code.
library(ggplot2)
df <- data.frame(x = c(1, 2, 3, 4, 5, 6),
         y = c(4, 2, 6, 1, 7, 7),
         count = c(3, 100, 200, 300, 400, 500))

plt <- ggplot() +
  geom_point(data = df,
     aes(x = x, y = y, size = count)) +
  scale_size_continuous(breaks = c(3, 100, 200, 500))


text:
Q: Power BI : Need to Calculate Last 3 Months MTD Sales I have scenario where I have to filter sales for last 3 months based on MTD of current Month.
Ex: If Selected Month is March which has maximum date 11th (11-Mar-2021) . I'll need to calculate for Last 3 months excluding current Month i.e. Till 11th in each of Feb 2021 ,Jan 2021,Dec 2020.
I see that following can be achieved using time intelligence for previous month. Can anyone suggest how to filter MTD with respect to other months as well
3Month MTD Test =
CALCULATE(SUM([Sales]), DATESINPERIOD('Date_Dim'[Date],LASTDATE(PREVIOUSMONTH(Date_Dim[Date])),-3,MONTH),Day(Date_Dimn[Date]<=DAY(TODAY()))
)

A: I think PARALLELPERIOD function should do the trick for you: https://learn.microsoft.com/en-us/dax/parallelperiod-function-dax .
I'm not sure how your data structure looks like, but in any case you first need to filter your date column only for dates in the current month. If you are not just using filter pane for it you can use DATESMTD function for example: https://learn.microsoft.com/en-us/dax/datesmtd-function-dax.
After that you can use this column and PARALLELPERIOD to get sales for the same period 1,2 and 3 months ago.


text:
Q: Need help removing duplicates numbers in Python exercise I'm supposed to write a program that eliminates duplicate values and returns unique numbers. I must use a def eliminate(alist) and a def main(). The numbers must be entered from standard input and must be space separated.
The output should be as follow

Enter numbers: 5 3 12 3 544 5 1 7 1
The numbers are: [5, 3, 12, 554, 1, 7]

Instead I get....

Enter numbers: 5 3 12 3 544 5 1 7 1
The numbers are: ['5', ' ', '3', '1', '2', '4', '7']

How do I remove the space? Also my program doesn't recognize 554 as a single number, it recognizes it as 5 4 4.
This is what I got so far
def eliminate(alist):
    outlist = []
    for element in alist:
        if element not in outlist:
            outlist.append(element)
    return outlist

def main():
    numbers=input("Enter numbers:")
    alist=list(numbers)
    print("The unique numbers are:",eliminate(alist))
main()

PLEASE NOTE: I'm not allow to use the set class for this program.

A: You're just giving it a series of characters, and asking for unique ones, which it seems to be doing correctly.  You need to split the string on spaces, and maybe even convert to numbers (int's, I'm guessing):
alist = [int(num) for num in numbers.split(' ')]

A: try:
item for item in myList if item.count(item) == 1

for the logic of your function body (if you must use it).  pass the return of this list comprehension to a variable or print.

A: You are getting '' and 544 as separate characters because in your input, the numbers is not a list of integers. It is a string of characters. Even if you convert it to a list, it is still a list of individual characters.
So, for converting it into integers, do this:
numbers=map(lambda x:int(x), numbers.split())
Now, to eliminate the duplicates, you can use a dictionary, if not a set:
unique = dict.fromkeys(numbers).keys()

A: Both of the problems will be solved if you used:
alist = numbers.split()

instead of alist=list(numbers)
>>> numbers = '5 3 12 3 544 5 1 7 1'
>>> alist = numbers.split()
>>> alist
['5', '3', '12', '3', '544', '5', '1', '7', '1']

Explanation:
if you pass numbers to the list() function as is, it takes each character of the string to a list member. This way, '544' becomes ['5', '4', '4'] and '5 6' becomes ['5', '6'].
split() on the other hand makes list of a string by splitting it according to a specific delimiter, which is by default, the " " char.


text:
Q: Will Structural Equation Modeling be reliable if I have two highly correlated variables and I know that they cannot share the same latent variable? I have two variables which are highly correlated (0.99). But I want to evaluate their individual effect on the target variables (2 in this case). I don't want to create a latent variable using these two variables because logically they don't belong in the same group.
If I use a regression-like model (Y1 ~ X1 + X2, Y2 ~ X1 + X2) in the SEM ( lavaan package in R), will it be the same thing as using multiple linear regression?
Does using structural equation modeling make sense in this case? If not, which would be a suitable method for this analysis?

A: You'll get the same estimates (and standard errors) as  running two linear regressions (assuming that you have covariances between Y1 and Y2, and X1 and X2).
SEM buys that you can do a multivariate test, which you can also do using   MANOVA.  Apart from that, you don't get very much. Also, you might look at this paper,  which talks about how the correlation between outcomes can affect power (it's true for SEM and MANOVA).
The big thing that SEM can buy you is Full Information Maximum Likelihood (FIML)estimates, if you have missing data. If you don't have missing data, you don't care though. And if you do have missing data, you can do multiple imputation, which is asymptotically equivalent. (I find FIML to be quicker and easier - but YMMV, it probably depends what you have more practice at.)


text:
Q: Setting a firestore document when a new user is created with firebase auth using node.js I'm using firebase cloud functions, firebase auth and firestore.
I've done this before with firebase database but just not sure with firestore how to set a document in the users collection to the uid of a newly created firebase auth user.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const db = admin.firestore()

exports.createUser  = functions.auth.user().onCreate(event => {

 const uid  = event.data.uid;
 console.log(uid);

 db.collection('users').doc(uid);

});

The above completes ok in the logs but the uid isn't getting set in the database. Do I need to call set at some stage?

A: const collection = db.collection("users")
const userID = "12345" // ID after created the user.
collection.doc(userID).set({
    name : "userFoo", // some another information for user you could save it here.
    uid : userID     // you could save the ID as field in document.
}).then(() => {
    console.log("done")
})

A: Note, that the onCreate return has changed, it does return the user now, so event.data.uid isn't valid anymore.
The full function should look something like this, it will create a document with the user's uid in the "users" root-collection.
exports.createUser = functions.auth.user().onCreate((user) => {
    const { uid } = user;

    const userCollection = db.collection('users');

    userCollection.doc(uid).set({
        someData: 123,
        someMoreData: [1, 2, 3],
    });
});


text:
Q: How many times the word is used on the html page I have a method that should return an integer which is the number of uses of the searchWord in the text of an HTML document:
public int searchForWord(String searchWord) {
    int count = 0;
    if(this.htmlDocument == null){
        System.out.println("ERROR! Call crawl() before performing analysis on the document");
    }
    System.out.println("Searching for the word " + searchWord + "...");
    String bodyText = this.htmlDocument.body().text();
    if (bodyText.toLowerCase().contains(searchWord.toLowerCase())){
        count++;
    }
    return count;
}

But my method always returns count=1, even if the word is used several times. I understand that the error should be obvious, but I'm stuck and I don't see it.

A: You are currently only checking once that the text contains the search word, so the count will always be either 0 or 1. To find the total count, keep looping using String#indexOf(str, fromIndex) while the String can be found using the second argument that indicates the index to start searching from.
public int searchForWord(String searchWord) {
    int count = 0;
    if(this.htmlDocument == null){
        System.out.println("ERROR! Call crawl() before performing analysis on the document");
    }
    System.out.println("Searching for the word " + searchWord + "...");
    String bodyText = this.htmlDocument.body().text();
    for(int idx = -1; (idx = bodyText.indexOf(searchWord, idx + 1)) != -1; count++);
    return count;
}

A: According to the Java docs String#contains:

Returns true if and only if this string contains the specified sequence of char values.

You're asking if the word you're looking for is contained in the document, which it is.
You could:

*

*Split the text on words (splitting it by spaces) and then count how many times it appears

*Iterate the String using String#indexOf starting on index 0 and then from last index you found until the end of the String.

*Iterate the String using contains but starting from a certain index (doing this logic yourself).

I'd go for the 2nd approach as it seems like the easiest one.

A: These are only conditional statements, you aren't looping through the HTML text, therefor, if it finds the instance of searchWord in bodyText, it'll increment it, and then exit the method with a value of 1. I suggest looping through every word in the html, adding it to an array, and counting it that way using something like this:
char[] bodyTextA = bodyText.toCharArray();

Or keep it in a string array and split it by a space, or new line, or whatever criteria you have. Example of space:
//puts hello, i'm, your, and string into their own array slots in the array
/split
str = "Hello I'm your String";
String[] split = str.split("\\s+");

A: Your issue here is that the if statement is checking if the text contains the word and the increments your count variable. So even if it contains the word multiple time, your logic goes basically, if it contains it at all, increase count by one. You will have to rewrite your code to check for multiple occurrences of the word. There are many ways you can go about this, you could loop through the entire body text, you could split the body text into an array of words and check that, or you could remove the search word from the text each time you find it and keep checking until it no longer contains the search word.

A: You can use indexOf(,) with an index for the last found word
public int searchForWord(String searchWord) {
    int count = 0;
    if(this.htmlDocument == null){
         System.out.println("ERROR! Call crawl() before performing analysis on the document");
    }
    System.out.println("Searching for the word " + searchWord + "...");
    String bodyText = this.htmlDocument.body().text();
    int index = 0;
    while ((index = bodyText.indexOf(searchWord, index + 1)) != -1) {
        count++;
    }
    return count;
}


text:
Q: Can I send data via express next() function? I'm working on a webapp that requires atuhentication process and session management with express. I've done with the backend sessions stuff. Now i want to show on the UI the user who is signed in. privateContent is a function that verify if someone is logged in, Like so:
...
app.get( '/authRequired', queries.privateContent , routes.tasks );
...

Here is queries.privateContent:
...
exports.privateContent = function ( req, res, next ) {
  if ( req.session.user ) {
    var username = req.session.user.username;
    User.findOne( { 'username': username }, function ( err, obj ) {
      if ( true ) {
        next();
      } else {
        res.redirect('/');
      }
    });
  } else {
    res.redirect('/');
  }
};
...

What i want to know is: Am i able to send data like this? :
...
next( username );
...

if so, how can i retrieve it when routes.tasks render, if that happens as follows (i'm trying to get the data in the code below, but it does not work.):
...
exports.my_tasks = function ( req, res, data ) {
      console.log(data);
      res.render('tasks/tasks',
                  { title: 'Paraíso', controller: 'MyTasksController', user: data });
};
...

As you can guess, my intentions are to pass via next the current user who is signed in to the routing modules, so i can print the username in the UI using jade.
Thank you for your help. :)

A: In this case you have a few options (only use one of these!):

*

*You can just access the req.session.user.username variable from your my_tasks route

*You can use res.locals

*You can add data to the req object

In your exports.privateContent function, once a user is found in the database, you can simply add that data to the res.locals:
User.findOne( { 'username': username }, function ( err, obj ) {
  if ( true ) {
    // this variable will be available directly by the view
    res.locals.user = obj;

    // this will be added to the request object
    req.user = obj;

    next();
  } else {
    res.redirect('/');
  }
});

Then in your exports.my_tasks route, res.locals.user will be whatever obj was in the middleware. You can then simply access that in the view as the variable user.
So, all together, you can access the data in your route in these ways:
exports.my_tasks = function ( req, res ) {
   res.render('tasks/tasks', {
     userFromReq: req.user, // this exists because you added in the middleware
     userFromSession: req.session.user, // this was already in the session, so you can access
     userFromRes: [DO NOT NEED TO DO THIS] // because res.locals are sent straight to the view (Jade).
   });
};


text:
Q: Deconstructs an array field ($unwind) with spark-mongo connector I´m trying to do queries with spark-mongo connector, a simple query like:
sqlContext.sql("SELECT members.name FROM members WHERE age >= 100")

Mike
Peter
...

but when I try to show a string-array (members.child_names) it does not execute $unwind, it generates a chain of Strings:
sqlContext.sql("SELECT members.child_names FROM members WHERE age >= 100")
Mike_child, Peter_child...

Is it possible project that query doing $unwind ???

A: You can always explode it:
sqlContext.sql("""
  SELECT EXPLODE(members.child_names) FROM members WHERE age >= 100
""")


text:
Q: How to make Sony WH-1000XM3 sound the same in wired and bluetooth mode on Windows 10 PC? My Windows 10 desktop setup has the Realtek audio driver. From many years I have set the equalizer to rock since the default sound of Windows isn't great. Usually any wired headphone or 2.1 speaker sounds great with this.
A while back I plugged in the TP-Link bluetooth USB dongle which lets me connect bluetooth earphones to the PC easily. The dongle works perfectly. A few days back we bought a Sony WH-1000XM3. It sounds great on Android phones and the Sony Connect app lets you try the additional features. This app isn't available for desktop OSes.
Now I realized that the 'rock' equalizer of Realtek works only when the headset is connected by wire to the PC. Removing the wire and listening through bluetooth doesn't make the audio sound as open. It sounds as if 'rock' is OFF—muffled.
I installed Equalizer APO and Peace GUI after searching online for solutions. After that the equalizer from Realtek disappeared. So I tried some settings in Peace (can't understand most of them) but it still doesn't make any difference. Weather I choose all devices or just the two versions of the bluetooth headset—stereo and hands-free AG audio—it still sounds bassy and muffled compared to when I connect the wires.
How can I make the bluetooth sound as great as the wired mode?

A: *

*Windows doesn't support LDAC codec, your phones might do. You can't do anything about this.

*I couldn't find any information if Windows supports aptX HD, so I'd assume it doesn't.

*Original aptX codec is supported in recent versions of Windows - if your dongle supports it. This app claims to be able to detect which codec is in use.

A: In the home app if you change the connection priority to stable (the codec to will change to SBC) then it will retain the home app settings for windows as well!


text:
Q: Meaning of # in a SQL Transaction Hi I was checking some store procedures of a product installed on my company, you know to see how other people solve problems and learn.
Among this I found this but I do not know what is the meaning of the # in the sql sp in the line select distinct objecttype from #CascadeCollect, any comments please?
This is the whole sp..
begin
    -- get all the unique otcs collected in the temp table.
    declare @EntityCode int
    -- check if the entity requires special casing.
    declare @DbCascadeMask int

    -- special casing for calendar delete
    exec p_DeleteCalendar

    declare otccursor cursor for
    select distinct objecttype from #CascadeCollect    <------ here is the # ....

    open otccursor
    fetch otccursor into @EntityCode

    while @@fetch_status = 0
    begin
        select @DbCascadeMask = DbCascadeMask
        from EntityView as Entity
        where Entity.ObjectTypeCode = @EntityCode

        if @DbCascadeMask <> 0
        begin
            exec p_BulkDeleteGeneric @EntityCode
        end

        fetch otccursor into @EntityCode
    end
    CLOSE otccursor
    DEALLOCATE otccursor

    -- Return the count of entity instances that are still not deleted (because they
    -- require platform bizlogic/special casing.
    select count(*) as NotDeletedCount from #CascadeCollect where processed = 2
end

Thanks for any comments !!!

A: a table prefixed with # is a local temporary table, it will be dropped once it is out of scope
create table #test(id int)

insert #test values (1)

select * from #test

If you run this from another connection select * from #test the table is not available since it is local

A: A single # as a prefix indicates a locally scoped temporary object. In this case it is clearly a table but you can also have #temp procedures as well.
It is only visible to the batch in which it is created (and any child batches) and dropped automatically when the batch exits.
So if that is the whole stored procedure then it is obviously expected to be run from another procedure that actually creates the temp table.
You can also have global temporary objects prefixed with ##.


text:
Q: Derivatives of the eikonal Let $y$ be an extremal function of the functional
$$J[y]=\int_{x_1}^{x_2} L(x, y(x), y'(x)) \mathrm{d}x$$
So it satisfies the Euler-Lagrange equation:
$$\frac{\partial L}{\partial y}-\frac{\mathrm{d}}{\mathrm{d}x}\frac{\partial L}{\partial y'}=0$$
If we then substitute this $y$ into the original functional, we get the eigonal:
$$S(x_1,x_2,y_1,y_1)=\int_{x_1}^{x_2} L(x, y(x), y'(x)) \mathrm{d}x$$
Which is now the function of $x_1, x_2, y_1=y(x_1), y_2=y(x_2)$. Then we have that
$$\frac{\partial S}{\partial x_2}=-E(x_2)$$
And
$$\frac{\partial S}{\partial y_2}=p(x_2)$$
Where
$$p=\frac{\partial L}{\partial y'}$$
And
$$E=py'-L$$
Question: How to show these identities with differentiating $S$ directly?
I've seen the derivation with discretization, but I would like to do it this way. I tried to apply the Leibniz integral rule:
$$\frac{\partial S}{\partial x_2}=L(x_2)+\int_{x_1}^{x_2}\frac{\partial L}{ \partial x_2} \mathrm{d}x$$
But I could not show that
$$\int_{x_1}^{x_2}\frac{\partial L}{ \partial x_2} \mathrm{d}x=-p(x_2)y'(x_2)$$


text:
Q: How to record audio/voice in background continuously in android? As I want to record audio in background I use service..But I am not able to record the audio in service.
I tried same code in Activity it works for me. but how to do audio recording in background when voice /speech is input that means audio recording should start if there is voice input and that should be in background...?

A: In one of my project I had this requirement to continuously record audio from Microphone. I can not share the project but I can share the specific AudioRecorder class.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;

    public class AudioRecorder {
        public enum State {
            INITIALIZING,
            READY,
            RECORDING,
            ERROR,
            STOPPED
        };
        private byte[] audioBuffer = null;
        private int source = MediaRecorder.AudioSource.MIC;
        private int sampleRate = 0;
        private int encoder = 0;
        private int nChannels = 0;
        private int bufferRead = 0;
        private int bufferSize = 0;
        private RandomAccessFile tempAudioFile = null;
        public AudioRecord audioRecorder = null;
        private State state;
        private short bSamples = 16;
        private int framePeriod;

        // The interval in which the recorded samples are output to the file
        // Used only in uncompressed mode
        private static final int TIMER_INTERVAL = 120;
        volatile Thread t = null;
        public int TimeStamp = 0, count = 0, preTimeStamp = 0;

        public AudioRecorder(Context c) {
            this.sampleRate = 11025;
            this.encoder = AudioFormat.ENCODING_PCM_16BIT;
            this.nChannels = AudioFormat.CHANNEL_CONFIGURATION_MONO;
            this.preTimeStamp = (int) System.currentTimeMillis();
            myApp = (MyApp) c.getApplicationContext();
            mQueue = myApp.getQueue();

            try {
                /*
                    String fileName = "/sdcard/XYZ/11025.wav";
                    tempAudioFile = new RandomAccessFile(fileName,"rw");
                */

                framePeriod = sampleRate * TIMER_INTERVAL / 1000;
                bufferSize = framePeriod * 2 * bSamples * nChannels / 8;

                if (bufferSize < AudioRecord.getMinBufferSize(sampleRate, nChannels, encoder)) {
                    bufferSize = AudioRecord.getMinBufferSize(sampleRate, nChannels, encoder);

                    // Set frame period and timer interval accordingly
                    framePeriod = bufferSize / (2 * bSamples * nChannels / 8);
                    Log.w(AudioRecorder.class.getName(), "Increasing buffer size to " + Integer.toString(bufferSize));
                }

                audioRecorder = new AudioRecord(source, sampleRate, nChannels, encoder, bufferSize);
                audioBuffer = new byte[2048];
                audioRecorder.setRecordPositionUpdateListener(updateListener);
                audioRecorder.setPositionNotificationPeriod(framePeriod);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        private AudioRecord.OnRecordPositionUpdateListener updateListener = new AudioRecord.OnRecordPositionUpdateListener() {
            @Override
            public void onPeriodicNotification(AudioRecord recorder) {
                //          Log.d(Constant.APP_LOG,"Into Periodic Notification...");
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            */
        }

        @Override
        public void onMarkerReached(AudioRecord recorder) {
            // TODO Auto-generated method stub
        }
    };

    public void start() {
        if (state == State.INITIALIZING) {
            audioRecorder.startRecording();
            state = State.RECORDING;

            t = new Thread() {
                public void run() {
                    //Here You can read your Audio Buffers
                    audioRecorder.read(audioBuffer, 0, 2048);
                }
            };

            t.setPriority(Thread.MAX_PRIORITY);
            t.start();
        } else {
            Log.e(AudioRecorder.class.getName(), "start() called on illegal state");
            state = State.ERROR;
        }
    }

    public void stop() {
        if (state == State.RECORDING) {
            audioRecorder.stop();
            Thread t1 = t;
            t = null;
            t1.interrupt();
            count = 0;
            state = State.STOPPED;
        } else {
            Log.e(AudioRecorder.class.getName(), "stop() called on illegal state");
            state = State.ERROR;
        }
    }

    public void release() {
        if (state == State.RECORDING) {
            stop();
        }

        if (audioRecorder != null) {
            audioRecorder.release();
        }
    }

    public void reset() {
        try {
            if (state != State.ERROR) {
                release();
            }
        } catch (Exception e) {
            Log.e(AudioRecorder.class.getName(), e.getMessage());

            state = State.ERROR;
        }
    }

    public State getState() {
        return state;
    }
}

Now, Create Service and just call start() method and manipulate your recorded audio buffer for your purpose.
Hope it will Help you.

A: For starting the recording in backgroun you can either

*

*create a thread and do the recording inside a thread.

*create a service which will run in background.
Hope it helps.
Edit 1
Thread recordInBackGround= new Thread(new Runnable() {
                    @Override
                    public void run() {
//Your recording portion of the code goes here.
}
});

recordInBackGround.start();


text:
Q: Parse parameters out of URL in Lua I have a URL and would like to parse its Parameter out of it, like:
function unescape (s)
  s = string.gsub(s, "+", " ")
  s = string.gsub(s, "%%(%x%x)", function (h)
        return string.char(tonumber(h, 16))
      end)
  return s
end

function parseurl (s,param)
for k, v in string.gmatch( s, "([^&=?]+)=([^&=?]+)" ) do
    --t[k] = v
    if k == param then
        --print (k.." "..v)
        return unescape(v)
    end
end

s = "http://www.page.com/link.php uname=Hans+Testmann&uemail=myemail%40gmail.com&utext=Now+this+is+working+great.%0D%0A++&mdt=1#&mydays:themeupload"s

Than I would call it and get Results like after -->
parseurl (s, "uname")      --> "Hans Testmann"
parseurl (s, "uemail")     --> "myemail@gmail.com"
parseurl (s, "utext")      --> "Now this is working great"

I already fixed a lot and seems to work,
but could you look how its possible to improve?

A: I would return all parameters in a table and use like so:
function urldecode(s)
  s = s:gsub('+', ' ')
       :gsub('%%(%x%x)', function(h)
                           return string.char(tonumber(h, 16))
                         end)
  return s
end

function parseurl(s)
  s = s:match('%s+(.+)')
  local ans = {}
  for k,v in s:gmatch('([^&=?]-)=([^&=?]+)' ) do
    ans[ k ] = urldecode(v)
  end
  return ans
end

t = parseurl(s)
print(t.uname ) --> 'Hans Testmann'
print(t.uemail) --> 'myemail@gmail.com'
print(t.utext ) --> 'Now this is working great'


text:
Q: Facebook video upload Exception "(OAuthException - #1) An unknown error has occurred." My WPF application i am using facebook C# SDK to upload videos to facebook wall. From last two days, when i upload video through my application, SDK returns "(OAuthException - #1) An unknown error has occurred." exception, but my video file uploaded to my facebook wall.
I tried the following way to resolve this problem,    1) Created new appliction for new AppID and AppSecretID.    2) Change authentication permissions (current permissions provided user_about_me,read_stream,publish_stream,user_photos)    3) Clear the existing application permission in my facebook account    4) Creating new facebook application and upload a video file.But nothing helps me. Here is the code i used to upload video,
public Task<bool> FacebookPost(string message,Stream videoFileStream)
    {
        bool result = false;
          try
            {
                if (!string.IsNullOrEmpty(_localSettings.FBAccessToken))
                {
                    _fbClient.AccessToken = "ACCESS_TOKEN";
                    _fbClient.AppId = "APP_ID";
                    _fbClient.AppSecret = "APP_SECRET";

                    var media = new FacebookMediaStream { ContentType = "video/mp4", FileName = "TestVideo.mp4" }.SetValue(fbStream);
                    dynamic parameters = new ExpandoObject();
                    parameters.Title = "Sample Video";
                    parameters.description = message;
                    parameters.source = media;
                    var uploadResult = await _fbClient.PostTaskAsync("me/videos", parameters);
                    result = uploadResult != null;
                }
            }
            catch (FacebookOAuthException ex)
            {
                result = false;
            }
            return result;
    }

Any help it will would be appreciated. Thanks in advanced.

A: Check that https://developers.facebook.com/x/bugs/247807142061930/ Appears to be a known bug


text:
Q: How can I align a widget to the center of a Row and align the other 2 widgets to the center of each remaining space? Link to the printscreen of the figma model
I want to place the VerticalDivider widget right in the middle of the Row with the other 2 Columns that contain "Objetivo: Recomendação médica" and "Nível do aluno: intermediário" and I want both of these Columns in the middle of the space left for each one.

A: Use Expanded to split remaining spaces in a Flex (like Row or Column).
For example:
Row(
  children: [
    Expanded(child: Container(color: Colors.blue)),
    VerticalDivider(),
    Expanded(child: Container(color: Colors.orange)),
  ],
)


text:
Q: How to add overlay to material UI table row? I am rendering a row like this
`<TableRow
  key={row.name}
>
  <TableCell>{row.empId}</TableCell>
  <TableCell>{row.userId}</TableCell>
  <TableCell>{row.name}</TableCell>
  <TableCell>{row.hireDate}</TableCell>
  <TableCell>{row.terDate}</TableCell>
  <TableCell>{row.empType}</TableCell>
  <TableCell>
    <Typography variant="button" color={row.empStatus ? 'primary' : 'error'}>
      {row.empStatus ? 'Active' : 'Inactive'}
    </Typography>{' '}
  </TableCell>
  <TableCell align="right">
    <IconButton aria-label="view log" onClick={() => setOpen(true)}>
      <HistoryIcon fontSize="small" />
    </IconButton>
    <IconButton aria-label="edit">
      <EditIcon fontSize="small" />
    </IconButton>
  </TableCell>

overlay text

</TableRow>`

and an overlay has CSS like
`.overley {
    position: absolute;
    background-color: gainsboro;
    opacity: 0.5;
    width: 100%;
  }
  .tableRow {
    position: relative;
  }`

I am expecting something like this
table
so how to add overlay effect or any div which display over the row without effecting table or row width and alignment.
above code is adding one more column at the end, if I give left : 0, it's shifting to the left of the screen. Does anyone know how to get this done?

A: I was looking to do the same and was able to do this by doing the following more or less:
<TableRow className={'row-overlay-hover'}>
    <TableCell/>
    ...
    <TableCell/>
    <TableCell>

                Overlay content

    </TableCell>
</TableRow>

.row-overlay-hover td:last-child {
    width: 0;
    padding: 0 !important;
}
.row-overlay-hover:hover .overlay-content {
    visibility: visible;
}
.overlay-wrapper {
    position: relative;
}
.overlay-content {
    visibility: hidden;
    position: absolute;
    right: 0;
}

Note:

*

*I referenced this Overlay table cells with two buttons on hover and it's answer notes that not all browsers support position: relative on a table cell (though it's from 2012) so I opted to wrap my overlay in a div with a zero-width column at the end of the table


text:
Q: how to remove item from list and update list in angularjs? i have platform list in my project , i want remove one item from platform list and see update list without reloading
platform list image : platform list image
i use ui-route in my project
body of platform-list.html :

            {{platform.PlatformID}}
            {{platform.Name}}
            <button ui-sref="platform-edit({id: platform.PlatformID})" class="btn btn-warning">Edit </button> |
            <button ng-click="remove(platform.PlatformID)"  class="btn btn-danger">Delete </button>

platform-list-controller.js :
mainApp.controller('platformListController', function ($scope, platform, $filter) {
  platform.query().$promise.then(function (data) {
    $scope.platforms = data;
  }, function (error) {
  });
});

platform model :
public class Platform
{
    [Key]
    public int PlatformID { get; set; }
    public string Name { get; set; }
}

how to write remove code in this controller?

A: this code solve your problem :
mainApp.controller('platformListController', function ($scope, platform, $filter) {
platform.query().$promise.then(function (data) {
    $scope.platforms = data;
}, function (error) {
});

//add this code
$scope.remove = function (id) {
    platform.remove({ id: id }).$promise.then(function () {
        $scope.platforms = $filter('filter')($scope.platforms, function (item) {
            return item.PlatformID !== id;
        });
        alert('Removed');
    }, function (error) {
        alert('Failed');
    });
};
//

});

A: You can use array.splice() method to remove data from array. This syntex is
array.splice(index , howMany[, element1[, ...[, elementN]]])

In your controller
mainApp.controller('platformListController', function ($scope, platform, $filter) {

  $scope.platforms = [];

  platform.query().$promise.then(function (data) {
    $scope.platforms = data;
  }, function (error) {
  });

$scope.remove = function(platformId, index){
    $scope.platforms.splice(index,1);
}

});

and your html should be like following:

            {{platform.PlatformID}}
            {{platform.Name}}
            <button ui-sref="platform-edit({id: platform.PlatformID})" class="btn btn-warning">Edit </button> |
            <button ng-click="remove(platform.PlatformID, $index)"  class="btn btn-danger">Delete </button>

A: What are the properties of $scope.platforms? Probably the easiest (not the most efficient) is to add an ng-click attribute.
In terms of code, this would be the HTML for the Delete button:
`<btn ng-model="delBtn" ng-click="deletePlatform(platform.id)">
    Delete
</btn>`

and the function in the controller or directive would be:
`function deletePlatform(platform.id) {
    $scope.platforms.filter(function (platformItem) {
        return platformItem.id !== platform.id;
    });
}`


text: Q: How to allocate multiple TPUs and adjust code to run on all of them as a part of my R&D I was given access to multiple TPUs, but I can't find documentation how to allocate them together for my training purposes, both node-wise and code-wise. The documentation said ctpu up -zone MY_ZONE_CHOICE but this command allocates only single TPU. And, similar what changes should I add to my code if I want to use multiple TPUs? So far I've used this call tf.contrib.cluster_resolver.TPUClusterResolver() to check for TPU, what should be changed (if any) to check if I can access multiple TPUs?


text:
Q: How to fix 'response.json is not a function' in async/await function Trying to turn my response into json. I'm not quite sure I'm getting TypeError: response.json is not a function error. Can someone please point me in the right direction. Thanks in advance.
    componentDidMount(){
        this.timingFunction = setInterval(() => this.getAllStations(), 1000);
    }

    async getAllStations(){
        try{
            const response = await(`http:api.bart.gov/api/etd.aspx?cmd=etd&orig=${this.state.selectedStation}&key=${bartKey}&json=y`);
            const data = await response.json();
            console.log(`Here: ${data}`)

        }catch(e){
            console.log(`Error: ${e}`)
        }

    }

I expected to see the json response but got the error message.
edit: Added await in front of response.json(); and got no where.

A: You are using await as a function
await is a system to wait for a promise only, instead of doing

const response = await('http:...');

You should do
const response = await fetch('http:...');

A: You're missing the call to fetch (or whatever else you use to get data from the api). Right now it looks like you've mistaken await for a function.
const response = await(`http:api.bart.gov...
(You're also missing the two slashes after the http but that's not a problem yet.)
Try this:
const response = await fetch(`http://api.bart.gov...


text:
Q: Embed wxmplot window in wxpython frame Is it possible to embed the wxm multiplot window in a wx main frame?
This site ( http://newville.github.io/wxmplot/other.html#multiplotframe ) gives details about how to get a multiplot but the plot is displayed as separate window. I want to create a GUI with wx widgets but I am unable to put them all in the same window frame.

A: Well, MultiPlotFrame is a frame that contains some PlotPanels, so you can't do it directly, but look as the source code of multiframe
https://github.com/newville/wxmplot/blob/master/lib/multiframe.py
I guess you can pretty much take it almost as it is and turn it into something like MultiPlotPanel, and use that in your frame.


text:
Q: Reverting git commits I have a git repository setup and I have made several commits from my local branch and pushed these changes onto the master branch. I realised that this changes need to be reverted.
First question is, could I recover the project to the version that works.
If so how would I go about doing this either from source tree or terminal.
Lastly what are the implications or risk of undoing changes. Is there a chance this project could be lost forever. I really I am beginner with git so I am totally out of my depth.

A: You may find this flowchart useful:
http://justinhileman.info/article/git-pretty/
The key point is this. Has anyone else got the erroneous commit on their machine? If so, then you should look at git revert. If not, they you may like to use git rebase -i to interactively remove a commit from your history before git push --force to get the content back onto your remote.
There really is no substitute for hands on experience. I suggest you create a git repository in a new folder and experiment with these scenarios there. Good luck!


text:
Q: Array with key value trying to calculate distance with lat and long and using pre-build php  distance() function.Problem is that I am unable to formet array like this $point1 and $Point 2
   $point1 = array("lat" => "48.8666667", "long" => "2.3333333"); // Paris (France)
    $point2 = array("lat" => "19.4341667", "long" => "-99.1386111"); // Mexico City (Mexico)
    echo$km = distanceCalculation($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);

Here is my query and its return array like  this
  Array
    (
        [0] => Array
            (
                [lat] => 32.9697
                [long] =>  -96.80322
            )

        [1] => Array
            (
                [lat] => 29.46786
                [long] =>  -98.53506
            )

    )

this is code
foreach ($usersInfo as $key=> $users)
{
      $ridefrom=$users['ride_from'];
      $rideto=$users['ride_to'];//this is from lat long
      $tempLatLong = explode(',',$users['ride_from']);
       $tempLatLong1 = explode(',',$users['ride_to']);
      $key = array('lat','long');
      $to = array_combine($key,$tempLatLong);
      $from = array_combine($key,$tempLatLong1);
      $array1=array_push($finalDest,$to);
      $array2=array_push($finalDest,$from);
echo $km = distanceCalculation($array1['lat'], $array1['long'],$array2['lat'],$array2['long']);
print_r($finalDest); // displays all array
}

Can I manage this out like $Point1 and $Point2
Thanks

A: Your code already has required arrays, try to print your $to and $from array, those should be same as $point1 and $point2. No need to push them in $finalDest
Your loop will look like this
    foreach ($usersInfo as $index=> $users){
                      $km= 0;
                      $ridefrom=$users['ride_from'];
                      $rideto=$users['ride_to'];//this is from lat long
                      $tempLatLong = explode(',',$users['ride_from']);
                      $tempLatLong1 = explode(',',$users['ride_to']);
                      $key = array('lat','long');
                      $to = array_combine($key,$tempLatLong);
                      $from = array_combine($key,$tempLatLong1);
                     $km=distanceCalculation($from['lat'],$from['long'],$to['lat'],$to['long']);
                      $usersInfo[$index]['distance'] = $km;
                 }


text:
Q: Match everything between 2nd last and last backslash character I want to extract a string of a URL that follows the same pattern:
http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47

I would like to extract only "the_string_i_want"

A:

var a="http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47";
var b=a.split("/");
console.log(b[b.length-2]);

A: Split the string on slashes and return the next-to-last segment:
const url = 'http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47';
const segs = url.pathname.split('/');
console.log(segs[segs.length - 2]);

If for some reason you want to use a regexp, create one which starts with a slash, takes other non-slash characters ([^\/]]) up to another slash (and captures them (())), and then more non-slash characters up to the end of the string ($).

var str = 'http://www.website.com/abcd/efg/xyz/the_string_i_want/?Cr=47';

console.log(str.match(/\/([^\/]*)\/[^\/]*$/)[1]);
//                     ^^                         START WITH SLASH
//                       ^^^^^^^^                 CAPTURE THE PART YOU WANT
//                               ^^               ANOTHER SLASH
//                                 ^^^^^^         MORE NON-SLASHES
//                                       ^        END OF STRING

However, whether you use split or regexp, in general parsing URLs is cumbersome and fragile. You should use a regexp parsing library. For instance, such libraries will handle issues such as / vs. \ as a path separator, and/or normalize the URL for trailing slashes.

A: Try this Regex
http(?:s)?\:\/\/www\.\w+\.[\w]{2,}\/(?:(\w+)\/)+(?:\?\w+\=\w+)?

https://regex101.com/r/MtEwQ7/2


text:
Q: How to create multiple falling down objects by using threads in java? **   Here i created only one moving object ,i want to create more objects which falls down and has random X coordinate .i know i should implement runnable and i should create squres then store them in a collection but its really hard for me to merge everything.i also might have done some mistakes btw . Could you help me some ?  **
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class Project3 extends JFrame {
    public Project3(){
        super("Game");
        setSize(600,600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Squares{
        public int x;
        public int y;

        public Squares(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

    class Game extends JPanel implements ActionListener {
        private int score;
        private java.util.List<Squares> shapeList=new ArrayList<>();
        private boolean play ;
        private int X=50;
        private int Y=0;
        Timer timer=new Timer(10,this);

        public Game(int w , int h){
            Dimension d = new Dimension(w, h);
            setBackground(Color.BLUE);

        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.fillRect(X,Y,60,60);
            timer.start();

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Y=Y+5;
            repaint();
            if(Y==600){
                Random random=new Random();
                Y=0;
                X=random.nextInt(600-60);
            }
        }
    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class Project3 extends JFrame {
    public Project3() {
        super("Game");
        setSize(600, 600);
        add(new Game(600,600));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Project3());
    }

    class Square {
        public int squareX;
        public int squareY;
        int squareW = 25;
        int squareH = 25;

        public Square(int X, int Y) {
            this.squareX = X;
            this.squareY = Y;
        }

        public int getSquareX() {
            return squareX;
        }

        public void setSquareX(int X) {
            this.squareX = X;
        }

        public int getSquareY() {
            return squareY;
        }

        public void setSquareY(int Y) {
            this.squareY = Y;
        }

    }

    class Game extends JPanel implements ActionListener ,Runnable,MouseListener {
        public int score;
        private java.util.List<Square> shapeList = new ArrayList<>();
        Timer timer = new Timer(10, this);
        private boolean play= true;

        public Game(int w, int h) {
            Dimension d = new Dimension(600, 600);
            setBackground(Color.BLUE);
            add(new Label("SCORE...."),BorderLayout.PAGE_END);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            for (Square s:shapeList) {
                g.fillRect(s.squareX,s.squareY,25,25);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            for (Square k : shapeList) {
                k.setSquareY(k.getSquareY() + 5);
                repaint();
            }
        }
        public void stop() {
            play = false;
        }
        @Override
        public void run() {
            while(play){

                int randomNumber=(int)(Math.random()*600)+1;
                shapeList.add(new Square(randomNumber,0));

                for (Square k : shapeList) {
                    if (k.getSquareY()== 600) {
                    stop();
                }try {
                    Thread.sleep(500);
                } catch (InterruptedException ignored) {
                    }
            }
        }
    }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {
            int mouseX=e.getX();
            int mouseY=e.getY();
            for (Square s:shapeList){
                if ((mouseX > s.squareX) && (mouseX < s.squareX + s.squareW) && (mouseY > s.squareY) && (mouseY < s.squareY + s.squareH)) {
                    shapeList.remove(s);
                    score++;
                }
            }

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }
}

A: This code produces three layers of 'snow flakes' which drift towards the bottom of the screen.
Have a look over it, for tips:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;

public class AnimatedSnowFall {

    private JComponent ui = null;

    AnimatedSnowFall() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        ui.add(new SnowFall());
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception useDefault) {
            }
            AnimatedSnowFall o = new AnimatedSnowFall();

            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setResizable(false);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationByPlatform(true);

            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());

            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}

class SnowFall extends JPanel implements ActionListener {

    Dimension prefSize = new Dimension(1600, 900);
    SnowFlake[] farFlakes = new SnowFlake[200];
    SnowFlake[] midFlakes = new SnowFlake[150];
    SnowFlake[] closeFlakes = new SnowFlake[75];
    Color farColor = new Color(100,100,255);
    Color midColor = new Color(150,150,255);
    Color closeColor = new Color(255,255,255);

    SnowFall() {
        setBackground(Color.BLACK);
        for (int ii = 0; ii < farFlakes.length; ii++) {
            farFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 2, 4);
        }
        for (int ii = 0; ii < midFlakes.length; ii++) {
            midFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 3, 6);
        }
        for (int ii = 0; ii < closeFlakes.length; ii++) {
            closeFlakes[ii] = new SnowFlake(prefSize.width, prefSize.height, 4, 8);
        }
        Timer timer = new Timer(50, this);
        timer.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(farColor);
        for (SnowFlake snowFlake : farFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(midColor);
        for (SnowFlake snowFlake : midFlakes) {
            snowFlake.draw(g);
        }

        g.setColor(closeColor);
        for (SnowFlake snowFlake : closeFlakes) {
            snowFlake.draw(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return prefSize;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

class SnowFlake {

    int w;
    int h;
    int x;
    int y;
    int size;
    int speed;
    static Random r = new Random();

    SnowFlake(int w, int h, int size, int speed) {
        this.w = w;
        this.h = h;
        x = r.nextInt(w);
        y = r.nextInt(h);
        this.size = size;
        this.speed = speed;
    }

    public void draw(Graphics g) {
        y += speed;
        if (y > h) {
            x = r.nextInt(w);
            y = 0;
        }
        g.fillOval(x, y, size, size);
    }
}


text:
Q: Docker container has no internet access when docker network bridge is used, unable to create new docker network bridge I deployed Tomcat as docker container using
docker run -d --name tomcatalive -p 9000:8080 -m 1G -e CATALINA_OPTS="$CATALINA_OPTS -Xmx1g" tomcat:9.0.5-jre8

PROBLEM 1: There is no internet access from inside the container.
The internet access on the host is OK. When I use the docker container with network type host, the internet access is OK. The problem is also with other docker images, e.g. tomcat:9.0.44-jdk11-adoptopenjdk-hotspot.
docker exec -it tomcatalive /bin/bash
root@98692dae37ef:/usr/local/tomcat# curl -v https://www.jenkins.io/
* Could not resolve host: www.jenkins.io
* Closing connection 0
curl: (6) Could not resolve host: www.jenkins.io

DNS settings seems to be right, both at host and container I see:
root@earth:/usr/local/tomcat# cat /etc/resolv.conf
nameserver 213.133.98.98
nameserver 213.133.100.100
nameserver 213.133.99.99

PROBLEM 2: new docker network bridge cannot be created.
docker network create -d bridge --subnet 10.0.0.1/24 testbridge
Error response from daemon: Failed to program FILTER chain: iptables failed: iptables --wait -I FORWARD -o br-58b48862a864 -j DOCKER: iptables v1.8.2 (nf_tables):  RULE_INSERT failed (Invalid argument): rule in chain FORWARD
 (exit status 4)

I suspect some problem with iptables. I will appreciate any help how to resolve the problem.
I tried to restart docker with no effect:
sudo systemctl restart docker

Related information:
uname -a
Linux earth 3.16.0-4-amd64 #1 SMP Debian 3.16.51-3 (2017-12-13) x86_64 GNU/Linux

lsb_release -a
Distributor ID: Debian
Description:    Debian GNU/Linux 10 (buster)
Release:        10
Codename:       buster

docker version
Client: Docker Engine - Community
 Version:           20.10.5
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        55c4c88
 Built:             Tue Mar  2 20:17:50 2021
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          19.03.13
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       4484c46d9d
  Built:            Wed Sep 16 17:01:25 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.4.4
  GitCommit:        05f951a3781f4f2c1911b05e61c160e9c30eaa8e
 runc:
  Version:          1.0.0-rc93
  GitCommit:        12644e614e25b05da6fd08a38ffa0cfe1903fdec
 docker-init:
  Version:          0.18.0

network interfaces in docker container
root@98692dae37ef:/usr/local/tomcat# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
316: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever

docker0 network interface of the host
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP gr                                                                             oup default
    link/ether 02:42:55:06:26:a5 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:55ff:fe06:26a5/64 scope link
       valid_lft forever preferred_lft forever

iptables list
sudo iptables -S
-P INPUT ACCEPT
-P FORWARD DROP
-P OUTPUT ACCEPT
-N DOCKER
-N DOCKER-ISOLATION-STAGE-1
-N DOCKER-USER
-N DOCKER-ISOLATION-STAGE-2
-A FORWARD -i br-58b48862a864 ! -o br-58b48862a864 -j ACCEPT
-A FORWARD -i br-58b48862a864 -o br-58b48862a864 -j ACCEPT
-A FORWARD -i br-b1c11aa2dbf5 ! -o br-b1c11aa2dbf5 -j ACCEPT
-A FORWARD -i br-b1c11aa2dbf5 -o br-b1c11aa2dbf5 -j ACCEPT
-A FORWARD -i br-a1c2c4de885a ! -o br-a1c2c4de885a -j ACCEPT
-A FORWARD -i br-a1c2c4de885a -o br-a1c2c4de885a -j ACCEPT
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-ISOLATION-STAGE-1
-A FORWARD -o docker0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -o docker0 -j DOCKER
-A FORWARD -i docker0 ! -o docker0 -j ACCEPT
-A FORWARD -i docker0 -o docker0 -j ACCEPT
-A FORWARD -i br-1c2fa77afc27 ! -o br-1c2fa77afc27 -j ACCEPT
-A FORWARD -i br-1c2fa77afc27 -o br-1c2fa77afc27 -j ACCEPT
-A FORWARD -i br-254792c3bc2d ! -o br-254792c3bc2d -j ACCEPT
-A FORWARD -i br-254792c3bc2d -o br-254792c3bc2d -j ACCEPT
-A FORWARD -i br-07e0ed65bae4 ! -o br-07e0ed65bae4 -j ACCEPT
-A FORWARD -i br-07e0ed65bae4 -o br-07e0ed65bae4 -j ACCEPT
-A FORWARD -i br-fd89fe6e8887 ! -o br-fd89fe6e8887 -j ACCEPT
-A FORWARD -i br-fd89fe6e8887 -o br-fd89fe6e8887 -j ACCEPT
-A FORWARD -i br-104bfec68f50 ! -o br-104bfec68f50 -j ACCEPT
-A FORWARD -i br-104bfec68f50 -o br-104bfec68f50 -j ACCEPT
-A FORWARD -i br-a40e22d1ac6f ! -o br-a40e22d1ac6f -j ACCEPT
-A FORWARD -i br-a40e22d1ac6f -o br-a40e22d1ac6f -j ACCEPT
-A FORWARD -i br-6626dff882c8 ! -o br-6626dff882c8 -j ACCEPT
-A FORWARD -i br-6626dff882c8 -o br-6626dff882c8 -j ACCEPT
-A FORWARD -i br-5e05d9b7b4bb ! -o br-5e05d9b7b4bb -j ACCEPT
-A FORWARD -i br-5e05d9b7b4bb -o br-5e05d9b7b4bb -j ACCEPT
-A FORWARD -i br-994968cc70f2 ! -o br-994968cc70f2 -j ACCEPT
-A FORWARD -i br-994968cc70f2 -o br-994968cc70f2 -j ACCEPT
-A FORWARD -i br-a27382ef713c ! -o br-a27382ef713c -j ACCEPT
-A FORWARD -i br-a27382ef713c -o br-a27382ef713c -j ACCEPT
-A FORWARD -i br-9057932215bd ! -o br-9057932215bd -j ACCEPT
-A FORWARD -i br-9057932215bd -o br-9057932215bd -j ACCEPT
-A FORWARD -i br-23def51354ff ! -o br-23def51354ff -j ACCEPT
-A FORWARD -i br-23def51354ff -o br-23def51354ff -j ACCEPT
-A FORWARD -i br-bf355b0f48b9 ! -o br-bf355b0f48b9 -j ACCEPT
-A FORWARD -i br-bf355b0f48b9 -o br-bf355b0f48b9 -j ACCEPT
-A FORWARD -i br-d7dcd6e73c07 ! -o br-d7dcd6e73c07 -j ACCEPT
-A FORWARD -i br-d7dcd6e73c07 -o br-d7dcd6e73c07 -j ACCEPT
-A FORWARD -i br-ea1e61ddb2d8 ! -o br-ea1e61ddb2d8 -j ACCEPT
-A FORWARD -i br-ea1e61ddb2d8 -o br-ea1e61ddb2d8 -j ACCEPT
-A FORWARD -i br-b84535a5f723 ! -o br-b84535a5f723 -j ACCEPT
-A FORWARD -i br-b84535a5f723 -o br-b84535a5f723 -j ACCEPT
-A DOCKER -d 172.17.0.2/32 ! -i docker0 -o docker0 -p tcp -m tcp --dport 8080 -j ACCEPT
-A DOCKER-ISOLATION-STAGE-1 -i docker0 ! -o docker0 -j DOCKER-ISOLATION-STAGE-2
-A DOCKER-ISOLATION-STAGE-1 -j RETURN
-A DOCKER-USER -j RETURN
-A DOCKER-ISOLATION-STAGE-2 -o docker0 -j DROP
-A DOCKER-ISOLATION-STAGE-2 -j RETURN

iptables legacy list
sudo iptables-legacy -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

saved iptables list
cat /etc/iptables/rules.v4
# Generated by iptables-save v1.6.0 on Thu Apr 16 00:40:29 2020
*filter
:INPUT ACCEPT [1962:615653]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [2075:623476]
COMMIT
# Completed on Thu Apr 16 00:40:29 2020
# Generated by iptables-save v1.6.0 on Thu Apr 16 00:40:29 2020
*nat
:PREROUTING ACCEPT [65:3673]
:INPUT ACCEPT [65:3673]
:OUTPUT ACCEPT [64:3840]
:POSTROUTING ACCEPT [64:3840]
COMMIT
# Completed on Thu Apr 16 00:40:29 2020

Probably related problems with netfilter-persistent (when installing bridge-utils)
Setting up netfilter-persistent (1.0.11+deb10u1) ...
Job for netfilter-persistent.service failed because the control process exited with error code.
See "systemctl status netfilter-persistent.service" and "journalctl -xe" for details.
invoke-rc.d: initscript netfilter-persistent, action "restart" failed.
 - netfilter persistent configuration
   Loaded: loaded (/lib/systemd/system/netfilter-persistent.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Thu 2021-04-08 15:20:15 CEST; 54ms ago
  Process: 26125 ExecStart=/usr/sbin/netfilter-persistent start (code=exited, status=1/FAILURE)
 Main PID: 26125 (code=exited, status=1/FAILURE)

Apr 08 15:20:15 earth netfilter-persistent[26125]: iptables-restore v1.8.2 (nf_tables):
Apr 08 15:20:15 earth netfilter-persistent[26125]: line 2: TABLE_FLUSH failed (Device or resource busy): table filter
Apr 08 15:20:15 earth netfilter-persistent[26125]: run-parts: /usr/share/netfilter-persistent/plugins.d/15-ip4tables exited with return code 4
Apr 08 15:20:15 earth netfilter-persistent[26125]: run-parts: executing /usr/share/netfilter-persistent/plugins.d/25-ip6tables start
Apr 08 15:20:15 earth netfilter-persistent[26125]: ip6tables-restore v1.8.2 (nf_tables):
Apr 08 15:20:15 earth netfilter-persistent[26125]: line 2: TABLE_FLUSH failed (Device or resource busy): table filter
Apr 08 15:20:15 earth netfilter-persistent[26125]: run-parts: /usr/share/netfilter-persistent/plugins.d/25-ip6tables exited with return code 4
Apr 08 15:20:15 earth systemd[1]: netfilter-persistent.service: Main process exited, code=exited, status=1/FAILURE
Apr 08 15:20:15 earth systemd[1]: netfilter-persistent.service: Failed with result 'exit-code'.
Apr 08 15:20:15 earth systemd[1]: Failed to start netfilter persistent configuration.
dpkg: error processing package netfilter-persistent (--configure):
 installed netfilter-persistent package post-installation script subprocess returned error exit status 1
dpkg: dependency problems prevent configuration of iptables-persistent:
 iptables-persistent depends on netfilter-persistent (= 1.0.11+deb10u1); however:
  Package netfilter-persistent is not configured yet.

dpkg: error processing package iptables-persistent (--configure):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.8.5-2) ...
Errors were encountered while processing:
 netfilter-persistent
 iptables-persistent
Error: Timeout was reached
E: Sub-process /usr/bin/dpkg returned an error code (1)


text:
Q: While initializing RestHighLevel client do we always need to use new RestHighLevel client and new host? RestHighLevelClient client =
new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
My question is do we always need to use new HttpHost ? Is there a way where we can maintain a pool of connections ?
We are having GET and POST apis and client.search() is always called when  there is a request triggered from front end.  So everytime a new request is triggered a new connection is created.  Is there a better approach of handling it. ?

A: You don't need to create multiple RestHighLevelClient in your application as mentioned in the official doc JHLRC is a thread safe client and typically instantiated by the application at startup and can be used by all the requests in your application.
from the same doc

The RestHighLevelClient is thread-safe. It is typically instantiated
by the application at startup time or when the first request is
executed.

Internally JHLRC maintains the pool of connection also does the load-balancing between Elasticsearch nodes, so you don't have to worry about these internals.


text:
Q: Change y-axis value in R GAM plot from smoothed to actual response variable I know similar questions have been asked before, but I've looked through them all and I'm still confused, in part because the other examples seem to be more complicated, so thought I'd throw mine up. I made a very simple GAM and plotted it, but the y axis values are the smoothed values. I'd like to make the y axis have the original units so it's easier to understand.
This is a growth curve, so I'm looking at weight by age separated by sex, with individual ID as a random effect since there are some repeated measures.
The plot gives me two plots, one for males and one for females, however I'd love the y axis to be in kilograms like the original dataset is, to better understand and compare the patterns.
gammWeight <- gamm(data = Data, Weight ~ s(Age, by = Sex),
                   random = list(IndivID=~1))
plot(gammWeight$gam)

I know this is likely a simple fix, but I haven't had much luck looking and this is my first time doing GAMs so figured I'd ask the experts.
ETA: I got it! I just added
shift = coef(gammWeight$gam)[1] in the plot, so now it's:
plot(gammWeight$gam), shift = coef(gammWeight$gam)[1])
I figured I'd keep this up in case anyone is searching and has the same question! I got the answer from Noam Ross's github tutorial.

A: The general solution is to use the predict() for a set of evenly spaced values of Age, repeated for each level of Sex.
But to just get a plot, you could do
plot(gammWeight$gam, shift = coef(gammWeight$gam)[1])

That will only show estimates for the first level of Sex, so the predict() approach is much better as you get actual estimates for all levels of that variable if you create the input data you pass to newdata correctly.
By the way, your model is missing the group means. You want Weight ~ Sex + s(Age, by = Sex)
To use predict() one first needs to create the new data at which the model will be evaluated, then we predict on the link scale, form the required credible interval, then transform to the response scale with the inverse of the link function used in the model. With a family = gaussian() model we can skip the last step as the link in such models is the identity function.
Hence (pseudo-ish code - not tested as there's no reproducible example here):
## new data - sequence of 200 values over range of Age
##          - all levels of Sex
##          - choose a dummy value of the subject
## expand.grid provides all combinations so the Age sequence is repeated for
## each level of Sex
newd <- with(Data, expand.grid(Age = seq(min(Age), max(Age), length = 200),
                               Sex = factor(levels(Sex), levels = levels(Sex)),
                               IndivID = IndivID[1]))

## predict
p <- predict(gammWeight$gam, newdata = newd, se.fit = TRUE)
p <- as.data.frame(p)
pred <- cbind(newd, p)
pred <- transform(pred, lower = fit - (1.96 * se.fit),
                        upper = fit + (1.96 * se.fit))

Now you can plot fit against Age, colouring by Sex say, to get actual model predicted values of the expected weight as a function of Age for each level of Sex. The plot() + shift approach is only adding the constant for the reference level of Sex to each smooth drawn. In other words, it's not showing the differences between sexes in their respective mean weights.
The above assumes you are using the corrected model Weight ~ Sex + s(Age, by = Sex); your model as you have it now is likely wrong because the smooth for each sex is trying to capture both the nonlinear way in which weight varies with age but also to fit the mean weight for that sex.


text:
Q: File size obtained from Script is not the same as "Get Info" in Finder Edit: I found more context on this problem and asked another question Calculate size of iOS framework using Swift script
I am creating a Swift script to calculate the size of a bunch of frameworks in my app. It seems to work, but the sizes don't add up.
In finder on a specific framework, Get Info shows 6,801 KB
In my script, I'm using this code to get the file sizes (with different keys):
  var bool: ObjCBool = false
  if FileManager.default.fileExists(atPath: documentsDirectoryURL.path, isDirectory: &bool), bool.boolValue {
    var folderSize = 0
    FileManager.default.enumerator(at: documentsDirectoryURL, includingPropertiesForKeys: [.<key_here>], options: [])?.forEach {
      folderSize += (try? ($0 as? URL)?.resourceValues(forKeys: [.<key_here>]))??.<key_here> ?? 0
    }

    return Int64(folderSize)
  }

I get 4,133 KB with fileAllocatedSizeKey & totalFileAllocatedSizeKey
I get 4,126 KB with fileSizeKey & totalFileSizeKey
According to the docs, the difference between these 4 keys has to do with metadata and the size vs allocated size. If I'm getting allocated size, why is there still 2-3 MB missing between these sizes?
PS: In this example the Finder version was bigger, but in many others the size calculated in the script is larger than the size from Finder.
I don't know what to trust!


text:
Q: Translating a description and a button inside a plugin I have a plugin that have a text and a button. The website have four languages and I need to translate the button text and also the description.
For translation, Polylang is being used.
Inside the plugin I can't access the Polylang config.
How should I do that?
Thanks!

A: After some research I found a solution.
I needed to prepare my plugin to receive the translation and in the end, actually was pretty simple.
This article cover everything that I needed, using PODEdit to create the PO and MO files for each language that I'm using.
https://premium.wpmudev.org/blog/how-to-translate-a-wordpress-plugin/
Since I was a layman in the subject, took longer to understand and figure out how to search about it.


text:
Q: D3 - position tooltip I have a plunker here - https://plnkr.co/edit/iOGJUosvruW9KV1FF9lp?p=preview
I have a tooltip that shows when you hover over a bar.
I'm trying to position it in the center of the bar.
How can I position the tooltip so it's in the center of the bar
d3.selectAll('.bar').on("mouseover", function(d){
      let xPos = d3.select(this).attr("x")
      let width = d3.select(this).attr("width")/2
      let tipPos = +xPos+width
      let html = d.day
      console.log('tipPos '+tipPos)
      d3.select('.chart-tooltip').style("display", null)

      d3.select('.chart-tooltip')
      .style("left", tipPos + "px")
      .style("top",  30 + "px")
        .html(html)

    })

    .on("mouseout", ()=>{
      d3.select('.chart-tooltip').style("display", "none")
    })

A: You could select the y and height attr and set it like this
d3.selectAll('.bar').on("mouseover", function(d){
  let xPos = d3.select(this).attr("x")
  let width = d3.select(this).attr("width")/2
  let thisHeight = Number(d3.select(this).attr("height")) / 2
  let thisY = Number(d3.select(this).attr("y"))
  let tipPos = +xPos+width
  let html = d.day

  console.log(thisHeight, thisY)
  d3.select('.chart-tooltip').style("display", null)

  d3.select('.chart-tooltip')
  .style("left", tipPos + "px")
  .style("top",  margin.top + thisY + thisHeight + "px") // <-- Here
    .html(html)

})

And the label will be appended to the middle, here's a fork
Plunker


text:
Q: get multi selection value from lookup field using java script I nee d get mutiple value from a lookup field and i need to validate it,if i get more than one value i need to give a message and if get one value i need to give another message.i have try something but it not work.

function getbankdetails()
{
  debugger;
  var arr = $('#R3413775').val();

  if(arr[0]!="" && arr[1] !="")
  {
    alert("first"+arr[0]+" "+arr[1]);
  }
  else
  {
    alert("sasa");
  }

}

A: This may work (Javascript)
function getbankdetails()
{
  debugger;
  var arr = Array.from(document.getElementById("R3413775").selectedOptions).map((ele) => ele.value)
  if(arr[0] && arr[1] && arr.length == 2)
  {
     alert("first"+arr[0]+" "+arr[1]);
  }
  else
  {
     alert("sasa");
  }
}

A: You can simply get the elements as the array and either console log the "sasa" string or the list of selected items as a string (by concatenating the array with commas.

$('#R3413775').change(function(){
  getbankdetails();
})

function getbankdetails() {
  var arr = $('#R3413775').val();
  arr.length == 1
   ? console.log("sasa")
   : console.log(arr.join(', '))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="R3413775" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel" >Opel</option>
  <option value="audi">Audi</option>
</select>


text:
Q: ASP.NET Core: Correct pattern to pass DbContext to separate class libraries? This is really a question about what would be a recommended pattern...
I use ASP.NET Core 2.0 and use dependency injection to allow my controllers and other classes to have access to a IMyDatabaseRepositor, via class constructors.
I also have several other projects in separate assemblies.  I was thinking of allowing these other projects do some repository work as well. We're really talking about providing access to an existing DbContext.
Should I somehow pass the IMyDatabaseRepository instance to methods in the other project classes, or should those classes simply instantiate their own IMyDatabaseRepository (and do all their own "Startup" and connection string stuff for database and DI)?
I'm not sure if the other project classes can use the IServicesCollection somehow as well in order to get DI instances from my main ASP.NET Core web app.
Any thoughts?

A: Libraries should not compose object graphs, only the startup project should.
This means that in the library you simply use Constructor Injection, while in your Startup class you register all components from all libraries.


text:
Q: If I want to learn how to administrate a web server which option will be easier? Which option will be easier to administrate Linux server or Windows server (for web platform)?
Also which one will cost me more if I choose managed hosting instead of learning how to manage it myself?

A: The easiest one to administer is whichever one you're most familiar with.  If you have no clue about either, then you should use whichever one your mentor is most familiar with.  If you have no mentor... flip a coin maybe?
Practically speaking, you should run whichever OS your application will work best on.  If you don't have an application, you don't need a server yet.
All things being equal (which they never are), Windows will be a more expensive option for managed hosting or doing it yourself, because it has licence fees which Linux doesn't.  In practice, the costs will vary far more based on the quality of the provider and their actual level of service than which operating system you choose.


text:
Q: How to handle responses sent from PHP differently in AJAX I am trying to figure out that how can I handle different responses sent from PHP to AJAX differently (I am using toastr for nice message display on front end). Say someone tried to insert some value into the database and the value got inserted successfully, then i sent I message from PHP by
echo "Data inserted";

and this gets caught by ajax response and gets handled by
success: function(response) {
 toastr.success(response);
}

But I want that, when PHP sends a message something like
echo "Unable to insert data";

My AJAX handles it as an error and I want to use toastr.danger() instead of toastr.success().
How can I handle this situation ?

A: In PHP, you can use the http_response_code() function to send the 400 HTTP status code:
http_response_code(400);
echo "Unable to insert data";

In jQuery, use the error callback to handle the 400 response:
error: function(response) {
  toastr.danger(response);
}

A: As Jon Stirling said in comment, check HTTP status code (200: OK, 404: Not found, 500: Server error...), statusCode in $.ajax options.
Or use error in $.ajax options (opposed to success options).
Or (but not the best really), check for a word in your response with String.indexOf('yourWord')

A: Try to send this in php
header("HTTP/1.0 403 Forbidden");
exit 'Bad user name / password';

header('HTTP/1.1 500 Internal Server Error');
exit("Something went wrong when we tried to save your comment. Please try again later. Sorry for any inconvenience");

header('HTTP/1.1 400 Bad Request');
exit("This is a message about your invalid fields. Please correct before resubmitting.");


text:
Q: Unittest tearDown() method depends on finished test I write Selenium tests, and have a problem. Before each test I upload different files for every test, and after test is done, I want to remove these files from application even if test failed. There are two methods setUp and tearDown. They are called before and after every test, but how can I define which test was finished in the tearDown method? It is important for me, because after each test I want to remove different files from application, depending on the finished test.
I want something like:
def tearDown(self):
    if test1_is_finished():
       remove_test1_files
    if test2_is_finished():
       remove_test2_files
    # and so on

I am new to Python and Selenium tests, and maybe a better approach exists to do some job after after the test was finished, even if it failed.

A: In the setUp method (to be run before every test), create a list, to_be_removed:
def setUp(self):
    self.to_be_removed = []

In each unit test, append the filenames to to_be_removed:
def test1(self):
    ...
    self.to_be_removed.append(filename)

Then, in tearDown, remove all files listed in to_be_removed:
def tearDown(self):
    for filename in self.to_be_removed:
        os.unlink(filename)

This way, you can handle all tearDowns the same way.


text:
Q: CAF: at least one type has no ID - Compiles on Linux but not Windows I have a proof of concept example that uses the C++ actor framework and Cmake, the issue is that it works fine on Linux but runs into what looks to be a CAF issue on Windows. The provided CAF examples compile fine on both platforms but I cannot understand why my proof of concept example (Duck Party) errors out. Unfortunately you need quite a bit of code to repoduce, here is the repo:
https://github.com/dylan-baros/duck_party
The error that I see on Windows is:

Severity  Code    Description Project File    Line    Suppression State
Error C2338   static_assert failed: 'at least one type has no ID, did
you forgot to announce it via
CAF_ADD_TYPE_ID?' DuckParty   C:\Users\dbaros\Documents\Repos\duck_party\build_deps\caf-src\libcaf_core\caf\mixin\sender.hpp 73

To Reproduce
Using Visual Studio 2022 Community Edition (Visual Studio 17 2022)

*

*Clone the repo

*Navigate to the root directory

*mkdir build

*cd build

*cmake ..

*cmake --build . (Or navigate to the solution using Visual Studio and build)

I have also included a provided CAF example (helloworld) in the Example folder that builds fine using cmake.
What I have Tried
I thought perhaps it was CMake at first but I think I have ruled that out since the helloworld example builds fine using the compiled caf libaries and cmake. I tried adding CAF_ADD_TYPE_ID for the types that are defined in CustomMessages.h as atoms but I get an error that they have already been defined.

A: In the line that triggers this compiler error, you are trying to send a std::chrono::system_clock::time_point. This is what CAF is complaining about, because this type has no type ID assigned. Neither by CAF per default nor in your application via CAF_ADD_TYPE_ID.
I cannot tell you why this is working on Linux for you, maybe GCC's or Clang's definition of the system clock type accidentally matches caf::timestamp on Linux.
In any case, caf::timestamp is the portable way to send timestamps around in CAF and this type is announced by default (i.e., has a type ID).
I got your example compiling using these changes:
diff --git a/source/DuckParty/CMakeLists.txt b/source/DuckParty/CMakeLists.txt
index fdf749b..6cdb857 100644
--- a/source/DuckParty/CMakeLists.txt
+++ b/source/DuckParty/CMakeLists.txt
@@ -16,7 +16,7 @@ target_include_directories(DuckParty
 )

 target_link_libraries(DuckParty
-    PRIVATE CAF::internal CAF::core duck_classes pthread
+    PRIVATE CAF::internal CAF::core duck_classes
 )

diff --git a/source/DuckParty/DisplayActor.h b/source/DuckParty/DisplayActor.h
index 73a8b77..ae8ad4e 100644
--- a/source/DuckParty/DisplayActor.h
+++ b/source/DuckParty/DisplayActor.h
@@ -9,7 +9,7 @@
 #include "Displayable.h"

 using DisplayActor = caf::typed_actor<
-   caf::result<void>(display_behavior, std::chrono::time_point<std::chrono::system_clock>, std::string)>;
+   caf::result<void>(display_behavior, caf::timestamp, std::string)>;

 class DisplayState {
    public:
@@ -20,8 +20,10 @@ class DisplayState {

        DisplayActor::behavior_type make_behavior() {
            return {
-               [this](display_behavior, std::chrono::time_point<std::chrono::system_clock> quack_time, std::string behavior) {
-                   displayable_->DisplayBehavior(quack_time, behavior);
+               [this](display_behavior, caf::timestamp quack_time, std::string behavior) {
+               using sys_dur_t = std::chrono::system_clock::duration;
+                   auto sys_time = std::chrono::time_point_cast<sys_dur_t>(quack_time);
+                   displayable_->DisplayBehavior(sys_time, behavior);
                }
            };
        }
diff --git a/source/DuckParty/DuckActor.h b/source/DuckParty/DuckActor.h
index eb92d3c..9ddf651 100644
--- a/source/DuckParty/DuckActor.h
+++ b/source/DuckParty/DuckActor.h
@@ -1,6 +1,7 @@
 #pragma once
 #include <chrono>
 #include <caf/typed_event_based_actor.hpp>
+#include <caf/type_id.hpp>
 #include "CustomMessages.h"

 #include "Duck.h"
@@ -27,7 +28,7 @@ class DuckState {
            return {
            [this](do_duck_behavior) {
                self_->delayed_send(self_, std::chrono::milliseconds(milliseconds_), do_duck_behavior_v);
-               std::chrono::time_point<std::chrono::system_clock> quackTime = std::chrono::system_clock::now();
+               auto quackTime = caf::make_timestamp();
                std::string duck_display = duck_->GetFlyBehavior() + " " + duck_->GetNoiseBehavior();
                self_->send(display_actor_, display_behavior_v, quackTime, duck_display);
                }
diff --git a/source/DuckParty/main.cpp b/source/DuckParty/main.cpp
index 1a10d73..3f199c0 100644
--- a/source/DuckParty/main.cpp
+++ b/source/DuckParty/main.cpp
@@ -24,7 +24,7 @@ void caf_main(caf::actor_system& sys) {
    DuckActor duck_actor3 = sys.spawn<DuckImpl>(move(duck3), 1500, display_actor);

    caf::scoped_actor self(sys);
-   self->send(display_actor, display_behavior_v, std::chrono::system_clock::now(), "Let's get this party started!");
+   self->send(display_actor, display_behavior_v, caf::make_timestamp(), "Let's get this party started!");
 }

 CAF_MAIN(caf::id_block::duck_msg_types)

I didn't run any binaries, but at least it compiled for me on Windows 10 with recent Visual Studio (Community Edition).
The static_assert in CAF unfortunately does not produce which of the types fails the check. However, you can use static_assert(caf::has_type_id_v<T>) to check your types one-by-one before calling send to quickly find the offending type.
Hope that helps you to move forward with your project.


text:
Q: Trouble with testing angularjs service with jasmine and multiple dependencies I have a service with quite a few dependencies defined as:
angular.module('serversync.services', ['database', 'date-time-format', 'serversync.config'])

.factory('ServerSync', function($log, $q, $http, _, DatabaseProvider, DateTimeFormatter, ExternalSyncServerConfig) {
    var self = this;

    var self.syncSomething = function() {
       ...
    };
    return self;

});

(DatabaseProvider, DateTimeFormatter, ExternalSyncServerConfig are other custom services in my app).
I have defined a basic test as follows:
describe('ServerSync Tests', function () {

  beforeEach(function() {
    module('database', []);
    module('date-time-format', []);
    module('serversync.config', []);
    module('serversync.services')
  });

  var ServerSyncSvc;
  var log, q, http, underscore;
  var DatabaseProviderSvc, DateTimeFormatterSvc, ExternalSyncServerConfigSvc;

  beforeEach(function() {
    inject(function($log,
                    $q,
                    $httpBackend,
                    DatabaseProvider,
                    DateTimeFormatter,
                    ExternalSyncServerConfig,
                    ServerSync) {
      ServerSyncSvc = ServerSync;
      log = $log;
      q = $q;
      http = $httpBackend;
      underscore = _;
      DatabaseProviderSvc = DatabaseProvider;
      DateTimeFormatterSvc = DateTimeFormatter;
      ExternalSyncServerConfigSvc = ExternalSyncServerConfig;
    });
  });

  it('should have a syncJourney function defined', function () {
    expect(ServerSyncSvc.syncSomething).toBeDefined();
  });

})
;

I've used this article to try and get up and running but am having no success.
When I run grunt karma I get the error:
PhantomJS 1.9.8 (Mac OS X) Service DTW should have a function to be defined FAILED
    Error: [$injector:modulerr] Failed to instantiate module undefined due to:
    Error: [ng:areq] Argument 'fn' is not a function, got undefined
    http://errors.angularjs.org/1.3.13/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined
        at assertArg (~/myApp/app/bower_components/angular/angular.js:1580)
        at assertArgFn (~/myApp/app/bower_components/angular/angular.js:1591)
        at annotate (~/myApp/app/bower_components/angular/angular.js:3471)
        at ~/myApp/app/bower_components/angular-mocks/angular-mocks.js:2147
        at invoke (~/myApp/app/bower_components/angular/angular.js:4163)
        at ~/myApp/app/bower_components/angular/angular.js:4104
        at forEach (~/myApp/app/bower_components/angular/angular.js:323)
        at loadModules (~/myApp/app/bower_components/angular/angular.js:4123)
        at createInjector (~/myApp/app/bower_components/angular/angular.js:4007)

I know my Jasmine conf is correct as I can run some tests on simple services that don't have any dependencies.
This whole unit testing thing for angular is a bit new to me and I'm having a bit of trouble wrapping my head around the concepts of mocking dependencies so I'm hoping it's something simple but I have no idea where to go next to get this working?

A: In the setup beforeEach - change the modules that are dependencies to angular.module instead of just module.
angular.module('database', []);
angular.module('date-time-format', []);
angular.module('serversync.config', []);
module('serversync.services')

module is used for whichever component you are testing (it is a shortcut to the mocks version angular.mock.module). The dependencies should be registered as regular angular modules.
This will probably fix it enough for your "to be defined" unit test to run. However, once you get to actually exercising the code that uses those dependencies you are going to have to provide mocks for the functions within the dependencies. If you are anything like I was, that will bring a slew of more questions.