text:
Q: attempt to re-open an already-closed object: SQLiteDatabase 1212 in my android app,i m using sqlite database but when using a query to read data from SQLite its giving me error.  i want to put the result in a listview.
this my activity :
public class activ5 extends Activity {
ListView etudiants=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activ5);
    BDD base2 = new BDD(activ5.this);
    base2.open();
    ArrayAdapter<Etudiant> etudiantAdapter = new ArrayAdapter<Etudiant>(this, android.R.layout.simple_list_item_activated_1, base2.getAllEtudiant());
    etudiants.setAdapter(etudiantAdapter);
    base2.close();

and this this the code for my database
    private static final String CREATE_BDD_ETUDIANT = "CREATE TABLE " + TABLE_ETUDIANT + " ("
        + COL_ID_ETUDIANT + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_NOM + " TEXT NOT NULL, "
        + COL_FILIERE + " TEXT NOT NULL, "+ COL_GROUPE +" TEXT NOT NULL);";
private static final String CREATE_BDD_PROF = "CREATE TABLE " + TABLE_PROF + " ("
        + COL_ID_PROF + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_MODULE + " TEXT NOT NULL, "
        + COL_MATIERE +" TEXT NOT NULL);";
private static final String CREATE_BDD_ABSENCE= "CREATE TABLE " + TABLE_ABSENCE + " ("+ COL_MATIERE_ABSENCE +  " TEXT NOT NULL, "  + COL_ABSENCE + " INTEGER, "
        + COL_NOM_ABSENCE + " TEXT  REFERENCES "+TABLE_ETUDIANT+"("+COL_NOM+")); ";
private static final String CREATE_BDD_COMPTE = "CREATE TABLE " + TABLE_COMPTE + " ("+COL_ID_COMPTE+" INTEGER PRIMARY KEY AUTOINCREMENT, "
        +COL_LOGIN+" TEXT NOT NULL,"+COL_PASSWORD+" TEXT NOT NULL,"
        + COL_ID_PROF_COMPTE + " INTEGER REFERENCES "+TABLE_PROF+"("+COL_ID_PROF+"),"
        + COL_ID_ETUDIANT_COMPTE+ " INTEGER REFERENCES "+TABLE_ETUDIANT+"("+COL_ID_ETUDIANT+"));";
private MaBaseDonne(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized MaBaseDonne getInstance(Context context) {

    if (sInstance == null) {
        sInstance = new MaBaseDonne(context.getApplicationContext());
    }
    return sInstance;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_BDD_ETUDIANT);
    db.execSQL(CREATE_BDD_PROF);
    db.execSQL(CREATE_BDD_ABSENCE);
    db.execSQL(CREATE_BDD_COMPTE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE " + TABLE_PROF + ";");
    db.execSQL("DROP TABLE " + TABLE_ETUDIANT + ";");
    db.execSQL("DROP TABLE " + TABLE_ABSENCE+ ";");
    db.execSQL("DROP TABLE " + TABLE_COMPTE+ ";");
    onCreate(db);
}

and this the method where i get the error :
 public List<Etudiant> getAllEtudiant() {
    List<Etudiant> etudiants = new ArrayList<Etudiant>();

    Cursor cursor = bdd.query(maBaseDonne.TABLE_ETUDIANT,null, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Etudiant etudiant = cursorToEtudiant(cursor);
        etudiants.add(etudiant);
        cursor.moveToNext();
    }
    cursor.close();
    return etudiants;
}
public void close() {
    bdd.close();
}

 public Etudiant cursorToEtudiant(Cursor c){

    if (c.getCount() == 0)
        return null;

           c.moveToFirst();

    Etudiant etudiant = new Etudiant();

    etudiant.setId(c.getInt(NUM_COL_ID_ETUDIANT));
    etudiant.setNom(c.getString(NUM_COL_NOM));
    etudiant.setFilierere(c.getString(NUM_COL_FILIERE));
    etudiant.setGroupe(c.getString(NUM_COL_GROUPE));
    c.close();
    return etudiant;

and this is the log file :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radouane.myapplication/com.example.radouane.myapplication.activ5}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM table_etudiant
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5349)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
 Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteQuery: SELECT * FROM table_etudiant
        at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
        at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:58)
        at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:152)
        at android.database.sqlite.SQLiteCursor.onMove(SQLiteCursor.java:124)
        at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:214)
        at android.database.AbstractCursor.moveToNext(AbstractCursor.java:245)
        at com.example.radouane.myapplication.BDD.getAllEtudiant(BDD.java:244)
        at com.example.radouane.myapplication.activ5.onCreate(activ5.java:25)
        at android.app.Activity.performCreate(Activity.java:6020)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284)

and finally the DAO class for all my methode
  public SQLiteDatabase bdd;
public MaBaseDonne maBaseDonne;
String[] allColumns = {maBaseDonne.COL_NOM,maBaseDonne.COL_GROUPE};

public BDD(Context context) {

    maBaseDonne = MaBaseDonne.getInstance(context.getApplicationContext());
}

public void open(){
    bdd = maBaseDonne.getWritableDatabase();
}
public void read()
{
    bdd=maBaseDonne.getReadableDatabase();   }

public SQLiteDatabase getBDD(){
    return bdd;
}

public long insertEtudiant(Etudiant etudiant) {
    ContentValues values = new ContentValues();

    values.put(COL_NOM, etudiant.getNom());
    values.put(COL_FILIERE, etudiant.getFiliere());
    values.put(COL_GROUPE, etudiant.getGroupe());
    return bdd.insert(TABLE_ETUDIANT, null, values);
}
public long insertProf(Prof prof) {
    ContentValues values = new ContentValues();
    values.put(COL_MODULE, prof.getModule());
    values.put(COL_MATIERE, prof.getMatiere());
    return bdd.insert(TABLE_PROF, null, values);
}
public long insertAbsence(Absence absence) {
    ContentValues values = new ContentValues();
    values.put(COL_NOM_ABSENCE, absence.getNom());
    values.put(COL_MATIERE, absence.getMatiere());
    values.put(COL_ABSENCE, absence.getAbsence());
    return bdd.insert(TABLE_ABSENCE, null, values);
}
public long insertCompte(Compte compte) {
    ContentValues values = new ContentValues();
    values.put(COL_LOGIN, compte.getLogin());
    values.put(COL_PASSWORD, compte.getPassword());
    values.put(COL_ID_PROF_COMPTE, compte.getId_prof());
    values.put(COL_ID_ETUDIANT_COMPTE, compte.getId_etudiant());

    return bdd.insert(TABLE_COMPTE, null, values);
}
public int updateEtudiant(int id, Etudiant etudiant) {

    ContentValues values = new ContentValues();
    values.put(COL_ID_ETUDIANT, etudiant.getId());
    values.put(COL_NOM, etudiant.getNom());
    values.put(COL_FILIERE, etudiant.getFiliere());
    values.put(COL_GROUPE, etudiant.getGroupe());
    return bdd.update(TABLE_ETUDIANT, values, COL_ID_ETUDIANT + " = " + id, null);
}
public int updateProf(int id, Prof prof) {

    ContentValues values = new ContentValues();
    values.put(COL_ID_PROF, prof.getId());
    values.put(COL_MODULE, prof.getModule());
    values.put(COL_MATIERE, prof.getMatiere());
    return bdd.update(TABLE_ETUDIANT, values, COL_ID_PROF + " = " + id, null);
}
public int updateAbsence(String nom_eleve, Absence absence) {

    ContentValues values = new ContentValues();
    values.put(COL_NOM_ABSENCE, absence.getNom());
    values.put(COL_MATIERE, absence.getMatiere());
    values.put(COL_ABSENCE, absence.getAbsence());
    return bdd.update(TABLE_ETUDIANT, values, COL_NOM_ABSENCE + " = " + nom_eleve, null);
}
public int updateCompte(String login, Compte compte) {

    ContentValues values = new ContentValues();
    values.put(COL_LOGIN, compte.getLogin());
    values.put(COL_PASSWORD, compte.getPassword());
    values.put(COL_ID_PROF_COMPTE, compte.getId_prof());
    values.put(COL_ID_ETUDIANT_COMPTE, compte.getId_etudiant());
    return bdd.update(TABLE_COMPTE, values, COL_LOGIN + " = " + login, null);
}
  public int removeEtudiant(int id){
    return bdd.delete(TABLE_ETUDIANT, COL_ID_ETUDIANT + " = " + id, null);
}
public int removeProf(int id){
    return bdd.delete(TABLE_PROF, COL_ID_PROF + " = " +id, null);
}
public int removeAbsence(String nom_eleve){
    return bdd.delete(TABLE_ABSENCE, COL_NOM_ABSENCE + " = " +nom_eleve, null);
}
public int removeCompte(String login){
    return bdd.delete(TABLE_COMPTE, COL_LOGIN + " = " + login, null);
}

public Etudiant getEtudiant(int id){
    Cursor c = bdd.query(TABLE_ETUDIANT, new String[] {COL_ID_ETUDIANT, COL_NOM, COL_FILIERE,COL_GROUPE}, COL_ID_ETUDIANT + " LIKE \"" + id +"\"", null, null, null, null);
    return cursorToEtudiant(c);
}
public Prof getProf(int id){
    Cursor c = bdd.query(TABLE_PROF, new String[] {COL_ID_PROF, COL_MODULE, COL_MATIERE}, COL_ID_PROF + " LIKE \"" + id +"\"", null, null, null, null);
    return cursorToProf(c);
}
public Absence getAbsence(String nom_eleve){
    Cursor c = bdd.query(TABLE_ABSENCE, new String[] {COL_NOM_ABSENCE, COL_MATIERE_ABSENCE, COL_ABSENCE}, COL_NOM_ABSENCE + " LIKE \"" + nom_eleve +"\"", null, null, null, null);
    return cursorToAbsence(c);
}
public Compte getCompte(String login,String password){
    Cursor c = bdd.query(TABLE_COMPTE, new String[] {COL_LOGIN, COL_PASSWORD, COL_ID_PROF_COMPTE,COL_ID_ETUDIANT_COMPTE},COL_LOGIN + " LIKE \"" + login +"\""+" and "+COL_LOGIN + " LIKE \"" + login +"\"" , null, null, null, null);
    return cursorToCompte(c);
}

public Etudiant cursorToEtudiant(Cursor c){

    if (c.getCount() == 0)
        return null;

           c.moveToFirst();

    Etudiant etudiant = new Etudiant();

    etudiant.setId(c.getInt(NUM_COL_ID_ETUDIANT));
    etudiant.setNom(c.getString(NUM_COL_NOM));
    etudiant.setFilierere(c.getString(NUM_COL_FILIERE));
    etudiant.setGroupe(c.getString(NUM_COL_GROUPE));
    c.close();
    return etudiant;
}
private Prof cursorToProf(Cursor c) {

    if (c.getCount() == 0)
        return null;

    c.moveToFirst();

    Prof prof = new Prof();

    prof.setId(c.getInt(NUM_COL_ID_ETUDIANT));
    prof.setModule(c.getString(NUM_COL_MODULE));
    prof.setMatiere(c.getString(NUM_COL_MATIERE));
    c.close();
    return prof;
}
private Absence cursorToAbsence(Cursor c) {

    if (c.getCount() == 0)
        return null;

    c.moveToFirst();

    Absence absence = new Absence();

    absence.setNom(c.getString(NUM_COL_NOM_ABSENCE));
    absence.setMatiere(c.getString(NUM_COL_MATIERE));
    absence.setAbsence(c.getInt(NUM_COL_ABSENCE));
    c.close();
    return absence;
}

private Compte cursorToCompte(Cursor c) {

    if (c.getCount() == 0)
        return null;

    c.moveToFirst();

    Compte compte = new Compte();

    compte.setLogin(c.getString(NUM_COL_LOGIN));
    compte.setPassword(c.getString(NUM_COL_PASSWORD));
    compte.setId_prof(c.getInt(NUM_COL_ID_PROF_COMPTE));
    compte.setId_etudiant(c.getInt(NUM_COL_ID_ETUDIANT_COMPTE));
    return compte;
}
public List<Etudiant> getAllEtudiant() {
    List<Etudiant> etudiants = new ArrayList<Etudiant>();

    Cursor cursor = bdd.query(maBaseDonne.TABLE_ETUDIANT,null, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Etudiant etudiant = cursorToEtudiant(cursor);
        etudiants.add(etudiant);
        cursor.moveToNext();
    }
    cursor.close();
    return etudiants;
}
public void close() {
    bdd.close();
}

}
i've beeen stuck for all day any help is welcome , thank U``

A: In getAllEtudiant() you are calling to cursorToEtudiant(cursor); and in this method you are closing the cursor c.close();, so the next time in the loop the cursor is closed, just delete the c.close() because you close the cursor after the while loop in getAllEtudiant()

A:  public List<Etudiant> getAllEtudiant() {
    List<Etudiant> etudiants = new ArrayList<Etudiant>();

    Cursor cursor = bdd.query(maBaseDonne.TABLE_ETUDIANT,null, null, null, null, null, null);

    if(cursor.getCount()!=0 && cursor.moveToFirst()){
       do{
        Etudiant etudiant = cursorToEtudiant(cursor);
        etudiants.add(etudiant);
       }while(cursor.moveToNext());
    cursor.close();
    return etudiants;
}
public void close() {
    bdd.close();
}

 public Etudiant cursorToEtudiant(Cursor c){

    Etudiant etudiant = new Etudiant();

    etudiant.setId(c.getInt(NUM_COL_ID_ETUDIANT));
    etudiant.setNom(c.getString(NUM_COL_NOM));
    etudiant.setFilierere(c.getString(NUM_COL_FILIERE));
    etudiant.setGroupe(c.getString(NUM_COL_GROUPE));
    c.close();
    return etudiant;


text:
Q: ImageView не отображается в Drawer header В не отображается значок аккаунта в drawer header - все остальные элементы отрисовываются. Всё инициализируется. Никак не могу понять, в чём проблема. Заранее спасибо за ответы.
drawer_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="150sp"
        android:background="#f4f6f8">

    <ImageView
            android:layout_width="101sp"
            android:layout_height="90sp"
            tools:srcCompat="@drawable/avatar"
            android:id="@+id/avatar"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.051"
            android:layout_marginTop="16sp"
            android:visibility="visible" />

    <TextView
            android:layout_width="300sp"
            android:layout_height="26sp"
            android:id="@+id/emailview"
            app:layout_constraintTop_toBottomOf="@+id/avatar"
            android:layout_marginTop="8sp"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="16sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>

A: Попробуйте заменить tools:srcCompat="@drawable/avatar" у компонента ImageView на android:src="@drawable/avatar".
В свойствах android:layout_width, android:layout_height, android:layout_marginTop, android:layout_marginStart лучше использовать dp вместо sp.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cx_freeze no based named 'Win32GUI' error when creating a EXE I want to convert a application into an executable file and have use cx_freeze for that purpose.
But i got this Error-Message:
......executable.py, line 86, in base
raise ConfigError(f"no base named {name!r}")
cx_Freeze.exception.ConfigError: no base named 'Win32GUI'

Versions: Win 10 Home (x64); Python 3.9.6; Cx_Freeze 6.8; PyQt - 5.15.4;
It's strange because some time ago this code worked without problem?!
import sys
from cx_Freeze import setup, Executable

try:
    from cx_Freeze.hooks import get_qt_plugins_paths
except ImportError:
    include_files = []
else:
    # Inclusion of extra plugins (new in cx_Freeze 6.8b2)
    # cx_Freeze imports automatically the following plugins depending of the
    # use of some modules:
    # imageformats - QtGui
    # platforms - QtGui
    # mediaservice - QtMultimedia
    # printsupport - QtPrintSupport
    #
    # So, "platforms" is used here for demonstration purposes.
    include_files = get_qt_plugins_paths("PyQt5", "platforms")

# base="Win32GUI" should be used only for Windows GUI app
base = None
if sys.platform == "win32":
    base = "Win32GUI"

build_exe_options = {
    "excludes": [""],
    "include_files": include_files,
}

bdist_mac_options = {
    "bundle_name": "Test",
}

bdist_dmg_options = {
    "volume_label": "TEST",
}

executables = [Executable("main.py", base=base, target_name="TESTS")]

setup(
    name="simple_PyQt5",
    version="0.3",
    description="Sample cx_Freeze PyQt5 script",
    options={
        "build_exe": build_exe_options,
        "bdist_mac": bdist_mac_options,
        "bdist_dmg": bdist_dmg_options,
    },
    executables=executables,
)

A: found the solution.
Updated all requirements (pip´s) and then it worked. Dont know why this happend but ok


text:
Q: Fit model on a subset of columns in dataframe in R I'm trying to use lm() and matchit() on a subset of covariates. I have generated an arbitrary number of columns with prefix "covar", i.e. "covar.1", "covar.2", etc. I'd like to do something like
lm(group ~ covars, data=df)
where covars is a vector of strings c("covar.1", "covar.2", ...).
I tried several things like
  cols <- colnames(df)
  covars <- cols[grep("covar", colnames(df))]
  m.out <- matchit(group ~ covars, data=df, method="nearest", distance="logit", caliper=.20)

but got variable lengths differ (found for 'covars').
Defining a new dataframe only with covars and group can work but that defeats my purpose using matchit because I want the matched data to have other columns, too, not just covars I picked to be the matched on.
This seems to be an easy task but somehow I can't figure out after some googling. Not sure what R formula expects there as subset of columns. Any help is appreciated.

A: You might want to use as.formula.
Try doing this:
Replace group ~ covars
with as.formula(paste('group','~', paste(covars, collapse="+"))))

A: I mentioned this in your other question, but the cobalt package has a function specifically for this, which is f.build(). The first argument to f.build() is a string containing the name of the treatment variable (or left hand side of the formula), and the second argument is a string vector containing the names of the variables to be on the right hand side of the formula (i.e., the covariates). The second argument can also be a data.frame containing the covariates; f.build() simply extracts the names. It then performs the operation described in the chosen answer, bit adds in a few other aspects that make it a little more general and robust to errors.
The cobalt documentation has a section on f.build() and uses its use with glm() and matchit() as examples.
After running matchit(), you can assess balance on the covariates using the bal.tab() function in cobalt, which is compatible with MatchIt:
bal.tab(m.out, un = TRUE)

The documentation for cobalt explains its use with MatchIt in detail.


text:
Q: How can I do a WpGraphQL query with a where clause? This works fine
  query QryTopics {
    topics {
      nodes {
          name
          topicId
          count
      }
    }
  }

But I want a filtered result. I'm new to graphql but I see a param on this collection called 'where', after 'first', 'last', 'after' etc... How can I use that? Its type is 'RootTopicsTermArgs' which is likely something autogenerated from my schema. It has fields, one of which is 'childless' of Boolean. What I'm trying to do, is return only topics (a custom taxonomy in Wordpress) which have posts tagged with them. Basically it prevents me from doing this on the client.
data.data.topics.nodes.filter(n => n.count !== null)

Can anyone direct me to a good example of using where args with a collection? I have tried every permutation of syntax I could think of. Inlcuding
  topics(where:childless:true)
  topics(where: childless: 'true')
  topics(where: new RootTopicsTermArgs())
  etc...

Obviously those are all wrong.

A: If a custom taxonomy, such as Topics, is registered to "show_in_graphql" and is part of your Schema you can query using arguments like so:
query Topics {
  topics(where: {childless: true}) {
    edges {
      node {
        id
        name
      }
    }
  }
}

Additionally, you could use a static query combined with variables, like so:
query Topics($where:RootTopicsTermArgs!) {
  topics(where:$where) {
    edges {
      node {
        id
        name
      }
    }
  }
}

$variables = {
  "where": {
    "childless": true
  }
};

One thing I would recommend is using a GraphiQL IDE, such as https://github.com/skevy/graphiql-app, which will help with validating your queries by providing hints as you type, and visual indicators of invalid queries.
You can see an example of using arguments to query terms here: https://playground.wpgraphql.com/#/connections-and-arguments


text:
Q: req value is undefinded in node js and pug I am using pug to generate a form as follows:
person.pug
html
head
   title Person
   body
      form(action = "/person", method = "POST")
      div
     label(for = "name") Name:
     input(name = "name")
  br
  div
     label(for = "age") Age:
     input(name = "age")
  br
  div
     label(for = "nationality") Nationality:
     input(name = "nationality")
  br
  button(type = "submit") Create new person

and in server side I am trying to handle the request by a post method: method:
app.post('/person', function(req, res){
var personInfo = req.body; //Get the parsed information
console.log(req.body);
if(req.body == null) {
    res.render('show_message', {
        message: "Sorry, you provided worng info", type: "error"});
} else {
    if(!personInfo.name || !personInfo.age || !personInfo.nationality){
    res.render('show_message', {
        message: "Sorry, you provided worng info", type: "error"});
    } else {
    var newPerson = new Person({
        name: personInfo.name,
        age: personInfo.age,
        nationality: personInfo.nationality
    });

    newPerson.save(function(err, Person){
        if(err)
            res.render('show_message', {message: "Database error", type: "error"});
        else
            res.render('show_message', {
                message: "New person added", type: "success", person: personInfo});
    });
    }
}
 });

When I run the request the req.body is always null (notdefiend).

A: req.body is not filled in by default. As it says in the documentation:

req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

(my emphasis)


text:
Q: VB.Net/C# - Listview Gridlines How can I show only vertical Gridlines in my Listview, without horizontal gridlines?
Like for example in taskmanager?
Is there a way to do this with GDI?
I am not sure how I can realize that, every helpful comment is appreciated :)

A: When you and I create controls we usually overload the onPaint method and do all our drawing there. Most of the default controls that you find in the toolbox however, redraws certain parts at certain messages, which makes it hard to draw over them as you never know when the control will redraw. It is possible to do so however, and the only way to figure out when to draw is by trail and error.
If you're lucky it's enough to redraw at a couple of events, but, for the most part overloading the WndProc method is the way to go.
I'm currently on a windows 8 computer, where the grid lines aren't drawn at all, so it's kinda hard to write a good example of how to remove the horizontal ones, but I'd just paint over them with the background color and then draw the vertical ones afterwards. The code below draws horizontal grid lines:
Public Class MyListView
Inherits ListView

Private Sub DrawLines() Handles Me.MouseUp
    Dim G = CreateGraphics()
    Dim x As Integer

    For i = 0 To Columns.Count - 1
        x += Columns(i).Width
        G.DrawLine(New Pen(Color.FromArgb(230, 230, 230)), x, 0, x, Height)
    Next
End Sub

Protected Overrides Sub WndProc(ByRef m As Message)
    MyBase.WndProc(m) ' To prevent something from drawing you can simply not do this call at a specific message
End Sub

End Class

A list of windows messages
Spy++ can also be helpful to find the right messages


text:
Q: Uploading large file with @azure/storage-blob using blockBlobClient.uploadBrowserData with sas key I'm trying to upload a ~700MB file to the blob storage directly from the front end using the @azure/storage-blob npm package. In order to do this, I'm making a call to our backend to generate an SAS key to authenticate the upload, then using blockBlobClient.uploadBrowserData to do the upload. This is working for smaller files but is failing for the very large file.
I think the issue is that blockBlobClient.uploadBrowserData is breaking up the upload into multiple blocks if the file size is over 250MB, and only the upload of the first block is able to use the sas key provided from the backend, as I eventually get a 403 (This request is not authorized to perform this operation using this permission.) error in the console.
Is there something I can do that will allow me to upload large files using an sas key generated in the backend?
Here is the code im using to retrieve the sas key from the backend and upload the file to blob:
    axios
      .all(
        workflowEndpoints.map((workflowEndpoint) => axios.get(workflowEndpoint))
      )
      .then((responses) => {
        responses.forEach((response, i) => {
          const { data } = response;
          const file = files[i];
          const fileName = fileNames[i];
          const blobServiceClient = new BlobServiceClient(
            `https://<storage_account_name>.blob.core.windows.net?${data.key}`
          );
          const containerClient = blobServiceClient.getContainerClient(
            data.container
          );
          const blockBlobClient = containerClient.getBlockBlobClient(fileName);
          blockBlobClient.uploadBrowserData(file).catch(() => {
            setStatus('Error: Upload failed.');
            setLockUser(false);
            throw new Error('Error: Upload failed.');
          });
        });
        if (gatherUploadFileData) {
          gatherUploadFileData(fileNames, multiple, inputId);
        }
        setStatus('Success: Upload complete!');
        setLockUser(false);
        setFiles([]);
      })
      .catch(() => {
        setStatus('Error: Upload failed.');
        setLockUser(false);
        throw new Error('Error: Upload failed.');
      });
    ```

A: Turns out the permissions that blockBlobClient.uploadBrowserData needs to upload files in blocks is different than the smaller files it uploads in one go. When generating the SAS key, I originally had only the create permission which worked with small files but not with larger files. After adding add and write permissions to the SAS token it worked. It also seems to require the SAS token to be valid during the whole duration of the block upload process, so I also had to extend the expiration time.

A: This is not expected.  I just tried a small code snippet and it works as expected (all operations are using the same SAS key)
const blockBlobClient = containerClient.getBlockBlobClient("block-blob-name");
const content = new Uint8Array(20 * 1024 * 1024);
for (let i = 0; i < content.length; i++) {
    content[i] = Math.floor(Math.random() * 256);
}
const file = new Blob([content]);
file.name = "block-blob-name";
await blockBlobClient.uploadBrowserData(file, {
    maxSingleShotSize: 2 * 1024 * 1024,
});

Do you have any proxy between your machine and Azure Blob endpoint? Sometimes proxy/cache servers can lead to strange behavior.
It may also be worth to log an issue at https://github.com/Azure/azure-sdk-for-js


text:
Q: Spring security: allow a few pages to be displayed in iframe I support a website that uses Spring Security (5.3.3.RELEASE). The site can't be displayed in iframe in other sites because of the following configuration
<security:headers>
  <security:frame-options policy="SAMEORIGIN"/>
</security:headers>

Now I am asked to allow a few pages to be displayed in iframe in ANY other sites (not a specific list of sites). I looked at the Spring documentation, and it appears that I can add a bean in the following way:
<security:headers>
  <security:frame-options policy="SAMEORIGIN" ref="bean_id"/>
</security:headers>

I am not able to find info about what interface or methods the bean (bean_id) must implement or whether it can be used to decide what pages are frameable. Any help or example is really appreciated.

A: The interface is of type AllowFromStrategy. But that interface is deprecated since the ALLOW-FROM is an obsolete directive that no longer works in modern browsers, see here. The alternative is to use CSP: frame-ancestors.
Spring Security has support for the Content-Security-Policy header. You can rely on the DelegatingRequestMatcherHeaderWriter implementation to add the headers only to specific pages, like so:
<http>
    <!-- ... -->

    <headers>
        <header ref="headerWriter"/>
    </headers>
</http>

<beans:bean id="headerWriter"
    class="org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter">
    <beans:constructor-arg>
        <bean class="org.springframework.security.web.util.matcher.AntPathRequestMatcher"
            c:pattern="/page-with-csp"/>
    </beans:constructor-arg>
    <beans:constructor-arg>
        <beans:bean
            class="org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter"/>
    </beans:constructor-arg>
</beans:bean>


text:
Q: Changing the style of the standard android.R.layout options? Is it possible to override the standard layouts that are provided with Android? Is it for example possible to make the text smaller for android.R.layout.simple_list_item_checked? Or would I simply need to make my own layout to do this? Thanks.

A: You have to make your own layout. In order to make a custom layout and use a standard adapter (like ArrayAdapter) you have to specifiy the same id(s) in your custom layout as in the standard layouts. For example the TextView in simple_list_item_checked has the id "@android:id/text1" (http://www.devdaily.com/java/jwarehouse/android-examples/platforms/android-2/data/res/layout/simple_list_item_checked.xml.shtml). In your custom layout you specify that id. Thus you do not have to write a custom adapter. So the best way is just by copying the standard xml layout and change what you wanne change

A: Yes, it is. Here's a similar thing being accomplished (res/values/styles.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="ContactLabelTextView">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:gravity">right</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">@android:color/white</item>
    <item name="android:layout_marginLeft">5dp</item>
    <item name="android:layout_marginRight">5dp</item>
    <item name="android:layout_marginTop">5dp</item>
  </style>
  <style name="questionTableRow">
      <item name="android:layout_width">wrap_content</item>
      <item name="android:layout_height">wrap_content</item>
      <item name="android:layout_margin">5dp</item>
      <item name="android:layout_marginLeft">5dp</item>
      <item name="android:background">@drawable/textview_border</item>
  </style>
</resources>

And then, when you want to apply the style to an element in the layout file that you have created (main.xml, res/layout/your_custom_layout.xml):
<?xml version="1.0" encoding="utf-8"?>
    <TableRow
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/questionTableRow"
        style="@style/questionTableRow"

Obviously you are looking to accomplish this with a textView. I provided an example of my own code where the textView gets a specific style. I actually don't even have that textView style applied, but I pasted in where I applied a style to a tableRow, just so you see how to apply it to an xml element.
Does this do what you need?


text:
Q: Adding a Sidebar Icon to my FinderSync extension I'm developing a FinderSync extension based on the following documentation:
https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/Finder.html
I'm failing to add a sidebar icon.
I've followed the steps: Created the .iconset folder and filled it with the requested PNGs. Added the folder to my info.plist etc.
But I don't see any icon in the sidebar on my monitored folders.
Context menu, toolbar button and badges works fine.
What could I be missing? Is there any limitation that the documentation fails to mention? Anything tricky with step 4?

A: Apparently its indeed extremely important to obey Apple's constraints regarding the icons:
they must be

"monochromatic images that are drawn just using black and
  transparency"

To my surprise, when a designer gave me pngs that complied with the mentioned above, everything worked like a charm.
Please comment if you encounter any other difficulty, as the documentation is very lacking.

A: The documentation mentions several exceptions where your app icon will not replace the folder's icon:

The sidebar icons you provide will replace the default folder icons in the Finder's sidebar for any of the root folders that your extension is monitoring.
This icon does not replace the icon for any folders contained by your monitored folder.
It also does not replace the icon for any system folders that you may be monitoring (for example, Documents, Desktop, Applications, and Downloads).
https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/Finder.html


text:
Q: ERROR AND/OR CORRUPTED GEM I'm receiving an error when using the gem install rspec command, I'm new at programming and it seems like whatever has gone wrong is over my head. Any advice or suggestions are greatly appreciated.
Ruby -v
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]
RVM -v
rvm 1.21.20 (stable)
The problem: Whether I type gem install rspec, gem -v, which gem, gem list here is the message:
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/config_file.rb:221:in read': Is a directory - /Users/JTee/.gemrc (Errno::EISDIR)
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/config_file.rb:221:inload_file'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/config_file.rb:168:in initialize'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:384:innew'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:384:in configuration'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:634:inpath'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/source_index.rb:68:in installed_spec_directories'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/source_index.rb:58:infrom_installed_gems'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:881:in source_index'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/gem_path_searcher.rb:81:ininit_gemspecs'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems/gem_path_searcher.rb:13:in initialize'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:839:innew'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:839:in searcher'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:838:insynchronize'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:838:in searcher'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:478:infind_files'
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:1103
    from /usr/bin/gem:8:in `require'
    from /usr/bin/gem:8

A: Try removing /Users/JTee/.gemrc.  It is supposed to be a file but on your computer it is a directory.


text:
Q: Anchor size increases on float Image size is fixed to 42*42. But if we hover over anchor tag in inspect element, size is shown as 42*46. Why the size of anchor tag increases? Is it because I am using float?

A: It's because of the display and vertical-align of img. Setting the vertical-align on the following works:


text:
Q: Detecting homotopy nontriviality of an element in a torsion homotopy group I have a map, constructed geometrically, $S^4 \to S^3$. I suspect that it is a representative for the generator $\eta_3\in \pi_4(S^3) \simeq \mathbb{Z}_2$, but I am not 100% sure ($\eta_3$ is defined as the suspension of the Hopf map $S^3 \to S^2$). I'd like to be able to detect the fact that my map is homotopically nontrivial in a geometric or combinatorial way. Is this possible? I imagine there is some sort of index one can calculate, but unfortunately the terms one looks these things up in are very generic (forms, integration, index etc).

A: How about thinking about framed cobordism, which in this case gives an isomorphism between $\pi_4(S^3)$ and the group of cobordism classes of normally framed 1-manifolds in $S^4$.  Since your map is constructed geometrically, it probably has a regular value.  Pull this back to a collection of disjoint circles in $S^4$, forming a trivial link, with framings of their normal bundles. Since $\pi_1SO(3)$ has order 2, just count up the number of circles with nontrivial framing to see whether this number is odd or even.


text:
Q: how to detect that app connected to local wifi I have two buttons in my app one will be on for local wifi(specially for "ati"), other will be on for if connection is specific server is available like www.google.com
Please help that how can detect the app is connected to local wifi and also how can detect that connection is available to specific server , same behavior as of Reachability in IOS programming

A: You can use the WifiManager class to get the state of Wi-Fi. I think only way to check whether connection to specific server is available to actually connect.


text:
Q: Android FrameLayout and Softkeyboard Issue I have a FrameLayout with a LinearLayout added to it with a gravity of bottom. As a result the LinearLayout appears at the bottom of the screen, and on top of all other layers. This is my required functionality. However when ever a softkeyboard appears on the screen, it pushes the bottom layout up. As a result that layout hides the fields that i am typing in. What can i do to avoid this ?
Kind Regards,

A: Add the following attribute to your related activity inside AndroidManifest.xml
android:windowSoftInputMode="adjustPan"


text:
Q: beginner JSON question: variable returns undefined I am doing my first project using JSON but so far I am getting stuck on something and don't see a solution.
What do I want to do.
I built a simple scraper using Apify.com that returns some information from a site I need. They say the format is JSON, so when I load in the file this is what I get:
[{
  "nowPlaying": "Four Corners Music Show September 16th 2019 - hosted by Melinki",
  "#error": false,
  "#debug": {
    "requestId": "aHg5UyCT6vWQhSD",
    "url": "http://www.example.com/example/",
    "loadedUrl": "http://www.example.com/example/",
    "method": "GET",
    "retryCount": 0,
    "errorMessages": null,
    "statusCode": 200
  }
}]

Now switching back to HTML and javascript I use this code to load the data and try and extract the first variable nowPlaying. But the problem that I have is that I see in the first console.log the exact same data as I showed before, so it seemed to have loaded the file. But when asking for the nowPlaying variable I see a 'undefined' appearing in the console.
There must be something obvious I totally miss, but I can't seem to get to the data I need.
Any suggestions on how to get the text " Four Corners Music Show September 16th 2019 - hosted by Melinki" in a variable that I can split and put in the right html elements?

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
xhttp.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
xhttp.send();

function processData(data) {
    var apiData = data.response;
    console.log(apiData);
    console.log(apiData.nowPlaying);

    var programmingInfo = apiData.nowPlaying.split('-');
    document.getElementById("showName").innerHTML = programmingInfo[0];
    document.getElementById("host").innerHTML = programmingInfo[1];
}

A: Just use JSON.parse to convert the requested string into a dictionary-like object as this SO answer from another question says:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
xhttp.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
xhttp.send();

function processData(data) {
    var apiData = data.response;
    var JSONdata = JSON.parse(apiData)[0];
    var programmingInfo = JSONdata.nowPlaying.split('-');
    console.log(programmingInfo)
    /*document.getElementById("showName").innerHTML = programmingInfo[0];
    document.getElementById("host").innerHTML = programmingInfo[1];*/ // You didn't post your html, so that wouldn't work
}

A: Specify you're waiting for a JSON response :

var xhttp = new XMLHttpRequest();

    xhttp.responseType = 'json';
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            processData(this);
        }
    };
    xhttp.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
    xhttp.send();

    function processData(data) {
        var apiData = data.response;
        console.log(apiData);
        console.log(apiData[0].nowPlaying);
    }

A: var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        processData(this);
    }
};
xhttp.open("GET", "https://api.apify.com/v2/actor-tasks/YSMp66SiktwNXocsf/runs/last/dataset/items?token=twn8q5PnsM5s485DNtxzabdcP&ui=1", true);
xhttp.send();

function processData(data) {
    var apiData = JSON.parse(data.response);

    console.log('apiData',apiData);
    console.log('nowPlaying',apiData[0].nowPlaying);

    var programmingInfo = apiData[0].nowPlaying.split('-');
    console.log('programmingInfo',apiData);
    document.getElementById("showName").innerHTML = programmingInfo[0];
    document.getElementById("host").innerHTML = programmingInfo[1];
}

A: JSON is an javascript object notation meaning, the text can be parsed into valid javascript object. But for this to work you will need to parse it first.
The data that is in your data.response is a string so you cant access its properties directly using javascript. Solution is to simply call JSON.parse on the string and assign that returnvalue to a variable.
Such as this, given your example:
var apiData = data.response;

After that you may access properties using a combination of array and object commands, such as:
 console.log(apiData[0].nowPlaying)

A: Using Oleg's example I could make it work. It was indeed a matter of parsing the data into JSON and correctly requesting the data.


text:
Q: Updating state for a value inside an object immutably in redux reducers I want to update a state value where the key is also dynamic in redux reducer, but I tried various method I am not able to do it.
So my Initial State looks like this
const initalState = {
ingredients:{
  bacon:0,
  salad:0,
  cheese:0,
  meat:0,
},
price:100
};

And my data passed in reducer looks like this
{type: "INCREASEQUANTITY", payload: {
item: "bacon",
value: 1
}}

And I want result state looks like
const initalState = {
ingredients:{
  bacon:1, //updated value
  salad:0,
  cheese:0,
  meat:0,
},
price:100
};

I tried to update it immutably, but its showing syntax error.
My code for this looks like this
      return{
    ...state,
    state.ingredients:{
      ...state.ingredients,
      action.payload.item:state.ingredients[action.payload.item]+action.payload.value //this line explained below
    }
  }

I want to update it with key and value both dynamically like bacon:0+1 but getting syntax issue.
Please help.Thank you

A: You were on the right track
return {
  ...state,
  ingridients: {
     ...state.ingridients,
     [action.payload.item]: state.ingredients[action.payload.item] + action.payload.value
  }
}


text:
Q: delete column in csv in Perl I have the following format for my CSV file that I downloaded online and need to parse it. I want to be able to get rid of the 'unit' column. How can I go about doing this? I want to be able to do it as I parse through the file and not copy it to a different file because the file is very large. Thanks!
 <radio>,<mcc>,<net>,<area>,<cell>,<unit>,<lon>,<lat>,<range>,<samples>,<changeable>,<created>,<updated>,<averageSignal>
UMTS,262,2,801,86355,,13.28527,52.521711,37,7,1,1282569574,1300175362,-91GSM,262,2,801,1795,,13.276605,52.525348,5714,9,1,1282569574,1300175362,-87

A: #!/usr/bin/env perl

use strict;
use warnings;

my $col_to_delete = '<unit>';

chomp ( my @header = split /,/, <> );
my @newheader = grep { not $_ eq $col_to_delete } @header;

print join (",", @newheader),"\n";

while ( <> ) {
   chomp;
   my %row;
   @row{@header} = split /,/;
   print join (",", @row{@newheader}),"\n";

}

Reads STDIN line by line, and prints as you go, so you don't need lots of memory.
You can probably do it via in-place editing, but you'll want to test it to make sure that it works satisfactorily first. You'd do this by setting $^I, but really you're better off creating two files, because it's shockingly easy to clobber one accidentally.


text:
Q: Why is my python merge sort not working? Can you please look at the below code and help me understand why my merge sort code is not working? I have done many changes to this code, I tried to add +1 and remove -1 from indexes wherever possible, but I couldn't debug it.
#!/usr/bin/python
def Merge(a,p,q,r):
    n1=q-p+1
    n2=r-q
    (l,ri)=([],[])
    for i in range(n1):
        l.append(a[p+i])
    for j in range(1,n2+1):
        ri.append(a[q+j])
    l.append(float('inf'))
    ri.append(float('inf'))
    print 'l and ri are %s and %s' % (l,ri)
    i=0
    j=0
    for k in range(p,r+1):
        if l[i]<=ri[j]:
            a[k]=l[i]
            i+=1
        else:
            a[k]=ri[j]
            j+=1
    print 'a after merge is %s' % (a)

def MergeSort(a,p,r):
#print 'a,P and r are %s, %d and %d' % (a,p,r)
    if p+1<r:
        q=divide(r-p)
        MergeSort(a,p,q)
        print 'After MS of %d and %d' % (p,q)
        MergeSort(a,q+1,r)
        print 'After 2nd MS of %d and %d' % (q+1,r)
        print 'Before Mer of %d and %d and %d' % (p,q,r)
        Merge(a,p,q,r)

def divide(number):
    Q,R=divmod(number,2)
    return Q+int(bool(R))

if __name__=="__main__":
    a=[2,9,6,5,4]
    MergeSort(a,0,len(a)-1)
    print a

Is it because my array starts with 0 index?

A: This code should be working.
While I usually don't support debugging solutions, there were many problems with yours. I believe it would be good for you to share your code on Code Review StackExchange site in order to get further useful comments and practices.
The issues I found with your code are along the lines of:

*

*Awful representation of indices. You used both closed and half-open intervals. If you can invest some time in improving your understanding of this, you won't make so much off-by-one errors or fixes.

*No spacing - your code was simply unreadable. While I didn't spend much time on editing it for clarity, you can clearly see my changes to make it more readable.

*Other small mistakes, which show poor understanding of either the merge sort algorithm, or the programming language  - for example the line q=divide(r-p). If p = 8 and r = 10, then you would get q = divide(2), which is 1. Therefore, you will call MergeSort(a, 8, 1) and MergeSort(a, 2, 10) - this is terribly wrong.

*Naming conventions, you can help yourself by using meaningful variable names. This will significantly improve your debugging time.

Hope this helps!


text:
Q: Connect to Service Fabric application endpoint I have set up a Service Fabric cluster on Azure, and have an application with 2 services running. now I want to be able to connect to the services in my browser, like I can when I run it on localhost.
The application uses Owin and Swagger. Here is how it looks like running on localhost: running on localhost. When I try to connect to it from Azure, I get a timeout error. I'm using port 20002 and 20001 in the application, and I have opened the ports when I set up the cluster (port 19000, 19080, 20001 and 20002 are open in my cluster). Here is my service in the Explorer: Service in the explorer. The cluster is setup with certificate security, and I have the certificate added to my browser (I'm using it to connect to the explorer). My code for CreateServiceInstanceListeners:
        protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return Context.CodePackageActivationContext.GetEndpoints()
            .Where(endpoint => endpoint.Protocol.Equals(EndpointProtocol.Http) || endpoint.Protocol.Equals(EndpointProtocol.Https))
            .Select(endpoint => new ServiceInstanceListener(serviceContext => new OwinCommunicationListener("", new Startup(), serviceContext)));
    }

and my code for OpenAsync:
        public OwinCommunicationListener(string appRoot, IOwinAppBuilder startup, StatelessServiceContext serviceInitializationParameters)
    {
        _startup = startup;
        _appRoot = appRoot;
        _parameters = serviceInitializationParameters;
    }

    public Task<string> OpenAsync(CancellationToken cancellationToken)
    {
        var serviceEndpoint =
            _parameters
            .CodePackageActivationContext
            .GetEndpoint("ServiceEndpoint");

        var port = serviceEndpoint.Port;
        var root =
            String.IsNullOrWhiteSpace(_appRoot)
            ? String.Empty
            : _appRoot.TrimEnd('/') + '/';

        //TODO: Make localhost configable
        _listeningAddress = String.Format(
            CultureInfo.InvariantCulture,
            "http://+:{0}/{1}",
            port,
            root
        );
        _serverHandle = WebApp.Start(
            _listeningAddress,
            appBuilder => _startup.Configuration(appBuilder)
        );

        var publishAddress = _listeningAddress.Replace(
            "+",
            FabricRuntime.GetNodeContext().IPAddressOrFQDN
        );

        ServiceEventSource.Current.Message("Listening on {0}", publishAddress);
        return Task.FromResult(publishAddress);
    }

and my ServiceEndpoint:
    <Endpoints>
  <Endpoint Name="ServiceEndpoint" Port="20002"  />
</Endpoints>

to sum up my question: how can I acces my Service Fabric applications services in my browser, using swagger and all?

A: The best way is for you to use the reverse proxy on port 19081. You have to enable it at cluster creation state.
You then have to set up the load balancer rule for reverse proxy.
The basic set up of a service fabric on Azure load balancer does not have rule for TCP port 19081 however you can copy the rule of 19000.
After that for example:

*

*Your application name is SampleApp

*Your service name is SampleService
hosted in port 20002

*You normally reach your service locally at
http://localhost:20002/api/values

*The public IP for your cluster is 51.140.xx.xx

Then now you can reach your service at
http://51.140.xx.xx:19081/SampleApp/SampleService/api/values (presume you dont secure your reverse proxy end point)


text:
Q: Why am I getting segfault with loading objects from shared library? Having this files:
plusone.c
int op(int i){ return i+1; }

main.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int main(int argc, char **argv){
    if (argc<3){
        printf("usage %s <library> <number>\n",argv[0]);
        exit(1);
    }

    char *lname = argv[1];
    int num = atoi(argv[2]);
    void *handle = dlopen(lname, RTLD_LAZY);
    if(!handle)
        perror("dlopen");

    int (*opp)(int);
    opp=dlsym(handle, "op");
    if(!opp)
        perror("dlsym");

    printf("number before:%i\nnumber after:%i\n",num,opp(num));
    dlclose(handle);
}

Compiled as:
$cc -fPIC -shared -o plusone.so -ldl plusone.c
$cc -o main.exe -ldl -Wpedantic main.c
warning: ISO C forbids assignment between function pointer and 'void *' [-Wpedantic]
$ls
main.c main.exe plusone.so main.exe
$main.exe
usage main.exe <library> <number>
$main plusone.so 1
dlopen: Success
dlsym: Success
Segmentation fault

Why is segfault?
As could be seen from the bash output, both the dlopen and dlsym give success (but they should not even output, otherwise that mean, the condition was true, and the returned values from those functions was NULL? - as from condition). But even of the "success" the perror returned, I cannot reproduce the segfault, since do not know where is the bug.

A:
Why is segfault?

Most likely because opp equals NULL the moment opp(num) is trying to be called.
You do not handle errors correctly for the calls to dlopen() and dlysym(), although the code tests the results it does not take the correct actions on failure of those two functions.
This code
  void *handle = dlopen(lname, RTLD_LAZY);
  if(!handle)
    perror("dlopen");

correctly branches on dlopen() returning NULL which indicated an error, but then the code takes the wrong actions.
dlopen() does not set errno, so using perror() to log an error makes no sense, as perror() relies on errno indicating an error, which is does not. So on failure of dlopen() you see perror() printing
dlopen: Success

which is misleading and contractionary to the fact that perror() was called at all, which in fact only happened if dlopen() returned NULL, indicating a failure. If dlopen() would have succeeded, perror() would not have been called at all and nothing would have been printed.
The same mistake appears with the call to dlsym().
To retrieve error info on failure of a member of the dl*() family of functions use dlerror().
For an example on how to correctly and completely implement error handling see below:
  void *handle = dlopen(...);
  if (!handle)
  {
    fprintf(stderr, "dlopen: %s\n", dlerror());
    exit(EXIT_FAILURE); /* Or do what ever to avoid using the value of handle. */
  }
#ifdef DEBUG
  else
  {
    fputs("dlopen: Success\n", stderr);
  }
#endif

The same approach should be taken to handle the outcome of dlsym().

Aside of all this and unrelated to the observed behaviour the code misses to call dlclose() when done with using a valid handle.


text:
Q: Change Date picker dialog theme I have implement datepickerdialog and want to remove the background color of Cancel and Ok Button and change text color of those buttons. This is in androidx project.

public void displayCalendar(final TextView tv, final String myFormat) {
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, monthOfYear);
            c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            SimpleDateFormat sdf1 = new SimpleDateFormat(myFormat, Locale.US);
            str_date = sdf1.format(c.getTime());
            tv.setText(str_date);
            mListener.onDateSelected();
        }

    };
    DatePickerDialog datePickerDialog = new DatePickerDialog(con, R.style.DatePicker, date, c
            .get(Calendar.YEAR), c.get(Calendar.MONTH),
            c.get(Calendar.DAY_OF_MONTH));

    datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
    datePickerDialog.setTitle("");
    datePickerDialog.show();
}

In styles-
<style name="DatePicker" parent="Theme.MaterialComponents.Light.Dialog">
    <item name="colorPrimary">#377dff</item>
    <item name="colorPrimaryDark">#1C5CD3</item>
    <item name="colorAccent">#377dff</item>
</style>

A: try as below
 Button btn_ok = alert.getButton(DialogInterface.BUTTON_POSITIVE);
 btn_ok .setBackgroundColor(Color.YELLOW); //add your color


text:
Q: How to define feature modify event in openlayers 3? I'm using OpenLayers-3.8.2. I have modify interaction as follows:
selectedInteraction = ...
modifyInteraction = new ol.interaction.Modify({
   features: selectInteraction.getFeatures()
});

I want to define an event that when a point of feature change, it fires. Something like this, but NOT for drawing, for modifying.
How do I do?

A: On modifystart you need to listen for change:geometryevent on the feature then on modifyend you remove this listener.

A: there is an event on the select interaction, that fires when you modify a feature and click outside of it:
selectedInteraction.getFeatures().on('add', function(e) {
    e.element.on('change', function(e) {
    //and here e.target is the feature that has been modified
    });
});


text:
Q: Pinescript Strategy Labels Modification I'm newer to Pinescript and have a working strategy, but I'd like more info on the label to help with my tracking and backtesting. I would like to be able to modify the Signal Label of the closed trades to also have how many pips were made or lost for each trade. Currently, it just says "Close entry(s) order Long". Is there a way to make it show for example "Close entry(s) order Long -23.5 Pips" or something similar to that. I am using strategy.close and I imagine this can be done by adding a comment, but I'm not sure how. Any help would be appreciated. If I can't do this, I would add a label instead if I can figure that out. This isn't vital to get the strategy to work, but will save me lots of time when I document the previous weeks trades.
if LongCondition
    strategy.entry("Long", strategy.long)
if LongExit
    strategy.close("Long")
if ShortCondition
    strategy.entry("Short", strategy.short)
if ShortExit
    strategy.close("Short")

A: Yes use the comment parameter for that
https://www.tradingview.com/pine-script-reference/v5/#fun_strategy{dot}close
Example:
if LongExit
    strategy.close("Long", comment = "Close Long " + str.tostring(strategy.openprofit, "#.##"))


text:
Q: Aligning title, subtitle and caption for horizontal ggplot barchart I would like to left align the plot.title, plot.subtitle and plot.caption in a horizontal ggplot2 barchart.
Example:
library("ggplot2") # ggplot2 2.2
df <- data.frame(type=factor(c("Brooklyn",
                               "Manhatten and\n Queens")),
                 value=c(15,30))

# manual hjust for title, subtitle & caption
myhjust <- -0.2

ggplot(df,
       aes(x=type, y=value)) +
  geom_bar(stat='identity') +
  coord_flip() +
  labs(
    title = "This is a nice title",
    subtitle = "A subtitle",
    caption  = "We even have a caption. A very long one indeed.") +
  theme(axis.title=element_blank(),
        plot.title=element_text(hjust = myhjust),
        plot.subtitle=element_text(hjust = myhjust ),
        plot.caption=element_text(hjust = myhjust))

How can I align all 3 labs elements (plot.title, plot.subtitle and plot.caption) to where the axis.text starts (red vertical line, "M" of Manhatten)?
Besides: Why does a fixed  myhjust result in 3 different horizontal positions for plot.title, plot.subtitle and plot.caption?

A: This question refers to this github tidyverse/ggplot2 solved issue: https://github.com/tidyverse/ggplot2/issues/3252
And it is implemented in ggplot2 (development version): https://github.com/tidyverse/ggplot2/blob/15263f7580d6b5100989f7c1da5d2f5255e480f9/NEWS.md

Themes have gained two new parameters, plot.title.position and plot.caption.position, that can be used to customize how plot title/subtitle and plot caption are positioned relative to the overall plot (@clauswilke, #3252).

To follow your example as a reprex:
# First install the development version from GitHub:
#install.packages("devtools") #If required
#devtools::install_github("tidyverse/ggplot2")

library(ggplot2)
packageVersion("ggplot2")
#> [1] '3.2.1.9000'

df <- data.frame(type=factor(c("Brooklyn","Manhatten and\n Queens")),
                 value=c(15,30))

ggplot(df, aes(x=type, y=value)) +
  geom_bar(stat='identity') +
  coord_flip() +
  labs(title = "This is a nice title",
       subtitle = "A subtitle",
       caption  = "We even have a caption. A very long one indeed.") +
  theme(plot.caption = element_text(hjust = 0, face= "italic"), #Default is hjust=1
        plot.title.position = "plot", #NEW parameter. Apply for subtitle too.
        plot.caption.position =  "plot") #NEW parameter

Created on 2019-09-04 by the reprex package (v0.3.0)

A: While you could edit those three grobs, you can also just:
library(gridExtra)
library(grid)

grid.arrange(
  textGrob("This is a nice title",
           gp=gpar(fontsize=16, col="#2b2b2b"),
           x=unit(0.005, "npc"), just=c("left", "bottom")),
  textGrob("A subtitle",
           gp=gpar(fontsize=12, col="#2b2b2b"),
           x=unit(0.005, "npc"), just=c("left", "bottom")),
  ggplot(df, aes(x=type, y=value)) +
    geom_bar(stat='identity') +
    coord_flip() +
    theme(axis.title=element_blank()),
  textGrob("We even have a caption. A very long one indeed.",
           gp=gpar(fontsize=9, col="#2b2b2b"),
           x=unit(0.005, "npc"), just=c("left", "bottom")),
  ncol=1,
  heights=c(0.075, 0.025, 0.85, 0.05)
)

Make a wrapper for it, put it in a personal pkg. Boom. Done.

library(ggplot2)
library(gridExtra)
library(grid)

df <- data.frame(type=factor(c("Brooklyn","Manhatten and\n Queens")), value=c(15,30))

ggplot(df, aes(x=type, y=value)) +
  geom_bar(stat='identity') +
  coord_flip() +
  theme(axis.title=element_blank()) +
  theme(plot.margin=margin(l=0, t=5, b=5))-> gg

flush_plot <- function(x, title, subtitle, caption) {
  tg <- function(label, ...) {
    textGrob(label,  x=unit(0, "npc"), just=c("left", "bottom"),
             gp=do.call(gpar, as.list(substitute(list(...)))[-1L])) }
  grid.arrange(
    tg(title, fontsize=16, col="#2b2b2b"),
    tg(subtitle, fontsize=12, col="#2b2b2b"), x,
    tg(caption, fontsize=9, col="#2b2b2b"),
    ncol=1, heights=c(0.075, 0.025, 0.85, 0.05)
  )
}

flush_plot(gg, "This is a nice title", "A subtitle",
           "We even have a caption. A very long one indeed.")


text:
Q: Controls running away from Canvas I have the following XAML code:
<TabItem Header="Hey there, handsome!">
    <Canvas>
      <GroupBox Header="30" Canvas.Top="40">
        <Canvas>
          <Label Canvas.Top="40">dawd</Label>
        </Canvas>
      </GroupBox>
    </Canvas>
</TabItem>

I expect to see a GroupBox that is 40px from the top of the tab and inside the GroupBox a label that is 40px from its top.
But this happens:

What am I doing wrong and how can I solve it?
(All in all, I just need a layout panel for absolute positioning).

A: I think this a Canvas behaviour, with Grid instead of Canvas that should work fine, and why not set the GroupBox Height and Width property to "Auto" ?


text:
Q: Correctly speeding up ball in breakout game on collision So I have these 3 scripts in my assets (among others). My General Manager(GM), my ball and my crazybrick. When it touches the crazy brick its supposed to move a little faster each time. In my GM I set a boolean fastball equal to false and set it true on collision in my crazybrick script using a GM instance. Then in my ball script, if true, I incrementally make the ball go faster then set fastball back to false. I test this with debug logs and it goes 100f faster every time. All seems perfect on the first test. But with subsequent tests weird things happen. The ball sometime goes slower, or shoots out of my walls after getting faster too quickly or doesn't seem to get faster at all. Its always different. Below is my relevant code for the three scripts.
public class GM : MonoBehaviour {
 public bool fastBall = false;
 public static GM instance = null;
}

public class CrazyBrick : MonoBehaviour {
    public GameObject brickParticle;

    void OnCollisionEnter ()
    {
        GM.instance.fastBall = true;
        Instantiate (brickParticle, transform.position, Quaternion.identity);
        GM.instance.DestroyBrick ();
        Destroy (gameObject);
    }
}

public class Ball : MonoBehaviour {

    public float ballInitialVelocity = 600f;
    public float newVelocity;
    private Rigidbody rb;
    private bool ballInPlay;

    // Use this for initialization
    void Awake () {

        rb = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void FixedUpdate () {
        if (GM.instance.fastBall) {

            newVelocity = newVelocity + 100f;
            Debug.Log ("increment 100f: " + newVelocity);
            rb.AddForce(new Vector3(newVelocity, newVelocity, 0));

            GM.instance.fastBall = false;

        }
        if(Input.GetButtonDown("Fire1") && ballInPlay == false)
        {

            transform.parent = null;
            ballInPlay = true;
            rb.isKinematic = false;
            rb.AddForce(new Vector3(ballInitialVelocity, ballInitialVelocity,
            0));
        }
    }
}

A: If you know the exact velocity you want the rigid body set to then you can just set the velocity directly instead of calling AddForce. On top of that you're calling AddForce and adding the full velocity plus the 100 units. So if you had a velocity of 50, you're then calculating 150 and calling addforce with that, giving you 50 + 150, instead of just giving you 150. If you want to call AddForce then you should add 100.
Also, if you add equal force along X and Y, which you're doing, then that's actually more than the original amount. If you think about the pythagorean theorem, the hypotenuse of a right triangle is longer than the other two sides. So if you're adding 100 to X and 100 to Y, that's actually approximately 141 units per second you'll be adding. You should get the velocity direction, and add 100 units along that direction, this avoids the issue of adding along multiple vectors and then having to normalize that value.
Try something like this in the places you're using rb.AddForce():
// Get the current velocity vector
var oldVelocity = rb.velocity;

// Get the current speed
var oldMagnitude = oldVelocity.magnitude;

// Get the current direction the rigid body is moving in
var direction = oldVelocity.normalized;

// The new velocity is in the same direction but faster than before
var newVelocity = direction * (oldMagnitude + 100f);

// Set the rigid body to the new velocity
rb.velocity = newVelocity;

Maybe this would work for you:
void FixedUpdate () {
    if (GM.instance.fastBall) {

        // Get the current velocity vector
        var oldVelocity = rb.velocity;

        // Get the current speed
        var oldMagnitude = oldVelocity.magnitude;

        // Get the current direction the rigid body is moving in
        var direction = oldVelocity.normalized;

        // The new velocity is in the same direction but faster than before
        var newVelocity = direction * (oldMagnitude + 100f);

        // Set the rigid body to the new velocity
        rb.velocity = newVelocity;

        GM.instance.fastBall = false;
    }
    if(Input.GetButtonDown("Fire1") && ballInPlay == false)
    {
        transform.parent = null;
        ballInPlay = true;
        rb.isKinematic = false;

        // Get the current direction the rigid body is moving in
        var direction = oldVelocity.normalized;

        rb.velocity = direction * ballInitialVelocity;
    }
}


text:
Q: When Eslint parse Tsx/Ts file 'public' token, always shows 'Parsing error: Unexpected token' i am using eslint and react, while writing public token in tsx/ts file, always show me public is unexpected token..

A: it shows error because i use babel-eslint...just change my eslint parser to @typescript-eslint/parser...


text:
Q: Flutter: Scraping a site with JavaScript generated content without dart:html How do I scrape a web page that generates some of its content with a JavaScript element? It is a local court booking site for my squash club and from what I can see, this is the JavaScript script it calls to retrieve the court bookings:
function load_js(url) {
    var e = document.createElement("script");
    e.src = url;
    e.type = "text/javascript";
    if (document.getElementsByTagName("head")[0].lastChild.src == e.src) {
        document.getElementsByTagName("head")[0].replaceChild(e, document.getElementsByTagName("head")[0].lastChild);
    }
    else {
        document.getElementsByTagName("head")[0].appendChild(e);
    }
}

onload = function () {
    setInterval("load_js('/js/bookings_reload.js.php')", 30000);
};

How could I replicate this in Flutter? I can scrape the HTML and parse it to create an HTML document, but since Flutter disallows the use of the dart:html library, I can't create a ScriptElement to duplicate the JavaScript script. Is there an alternative in Flutter?
Here is my Dart function so far:
var httpClient = createHttpClient();
getData() async {
      // Send POST request to get authorized cookie
      var response = await httpClient.post('http://bookings.squashgym.co.nz/login',
          body: {'username': username, 'password': password});

      // Send get request with authenticated cookie to get bookings
      var courts = await httpClient.get('http://bookings.squashgym.co.nz/booking-sheet',
      headers: {'cookie': response.headers['set-cookie']});

      Document data = parse(courts.body);
      httpClient.close();
}

Thanks!

A: I agree on using WebView to load the URL needed. Here is an example implementation of WebView using the webview_flutter.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WebView(
        initialUrl: "https://flutter.dev/",
        onWebViewCreated: (WebViewController webViewController) {
          _controller.complete(webViewController);
        },
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );
  }
}

This is how it will look like:

And when the page is rendered you will be able to get the DOM from the WebView. There is also an available example of getting DOM from WebView. Check it here.


text:
Q: Overwrite File With Cron Job OR Multiple Entry Cron? I have the following cron job
0   0 * * * /usr/bin/wget http://www.example.com/chron_sitemap.php

This basically runs the script to create a new sitemap located at sitemap.xml
The problem arises because the sitemap already exists and it needs to be either overwritten or deleted before it is created.
I tried
unlink('sitemap.xml');

but that erases the file and even though it's at the top of the script, and I have at the bottom
$xml->save("http://www.example.com/sitemap.xml");

It doesn't work. I still get a 404 - page not found.
I also thought about putting in another cron job to delete said file, but that could possibly leave a gap between deletion and creation.
What's the best way to proceed here and how?
THANK YOU!
PS: I'm using cPanel to set chrons if that makes a difference.

A: This command will not work
$xml->save("http://www.example.com/sitemap.xml");

better use
$xml->save("local path to file") //e.g $xml->save("/var/www/sitemap.xml");

to actually store it on you local machine.
http://www.php.net/manual/de/domdocument.savexml.php


text:
Q: What is high level modules and low level modules.? I know this is the exact duplicate of below link.
What are "High-level modules" and "low-level modules" (in the context of Dependency inversion principle)?
But after reading that I do not understand what exactly it is.
High level modules are abstract classes and Interfaces ?

A: High level module is the interface / abstraction that will be consumed directly by the presentation layer. Low level on the other hand are bunch of small modules (subsystems) help the high level do their work. Example below is the high level module. I have excluded the dependency constructor injection for shorter sample.
public class OrderService : IOrderService
{
    public void InsertOrder(Order ord)
    {
        if(orderValidator.IsValidOrder(ord)
        {
            orderRepository.InsertNew(ord);
            userNotification.Notify(ord);
        }
    }
}

And one of the low level module (the OrderValidator):
public class OrderValidator : IOrderValidator
{
    public bool IsValidOrder(Order ord)
    {
        if(ord == null)
            throw new NullArgumentException("Order is null");
        else if(string.IsNullOrEmpty(ord.CustomerId))
            throw new InvalidArgumentException("Customer is not set");
        else if(ord.Details == null || !ord.Details.Any())
            throw new InvalidArgumentException("Order detail is empty");
    }
}


text:
Q: Why and when use append() instead of concat() in Pandas? I have read all topics on append vs concat here, but still:
Why should I use append if concat has the same options and funcionallity?
Please correct me if I am mistaken.

*

*append() : can append two data frames at once; it's the same as concat in axis=0

*concat() : can concatenate multiple DFs

To concatenate multiple DFs, should I use append() with a for-loop? Is it faster?
Let's assume that I am opening DFs from different files like:
df = pd.DataFrame()
for file in file_folder:
    df = df.append(pd.read_csv(file))

OR

df = pd.DataFrame()
for file in file_folder:
   df = pd.concat([df, pd.read_csv(file)])

The output is the same. So why?
EDIT: to speed it up should I do:
df_list = []
for file in file_folder:

    df_list.append(pd.read_csv(file))

#and then use concat

df_all = pd.concat(df_list)`

right?

A: append is a convenience method which calls concat under the hood. If you look at the implementation of the append method, you will see that.
def append(...
    ...
    if isinstance(other, (list, tuple)):
        to_concat = [self, *other]
    else:
        to_concat = [self, other]
    return concat(
        to_concat,
        ignore_index=ignore_index,
        verify_integrity=verify_integrity,
        sort=sort,
    )

As for the performance. Both of these called over and over in a loop can be computationally expensive. You should just create a list and do one concatenation after you are done looping.
From docs:

iteratively appending rows to a DataFrame can be more computationally
intensive than a single concatenate. A better solution is to append
those rows to a list and then concatenate the list with the original
DataFrame all at once.

A: *

*It is an arbitrary choice to either use .append() or .concat()
For example if you have to merge two dataframes on axis=1 then go with concat and on the other hand if you have to merge two dataframes on axis=0 go with whatever choice you prefer to use or works best for you!

*Personally I would reccomend you to go with the pandas default DF merger(concat) to avoid any delays, latencies and most importantly bugs in you code.
Hope so that you find this information useful and answers you question!
Happy Coding!


text:
Q: BizTalk: Knowing send port finished write file I has a problem with send port and an application: The process cannot access the file because another process has locked a portion of the file.
I guess the problem is while BizTalk send port is writing a file, the application pickup this file and process.
My scenario:

*

*I have an orchestration with a file send port to write a file to a location.

*After this port I have another send port to call an application to picking the written file and process.
I think: While file send port is writing and not yet finished, the orchestration does not wait but continue next step - calling application. And this leads to above error.
Is my assumption correct?
And how can I solve this problem?

A: You are absolutely correct your orchestration basically throws the message in your send port and continues, but you can change this behavior and I'll give you a really simple solution here it is
* Set your Logical send port like this

Now your orchestration will wait for delivery ACK
*To make things cleaner
Create a scope and catch the Microsoft.XLANGs.BaseTypes.DeliveryFailureException which occurs when you don't get an ACK
*Also add in your catch block a suspend Orchestration shape so you can resume your orchestration if your message doesn't get to its destination :)
This works with both File and FTP protocol, (I didn't test others)


text:
Q: "No Material widget found. " at Hero image animation between routes Flutter Newb: I have a grid of image buttons on a menu screen. When clicking a button it animates into the 'leading' element of the new view's AppBar. That works as I was expecting it to. So far so good...
When I Navigator.pop() that 2nd view I get the error  "No Material widget found."...
The specific widget that could not find a Material ancestor was: _InkResponseStateWidget...
(though the menu screen does reappear as expected
/// ...
class MenuScreen extends StatelessWidget {
  const MenuScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Menu'),
      ),
      body: Center(
        child: GridView.count(
          crossAxisCount: 3,
          children: const [
            MenuButton('clients'),
    //...and so on

///...
class MenuButton extends StatelessWidget {
  final String indexStr;

  const MenuButton(this.indexStr, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Hero(
      child: InkWell(
        child: Ink.image(
          image: AssetImage('assets/images/$indexStr.png'),
          fit: BoxFit.cover,
        ),
        onTap: () => Navigator.pushNamed(context, '/' + indexStr),
        highlightColor: Colors.blue.withOpacity(0.5),
        splashColor: Colors.blue.withOpacity(0.9),
        borderRadius: BorderRadius.circular(100),
      ),
      tag: indexStr,
    );
  }
}

PS. I can't say I completely understand all the context and key stuff either :-)
The second 'screen's code is
import 'package:flutter/material.dart';

class ClientsScreen extends StatelessWidget {
  const ClientsScreen({Key? key}) : super(key: key);
  final indexStr = 'clients';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: Material(
          child: Hero(
            child: Image.asset('../assets/images/$indexStr.png'),
            tag: indexStr,
          ),
        ),
        title: const Text('Clients.'),
      ),
      body: Center(child: Text('Test')),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('Back')),
    );
  }
}

I imagine I'm missing something obvious, but can't see what it might be...
Update:, and the main.dart root app with the routes map:
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes',
      theme: ThemeData(scaffoldBackgroundColor: Colors.white),
      initialRoute: '/',
      routes: {
        '/': (context) => const MenuScreen(),
        '/clients': (context) => const ClientsScreen(),
        '/checkin': (context) => const CheckinScreen(),
             },
    );
  }
}

A: As others already pointed out in the comments, a Material widget is needed to wrap the InkWell.
Reason:

The InkWell widget must have a Material widget as an ancestor. The
Material widget is where the ink reactions are actually painted. This
matches the material design premise wherein the Material is what is
actually reacting to touches by spreading ink.

https://api.flutter.dev/flutter/material/InkWell-class.html

Ink effects: Material shows ink effects implemented by InkFeatures
like InkSplash and InkHighlight below its children.

https://api.flutter.dev/flutter/material/Material-class.html
The Material widget displays ink effects like InkSplash and InkHighlight of its respective children. Widgets already implementing the Material functionality are Scaffold, Card etc. Which is why one of these is needed as an ancestor, and if not, Material is needed.


text:
Q: Inconsistent output of date in controller and template I'm using Symfony 5, I've entity with two date field. 1st is "date" and second is "recievedDate"
Problem is while displaying date in a loop "{{ record.date | date('H : i')}}" in a datatable, the twig display correct hours for field date and display 00.00 as hour for the second field date witch is recievedDate and it is not correct.
Same problem with another entity having only one field date. Again twig display 00.00 witch is not correct. If I do a foreach in my controller and dump the date the hours are correct. Strangely when i send the collection to the twig and display hours then it show wrong hour 00.00
Twig screen shot of dump date in the loop (get with findAll function)

Normally it should show 8:50. There is not problem while showing display the entity outside of loop in a another page get with find(id) function

And here is an example when I dump date and recieved date in the loop

A: I figured out that the problem was somewhere else
Actually, I have function inside of my entity class that calculates the day interval passed. So this function take the date and set hour to 00.00.00 and do calculations.
Thats why in that list hours was always showing 00.00.00
The solution was to clone the date
so instead of :
$start_date = $this->getDate()
I used this :
$start_date = clone  $this->getDate()


text:
Q: idle time period between group of records in mysql i am going to get idle and running time period of a car using mysql.here my table
speed(kmph) |  cdate
00.00  | 2014-08-11 00:00:01
00.00  | 2014-08-11 01:01:01
00.00  | 2014-08-11 03:03:41
00.00  | 2014-08-11 05:01:01
00.00  | 2014-08-11 08:20:01
50.88 |  2014-08-11 08:20:02
100.88  | 2014-08-11 09:40:22
00.00  | 2014-08-11 10:20:23
00.00  | 2014-08-11 11:10:33
00.00  | 2014-08-11 13:30:56
50.88 |   2014-08-11 13:30:57
100.88 | 2014-08-11 15:10:22
what i need is,
the idle time of the car is
2014-08-11 00:00:01 to 2014-08-11 08:20:01
2014-08-11 10:20:23 to 2014-08-11 13:30:56
i have to get these result from mysql table .
please help..

A: You can do this by assigning a grouping variable to each row of idle periods.  The easiest is simply the number of non-zero speeds before any given record (that has a speed of 0).  Then do the aggregation:
select min(cdate), max(cdate)
from (select t.*,
             (select count(*)
              from table t2
              where t2.cdate <= t.cdate and t2.speed > 0
             ) as grp
      from table t
      where t.speed = 0
     ) x
group by grp;


text:
Q: How to upload file using below HTML script in selenium python I tried to send_keys() directly to attached path file but getting error can any on guide me how to upload file.
below is my selenium python script:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()
browser.maximize_window()
wait = WebDriverWait(browser,20)
browser.get('https://www.google.com/')

browser.find_element('xpath', '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[3]/div[3]/img').click()

att = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#ow6 > div.M8H8pb > c-wiz > div.ea0Lbe > div > div.gIYJUc > div.f6GA0 > div > div.ZeVBtc > span')))
att.send_keys('C:/Users/avu/caha.png')

A: You are using a wrong web element.
To upload file with Selenium you need to use the following locator:
wait.until(EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))).send_keys(file_path)

This element is not visible or clickable, so presence_of_element_located should be used in case you want to use WebDriverWait.
UPD
Your code should be as following:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()
browser.maximize_window()
wait = WebDriverWait(browser,20)
browser.get('https://www.google.com/')

browser.find_element(XPATH, "//img[@alt='Camera search']").click()

wait.until(EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))).send_keys('C:/Users/avu/caha.png')

Possibly you even don't need to use browser.find_element(XPATH, "//img[@alt='Camera search']").click() line.


text:
Q: How should I use backup/restore vs import-ldif/export-ldif I'm looking to take periodic backups of an ldap server for disaster recovery. It seems that data can be backed up and recovered via both backup/restore and export-ldif/import-ldif.
What are the advantages of each system?

A: Depending on the server software, backup and restore are probably faster, since presumably the operate on the binary copy of the database. The LDIF would be useful when a totally new environment needs to be created. LDAP server administrators should use both methods. If the server runs on Solaris, then a ZFS snapshot should also be created.


text:
Q: What to use for r in proof by contradiction? This is a problem from Discrete Mathematics and its applications

To this proof, I am trying to use proof by contradiction. Here is how the book described the process of proof by contradiction.

I get the idea behind this. A contradiction is basically a compound proposition that no matter what combination the propositions within it take, the compound proposition will always evaluate to false. https://courses.cs.washington.edu/courses/cse311/14au/slides/lecture03-filled.pdf (slide 5) Because the q in this case is false, and the implication we're using, ~p -> q, is true(assuming to be true, like direct proof? Might need clarification on this as well), ~p must be false, which means p is true. So in the end p is proved to be true
Here is my work so far for the problem
What I have so far is a truth table that shows r ^ ~r is a contradiction. I am trying to prove p which is (x*y is irrational. To do proof by contradiction, I know that I am going to have to use ~p, which is x * y is rational. I express ~p with the definition of rationality - exists integers p and q, q!=0, etc... My question is what do I use for r? Just any proposition? Or does it have to relate to the problem? I know that r ^ ~r is a contradiction.

A: This is implicitly a universal statement.  To disprove a universal statement, all you have to do is provide a counterexample.   So,  all it takes to disprove this statement is to find two irrational numbers that their product is rational.   Can you find such a counterexample?

A: While in conventional language, a contradiction is a statement of the form "X and not X", for mathematical purposes, any false statement is equal to a contradiction.  In logic "summer is cold" equals "today is Tuesday and today is not Tuesday" since both equal "false".
You don't actually have to form a conclusion of the form $\lnot R \land R$, just concluding any false result is enough to show false premise.
This should be fairly intuitive.  If you are grasping at definitions to understand the concept, then you are making things unnecessarily difficult.  "A false conclusion can only come from false premises" is all you need to understand to use proof by contradiction.


text:
Q: Dynamically format a cell I am creating an Excel Dashboard that returns Dollar Amounts in a specific cell based on a few List Selections.
What I need to do now is have the Cell dynamically format the Dollar Amount.
For example, if it returns $3,152,234.25 I want it to display $3.2M, but if it returns $756,253.67 then I want it to display $756K and so on.
Any ideas?

A: You could use the following custom formatting:

[>1000000]0.0,,\M;0.0,k

Result:

A: You can certainly get one or the other with custom formats like this:
$0,"K";-$0,"K"
$0.00,,"M";-$0.00,,"M"
$0.00,,,"B";-$0.00,,,"B"

However, to have the conditions check for K/M/B, you would probably need a macro to dynamically set your formatting based on the values in the cells

A: This isn't a particularly elegant solution, but you could use a formula like this:
=IF(A1/1000000>1,TEXT(A1/1000000,"$0.0")&"M",TEXT(A1/1000,"$0")&"K")

(Assumes your number is in cell A1)


text:
Q: How to address "Select-String -pattern" return object via pipeline without using foreach loop? Let's say I have a file with a following content:
1,first_string,somevalue
2,second_string,someothervalue
n,n_nd_string,somemorevalue

I need to Get-Content of this file, get the last string and get the number before the "," symbol (n in this case). (I'll just increment it and append n+1 string to this file, but it does not matter right now). I want all this stuff be done with pipeline cascade
I have come to this solution so far:
[int]$number = Get-Content .\1.mpcpl | Select-Object -Last 1 | Select-String -Pattern '^(\d)' | ForEach-Object {$_.matches.value}

It actually works, but I wonder if there are any ways of addressing Select-String -Pattern '^(\d)' return object without using the foreach loop? Beacause I know that the return collection in my case will only consist of a 1 element (I'm selecting a single last string of a file and I get only one match)

A: You may use
$num = [int]((Get-Content .\1.mpcpl | Select-Object -Last 1) -replace '^(\d).*', '$1')

Notes

*

*(Get-Content .\1.mpcpl | Select-Object -Last 1) - reads the file and gets the last line

*(... -replace '^(\d).*', '$1') - gets the first digit from the returned line (NOTE: if the line does not start with a digit, it will fail as the output will be the whole line)

*[int] casts the string value to an int.

Another way can be getting a match and then retrieving it from the default $matches variable:
[IO.File]::ReadAllText($filepath) -match '(?m)^(\d).*\z' | Out-Null
[int]$matches[1]

The (?m)^(\d).*\z pattern gets the digit at the start of the last line into Group 1, hence $matches[1].

A: It looks like a csv to me...
import-csv 1.mpcpl -header field1,field2,field3 | select -last 1 | select -expand field1

output:
n


text:
Q: Removing duplicates from a list of lists?
Possible Duplicate:
Python: removing duplicates from a list of lists

What is the best way to remove duplicates from a list of lists?
I was trying to use set like this:
L1 = [['fox', 'dog'],['bat', 'rat'],['fox', 'dog']]
L1 = list(set(L1))

Unfortunately, I get a TypeError: unhashable type: 'list'.
In my list there are two occurrences of ['fox', 'dog']. I want L1 to remove the duplicate and look like this:
L1 = [['fox', 'dog'],['bat', 'rat']]

A: If you convert the inner lists to tuples you will be able to add them to a set successfully, for example:
>>> set(map(tuple, L1))
set([('fox', 'dog'), ('bat', 'rat')])

If necessary, you can get back to lists of lists like this:
>>> map(list, set(map(tuple, L1)))
[['fox', 'dog'], ['bat', 'rat']]


text:
Q: Having Actions Performed Upon Button Press I'm a bit of a newbie with Rails and I have what I believe is a pretty simple question. I'm designing a voting application. Upon pressing a button, the number of votes increases by one. The controller method code looks like:
def vote
  @item = Item.find(params[:id])
  @item.increment(:votes)
  @item.save
  redirect_to :show
end

The button has the code of:
%= button_to "Vote",  :method => "Vote" %

This seems to be where my error occurs. It's trying to go to a url of /:id?method=Vote when I'm just trying to get the application to run the method then return back to the show page. Any suggestions are very appreciated! I'm convinced this is an issue of not fully understanding the concept of routing, but honestly I'm a little stumped.

A: :method pertains to the HTTP verb, and default is :post, but since you are updating an object, you probably want to use :put
button_to "Vote", vote_item_path(@item), :method => :put

where @item is your Item object. You also need to define your route
put 'items/:id/vote' => 'items#vote', :as => :vote_item

To clarify what is going on here, vote_item_path(@item) will generate the URL items/1/vote if @item.id = 1


text:
Q: For $x+y=n$, if $V'-V=3$ then $\large \frac{n}2$ is prime. Define $V$ and $V'$ as the number of visible and non-visible lattice points from the origin respectively.
Conjecture
For $x+y=n, (x,y)\in\mathbb{Z}^2$, if $V'-V=3$ then $\large \frac{n}2$ is prime.
Examples
Let $n=6,V=2\textrm{ (green)},V'=5 \textrm{ (purple)}$ then $3$ is prime.

Similarly for
n=10,V=4,V'=7 then 5 is prime.

n=14,V=6,V'=9 then 7 is prime.

n=22,V=10,V'=13 then 11 is prime.

n=26,V=12,V'=15 then 13 is prime.

n=34,V=16,V'=19 then 17 is prime.

n=38,V=18,V'=21 then 19 is prime.

...

A: A point $(x,y)$ is visible if and only if $\gcd(x,y)=1$. If $x+y=n$, then $\gcd(x,y)=\gcd(x,x+y)=\gcd(x,n)$. So, $V$ is the number of $0\leq x\leq n$ with $\gcd(x,n)=1$, and $V'=(n+1-V)$. So, you're asking for when
$$3=V'-V\Longleftrightarrow V'=\frac n2+2.$$
If this is true, then $n$ must be even, so let $n=2k$ for some $k$. Then, if $x$ is even, $\gcd(x,n)\geq 2$, so $(x,n-x)$ cannot be visible. This accounts for $k+1$ points $(0,2k),(2,2k-2),\dots,(2k-2,2),(2k,0)$. If $k$ is a power of $2$, then these are the only non-visible points, so $V'=k+1$, not $k+2$. Otherwise, if $k$ is not prime, there is some odd prime $p$ which divides $k$; in this case, $(p,n-p)$ and $(n-p,p)$ are distinct non-visible points that we haven't already counted. This gives that $V'\geq k+3$, so $V'\neq k+2$. So, $k$ must be prime, as desired. (The last non-visible point is $(k,k)$, and one can show there aren't any others, which gives the converse of the statement for whenever $n/2$ is an odd prime.)
Note: for $n>1$, $V$ is the same as the Euler totient function $\varphi(n)$ of $n$. Your conjecture can be rephrased as requiring $\varphi(n)=n/2-1$ and asking if $n$ is twice a prime.


text:
Q: Why doesn't a GUI application in crontab open with auto-login? I want to start a GUI application through crontab on reboot. I have setup the crontab as @reboot export DISPLAY=:0 && ./myscript.sh and it works perfectly fine when auto-login is disabled i.e. I need to manually enter password to login.
However, when auto-login is enabled, the crontab still works but the GUI application is not launched.
Why does this happen?


text:
Q: Converting character dates I am trying to convert character dates as below in R:
Before          After
"31/03/2018"    "201804"
"30/06/2018"    "201807"
"30/09/2018"    "201810"
"31/12/2018"    "201901"

The month is advanced by a month. This will be helpful to people trying to convert calendar date to the Canadian fiscal date which follow months 1, 4, 7 and 10 instead of months 3, 6, 9 and 12 elsewhere(generally).

A: Looks like you haven't tried anything yet, Here you go:
format(as.Date("31/03/2018","%d/%m/%Y")+1,"%Y%m")
format(as.Date(Before,"%d/%m/%Y")+1,"%Y%m")

A: With lubridate, things are as easy as adding a day :
library(lubridate)
before <- c("31/03/2018","30/06/2018","30/09/2018","31/12/2018")
after <- dmy(before)+days(1)
format(after, "%Y%m")

A: Use of %m+% operator is very handy in such case. %m+% months(1) will add 1 month in date or %m+% months(2) will add 2 months to date. Even one can use %m+% years(1) to add 1 year to a date variable.
library(lubridate)

v <- c("31/03/2018", "30/06/2018", "30/09/2018", "31/12/2018")

format((dmy(v) %m+% months(1)), "%Y%m")
#[1] "201804" "201807" "201810" "201901"