问:
Getting an error android.util.SuperNotCalledException: Activity {} did not call through to super.onCreate()
I'm making a TV that plays music and youtube videos. I get the following error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.newapp, PID: 12965
    android.util.SuperNotCalledException: Activity {com.example.newapp/com.example.newapp.YoutubeActivity} did not call through to super.onCreate()
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3081)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:209)
        at android.app.ActivityThread.main(ActivityThread.java:7021)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
</code>```

This is my code for the youtube activity

```<code>public class YoutubeActivity extends YouTubeBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("youtube", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youtube_main);

        setupVideoPlayer();
    }
</code>```

And this is the code (in another file) that initializes the Activity

```<code> private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Radio) {
                Radio radio = (Radio) item;
                Log.d(TAG, "RadioItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                intent.putExtra(DetailsActivity.RADIO, radio);

                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        DetailsActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            } else if (item instanceof Video) {
                Video video = (Video) item;
                Log.e(TAG, "VideoItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), YoutubeActivity.class);
                intent.putExtra(YoutubeActivity.VIDEO, video);
                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        YoutubeActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            }
            else if (item instanceof String) {
                if (((String) item).contains(getString(R.string.error_fragment))) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
</code>```

As you can see, if the item clicked is a radio, then it goes to another activity that plays the radio. This works perfectly. But if the item clicked is a video, it goes to the youtube player activity, which gives the exception given in the first code block.

In addition, you can see that I have the super.OnCreate() function, so I am unsure where I'm messing up.

答: So I got it to work, not by conventional methods though. I just made a new project and copied over the old one to the new. Still not sure what was going wrong but it's working now.</p>

Body:
I'm making a TV that plays music and youtube videos. I get the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.newapp, PID: 12965
    android.util.SuperNotCalledException: Activity {com.example.newapp/com.example.newapp.YoutubeActivity} did not call through to super.onCreate()
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3081)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:209)
        at android.app.ActivityThread.main(ActivityThread.java:7021)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)

This is my code for the youtube activity

public class YoutubeActivity extends YouTubeBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("youtube", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youtube_main);

        setupVideoPlayer();
    }

And this is the code (in another file) that initializes the Activity

 private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Radio) {
                Radio radio = (Radio) item;
                Log.d(TAG, "RadioItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                intent.putExtra(DetailsActivity.RADIO, radio);

                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        DetailsActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            } else if (item instanceof Video) {
                Video video = (Video) item;
                Log.e(TAG, "VideoItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), YoutubeActivity.class);
                intent.putExtra(YoutubeActivity.VIDEO, video);
                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        YoutubeActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            }
            else if (item instanceof String) {
                if (((String) item).contains(getString(R.string.error_fragment))) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

As you can see, if the item clicked is a radio, then it goes to another activity that plays the radio. This works perfectly. But if the item clicked is a video, it goes to the youtube player activity, which gives the exception given in the first code block.

In addition, you can see that I have the super.OnCreate() function, so I am unsure where I'm messing up.


来源: stackexchange

问:
Simple TableAPI SQL query doesn't work on Flink 1.10 and Blink
I want to define Kafka connector using TableAPI and run SQL over such described table (backed by Kafka). Unfortunately, it seems that Rowtime definition doesn't work as expected.

Here's a reproducible example:

```<code>object DefineSource extends App {

  import org.apache.flink.streaming.api.scala._
  import org.apache.flink.table.api.scala._

  val env = StreamExecutionEnvironment.getExecutionEnvironment
  env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

  val config = EnvironmentSettings.newInstance().inStreamingMode().useBlinkPlanner().build()
  val tEnv = StreamTableEnvironment.create(env, config)

  val rowtime = new Rowtime().watermarksPeriodicBounded(5000)
  val schema = new Schema()
    .field("k", "string")
    .field("ts", "timestamp(3)").rowtime(rowtime)

  tEnv.connect(new Kafka()
    .topic("test")
    .version("universal"))
    .withSchema(schema)
    .withFormat(new Csv())
    .createTemporaryTable("InputTable")

  val output = tEnv.sqlQuery(
    """SELECT k, COUNT(*)
      |  FROM InputTable
      | GROUP BY k, TUMBLE(ts, INTERVAL '15' MINUTE)
      |""".stripMargin
  )

  tEnv.toAppendStream[(String, Long)](output).print()

  env.execute()
}
</code>```

which yields

```<code>org.apache.flink.table.api.TableException: Window aggregate can only be defined over a time attribute column, but TIMESTAMP(3) encountered.
    at org.apache.flink.table.planner.plan.rules.logical.StreamLogicalWindowAggregateRule.getInAggregateGroupExpression(StreamLogicalWindowAggregateRule.scala:51)
    at org.apache.flink.table.planner.plan.rules.logical.LogicalWindowAggregateRuleBase.onMatch(LogicalWindowAggregateRuleBase.scala:79)
    at org.apache.calcite.plan.AbstractRelOptPlanner.fireRule(AbstractRelOptPlanner.java:319)
    at org.apache.calcite.plan.hep.HepPlanner.applyRule(HepPlanner.java:560)
    at org.apache.calcite.plan.hep.HepPlanner.applyRules(HepPlanner.java:419)
    at org.apache.calcite.plan.hep.HepPlanner.executeInstruction(HepPlanner.java:256)
    at org.apache.calcite.plan.hep.HepInstruction$RuleInstance.execute(HepInstruction.java:127)
    at org.apache.calcite.plan.hep.HepPlanner.executeProgram(HepPlanner.java:215)
    at org.apache.calcite.plan.hep.HepPlanner.findBestExp(HepPlanner.java:202)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkHepProgram.optimize(FlinkHepProgram.scala:69)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgram.optimize(FlinkHepRuleSetProgram.scala:87)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram.$anonfun$optimize$1(FlinkChainedProgram.scala:62)
    at scala.collection.TraversableOnce.$anonfun$foldLeft$1(TraversableOnce.scala:160)
    at scala.collection.TraversableOnce.$anonfun$foldLeft$1$adapted(TraversableOnce.scala:160)
    at scala.collection.Iterator.foreach(Iterator.scala:941)
    at scala.collection.Iterator.foreach$(Iterator.scala:941)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
    at scala.collection.IterableLike.foreach(IterableLike.scala:74)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
    at scala.collection.TraversableOnce.foldLeft(TraversableOnce.scala:160)
    at scala.collection.TraversableOnce.foldLeft$(TraversableOnce.scala:158)
    at scala.collection.AbstractTraversable.foldLeft(Traversable.scala:108)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram.optimize(FlinkChainedProgram.scala:58)
    at org.apache.flink.table.planner.plan.optimize.StreamCommonSubGraphBasedOptimizer.optimizeTree(StreamCommonSubGraphBasedOptimizer.scala:170)
    at org.apache.flink.table.planner.plan.optimize.StreamCommonSubGraphBasedOptimizer.doOptimize(StreamCommonSubGraphBasedOptimizer.scala:94)
    at org.apache.flink.table.planner.plan.optimize.CommonSubGraphBasedOptimizer.optimize(CommonSubGraphBasedOptimizer.scala:77)
    at org.apache.flink.table.planner.delegation.PlannerBase.optimize(PlannerBase.scala:248)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:151)
    at org.apache.flink.table.api.scala.internal.StreamTableEnvironmentImpl.toDataStream(StreamTableEnvironmentImpl.scala:210)
    at org.apache.flink.table.api.scala.internal.StreamTableEnvironmentImpl.toAppendStream(StreamTableEnvironmentImpl.scala:107)
</code>```

I'm on Flink 1.10.0.

答:
this is a bug and fixed 1.10.0+
https://issues.apache.org/jira/browse/FLINK-16160</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to define Kafka connector using TableAPI and run SQL over such described table (backed by Kafka). Unfortunately, it seems that Rowtime definition doesn't work as expected.

Here's a reproducible example:

object DefineSource extends App {

  import org.apache.flink.streaming.api.scala._
  import org.apache.flink.table.api.scala._

  val env = StreamExecutionEnvironment.getExecutionEnvironment
  env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

  val config = EnvironmentSettings.newInstance().inStreamingMode().useBlinkPlanner().build()
  val tEnv = StreamTableEnvironment.create(env, config)

  val rowtime = new Rowtime().watermarksPeriodicBounded(5000)
  val schema = new Schema()
    .field("k", "string")
    .field("ts", "timestamp(3)").rowtime(rowtime)

  tEnv.connect(new Kafka()
    .topic("test")
    .version("universal"))
    .withSchema(schema)
    .withFormat(new Csv())
    .createTemporaryTable("InputTable")

  val output = tEnv.sqlQuery(
    """SELECT k, COUNT(*)
      |  FROM InputTable
      | GROUP BY k, TUMBLE(ts, INTERVAL '15' MINUTE)
      |""".stripMargin
  )

  tEnv.toAppendStream[(String, Long)](output).print()

  env.execute()
}

which yields

org.apache.flink.table.api.TableException: Window aggregate can only be defined over a time attribute column, but TIMESTAMP(3) encountered.
    at org.apache.flink.table.planner.plan.rules.logical.StreamLogicalWindowAggregateRule.getInAggregateGroupExpression(StreamLogicalWindowAggregateRule.scala:51)
    at org.apache.flink.table.planner.plan.rules.logical.LogicalWindowAggregateRuleBase.onMatch(LogicalWindowAggregateRuleBase.scala:79)
    at org.apache.calcite.plan.AbstractRelOptPlanner.fireRule(AbstractRelOptPlanner.java:319)
    at org.apache.calcite.plan.hep.HepPlanner.applyRule(HepPlanner.java:560)
    at org.apache.calcite.plan.hep.HepPlanner.applyRules(HepPlanner.java:419)
    at org.apache.calcite.plan.hep.HepPlanner.executeInstruction(HepPlanner.java:256)
    at org.apache.calcite.plan.hep.HepInstruction$RuleInstance.execute(HepInstruction.java:127)
    at org.apache.calcite.plan.hep.HepPlanner.executeProgram(HepPlanner.java:215)
    at org.apache.calcite.plan.hep.HepPlanner.findBestExp(HepPlanner.java:202)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkHepProgram.optimize(FlinkHepProgram.scala:69)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkHepRuleSetProgram.optimize(FlinkHepRuleSetProgram.scala:87)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram.$anonfun$optimize$1(FlinkChainedProgram.scala:62)
    at scala.collection.TraversableOnce.$anonfun$foldLeft$1(TraversableOnce.scala:160)
    at scala.collection.TraversableOnce.$anonfun$foldLeft$1$adapted(TraversableOnce.scala:160)
    at scala.collection.Iterator.foreach(Iterator.scala:941)
    at scala.collection.Iterator.foreach$(Iterator.scala:941)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
    at scala.collection.IterableLike.foreach(IterableLike.scala:74)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
    at scala.collection.TraversableOnce.foldLeft(TraversableOnce.scala:160)
    at scala.collection.TraversableOnce.foldLeft$(TraversableOnce.scala:158)
    at scala.collection.AbstractTraversable.foldLeft(Traversable.scala:108)
    at org.apache.flink.table.planner.plan.optimize.program.FlinkChainedProgram.optimize(FlinkChainedProgram.scala:58)
    at org.apache.flink.table.planner.plan.optimize.StreamCommonSubGraphBasedOptimizer.optimizeTree(StreamCommonSubGraphBasedOptimizer.scala:170)
    at org.apache.flink.table.planner.plan.optimize.StreamCommonSubGraphBasedOptimizer.doOptimize(StreamCommonSubGraphBasedOptimizer.scala:94)
    at org.apache.flink.table.planner.plan.optimize.CommonSubGraphBasedOptimizer.optimize(CommonSubGraphBasedOptimizer.scala:77)
    at org.apache.flink.table.planner.delegation.PlannerBase.optimize(PlannerBase.scala:248)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:151)
    at org.apache.flink.table.api.scala.internal.StreamTableEnvironmentImpl.toDataStream(StreamTableEnvironmentImpl.scala:210)
    at org.apache.flink.table.api.scala.internal.StreamTableEnvironmentImpl.toAppendStream(StreamTableEnvironmentImpl.scala:107)

I'm on Flink 1.10.0.


问:
Python Shell says I have version 3.6 but terminal says I have 2.7
which python returns:
/Library/Frameworks/Python.framework/Versions/2.7/bin/python

When I open my shell, the first couple lines of the shell read:
Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.

And finally, the issue is that when I am in my shell and I try to import pandas (which is installed), I receive no module named 'pandas'. Which, according to this article, is due to having multiple installations of Python and running Python from the system.

The solution proposed by the aforementioned article is to use conda. But, will simply installing conda solve my issue of my shell returning something different from terminal? I am really new to programming so assume I don't know how any of this works!

答:
I would suggest doing a cleanup of your python environment for your Mac.

You can first find out what python do you have by typing the following in your terminal:

```<code>which -a python
</code>```

In my case I have:

```<code>/Users/.../anaconda3/bin/python
/usr/bin/python
</code>```

Anaconda python3 and the default python2. In your case, since you had a python3.6.8, it must be installed somewhere and you should be able to see it from the above command.

Now there are 2 options:

You can continue using that python3.6.8 by adding that to your environment path. According to your description, seems like your default is python3.6.8, you probably used wrong pip to install pandas. Maybe instead of pip, use pip3.

You can delete where your python3.6.8 is, and then install anaconda. When you are installing anaconda, it takes care of everything including setting your environment. So that most likely you won't accidentally use any of your other python installations anymore. The defaults will be set to anaconda python. You can continue to use pip to install packages, or you can use conda install which comes with anaconda installation. You can also install miniconda, which is a light-weight version of anaconda that only comes with default most basic packages. This way you will have a better control of your python packages. But if you are new, you can safely go for the full anaconda distribution.

Body:
I would suggest doing a cleanup of your python environment for your Mac.

You can first find out what python do you have by typing the following in your terminal:

which -a python

In my case I have:

/Users/.../anaconda3/bin/python
/usr/bin/python

Anaconda python3 and the default python2. In your case, since you had a python3.6.8, it must be installed somewhere and you should be able to see it from the above command.

Now there are 2 options:

You can continue using that python3.6.8 by adding that to your environment path. According to your description, seems like your default is python3.6.8, you probably used wrong pip to install pandas. Maybe instead of pip, use pip3.

You can delete where your python3.6.8 is, and then install anaconda. When you are installing anaconda, it takes care of everything including setting your environment. So that most likely you won't accidentally use any of your other python installations anymore. The defaults will be set to anaconda python. You can continue to use pip to install packages, or you can use conda install which comes with anaconda installation. You can also install miniconda, which is a light-weight version of anaconda that only comes with default most basic packages. This way you will have a better control of your python packages. But if you are new, you can safely go for the full anaconda distribution.


问:
How to shorten the Qt make process?
I have downloaded an open source Qt that target on Windows. Since I am using the VS2010 command prompt to do the installation, it automatically set the platform to msvc-2010. When I am trying to build using nmake, it took about 7-8 hours to complete the installation. During the process, I have notice that Qt is compiling the libraries which I don't need like javascript.

May I know how can I shorten the build process since I am focusing on desktop development?

答:
As @tibur said, you can use jom, which is a kind of "parallel nmake". You can also pass several options to Qt's configure, some of which are:

-release or -debug: build only release or debug binaries

-nomake demos, -nomake examples, -nomake tools: don't build well, demos, examples or tools.

-no-webkit, -no-qt3support, -no-script, -no-scripttools: disable certain Qt modules.

There may be more, configure.exe --help will tell you all the options available to you.

ContentLicense: CC BY-SA 3.0

Title: How to shorten the Qt make process?


问:
Changing image src constantly / memory usage (Electron)
Here's the following code :

```<code>let g = {
  characterImg: document.createElement('img'),
  num: 0
}

function test() {

  let myDiv = document.getElementById('my-div')

  const param = '#date=' + new Date().getTime()
  const imagePath = (g.num + 1).toString() + '.png' + param

  let removeListener = false
  const myFunction = function() {
    myDiv.style.backgroundImage = "url('" + imagePath + "')"

    if (removeListener)
      g.characterImg.removeEventListener('load', myFunction)
  }

  g.characterImg.src = imagePath
  if (g.characterImg.complete)
    myFunction()
  else {
    removeListener = true
    g.characterImg.addEventListener('load', myFunction)
  }

  // 15 pictures
  g.num = (g.num + 1) % 15
}
</code>```

Knowing my application uses many animated png files constantly, i have two questions :

Executing the test function many times increase the memory without being released by the garbage collector at any time. Even if it's only a matter of a few Mo after minutes of use, i want to be able to load an image without a little leak for each load. From what i know, changing the src is the cause but i don't know how to resolve this.

Changing the backgroundImage isn't a memory leak but constantly increases the memory without calling the garbage collector until i minimize the active window for a few seconds or when the app reaches around 500 Mo of use in my case. Isn't there a way to make the app call the garbage collector more efficiently or at least set a memory limit for an Electron application?

Any help is appreciated :)

答:
Here's an actual answer, i used fs.readFile then set the background property in base64.

```<code>fs.readFile(imagePath, function(err, data) {
if (err) throw err
  const myImageData = 'data:image/png;base64,' + data.toString('base64')
  myDiv.style.backgroundImage = 'url(' + myImageData + ')'
})
</code>```

Much better than creating an image everytime!

Body:
Here's the following code :

let g = {
  characterImg: document.createElement('img'),
  num: 0
}

function test() {

  let myDiv = document.getElementById('my-div')

  const param = '#date=' + new Date().getTime()
  const imagePath = (g.num + 1).toString() + '.png' + param

  let removeListener = false
  const myFunction = function() {
    myDiv.style.backgroundImage = "url('" + imagePath + "')"

    if (removeListener)
      g.characterImg.removeEventListener('load', myFunction)
  }

  g.characterImg.src = imagePath
  if (g.characterImg.complete)
    myFunction()
  else {
    removeListener = true
    g.characterImg.addEventListener('load', myFunction)
  }

  // 15 pictures
  g.num = (g.num + 1) % 15
}

Knowing my application uses many animated png files constantly, i have two questions :

Executing the test function many times increase the memory without being released by the garbage collector at any time. Even if it's only a matter of a few Mo after minutes of use, i want to be able to load an image without a little leak for each load. From what i know, changing the src is the cause but i don't know how to resolve this.

Changing the backgroundImage isn't a memory leak but constantly increases the memory without calling the garbage collector until i minimize the active window for a few seconds or when the app reaches around 500 Mo of use in my case. Isn't there a way to make the app call the garbage collector more efficiently or at least set a memory limit for an Electron application?

Any help is appreciated :)

Body:
Here's an actual answer, i used fs.readFile then set the background property in base64.

fs.readFile(imagePath, function(err, data) {
if (err) throw err
  const myImageData = 'data:image/png;base64,' + data.toString('base64')
  myDiv.style.backgroundImage = 'url(' + myImageData + ')'
})

Much better than creating an image everytime!


问:
Groupby, value counts and calculate percentage in Pandas
I have groupby state, value counts industry of a dataframe.

```<code>df.loc[df['state'].isin(['Alabama','Arizona'])].groupby(df['state'])['industry'].value_counts(sort = True)
</code>```

Out:

```<code>state    industry
Alabama  Financial Services                        224
         Education                                   7
         Healthcare, Pharmaceuticals, & Biotech      5
         Business Services                           2
         Other                                       2
         Retail                                      2
         Government                                  1
         Manufacturing                               1
         Transportation & Storage                    1
Arizona  Healthcare, Pharmaceuticals, & Biotech     19
         Other                                      13
         Education                                   5
         Retail                                      5
         Transportation & Storage                    5
         Manufacturing                               4
         Travel, Recreation, and Leisure             4
         Consumer Services                           3
         Energy & Utilities                          2
         Financial Services                          2
         Government                                  2
         Business Services                           1
         Computers & Electronics                     1
         Software & Internet                         1
Name: industry, dtype: int64
</code>```

Now I would like to go further, get percentage of value counts, for example, for Alabama, I want to know the percentage of Financial Services, which is calculated by 224/ (224 + 7 + ... + 1), etc.

How could I do that by using new code or modify the code above? Thanks.

答:
Adding normalize

```<code>df.loc[df['state'].isin(['Alabama','Arizona'])].groupby(df['state'])['industry'].value_counts(sort = True, normalize=True)
</code>```

Body:
I have groupby state, value counts industry of a dataframe.

df.loc[df['state'].isin(['Alabama','Arizona'])].groupby(df['state'])['industry'].value_counts(sort = True)

Out:

state    industry
Alabama  Financial Services                        224
         Education                                   7
         Healthcare, Pharmaceuticals, & Biotech      5
         Business Services                           2
         Other                                       2
         Retail                                      2
         Government                                  1
         Manufacturing                               1
         Transportation & Storage                    1
Arizona  Healthcare, Pharmaceuticals, & Biotech     19
         Other                                      13
         Education                                   5
         Retail                                      5
         Transportation & Storage                    5
         Manufacturing                               4
         Travel, Recreation, and Leisure             4
         Consumer Services                           3
         Energy & Utilities                          2
         Financial Services                          2
         Government                                  2
         Business Services                           1
         Computers & Electronics                     1
         Software & Internet                         1
Name: industry, dtype: int64

Now I would like to go further, get percentage of value counts, for example, for Alabama, I want to know the percentage of Financial Services, which is calculated by 224/ (224 + 7 + ... + 1), etc.

How could I do that by using new code or modify the code above? Thanks.

Body:
Adding normalize

df.loc[df['state'].isin(['Alabama','Arizona'])].groupby(df['state'])['industry'].value_counts(sort = True, normalize=True)


问:
Show text in the toolbar when title of the page is not visible in the sidenav content
I'm working on an angular project (I'm still learning, still a newbie). I would like to know how to set the title (driver name and information) in the toolbar when the toolbar overlaps the text (JAMES SMITH- PLACA: ABC1234) when the user scrolls down the sidenav page content.

I forked a boilerplate sidenav code to share with you https://stackblitz.com/edit/angular-closing-side-nav-in-mobile-z35xfw?file=app/sidenav-responsive-example.html

This is what I want to achieve.

Thanks in advance for your help.

答:
I did this feature, and you can see it here in stackblitz basically, I did a ref to the title (check the line 39 in the HTML), and the logic to check if this title is visible is:

this.titleIsVisible =
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.right <=
        (window.innerWidth || document.documentElement.clientWidth) &&
      bounding.bottom <=
        (window.innerHeight || document.documentElement.clientHeight);
```

<p>To listen the scroll event I used <code>@HostListener("window:scroll", ["$event"])</code> in the TS and in the HTML I just used (scroll). To see this check the line 28 in the TS and the line 30 in the HTML.</p>

<p>Just in case, this is the code. </p>

<pre class="lang-typescript prettyprint-override"><code>import { Component, ViewChild, ElementRef, HostListener } from "@angular/core";
import {
  BreakpointObserver,
  Breakpoints,
  BreakpointState
} from "@angular/cdk/layout";
import { FormControl } from "@angular/forms";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
/** @title Responsive sidenav */
@Component({
  selector: "sidenav-responsive-example",
  templateUrl: "sidenav-responsive-example.html",
  styleUrls: ["sidenav-responsive-example.css"]
})
export class SidenavResponsiveExample {
  @ViewChild("drawer") drawer: any;
  @ViewChild("title") title: ElementRef;

  public selectedItem: string = "";
  public isHandset$: Observable<boolean> = this.breakpointObserver
    .observe(Breakpoints.Handset)
    .pipe(map((result: BreakpointState) => result.matches));
  public titleIsVisible: boolean = true;

  constructor(private breakpointObserver: BreakpointObserver) {}

  @HostListener("window:scroll", ["$event"])
  onScroll() {
    const bounding = this.title.nativeElement.getBoundingClientRect();
    this.titleIsVisible =
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.right <=
        (window.innerWidth || document.documentElement.clientWidth) &&
      bounding.bottom <=
        (window.innerHeight || document.documentElement.clientHeight);

  }

  closeSideNav() {
    if (this.drawer._mode == "over") {
      this.drawer.close();
    }
  }
}
</code>```

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
    [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)">
    <mat-toolbar color="primary" style="margin-top:30px;"> Business</mat-toolbar>

    <mat-nav-list >
      <mat-list-item  (click)="closeSideNav()">
        <mat-icon matListIcon>home</mat-icon>
        Home
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>person</mat-icon>
        Customers
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>group_work</mat-icon>
        employees
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>business</mat-icon>
        business
      </mat-list-item>

    </mat-nav-list>
  </mat-sidenav>

  <mat-sidenav-content (scroll)="onScroll($event)">
    <mat-toolbar color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>

TITLE

    </mat-toolbar>

TITLE

        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

      <ng-content>

      </ng-content>

  </mat-sidenav-content>
</mat-sidenav-container>
```

Body:
I did this feature, and you can see it here in stackblitz basically, I did a ref to the title (check the line 39 in the HTML), and the logic to check if this title is visible is:

this.titleIsVisible =
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.right <=
        (window.innerWidth || document.documentElement.clientWidth) &&
      bounding.bottom <=
        (window.innerHeight || document.documentElement.clientHeight);

To listen the scroll event I used @HostListener("window:scroll", ["$event"]) in the TS and in the HTML I just used (scroll). To see this check the line 28 in the TS and the line 30 in the HTML.

Just in case, this is the code.

import { Component, ViewChild, ElementRef, HostListener } from "@angular/core";
import {
  BreakpointObserver,
  Breakpoints,
  BreakpointState
} from "@angular/cdk/layout";
import { FormControl } from "@angular/forms";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
/** @title Responsive sidenav */
@Component({
  selector: "sidenav-responsive-example",
  templateUrl: "sidenav-responsive-example.html",
  styleUrls: ["sidenav-responsive-example.css"]
})
export class SidenavResponsiveExample {
  @ViewChild("drawer") drawer: any;
  @ViewChild("title") title: ElementRef;

  public selectedItem: string = "";
  public isHandset$: Observable<boolean> = this.breakpointObserver
    .observe(Breakpoints.Handset)
    .pipe(map((result: BreakpointState) => result.matches));
  public titleIsVisible: boolean = true;

  constructor(private breakpointObserver: BreakpointObserver) {}

  @HostListener("window:scroll", ["$event"])
  onScroll() {
    const bounding = this.title.nativeElement.getBoundingClientRect();
    this.titleIsVisible =
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.right <=
        (window.innerWidth || document.documentElement.clientWidth) &&
      bounding.bottom <=
        (window.innerHeight || document.documentElement.clientHeight);

  }

  closeSideNav() {
    if (this.drawer._mode == "over") {
      this.drawer.close();
    }
  }
}

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #drawer fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
    [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)">
    <mat-toolbar color="primary" style="margin-top:30px;"> Business</mat-toolbar>

    <mat-nav-list >
      <mat-list-item  (click)="closeSideNav()">
        <mat-icon matListIcon>home</mat-icon>
        <a matLine>Home</a>
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>person</mat-icon>
        <a matLine>Customers</a>
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>group_work</mat-icon>
        <a matLine>employees</a>
      </mat-list-item>

      <mat-list-item (click)="closeSideNav()">
        <mat-icon matListIcon>business</mat-icon>
        <a matLine>business</a>
      </mat-list-item>

    </mat-nav-list>
  </mat-sidenav>

  <mat-sidenav-content (scroll)="onScroll($event)">
    <mat-toolbar color="primary">
      <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <h1 *ngIf=!titleIsVisible>TITLE</h1>
    </mat-toolbar>

    <div class="ylb-app-content">
      <h1 #title >TITLE</h1>
      <div >
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

      </div>
      <ng-content>

      </ng-content>
    </div>
  </mat-sidenav-content>
</mat-sidenav-container>


问:
how to run code when Microsoft toast notification button is pressed in javascript
I am trying to make a microsoft toast notification that has buttons or so called "actions"
in this code i have 3 buttons A,B,C and i want to check if any of them are clicked and if so the run a line of code
just for example if A is clicked then run debug.log('A')
how can i do that?
(im new to visual studio and javascript)</p>

```<code>document.addEventListener('keydown', logKey);

function logKey(e) {
    var notifLib = Microsoft.Toolkit.Uwp.Notifications;

    var toastContent = new notifLib.ToastContent();
    var toastVisual = new notifLib.ToastVisual();
    var toastBindingGeneric = new notifLib.ToastBindingGeneric();

    var adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "Hello World";
    toastBindingGeneric.children.push(adaptiveText);

    adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "This is a simple toast message";
    toastBindingGeneric.children.push(adaptiveText);

    toastVisual.bindingGeneric = toastBindingGeneric;

    toastContent.visual = toastVisual;

    var toastActionsCustom = new notifLib.ToastActionsCustom();

    var toastButton = new notifLib.ToastButton("a", "action=at&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("b", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("c", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastContent.actions = toastActionsCustom;

    // Create the toast notification
    var toastNotif = new Windows.UI.Notifications.ToastNotification(toastContent.getXml());

    // And send the notification
    Windows.UI.Notifications.ToastNotificationManager.createToastNotifier().show(toastNotif);
};
</code>```

答:
for UWP applications, when the notification button is pressed, the activated event of the application will be triggered. In javascript, it can be written like this:

Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
     if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.toastNotification) {
          console.log(activatedEventArgs.argument);
     }
});
```

<p>If you are using WinJs to build your application, you can find the corresponding code block that handles the click of the Toast notification in the <code>app.onactivated</code> event in <strong>main.js</strong></p>

<pre class="lang-js prettyprint-override"><code>...
else if (args.detail.kind === activation.ActivationKind.launch) {
    if (args.detail.arguments) {
    }
    ...
}
...
</code>```

Body:
I am trying to make a microsoft toast notification that has buttons or so called "actions"
in this code i have 3 buttons A,B,C and i want to check if any of them are clicked and if so the run a line of code
just for example if A is clicked then run debug.log('A')
how can i do that?
(im new to visual studio and javascript)

document.addEventListener('keydown', logKey);

function logKey(e) {
    var notifLib = Microsoft.Toolkit.Uwp.Notifications;

    var toastContent = new notifLib.ToastContent();
    var toastVisual = new notifLib.ToastVisual();
    var toastBindingGeneric = new notifLib.ToastBindingGeneric();

    var adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "Hello World";
    toastBindingGeneric.children.push(adaptiveText);

    adaptiveText = new notifLib.AdaptiveText();
    adaptiveText.text = "This is a simple toast message";
    toastBindingGeneric.children.push(adaptiveText);

    toastVisual.bindingGeneric = toastBindingGeneric;

    toastContent.visual = toastVisual;

    var toastActionsCustom = new notifLib.ToastActionsCustom();

    var toastButton = new notifLib.ToastButton("a", "action=at&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("b", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastButton = new notifLib.ToastButton("c", "action=b&userId=1");
    toastButton.activationType = notifLib.ToastActivationType.background;
    toastActionsCustom.buttons.push(toastButton);

    toastContent.actions = toastActionsCustom;

    // Create the toast notification
    var toastNotif = new Windows.UI.Notifications.ToastNotification(toastContent.getXml());

    // And send the notification
    Windows.UI.Notifications.ToastNotificationManager.createToastNotifier().show(toastNotif);
};

Body:
for UWP applications, when the notification button is pressed, the activated event of the application will be triggered. In javascript, it can be written like this:

Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
     if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.toastNotification) {
          console.log(activatedEventArgs.argument);
     }
});

If you are using WinJs to build your application, you can find the corresponding code block that handles the click of the Toast notification in the app.onactivated event in main.js

...
else if (args.detail.kind === activation.ActivationKind.launch) {
    if (args.detail.arguments) {
    }
    ...
}
...


问:
What are the best practices for Azure account setup with a B2C tenant?
I'm trying to find information on how to best set up an Azure account/directory when leveraging a B2C tenant as part of the process. This includes how to have instances for both Production and Development.

Right now I have a primary Directory with a subscription, storage resource, and B2C tenant. But there's a second Directory which was created IIRC as part of the B2C setup. There are no resources under that Directory and I'm confused as to what its purpose is.

Should I add additional resources that I need to the main Directory or under that B2C one?

What exactly does that B2C directory do other than sit there? I'm so confused by its presence.

Is there an easy way to clone everything and create a copy for Prod/Dev or is it all manual?

Edit: It should have been obvious but wasn't.. the reason for the additional B2C AD is that it acts a container for all your users. Makes sense once you think about it.

答:
1.Should I add additional resources that I need to the main Directory or under that B2C one?

It depends on you, if you want the B2C tenant be able to access Azure resources, you can link your B2C tenant to your Azure subscription. If you just want to use Azure B2C to authenticate users, there is no need to link it to azure subscription.

2.What exactly does that B2C directory do other than sit there? I'm so confused by its presence.

The B2C AD is a feature of Azure B2C, just like Azure AD. If you want to use Azure AD as the provider to your b2c sign flow, you can use this one or some other Azure AD tenants.

3.Is there an easy way to clone everything and create a copy for Prod/Dev or is it all manual?

I think you need to clone them manually. Some Azure resources also have a feature of clone. If you have some resources which need to be deployed multiple times, you can use ARM template deployment.


问:
repeated logging in log 4j in java
I used log4j in a java program. I initialized it with :

```<code>BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}
</code>```

But, during the execution of the program i get 3 log statements instead of one. For example,

```<code>3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

instead of one line

```<code>1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
</code>```

Are there any extra configurations to be done to log4j to avoid this?

答:
Well, you haven't shown how your program is executing. Here's a complete program which only shows a single line:

```<code>import org.apache.log4j.*;

public class Test
{
    public static void main(String[] args)
    {
        BasicConfigurator.configure(); // logger configuration
        Logger logger = Logger.getLogger(Test.class);
        logger.setLevel(Level.DEBUG);
        logger.info("Hello");
    }
}
</code>```

Is it possible that your code really is running three times?

OwnerDisplayName: BHARATH

ContentLicense: CC BY-SA 2.5

Title: repeated logging in log 4j in java

Body:
I used log4j in a java program. I initialized it with :

BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}

But, during the execution of the program i get 3 log statements instead of one. For example,

3 lines
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

instead of one line

1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

Are there any extra configurations to be done to log4j to avoid this?

LastEditorDisplayName: Jon Skeet

Body:
Well, you haven't shown how your program is executing. Here's a complete program which only shows a single line:

import org.apache.log4j.*;

public class Test
{
    public static void main(String[] args)
    {
        BasicConfigurator.configure(); // logger configuration
        Logger logger = Logger.getLogger(Test.class);
        logger.setLevel(Level.DEBUG);
        logger.info("Hello");
    }
}

Is it possible that your code really is running three times?

OwnerDisplayName: Jon Skeet


问:
understand file processing with While vs For Loop
I am trying to read a large file using several methods. So my code is supposed to look for and count how many times the text "time_data" shows up in a file. The total count is actually 24. However using the code I havee, it only finds 4 counts of it using a while loop:

```<code>with open(filename) as f:
    time_data_count = 0
    while True:
        memcap = f.read(102400)
        if 'TIME_DATA' in memcap:
            time_data_count += 1
        if not memcap:
            break
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")
</code>```

Why is time_data_count only returning a count of 4? It's supposed to search through all of memcap and look increment each time it finds "time_data". I don't have this issue when I use a for loop like so:

```<code>with open(filename, 'r', buffering=102400) as f:
    time_data_count = 0
    for line in f:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")
</code>```

What am I missing? Yes the file does indeed have newlines

答:
It's most likely related to your if not statement as that is the only thing that would break the while loop. Since it is while True, theoretically it would run forever unless broken. Since there is only one line that can break the while loop it must be within there. As you know, a while loop needs to have a break point, I would personally do it this way:

```<code>    byt= 0 #count the number of bytes (that is your 102400)
    while True:
        memcap = f.read(102400)
        if 'TIME_DATA' in memcap:
            time_data_count += 1
            byt += 1 #iterate so that you count up to that value
        elif byt == 102400: #total number of bytes in the file
            break
</code>```

This will run until every byte of the file has been read and then it will break the while loop. It's similar to what you were doing except slightly different, should work if you want to stick with the while loop.

Body:
I am trying to read a large file using several methods. So my code is supposed to look for and count how many times the text "time_data" shows up in a file. The total count is actually 24. However using the code I havee, it only finds 4 counts of it using a while loop:

with open(filename) as f:
    time_data_count = 0
    while True:
        memcap = f.read(102400)
        if 'TIME_DATA' in memcap:
            time_data_count += 1
        if not memcap:
            break
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")

Why is time_data_count only returning a count of 4? It's supposed to search through all of memcap and look increment each time it finds "time_data". I don't have this issue when I use a for loop like so:

with open(filename, 'r', buffering=102400) as f:
    time_data_count = 0
    for line in f:
        if 'TIME_DATA' in line:
            time_data_count += 1
    if time_data_count > 20:
        print("time_data complete")
    else:
        print("incomplete time_data data")

What am I missing? Yes the file does indeed have newlines

Body:
It's most likely related to your if not statement as that is the only thing that would break the while loop. Since it is while True, theoretically it would run forever unless broken. Since there is only one line that can break the while loop it must be within there. As you know, a while loop needs to have a break point, I would personally do it this way:

    byt= 0 #count the number of bytes (that is your 102400)
    while True:
        memcap = f.read(102400)
        if 'TIME_DATA' in memcap:
            time_data_count += 1
            byt += 1 #iterate so that you count up to that value
        elif byt == 102400: #total number of bytes in the file
            break

This will run until every byte of the file has been read and then it will break the while loop. It's similar to what you were doing except slightly different, should work if you want to stick with the while loop.


问:
How to create a Woocommerce Product Filter with AJAX?
I wanted to create my own Product Filter for Woocommerce with AJAX, I don't want to use any plugin. But there is one problem though, I don't know how to fetch the products by the selected filter or I don't know how my filter will apply to the products.

For example, if I want to have a filter for Ratings.

HTML

```<code><select id="filter_ratings">
<option value="5">5 star</option>
<option value="4">4 star</option>
<option value="3">3 star</option>
<option value="2">2 star</option>
<option value="1">1 star</option>
</select>
</code>```

jQuery

```<code>jQuery('#filter_ratings').change(function() {
        var values = jQuery(this).val();
        jQuery.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {opc: values, action: 'filter_product_by_ratings', dataType: "json"},
            success: function(result){
                //Should I get all the products with the current filter?
                console.log('Filter Successful: ' + result);
            },
            error:function (xhr, ajaxOptions, thrownError) {
                console.log('Filter ERROR STATUS: ' + xhr.status);
                console.log('Filter Error: ' + thrownError);
            }
        });
    });
</code>```

function.php

```<code>add_action('wp_enqueue_scripts', 'add_js_scripts');
function add_js_scripts(){
    wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' =>   admin_url( 'admin-ajax.php' ) ) );
}

//call this function by ajax
function filter_product_by_ratings(){
   //what now?
   //How can I apply the current filter?
   //Should I fetch all the products by the current filter?
   //What about for other attributes like size, color, etc?
}
</code>```

is there a guide on how to apply filters to the products by code in Woocommerce?

答:
First of all, you will have an error of ajax_object as undefined or Object not found because you didn't localize it properly.

Look at your ajax url, ajax_object and ajax_url where in your function you localize it as ajax_object and ajaxurl. You simply missed the underscore in your ajax URL, it should be ajax_object.ajaxurl.

Refer to the link below on how to localize properly.
https://developer.wordpress.org/reference/functions/wp_localize_script/

With your question as how to filter the products, you can use the WP_Query then just change the arguments depending on your needs. For example, since you want to fetch the products only then the post_type should be product and the other arguments will vary on your needs like orderby, ratings, etc.

Here's a sample of what your missing code in your function.php.

```<code>function filter_products(){

    $select_opc = $_POST['opc']; //here is your post data, you can use its value to filter the products

    $args = array('post_type' => 'product','posts_per_page' => 12); //change this arguments depending on your needs
    $loop = new WP_Query( $args );
    $products = '';
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
            $products .= wc_get_template_part( 'content', 'product' );
        endwhile;
    } else {
            $products = 'No products found';
    }
    echo $products;
    exit;

}
</code>```

After getting the result of ajax, you can then replace the content of the products on your front-end, for example on your ajax.

```<code>//on ajax success
....
$('.products').html(result);
</code>```

I hope it helps.

Body:
I wanted to create my own Product Filter for Woocommerce with AJAX, I don't want to use any plugin. But there is one problem though, I don't know how to fetch the products by the selected filter or I don't know how my filter will apply to the products.

For example, if I want to have a filter for Ratings.

HTML

<select id="filter_ratings">
<option value="5">5 star</option>
<option value="4">4 star</option>
<option value="3">3 star</option>
<option value="2">2 star</option>
<option value="1">1 star</option>
</select>

jQuery

jQuery('#filter_ratings').change(function() {
        var values = jQuery(this).val();
        jQuery.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {opc: values, action: 'filter_product_by_ratings', dataType: "json"},
            success: function(result){
                //Should I get all the products with the current filter?
                console.log('Filter Successful: ' + result);
            },
            error:function (xhr, ajaxOptions, thrownError) {
                console.log('Filter ERROR STATUS: ' + xhr.status);
                console.log('Filter Error: ' + thrownError);
            }
        });
    });

function.php

add_action('wp_enqueue_scripts', 'add_js_scripts');
function add_js_scripts(){
    wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' =>   admin_url( 'admin-ajax.php' ) ) );
}

//call this function by ajax
function filter_product_by_ratings(){
   //what now?
   //How can I apply the current filter?
   //Should I fetch all the products by the current filter?
   //What about for other attributes like size, color, etc?
}

is there a guide on how to apply filters to the products by code in Woocommerce?

Body:
First of all, you will have an error of ajax_object as undefined or Object not found because you didn't localize it properly.

Look at your ajax url, ajax_object and ajax_url where in your function you localize it as ajax_object and ajaxurl. You simply missed the underscore in your ajax URL, it should be ajax_object.ajaxurl.

Refer to the link below on how to localize properly.
https://developer.wordpress.org/reference/functions/wp_localize_script/

With your question as how to filter the products, you can use the WP_Query then just change the arguments depending on your needs. For example, since you want to fetch the products only then the post_type should be product and the other arguments will vary on your needs like orderby, ratings, etc.

Here's a sample of what your missing code in your function.php.

function filter_products(){

    $select_opc = $_POST['opc']; //here is your post data, you can use its value to filter the products

    $args = array('post_type' => 'product','posts_per_page' => 12); //change this arguments depending on your needs
    $loop = new WP_Query( $args );
    $products = '';
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
            $products .= wc_get_template_part( 'content', 'product' );
        endwhile;
    } else {
            $products = 'No products found';
    }
    echo $products;
    exit;

}

After getting the result of ajax, you can then replace the content of the products on your front-end, for example on your ajax.

//on ajax success
....
$('.products').html(result);

I hope it helps.


问:
"Undefinded variable: http" error when I'm trying batch enrollment reference code at google classroom
I'm trying to test batch enrollment for build up the google classroom, but I found some compile error at batch.execute(http=**http**)

error message is "Undefinded variable: http"

this is the code and compile error occurred the last part of this code.

```<code>def callback(request_id, response, exception):
    if exception is not None:
        print('Error adding user "{0}" to the course course: {1}'.format(
            request_id, exception))
    else:
        print('User "{0}" added as a student to the course.'.format(
            response.get('profile').get('name').get('fullName')))
batch = service.new_batch_http_request(callback=callback)
for student_email in student_emails:
    student = {
        'userId': student_email
    }
    request = service.courses().students().create(courseId=course_id,
                                                  body=student)
    batch.add(request, request_id=student_email)
batch.execute(http=http)
</code>```

and the reference is below that.

https://developers.google.com/classroom/guides/batch#python

Somebody help me.

答:
Let's dig into the documentation to find the answer!

The error appears on a call to the execute function of the batch object.  So what kind of an object is batch?

It was returned from a call to the new_batch_http_request of the service object.  So what kind of an object is service?

It's not created in the reference code you cited, so we have to rummage around in the document to find some other code where something named service is created.  The authors probably assumed that service in this example is the same kind of object.

The Quickstart page for Python seems like a good place to look and sure enough, there is code that creates an object named service there:

service = build('classroom', 'v1', credentials=creds)

So we can guess that service was returned from a call to build.  So what is build?

It's defined in that same sample:

from googleapiclient.discovery import build

So now we have to find the documentation for googleapiclient.discovery.  A search for that name leads us to:

https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.discovery-module.html

Here we see that the build function returns a Resource.  So service is a Resource.

But when we look at the documentation for Resource, it has no function new_batch_http_request.  What foul treachery is this?

"new_batch_http_request" looks like a pretty distinctive string, so we can search for that.  Let's try the search box of the Google Classroom API site.

It only finds the Batching Requests page where we started.  But it also offers to search all of Google Developers.  So let's do that.

The search results then show that there are a lot of APIs with functions with this name and they all seem to create BatchHttpRequest objects, so the one for Resource probably does, too.  So what is a BatchHttpRequest?  Let's do another search for this name!

It turns out to be documented as part of the http module of the googleapiclient package at

https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http.BatchHttpRequest-class.html

The error came from a call to the execute function of the batch object, which we have guessed to be a BatchHttpRequest.  Fortunately, a BatchHttpRequest has an execute function and that execute function takes an http argument.  The documentation of the execute function says that the http argument can be omitted, but if it is supplied, it should be an httplib2.Http.

The reference code passes an object called http as the parameter also called http, but doesn't bother to construct it.  That's why the compiler is complaining that it's undefined.

So to get the code to compile, you should be able just to omit the http=http parameter.  Then maybe it will run and maybe it won't.  If it doesn't, you will have to figure out how to construct an appropriate Http object using the httplib2 library, with documentation at:

https://httplib2.readthedocs.io/en/latest/libhttplib2.html#http-objects

Body:
I'm trying to test batch enrollment for build up the google classroom, but I found some compile error at batch.execute(http=**http**)

error message is "Undefinded variable: http"

this is the code and compile error occurred the last part of this code.

def callback(request_id, response, exception):
    if exception is not None:
        print('Error adding user "{0}" to the course course: {1}'.format(
            request_id, exception))
    else:
        print('User "{0}" added as a student to the course.'.format(
            response.get('profile').get('name').get('fullName')))
batch = service.new_batch_http_request(callback=callback)
for student_email in student_emails:
    student = {
        'userId': student_email
    }
    request = service.courses().students().create(courseId=course_id,
                                                  body=student)
    batch.add(request, request_id=student_email)
batch.execute(http=http)

and the reference is below that.

https://developers.google.com/classroom/guides/batch#python

Somebody help me.


问:
Correct place to pass in parameters in Selenium testing?
What is the "proper" way to pass in parameters?

Code snippet below (pieces have been removed that aren't relevant)...

I am passing in the login parameters in the [TestMethod] itself, and not in the LoginPage class object.  Is that the right way to do this?  Or, should I be passing the strings into the LoginPage class itself?  (I realized there are other ways where I don't need to hard-code anywhere, but I am strictly referring to this hard-code scenario)

```<code>class LoginPage
{

    IWebDriver driver;

    By username = By.Id("user_login");
    By password = By.XPath(".//*[@id='user_pass']");
    By loginButton = By.Name("wp-submit");

    public void loginToWordpress(string userid, string pass)
    {
        driver.FindElement(username).SendKeys(userid);
        driver.FindElement(password).SendKeys(pass);
    }

}
</code>```

and the corresponding test....

```<code>   [TestMethod]
        public void assertPageSource()
        {
            LoginPage login = new LoginPage(driver);
            login.loginToWordpress("admin", "demo123");
            login.clickOnLoginButton();
        }
</code>```

答:
I can think of below ways:

1.@DataProvider annotation from TestNG can be used for passing parameters
Here's a good example : https://www.edureka.co/blog/dataprovider-in-testng/

2.Passing parameters using an excel file - you can save the username and passwords in the file(although not the best practice) and use the file for passing parameters. Apache POI is used for reading/writing Excel file in Java, not sure about C#

3.Create a table with usernames and passwords, connect to the table through your code and use the values as parameters

Body:
What is the "proper" way to pass in parameters?

Code snippet below (pieces have been removed that aren't relevant)...

I am passing in the login parameters in the [TestMethod] itself, and not in the LoginPage class object.  Is that the right way to do this?  Or, should I be passing the strings into the LoginPage class itself?  (I realized there are other ways where I don't need to hard-code anywhere, but I am strictly referring to this hard-code scenario)

class LoginPage
{

    IWebDriver driver;

    By username = By.Id("user_login");
    By password = By.XPath(".//*[@id='user_pass']");
    By loginButton = By.Name("wp-submit");

    public void loginToWordpress(string userid, string pass)
    {
        driver.FindElement(username).SendKeys(userid);
        driver.FindElement(password).SendKeys(pass);
    }

}

and the corresponding test....

   [TestMethod]
        public void assertPageSource()
        {
            LoginPage login = new LoginPage(driver);
            login.loginToWordpress("admin", "demo123");
            login.clickOnLoginButton();
        }


问:
How to use mixing in cypress of vue/cli 4 app?
In vue/cli 4 app using cypress for testing I want to use my mixing and for this in my
tests/e2e/specs/fileupload_tests.js I added declaration:

```<code>import faker from 'faker'
import 'cypress-file-upload'
import appMixin from '../../../src/appMixin'        // Full path is src/appMixin.js

describe('Admin category fileupload functionality', () => {
    it('category fileupload', () => {
        ...
</code>```

But I see error in my browser :
/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/node_modules/@babel/runtime/helpers/esm/typeof.js:1

```<code>export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
</code>```

That is not error of invalid mixing path - in this case I got different error.

Which way is valid ?

```<code>"axios": "^0.19.0",
"core-js": "^3.3.2",
"cypress-file-upload": "^3.5.3",
"vue": "^2.6.10",
</code>```

MODIFIED :
I commented import in my fileupload_tests.js  file

and I added 1 line in tests/e2e/support/index.js :

```<code>import appMixin from '../../../src/appMixin'        // src/appMixin.js

// Import commands.js using ES2015 syntax:
import './commands'
</code>```

But running the test have error anyway:

```<code>/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/node_modules/@babel/runtime/helpers/esm/typeof.js:1
export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
</code>```

In my project I have some config files, like cypress.json or babel.config.js
Can it be that I have to add mixing declarations in one of these files?
If Yes, in which format?

MODIFIED # 2:
I successfully run command

```<code>npm install babel-preset-es2015 --save-dev
</code>```

and after that running tests I always got error :

```<code>/node_modules/@babel/runtime/helpers/esm/typeof.js:1
export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
</code>```

Even if in my tests.js I commented all “import ” lines

My package.json :

```<code>{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:e2e": "vue-cli-service test:e2e",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@voerro/vue-tagsinput": "^2.2.0",
    "axios": "^0.19.0",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "core-js": "^3.3.2",
    "cypress-file-upload": "^3.5.3",
    "file-saver": "^2.0.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "v-money": "^0.8.1",
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",
    "vue-avatar": "^2.1.8",
    "vue-context-menu": "^2.0.6",
    "vue-focus": "^2.1.0",
    "vue-head": "^2.2.0",
    "vue-js-modal": "^1.3.31",
    "vue-nav-tabs": "^0.5.7",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vue-simple-calendar": "^4.3.2",
    "vue-simple-suggest": "^1.10.1",
    "vue-slider-component": "^3.1.1",
    "vue-the-mask": "^0.11.1",
    "vue-upload-component": "^2.8.20",
    "vue-wysiwyg": "^1.7.2",
    "vue2-datepicker": "^3.3.0",
    "vue2-filters": "^0.8.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-e2e-cypress": "~4.2.0",
    "@vue/cli-plugin-eslint": "~4.2.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "babel-eslint": "^10.0.3",
    "bootstrap": "^4.3.1",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.1.2",
    "faker": "^4.1.0",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {
      "semi": [
        2,
        "never"
      ]
    }
  }
}
</code>```

Was it wrong version of babel ?
Which is Correct ?

Thanks!

答:
@babel/runtime/helpers/esm/typeof.js

Can you try with older version of babel, just do npm install babel-preset-es2015 --save-dev

It turns out that earlier Babel was shipping with all the required plugin, including one that translates ES6 to ES5. But since Babel 6.0, you have to explicitly include plugins or presets (which include certain predefined plugins). So we will install Babel preset es2015 .

Source

Body:
In vue/cli 4 app using cypress for testing I want to use my mixing and for this in my
tests/e2e/specs/fileupload_tests.js I added declaration:

import faker from 'faker'
import 'cypress-file-upload'
import appMixin from '../../../src/appMixin'        // Full path is src/appMixin.js

describe('Admin category fileupload functionality', () => {
    it('category fileupload', () => {
        ...

But I see error in my browser :
/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/node_modules/@babel/runtime/helpers/esm/typeof.js:1

export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

That is not error of invalid mixing path - in this case I got different error.

Which way is valid ?

"axios": "^0.19.0",
"core-js": "^3.3.2",
"cypress-file-upload": "^3.5.3",
"vue": "^2.6.10",

MODIFIED :
I commented import in my fileupload_tests.js  file

and I added 1 line in tests/e2e/support/index.js :

import appMixin from '../../../src/appMixin'        // src/appMixin.js

// Import commands.js using ES2015 syntax:
import './commands'

But running the test have error anyway:

/mnt/_work_sdb8/wwwroot/lar/VApps/vtasks/node_modules/@babel/runtime/helpers/esm/typeof.js:1
export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

In my project I have some config files, like cypress.json or babel.config.js
Can it be that I have to add mixing declarations in one of these files?
If Yes, in which format?

MODIFIED # 2:
I successfully run command

npm install babel-preset-es2015 --save-dev

and after that running tests I always got error :

/node_modules/@babel/runtime/helpers/esm/typeof.js:1
export default function _typeof(obj) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

Even if in my tests.js I commented all “import ” lines

My package.json :

{
  "name": "ctasks",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:e2e": "vue-cli-service test:e2e",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@voerro/vue-tagsinput": "^2.2.0",
    "axios": "^0.19.0",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "core-js": "^3.3.2",
    "cypress-file-upload": "^3.5.3",
    "file-saver": "^2.0.2",
    "font-awesome": "^4.7.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "v-money": "^0.8.1",
    "vee-validate": "^3.1.0",
    "vue": "^2.6.10",
    "vue-avatar": "^2.1.8",
    "vue-context-menu": "^2.0.6",
    "vue-focus": "^2.1.0",
    "vue-head": "^2.2.0",
    "vue-js-modal": "^1.3.31",
    "vue-nav-tabs": "^0.5.7",
    "vue-notification": "^1.3.20",
    "vue-router": "^3.1.3",
    "vue-select": "^3.2.0",
    "vue-simple-calendar": "^4.3.2",
    "vue-simple-suggest": "^1.10.1",
    "vue-slider-component": "^3.1.1",
    "vue-the-mask": "^0.11.1",
    "vue-upload-component": "^2.8.20",
    "vue-wysiwyg": "^1.7.2",
    "vue2-datepicker": "^3.3.0",
    "vue2-filters": "^0.8.0",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.0.0",
    "@vue/cli-plugin-e2e-cypress": "~4.2.0",
    "@vue/cli-plugin-eslint": "~4.2.0",
    "@vue/cli-plugin-router": "^4.0.0",
    "@vue/cli-plugin-vuex": "^4.0.0",
    "@vue/cli-service": "^4.0.0",
    "babel-eslint": "^10.0.3",
    "bootstrap": "^4.3.1",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.1.2",
    "faker": "^4.1.0",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper.js": "^1.16.0",
    "sass-loader": "^8.0.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {
      "semi": [
        2,
        "never"
      ]
    }
  }
}

Was it wrong version of babel ?
Which is Correct ?

Thanks!


问:
C++ small function not inlining
I have a hot and critical path function (about 45% of cycles:ppp as per perf record) in my C++17 application that is not being inlined as I would expect. It's a tiny function -- it simply returns the value of an atomic pointer member. The disassembly confirms that the function is just four assembly instructions, including the retq. Furthermore, there is only a single caller of this function in the entire build. I've even declared this function as __attribute__((always_inline)). Yet, there's a call and return to this function being generated.

The caller is in file A and the callee is in file B.

Some additional notes:

I'm compiling with -O3 and -march=native

The callee is declared const and doesn't access any static members

I'm doing link-type optimization via -flto when linking

I'm using icc (ICC) 19.0.3.199 to compile

The functions are simple member functions that are const and not templates, all with a dozen or fewer x86 assembly instructions

Actually, I've simplified a bit -- there are actually two places where this lack of inlining is happening in my application. File B has a function F1, which calls File A's F2, which calls File B's F3 (F2 and F3 are the ones listed above).

File A:

```<code>F2() {
  F3();
}
</code>```

File B:

```<code>F1() {
  F2();
}

F3() {}
</code>```

How can I get all of these to inline into one function? Another more fundamental question: can a function defined in a different file be inlined (perhaps using LTO)?

答: "Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call." A translation unit means a source file together with it headers that compiles to one compilation unit. So in this case you could try to declare the function in the same source file or the in the included header.</p>

Title: C++ small function not inlining

Body:
I have a hot and critical path function (about 45% of cycles:ppp as per perf record) in my C++17 application that is not being inlined as I would expect. It's a tiny function -- it simply returns the value of an atomic pointer member. The disassembly confirms that the function is just four assembly instructions, including the retq. Furthermore, there is only a single caller of this function in the entire build. I've even declared this function as __attribute__((always_inline)). Yet, there's a call and return to this function being generated.

The caller is in file A and the callee is in file B.

Some additional notes:

I'm compiling with -O3 and -march=native

The callee is declared const and doesn't access any static members

I'm doing link-type optimization via -flto when linking

I'm using icc (ICC) 19.0.3.199 to compile

The functions are simple member functions that are const and not templates, all with a dozen or fewer x86 assembly instructions

Actually, I've simplified a bit -- there are actually two places where this lack of inlining is happening in my application. File B has a function F1, which calls File A's F2, which calls File B's F3 (F2 and F3 are the ones listed above).

File A:

F2() {
  F3();
}

File B:

F1() {
  F2();
}

F3() {}

How can I get all of these to inline into one function? Another more fundamental question: can a function defined in a different file be inlined (perhaps using LTO)?


问:
Transfer list of dictionaries from python to json file
I have a list of dictionaries in python with the format:

```<code>[{key1a: value1a, key2a: values2a}, {key1b: value1b, key2b: values2b}, ...]
</code>```

I need to create a json file with the format:

Line 1: {key1a: value1a, key2a: values2a}

Line 2: {key1b: value1b, key2b: values2b}
...

I know that I can write json files with:

```<code>with open('data.json', 'w') as outfile:
    json.dump(data_json, outfile)
</code>```

But I need the exact format I described, without ',' separation between lines and [..] brackets.

答:
I am not sure if this is what you are looking for but here it is:</p>

```<code>s = [{"key1a": "value1a", "key2a": "values2a"}, {"key1b": "value1b", "key2b": "values2b"}]

with open("data.json", "w+") as f:
    for i in s:
        json.dump(i, f)
        f.write("\n")
</code>```

Body:
I have a list of dictionaries in python with the format:

[{key1a: value1a, key2a: values2a}, {key1b: value1b, key2b: values2b}, ...]

I need to create a json file with the format:

Line 1: {key1a: value1a, key2a: values2a}

Line 2: {key1b: value1b, key2b: values2b}
...

I know that I can write json files with:

with open('data.json', 'w') as outfile:
    json.dump(data_json, outfile)

But I need the exact format I described, without ',' separation between lines and [..] brackets.

Body:
I am not sure if this is what you are looking for but here it is:

s = [{"key1a": "value1a", "key2a": "values2a"}, {"key1b": "value1b", "key2b": "values2b"}]

with open("data.json", "w+") as f:
    for i in s:
        json.dump(i, f)
        f.write("\n")