问:
How to get the height of ListView.builder() widgets to be the height of the entire stack?
I have a ListView.builder() inside a column, and I would like to tell the LisView.builder to set the height according to the height of the widget that it will be returning from the builder method. How do I do that? </p>

答:
I am not sure but looking at your question it looks like you want to render listview within the sizes which child widgets are taking
For that we can assign mainAxisSize: MainAxisSize.min, to column and shrinkWrap: true to Listview.builder

```<code>class _MyHomePageState extends State<MyHomePage> {
  List<String> itemsList = [
    "item0",
    "item1",
    "item2",
    "item3",
    "item4",
    "item5"
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView Sample"),
      ),
      body: Container(
        color: Colors.black54,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ListView.builder(
              shrinkWrap: true,
                itemCount: itemsList.length,
                itemBuilder: (context, index) {
                  return Container(
                      child:
                      Align(
                        alignment: Alignment.centerRight,
                        child:Text(
                          itemsList[index],
                          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                        ),),
                      width: 100,
                      height: 20,
                      margin: EdgeInsets.only(bottom: 10),
                      color: Colors.red);
                }),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I am not sure but looking at your question it looks like you want to render listview within the sizes which child widgets are taking
For that we can assign mainAxisSize: MainAxisSize.min, to column and shrinkWrap: true to Listview.builder

class _MyHomePageState extends State<MyHomePage> {
  List<String> itemsList = [
    "item0",
    "item1",
    "item2",
    "item3",
    "item4",
    "item5"
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ListView Sample"),
      ),
      body: Container(
        color: Colors.black54,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ListView.builder(
              shrinkWrap: true,
                itemCount: itemsList.length,
                itemBuilder: (context, index) {
                  return Container(
                      child:
                      Align(
                        alignment: Alignment.centerRight,
                        child:Text(
                          itemsList[index],
                          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                        ),),
                      width: 100,
                      height: 20,
                      margin: EdgeInsets.only(bottom: 10),
                      color: Colors.red);
                }),
          ],
        ),
      ),
    );
  }
}


来源: stackexchange

问:
CakePHP 3.x case statement on order
I am trying to use a CASE statement on the order of a MySQL statement in CakePHP 3.x app. The simple select is as follows:

```<code>$articles = $this->Articles->find()
    ->where($conditions)
    ->order(function ($exp, $q) {
        return $exp->addCase(
            [
                $q->newExpr()->gt('Articles.modified', (new Time())->subDays(365)) // article has been updated in the last x days
                    ],
            ['priority'], # values matching conditions
            ['string'] # type of each value
        );
    })
->limit(15)
->all();
</code>```

The following SQL is generated:

```<code>SELECT `Articles`.`id` AS `Articles__id`, ....
FROM `articles` `Articles`
WHERE (`publish` < :c0 AND `Articles`.`publish` > :c1)
ORDER BY CASE WHEN `Articles`.`modified` > :c2 THEN :param3 END LIMIT 15
</code>```

The case statement is not correct because it is missing the DESC order which should come after the 'END' - see this fiddle:

http://sqlfiddle.com/#!9/8df161/5

I'm not sure if this is a limitation with how CakePHP handles CASE?

Further I require a second order after the case statement to order by 'publish' desc.

答:
Expressions passed to Query::order() must generate everything required by the ORDER BY clause, including the direction keyword.

If the expression that you're using doesn't support that, then you can use Query::oderAsc() or Query::oderDesc(), which will append the respective direction keyword accordingly.

$query = $this->Articles->find();
$query
    ->where($conditions)
    ->orderDesc(
        $query->newExpr()->addCase(/* ... */)
    )
    // ...
```

See also

Cookbook > Database Access & ORM > Query Builder > Selecting Data

ContentLicense: CC BY-SA 4.0

Title: CakePHP 3.x case statement on order

Body:
I am trying to use a CASE statement on the order of a MySQL statement in CakePHP 3.x app. The simple select is as follows:

$articles = $this->Articles->find()
    ->where($conditions)
    ->order(function ($exp, $q) {
        return $exp->addCase(
            [
                $q->newExpr()->gt('Articles.modified', (new Time())->subDays(365)) // article has been updated in the last x days
                    ],
            ['priority'], # values matching conditions
            ['string'] # type of each value
        );
    })
->limit(15)
->all();

The following SQL is generated:

SELECT `Articles`.`id` AS `Articles__id`, ....
FROM `articles` `Articles`
WHERE (`publish` < :c0 AND `Articles`.`publish` > :c1)
ORDER BY CASE WHEN `Articles`.`modified` > :c2 THEN :param3 END LIMIT 15

The case statement is not correct because it is missing the DESC order which should come after the 'END' - see this fiddle:

http://sqlfiddle.com/#!9/8df161/5

I'm not sure if this is a limitation with how CakePHP handles CASE?

Further I require a second order after the case statement to order by 'publish' desc.

Body:
Expressions passed to Query::order() must generate everything required by the ORDER BY clause, including the direction keyword.

If the expression that you're using doesn't support that, then you can use Query::oderAsc() or Query::oderDesc(), which will append the respective direction keyword accordingly.

$query = $this->Articles->find();
$query
    ->where($conditions)
    ->orderDesc(
        $query->newExpr()->addCase(/* ... */)
    )
    // ...

See also

Cookbook > Database Access & ORM > Query Builder > Selecting Data


问:
right to left direction not working properly on urdu font
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <span class='r2l'>خدا کرے کے میری عرض پاک پے اترے</span>
  <span class='r2l'>وہ فصل گل جسے </span>
  <span class='r2l'>اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو</span>
  <span class='r2l'>یہاں جو سبزہ اگے ہمیشہ سبز رہے</span>
  <span class='r2l'>اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا</span>
  <span class='r2l'> اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</span>
</body>

</html></code>```

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

答:
direction property on itself works on block level elements , span is not block

use p tag instead

.r2l {
  direction: rtl;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <p class='r2l'>خدا کرے کے میری عرض پاک پے اترےوہ فصل گل جسے اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں سے خزاں کو گزارنے کی مجال نہ ہویہاں جو سبزہ اگے ہمیشہ سبز رہےاور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو تہذیب و فن کا اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</p>
</body>

</html></code>```

Body:
I have urdu text in html tag (span). Urdu is written right to left, so I applied direction:rtl. But it doesn't seem to work because on last line, it leaves space on right. Example will better explain.

.r2l {
  direction: rtl;
}

  خدا کرے کے میری عرض پاک پے اترے
  وہ فصل گل جسے
  اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں
  سے خزاں کو گزارنے کی مجال نہ ہو
  یہاں جو سبزہ اگے ہمیشہ سبز رہے
  اور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام
   ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو
   تہذیب و فن کا
   اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے
     میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو

If you run the snippet and see last line, it doesn't start from right instead it leaves space empty.

Edit
Actual scenario added to html, point of having spans is I attach an attribute to each span which is shown on hover (it is time of text added into database)

Body:
direction property on itself works on block level elements , span is not block

use p tag instead

.r2l {
  direction: rtl;
}

<html>

<head>
</head>

<body>
  <p class='r2l'>خدا کرے کے میری عرض پاک پے اترےوہ فصل گل جسے اندیشہ زوال نہ ہویہاں جو پھول کھلے کھلا رہےصدیوں یہاں سے خزاں کو گزارنے کی مجال نہ ہویہاں جو سبزہ اگے ہمیشہ سبز رہےاور ایسا سبز کے جسکیکوئی مثال نہ ہوخدا کرے کے نہ خام ہو سر وقار وطن اور اس کے حسن کو تشوش ماہ وسا ل نہ ہو ہر ایک فرد ہو تہذیب و فن کا اوج و کمال کوئی ملول نہ ہو کوئی خستہ حال نہ ہوخدا کرے میرے ایک بھی ہم وطن کے لئےحیات جرم نہ ہو، زندگی وبال نہ ہو</p>
</body>

</html>


问:
How can you stop a C1.Win.C1FlexGrid grid from scrolling in window?
I have C1FlexGrid  grid in windowform, then scroll down so that the lower half of the grid is shown, then click on a control outside the grid, then click on a line in the grid, the grid scrolls up to the top and the wrong row in the grid is selected.
the grid scroll happens before the events fire. I want to stop autoscroll when grid get focus.

Any suggestions?

答:
I figure out in our custom grid control inherited from C1FlexGrid has a method OnEnter

```<code>public class FAGrid : C1FlexGrid
{
       public FAGrid();
       //
       protect override void  OnEnter(EventArgs e)
       {
         this.Select(1,1);
          base.OnEnter(e);
       }
}
</code>```

This is a cause of strange behavior. I removed OnEnter method, it works. Thank you.

Body:
I figure out in our custom grid control inherited from C1FlexGrid has a method OnEnter

public class FAGrid : C1FlexGrid
{
       public FAGrid();
       //
       protect override void  OnEnter(EventArgs e)
       {
         this.Select(1,1);
          base.OnEnter(e);
       }
}

This is a cause of strange behavior. I removed OnEnter method, it works. Thank you.


问:
java.io.FileNotFoundException: open failed: EISDIR (Is a directory)
I am trying to record audio in my Piano app in android studio using MediaRecorder. After searching for answers on how to save the file as getExternalPublicDirectory is deprecated so i used context.getExternalFilesDir(null).getAbsolutePath(); . Now when i run the app and hit the record button , i get this error java.io.FileNotFoundException: open failed: EISDIR (Is a directory) in the line mediaRecorder.prepare(); .. Please Help!!

```<code>private void startRecording() throws IOException {

        try {
            String path = context.getExternalFilesDir(null).getAbsolutePath();
            audioFile = new File(path);
        } catch (Exception e) {
            Log.e("Error Tag", "external storage access error " + e.getMessage());
            return;
        }

        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

         mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
         mediaRecorder.setOutputFile(audioFile.getAbsolutePath());

            mediaRecorder.prepare();
            mediaRecorder.start();
</code>```

答:
Getting java.io.FileNotFoundException: open failed: EISDIR (Is a directory) is what expected since the path that you're providing to setOutputFile() points to a directory and not a file to save the recorded data.

The documentation is clear,

Sets the path of the output file to be produced.

Try and fix your path,

```<code>String dirPath = context.getExternalFilesDir(null).getAbsolutePath();
String filePath = direPath + "/recording";
audioFile = new File(filePath);
</code>```

Body:
I am trying to record audio in my Piano app in android studio using MediaRecorder. After searching for answers on how to save the file as getExternalPublicDirectory is deprecated so i used context.getExternalFilesDir(null).getAbsolutePath(); . Now when i run the app and hit the record button , i get this error java.io.FileNotFoundException: open failed: EISDIR (Is a directory) in the line mediaRecorder.prepare(); .. Please Help!!

private void startRecording() throws IOException {

        try {
            String path = context.getExternalFilesDir(null).getAbsolutePath();
            audioFile = new File(path);
        } catch (Exception e) {
            Log.e("Error Tag", "external storage access error " + e.getMessage());
            return;
        }

        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

         mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
         mediaRecorder.setOutputFile(audioFile.getAbsolutePath());

            mediaRecorder.prepare();
            mediaRecorder.start();

Body:
Getting java.io.FileNotFoundException: open failed: EISDIR (Is a directory) is what expected since the path that you're providing to setOutputFile() points to a directory and not a file to save the recorded data.

The documentation is clear,

Sets the path of the output file to be produced.

Try and fix your path,

String dirPath = context.getExternalFilesDir(null).getAbsolutePath();
String filePath = direPath + "/recording";
audioFile = new File(filePath);


问:
How do I join two documents by id
I need some help with elasticsearch
I want to join two things the schema for the first thing looks like

STAT GROUP

```<code>{
    "_id": 38282922829,
    "statValues": [{
          _ref: 282828290,
     }]
}
</code>```

STAT DATA

```<code>{
    "_id": 282828290,
    "key": itemsGained
}
</code>```

As you can see, I want to join all the refs in statvalues with the id for the stat data. How would I do this?

答:
You need to use $unwind operator and $lookup operator to do this.

db.STAT_GROUP.aggregate([
  {
     $unwind: '$statValues'
  },
  {
     $lookup: {
       from: 'STAT_DATA',
       localField: 'statValues._ref',
       foreignField: '_id',
       as: 'Refs'
     }
  }
])
```

MongoPlayGroundLink

Title: How do I join two documents by id

Body:
I need some help with elasticsearch
I want to join two things the schema for the first thing looks like

STAT GROUP

{
    "_id": 38282922829,
    "statValues": [{
          _ref: 282828290,
     }]
}

STAT DATA

{
    "_id": 282828290,
    "key": itemsGained
}

As you can see, I want to join all the refs in statvalues with the id for the stat data. How would I do this?

Body:
You need to use $unwind operator and $lookup operator to do this.

db.STAT_GROUP.aggregate([
  {
     $unwind: '$statValues'
  },
  {
     $lookup: {
       from: 'STAT_DATA',
       localField: 'statValues._ref',
       foreignField: '_id',
       as: 'Refs'
     }
  }
])

MongoPlayGroundLink


问:
smarty processes strong (text) format over php -> put out modified php only
Have prepared a string modification with php in the classes file. Now in the smarty template (tpl) file when outputting the string I get a wrong text format. The project uses smarty 3.1-DEV and php 5.6.

I have this php code and assigned the variable in php class file:

```<code>    $pattern = '/' . implode('|', $allergens_searchnames) . '/iu';
    echo preg_replace_callback($pattern, function ($m) {
    return mb_strtoupper($m[0]); }, $prodIngredients);
    }
    $this->assign("articleIngredients", $prodIngredients);
</code>```

Outputting directly with "echo" over classes file I get on front end the desired format:
"Zutaten:
MARILLEn (75%), Zucker, Zitronensaft, Geliermittel: PEKTINe (aus Apfel)"

Implementation over smarty output is wrong:
"Zutaten:
Marillen (75%), Zucker, Zitronensaft, Geliermittel: Pektine (aus Apfel)"

Here like I implemented to the tpl-file:

```<code><span class="pull-right">
{if isset($articleIngredients)}
<p>{$articleIngredients|unescape:'html'}</p>
{/if}
</span>
</code>```

Due to the fact that I don't know much of the project and of smarty it is nearly impossible to fix this for me. Any help is appreciated.

答:
I found a solution to implement it directly on the template: smarty replace multiple values

problem is to hardcode all diffrent possibilities to replace into two arrays. Maybe I can find another solution for this.

Body:
Have prepared a string modification with php in the classes file. Now in the smarty template (tpl) file when outputting the string I get a wrong text format. The project uses smarty 3.1-DEV and php 5.6.

I have this php code and assigned the variable in php class file:

    $pattern = '/' . implode('|', $allergens_searchnames) . '/iu';
    echo preg_replace_callback($pattern, function ($m) {
    return mb_strtoupper($m[0]); }, $prodIngredients);
    }
    $this->assign("articleIngredients", $prodIngredients);

Outputting directly with "echo" over classes file I get on front end the desired format:
"Zutaten:
MARILLEn (75%), Zucker, Zitronensaft, Geliermittel: PEKTINe (aus Apfel)"

Implementation over smarty output is wrong:
"Zutaten:
Marillen (75%), Zucker, Zitronensaft, Geliermittel: Pektine (aus Apfel)"

Here like I implemented to the tpl-file:

{if isset($articleIngredients)}

{$articleIngredients|unescape:'html'}

{/if}

Due to the fact that I don't know much of the project and of smarty it is nearly impossible to fix this for me. Any help is appreciated.


问:
Google Search Console shows "Disallowed attribute or attribute value present in HTML tag " for <amp-img layout="fixed"
I don't understand why the layout="fixed" is an disallowed attribute value. Could anyone please help find a solution to this error being shown for several pages across our Magento store?

```<code><amp-img layout="fixed" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" class="lazy lazy-loading lazy-blur p1only" name="NewportHotHero" data-src="/images/5b22c63cd95b2.jpg" width="1500" id="NewportHotHero" height="1"></amp-img></a>
</code>```

The actual content for this category in the Magento Admin is as follows:

```<code><p><a href="#products"><img id="NewportHotHero" class="p1only" style="display: none;" src="/images/5b22c63cd95b2.jpg" width="1500" name="NewportHotHero" border="0" /></a> <a name="pro_d"></a></p>
</code>```

答:
Your all attribute looks right, except name="NewportHotHero".

The

"name"

attribute is not documented in  documentation.

Or you can play your code posted here and see the error.

Body:
I don't understand why the layout="fixed" is an disallowed attribute value. Could anyone please help find a solution to this error being shown for several pages across our Magento store?

<amp-img layout="fixed" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" class="lazy lazy-loading lazy-blur p1only" name="NewportHotHero" data-src="/images/5b22c63cd95b2.jpg" width="1500" id="NewportHotHero" height="1"></amp-img>

The actual content for this category in the Magento Admin is as follows:


问:
Kotlin App Crash if back button pressed during fetching API
So i have the problem that the App will crash if the Back button is pressed during fetching service in a fragment. Currently I'm using Retrofit Library to do the service calling tasks. Below is the code snippet of the fragment :

ProductStockOutletListFragment.kt

```<code>override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_product_stock_outlet_list, container, false)

    //Show Progressbar While loading data
    binding.progressBar.visibility = View.VISIBLE

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    NetworkConfig().getOutletListService()
        .getOutlets()
        .enqueue(object : Callback<OutletListPOJODataClasses> {

            override fun onFailure(call: Call<OutletListPOJODataClasses>, t: Throwable) {

                if(call.isCanceled){
                    Toast.makeText((activity as AppCompatActivity), "Request Aborted", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
                }

            }

            override fun onResponse(
                call: Call<OutletListPOJODataClasses>,
                response: Response<OutletListPOJODataClasses>
            ) {
                binding.progressBar.visibility = View.GONE
                binding.rvOutletList.adapter = response.body()?.let { OutletListAdapter(it, this@ProductStockOutletListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show() //It points out this line. This is where the error happened.
            }

        })

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}
</code>```

If back button is pressed, it'll crash and return the error

kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.app.AppCompatActivity

The error pointed out at the below line at OnResponse()

Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()

Am I missing something ? Or maybe this is a lifecycle-related problem ? Let me know if there's anything Unclear.

Edit : As requested, This is the full error log.

答: You should only handle the response in your Fragment if your fragment is isAdded.

Body:
So i have the problem that the App will crash if the Back button is pressed during fetching service in a fragment. Currently I'm using Retrofit Library to do the service calling tasks. Below is the code snippet of the fragment :

ProductStockOutletListFragment.kt

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    (activity as AppCompatActivity).supportActionBar?.title = "Product List"

    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_product_stock_outlet_list, container, false)

    //Show Progressbar While loading data
    binding.progressBar.visibility = View.VISIBLE

    //Apply layout manager
    binding.rvOutletList.layoutManager = LinearLayoutManager((activity as AppCompatActivity))

    NetworkConfig().getOutletListService()
        .getOutlets()
        .enqueue(object : Callback<OutletListPOJODataClasses> {

            override fun onFailure(call: Call<OutletListPOJODataClasses>, t: Throwable) {

                if(call.isCanceled){
                    Toast.makeText((activity as AppCompatActivity), "Request Aborted", Toast.LENGTH_SHORT).show()
                }else{
                    Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
                }

            }

            override fun onResponse(
                call: Call<OutletListPOJODataClasses>,
                response: Response<OutletListPOJODataClasses>
            ) {
                binding.progressBar.visibility = View.GONE
                binding.rvOutletList.adapter = response.body()?.let { OutletListAdapter(it, this@ProductStockOutletListFragment) }

                Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show() //It points out this line. This is where the error happened.
            }

        })

    // Declare that this fragment has menu
    setHasOptionsMenu(true)

    // Set action bar title to "Outlet List"
    (activity as AppCompatActivity).supportActionBar?.title = "Outlet List"

    return binding.root
}

If back button is pressed, it'll crash and return the error

kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.app.AppCompatActivity

The error pointed out at the below line at OnResponse()

Toast.makeText((activity as AppCompatActivity), "Data retrieved!", Toast.LENGTH_SHORT).show()

Am I missing something ? Or maybe this is a lifecycle-related problem ? Let me know if there's anything Unclear.

Edit : As requested, This is the full error log.


问:
How to have Text with Icon in center Flutter?
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

```<code>FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),
</code>```

答:
You can use columns for this like:</p>

```<code>FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Column(
       children: <Widget>[
                Icon(Icons.power_settings_new),
                SizedBox(height:10),          // set height according to your needs
                Text('Logout'),
                ],
      ),
 ),
</code>```

Body:
I am using a package fab_circular_menu, That package is for an animated floating action button which opens up a circular menu. within it I want a widget as a menu item such that there is an icon and a text below. the icon is centered with text.

e.g.

How can I achieve this, as of now I am using the code below but it does not work well with different screen size.

FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Stack(
       overflow: Overflow.visible,
       children: <Widget>[
                Icon(Icons.power_settings_new),
                  Positioned(
                    bottom: -12,
                    right: -10,
                    child: Text('Logout'),
                  ),
                ],
      ),
 ),

Body:
You can use columns for this like:

FlatButton(
 splashColor: Colors.transparent,
 highlightColor: Colors.transparent,
 shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
 ),
 padding: EdgeInsets.only(bottom: 15),
 onPressed: () async {
   await _auth.signOut().then((value) {
   Navigator.of(context).popUntil((route) => route.isFirst);
   });
 },
 child: Column(
       children: <Widget>[
                Icon(Icons.power_settings_new),
                SizedBox(height:10),          // set height according to your needs
                Text('Logout'),
                ],
      ),
 ),


问:
Android - loadDrawableForCookie Resources$NotFoundException in setContentView
This crash occurs on some Android 6.0 devices when setContentView() is called in Activity.onCreate()

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3319)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3415)
  at android.app.ActivityThread.access$1100 (ActivityThread.java:229)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1821)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:148)
  at android.app.ActivityThread.main (ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)
Caused by: android.view.InflateException:
  at android.view.LayoutInflater.inflate (LayoutInflater.java:551)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:429)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:380)
  at com.android.internal.policy.PhoneWindow.setContentView (PhoneWindow.java:479)
  at android.app.Activity.setContentView (Activity.java:2400)
  at MyActivity.onCreate (MyActivity.java:42)
  at android.app.Activity.performCreate (Activity.java:6904)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1136)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3266)
Caused by: android.view.InflateException:
  at android.view.LayoutInflater.createView (LayoutInflater.java:657)
  at com.android.internal.policy.PhoneLayoutInflater.onCreateView (PhoneLayoutInflater.java:58)
  at android.view.LayoutInflater.onCreateView (LayoutInflater.java:706)
  at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:774)
  at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:716)
  at android.view.LayoutInflater.rInflate (LayoutInflater.java:847)
  at android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:810)
  at android.view.LayoutInflater.rInflate (LayoutInflater.java:855)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:495)
Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Constructor.newInstance (Native Method)
  at android.view.LayoutInflater.createView (LayoutInflater.java:631)
Caused by: android.content.res.Resources$NotFoundException:
  at android.content.res.Resources.loadDrawableForCookie (Resources.java:4289)
  at android.content.res.Resources.loadDrawable (Resources.java:4158)
  at android.content.res.Resources.loadDrawable (Resources.java:4003)
  at android.content.res.TypedArray.getDrawable (TypedArray.java:886)
  at android.view.View.<init> (View.java:4242)
  at android.widget.TextView.<init> (TextView.java:961)
  at android.widget.Button.<init> (Button.java:112)
  at android.widget.Button.<init> (Button.java:105)
  at android.widget.Button.<init> (Button.java:101)
Caused by: org.xmlpull.v1.XmlPullParserException:
  at android.graphics.drawable.StateListDrawable.inflateChildElements (StateListDrawable.java:182)
  at android.graphics.drawable.StateListDrawable.inflate (StateListDrawable.java:115)
  at android.graphics.drawable.Drawable.createFromXmlInner (Drawable.java:2551)
  at android.graphics.drawable.Drawable.createFromXml (Drawable.java:2322)
  at android.content.res.Resources.loadDrawableForCookie (Resources.java:4279)
</code>```

Is there a fix or workaround for this?

答: I think you pass a null layout/view in the setContentView Method. Can you attach the Method and the parameter you are passing?</p>

Body:
This crash occurs on some Android 6.0 devices when setContentView() is called in Activity.onCreate()

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3319)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3415)
  at android.app.ActivityThread.access$1100 (ActivityThread.java:229)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1821)
  at android.os.Handler.dispatchMessage (Handler.java:102)
  at android.os.Looper.loop (Looper.java:148)
  at android.app.ActivityThread.main (ActivityThread.java:7325)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)
Caused by: android.view.InflateException:
  at android.view.LayoutInflater.inflate (LayoutInflater.java:551)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:429)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:380)
  at com.android.internal.policy.PhoneWindow.setContentView (PhoneWindow.java:479)
  at android.app.Activity.setContentView (Activity.java:2400)
  at MyActivity.onCreate (MyActivity.java:42)
  at android.app.Activity.performCreate (Activity.java:6904)
  at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1136)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3266)
Caused by: android.view.InflateException:
  at android.view.LayoutInflater.createView (LayoutInflater.java:657)
  at com.android.internal.policy.PhoneLayoutInflater.onCreateView (PhoneLayoutInflater.java:58)
  at android.view.LayoutInflater.onCreateView (LayoutInflater.java:706)
  at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:774)
  at android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:716)
  at android.view.LayoutInflater.rInflate (LayoutInflater.java:847)
  at android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:810)
  at android.view.LayoutInflater.rInflate (LayoutInflater.java:855)
  at android.view.LayoutInflater.inflate (LayoutInflater.java:495)
Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Constructor.newInstance (Native Method)
  at android.view.LayoutInflater.createView (LayoutInflater.java:631)
Caused by: android.content.res.Resources$NotFoundException:
  at android.content.res.Resources.loadDrawableForCookie (Resources.java:4289)
  at android.content.res.Resources.loadDrawable (Resources.java:4158)
  at android.content.res.Resources.loadDrawable (Resources.java:4003)
  at android.content.res.TypedArray.getDrawable (TypedArray.java:886)
  at android.view.View.<init> (View.java:4242)
  at android.widget.TextView.<init> (TextView.java:961)
  at android.widget.Button.<init> (Button.java:112)
  at android.widget.Button.<init> (Button.java:105)
  at android.widget.Button.<init> (Button.java:101)
Caused by: org.xmlpull.v1.XmlPullParserException:
  at android.graphics.drawable.StateListDrawable.inflateChildElements (StateListDrawable.java:182)
  at android.graphics.drawable.StateListDrawable.inflate (StateListDrawable.java:115)
  at android.graphics.drawable.Drawable.createFromXmlInner (Drawable.java:2551)
  at android.graphics.drawable.Drawable.createFromXml (Drawable.java:2322)
  at android.content.res.Resources.loadDrawableForCookie (Resources.java:4279)

Is there a fix or workaround for this?


问:
cmake and Visual Studio 15 2017 generator - defining a build type
I work on Windows 10. I use cmake with Visual Studio 15 2017 generator. CMakeLists.txt requires CMAKE_BUILD_TYPE to be defined because it is used by Conan command called from cmake (execute_process). Here is the cmake command:

```<code>cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 15 2017" ..
</code>```

When I run build command this way:

```<code>cmake --build .
</code>```

I get the following error:

```<code>error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in Tests.obj
</code>```

Conan installs a release library (MT_StaticRelease) but CMAKE_BUILD_TYPE is ignored during build. Building works when I use the following command:

```<code>cmake --build . --config Release
</code>```

How does it work ? When I have to define --config buildType ? What with other generators, for example Ninja ?

答:
Visual Studio is a multi-configuration system. It means that the build type is selected at build time, lets say when you are using the IDE, you can select at that time the Release or Debug configuration and build. So when you are generating the Visual Studio solution (project generation or configure step), with cmake -G "Visual Studio ...", CMake doesnt have a value for CMAKE_BUILD_TYPE.

So the CMake invocations need to be different depending on the system:

In multi-configuration environments like Visual Studio, you use just 1 build folder:

```<code>$ mkdir build && cd build # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Visual Studio 15 2017 Win64" # Unless building for 32 bits, add the Win64
$ cmake --build . --config Release # Or open IDE, change config to Release and build
$ cmake --build . --config Debug
</code>```

In single-configuration environments like gcc with Makefiles, you need to use 1 folder for every configuration

```<code>$ mkdir build_release && cd build_release # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
$ cmake --build .
$ cd .. && mkdir build_debug && cd build_debug
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug
$ cmake --build .
</code>```

A different issue is the definition of the MT (static) Visual Studio runtime. It is possible that you have defined in your Conan profile compiler.runtime=MT, or it is being set by your CMakeLists.txt directly. Conan doesn't install such static MT_StaticRelease library, it is part of Visual Studio. If you are trying to statically link the visual studio environment, your used profiles should look like:

```<code># for debug
$ conan install .. -s build_type=Debug -s compiler.runtime=MTd
# for release
$ conan install .. -s build_type=Release -s compiler.runtime=MT
</code>```

Body:
I work on Windows 10. I use cmake with Visual Studio 15 2017 generator. CMakeLists.txt requires CMAKE_BUILD_TYPE to be defined because it is used by Conan command called from cmake (execute_process). Here is the cmake command:

cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 15 2017" ..

When I run build command this way:

cmake --build .

I get the following error:

error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in Tests.obj

Conan installs a release library (MT_StaticRelease) but CMAKE_BUILD_TYPE is ignored during build. Building works when I use the following command:

cmake --build . --config Release

How does it work ? When I have to define --config buildType ? What with other generators, for example Ninja ?

Body:
Visual Studio is a multi-configuration system. It means that the build type is selected at build time, lets say when you are using the IDE, you can select at that time the Release or Debug configuration and build. So when you are generating the Visual Studio solution (project generation or configure step), with cmake -G "Visual Studio ...", CMake doesnt have a value for CMAKE_BUILD_TYPE.

So the CMake invocations need to be different depending on the system:

In multi-configuration environments like Visual Studio, you use just 1 build folder:

$ mkdir build && cd build # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Visual Studio 15 2017 Win64" # Unless building for 32 bits, add the Win64
$ cmake --build . --config Release # Or open IDE, change config to Release and build
$ cmake --build . --config Debug

In single-configuration environments like gcc with Makefiles, you need to use 1 folder for every configuration

$ mkdir build_release && cd build_release # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
$ cmake --build .
$ cd .. && mkdir build_debug && cd build_debug
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug
$ cmake --build .

A different issue is the definition of the MT (static) Visual Studio runtime. It is possible that you have defined in your Conan profile compiler.runtime=MT, or it is being set by your CMakeLists.txt directly. Conan doesn't install such static MT_StaticRelease library, it is part of Visual Studio. If you are trying to statically link the visual studio environment, your used profiles should look like:

# for debug
$ conan install .. -s build_type=Debug -s compiler.runtime=MTd
# for release
$ conan install .. -s build_type=Release -s compiler.runtime=MT


问:
How to style angular material?
I want to use ngx-mat-intl-tel-input,  but I cannot set any style. . The button is taking 100% heigh everything gx-mat-intl-tel-input take 100% heigh.
here is my code:

.main {
    width: 400px;
    height: 500px;
    border: 1px solid blue;
    margin: 0 auto;
}

.phone {
    border: 1px solid black;
    margin: 300px;
}

ngx-mat-intl-tel-input>div>button {
    margin: 100px;
    background-color: green;
}

form {
    border: 1px solid black;
    width: 100%;
    background-color: green;
}

::ng-deep.mat-menu-panel {
    max-height: calc(100vh - 70vh);
}

.mat-button.mat-blue {
    color: blue;
}

.tp-button-row button,
.tp-button-row a {
    margin-right: 68px;
}

::ng-deep.mat-menu-panel {
    max-width: none !important;
}

::ng-deep ngx-mat-tel-input-container {
    width: 20px;
    border: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<form #f=ngForm [formGroup]="phoneForm">
    <div>
        <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>
    </div>
</form></code>```

// app.component file

```<code>import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  phoneForm = new FormGroup({
    phone: new FormControl('', Validators.required)

  });

  get f() {
    return this.phoneForm.errors;
  }

  ngOnInit() {
    // initialization logic goes here

  }

}
</code>```

答:
Angular use css encapsulation, that's why your styles are not applied.

if gx-mat-intl-tel-input is a component available in the project, you need to put your css into this component (in gx-mat-intl-tel-input.component.css) and that's it.

if you have no access to this component (you took it from a library for example), first of all you need to check with a browser web tool developer how the component is build. Check the html and the css already applied in the component.

After that, you need to play with the css already existing with applying new rules or override pre-existant rule (!important is your friend)

You have 3 places to write your css :

in the css file component using ngx-mat-intl-tel-input, apply your css rules with /deep/, >>> or ::ng-deep in front of each rule. It's disabling css encapsulation for a specific rule. Problem : this method is deprecated.

disable the encapsulation in the entire component by using ViewEncapsulation.None :

import {ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html',
  encapsulation: ViewEncapsulation.None
})
class AppComponent {}```

Be carefull : if you do that, all the css rules in app.component.css will be applied in all the project. That's why i don't recommand you to do that because that's confusing : later, you will apply a rule in this component and forgot the ViewEncapsulation is set to None.

Put your css in style.css, available in the root of your project. This will do the same than above, those rules will be applied in all your project but that's sound more logical because you know it is a global file. You can also use comments to clarify the desired scope of your css rules and avoid mess in your style.css

Title: How to style angular material?

Body:
I want to use ngx-mat-intl-tel-input,  but I cannot set any style. . The button is taking 100% heigh everything gx-mat-intl-tel-input take 100% heigh.
here is my code:

.main {
    width: 400px;
    height: 500px;
    border: 1px solid blue;
    margin: 0 auto;
}

.phone {
    border: 1px solid black;
    margin: 300px;
}

ngx-mat-intl-tel-input>div>button {
    margin: 100px;
    background-color: green;
}

form {
    border: 1px solid black;
    width: 100%;
    background-color: green;
}

::ng-deep.mat-menu-panel {
    max-height: calc(100vh - 70vh);
}

.mat-button.mat-blue {
    color: blue;
}

.tp-button-row button,
.tp-button-row a {
    margin-right: 68px;
}

::ng-deep.mat-menu-panel {
    max-width: none !important;
}

::ng-deep ngx-mat-tel-input-container {
    width: 20px;
    border: 1px solid blue;
}

<form #f=ngForm [formGroup]="phoneForm">

        <ngx-mat-intl-tel-input style="border: 2px solid red; padding: 10px; margin-left: 100px;width: 100px; height: 100px;" [preferredCountries]="[ 'us', 'gb']" [enablePlaceholder]="true" name="phone" formControlName="phone" #phone></ngx-mat-intl-tel-input>

</form>

// app.component file

import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  phoneForm = new FormGroup({
    phone: new FormControl('', Validators.required)

  });

  get f() {
    return this.phoneForm.errors;
  }

  ngOnInit() {
    // initialization logic goes here

  }

}

Body:
Angular use css encapsulation, that's why your styles are not applied.

if gx-mat-intl-tel-input is a component available in the project, you need to put your css into this component (in gx-mat-intl-tel-input.component.css) and that's it.

if you have no access to this component (you took it from a library for example), first of all you need to check with a browser web tool developer how the component is build. Check the html and the css already applied in the component.

After that, you need to play with the css already existing with applying new rules or override pre-existant rule (!important is your friend)

You have 3 places to write your css :

in the css file component using ngx-mat-intl-tel-input, apply your css rules with /deep/, >>> or ::ng-deep in front of each rule. It's disabling css encapsulation for a specific rule. Problem : this method is deprecated.

disable the encapsulation in the entire component by using ViewEncapsulation.None :

import {ViewEncapsulation} from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html',
  encapsulation: ViewEncapsulation.None
})
class AppComponent {}

Be carefull : if you do that, all the css rules in app.component.css will be applied in all the project. That's why i don't recommand you to do that because that's confusing : later, you will apply a rule in this component and forgot the ViewEncapsulation is set to None.

Put your css in style.css, available in the root of your project. This will do the same than above, those rules will be applied in all your project but that's sound more logical because you know it is a global file. You can also use comments to clarify the desired scope of your css rules and avoid mess in your style.css


问:
How can CoffeeScript be written in CoffeeScript?
So as a new web programmer (background is mostely in C,C++, and Python) with no javascript experience (or desire to experience it, based on what I have seen)  I have been doing some precursory research on CoffeeScript and am really liking what I see.  One cool little nuance I noticed was that CoffeeScript was written in CoffeeScript, which is cool... but I don't really understand how that is possible.  Unfortunately I opted to take Network Security instead of Compilers during my last senior level Computer Science courses.

I have heard of people writing languages in target language to interpret using existing compilers for that language, but I can't dig up any info on how this might work since this is the first implementation.

My guess is an embedded shell script that might take care of laying down some of the initial framework for building a self-referential (does this term properly describe this behavior?) language?

答:
This is nothing new. C compilers have been written in C. Python has been written in Python.

It's possible to use a compiler for Language X to compile a newer version of itself, with more features. It's called bootstrapping.

Bootstrapping a language

Writing a compiler in its own language

How do you write a compiler for a language in that language?

Bootstrapping a compiler: why?

BTW, if you want to learn more about compilers, despite having missed out at uni, have a look at Learning to write a compiler — specifically, the Dragon Book.

ContentLicense: CC BY-SA 3.0


问:
Python Pandas DataFrame read_csv UnicodeDecodeError
I have a 129 MB CSV file with 849,275 rows and 18 columns.  I'm trying to read the CSV file into a pandas DataFrame using read_csv.

When I use encoding='cp1252':

```<code>read_file = pd.read_csv('myfile.csv', encoding='cp1252')
</code>```

The error is quite long but ultimately says this at the bottom:

```<code> UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 41:
 character maps to <undefined>
</code>```

When I specify: no encoding, encoding='utf-8', or encoding='utf-8-sig', I get:

```<code> UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 65:
 invalid start byte
</code>```

QUESTION:

I am fine with deleting these problematic characters altogether.  Better yet would be to normalize them to ASCII characters under 127. How can I do this using JUST PANDAS?  I'm looking for the most panda-like way if it exists.

Not to overkill this question but here's a list of the types of characters in one of the columns that I'm certain is causing the problem:

```<code>Character   Ord
    32
!   33
"   34
#   35
$    36
%   37
&   38
'   39
(   40
)   41
*   42
+   43
,   44
-   45
.   46
/   47
0   48
1   49
2   50
3   51
4   52
5   53
6   54
7   55
8   56
9   57
:   58
;   59
<   60
=   61
>   62
?   63
@   64
A   65
B   66
C   67
D   68
E   69
F   70
G   71
H   72
I   73
J   74
K   75
L   76
M   77
N   78
O   79
P   80
Q   81
R   82
S   83
T   84
U   85
V   86
W   87
X   88
Y   89
Z   90
[   91
\   92
]   93
^   94
_   95
`   96
a   97
b   98
c   99
d   100
e   101
f   102
g   103
h   104
i   105
j   106
k   107
l   108
m   109
n   110
o   111
p   112
q   113
r   114
s   115
t   116
u   117
v   118
w   119
x   120
y   121
z   122
{   123
|   124
}   125
~   126
   129
   143
   157
    160
¡   161
¢   162
£   163
§   167
¨   168
©   169
«   171
¬   172
®   174
°   176
±   177
²   178
³   179
´   180
µ   181
·   183
¸   184
¹   185
º   186
¼   188
½   189
¾   190
×   215
ß   223
à   224
á   225
â   226
ã   227
ä   228
å   229
æ   230
ç   231
è   232
é   233
ì   236
í   237
î   238
ï   239
ð   240
ñ   241
ó   243
ô   244
ö   246
ú   250
û   251
ü   252
š   353
Ž   381
ƒ   402
–   8211
—   8212
‘   8216
’   8217
‚   8218
“   8220
”   8221
„   8222
†   8224
•   8226
…   8230
‹   8249
›   8250
€   8364
™   8482
</code>```

答:
If you completely sure that file in windows-1251/cp1251, you could try to switch off decode errors:

```<code>import codecs
codecs.register_error("strict", codecs.ignore_errors)
</code>```

It helped me to read csv files under Linux that was built under Windows.

Body:
I have a 129 MB CSV file with 849,275 rows and 18 columns.  I'm trying to read the CSV file into a pandas DataFrame using read_csv.

When I use encoding='cp1252':

read_file = pd.read_csv('myfile.csv', encoding='cp1252')

The error is quite long but ultimately says this at the bottom:

 UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 41:
 character maps to <undefined>

When I specify: no encoding, encoding='utf-8', or encoding='utf-8-sig', I get:

 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 65:
 invalid start byte

QUESTION:

I am fine with deleting these problematic characters altogether.  Better yet would be to normalize them to ASCII characters under 127. How can I do this using JUST PANDAS?  I'm looking for the most panda-like way if it exists.

Not to overkill this question but here's a list of the types of characters in one of the columns that I'm certain is causing the problem:

Character   Ord
    32
!   33
"   34
#   35
$    36
%   37
&   38
'   39
(   40
)   41
*   42
+   43
,   44
-   45
.   46
/   47
0   48
1   49
2   50
3   51
4   52
5   53
6   54
7   55
8   56
9   57
:   58
;   59
<   60
=   61
>   62
?   63
@   64
A   65
B   66
C   67
D   68
E   69
F   70
G   71
H   72
I   73
J   74
K   75
L   76
M   77
N   78
O   79
P   80
Q   81
R   82
S   83
T   84
U   85
V   86
W   87
X   88
Y   89
Z   90
[   91
\   92
]   93
^   94
_   95
`   96
a   97
b   98
c   99
d   100
e   101
f   102
g   103
h   104
i   105
j   106
k   107
l   108
m   109
n   110
o   111
p   112
q   113
r   114
s   115
t   116
u   117
v   118
w   119
x   120
y   121
z   122
{   123
|   124
}   125
~   126
   129
   143
   157
    160
¡   161
¢   162
£   163
§   167
¨   168
©   169
«   171
¬   172
®   174
°   176
±   177
²   178
³   179
´   180
µ   181
·   183
¸   184
¹   185
º   186
¼   188
½   189
¾   190
×   215
ß   223
à   224
á   225
â   226
ã   227
ä   228
å   229
æ   230
ç   231
è   232
é   233
ì   236
í   237
î   238
ï   239
ð   240
ñ   241
ó   243
ô   244
ö   246
ú   250
û   251
ü   252
š   353
Ž   381
ƒ   402
–   8211
—   8212
‘   8216
’   8217
‚   8218
“   8220
”   8221
„   8222
†   8224
•   8226
…   8230
‹   8249
›   8250
€   8364
™   8482

Body:
If you completely sure that file in windows-1251/cp1251, you could try to switch off decode errors:

import codecs
codecs.register_error("strict", codecs.ignore_errors)

It helped me to read csv files under Linux that was built under Windows.


问:
Pytorch can't convert np.ndarray of type numpy.object
I am trying to create a PyTorch data-loader with variable image size. Here is a snippet of my code

```<code>def get_imgs(path_to_imgs):

    imgs = []
    for path in path_to_imgs:

        imgs.append(cv2.imread(path))

    imgs = np.asarray(imgs)

    return imgs
</code>```

The function above takes a list of paths and loads the images from the path to the list 'imgs'. BTW the images are not equal-sized. The list looks like imgs = [NumPy array, NumPy array ....]. However, when I convert the list to np.asarray it turns the list into dtype = object.

This is my dataloader class

```<code>class Dataset(torch.utils.data.Dataset):

  def __init__(self, path_to_imgs, path_to_label):
        'Initialization'
        self.path_to_imgs = path_to_imgs
        self.path_to_label = path_to_label

        self.imgs = get_imgs(path_to_imgs)
        self.label = get_pts(path_to_label)

        self.imgs = torch.Tensor(self.imgs)             **Error here
        # self.imgs = torch.from_numpy(self.imgs)       ** I tried this as well. Same error

        self.label = torch.Tensor(self.label)

        self.len = len(self.imgs)

  def __len__(self):
        'Denotes the total number of samples'
        return self.len

  def __getitem__(self, index):

        return self.imgs, self.label
</code>```

When I try to convert the list of images to tensor** it fails giving the following error

can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.

I have looked similar questions here and here but they were not helpful.

答:
```
def get_imgs(path_to_imgs):

    imgs = []
    for path in path_to_imgs:
        imgs.append(torch.Tensor(cv2.imread(path)))

    return imgs
```

```
class Dataset(torch.utils.data.Dataset):
    def __init__(self, path_to_imgs, path_to_label):
        'Initialization'
        self.path_to_imgs = path_to_imgs
        self.path_to_label = path_to_label

        self.imgs = get_imgs(path_to_imgs)
        self.label = get_pts(path_to_label)

        # padding ops here (https://pytorch.org/docs/stable/nn.html#padding-layers)
        # for img in self.imgs:
        #     ...

        self.label = torch.Tensor(self.label)

        self.len = len(self.imgs)

    def __len__(self):
        'Denotes the total number of samples'
        return self.len

    def __getitem__(self, index):

        return self.imgs, self.label
```

Body:
I am trying to create a PyTorch data-loader with variable image size. Here is a snippet of my code

def get_imgs(path_to_imgs):

    imgs = []
    for path in path_to_imgs:

        imgs.append(cv2.imread(path))

    imgs = np.asarray(imgs)

    return imgs

The function above takes a list of paths and loads the images from the path to the list 'imgs'. BTW the images are not equal-sized. The list looks like imgs = [NumPy array, NumPy array ....]. However, when I convert the list to np.asarray it turns the list into dtype = object.

This is my dataloader class

class Dataset(torch.utils.data.Dataset):

  def __init__(self, path_to_imgs, path_to_label):
        'Initialization'
        self.path_to_imgs = path_to_imgs
        self.path_to_label = path_to_label

        self.imgs = get_imgs(path_to_imgs)
        self.label = get_pts(path_to_label)

        self.imgs = torch.Tensor(self.imgs)             **Error here
        # self.imgs = torch.from_numpy(self.imgs)       ** I tried this as well. Same error

        self.label = torch.Tensor(self.label)

        self.len = len(self.imgs)

  def __len__(self):
        'Denotes the total number of samples'
        return self.len

  def __getitem__(self, index):

        return self.imgs, self.label

When I try to convert the list of images to tensor** it fails giving the following error

can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.

I have looked similar questions here and here but they were not helpful.

Body:
def get_imgs(path_to_imgs):

    imgs = []
    for path in path_to_imgs:
        imgs.append(torch.Tensor(cv2.imread(path)))

    return imgs

class Dataset(torch.utils.data.Dataset):
    def __init__(self, path_to_imgs, path_to_label):
        'Initialization'
        self.path_to_imgs = path_to_imgs
        self.path_to_label = path_to_label

        self.imgs = get_imgs(path_to_imgs)
        self.label = get_pts(path_to_label)

        # padding ops here (https://pytorch.org/docs/stable/nn.html#padding-layers)
        # for img in self.imgs:
        #     ...

        self.label = torch.Tensor(self.label)

        self.len = len(self.imgs)

    def __len__(self):
        'Denotes the total number of samples'
        return self.len

    def __getitem__(self, index):

        return self.imgs, self.label


问:
Making button enabled when javascript return true
I'm trying to do a form with a basic captcha. Currently, because I'm a novice HTML coder, I only did the submit button enabled when the user clicks the verify button (it doesn'T enable itself when it sees return true.) And I'm trying to make it so if it returns return true i want to make the button enabled, and disabled at other times. Here is the link to the code: https://codepen.io/pen/GRpVmve

I would appreciate if anyone helps.

答:
I think this will work for you...

window.onload=()=>{
  document.getElementById('button2').disabled = true;
  let text = document.getElementById('txtInput').value;
 Captcha();
}

function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
for (i=0;i<6;i++){
   var a = alpha[Math.floor(Math.random() * alpha.length)];
   var b = alpha[Math.floor(Math.random() * alpha.length)];
   var c = alpha[Math.floor(Math.random() * alpha.length)];
   var d = alpha[Math.floor(Math.random() * alpha.length)];
   var e = alpha[Math.floor(Math.random() * alpha.length)];
   var f = alpha[Math.floor(Math.random() * alpha.length)];
   var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
 document.getElementById("mainCaptcha").value = code
 }

function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
  document.getElementById('button2').disabled = false;
}
else{
 document.getElementById('button2').disabled = true;
}
}
function removeSpaces(string){
  return string.split(' ').join('');
}
function check(x){
  if(x.length<7 || x.length>7){
     document.getElementById('button2').disabled = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="https://www.w3schools.com/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <h3>Gender</h3>
    <input type="radio" id="male" name="gender" value="male">

  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>

     <body onload="Captcha();">
        <table>
          <tr>
           <h3>
                 Captcha<br />
           </td>
          </tr>
          <tr>
           <td>
             <input type="text" id="mainCaptcha" disabled/>
              <input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
           </td>
          </tr>
          <tr>
           <td>
            <input type="text" id="txtInput" onkeyup="check(this.value)"/>
          </td>
         </tr>
         <tr>
          <td>
              <input id="button1" type="button" value="Verify" onclick="ValidCaptcha()">
              <input type="submit" id="button2" value="Send">
          </td>
        </tr>
      </table>
    </body>

</form> </code>```

Body:
I think this will work for you...

window.onload=()=>{
  document.getElementById('button2').disabled = true;
  let text = document.getElementById('txtInput').value;
 Captcha();
}

function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
for (i=0;i<6;i++){
   var a = alpha[Math.floor(Math.random() * alpha.length)];
   var b = alpha[Math.floor(Math.random() * alpha.length)];
   var c = alpha[Math.floor(Math.random() * alpha.length)];
   var d = alpha[Math.floor(Math.random() * alpha.length)];
   var e = alpha[Math.floor(Math.random() * alpha.length)];
   var f = alpha[Math.floor(Math.random() * alpha.length)];
   var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
 document.getElementById("mainCaptcha").value = code
 }

function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
  document.getElementById('button2').disabled = false;
}
else{
 document.getElementById('button2').disabled = true;
}
}
function removeSpaces(string){
  return string.split(' ').join('');
}
function check(x){
  if(x.length<7 || x.length>7){
     document.getElementById('button2').disabled = true;
  }
}

<form action="https://www.w3schools.com/action_page.php">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <h3>Gender</h3>
    <input type="radio" id="male" name="gender" value="male">

  <label for="male">Male</label><br>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label><br>
  <input type="radio" id="other" name="gender" value="other">
  <label for="other">Other</label>

     <body onload="Captcha();">
        <table>
          <tr>
           <h3>
                 Captcha<br />
           </td>
          </tr>
          <tr>
           <td>
             <input type="text" id="mainCaptcha" disabled/>
              <input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
           </td>
          </tr>
          <tr>
           <td>
            <input type="text" id="txtInput" onkeyup="check(this.value)"/>
          </td>
         </tr>
         <tr>
          <td>
              <input id="button1" type="button" value="Verify" onclick="ValidCaptcha()">
              <input type="submit" id="button2" value="Send">
          </td>
        </tr>
      </table>
    </body>

</form>


答:
When you exit the activity, context is null
your can use applicationContext

```<code>  Toast.makeText(applicationContext, "Data retrieved!", Toast.LENGTH_SHORT).show()
</code>```

Title: Kotlin App Crash if back button pressed during fetching API

Body:
When you exit the activity, context is null
your can use applicationContext

  Toast.makeText(applicationContext, "Data retrieved!", Toast.LENGTH_SHORT).show()


问:
ASP Net MVC pagedlistpager without style
i installed PagedList.Mvc and PagedList but when i use it i have no style at all:

Image of pagedListPager without any style

My controller looks like that:

```<code>public ActionResult CarrosList(string search, int? i)
{
    return View(db.Carro.Where(x=>x.Estado != "Vendido" && x.Titulo.StartsWith(search) || search == null).ToList().ToPagedList(i ?? 1, 6));
}
</code>```

And My cshtml page looks like that:

```<code>@Html.PagedListPager(Model, i => Url.Action("CarrosList", new { i, search = Request.QueryString["search"]}))
</code>```

答:
The code you have shown handles the server side paging and renders the HTML.

Styles however, are all to do with CSS stylesheets.

From https://github.com/TroyGoode/PagedList :

```<code><!-- import the included stylesheet for some (very basic) default styling -->
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
</code>```

Basically make sure the stylesheet is included.

Gotcha

Stuff in the Content folder is only installed when you first add the nuget package. So if someone else installed the package and didn't add the relevant CSS file to source control it may be missing. You may need to remove and re-add the nuget package to fix.

Body:
i installed PagedList.Mvc and PagedList but when i use it i have no style at all:

Image of pagedListPager without any style

My controller looks like that:

public ActionResult CarrosList(string search, int? i)
{
    return View(db.Carro.Where(x=>x.Estado != "Vendido" && x.Titulo.StartsWith(search) || search == null).ToList().ToPagedList(i ?? 1, 6));
}

And My cshtml page looks like that:

@Html.PagedListPager(Model, i => Url.Action("CarrosList", new { i, search = Request.QueryString["search"]}))

Body:
The code you have shown handles the server side paging and renders the HTML.

Styles however, are all to do with CSS stylesheets.

From https://github.com/TroyGoode/PagedList :

<!-- import the included stylesheet for some (very basic) default styling -->
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />

Basically make sure the stylesheet is included.

Gotcha

Stuff in the Content folder is only installed when you first add the nuget package. So if someone else installed the package and didn't add the relevant CSS file to source control it may be missing. You may need to remove and re-add the nuget package to fix.


问:
open a shell tab for each service in a docker compose file
I have a client-server (both written in C++) application that I am managing using docker-compose. I'm quite new in docker technology and I'm wondering if docker-compose up can do the following job for me:

run services

open a shell tab for each service in the docker-compose.yml file.

I need a separate shell for each service because everytime that I change the code (in client or server) I would like to stop the program, re-compile it and re-run. At the moment I use a workaround:

run docker-compose up

run docker container ls to find containers id

for each container open a shell tab and run docker exec -it <container-id> /bin/bash

I'm wondering if there is a more elegant solution. I'm using Ubuntu and this is my docker-compose.yml:

```<code>version: '3.1'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        volumes:
            - ./server/src:/home/src
            - ./server/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    client:
        build: ./client
        ports:
            - "2800:2800"
        volumes:
            - ./client/src:/home/src
            - ./client/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    db:
        image: mysql
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: example
</code>```

答:
You can simplify this setup using Docker's native image system.  Typically the instructions for compiling the application will be built into the Dockerfile, so running docker-compose up --build will recompile things.  Docker's layer cache system makes this run very quickly if the application hasn't actually changed.  Once you have that, you don't need volumes: to overwrite the image contents, and you shouldn't separately need an interactive shell attached to each container.

If you remove volumes: and some other settings that are either in the Dockerfile or that you don't usually need, that leaves you with a much shorter docker-compose.yml:

version: '3'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        # volumes: undo what server/Dockerfile does
        # working_dir: is the Dockerfile WORKDIR
        # server-type processes don't usually need stdin_open: or tty:
    client:
        build: ./client
        ports:
            - "2800:2800"
    db:
        # as above
```

<p>When you change something, you can run <code>docker-compose up --build -d</code>, and it will rebuild and restart the specific things that need to be rebuilt and restarted.</p>

<p>There are direct <code>docker-compose</code> equivalents to many of the <code>docker</code> commands.  If you really need an interactive shell in a container, for example, you can</p>

<pre class="lang-sh prettyprint-override"><code>docker-compose exec server /bin/sh
</code>```

docker-compose exec will look up the Docker container ID for you, and defaults to the docker exec -it flags.

Body:
I have a client-server (both written in C++) application that I am managing using docker-compose. I'm quite new in docker technology and I'm wondering if docker-compose up can do the following job for me:

run services

open a shell tab for each service in the docker-compose.yml file.

I need a separate shell for each service because everytime that I change the code (in client or server) I would like to stop the program, re-compile it and re-run. At the moment I use a workaround:

run docker-compose up

run docker container ls to find containers id

for each container open a shell tab and run docker exec -it <container-id> /bin/bash

I'm wondering if there is a more elegant solution. I'm using Ubuntu and this is my docker-compose.yml:

version: '3.1'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        volumes:
            - ./server/src:/home/src
            - ./server/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    client:
        build: ./client
        ports:
            - "2800:2800"
        volumes:
            - ./client/src:/home/src
            - ./client/bin:/home/bin
        working_dir: /home/src
        stdin_open: true
        tty: true
    db:
        image: mysql
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: example

Body:
You can simplify this setup using Docker's native image system.  Typically the instructions for compiling the application will be built into the Dockerfile, so running docker-compose up --build will recompile things.  Docker's layer cache system makes this run very quickly if the application hasn't actually changed.  Once you have that, you don't need volumes: to overwrite the image contents, and you shouldn't separately need an interactive shell attached to each container.

If you remove volumes: and some other settings that are either in the Dockerfile or that you don't usually need, that leaves you with a much shorter docker-compose.yml:

version: '3'
services:
    server:
        build: ./server
        ports:
            - "3500:3500"
        # volumes: undo what server/Dockerfile does
        # working_dir: is the Dockerfile WORKDIR
        # server-type processes don't usually need stdin_open: or tty:
    client:
        build: ./client
        ports:
            - "2800:2800"
    db:
        # as above

When you change something, you can run docker-compose up --build -d, and it will rebuild and restart the specific things that need to be rebuilt and restarted.

There are direct docker-compose equivalents to many of the docker commands.  If you really need an interactive shell in a container, for example, you can

docker-compose exec server /bin/sh

docker-compose exec will look up the Docker container ID for you, and defaults to the docker exec -it flags.


问:
Getting "Run-time error '1004': Select method of Range class failed"
I have two (2) sheets. The first one has a button. The second sheet is my summary page, and I plan to have a button here that is linked to the button on my first sheet. However, I get the

Run-time error '1004': Select method of Range class failed.

I assigned Command1_Click() to be my button at Sheet2

Module1:

```<code>Sub Command1_Click()
Call Model01
End Sub
</code>```

Module2:

```<code>Sub Model01()
Sheet1.Range("C8:GF8").Value = Sheet1.Range("C240:GF240").Value
Sheet1.Range("B7").Value = Sheet1.Range("B240").Value
r = DataUpdate()
End Sub
</code>```

Module3:

```<code>Function DataUpdate()
If (validateVer() = False) Then
    Exit Function
End If

Dim AsCn, AsRs, SQL
Dim x, y, WDATE, NGQTY, FAQTY, RWQTY, RNQTY, TotalCell, TotalCellx
Dim FA_TBL As Variant   ' (y, x)
Dim RW_TBL As Variant   ' (y, x)
Dim RN_TBL As Variant   ' (y, x)
Dim NG_TBL As Variant   ' (y, x)

'Sheet => Table
Sheet1.Range("C2:GS2").Select
Selection.ClearContents
FA_TBL = Sheet1.Range("A2:GS2")
Sheet1.Range("C4:GS4").Select
Selection.ClearContents
RW_TBL = Sheet1.Range("A4:GS4")
Sheet1.Range("C5:GS5").Select
Selection.ClearContents
RN_TBL = Sheet1.Range("A5:GS5")
Sheet1.Range("A9:GS208").Select
Selection.ClearContents
Sheet1.Range("C9").Select
NG_TBL = Sheet1.Range("A8:GS208")

'Connect DataBase ODBC
Set AsCn = CreateObject("ADODB.Connection")
AsCn.Open "Provider=IBMDA400;Data Source=FCP2040;", "FCPMIS", "AUTOSENT"
'AsCn.Open "dsn=FCP2040;uid=FCPMIS;pwd=AUTOSENT"

'Get Total cell
TotalCell = 3
While NG_TBL(1, TotalCell) <> "Total"
    TotalCell = TotalCell + 1
Wend
</code>```

..

```<code>'Get NG Qty
y = 2
NGQTY = 0
While Not (AsRs.EOF)

    NG_TBL(y, 1) = AsRs(1)
    NG_TBL(y, 2) = AsRs(2)
    NGQTY = 0
    x = 3
    While x < TotalCell
        WDATE = Right(Year(NG_TBL(1, x)), 2) & Right("00" & Month(NG_TBL(1, x)), 2) & Right("00" & Day(NG_TBL(1, x)), 2)
        If Not (AsRs.EOF) Then
            If ((NG_TBL(y, 1) = AsRs(1)) And _
                ((WDATE = AsRs(0)) Or ((x + 1) = TotalCell))) Then
                NG_TBL(y, x) = AsRs(3)
                NGQTY = NGQTY + AsRs(3)
                AsRs.MoveNext
            Else
                If FA_TBL(1, x) <> "" Then
                    NG_TBL(y, x) = 0
                End If
            End If
        Else
            If FA_TBL(1, x) <> "" Then
                NG_TBL(y, x) = 0
            End If
        End If
        x = x + 1
    Wend
    NG_TBL(y, TotalCell) = NGQTY
    y = y + 1
Wend

'Sheet => Table
Sheet1.Range("A2:GS2") = FA_TBL
Sheet1.Range("A4:GS4") = RW_TBL
Sheet1.Range("A5:GS5") = RN_TBL
Sheet1.Range("A8:GS208") = NG_TBL

'--------------------------------------------------------------------------------
'   Sort
'--------------------------------------------------------------------------------
If (TotalCell \ 26) = 0 Then
    TotalCellx = Chr(TotalCell + 64)
Else
    TotalCellx = Chr(TotalCell \ 26 + 64) & Chr(TotalCell Mod 26 + 64)
End If

Sheet1.Range("A8:" & TotalCellx & "100").Select
Selection.Sort Key1:=Range(TotalCellx & "9"), Order1:=xlDescending, Header:=xlGuess _
    , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin
Sheet1.Range("C9").Select

'Close Recordset
AsRs.Close
Set AsRs = Nothing

'Close DataBase ODBC
AsCn.Close
Set AsCn = Nothing
End Function
</code>```

答:
You can only select a range on an active sheet. Hence you can't directly select a range in Sheet1 from a button in Sheet2. The solution is not to activate the sheet before selecting. The solution is to not use Select at all. That method is almost never needed. For example

```<code>Sheet1.Range("C2:GS2").Select
Selection.ClearContents
</code>```

is more cleanly expressed as

```<code>Sheet1.Range("C2:GS2").ClearContents
</code>```

See How to avoid using Select in Excel VBA for other suggestions for eliminating needless selects in your code.

Body:
I have two (2) sheets. The first one has a button. The second sheet is my summary page, and I plan to have a button here that is linked to the button on my first sheet. However, I get the

Run-time error '1004': Select method of Range class failed.

I assigned Command1_Click() to be my button at Sheet2

Module1:

Sub Command1_Click()
Call Model01
End Sub

Module2:

Sub Model01()
Sheet1.Range("C8:GF8").Value = Sheet1.Range("C240:GF240").Value
Sheet1.Range("B7").Value = Sheet1.Range("B240").Value
r = DataUpdate()
End Sub

Module3:

Function DataUpdate()
If (validateVer() = False) Then
    Exit Function
End If

Dim AsCn, AsRs, SQL
Dim x, y, WDATE, NGQTY, FAQTY, RWQTY, RNQTY, TotalCell, TotalCellx
Dim FA_TBL As Variant   ' (y, x)
Dim RW_TBL As Variant   ' (y, x)
Dim RN_TBL As Variant   ' (y, x)
Dim NG_TBL As Variant   ' (y, x)

'Sheet => Table
Sheet1.Range("C2:GS2").Select
Selection.ClearContents
FA_TBL = Sheet1.Range("A2:GS2")
Sheet1.Range("C4:GS4").Select
Selection.ClearContents
RW_TBL = Sheet1.Range("A4:GS4")
Sheet1.Range("C5:GS5").Select
Selection.ClearContents
RN_TBL = Sheet1.Range("A5:GS5")
Sheet1.Range("A9:GS208").Select
Selection.ClearContents
Sheet1.Range("C9").Select
NG_TBL = Sheet1.Range("A8:GS208")

'Connect DataBase ODBC
Set AsCn = CreateObject("ADODB.Connection")
AsCn.Open "Provider=IBMDA400;Data Source=FCP2040;", "FCPMIS", "AUTOSENT"
'AsCn.Open "dsn=FCP2040;uid=FCPMIS;pwd=AUTOSENT"

'Get Total cell
TotalCell = 3
While NG_TBL(1, TotalCell) <> "Total"
    TotalCell = TotalCell + 1
Wend

..

'Get NG Qty
y = 2
NGQTY = 0
While Not (AsRs.EOF)

    NG_TBL(y, 1) = AsRs(1)
    NG_TBL(y, 2) = AsRs(2)
    NGQTY = 0
    x = 3
    While x < TotalCell
        WDATE = Right(Year(NG_TBL(1, x)), 2) & Right("00" & Month(NG_TBL(1, x)), 2) & Right("00" & Day(NG_TBL(1, x)), 2)
        If Not (AsRs.EOF) Then
            If ((NG_TBL(y, 1) = AsRs(1)) And _
                ((WDATE = AsRs(0)) Or ((x + 1) = TotalCell))) Then
                NG_TBL(y, x) = AsRs(3)
                NGQTY = NGQTY + AsRs(3)
                AsRs.MoveNext
            Else
                If FA_TBL(1, x) <> "" Then
                    NG_TBL(y, x) = 0
                End If
            End If
        Else
            If FA_TBL(1, x) <> "" Then
                NG_TBL(y, x) = 0
            End If
        End If
        x = x + 1
    Wend
    NG_TBL(y, TotalCell) = NGQTY
    y = y + 1
Wend

'Sheet => Table
Sheet1.Range("A2:GS2") = FA_TBL
Sheet1.Range("A4:GS4") = RW_TBL
Sheet1.Range("A5:GS5") = RN_TBL
Sheet1.Range("A8:GS208") = NG_TBL

'--------------------------------------------------------------------------------
'   Sort
'--------------------------------------------------------------------------------
If (TotalCell \ 26) = 0 Then
    TotalCellx = Chr(TotalCell + 64)
Else
    TotalCellx = Chr(TotalCell \ 26 + 64) & Chr(TotalCell Mod 26 + 64)
End If

Sheet1.Range("A8:" & TotalCellx & "100").Select
Selection.Sort Key1:=Range(TotalCellx & "9"), Order1:=xlDescending, Header:=xlGuess _
    , OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    SortMethod:=xlPinYin
Sheet1.Range("C9").Select

'Close Recordset
AsRs.Close
Set AsRs = Nothing

'Close DataBase ODBC
AsCn.Close
Set AsCn = Nothing
End Function

Body:
You can only select a range on an active sheet. Hence you can't directly select a range in Sheet1 from a button in Sheet2. The solution is not to activate the sheet before selecting. The solution is to not use Select at all. That method is almost never needed. For example

Sheet1.Range("C2:GS2").Select
Selection.ClearContents

is more cleanly expressed as

Sheet1.Range("C2:GS2").ClearContents

See How to avoid using Select in Excel VBA for other suggestions for eliminating needless selects in your code.


问:
Mininet : Creating a host with multiple interfaces and assigning IP address using addLink()
I want to create a network with 2 hosts connected to each other via 3
links (each link belonging to a different network)

```<code>   _________10.0.0.0/31 network________________
  |                                            |
H1+---------10.0.1.0/31 network----------------+H2
  | ________10.0.2.0/31 network----------------|
</code>```

I followed the solution given in the mininet mailing list
to try and add the links.

self.addLink( 'h1', s1, params1={'ip':'10.3/8'} )

While the hosts do get 3 interfaces only one
of the interfaces gets assigned the default IP 10.0.0.1/8
I dug through the source code and the way I did it should work but I don't understand why mine doesn't

from mininet.topo import Topo
from mininet.link import TCLink, Link
from mininet.net import Mininet

class MyTopo( Topo ):
    "Simple topology example."

    def __init__( self ):
        "Create custom topo."

        # Initialize topology
        Topo.__init__( self )

        # Add hosts and switches
        lH = self.addHost( 'h1' )
        rH = self.addHost( 'h2')

        # Add links
        self.addLink(lH, rH, bw = 10, delay='50ms', params1={ 'ip' : '10.0.0.1/31' }, params2={ 'ip' : '10.0.0.2/31' })
        self.addLink(lH, rH, bw = 1, delay='200ms', params1={ 'ip' : '10.1.0.1/31' }, params2={ 'ip' : '10.1.0.2/31' })
        self.addLink(lH,rH, bw = 0.1, delay='500ms',  params1={ 'ip' : '10.2.0.1/31' }, params2={ 'ip' : '10.2.0.2/31' })

topos = { 'mytopo': ( lambda: MyTopo() ) }
```

答:
I just needed to pass intf=TCIntf to the addLink() function and pass the appropriate arguments

self.addLink(lH, rH, intf=TCIntf,  params1={'delay':'50ms', 'bw' : 10, 'ip' : '10.0.0.1/24' }
```

Body:
I want to create a network with 2 hosts connected to each other via 3
links (each link belonging to a different network)

   _________10.0.0.0/31 network________________
  |                                            |
H1+---------10.0.1.0/31 network----------------+H2
  | ________10.0.2.0/31 network----------------|

I followed the solution given in the mininet mailing list
to try and add the links.

self.addLink( 'h1', s1, params1={'ip':'10.3/8'} )

While the hosts do get 3 interfaces only one
of the interfaces gets assigned the default IP 10.0.0.1/8
I dug through the source code and the way I did it should work but I don't understand why mine doesn't

from mininet.topo import Topo
from mininet.link import TCLink, Link
from mininet.net import Mininet

class MyTopo( Topo ):
    "Simple topology example."

    def __init__( self ):
        "Create custom topo."

        # Initialize topology
        Topo.__init__( self )

        # Add hosts and switches
        lH = self.addHost( 'h1' )
        rH = self.addHost( 'h2')

        # Add links
        self.addLink(lH, rH, bw = 10, delay='50ms', params1={ 'ip' : '10.0.0.1/31' }, params2={ 'ip' : '10.0.0.2/31' })
        self.addLink(lH, rH, bw = 1, delay='200ms', params1={ 'ip' : '10.1.0.1/31' }, params2={ 'ip' : '10.1.0.2/31' })
        self.addLink(lH,rH, bw = 0.1, delay='500ms',  params1={ 'ip' : '10.2.0.1/31' }, params2={ 'ip' : '10.2.0.2/31' })

topos = { 'mytopo': ( lambda: MyTopo() ) }


问:
Unsuccessful assignment in SystemVerilog
I write ldpc_if.sv and ldpc_transaction.sv as follows.

"ldpc_if.sv"

```<code>interface ldpc_if#(parameter COLS=9216, parameter ROWS=1024) (input clk, input reset);
  logic [COLS-ROWS-1:0] en_enq_data;
  logic                 en_enq_valid;
  logic                 en_enq_ready;

  logic [ROWS-1:0]      en_deq_data;
  logic                 en_deq_valid;
  logic                 en_deq_ready;

  logic [COLS-1:0]      de_enq_data;
  logic                 de_enq_valid;
  logic                 de_enq_ready;

  logic [COLS-1:0]      de_deq_data;
  logic                 de_deq_valid;
  logic                 de_deq_ready;

 endinterface
</code>```

"ldpc_transaction.sv"

```<code>class ldpc_transaction#(parameter WIDTH=8192) extends uvm_sequence_item;
  rand bit [WIDTH-1:0] data;

  bit [8191:0]  encode_data_in;
  bit [1023:0]  encode_data_out;

  bit [9215:0]  decode_data;

  `uvm_object_utils(ldpc_transaction)

  function new(string name = "ldpc_transaction");
    super.new();
  endfunction
endclass
</code>```

And I write ldpc_monitor.sv to monitor interface.

```<code>task ldpc_monitor::collect_one_pkt(ldpc_transaction tr);
  while(1) begin
  @(posedge vif.clk);
  if(vif.en_enq_valid && vif.en_enq_ready) break;
  end

  tr.encode_data_in <= vif.en_enq_data;

  while(1) begin
    @(posedge vif.clk)
    if(vif.en_deq_valid && vif.en_deq_ready) break;
  end

  tr.encode_data_out <= vif.en_deq_data;

 while(1)begin
   @(posedge vif.clk)
   if(vif.de_deq_valid && vif.de_deq_ready)begin
     break;
   end
 end
 tr.decode_data <= vif.de_deq_data;
 $display("tr.decode_data = %0h", tr.decode_data);
 $display("vif.de_deq_data = %0h", vif.de_deq_data);
endtask
</code>```

vcs compiles all files successfully. However, tr.decode_data is always displayed as zero. But, vif.de_deq_data is correct. Why is vif.de_deq_data not assigned to tr.decode_data.

答:
It's because the $display you've used to display your transaction is blocking. Conversely, you've used an non-blocking assignment to set tr.decode_data.

Thus, your $display statement actually gets executed before your assignment. Getting a 0 is just an artefact of your simulator - could be any random stuff in the memory assigned to that variable (though most simulators just reset to 0).

Quick search revealed this useful example which illustrates exactly your problem.

https://verificationguide.com/systemverilog/systemverilog-nonblocking-assignment/

Body:
I write ldpc_if.sv and ldpc_transaction.sv as follows.

"ldpc_if.sv"

interface ldpc_if#(parameter COLS=9216, parameter ROWS=1024) (input clk, input reset);
  logic [COLS-ROWS-1:0] en_enq_data;
  logic                 en_enq_valid;
  logic                 en_enq_ready;

  logic [ROWS-1:0]      en_deq_data;
  logic                 en_deq_valid;
  logic                 en_deq_ready;

  logic [COLS-1:0]      de_enq_data;
  logic                 de_enq_valid;
  logic                 de_enq_ready;

  logic [COLS-1:0]      de_deq_data;
  logic                 de_deq_valid;
  logic                 de_deq_ready;

 endinterface

"ldpc_transaction.sv"

class ldpc_transaction#(parameter WIDTH=8192) extends uvm_sequence_item;
  rand bit [WIDTH-1:0] data;

  bit [8191:0]  encode_data_in;
  bit [1023:0]  encode_data_out;

  bit [9215:0]  decode_data;

  `uvm_object_utils(ldpc_transaction)

  function new(string name = "ldpc_transaction");
    super.new();
  endfunction
endclass

And I write ldpc_monitor.sv to monitor interface.

task ldpc_monitor::collect_one_pkt(ldpc_transaction tr);
  while(1) begin
  @(posedge vif.clk);
  if(vif.en_enq_valid && vif.en_enq_ready) break;
  end

  tr.encode_data_in <= vif.en_enq_data;

  while(1) begin
    @(posedge vif.clk)
    if(vif.en_deq_valid && vif.en_deq_ready) break;
  end

  tr.encode_data_out <= vif.en_deq_data;

 while(1)begin
   @(posedge vif.clk)
   if(vif.de_deq_valid && vif.de_deq_ready)begin
     break;
   end
 end
 tr.decode_data <= vif.de_deq_data;
 $display("tr.decode_data = %0h", tr.decode_data);
 $display("vif.de_deq_data = %0h", vif.de_deq_data);
endtask

vcs compiles all files successfully. However, tr.decode_data is always displayed as zero. But, vif.de_deq_data is correct. Why is vif.de_deq_data not assigned to tr.decode_data.


问:
Finding matching keys in two large dictionaries and doing it fast
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

```<code>    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }
</code>```

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

```<code>    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]
</code>```

I've tried the following but it always results in a KeyError:

```<code>    for key in myRDP:
        print myNames[key]
</code>```

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.

答:
```<code>def combine_two_json(json_request, json_request2):
intersect = {}

for item in json_request.keys():
    if item in json_request2.keys():
        intersect[item]=json_request2.get(item)
return intersect
</code>```

Body:
I am trying to find corresponding keys in two different dictionaries.  Each has about 600k entries.

Say for example:

    myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
    myNames = { 'Actinobacter': '8924342' }

I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.

The following code works, but is very slow:

    for key in myRDP:
        for jey in myNames:
            if key == jey:
                print key, myNames[key]

I've tried the following but it always results in a KeyError:

    for key in myRDP:
        print myNames[key]

Is there perhaps a function implemented in C for doing this?  I've googled around but nothing seems to work.


问:
ASP MVC HTML Helpers - Good or Bad?
I understand the reason for having the HTML helpers in ASP.NET MVC and extending this to provide your own, but I am wondering whether using HTML helpers is a good idea.

I thought one of the benefits of ASP.NET MVC is control over the HTML. If you start hiding it away in helper functions that generate HTML don't you start losing visibility? I guess this isn't such a problem when you are generating simple controls such as a button, but I have seen the use of html helpers to create grids and more complex HTML output.

Now I also understand the reason for doing so is to keep things DRY, avoiding duplication. But is there not a danger of having something akin to code-behind here? In addition, what if you are working in collaboration with designers? Generally the designer would be creating the markup and applying styling. If you start injecting your view with helpers that generate markup, doesn't this make such collaboration difficult?

答: There's definitely nothing wrong with helpers. They're used to keep your views clean and declarative. There's a saying that goes something like "if there's an "if" statement in your view, you're doing it wrong". They're used in many prominent MVC frameworks like Ruby On Rails and Cake PHP. Check out this post. "Purist" or not, helpers are a good thing and not to be confused with bad practice or leaky abstractions.</p>

ContentLicense: CC BY-SA 2.5

Title: ASP MVC HTML Helpers - Good or Bad?


问:
ORA-04092: cannot ROLLBACK in a trigger after exceeding number of applications made daily
May I know how a trigger would be written if lets say there are applicant, position, applies relations and applies is like the association class as an applicant can apply many position and a position can by applied by many applicants and the applies relation has its own attribute called dateApp and I want to limit the amount of applications to twice a day, so this means a customer can only apply 2 items in one day. So far I have this code:

```<code>CREATE OR REPLACE TRIGGER APPLYTWICEONLY
AFTER INSERT ON APPLIES
DECLARE
CURSOR C IS
SELECT ANUMBER, COUNT(APPDATE) AS TOTAL
FROM APPLIES
WHERE APPDATE = TRUNC(SYSDATE)
GROUP BY ANUMBER;
BEGIN

FOR APPLY IN C
LOOP

   IF APPLY.TOTAL > 2 THEN
      DBMS_OUTPUT.PUT_LINE('AN APPLICANT CAN APPLY MAXIMUM TWICE A DAY.');
      ROLLBACK;
   END IF;
END LOOP;

END;
/
</code>```

so what is happening here is, after an applicant applies for a position, i check the total number of applications made today for each applicant using the anumber, if the total applications exceed 2 for an applicant today, then i will roll back and undo that insert. I want to do this using a statement  trigger instead of a row trigger, but i keep getting ORA-04092: cannot ROLLBACK in a trigger, after an applicant has exceeded the number of applications for the day. Can someone help me?

答:
Enforcing business logic via database triggers is most often wrong approach.

You should do that check where applicant applies for a position and either let it proceed or stop the application process.

As of triggers being unable to commit or rollback; well, that's not entirely true. If it (a trigger) is an autonomous transaction, it can. For example:

```<code>SQL> create or replace trigger trg_rlbk
  2    after insert on test
  3  declare
  4    pragma autonomous_transaction;
  5  begin
  6    rollback;
  7  end;
  8  /

Trigger created.

SQL> insert into test (id) values (2);

1 row created.

SQL> select * From test;

        ID NAME
---------- --------------------
         2

SQL>
</code>```

As you can see, the main transaction wasn't rolled back - ID = 2 was inserted into the table. What would have been rolled back, would be code contained within the trigger itself. There's none in my example, on purpose, to show you that such a pragma won't help in what you're trying to do.

Also, the fact that you can do something doesn't mean that you should do it.

Body:
May I know how a trigger would be written if lets say there are applicant, position, applies relations and applies is like the association class as an applicant can apply many position and a position can by applied by many applicants and the applies relation has its own attribute called dateApp and I want to limit the amount of applications to twice a day, so this means a customer can only apply 2 items in one day. So far I have this code:

CREATE OR REPLACE TRIGGER APPLYTWICEONLY
AFTER INSERT ON APPLIES
DECLARE
CURSOR C IS
SELECT ANUMBER, COUNT(APPDATE) AS TOTAL
FROM APPLIES
WHERE APPDATE = TRUNC(SYSDATE)
GROUP BY ANUMBER;
BEGIN

FOR APPLY IN C
LOOP

   IF APPLY.TOTAL > 2 THEN
      DBMS_OUTPUT.PUT_LINE('AN APPLICANT CAN APPLY MAXIMUM TWICE A DAY.');
      ROLLBACK;
   END IF;
END LOOP;

END;
/

so what is happening here is, after an applicant applies for a position, i check the total number of applications made today for each applicant using the anumber, if the total applications exceed 2 for an applicant today, then i will roll back and undo that insert. I want to do this using a statement  trigger instead of a row trigger, but i keep getting ORA-04092: cannot ROLLBACK in a trigger, after an applicant has exceeded the number of applications for the day. Can someone help me?

Body:
Enforcing business logic via database triggers is most often wrong approach.

You should do that check where applicant applies for a position and either let it proceed or stop the application process.

As of triggers being unable to commit or rollback; well, that's not entirely true. If it (a trigger) is an autonomous transaction, it can. For example:

SQL> create or replace trigger trg_rlbk
  2    after insert on test
  3  declare
  4    pragma autonomous_transaction;
  5  begin
  6    rollback;
  7  end;
  8  /

Trigger created.

SQL> insert into test (id) values (2);

1 row created.

SQL> select * From test;

        ID NAME
---------- --------------------
         2

SQL>

As you can see, the main transaction wasn't rolled back - ID = 2 was inserted into the table. What would have been rolled back, would be code contained within the trigger itself. There's none in my example, on purpose, to show you that such a pragma won't help in what you're trying to do.

Also, the fact that you can do something doesn't mean that you should do it.