问:
Android SQLite Where and when to initialise SQLiteOpenHelper
I am really struggling with using the SqlLite in my App;

I have set up a database helper class that extends from SQLiteOpenHelper

```<code>public class DatabaseHelper extends SQLiteOpenHelper {
</code>```

In the OnCreate I am Creating about 6 tables:

```<code>public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE myTestTable (Id INTEGER PRIMARY KEY , "
            + "info TEXT," +
            + "TopLeft TEXT")); <-- example insert

}
</code>```

When my App starts I am parsing some xml and entering the data into the table, and I have checked the database and all is in there and my tables created correctly.

When I go to call the data it is gone!
I have lots of different queries within my dbhelper class and on each activity I;m re initilizing the class so I can get at my function within the class.

I assume this is not the way to do it as it runs my oncreate again and wipes all my tables (or at least this is when it appears to be doing as I check the DB after I've tried calling data from it and it's empty!

I was under the impression the oncreate only ran once, but this is obviously not the case as it appears to be recreating my DB everytime and wiping my data!

Where are you meant to initialize the the dbhelper class and how do you stop it recreating the tables? I need the data to persist even when the app closes!

I'm confused!

If this doesn't make sense please ask specific questions on how I can clarify it!

UPDATE

I have found I can add

```<code>CREATE TABLE IF NOT EXISTS
</code>```

Which stops it recreating the tables, but it still doesn't seem right calling the oncreate every time..

答:
You could put a wrapper class around it?</p>

```<code>public class DbAdapter
{

  // database details
  private static final String DATABASE_NAME = "dbname";
  private static final int DATABASE_VERSION = 1;

  // where we're running
  private final Context mCtx;

  private static class DatabaseHelper extends SQLiteOpenHelper
  {
    DatabaseHelper(Context context)
    {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
      // your initial database create statements go here
      db.execSQL(DATABASE_CREATE);
    }

    // if you need to recreate the database, you just up the version number
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
      // drop commands for each table goes here
      db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
      onCreate(db);
    }
  }

  public DbAdapter(Context ctx)
  {
    this.mCtx = ctx;
  }

  public DbAdapter open() throws SQLException
  {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
  }

  public void close()
  {
    mDbHelper.close();
  }

  // other database methods can go here
}
</code>```

Body:
I am really struggling with using the SqlLite in my App;

I have set up a database helper class that extends from SQLiteOpenHelper

public class DatabaseHelper extends SQLiteOpenHelper {

In the OnCreate I am Creating about 6 tables:

public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE myTestTable (Id INTEGER PRIMARY KEY , "
            + "info TEXT," +
            + "TopLeft TEXT")); <-- example insert

}

When my App starts I am parsing some xml and entering the data into the table, and I have checked the database and all is in there and my tables created correctly.

When I go to call the data it is gone!
I have lots of different queries within my dbhelper class and on each activity I;m re initilizing the class so I can get at my function within the class.

I assume this is not the way to do it as it runs my oncreate again and wipes all my tables (or at least this is when it appears to be doing as I check the DB after I've tried calling data from it and it's empty!

I was under the impression the oncreate only ran once, but this is obviously not the case as it appears to be recreating my DB everytime and wiping my data!

Where are you meant to initialize the the dbhelper class and how do you stop it recreating the tables? I need the data to persist even when the app closes!

I'm confused!

If this doesn't make sense please ask specific questions on how I can clarify it!

UPDATE

I have found I can add

CREATE TABLE IF NOT EXISTS

Which stops it recreating the tables, but it still doesn't seem right calling the oncreate every time..

Body:
You could put a wrapper class around it?

public class DbAdapter
{

  // database details
  private static final String DATABASE_NAME = "dbname";
  private static final int DATABASE_VERSION = 1;

  // where we're running
  private final Context mCtx;

  private static class DatabaseHelper extends SQLiteOpenHelper
  {
    DatabaseHelper(Context context)
    {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
      // your initial database create statements go here
      db.execSQL(DATABASE_CREATE);
    }

    // if you need to recreate the database, you just up the version number
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
      // drop commands for each table goes here
      db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
      onCreate(db);
    }
  }

  public DbAdapter(Context ctx)
  {
    this.mCtx = ctx;
  }

  public DbAdapter open() throws SQLException
  {
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
  }

  public void close()
  {
    mDbHelper.close();
  }

  // other database methods can go here
}


来源: stackexchange

问:
javascript - if and or (||) statement
```<code>if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}
</code>```

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

答:
```<code>if (["/", "/yyy.asp", "zzzz.html", "/xxx.html"].includes(window.location.pathname)) {
  runSlideShow();
}
</code>```

or, full gangsta:

```<code>["/", "/yyy.asp", "zzzz.html", "/xxx.html"].includes(window.location.pathname) && runSlideShow();
</code>```

ContentLicense: CC BY-SA 4.0

Title: javascript - if and or (||) statement

Body:
if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

Body:
if (["/", "/yyy.asp", "zzzz.html", "/xxx.html"].includes(window.location.pathname)) {
  runSlideShow();
}

or, full gangsta:

["/", "/yyy.asp", "zzzz.html", "/xxx.html"].includes(window.location.pathname) && runSlideShow();


问:
Is there a way to avoid passing two generic parameter in my Extension method?
I have a class of type Installer where TModel has a constraint.
I want to create an extension method with the type signature :\

```<code>public static void DoRepetitiveStuff<TOtherObject, TModel>(this Installer<TModel> installer)
where TModel : class, IConstraint, new()
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoSomeStuff<TOtherObject>(c => { });
}
</code>```

the goal being that eventually I can call the function using a simple installer.DoRepetitiveStuff<TOtherObject>();

For some reason when I call that function on my other file. It complains there isn't any extension method that accept a Installer in existance... I need to use it with:

```<code>installer.DoRepetitiveStuff<TOtherObject, TModel>();
</code>```

Anyone knows why ?

答:
The C# compiler can't infer a partial generic signature. It's basically all or nothing. Why?

Let's say your code is accepted, and then you create a new method:

public static void DoRepetitiveStuff<TOtherObject>(this Installer installer)
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoOtherStuff();
   installer.DoSomeStuff<TOtherObject>(c => { });
}
```

Now, which method does your code call? Yours or this one? We can't know, because it's ambiguous.

To avoid this, either the compiler infers the full signature, or none at all.

As an alternative, you would need to introduce another class that can do the inference for you. However, at this point, it's actually more concise to just specify both generic types.

Body:
I have a class of type Installer where TModel has a constraint.
I want to create an extension method with the type signature :\

public static void DoRepetitiveStuff<TOtherObject, TModel>(this Installer<TModel> installer)
where TModel : class, IConstraint, new()
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoSomeStuff<TOtherObject>(c => { });
}

the goal being that eventually I can call the function using a simple installer.DoRepetitiveStuff<TOtherObject>();

For some reason when I call that function on my other file. It complains there isn't any extension method that accept a Installer in existance... I need to use it with:

installer.DoRepetitiveStuff<TOtherObject, TModel>();

Anyone knows why ?

Body:
The C# compiler can't infer a partial generic signature. It's basically all or nothing. Why?

Let's say your code is accepted, and then you create a new method:

public static void DoRepetitiveStuff<TOtherObject>(this Installer installer)
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoOtherStuff();
   installer.DoSomeStuff<TOtherObject>(c => { });
}

Now, which method does your code call? Yours or this one? We can't know, because it's ambiguous.

To avoid this, either the compiler infers the full signature, or none at all.

As an alternative, you would need to introduce another class that can do the inference for you. However, at this point, it's actually more concise to just specify both generic types.


问:
Flush message queue to prevent Message-based leak. But which HandlerThread to flush?
I have essentially the memory leak described here as detected by LeakCanary.

I am trying to solve this by using the "Plumber's Fix" in the above post which flushes the message queue with an empty message. The provided code sample flush message queue every time it becomes idle. I only need to flush the queue once, after my dialog gets dismissed:

```<code>public class ExampleDialogFragment extends AppCompatDialogFragment {

    public static ExampleDialogFragment newInstance() {
        return new ExampleDialogFragment();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        return new AlertDialog.Builder(getContext())
                .setPositiveButton(android.R.string.ok, (dialog, which) -> onClicked())
                .create();
    }

    private void onClicked() {
        if (getTargetFragment() instanceof Callbacks) {
            ((Callbacks) getTargetFragment()).onButtonClicked();
            flushStackLocalLeaks();
        }
    }

    private static void flushStackLocalLeaks() {
        final Handler handler = new Handler(Looper.myLooper());
        handler.post(() -> Looper.myQueue().addIdleHandler(() -> {
            Timber.d("Flushing on thread %s", Thread.currentThread().getName());
            handler.sendMessageDelayed(handler.obtainMessage(), 1000);
            return false; // we only want to flush once, not *every* 1000 mSec
        }));
    }

    public interface Callbacks {
        void onButtonClicked();
    }
}
</code>```

The problem I'm facing is that in the LeakCanary report, the HandlerThread at the root of the leak is never the thread I expect. Sometimes it's a ConnectivityThread, sometimes it's a HandlerThread, where mName = "queued-work-looper", other it's a HandlerThread used by my analytics library. In none of these cases is it the main thread. I would expect the message to be leaking from the main thread. So

why is this leak happening on a HandlerThread/ConnectivityThread other than the main thread?

how do I know which HandlerThread needs flushing?

答:
I filed the issue here in December: https://issuetracker.google.com/issues/146144484 .

The core problem is that every idle HandlerThread retains their last recycled Message.

Our current fix is to find new handler threads over time and set up a recurring flush:

```<code>import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit.SECONDS

object AndroidLeaks {

  /**
   * HandlerThread instances keep local reference to their last handled message after recycling it.
   * That message is obtained by a dialog which sets on an OnClickListener on it and then never
   * recycles it, expecting it to be garbage collected but it ends up being held by the HandlerThread.
   */
  fun flushHandlerThreads() {
    val executor = Executors.newSingleThreadScheduledExecutor()

    val flushedThreadIds = mutableSetOf<Int>()
    // Wait 2 seconds then look for handler threads every 3 seconds.
    executor.scheduleWithFixedDelay({
      val newHandlerThreadsById = findAllHandlerThreads()
          .mapNotNull { thread ->
            val threadId = thread.threadId
            if (threadId == -1 || threadId in flushedThreadIds) {
              null
            } else {
              threadId to thread
            }
          }
      flushedThreadIds += newHandlerThreadsById.map { it.first }
      newHandlerThreadsById
          .map { it.second }
          .forEach { handlerThread ->
            var scheduleFlush = true
            val flushHandler = Handler(handlerThread.looper)
            flushHandler.onEachIdle {
              if (scheduleFlush) {
                scheduleFlush = false
                // When the Handler thread becomes idle, we post a message to force it to move.
                // Source: https://developer.squareup.com/blog/a-small-leak-will-sink-a-great-ship/
                try {
                  flushHandler.postDelayed({
                    // Right after this postDelayed executes, the idle handler will likely be called
                    // again (if the queue is otherwise empty), so we'll need to schedule a flush
                    // again.
                    scheduleFlush = true
                  }, 1000)
                } catch (ignored: RuntimeException) {
                  // If the thread is quitting, posting to it will throw. There is no safe and atomic way
                  // to check if a thread is quitting first then post it it.
                }
              }
            }
          }
    }, 2, 3, SECONDS)
  }

  private fun Handler.onEachIdle(onIdle: () -> Unit) {
    try {
      // Unfortunately Looper.getQueue() is API 23. Looper.myQueue() is API 1.
      // So we have to post to the handler thread to be able to obtain the queue for that
      // thread from within that thread.
      post {
        Looper
            .myQueue()
            .addIdleHandler {
              onIdle()
              true
            }
      }
    } catch (ignored: RuntimeException) {
      // If the thread is quitting, posting to it will throw. There is no safe and atomic way
      // to check if a thread is quitting first then post it it.
    }
  }

  private fun findAllHandlerThreads(): List<HandlerThread> {
    // Based on https://stackoverflow.com/a/1323480
    var rootGroup = Thread.currentThread().threadGroup!!
    while (rootGroup.parent != null) rootGroup = rootGroup.parent
    var threads = arrayOfNulls<Thread>(rootGroup.activeCount())
    while (rootGroup.enumerate(threads, true) == threads.size) {
      threads = arrayOfNulls(threads.size * 2)
    }
    return threads.mapNotNull { if (it is HandlerThread) it else null }
  }
}
</code>```

Body:
I have essentially the memory leak described here as detected by LeakCanary.

I am trying to solve this by using the "Plumber's Fix" in the above post which flushes the message queue with an empty message. The provided code sample flush message queue every time it becomes idle. I only need to flush the queue once, after my dialog gets dismissed:

public class ExampleDialogFragment extends AppCompatDialogFragment {

    public static ExampleDialogFragment newInstance() {
        return new ExampleDialogFragment();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        return new AlertDialog.Builder(getContext())
                .setPositiveButton(android.R.string.ok, (dialog, which) -> onClicked())
                .create();
    }

    private void onClicked() {
        if (getTargetFragment() instanceof Callbacks) {
            ((Callbacks) getTargetFragment()).onButtonClicked();
            flushStackLocalLeaks();
        }
    }

    private static void flushStackLocalLeaks() {
        final Handler handler = new Handler(Looper.myLooper());
        handler.post(() -> Looper.myQueue().addIdleHandler(() -> {
            Timber.d("Flushing on thread %s", Thread.currentThread().getName());
            handler.sendMessageDelayed(handler.obtainMessage(), 1000);
            return false; // we only want to flush once, not *every* 1000 mSec
        }));
    }

    public interface Callbacks {
        void onButtonClicked();
    }
}

The problem I'm facing is that in the LeakCanary report, the HandlerThread at the root of the leak is never the thread I expect. Sometimes it's a ConnectivityThread, sometimes it's a HandlerThread, where mName = "queued-work-looper", other it's a HandlerThread used by my analytics library. In none of these cases is it the main thread. I would expect the message to be leaking from the main thread. So

why is this leak happening on a HandlerThread/ConnectivityThread other than the main thread?

how do I know which HandlerThread needs flushing?

Body:
I filed the issue here in December: https://issuetracker.google.com/issues/146144484 .

The core problem is that every idle HandlerThread retains their last recycled Message.

Our current fix is to find new handler threads over time and set up a recurring flush:

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit.SECONDS

object AndroidLeaks {

  /**
   * HandlerThread instances keep local reference to their last handled message after recycling it.
   * That message is obtained by a dialog which sets on an OnClickListener on it and then never
   * recycles it, expecting it to be garbage collected but it ends up being held by the HandlerThread.
   */
  fun flushHandlerThreads() {
    val executor = Executors.newSingleThreadScheduledExecutor()

    val flushedThreadIds = mutableSetOf<Int>()
    // Wait 2 seconds then look for handler threads every 3 seconds.
    executor.scheduleWithFixedDelay({
      val newHandlerThreadsById = findAllHandlerThreads()
          .mapNotNull { thread ->
            val threadId = thread.threadId
            if (threadId == -1 || threadId in flushedThreadIds) {
              null
            } else {
              threadId to thread
            }
          }
      flushedThreadIds += newHandlerThreadsById.map { it.first }
      newHandlerThreadsById
          .map { it.second }
          .forEach { handlerThread ->
            var scheduleFlush = true
            val flushHandler = Handler(handlerThread.looper)
            flushHandler.onEachIdle {
              if (scheduleFlush) {
                scheduleFlush = false
                // When the Handler thread becomes idle, we post a message to force it to move.
                // Source: https://developer.squareup.com/blog/a-small-leak-will-sink-a-great-ship/
                try {
                  flushHandler.postDelayed({
                    // Right after this postDelayed executes, the idle handler will likely be called
                    // again (if the queue is otherwise empty), so we'll need to schedule a flush
                    // again.
                    scheduleFlush = true
                  }, 1000)
                } catch (ignored: RuntimeException) {
                  // If the thread is quitting, posting to it will throw. There is no safe and atomic way
                  // to check if a thread is quitting first then post it it.
                }
              }
            }
          }
    }, 2, 3, SECONDS)
  }

  private fun Handler.onEachIdle(onIdle: () -> Unit) {
    try {
      // Unfortunately Looper.getQueue() is API 23. Looper.myQueue() is API 1.
      // So we have to post to the handler thread to be able to obtain the queue for that
      // thread from within that thread.
      post {
        Looper
            .myQueue()
            .addIdleHandler {
              onIdle()
              true
            }
      }
    } catch (ignored: RuntimeException) {
      // If the thread is quitting, posting to it will throw. There is no safe and atomic way
      // to check if a thread is quitting first then post it it.
    }
  }

  private fun findAllHandlerThreads(): List<HandlerThread> {
    // Based on https://stackoverflow.com/a/1323480
    var rootGroup = Thread.currentThread().threadGroup!!
    while (rootGroup.parent != null) rootGroup = rootGroup.parent
    var threads = arrayOfNulls<Thread>(rootGroup.activeCount())
    while (rootGroup.enumerate(threads, true) == threads.size) {
      threads = arrayOfNulls(threads.size * 2)
    }
    return threads.mapNotNull { if (it is HandlerThread) it else null }
  }
}


问:
Starting a web request when an nfc sticker is detected
Is there an app which calls a definable URL when a NFC sticker is detected? I want to put different stickers on my desk and when I place my phone on one of the stickers a specific URL should be call:

If StickerA is detectd call https://www.myserver.com/?val=a

If StickerB is detectd call https://www.myserver.com/?val=b

If StickerC is detectd call https://www.myserver.com/?val=c

etc.

Is this possible with android without activating the phone and is there a an existing app for that task?

答:
you can write unique URL in every "sticker" or nfc tag by many Android App you can try NFC tools, then when you touch your Android device it will open the URL.

without activiating the Android device you will not be able to communicate with NFC tag*.

*you could with rooted device and you need to write the app by your self.


问:
Inserting datas for a specified date range in django
Please lemme know , how to add datas for all days in an year or more in django. Let's say i want to add a vechicle which is available for all days. How can i store this in mysql?, Later whenever search for that vehicles, it should display , AVAILABLE ON EVERYDAY!. I think you guys understand the question! Please help me.

Thanks

答:
You can take boolean field of Django model and if the vehicle is for all days then you have to save True in that Django model field otherwise it will store false.

When you get the data from sql and you will get True value of that field then that vehicle is available for all days.


答:
There is no reason you shouldn't be able to have 4 conditional checks in a single if statement.</p>

```<code>if (window.location.pathname=="/" || window.location.pathname=="/yyy.asp" || window.location.pathname=="zzzz.html" || window.location.pathname=="/xxx.html") {
  runSlideShow();
}
</code>```

Title: javascript - if and or (||) statement

Body:
There is no reason you shouldn't be able to have 4 conditional checks in a single if statement.

if (window.location.pathname=="/" || window.location.pathname=="/yyy.asp" || window.location.pathname=="zzzz.html" || window.location.pathname=="/xxx.html") {
  runSlideShow();
}


问:
Grails i18 message properties
I want to change the default message for typemismatch.java.math.BigDecimal in i18 message properties file for different properties.

In the documentation it says, use typeMismatch.$className.$propertyName to customize but that does not work for me.

Did anyone come across this issue. Any help is appreciated.

答:
For a property foo, the following should override the default message:

```<code>typeMismatch.java.math.BigDecimal.foo=Property {0} must be a valid number
</code>```

ContentLicense: CC BY-SA 3.0

Title: Grails i18 message properties

Body:
For a property foo, the following should override the default message:

typeMismatch.java.math.BigDecimal.foo=Property {0} must be a valid number


问:
Checking some columns for specific values before insert/update using a trigger
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

```<code>Foo {
    Url
}
</code>```

Here is the algorithm

```<code>Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success
</code>```

答:
A unique constraint wouldn't do what you want but you could create an instead of trigger with content something like as:</p>

```<code>Create TRIGGER [dbo].[Trig_Insert_XXX]
ON [dbo].[XXX]
INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;
  INSERT INTO xxx ([url], field1, field2, fieldN)
  SELECT [url], field1, field2, fieldN
  FROM inserted i
  WHERE i.url = 'hello' OR NOT EXISTS (SELECT * FROM xxx t2 WHERE t2.url = i.url);
END;
</code>```

Body:
I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

Foo {
    Url
}

Here is the algorithm

Before update insert
if new value of Url is not "hello1" o "hello 2"
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success

Body:
A unique constraint wouldn't do what you want but you could create an instead of trigger with content something like as:

Create TRIGGER [dbo].[Trig_Insert_XXX]
ON [dbo].[XXX]
INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;
  INSERT INTO xxx ([url], field1, field2, fieldN)
  SELECT [url], field1, field2, fieldN
  FROM inserted i
  WHERE i.url = 'hello' OR NOT EXISTS (SELECT * FROM xxx t2 WHERE t2.url = i.url);
END;


问:
JavaScript: implement let-working with var
So I have a code that clone let-behavior. But I don't undestand how and why it is working. Can someone explain it?</p>

```<code>(function() {
  var a = 2;
})()
</code>```

答:
let is scoped to the block it appears in.

var is scoped to the function it appears in.

By replacing a block with a function (which is immediately invoked) var is scoped to the same lines of code as let would be.

Body:
So I have a code that clone let-behavior. But I don't undestand how and why it is working. Can someone explain it?

(function() {
  var a = 2;
})()


问:
Where do the settings in my Git configuration come from?
I've noticed that I have two listings for core.autocrlf when I run git config -l

```<code>$ git config -l
core.symlinks=false
core.autocrlf=false
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=name
user.email=email@example.com
core.autocrlf=true
</code>```

Those last three (from user.name down) are the only ones in my C:\users\username\.gitconfig file. Where are all of the other ones coming from?  Why is core.autocrlf listed twice?

This is with MSysGit 1.8.3, and I also have Sourcetree installed (Windows 7). In Sourcetree I have unchecked the "Allow Sourcetree to modify your global Git config files"

答:
In addition of git config -l --show-origin, that I presented here, with git 2.8 (March 2016), you now have, with Git 2.26 (Q1 2020)

```<code>git config -l --show-scope

# you can combine both options:
git config -l --show-origin --show-scope
</code>```

git config learned to show in which "scope", in addition to in which file, each config setting comes from.

See commit 145d59f, commit 9a83d08, commit e37efa4, commit 5c105a8, commit 6766e41, commit 6dc905d, commit a5cb420 (10 Feb 2020), and commit 417be08, commit 3de7ee3, commit 329e6ec (24 Jan 2020) by Matthew Rogers (ROGERSM94).

(Merged by Junio C Hamano -- gitster -- in commit 5d55554, 17 Feb 2020)

config: add '--show-scope' to print the scope of a config value

Signed-off-by: Matthew Rogers

When a user queries config values with --show-origin, often it's difficult to determine what the actual "scope" (local, global, etc.) of a given value is based on just the origin file.

Teach 'git config' the '--show-scope' option to print the scope of all displayed config values.

Note that we should never see anything of "submodule" scope as that is only ever used by submodule-config.c when parsing the '.gitmodules' file.

Example:

```<code>git config -l --show-scope

global  user.global=true
global  user.override=global
global  include.path=$INCLUDE_DIR/absolute.include
global  user.absolute=include
local   user.local=true
local   user.override=local
local   include.path=../include/relative.include
local   user.relative=include
</code>```

That allows you to quickly distinguish between:

Protected configuration: 'system', 'global', and 'command' scopes.

standard configuration: local to the repository.

This is introduced with Git 2.38 (Q3 2022):

See commit 8d1a744, commit 6061601, commit 5b3c650, commit 779ea93, commit 5f5af37 (14 Jul 2022) by Glen Choo (chooglen).

(Merged by Junio C Hamano -- gitster -- in commit 18bbc79, 22 Jul 2022)

Documentation: define protected configuration

Signed-off-by: Glen Choo

For security reasons, there are config variables that are only trusted when they are specified in certain configuration scopes, which are sometimes referred to on-list as 'protected configuration' (as in this thread).

A future commit will introduce another such variable (safe.bareRepository), so let's define our terms so that we can have consistent documentation and implementation.

In our documentation, define 'protected configuration' as the system, global and command config scopes.

As a shorthand, I will refer to variables that are only respected in protected configuration as 'protected configuration only', but this term is not used in the documentation.

This definition of protected configuration is based on whether or not Git can reasonably protect the user by ignoring the configuration scope:

System, global and command line config are considered protected because an attacker who has control over any of those can do plenty of harm without Git, so we gain very little by ignoring those scopes.

On the other hand, local (and similarly, worktree) config are not considered protected because it is relatively easy for an attacker to control local config, e.g.:

On some shared user environments, a non-admin attacker can create a repository high up the directory hierarchy (e.g. C:\.git on Windows), and a user may accidentally use it when their PS1 automatically invokes "git" commands.

safe.directory prevents attacks of this form by making sure that the user intended to use the shared repository.

It obviously shouldn't be read from the repository, because that would end up trusting the repository that Git was supposed to reject.

"git upload-pack"(man) is expected to run in repositories that may not be controlled by the user.

We cannot ignore all config in that repository (because "git upload-pack" would fail), but we can limit the risks by ignoring uploadpack.packObjectsHook.

Only uploadpack.packObjectsHook is 'protected configuration only'.

The following variables are intentionally excluded:

safe.directory should be 'protected configuration only', but it does not technically fit the definition because it is not respected in the "command" scope.

A future commit will fix this.

trace2.* happens to read the same scopes as safe.directory because they share an implementation.

However, this is not for security reasons; it is because we want to start tracing so early that repository-level config and "-c" are not available.

This requirement is unique to trace2.*, so it does not makes sense for protected configuration to be subject to the same constraints.

git config now includes in its man page:

Protected configuration

Protected configuration refers to the 'system', 'global', and 'command' scopes.

For security reasons, certain options are only respected when they are specified in protected configuration, and ignored otherwise.

Git treats these scopes as if they are controlled by the user or a trusted administrator. This is because an attacker who controls these scopes can do substantial harm without using Git, so it is assumed that the user's environment protects these scopes against attackers.

With Git 2.39 (Q4 2022), allow configuration files in "protected" scopes to include other configuration files.

See commit ecec57b (13 Oct 2022) by Glen Choo (chooglen).

(Merged by Junio C Hamano -- gitster -- in commit 777f548, 25 Oct 2022)

config: respect includes in protected config

Signed-off-by: Glen Choo

Protected config is implemented by reading a fixed set of paths, which ignores config [include]-s.

Replace this implementation with a call to config_with_options(), which handles [include]-s and saves us from duplicating the logic of 1) identifying which paths to read and 2) reading command line config.

As a result, git_configset_add_parameters() is unused, so remove it.

It was introduced alongside protected config in 5b3c650 ("config: learn git_protected_config()", 2022-07-14, Git v2.38.0-rc0 -- merge listed in batch #6) as a way to handle command line config.

Body:
I've noticed that I have two listings for core.autocrlf when I run git config -l

$ git config -l
core.symlinks=false
core.autocrlf=false
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=name
user.email=email@example.com
core.autocrlf=true

Those last three (from user.name down) are the only ones in my C:\users\username\.gitconfig file. Where are all of the other ones coming from?  Why is core.autocrlf listed twice?

This is with MSysGit 1.8.3, and I also have Sourcetree installed (Windows 7). In Sourcetree I have unchecked the "Allow Sourcetree to modify your global Git config files"

Body:
In addition of git config -l --show-origin, that I presented here, with git 2.8 (March 2016), you now have, with Git 2.26 (Q1 2020)

git config -l --show-scope

# you can combine both options:
git config -l --show-origin --show-scope

git config learned to show in which "scope", in addition to in which file, each config setting comes from.

See commit 145d59f, commit 9a83d08, commit e37efa4, commit 5c105a8, commit 6766e41, commit 6dc905d, commit a5cb420 (10 Feb 2020), and commit 417be08, commit 3de7ee3, commit 329e6ec (24 Jan 2020) by Matthew Rogers (ROGERSM94).

(Merged by Junio C Hamano -- gitster -- in commit 5d55554, 17 Feb 2020)

config: add '--show-scope' to print the scope of a config value

Signed-off-by: Matthew Rogers

When a user queries config values with --show-origin, often it's difficult to determine what the actual "scope" (local, global, etc.) of a given value is based on just the origin file.

Teach 'git config' the '--show-scope' option to print the scope of all displayed config values.

Note that we should never see anything of "submodule" scope as that is only ever used by submodule-config.c when parsing the '.gitmodules' file.

Example:

git config -l --show-scope

global  user.global=true
global  user.override=global
global  include.path=$INCLUDE_DIR/absolute.include
global  user.absolute=include
local   user.local=true
local   user.override=local
local   include.path=../include/relative.include
local   user.relative=include

That allows you to quickly distinguish between:

Protected configuration: 'system', 'global', and 'command' scopes.

standard configuration: local to the repository.

This is introduced with Git 2.38 (Q3 2022):

See commit 8d1a744, commit 6061601, commit 5b3c650, commit 779ea93, commit 5f5af37 (14 Jul 2022) by Glen Choo (chooglen).

(Merged by Junio C Hamano -- gitster -- in commit 18bbc79, 22 Jul 2022)

Documentation: define protected configuration

Signed-off-by: Glen Choo

For security reasons, there are config variables that are only trusted when they are specified in certain configuration scopes, which are sometimes referred to on-list as 'protected configuration' (as in this thread).

A future commit will introduce another such variable (safe.bareRepository), so let's define our terms so that we can have consistent documentation and implementation.

In our documentation, define 'protected configuration' as the system, global and command config scopes.

As a shorthand, I will refer to variables that are only respected in protected configuration as 'protected configuration only', but this term is not used in the documentation.

This definition of protected configuration is based on whether or not Git can reasonably protect the user by ignoring the configuration scope:

System, global and command line config are considered protected because an attacker who has control over any of those can do plenty of harm without Git, so we gain very little by ignoring those scopes.

On the other hand, local (and similarly, worktree) config are not considered protected because it is relatively easy for an attacker to control local config, e.g.:

On some shared user environments, a non-admin attacker can create a repository high up the directory hierarchy (e.g. C:\.git on Windows), and a user may accidentally use it when their PS1 automatically invokes "git" commands.

safe.directory prevents attacks of this form by making sure that the user intended to use the shared repository.

It obviously shouldn't be read from the repository, because that would end up trusting the repository that Git was supposed to reject.

"git upload-pack"(man) is expected to run in repositories that may not be controlled by the user.

We cannot ignore all config in that repository (because "git upload-pack" would fail), but we can limit the risks by ignoring uploadpack.packObjectsHook.

Only uploadpack.packObjectsHook is 'protected configuration only'.

The following variables are intentionally excluded:

safe.directory should be 'protected configuration only', but it does not technically fit the definition because it is not respected in the "command" scope.

A future commit will fix this.

trace2.* happens to read the same scopes as safe.directory because they share an implementation.

However, this is not for security reasons; it is because we want to start tracing so early that repository-level config and "-c" are not available.

This requirement is unique to trace2.*, so it does not makes sense for protected configuration to be subject to the same constraints.

git config now includes in its man page:

Protected configuration

Protected configuration refers to the 'system', 'global', and 'command' scopes.

For security reasons, certain options are only respected when they are specified in protected configuration, and ignored otherwise.

Git treats these scopes as if they are controlled by the user or a trusted administrator. This is because an attacker who controls these scopes can do substantial harm without using Git, so it is assumed that the user's environment protects these scopes against attackers.

With Git 2.39 (Q4 2022), allow configuration files in "protected" scopes to include other configuration files.

See commit ecec57b (13 Oct 2022) by Glen Choo (chooglen).

(Merged by Junio C Hamano -- gitster -- in commit 777f548, 25 Oct 2022)

config: respect includes in protected config

Signed-off-by: Glen Choo

Protected config is implemented by reading a fixed set of paths, which ignores config [include]-s.

Replace this implementation with a call to config_with_options(), which handles [include]-s and saves us from duplicating the logic of 1) identifying which paths to read and 2) reading command line config.

As a result, git_configset_add_parameters() is unused, so remove it.

It was introduced alongside protected config in 5b3c650 ("config: learn git_protected_config()", 2022-07-14, Git v2.38.0-rc0 -- merge listed in batch #6) as a way to handle command line config.


问:
Dialogflow fulfilment using request-promise-native : unable to parse response
I'm performing a REST API call in Salesforce from DialogFlow fulfilment but I just can not read the JSON response. I'd like to access some fields of the JSON response esp CaseNumber. The query can return 0 or several records.

Could someone help me just to parse the returned response? Thanks!

```<code>  function ticket(agent) {
    agent.add('Looking for ticket --> ' + agent.parameters.numero);
    var rpTicket = require('request-promise-native');
    var optionsTicket = {
    method: 'GET',
    uri: "https://eu26.salesforce.com/services/data/v44.0/query?q=select CaseNumber from Case where ContactID='XXXXXXX'+order+by+CreatedDate+desc",
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer XXXXXXXXXX'
     },
    json: true
    };

    return rpTicket( optionsTicket )
    .then( body => {
        console.log( 'Ok here is the JSON --> ' + util.inspect(body,false,null)); // I can read the JSON response in the Google Log console so I m fine
        var myTickets = JSON.parse(util.inspect(body,false,null));
        // or
        //var myTickets = JSON.parse(body);
        console.log( 'Ok here is the # of tickets --> ' + myTickets.count); // Throws an error
        return Promise.resolve( true );
    })
    .catch( err => {
        // You should also return a message here of some sort
        console.log( 'Error ... --> ' + err);
        return Promise.resolve( true );
    });
  }
</code>```

答:
Since you have json: true in your request-promise configuration, the body that is returned is already a JavaScript object. So you do not need to call JSON.parse(body).

You should just be able to read the value you want with body.count (assuming count is a field that is returned).

Body:
I'm performing a REST API call in Salesforce from DialogFlow fulfilment but I just can not read the JSON response. I'd like to access some fields of the JSON response esp CaseNumber. The query can return 0 or several records.

Could someone help me just to parse the returned response? Thanks!

  function ticket(agent) {
    agent.add('Looking for ticket --> ' + agent.parameters.numero);
    var rpTicket = require('request-promise-native');
    var optionsTicket = {
    method: 'GET',
    uri: "https://eu26.salesforce.com/services/data/v44.0/query?q=select CaseNumber from Case where ContactID='XXXXXXX'+order+by+CreatedDate+desc",
    headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer XXXXXXXXXX'
     },
    json: true
    };

    return rpTicket( optionsTicket )
    .then( body => {
        console.log( 'Ok here is the JSON --> ' + util.inspect(body,false,null)); // I can read the JSON response in the Google Log console so I m fine
        var myTickets = JSON.parse(util.inspect(body,false,null));
        // or
        //var myTickets = JSON.parse(body);
        console.log( 'Ok here is the # of tickets --> ' + myTickets.count); // Throws an error
        return Promise.resolve( true );
    })
    .catch( err => {
        // You should also return a message here of some sort
        console.log( 'Error ... --> ' + err);
        return Promise.resolve( true );
    });
  }


问:
JavaScript Sequencer MIDI file timing resolution (PPQN)
I read a lot about MIDI resolution and studied some codes like Tone.js and heartbeat. But I don't understand why there are different Pulses Per Quarter Note (PPQN) values and what the effect it has on playing notes. When I have 960 PPQN so this means 1 quarter note has 960 ticks, 1 eight note 480 ticks, ect. And if I understand it correctly, the delta time is just a relative value.

What I don't understand right is, what should the PPQN when I play notes in JavScript, and when I set the PPQN why it should have this value? For example I use the WebAudio API for playing notes:

```<code>function nextNote() {
  var quarterBeat = 60.0/tempo;
  nextNoteDuration = nextNoteDuration + (quarterBeat/32);
  currentNote++;
}
</code>```

This way I can play different notes durations. Now when I read the MIDI file, should I just compare the delta time and convert it to my sequencers current playback? For example when I read a MIDI file with this values:

```<code>Tempo = 120
PQN = 960
4 Quarter Notes
</code>```

I read the MIDI file, save the notes in an array (assume the delta time is for each note a 1/4)

```<code>duration = [quarterNote, quarterNote, quarterNote, quarterNote]
</code>```

And play the notes:

```<code>while (nextNoteDuration < audioContext.currentTime) {
  if (duration[i] %32 == 0) playNote(currentNote, nextNoteDuration);
  nextNote();
  i++;
}
</code>```

Should I use PPQN only when exporting a MIDI file? If so, in relation to what should I set the PPQN? I hope someone can explain this to me in more detail.

答:
PPQ is about resolution. More specifically about time resolution.

what should (be?) the PPQN when I play notes in JavScript, and when I set
  the PPQN why it should have this value?

When your program plays notes, it may use whatever time units you want or need, for instance milliseconds, nanoseconds, movie frames, ticks. Absolute wall clock or relative times. It depends on your sequencer capabilities and your software features. It is only required to choose a PPQ value when storing MIDI sequences as MIDI files. Of course you need to be able to convert time units when reading/storing MIDI files.

Now when I read the MIDI file, should I just compare the delta time
  and convert it to my sequencers current playback?

Of course, if internally your music events use a different time representation, then you need to be able to translate the delta times from the MIDI file to your internal representation.

You are only asking about PPQ, but this value is found only once, at the MIDI file header. The tempo events in contrast may occur multiple times along the file, and it affects to the translation of the next delta times into wall clock times until the next tempo event. If your sequencer/player allows the user to change/add  tempo events, it would be a good idea to use relative units instead of wall clock units for internal time representation (or both).

Should I use PPQN only when exporting a MIDI file? If so, in relation
  to what should I set the PPQN?

Yes, you need to choose a suitable value for PPQ when you export a MIDI file. If your internal time units are relative (as most sequencers do) then use your internal unit resolution for PPQ. If you convert from wall clock units to delta times, then you need to choose a resolution which your translation loses less details (by quantization). Higher values are better in this sense. Rosegarden stores MIDI files always with 960 PPQ. In contrast, Steinberg's Cubase used 480. I remember using Cakewalk a long time ago having only 120 PPQ, but later versions allowed this value to be changed as a  configuration setting. In general you need to accommodate not only all music figures shorter than quarter, including subdivisions like triplets, etc. but you also need to take into account effects like swing that are based on fine time adjustments.

Body:
I read a lot about MIDI resolution and studied some codes like Tone.js and heartbeat. But I don't understand why there are different Pulses Per Quarter Note (PPQN) values and what the effect it has on playing notes. When I have 960 PPQN so this means 1 quarter note has 960 ticks, 1 eight note 480 ticks, ect. And if I understand it correctly, the delta time is just a relative value.

What I don't understand right is, what should the PPQN when I play notes in JavScript, and when I set the PPQN why it should have this value? For example I use the WebAudio API for playing notes:

function nextNote() {
  var quarterBeat = 60.0/tempo;
  nextNoteDuration = nextNoteDuration + (quarterBeat/32);
  currentNote++;
}

This way I can play different notes durations. Now when I read the MIDI file, should I just compare the delta time and convert it to my sequencers current playback? For example when I read a MIDI file with this values:

Tempo = 120
PQN = 960
4 Quarter Notes

I read the MIDI file, save the notes in an array (assume the delta time is for each note a 1/4)

duration = [quarterNote, quarterNote, quarterNote, quarterNote]

And play the notes:

while (nextNoteDuration < audioContext.currentTime) {
  if (duration[i] %32 == 0) playNote(currentNote, nextNoteDuration);
  nextNote();
  i++;
}

Should I use PPQN only when exporting a MIDI file? If so, in relation to what should I set the PPQN? I hope someone can explain this to me in more detail.


问:
'flask instance' does not have attribute 'record' error
I have a project where I am trying to build an api using flask and python with the following structure:

```<code>graph:
    -app.py
    -server.py
    -apis:
        -__init__.py
        -users.py
        -transaction_functions.py
        -neo4j_ops.py
</code>```

In the server.py file I am trying to add authentification to the endpoints of my api which are coded in the users.py file. My server.py file looks like this:

```<code>import json
from six.moves.urllib.request import urlopen
from functools import wraps

from flask import Flask, request, jsonify, _request_ctx_stack
from flask_cors import cross_origin
from jose import jwt

AUTH0_DOMAIN = 'mydomain.eu'
API_AUDIENCE = 'https://my_audience.com'
ALGORITHMS = ["RS256"]

APP = Flask(__name__)

# Error handler
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code

@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    #some code

# Format error response and append status code
def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header
    """
    # some code
    return token

def requires_auth(f):
    """Determines if the Access Token is valid
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        #some code
    return decorated

def requires_scope(required_scope):
    """Determines if the required scope is present in the Access Token
    Args:
        required_scope (str): The scope required to access the resource
    """
    #some code
</code>```

And I keep getting this error:

```<code>Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 183, in init_app
    app.record(self._deferred_blueprint_init)
AttributeError: 'Flask' object has no attribute 'record'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    api.init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 186, in init_app
    self._init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 204, in _init_app
    self._register_view(app, resource, *urls, **kwargs)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 282, in _register_view
    resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'
</code>```

As you can see the result of this printstack is not really useful at all since none of these calls comes from any of my files.
The only file involved in that is app.py and it looks like this:

```<code>from flask import Flask
from flask_restplus import Api
from apis import api
import config
import os

app = Flask(__name__)

api.init_app(app)#traceback comes from here.
app.run(host='0.0.0.0', port=8080)

</code>```

The apis/__init__.py file looks like this:

```<code>from flask_restplus import Api, fields
from .users import api as users
from flask import Flask

api = Api(
    title='Graph Api',
    version='0.2',
)

api.add_namespace(users)

</code>```

Any idea of what the issue is?
If I import app (the flask instance) from app.py into server.py and use that flask instance created in app rather than creating a new whole flask instance in server.py somehow the error goes away, but the issue is that I would then create a circular call of dependencies, so I cant do that.

答: The problem stopped existing as soon as I went back to the version of the code of before adding the server.py file, and then I added it again. I have no clue of what the issue was though as the code is actually the same.

Body:
I have a project where I am trying to build an api using flask and python with the following structure:

graph:
    -app.py
    -server.py
    -apis:
        -__init__.py
        -users.py
        -transaction_functions.py
        -neo4j_ops.py

In the server.py file I am trying to add authentification to the endpoints of my api which are coded in the users.py file. My server.py file looks like this:

import json
from six.moves.urllib.request import urlopen
from functools import wraps

from flask import Flask, request, jsonify, _request_ctx_stack
from flask_cors import cross_origin
from jose import jwt

AUTH0_DOMAIN = 'mydomain.eu'
API_AUDIENCE = 'https://my_audience.com'
ALGORITHMS = ["RS256"]

APP = Flask(__name__)

# Error handler
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code

@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    #some code

# Format error response and append status code
def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header
    """
    # some code
    return token

def requires_auth(f):
    """Determines if the Access Token is valid
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        #some code
    return decorated

def requires_scope(required_scope):
    """Determines if the required scope is present in the Access Token
    Args:
        required_scope (str): The scope required to access the resource
    """
    #some code

And I keep getting this error:

Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 183, in init_app
    app.record(self._deferred_blueprint_init)
AttributeError: 'Flask' object has no attribute 'record'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "app.py", line 16, in <module>
    api.init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 186, in init_app
    self._init_app(app)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 204, in _init_app
    self._register_view(app, resource, *urls, **kwargs)
  File "C:\Python37\lib\site-packages\flask_restplus\api.py", line 282, in _register_view
    resource_func = self.output(resource.as_view(endpoint, self, *resource_class_args,
AttributeError: 'function' object has no attribute 'as_view'

As you can see the result of this printstack is not really useful at all since none of these calls comes from any of my files.
The only file involved in that is app.py and it looks like this:

from flask import Flask
from flask_restplus import Api
from apis import api
import config
import os

app = Flask(__name__)

api.init_app(app)#traceback comes from here.
app.run(host='0.0.0.0', port=8080)

The apis/__init__.py file looks like this:

from flask_restplus import Api, fields
from .users import api as users
from flask import Flask

api = Api(
    title='Graph Api',
    version='0.2',
)

api.add_namespace(users)

Any idea of what the issue is?
If I import app (the flask instance) from app.py into server.py and use that flask instance created in app rather than creating a new whole flask instance in server.py somehow the error goes away, but the issue is that I would then create a circular call of dependencies, so I cant do that.


问:
using pandas, extract data from long format df and add it to wide format df
I have two dataframes, df1 and df2. df1 has repeat observations arranged in wide format, and df2 in long format.

```<code>import pandas as pd
df1 = pd.DataFrame({"ID":[1,2,3],"colA_1":[1,2,3],"date1":["1.1.2001", "2.1.2001","3.1.2001"],"colA_2":[4,5,6],"date2":["1.1.2002", "2.1.2002","3.1.2002"]})
df2 = pd.DataFrame({"ID":[1,1,2,2,3,3],"col1":[1,1.5,2,2.5,3,3.5],"date":["1.1.2001", "1.1.2002","2.1.2001","2.1.2002","3.1.2001","3.1.2002"], "col3":[11,12,13,14,15,16],"col4":[21,22,23,24,25,26]})

</code>```

df1 looks like:

```<code>   ID  colA_1     date1  colA_2     date2
0   1       1  1.1.2001       4  1.1.2002
1   2       2  2.1.2001       5  2.1.2002
2   3       3  3.1.2001       6  3.1.2002
</code>```

df2 looks like:

```<code>   ID  col1     date1  col3  col4
0   1   1.0  1.1.2001    11    21
1   1   1.5  1.1.2002    12    22
2   2   2.0  2.1.2001    13    23
3   2   2.5  2.1.2002    14    24
4   3   3.0  3.1.2001    15    25
5   3   3.5  3.1.2002    16    26
6   3   4.0  4.1.2002    17    27

</code>```

I want to take a given column from df2, "col3", and then:

(1) if the columns "ID" and "date" in df2 match with the columns "ID" and "date1" in df1, I want to put the value in a new column in df1 called "colB_1".

(2) else if the columns "ID" and "date" in df2 match with the columns "ID" and "date2" in df1, I want to put the value in a new column in df1 called "colB_2".

(3) else if the columns "ID" and "date" in df2 have no match with either ("ID" and "date1") or ("ID" and "date2"), I want to ignore these rows.

So, the output of this output dataframe, df3, should look like this:

```<code>   ID  colA_1     date1  colA_2     date2  colB_1  colB_2
0   1       1  1.1.2001       4  1.1.2002      11      12
1   2       2  2.1.2001       5  2.1.2002      13      14
2   3       3  3.1.2001       6  3.1.2002      15      16

</code>```

What is the best way to do this?

I found this link, but the answer doesn't work for my case. I would like a really explicit way to specify column matching. I think it's possible that df.mask might be able to help me, but I am not sure how to implement it.

e.g.: the following code

```<code>df3 = df1.copy()
df3["colB_1"] = ""
df3["colB_2"] = ""
filter1 = (df1["ID"] == df2["ID"]) & (df1["date1"] == df2["date"])
filter2 = (df1["ID"] == df2["ID"]) & (df1["date2"] == df2["date"])
df3["colB_1"] = df.mask(filter1, other=df2["col3"])
df3["colB_2"] = df.mask(filter2, other=df2["col3"])

</code>```

gives the error

```<code>ValueError: Can only compare identically-labeled Series objects
</code>```

I asked this question previously, and it was marked as closed; my question was marked as a duplicate of this one. However, this is not the case. The answers in the linked question suggest the use of either map or df.merge. Map does not work with multiple conditions (in my case, ID and date). And df.merge (the answer given for matching multiple columns) does not work in my case when one of the column names in df1 and df2 that are to be merged are different ("date" and "date1", for example).

For example, the below code:

```<code>df3 = df1.merge(df2[["ID","date","col3"]], on=['ID','date1'], how='left')

</code>```

fails with a Key Error.

Also noteworthy is that I will be dealing with many different files, with many different column naming schemes, and I will need a different subset each time. This is why I would like an answer that explicitly names the columns and conditions.

Any help with this would be much appreciated.

答:
You can the pd.wide_to_long after replacing the underscore , this will unpivot the dataframe which you can use to merge with df2 and then pivot back using unstack:

```<code>m =df1.rename(columns=lambda x: x.replace('_',''))
unpiv = pd.wide_to_long(m,['colA','date'],'ID','v').reset_index()

merge_piv = (unpiv.merge(df2[['ID','date','col3']],on=['ID','date'],how='left')
     .set_index(['ID','v'])['col3'].unstack().add_prefix('colB_'))

final = df1.merge(merge_piv,left_on='ID',right_index=True)
</code>```

```<code>   ID  colA_1     date1  colA_2     date2  colB_1  colB_2
0   1       1  1.1.2001       4  1.1.2002      11      12
1   2       2  2.1.2001       5  2.1.2002      13      14
2   3       3  3.1.2001       6  3.1.2002      15      16
</code>```

Body:
I have two dataframes, df1 and df2. df1 has repeat observations arranged in wide format, and df2 in long format.

import pandas as pd
df1 = pd.DataFrame({"ID":[1,2,3],"colA_1":[1,2,3],"date1":["1.1.2001", "2.1.2001","3.1.2001"],"colA_2":[4,5,6],"date2":["1.1.2002", "2.1.2002","3.1.2002"]})
df2 = pd.DataFrame({"ID":[1,1,2,2,3,3],"col1":[1,1.5,2,2.5,3,3.5],"date":["1.1.2001", "1.1.2002","2.1.2001","2.1.2002","3.1.2001","3.1.2002"], "col3":[11,12,13,14,15,16],"col4":[21,22,23,24,25,26]})

df1 looks like:

   ID  colA_1     date1  colA_2     date2
0   1       1  1.1.2001       4  1.1.2002
1   2       2  2.1.2001       5  2.1.2002
2   3       3  3.1.2001       6  3.1.2002

df2 looks like:

   ID  col1     date1  col3  col4
0   1   1.0  1.1.2001    11    21
1   1   1.5  1.1.2002    12    22
2   2   2.0  2.1.2001    13    23
3   2   2.5  2.1.2002    14    24
4   3   3.0  3.1.2001    15    25
5   3   3.5  3.1.2002    16    26
6   3   4.0  4.1.2002    17    27

I want to take a given column from df2, "col3", and then:

(1) if the columns "ID" and "date" in df2 match with the columns "ID" and "date1" in df1, I want to put the value in a new column in df1 called "colB_1".

(2) else if the columns "ID" and "date" in df2 match with the columns "ID" and "date2" in df1, I want to put the value in a new column in df1 called "colB_2".

(3) else if the columns "ID" and "date" in df2 have no match with either ("ID" and "date1") or ("ID" and "date2"), I want to ignore these rows.

So, the output of this output dataframe, df3, should look like this:

   ID  colA_1     date1  colA_2     date2  colB_1  colB_2
0   1       1  1.1.2001       4  1.1.2002      11      12
1   2       2  2.1.2001       5  2.1.2002      13      14
2   3       3  3.1.2001       6  3.1.2002      15      16

What is the best way to do this?

I found this link, but the answer doesn't work for my case. I would like a really explicit way to specify column matching. I think it's possible that df.mask might be able to help me, but I am not sure how to implement it.

e.g.: the following code

df3 = df1.copy()
df3["colB_1"] = ""
df3["colB_2"] = ""
filter1 = (df1["ID"] == df2["ID"]) & (df1["date1"] == df2["date"])
filter2 = (df1["ID"] == df2["ID"]) & (df1["date2"] == df2["date"])
df3["colB_1"] = df.mask(filter1, other=df2["col3"])
df3["colB_2"] = df.mask(filter2, other=df2["col3"])

gives the error

ValueError: Can only compare identically-labeled Series objects

I asked this question previously, and it was marked as closed; my question was marked as a duplicate of this one. However, this is not the case. The answers in the linked question suggest the use of either map or df.merge. Map does not work with multiple conditions (in my case, ID and date). And df.merge (the answer given for matching multiple columns) does not work in my case when one of the column names in df1 and df2 that are to be merged are different ("date" and "date1", for example).

For example, the below code:

df3 = df1.merge(df2[["ID","date","col3"]], on=['ID','date1'], how='left')

fails with a Key Error.

Also noteworthy is that I will be dealing with many different files, with many different column naming schemes, and I will need a different subset each time. This is why I would like an answer that explicitly names the columns and conditions.

Any help with this would be much appreciated.

Body:
You can the pd.wide_to_long after replacing the underscore , this will unpivot the dataframe which you can use to merge with df2 and then pivot back using unstack:

m =df1.rename(columns=lambda x: x.replace('_',''))
unpiv = pd.wide_to_long(m,['colA','date'],'ID','v').reset_index()

merge_piv = (unpiv.merge(df2[['ID','date','col3']],on=['ID','date'],how='left')
     .set_index(['ID','v'])['col3'].unstack().add_prefix('colB_'))

final = df1.merge(merge_piv,left_on='ID',right_index=True)

   ID  colA_1     date1  colA_2     date2  colB_1  colB_2
0   1       1  1.1.2001       4  1.1.2002      11      12
1   2       2  2.1.2001       5  2.1.2002      13      14
2   3       3  3.1.2001       6  3.1.2002      15      16


答:
Where you can only use var variables but you want to ensure that a variable declaration is not going to overwrite another pre-existing variable of the same name, you can use an IIFE to scope that variable to the function. This in effect creates a "block", similar to the second example below.

var variables are scoped to functions:

var a = 1;
let b = 1;

(function() {
  var a = 2;
  let b = 1;
})();

console.log(a); //=> 1 (a is not overwritten because the second `var a` is function-scoped)
console.log(b); //=> 1```
</div>
</div>
</p>

<p><code>let</code> variables are scoped to blocks:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = 1;
var b = 1;

{
  let a = 2;
  var b = 2;
}

console.log(a); //=> 1 (a is not overwritten as let is block-scoped)
console.log(b); //=> 2 (b is overwritten as var is not block-scoped)</code>```

It's worth mentioning that you can redeclare a var variable, hence why it would be possible to overwrite an existing var variable of the same name. However, you cannot redeclare a let variable:

var a = 1

// will not error as `var` does not prevent redeclaration
var a = 2

let b = 1

{
  // will not error as `b` is not declared in this block
  let b = 2
}

// will error as `b` is already declared in this scope
let b = 3```

You can read more about let and var in this question and its answers.

Title: JavaScript: implement let-working with var

Body:
Where you can only use var variables but you want to ensure that a variable declaration is not going to overwrite another pre-existing variable of the same name, you can use an IIFE to scope that variable to the function. This in effect creates a "block", similar to the second example below.

var variables are scoped to functions:

var a = 1;
let b = 1;

(function() {
  var a = 2;
  let b = 1;
})();

console.log(a); //=> 1 (a is not overwritten because the second `var a` is function-scoped)
console.log(b); //=> 1

let variables are scoped to blocks:

let a = 1;
var b = 1;

{
  let a = 2;
  var b = 2;
}

console.log(a); //=> 1 (a is not overwritten as let is block-scoped)
console.log(b); //=> 2 (b is overwritten as var is not block-scoped)

It's worth mentioning that you can redeclare a var variable, hence why it would be possible to overwrite an existing var variable of the same name. However, you cannot redeclare a let variable:

var a = 1

// will not error as `var` does not prevent redeclaration
var a = 2

let b = 1

{
  // will not error as `b` is not declared in this block
  let b = 2
}

// will error as `b` is already declared in this scope
let b = 3

You can read more about let and var in this question and its answers.


答:
You can have different approachto this problem</p>

```<code>// set array with allowed paths
const pathsForSlideShow = ['/', '/yyyy.asp', 'etc...'];
// check if path is in array if so run the slidshow
if ( pathForSlideShow.indexOf(window.location.pathname) !== -1 ) runSlideShow();

// or if you don't need to support IE
if ( pathForSlideShow.includes(window.location.pathname) ) runSlideShow();
</code>```

Title: javascript - if and or (||) statement

Body:
if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

Body:
You can have different approachto this problem

// set array with allowed paths
const pathsForSlideShow = ['/', '/yyyy.asp', 'etc...'];
// check if path is in array if so run the slidshow
if ( pathForSlideShow.indexOf(window.location.pathname) !== -1 ) runSlideShow();

// or if you don't need to support IE
if ( pathForSlideShow.includes(window.location.pathname) ) runSlideShow();


问:
Mesuring Derby speed with hibernate. Strange values
I'm writing application to mesure speed of CRUD with hibernate for Derby.

This is my function :

```<code>  @Override
    public BulkTestResult testBulkInsertScenario(Long volume, Integer repeat) {
        StopWatch sw = new StopWatch();
        BulkTestResult bulkTestResult = new BulkTestResult();
        bulkTestResult.setStartDate(Instant.now());
        bulkTestResult.setCountTest(volume);
        bulkTestResult.setTestRepeat(repeat);
        familyService.clear();
       for(int i =0; i < repeat; i++) {
           List<ProjectEntity> projects = dataAnonymization.generateProjectEntityList(volume);
           runBulkTest(sw, bulkTestResult, projects, true);
       }

        bulkTestResult.setEndDate(Instant.now());
        return bulkTestResult;
    }

    private void runBulkTest(StopWatch sw, BulkTestResult bulkTestResult, List<ProjectEntity> projects, boolean resetAfter) {
        sw.reset();
        sw.start();
        familyService.save(projects);
        sw.stop();
        bulkTestResult.addMsSpeedResult(sw.getTime());
        if (resetAfter) familyService.clear();
        sw.reset();
    }
</code>```

clear method remove all record from DB.

The problem that I have is values that I recieved as output of application.

Testing data : 1000 record, and 10 repeats

Example speed values recieved running this test few times:

311, 116, 87, (...)38

32, 27, 30, (...) 24

22, 19, 18, (...) 21

19, 18, 18, (...) 19

Why there are so many difference and why for first time insert is always slower ?
It could be any hardware acceleration ?

答:
I found solution.
This issue is related to optimalization. After Disable JIT, recieved values are correct.

-Djava.compiler=NONE -Xint

Body:
I'm writing application to mesure speed of CRUD with hibernate for Derby.

This is my function :

  @Override
    public BulkTestResult testBulkInsertScenario(Long volume, Integer repeat) {
        StopWatch sw = new StopWatch();
        BulkTestResult bulkTestResult = new BulkTestResult();
        bulkTestResult.setStartDate(Instant.now());
        bulkTestResult.setCountTest(volume);
        bulkTestResult.setTestRepeat(repeat);
        familyService.clear();
       for(int i =0; i < repeat; i++) {
           List<ProjectEntity> projects = dataAnonymization.generateProjectEntityList(volume);
           runBulkTest(sw, bulkTestResult, projects, true);
       }

        bulkTestResult.setEndDate(Instant.now());
        return bulkTestResult;
    }

    private void runBulkTest(StopWatch sw, BulkTestResult bulkTestResult, List<ProjectEntity> projects, boolean resetAfter) {
        sw.reset();
        sw.start();
        familyService.save(projects);
        sw.stop();
        bulkTestResult.addMsSpeedResult(sw.getTime());
        if (resetAfter) familyService.clear();
        sw.reset();
    }

clear method remove all record from DB.

The problem that I have is values that I recieved as output of application.

Testing data : 1000 record, and 10 repeats

Example speed values recieved running this test few times:

311, 116, 87, (...)38

32, 27, 30, (...) 24

22, 19, 18, (...) 21

19, 18, 18, (...) 19

Why there are so many difference and why for first time insert is always slower ?
It could be any hardware acceleration ?


问:
store input value which is in loop with javascript
I have a column input field in  which is in the loop due to this each Row has input field I got a javascript from which it storing local storage for input field but the issue is this javascript is working only for one input For Example :

I have five rows and due to loop input field generated for 5 rows automatically

What I am looking for is to store different values for each row..due to this script its not implementing for each row individually

Code

```<code><input type="text" id="txt_1" onkeyup='saveValue(this);'/>
</code>```

Javascript

```<code><script type="text/javascript">
        document.getElementById("txt_1").value = getSavedValue("txt_1");    // set the value to this input
        document.getElementById("txt_2").value = getSavedValue("txt_2");   // set the value to this input
        /* Here you can add more inputs to set value. if it's saved */

        //Save the value function - save it to localStorage as (ID, VALUE)
        function saveValue(e){
            var id = e.id;  // get the sender's id to save it .
            var val = e.value; // get the value.
            localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
        }

        //get the saved value function - return the value of "v" from localStorage.
        function getSavedValue  (v){
            if (!localStorage.getItem(v)) {
                return "";// You can change this to your defualt value.
            }
            return localStorage.getItem(v);
        }
</script>
</code>```

Image Showing

COde

```<code><table class="table table-hover table-striped table-bordered" id="input-group">
<thead ><tr >
 <th class="text-right"><?php echo "Contact No."; ?></th>
  <th><?php echo "Followup 1 Date"; ?>
    </th></tr></thead>
    <tbody>
    <?php
      if (empty($enquiry_list)) {
       ?>
       <?php
        } else {
        foreach ($enquiry_list as $key => $value) {
         $current_date = date("d/m/Y");
         $next_date = $value["next_date"];
         if (empty($next_date)) { $next_date = $value["follow_up_date"];
          }if ($next_date < $current_date) {
          $class = "class='danger'";} else {
           $class = ""; } ?>
           <td class="mailbox-name"><?php echo $value['contact']; ?> </td>
   <td class="mailbox-name" >
    <div  style="width:200px" style="height:200px" >
     <input id="txt_<?= $row[id] ?>" onkeyup='saveValue(this);'
      autocomplete="off" type="text" class="form-control"   /></div></td>
      </tr> </tr>
      <?php }}?> </tbody> </table>
</code>```

答:
First of all you need to pass the event listener to the function that you have implemented, so i've solved it adding the events on the js file.
So instead of this:

```<code><input type="text" id="txt_1" onkeyup='saveValue(this);'/>
</code>```

You need to add the event on the js:

```<code><input type="text" id="txt_1"/>
<input type="text" id="txt_2"/>

document.getElementById("txt_1").onkeyup = saveValue;
document.getElementById("txt_2").onkeyup = saveValue;

</code>```

After this you need to access the id and the value from the event.target like this:

```<code>function saveValue(e) {
  var id = e.target.id; // get the sender's id to save it .
  var val = e.target.value; // get the value.
  localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
</code>```

Look at this codesandbox and see if it helps you out

Body:
I have a column input field in  which is in the loop due to this each Row has input field I got a javascript from which it storing local storage for input field but the issue is this javascript is working only for one input For Example :

I have five rows and due to loop input field generated for 5 rows automatically

What I am looking for is to store different values for each row..due to this script its not implementing for each row individually

Code

<input type="text" id="txt_1" onkeyup='saveValue(this);'/>

Javascript

Image Showing

COde

 <?php echo "Contact No."; ?>
  <?php echo "Followup 1 Date"; ?>

    <?php
      if (empty($enquiry_list)) {
       ?>
       <?php
        } else {
        foreach ($enquiry_list as $key => $value) {
         $current_date = date("d/m/Y");
         $next_date = $value["next_date"];
         if (empty($next_date)) { $next_date = $value["follow_up_date"];
          }if ($next_date < $current_date) {
          $class = "class='danger'";} else {
           $class = ""; } ?>
           <?php echo $value['contact']; ?>

     <input id="txt_<?= $row[id] ?>" onkeyup='saveValue(this);'
      autocomplete="off" type="text" class="form-control"   />

      <?php }}?>

Body:
First of all you need to pass the event listener to the function that you have implemented, so i've solved it adding the events on the js file.
So instead of this:

<input type="text" id="txt_1" onkeyup='saveValue(this);'/>

You need to add the event on the js:

<input type="text" id="txt_1"/>
<input type="text" id="txt_2"/>

document.getElementById("txt_1").onkeyup = saveValue;
document.getElementById("txt_2").onkeyup = saveValue;

After this you need to access the id and the value from the event.target like this:

function saveValue(e) {
  var id = e.target.id; // get the sender's id to save it .
  var val = e.target.value; // get the value.
  localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}

Look at this codesandbox and see if it helps you out


问:
Make Flex List Vertical Not Horizontal
I work with CSS and I don't have a lot of flex-box experience as I've only recently began adopting it as the web continues to drive forward. I am working with code that I don't quite understand. The DIVs are all floating next to each other in a horizontal grid but I want each .styled-container to be vertical with each .styled-container in it's own row. I'm not sure which CSS lines are causing it to do this so I'd like to

1) Understand the flex better and what's causing it

2) How to make this list vertical

I appreciate it!

CodePen
https://codepen.io/CoderPerson87/pen/zYGBpPE

HTML

```<code><div class="family-container">
  <div class="styled-container">
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />
  <p>Company Name</p>
  </div>
  <div class="styled-container">
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />
  <p>Company Name</p>
  </div>
  <div class="styled-container">
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />
  <p>Company Name</p>
  </div>
</div>
</code>```

CSS

```<code>.family-container{
  margin-bottom:96px;
  display:flex;
  width:100%;
  justify-content:center;
  align-items:center;
}

.styled-container{
  flex-direction:column;
  display:flex;
  align-items:center;
  margin-bottom:5px;
  margin-right:32px;
}

img{
  max-width:64px;
  grid-column:span;
  border-radius:120px;
}
</code>```

答:
You can use flex-direction: row; in class .family-container for each .styled-container set in horizontal, for vertical use flex-direction: column;

```<code> .family-container{
  margin-bottom:96px;
  display:flex;
  width:100%;
  justify-content:center;
  align-items:center;
  flex-direction:column;
}
.styled-container{
  flex-direction:column;
  display:flex;
  align-items:center;
  margin-bottom:5px;
  margin-right:32px;
}
img{
  max-width:64px;
  grid-column:span;
  border-radius:120px;
}
</code>```

for reference:- https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: Make Flex List Vertical Not Horizontal

Body:
I work with CSS and I don't have a lot of flex-box experience as I've only recently began adopting it as the web continues to drive forward. I am working with code that I don't quite understand. The DIVs are all floating next to each other in a horizontal grid but I want each .styled-container to be vertical with each .styled-container in it's own row. I'm not sure which CSS lines are causing it to do this so I'd like to

1) Understand the flex better and what's causing it

2) How to make this list vertical

I appreciate it!

CodePen
https://codepen.io/CoderPerson87/pen/zYGBpPE

HTML

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />

Company Name

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />

Company Name

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAADCCAMAAAB6zFdcAAAAYFBMVEUAZq7///8AY60AXKozfLnC0eTD1+kAX6t8ps49e7iOr9MAUKUqeLe50OVqlMNGg7zu9foAWakAV6iEqtDM3OtxncnW4+9IiL+xxt+80uaQs9SYuNeevdqyyuE4f7rI2+sR6XqnAAACJUlEQVR4nO3c21aCQBSAYQYM8lSOGallvv9b1lQayAzsWWYsNv93PRez/+UBREgSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADGJU2KLKjvzf2P7CWb3YVsRxHB7jfznQnarPve4O3Zmcnny3CDEUSwe9PRwBxt35u8LZegq4HJVUewr0bQQHWE7wTdDUyu9tvhJ4GggdoI9u00YHcDs1P5djgnEDVQGeE3gayBwgjr3wTCBmap7GCpmkDaQFmE9bY6m7SBqgj1BPIGiiLYQ30yeQNzUPLBeJkgpoGSCI0EUQ1URGgmiGugIELhGTef5xENzDLte4jrpFPPULldTIIWDe99D3Elf4MsDVo8NE2H/UIINAiuL5486/fFP+7470U3uPesn9GABjSgAQ1oQAMa0IAGNKABDRwa0MChAQ0cGtDAoQENnNE0OI6rQZI8Nk3Cl1hUNkg9V8/CF9omOhv4hgrLPMvLvme4WvYckWDlaVCmw77c6MRE8DTQkCAqQrNBWWhIEBOh0aDMdCSIiHDZQE8CeYSLBuXg/4pUJYxQb6ArQZJY0XFCrcFGWQJhhGqDjcJbWSQRKg00JviM4Pu/VahBy7nloHVHODfQek+XIMKpgd4E3RF+Gmi+x7MzwncD3Qm6Inw1yNXcvBLSGsE10J+gPcIqezqOIIGLEHwSyCF9H/hvh1JtT4TRc64MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDMBzHnJaGfdaRoAAAAAElFTkSuQmCC" />

Company Name

CSS

.family-container{
  margin-bottom:96px;
  display:flex;
  width:100%;
  justify-content:center;
  align-items:center;
}

.styled-container{
  flex-direction:column;
  display:flex;
  align-items:center;
  margin-bottom:5px;
  margin-right:32px;
}

img{
  max-width:64px;
  grid-column:span;
  border-radius:120px;
}

Body:
You can use flex-direction: row; in class .family-container for each .styled-container set in horizontal, for vertical use flex-direction: column;

 .family-container{
  margin-bottom:96px;
  display:flex;
  width:100%;
  justify-content:center;
  align-items:center;
  flex-direction:column;
}
.styled-container{
  flex-direction:column;
  display:flex;
  align-items:center;
  margin-bottom:5px;
  margin-right:32px;
}
img{
  max-width:64px;
  grid-column:span;
  border-radius:120px;
}

for reference:- https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Closing Popup after clicking child button using no code-behind
I have a wpf application with a toggle window which opens a popup control. I want to be able to close it after the user clicks it's child button.

My preference would be to do it in the xaml via style triggers. But for some reason I can't set my popup IsOpen property inside of the event trigger. I receive an error saying

```<code>A value of type setter cannot be added to a collection or dictionary of type TriggerActionCollection
</code>```

here's how I have the xaml set up

```<code><ToggleButton x:Name="ShowAvailableOptionsToggleButton"
                                              Content="Add Options" />

<Popup IsOpen="{Binding IsChecked, ElementName=ShowAvailableOptionsToggleButton}">
                <StackPanel>
                    <ListView ItemsSource="{Binding AvailableOptions}"
                              IsSynchronizedWithCurrentItem="True"
                              DisplayMemberPath="Name"/>
                    <Button Content="Add"
                            Name="AddOptionBtn"
                            Command="{Binding AddOptionCommand}"/>
                </StackPanel>
                <Popup.Style>
                   <Style>
                       <Style.Triggers>
                          <EventTrigger SourceName="AddOptionBtn" RoutedEvent="Button.Click">
                             //ERROR HAPPENS HERE
                             <Setter Property="IsOpen" Value="False"/>
                          </EventTrigger>
                       </Style.Triggers>
                   </Style>
                </Popup.Style>
            </Popup>
</code>```

Can someone see what I am doing wrong?

答:
EventTrigger has to be used with animations:

```<code><Popup IsOpen="True">
  <Button x:Name="AddOptionBtn"
          Content="Add" />
  <Popup.Triggers>
    <EventTrigger SourceName="AddOptionBtn"
                  RoutedEvent="Button.Click">
      <BeginStoryboard>
        <Storyboard>
          <BooleanAnimationUsingKeyFrames Storyboard.Target="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Popup}}"
                                          Storyboard.TargetProperty="IsOpen">
            <DiscreteBooleanKeyFrame KeyTime="0"
                                     Value="False" />
          </BooleanAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Popup.Triggers>
</Popup>
</code>```

Body:
I have a wpf application with a toggle window which opens a popup control. I want to be able to close it after the user clicks it's child button.

My preference would be to do it in the xaml via style triggers. But for some reason I can't set my popup IsOpen property inside of the event trigger. I receive an error saying

A value of type setter cannot be added to a collection or dictionary of type TriggerActionCollection

here's how I have the xaml set up

<ToggleButton x:Name="ShowAvailableOptionsToggleButton"
                                              Content="Add Options" />

<Popup IsOpen="{Binding IsChecked, ElementName=ShowAvailableOptionsToggleButton}">
                <StackPanel>
                    <ListView ItemsSource="{Binding AvailableOptions}"
                              IsSynchronizedWithCurrentItem="True"
                              DisplayMemberPath="Name"/>
                    <Button Content="Add"
                            Name="AddOptionBtn"
                            Command="{Binding AddOptionCommand}"/>
                </StackPanel>
                <Popup.Style>

                   </Style>
                </Popup.Style>
            </Popup>

Can someone see what I am doing wrong?

Body:
EventTrigger has to be used with animations:

<Popup IsOpen="True">
  <Button x:Name="AddOptionBtn"
          Content="Add" />
  <Popup.Triggers>
    <EventTrigger SourceName="AddOptionBtn"
                  RoutedEvent="Button.Click">
      <BeginStoryboard>
        <Storyboard>
          <BooleanAnimationUsingKeyFrames Storyboard.Target="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Popup}}"
                                          Storyboard.TargetProperty="IsOpen">
            <DiscreteBooleanKeyFrame KeyTime="0"
                                     Value="False" />
          </BooleanAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Popup.Triggers>
</Popup>


问:
Navigation error - This navigation graph is not referenced to any layout files?
I am trying to apply navigation feature to my project.

And I have this error:

```<code>This navigation graph is not referenced to any layout files(expected to find it in at least one layout file with a NavHostFragment with app:navGraph="@navigation/@navigation" attribute
</code>```

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/navigation"
    android:label="fragment_init"
    app:startDestination="@id/initFragment"
    >

    <fragment
        android:id="@+id/initFragment"
        android:label="fragment_init"
        tools:layout="@layout/fragment_init">
        <action
            android:id="@+id/action_initFragment_to_authenticationFragment5"
            app:destination="@id/authenticationFragment"
            />
        <action
            android:id="@+id/action_initFragment_to_settingFragment3"
            app:destination="@id/settingFragment" />
    </fragment>
    <fragment
        android:id="@+id/authenticationFragment"
        android:name="com.example.AuthenticationFragment"
        android:label="fragment_authentication"
        tools:layout="@layout/fragment_authentication" />
    <fragment
        android:id="@+id/settingFragment"
        android:name="com.example.view.main.fragment.SettingFragment"
        android:label="SettingFragment"
        tools:layout="@layout/fragment_setting" />
</navigation>
</code>```

I added that attribute here and there (navigation and fragments ). And also, the layout files in layout folder which are used in navigation.xml. But didn't work.

This is activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
    android:background="#000"
    android:tint="#555"
    tools:context=come.example.view.main.MainActivity">

    <ImageView
        android:id="@+id/iv_flame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:navGraph="@navigation/navigation"/>
</RelativeLayout>
</code>```

答: If the accepted answer does not work initially, try "Make Project". Worked for me with <fragment/>

Body:
I am trying to apply navigation feature to my project.

And I have this error:

This navigation graph is not referenced to any layout files(expected to find it in at least one layout file with a NavHostFragment with app:navGraph="@navigation/@navigation" attribute

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/navigation"
    android:label="fragment_init"
    app:startDestination="@id/initFragment"
    >

    <fragment
        android:id="@+id/initFragment"
        android:label="fragment_init"
        tools:layout="@layout/fragment_init">
        <action
            android:id="@+id/action_initFragment_to_authenticationFragment5"
            app:destination="@id/authenticationFragment"
            />
        <action
            android:id="@+id/action_initFragment_to_settingFragment3"
            app:destination="@id/settingFragment" />
    </fragment>
    <fragment
        android:id="@+id/authenticationFragment"
        android:name="com.example.AuthenticationFragment"
        android:label="fragment_authentication"
        tools:layout="@layout/fragment_authentication" />
    <fragment
        android:id="@+id/settingFragment"
        android:name="com.example.view.main.fragment.SettingFragment"
        android:label="SettingFragment"
        tools:layout="@layout/fragment_setting" />
</navigation>

I added that attribute here and there (navigation and fragments ). And also, the layout files in layout folder which are used in navigation.xml. But didn't work.

This is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
    android:background="#000"
    android:tint="#555"
    tools:context=come.example.view.main.MainActivity">

    <ImageView
        android:id="@+id/iv_flame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:navGraph="@navigation/navigation"/>
</RelativeLayout>


问:
what is the distribution OS of docker image
How can find distribution OS of an official docker image into docker hub ?

I want custom my building of image docker into my Dockerfile but if I don't know which OS is running, I have lot of error that can't resolve inficiently.

I try :

The docker hub website hasn't given this information

The inspect layer of image with 'dive' program don't give this information

I know that exist this OS ; Alpine, Distroless but I don't know how knowing which used

答:
whatever docker image you are using for finding OS distribution image builds with is, login to your running container and executes:
cat /etc/*release