问:
Download a zip file that is created when a URL is passed to domain site, but I have tried for 4 days 30-50 different ways, and no luck. CAISO OASIS
The site is the CAISO OASIS and they use an old way of querying and returning datasets. 30 days at a time, zip file with enclosed *.csv files. I have tried for 4 days coming up with a way to automate this download first of the zip file but i cant even get past there.

If I populate the url string I want and enter it myself in the address bar a zip file will start downloading, I cannot for the life of me get it to do the same through code.

I need to use php to accomplish this task.
I have tried, fopen, file_get_contents, file_put_contents, cURL, ziparchive class.  I have tried changing all sorts of things. The best I get is a download of a corrupt zip file that is empty.

Ideally i would love to extract the *.csv or xml file but I cannot even do the first basic step.

The following variable I populate, $url_caiso_qry,  if you take the echo string and past in the browser and enter the zip file will start downloading, but I cannot download it automatically.

http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1

<?php

$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);

// creates data array for precio de carga SIN
// function create_dataarrayp_chrt($zona) {

$ayer = date("Ymd\T7:00-0000", strtotime('now - 1 day'));
$mespasado = date("Ymd\T7:00-0000",strtotime('-30 days'));

$sdate = $mespasado;  //startdatetime=
$edate = $ayer;   //enddatetime=
$resultformat = '6';
$queryname='SLD_FCST';
$version='1';
$marketrunid='ACTUAL';

$fields = [
    'startdatetime' => $sdate,
    'enddatetime' => $edate,
    'resultformat' => $resultformat,
    'queryname' => $queryname,
    'market_run_id' => $marketrunid,
    'version' => $version,
];

//post fields
$postparam = urldecode(http_build_query($fields));

//PRECIOS   url base string
$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?';
//$urlcaiso = 'http://oasis.caiso.com/oasisapi/SingleZip?resultformat=6&queryname=SLD_FCST&version=1&market_run_id=ACTUAL&startdatetime=' . $sdate . 'T07:00-0000&enddatetime=' . $edate . 'T07:00-0000';

$url_caiso_qry = $urlcaiso . $postparam;

$caisofile = file_get_contents($url_caiso_qry, "rb");

//attempt to write file to destination path, but no file is written.  Instead the following warning
//Warning: file_put_contents(/name1/name2/private/test/):
// failed to open stream: No such file or directory in C:\xampp\htdocs\name1\name2\private\test.php on line 94

$destination_path = WWW_ROOT . 'name2/private/test/';
$newfile = file_put_contents($destination_path, $caisofile);

echo $newfile . '

';
?>
```

答:
The second parameter you pass to file_get_contents describes the use_include_path according to the php documentation.

I tried this simple example to get the file and save it:

<?php

$content = file_get_contents('http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1');

file_put_contents('example.zip', $content);
```
<p>Running <code>file example.zip</code> gives the following output:
<code>example.zip: Zip archive data, at least v2.0 to extract</code> which indicates success.</p>
<p>So essentially your final code could look something like this:</p>
<pre class="lang-php prettyprint-override"><code><?php

// Build url here
$url = 'http://oasis.caiso.com/...';

// Download file
$zipFile = file_get_contents($url);

$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);

$targetPath = WWW_ROOT . 'proj3-ampenergy/private/test/'; // This could be any other path where your file should be stored

// Write contents to file
file_put_contents($targetPath, $zipFile);

// Write extraction logic here
</code>```

Body:
The second parameter you pass to file_get_contents describes the use_include_path according to the php documentation.

I tried this simple example to get the file and save it:

<?php

$content = file_get_contents('http://oasis.caiso.com/oasisapi/SingleZip?startdatetime=20220109T7:00-0000&enddatetime=20220207T7:00-0000&resultformat=6&queryname=SLD_FCST&market_run_id=ACTUAL&version=1');

file_put_contents('example.zip', $content);

Running file example.zip gives the following output:
example.zip: Zip archive data, at least v2.0 to extract which indicates success.

So essentially your final code could look something like this:

<?php

// Build url here
$url = 'http://oasis.caiso.com/...';

// Download file
$zipFile = file_get_contents($url);

$public_end = strpos($_SERVER['SCRIPT_NAME'], '/public') + 13;
$doc_root = substr($_SERVER['SCRIPT_NAME'], 0, $public_end);
define("WWW_ROOT", $doc_root);

$targetPath = WWW_ROOT . 'proj3-ampenergy/private/test/'; // This could be any other path where your file should be stored

// Write contents to file
file_put_contents($targetPath, $zipFile);

// Write extraction logic here


来源: stackexchange

问:
How to load all files from a directory?
Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.

Edit:
For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.

答: Listing files in a directory is defined by the platform so you would have to use a platform dependent library.  This is true of c++ and Lua (which implements only ansi c functionality).  </p>

OwnerDisplayName: Bumhunter

ContentLicense: CC BY-SA 2.5

Title: How to load all files from a directory?

LastEditorDisplayName: Bumhunter

OwnerDisplayName: Nick

LastEditorDisplayName: Nick


问:
Why don't Haskell compilers facilitate deterministic memory management?
With the wealth of type information available why can't Haskell runtimes avoid running GC to clean up? It should be possible to figure out all usages and insert appropriate calls to alloc/release in the compiled code, right? This would avoid the overhead of a runtime GC.</p>

答: Region-based memory management is what programmers in C and C++ often end up programming by hand: Allocate a chunk of memory ("region", "arena", etc.), allocate the individual data in it, use them and eventually deallocate the whole chunk when you know none of the individual data are needed any more.  Work in the 90s by Tofte, Aiken, and others (incl. yours truly, with our respective colleagues), has shown that it is possible to statically infer region allocation and deallocation points automatically ("region inference") in such a way as to guarantee that chunks are never freed too early and, in practice, early enough to avoid having too much memory being held for long after the last data in it was needed.  The ML Kit for Regions, for example, is a full Standard ML compiler based on region inference.  In its final version it is combined with intra-region garbage collection: If the static inference shows there is a long-living region, use garbage collection inside it.  You get to have your cake and eat it, too: You have garbage collection for long living data, but a lot of data is managed like a stack, even though it would end in a heap ordinarily.</p>

ContentLicense: CC BY-SA 3.0


问:
Using GoogleSheet Appscript to pull an ID from one column to a cell when another column has the number 1 in it
Column B is filled with a list of IDs, say B2 is 'w131' and B3 is 'z1122', etc.

I need Cell BW2 to be filled with one of these IDs if I put a '1' in column BY,

but it has to be the corresponding ID so putting a '1' in BY2 fills BW2 with 'w131' and putting a '1' in BY3 fills BW2 with 'z1122' etc.

I have the start of some Apps Script code here:

```<code>function setCalculate(){

  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1Z-iZLMiCumHmyloF62335QYOWTn14canbEb4r_7eamM/edit#gid=0");
  var srcSheet = ss.getSheetByName("AutoQuoteDataBase");
  var range = srcSheet.getRange("BY2:BY");
  var values = range.getValues();

  if( values == "1"){

  }
}
</code>```

obviously it isn't finished, or maybe this could be done with a formula.

答:
I believe your goal is as follows.

When the column "BY" is 1, you want to copy the value from column "B" to column "BW".

You want to achieve this by modifying your function of setCalculate.

In this case, how about the following modification?

Modified script:

From:

```<code>var range = srcSheet.getRange("BY2:BY");
var values = range.getValues();

if( values == "1"){

}
</code>```

To:

```<code>var lastRow = srcSheet.getLastRow();
var values = srcSheet.getRange("A2:BY" + lastRow).getValues();
var res = values.map(r => [r[76] == 1 ? r[1] : r[74]]);
srcSheet.getRange("BW2:BW" + lastRow).setValues(res);
</code>```

When this script is run, your goal is achieved.

If you want to set the empty when the column "BY" is not 1, please modify var res = values.map(r => [r[76] == 1 ? r[1] : r[74]]); to var res = values.map(r => [r[76] == 1 ? r[1] : ""]);.

Reference:

map()

Added:

From the following replying,

however I need it to change only the cell BW2, otherwise it is perfect

How about the following modification?

Modified script:

```<code>var lastRow = srcSheet.getLastRow();
var values = srcSheet.getRange("A2:BY" + lastRow).getValues();
var res = values.flatMap(r => r[76] == 1 ? [r[1]] : []);
if (res.length == 0) return;
srcSheet.getRange("BW2").setValue(res[0]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Column B is filled with a list of IDs, say B2 is 'w131' and B3 is 'z1122', etc.

I need Cell BW2 to be filled with one of these IDs if I put a '1' in column BY,

but it has to be the corresponding ID so putting a '1' in BY2 fills BW2 with 'w131' and putting a '1' in BY3 fills BW2 with 'z1122' etc.

I have the start of some Apps Script code here:

function setCalculate(){

  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1Z-iZLMiCumHmyloF62335QYOWTn14canbEb4r_7eamM/edit#gid=0");
  var srcSheet = ss.getSheetByName("AutoQuoteDataBase");
  var range = srcSheet.getRange("BY2:BY");
  var values = range.getValues();

  if( values == "1"){

  }
}

obviously it isn't finished, or maybe this could be done with a formula.

Body:
I believe your goal is as follows.

When the column "BY" is 1, you want to copy the value from column "B" to column "BW".

You want to achieve this by modifying your function of setCalculate.

In this case, how about the following modification?

Modified script:

From:

var range = srcSheet.getRange("BY2:BY");
var values = range.getValues();

if( values == "1"){

}

To:

var lastRow = srcSheet.getLastRow();
var values = srcSheet.getRange("A2:BY" + lastRow).getValues();
var res = values.map(r => [r[76] == 1 ? r[1] : r[74]]);
srcSheet.getRange("BW2:BW" + lastRow).setValues(res);

When this script is run, your goal is achieved.

If you want to set the empty when the column "BY" is not 1, please modify var res = values.map(r => [r[76] == 1 ? r[1] : r[74]]); to var res = values.map(r => [r[76] == 1 ? r[1] : ""]);.

Reference:

map()

Added:

From the following replying,

however I need it to change only the cell BW2, otherwise it is perfect

How about the following modification?

Modified script:

var lastRow = srcSheet.getLastRow();
var values = srcSheet.getRange("A2:BY" + lastRow).getValues();
var res = values.flatMap(r => r[76] == 1 ? [r[1]] : []);
if (res.length == 0) return;
srcSheet.getRange("BW2").setValue(res[0]);


问:
Search data between two tables from SQL
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

```<code>SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"
</code>```

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

答:
It seems to me what you really want is something like this:

```<code>SELECT *
 FROM categories c
 LEFT JOIN products p
 ON c.category_id = p.category_id
AND c.category_name LIKE "%LAPTOP%";
</code>```

However, I can't help to think that since you have p.model LIKE "%LAPTOP%" in your condition, you're probably aiming for something a little bit different. Check out the result in this fiddle and tell me if this is close to what you're looking for or not:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4016c1e1a09c1d718f06a6605fd9677b

Title: Search data between two tables from SQL

Body:
I want to get the data only from "products" table, the problem is if the data was found from "categories" table it will returns empty.

SELECT p.code AS CODE, p.model AS NAME
FROM products p
LEFT JOIN categories c
ON p.category = c.id
WHERE p.model LIKE "%LAPTOP%" OR c.category_name LIKE "%LAPTOP%"

I thought this query will return exact table column you want to achieve if both were connected from this ON p.category = c.id.

Body:
It seems to me what you really want is something like this:

SELECT *
 FROM categories c
 LEFT JOIN products p
 ON c.category_id = p.category_id
AND c.category_name LIKE "%LAPTOP%";

However, I can't help to think that since you have p.model LIKE "%LAPTOP%" in your condition, you're probably aiming for something a little bit different. Check out the result in this fiddle and tell me if this is close to what you're looking for or not:

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4016c1e1a09c1d718f06a6605fd9677b


问:
Use triplets of integers vs HashMap<Integer,HashMap<Integer....>>
let's asume that there is a class Pos, implementing Lombok's equals and hashcode and have only immutable 3 integers (int x,y,z)

what may be more effective
HashMap<Integer, HashMap<Integer, HashMap<Integer,T>>> or
HashMap<Pos, T> ?

considering that i register values only at creation, and after that i only read values lots of times from the map, and also very often loop trough that map for every x and z possible for a specific y value (so in first case i even don't need to filter the y value, i just get the map for it, and filter null z maps for that y value)

答:
Records

Java 16+ offers a brief class definition now: records. So no need to resort to Lombok for that. See JEP 395: Records.

A record is appropriate when the main purpose of your class is to carry data transparently and immutably. The compiler implicitly creates the constructor, getters, equals and hashCode, and toString.

```<code>record Position ( int x , int y , int z ) {}
</code>```

Collect your Position objects.

```<code>List< Position > positions = new ArrayList<>() ;
positions.add( new Person( 1 , 2 , 3 ) ) ;
…
</code>```

From stream to map via Collectors.groupingBy

Group them by their y value.

```<code>Map< Integer, Set< Position > > positionsByY =
    positions
    .stream()
    .collect(
        Collectors.groupingBy( Position :: y )
    );
</code>```

When you want all x and z values for a particular valid of y, retrieve a list.

Body:
Records

Java 16+ offers a brief class definition now: records. So no need to resort to Lombok for that. See JEP 395: Records.

A record is appropriate when the main purpose of your class is to carry data transparently and immutably. The compiler implicitly creates the constructor, getters, equals and hashCode, and toString.

record Position ( int x , int y , int z ) {}

Collect your Position objects.

List< Position > positions = new ArrayList<>() ;
positions.add( new Person( 1 , 2 , 3 ) ) ;
…

From stream to map via Collectors.groupingBy

Group them by their y value.

Map< Integer, Set< Position > > positionsByY =
    positions
    .stream()
    .collect(
        Collectors.groupingBy( Position :: y )
    );

When you want all x and z values for a particular valid of y, retrieve a list.


问:
How to represent Symmetry relationships in database modeling
If there is a symmetry relationship in a table, how to represent it in a elegant way?
For example, there is a table called Friend, in which should contain user ID of two users. If we use UID1 and UID2 in this table, when we want to find out if A_uid and B_uid are friends, we should use

```<code>SELECT * FROM Friend WHERE (UID1 = A_uid AND UID2 = B_uid) OR (UID1 = B_uid AND UID2 = A_uid);
</code>```

since UID1 and UID2 are the same in representing a friendship. And the most important in this dilemma is that UID1 and UID2 are symmetry.

I think this is ugly and want to know if there is a better way to do with it.

Thanks!

答:
An idea off the top of my head: if your UID types are subject to a total ordering, you can do something like this:

```<code>CREATE TABLE friends (
  uid1 uid REFERENCES users,
  uid2 uid REFERENCES users,
  PRIMARY KEY (uid1, uid2),
  CONSTRAINT uid1_above_uid2 CHECK(uid1 < uid2)
);
</code>```

Then your queries will have to put the lower one in first. But you can protect that with a stored procedure that ensures that you do that:

```<code>CREATE FUNCTION friends_with(uid, uid) RETURNS SETOF friends AS $$
  SELECT * FROM friends WHERE uid1 = LESSER($1, $2) AND uid2 = GREATER($1, $2)
$$ LANGUAGE SQL;
</code>```

That will of course have to be translated to your RDBMS of choice.

Now your queries look like this:

```<code>SELECT * FROM friends_with(5001, 2393);
SELECT * FROM friends_with(2393, 5001);
</code>```

and they return the same results.

On the other hand, you could protect it with procedures without putting the CHECK constraint on there, I just think it's handy to prevent you from accidentally inserting the same relation more than once.

Body:
If there is a symmetry relationship in a table, how to represent it in a elegant way?
For example, there is a table called Friend, in which should contain user ID of two users. If we use UID1 and UID2 in this table, when we want to find out if A_uid and B_uid are friends, we should use

SELECT * FROM Friend WHERE (UID1 = A_uid AND UID2 = B_uid) OR (UID1 = B_uid AND UID2 = A_uid);

since UID1 and UID2 are the same in representing a friendship. And the most important in this dilemma is that UID1 and UID2 are symmetry.

I think this is ugly and want to know if there is a better way to do with it.

Thanks!

Body:
An idea off the top of my head: if your UID types are subject to a total ordering, you can do something like this:

CREATE TABLE friends (
  uid1 uid REFERENCES users,
  uid2 uid REFERENCES users,
  PRIMARY KEY (uid1, uid2),
  CONSTRAINT uid1_above_uid2 CHECK(uid1 < uid2)
);

Then your queries will have to put the lower one in first. But you can protect that with a stored procedure that ensures that you do that:

CREATE FUNCTION friends_with(uid, uid) RETURNS SETOF friends AS $$
  SELECT * FROM friends WHERE uid1 = LESSER($1, $2) AND uid2 = GREATER($1, $2)
$$ LANGUAGE SQL;

That will of course have to be translated to your RDBMS of choice.

Now your queries look like this:

SELECT * FROM friends_with(5001, 2393);
SELECT * FROM friends_with(2393, 5001);

and they return the same results.

On the other hand, you could protect it with procedures without putting the CHECK constraint on there, I just think it's handy to prevent you from accidentally inserting the same relation more than once.


问:
Android: lazy-loading of DataBinding view throws exception
There is a large data-bound view, which may take several seconds to inflate. I would like to display the user a splash screen and inflate the main view a delayed action. Android studio throws an exception "Failed to call observer method".

MainActivity:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.screen_splash)
    Handler(Looper.getMainLooper()).postDelayed({
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
            this,
            R.layout.activity_main
        )
        binding.lifecycleOwner = this // this line throws exception
    }, 1000)
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="vm"
        type="com.example.ViewModel"/>
</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
            android:id="@+id/map_list"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity" />
</RelativeLayout>
</code>```

Exception:

```<code>2021-12-05 13:42:56.638 23701-23701/com.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 23701
java.lang.RuntimeException: Failed to call observer method
    at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:226)
    at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeMethodsForEvent(ClassesInfoCache.java:194)
    at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeCallbacks(ClassesInfoCache.java:185)
    at androidx.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:37)
    at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
    at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:196)
    at androidx.databinding.ViewDataBinding.setLifecycleOwner(ViewDataBinding.java:434)
    at com.example.databinding.ActivityMainBindingImpl.setLifecycleOwner(ActivityMainBindingImpl.java:166)
    at com.example.MainActivity.onCreate$lambda-3(MainActivity.kt:106)
    at com.example.MainActivity.$r8$lambda$lffeScwTEbHi2B1isKEoQYU2po4(Unknown Source:0)
    at com.example.MainActivity$$ExternalSyntheticLambda5.run(Unknown Source:2)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8178)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
 Caused by: java.lang.NumberFormatException: s == null
    at java.lang.Integer.parseInt(Integer.java:577)
    at java.lang.Integer.valueOf(Integer.java:801)
    at com.example.databinding.ControlPanelBindingImpl.executeBindings(ControlPanelBindingImpl.java:800)...
</code>```

答:
Finally found the problem and, in retrospect, it was too elementary for the question:

Must assign ViewModel before lifecycleOwner

```<code>binding.viewModel = myViewModer
binding.livecycleOwner = this@MainActivity
</code>```

Just changing order of these lines fixed it.

Body:
There is a large data-bound view, which may take several seconds to inflate. I would like to display the user a splash screen and inflate the main view a delayed action. Android studio throws an exception "Failed to call observer method".

MainActivity:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.screen_splash)
    Handler(Looper.getMainLooper()).postDelayed({
        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
            this,
            R.layout.activity_main
        )
        binding.lifecycleOwner = this // this line throws exception
    }, 1000)
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="vm"
        type="com.example.ViewModel"/>
</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
            android:id="@+id/map_list"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity" />
</RelativeLayout>

Exception:

2021-12-05 13:42:56.638 23701-23701/com.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 23701
java.lang.RuntimeException: Failed to call observer method
    at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:226)
    at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeMethodsForEvent(ClassesInfoCache.java:194)
    at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeCallbacks(ClassesInfoCache.java:185)
    at androidx.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:37)
    at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
    at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:196)
    at androidx.databinding.ViewDataBinding.setLifecycleOwner(ViewDataBinding.java:434)
    at com.example.databinding.ActivityMainBindingImpl.setLifecycleOwner(ActivityMainBindingImpl.java:166)
    at com.example.MainActivity.onCreate$lambda-3(MainActivity.kt:106)
    at com.example.MainActivity.$r8$lambda$lffeScwTEbHi2B1isKEoQYU2po4(Unknown Source:0)
    at com.example.MainActivity$$ExternalSyntheticLambda5.run(Unknown Source:2)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8178)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
 Caused by: java.lang.NumberFormatException: s == null
    at java.lang.Integer.parseInt(Integer.java:577)
    at java.lang.Integer.valueOf(Integer.java:801)
    at com.example.databinding.ControlPanelBindingImpl.executeBindings(ControlPanelBindingImpl.java:800)...

Body:
Finally found the problem and, in retrospect, it was too elementary for the question:

Must assign ViewModel before lifecycleOwner

binding.viewModel = myViewModer
binding.livecycleOwner = this@MainActivity

Just changing order of these lines fixed it.


问:
SQL query to derive average sale of an item
Below are two tables. An item is being sold at different values during different periods. I need to calculate average sale of the item. I need to come to an optimal working query. I think the trick would be to map each sales date with their start_date and end_date and multiply the quatity with their respective price for that period and then derive the avergae using the formula total sales amount/ total quatity.

CREATE TABLE sales(
 item_id varchar(255) ,
 start_date date ,
 end_date date,
 price int
) ;

insert into sales values
('mobile','2021-01-01','2021-01-05',500),
('mobile','2021-01-06','2021-01-09',400),
('mobile','2021-01-10','2021-01-15',900) ;

CREATE TABLE item(
 sales_id int,
 item_id varchar(255) ,
 sales_date date ,
 quatity int
) ;

insert into item values
(101,'mobile','2021-01-01',10),
(102,'mobile','2021-01-06',20),
(103,'mobile','2021-01-15',30) ;
```

答:
Please try this,</p>
```<code>SELECT
i.item_id,avg(s.price*i.quatity) FROM
item I
LEFT JOIN
sales S
on
I.item_id=S.item_id
AND I.sales_date >=S.start_date AND I.sales_date<=S.end_date
group by i.item_id;
</code>```

Body:
Please try this,

SELECT
i.item_id,avg(s.price*i.quatity) FROM
item I
LEFT JOIN
sales S
on
I.item_id=S.item_id
AND I.sales_date >=S.start_date AND I.sales_date<=S.end_date
group by i.item_id;


问:
Replace a pattern in column of a csv file using Python
I am looking for some help with editing CSV in python. I have a file in below format

Account
InstanceId
InstanceName
InstanceType
Platform
Status
AvailabilityZone
PrivateIpAddress
publicIpAdress
Owner

12345678901
i-0abcdef1234567890
Test123
t3a.micro
windows
stopped
ap-southeast-2a
10.0.0.100

arn:aws:sts::12345678901:user/test-user

98765432109
i-0987654321abcdefg
test345
t2.nano
Linux
running
ap-southeast-2b
10.0.0.200
99.99.99.100
arn:aws:sts::98765432109:assumed-role/testrole/user@example.com

98765432109
i-abcdefghij01234899
test987
t2.nano
windows
running
ap-southeast-2b
10.0.0.201

I would like to edit this file in place and and have the resulting file in below format

Account
InstanceId
InstanceName
InstanceType
Platform
Status
AvailabilityZone
PrivateIpAddress
publicIpAdress
Owner

12345678901
i-0abcdef1234567890
Test123
t3a.micro
windows
stopped
ap-southeast-2a
10.0.0.100

test-user

98765432109
i-0987654321abcdefg
test345
t2.nano
Linux
running
ap-southeast-2b
10.0.0.200
99.99.99.100
user@example.com

98765432109
i-abcdefghij01234899
test987
t2.nano
windows
running
ap-southeast-2b
10.0.0.201

I tried a few things with no luck and would really appreciate if you can help me with this.
Thanks in advance.

答:
Use:

```<code>df['Owner'] = df['Owner'].str.split('/').str[-1]
</code>```

Demonstration:

```<code>df = pd.DataFrame({'Owner': ['arn:aws:sts::12345678901:user/test-user']})
df['Owner'].str.split('/').str[-1]
</code>```

Output:

Body:
Use:

df['Owner'] = df['Owner'].str.split('/').str[-1]

Demonstration:

df = pd.DataFrame({'Owner': ['arn:aws:sts::12345678901:user/test-user']})
df['Owner'].str.split('/').str[-1]

Output:


问:
Im working on a CTF project using SecGen and I have everything install and when I run the command to run SecGen this is what I get
enter image description here

Here is a screen shot of the commands.

答: process_helper is provided by a gem package named process_helper. It is very likely, that your package will contain a file Gemfile with a description of all the dependencies you will need - and you can install all of them using a command bundle install. Individually you can install packages by using eg. gem install process_helper for process_helper.


问:
How to display two or more array on same table
Hey guys I have one mysql table tick where i have some info like user id now to display that data I need to retrieve from user table name of the user based on that id

```<code>?php

$mysql5 = mysqli_query($dbc, "SELECT * FROM tick where status='1' ORDER BY dt DESC LIMIT 6 ");
if($indtbl = mysqli_fetch_array($mysql5))
{

  $title = $indtbl['tickettitle'];
  $company = $indtbl['companyname'];
  $companyid =$indtbl['compid'];
  $trackid = $indtbl['trackid'];
  $assignto = $indtbl['assignto'];
  $priority = $indtbl['priority'];

}
?>
</code>```

and user table query is based on first one

```<code><?php
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
if($rest = mysqli_fetch_array($findresults2323))
{

  $userimg = $rest['img'];
  $fname1 = $rest['fname'];
  $lname1 = $rest['lname'];

}
?>
</code>```

now the problem is when i am fetching the array

```<code><thead>
                        <tr>
                          <th class="text-left">Title</th>
                          <th>Company</th>
                          <th>Ticket ID</th>
                          <th>Assign To</th>
                          <th>Priority</th>

                        </tr>
                      </thead>
                      <?php

while($rowten = mysqli_fetch_array($mysql5)) {

$retrive11 = mysqli_fetch_array($findresults23);

?>
<tr>
    <td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["tickettitle"]; ?></td>
    <td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["companyname"];?> <?php echo $rowten["compid"];?></td>
    <td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["trackid"]; ?></td>
    <td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
    <td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["priority"]; ?></td>
</tr>
<?php

}

?>
</code>```

i am getting the error

```<code>Notice: Trying to access array offset on value of type null  on line 459
</code>```

line 459 is

```<code><td><a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?></td>
</code>```

what I am doing wrong

答:
In order to use 2 queries, you need to run the second query inside of the loop so it retrieves the specific user record for the given result from the tick query.

while($rowten = mysqli_fetch_array($mysql5)) {
    $assignto = $rowten['assignto'];
    $findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
    $retrive11 = mysqli_fetch_array($findresults23);
```
<p>However, this is very inefficient as it requires a query on the user table for every result in the tick query. The proper way of doing this is to use a single query with a join.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT tick.*, users.fname FROM tick LEFT JOIN users ON (tick.assignto=users.id) where tick.status='1' ORDER BY tick.dt DESC LIMIT 6
</code>```

The result of this query will have all the data from both your queries in one result.

Body:
Hey guys I have one mysql table tick where i have some info like user id now to display that data I need to retrieve from user table name of the user based on that id

?php

$mysql5 = mysqli_query($dbc, "SELECT * FROM tick where status='1' ORDER BY dt DESC LIMIT 6 ");
if($indtbl = mysqli_fetch_array($mysql5))
{

  $title = $indtbl['tickettitle'];
  $company = $indtbl['companyname'];
  $companyid =$indtbl['compid'];
  $trackid = $indtbl['trackid'];
  $assignto = $indtbl['assignto'];
  $priority = $indtbl['priority'];

}
?>

and user table query is based on first one

<?php
$findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
if($rest = mysqli_fetch_array($findresults2323))
{

  $userimg = $rest['img'];
  $fname1 = $rest['fname'];
  $lname1 = $rest['lname'];

}
?>

now the problem is when i am fetching the array

                          Title
                          Company
                          Ticket ID
                          Assign To
                          Priority

                      <?php

while($rowten = mysqli_fetch_array($mysql5)) {

$retrive11 = mysqli_fetch_array($findresults23);

?>

    <a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["tickettitle"]; ?>
    <a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["companyname"];?> <?php echo $rowten["compid"];?>
    <a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["trackid"]; ?>
    <a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?>
    <a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $rowten["priority"]; ?>

<?php

}

?>

i am getting the error

Notice: Trying to access array offset on value of type null  on line 459

line 459 is

<a href="readit.php?id=<?php echo $rowten["id"];?>"><?php echo $retrive11['fname'];?>

what I am doing wrong

Body:
In order to use 2 queries, you need to run the second query inside of the loop so it retrieves the specific user record for the given result from the tick query.

while($rowten = mysqli_fetch_array($mysql5)) {
    $assignto = $rowten['assignto'];
    $findresults2323 = mysqli_query($dbc, "SELECT * FROM users WHERE id= '$assignto'");
    $retrive11 = mysqli_fetch_array($findresults23);

However, this is very inefficient as it requires a query on the user table for every result in the tick query. The proper way of doing this is to use a single query with a join.

SELECT tick.*, users.fname FROM tick LEFT JOIN users ON (tick.assignto=users.id) where tick.status='1' ORDER BY tick.dt DESC LIMIT 6

The result of this query will have all the data from both your queries in one result.


问:
How to get Hotkey for background MFC app to show
I create a MFC App that can hide (SHIFT+W) or show (SHIFT+A) if I press hot key. By default it's hidden when startup. I search the solution and find it:

```<code>// OnPaint to paint the app and hide
void CAppDlg::OnPaint()
{
    ShowWindow(SW_HIDE);
}

// Register the Hotkey when app startup
BOOL CAppDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    RegisterHotKey(CAppDlg::m_hWnd, 1001, MOD_SHIFT, 'A');
    RegisterHotKey(CAppDlg::m_hWnd, 1002, MOD_SHIFT, 'a');
}

// Get SHIFT+W to hide app again
BOOL CAppDlg::PreTranslateMessage(MSG* pMsg){
    if (pMsg->message == WM_KEYDOWN){
        if (pMsg->wParam == 0x57){
            if (GetKeyState(VK_SHIFT) & 0x8000) {
                ShowWindow(SW_HIDE);
            }
        }
    }

    return CDialog::PreTranslateMessage(pMsg);
}

// Get hotkey id (SHIFT+A) to show app
LRESULT CAppDlg::OnHotKey(WPARAM wParam, LPARAM lParam){
    if (wParam == 1001 || wParam == 1002){
        ShowWindow(SW_SHOWNORMAL);
    }
    return 0;
}
</code>```

This app will hide when startup, function ShowWindow(SW_HIDE) must be declared in OnPaint() function, if it's declared in OnInitDialog() it's not hidden. But if I press SHIFT+A to show windows, it shows and hide right away (because of OnPaint() function is recalled). How can I do now? Thank all

答:
Here is how you can hide a main window of the dialog-based MFC app.

Add bool member variable to your dialog class:

```<code>bool m_bFirst = true;
</code>```

Add handler for WM_WINDOWPOSCHANGING message to your BEGIN_MESSAGE_MAP:

```<code>ON_WM_WINDOWPOSCHANGING()
</code>```

and declare it in the header file

```<code>afx_msg void OnWindowPosChanging(WINDOWPOS* lpwndpos);
</code>```

You can use a Class Wizard to add it to your class.

In the handler, enforce a flag to hide the window until you get a first hot key message:

```<code>void CMFCApplicationDlg::OnWindowPosChanging(WINDOWPOS* lpwndpos)
{
    if (m_bFirst) {
        lpwndpos->flags &= ~SWP_SHOWWINDOW;
        lpwndpos->flags |= SWP_HIDEWINDOW;
    }
    CDialogEx::OnWindowPosChanging(lpwndpos);
}
</code>```

And finally reset that flag in your WM_HOTKEY handler:

```<code>void CMFCApplicationDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
{
    if (nHotKeyId == 1001) {
        m_bFirst = false;
        ShowWindow(SW_SHOW);
    }
    else if (nHotKeyId == 1002)
        ShowWindow(SW_HIDE);
}
</code>```

NOTE:

I would strongly advise against using simple MOD_SHIFT modifier for the hot key: you will no longer be able to type upper-case A into any other apps.

Body:
I create a MFC App that can hide (SHIFT+W) or show (SHIFT+A) if I press hot key. By default it's hidden when startup. I search the solution and find it:

// OnPaint to paint the app and hide
void CAppDlg::OnPaint()
{
    ShowWindow(SW_HIDE);
}

// Register the Hotkey when app startup
BOOL CAppDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    RegisterHotKey(CAppDlg::m_hWnd, 1001, MOD_SHIFT, 'A');
    RegisterHotKey(CAppDlg::m_hWnd, 1002, MOD_SHIFT, 'a');
}

// Get SHIFT+W to hide app again
BOOL CAppDlg::PreTranslateMessage(MSG* pMsg){
    if (pMsg->message == WM_KEYDOWN){
        if (pMsg->wParam == 0x57){
            if (GetKeyState(VK_SHIFT) & 0x8000) {
                ShowWindow(SW_HIDE);
            }
        }
    }

    return CDialog::PreTranslateMessage(pMsg);
}

// Get hotkey id (SHIFT+A) to show app
LRESULT CAppDlg::OnHotKey(WPARAM wParam, LPARAM lParam){
    if (wParam == 1001 || wParam == 1002){
        ShowWindow(SW_SHOWNORMAL);
    }
    return 0;
}

This app will hide when startup, function ShowWindow(SW_HIDE) must be declared in OnPaint() function, if it's declared in OnInitDialog() it's not hidden. But if I press SHIFT+A to show windows, it shows and hide right away (because of OnPaint() function is recalled). How can I do now? Thank all

Body:
Here is how you can hide a main window of the dialog-based MFC app.

Add bool member variable to your dialog class:

bool m_bFirst = true;

Add handler for WM_WINDOWPOSCHANGING message to your BEGIN_MESSAGE_MAP:

ON_WM_WINDOWPOSCHANGING()

and declare it in the header file

afx_msg void OnWindowPosChanging(WINDOWPOS* lpwndpos);

You can use a Class Wizard to add it to your class.

In the handler, enforce a flag to hide the window until you get a first hot key message:

void CMFCApplicationDlg::OnWindowPosChanging(WINDOWPOS* lpwndpos)
{
    if (m_bFirst) {
        lpwndpos->flags &= ~SWP_SHOWWINDOW;
        lpwndpos->flags |= SWP_HIDEWINDOW;
    }
    CDialogEx::OnWindowPosChanging(lpwndpos);
}

And finally reset that flag in your WM_HOTKEY handler:

void CMFCApplicationDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2)
{
    if (nHotKeyId == 1001) {
        m_bFirst = false;
        ShowWindow(SW_SHOW);
    }
    else if (nHotKeyId == 1002)
        ShowWindow(SW_HIDE);
}

NOTE:

I would strongly advise against using simple MOD_SHIFT modifier for the hot key: you will no longer be able to type upper-case A into any other apps.


问:
Unsure why my math min function is not working but math max function is in script code

function selectHighestNumber()
    {
        var valueFirstNumber;
        var valueSecondNumber;
        var valueThirdNumber;
        var selectMaxNumber;

        valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
        valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
        valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
        selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
        document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
    {
        var valueFirstNumber;
        var valueSecondNumber;
        var valueThirdNumber;
        var selectMinNumber;

        valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
        valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
        valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
        selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
        document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main class="fancy-border">
    <form id="userNumberEntry">
        <p><label for="txtFirstNumberValue">Enter your first number here:</label>
        <input type="text"  id="txtFirstNumberValue"  maxlength="20"  size="20"></p>
        <p><label for="txtSecondNumberValue">Enter your second number here:</label>
        <input type="text"  id="txtSecondNumberValue"  maxlength="20"  size="20"></p>
        <p><label for="txtThirdNumberValue">Enter your third number here:</label>
        <input type="text"  id="txtThirdNumberValue"  maxlength="20"  size="20"></p>
        <p><input type="button"
                  value="Find the highest number"
                  id="btnSubmit"
                  onclick="selectHighestNumber();">
        </p>
        <p><input type="button"
                  value="Find the lowest number"
                  id="btnSubmit"
                  onlick="selectLowestNumber();">
        </p>
        <br>
        <div id="selectRankingNumbersResults">
        </div> <!--end of selectRankingNumberValues div-->
    </form>
</main></code>```

So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.

```<code>function selectHighestNumber()
  {
    var valueFirstNumber;
    var valueSecondNumber;
    var valueThirdNumber;
    var selectMaxNumber;

    valueFirstNumber = document.getElementById("txtFirstNumberValue")
    .value;
    valueSecondNumber = document.getElementById("txtSecondNumberValue")
    .value;
    valueThirdNumber = document.getElementById("txtThirdNumberValue")
    .value;
    selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
    valueThirdNumber);
    document.getElementById("selectRankingNumbersResults").innerHTML =
    selectMaxNumber;
}

function selectLowestNumber()
   {
    var valueFirstNumber;
    var valueSecondNumber;
    var valueThirdNumber;
    var selectMinNumber;

    valueFirstNumber = document.getElementById("txtFirstNumberValue")
    .value;
    valueSecondNumber = document.getElementById("txtSecondNumberValue")
    .value;
    valueThirdNumber = document.getElementById("txtThirdNumberValue")
    .value;
    selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
    valueThirdNumber);
    document.getElementById("selectRankingNumbersResults").innerHTML =
    selectMinNumber;
}
</code>```

If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!

答:
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.

Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.

document.querySelector("form").addEventListener("submit", function(event) {
  event.preventDefault();
  console.log("Max:" + getEdgeCase(true));
  console.log("Min:" + getEdgeCase(false));
});

function getEdgeCase(flag) {
  // get all the inputs in one go and convert them to an array
  var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
  var inputList = inputList.map(function(input) {
    // convert to number, if it's not a valid number and ends up as NaN then return 0
    return +input.value || 0;
  });
  // get the right function and call apply (spreads an array into arguments)
  return Math[flag ? "max" : "min"].apply(Math, inputList);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="number" />
  <input type="number" />
  <input type="number" />
  <input type="submit" />
</form></code>```

Body:
function selectHighestNumber()
    {
        var valueFirstNumber;
        var valueSecondNumber;
        var valueThirdNumber;
        var selectMaxNumber;

        valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
        valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
        valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
        selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber, valueThirdNumber);
        document.getElementById("selectRankingNumbersResults").innerHTML = selectMaxNumber;
}
function selectLowestNumber()
    {
        var valueFirstNumber;
        var valueSecondNumber;
        var valueThirdNumber;
        var selectMinNumber;

        valueFirstNumber = document.getElementById("txtFirstNumberValue").value;
        valueSecondNumber = document.getElementById("txtSecondNumberValue").value;
        valueThirdNumber = document.getElementById("txtThirdNumberValue").value;
        selectMinNumber = Math.min(+valueFirstNumber, +valueSecondNumber, +valueThirdNumber);
        document.getElementById("selectRankingNumbersResults").innerHTML = selectMinNumber;
}

    <form id="userNumberEntry">

Enter your first number here:
        <input type="text"  id="txtFirstNumberValue"  maxlength="20"  size="20">

Enter your second number here:
        <input type="text"  id="txtSecondNumberValue"  maxlength="20"  size="20">

Enter your third number here:
        <input type="text"  id="txtThirdNumberValue"  maxlength="20"  size="20">

<input type="button"
                  value="Find the highest number"
                  id="btnSubmit"
                  onclick="selectHighestNumber();">

<input type="button"
                  value="Find the lowest number"
                  id="btnSubmit"
                  onlick="selectLowestNumber();">

    </form>

So very recently I came into a problem in my script where I was unsure why my Math min function was not working. I asked about that issue in a previous question and found that a spelling error was causing one of my functions to not work. Essentially, I have two functions, a math min, and a math max, both serving similar purposes. I am working in Html code, and use a script for my functions within my Html document. The purpose of this math min and math max function is that I have three text boxes to input numbers into, there are two buttons that will either serve to show the highest or lowest of these three values. My math max function works fine and shows the highest value, however, my math min function does not. It does not return any value at all. I have cross-checked my code to see if it was misspelled, spacing errors, or other mismatched words with the rest of my code but none of it seems to be the problem. This is how my math max and math min functions in my script look respectively.

function selectHighestNumber()
  {
    var valueFirstNumber;
    var valueSecondNumber;
    var valueThirdNumber;
    var selectMaxNumber;

    valueFirstNumber = document.getElementById("txtFirstNumberValue")
    .value;
    valueSecondNumber = document.getElementById("txtSecondNumberValue")
    .value;
    valueThirdNumber = document.getElementById("txtThirdNumberValue")
    .value;
    selectMaxNumber = Math.max(valueFirstNumber, valueSecondNumber,
    valueThirdNumber);
    document.getElementById("selectRankingNumbersResults").innerHTML =
    selectMaxNumber;
}

function selectLowestNumber()
   {
    var valueFirstNumber;
    var valueSecondNumber;
    var valueThirdNumber;
    var selectMinNumber;

    valueFirstNumber = document.getElementById("txtFirstNumberValue")
    .value;
    valueSecondNumber = document.getElementById("txtSecondNumberValue")
    .value;
    valueThirdNumber = document.getElementById("txtThirdNumberValue")
    .value;
    selectMinNumber = Math.min(valueFirstNumber, valueSecondNumber,
    valueThirdNumber);
    document.getElementById("selectRankingNumbersResults").innerHTML =
    selectMinNumber;
}

If anyone could help me understand where I might be going wrong, that would be greatly appreciated! I am very confused about what I could have coded wrong, so any insight/outlook is greatly appreciated!

Body:
Math.max and Math.min will return the largest/smallest value (or -Infinity/Infinity if no values are supplied) and then convert to a number if they're not already, this means that strings will first be compared as strings and not numbers ("123" > "3"), so you should first convert each value to a number.

Also I recommend batching up the whole process instead of getting each element separately, reading its value, converting it to a number, checking it's valid, passing it to the function. So try to do the whole thing in a loop of some sort.

document.querySelector("form").addEventListener("submit", function(event) {
  event.preventDefault();
  console.log("Max:" + getEdgeCase(true));
  console.log("Min:" + getEdgeCase(false));
});

function getEdgeCase(flag) {
  // get all the inputs in one go and convert them to an array
  var inputList = [].slice.call(document.querySelectorAll("form input[type=\"number\"]"));
  var inputList = inputList.map(function(input) {
    // convert to number, if it's not a valid number and ends up as NaN then return 0
    return +input.value || 0;
  });
  // get the right function and call apply (spreads an array into arguments)
  return Math[flag ? "max" : "min"].apply(Math, inputList);
}

<form>
  <input type="number" />
  <input type="number" />
  <input type="number" />
  <input type="submit" />
</form>


问:
non-http in mochiweb
I am using mochiweb for a server that may also get a TCP connction to which the client sends a simple string (without a newline, the string is not http). Mochiweb uses HTTP sockets and therefore fails to detect this (i dont even get http_error that i can easily get in mochiweb). How can I solve this? Ideally I wish to change mochiweb code to do setopt({packet, http_or_raw}) but this kind of thing does not exist. How would you recommend handling this? my current idea was to modify mochiweb and use erlang:decode_packet, is there a better approach?

EDIT:

More info.
Our server is a websocket service. We wish to allow
people without a ws supporting browser to use it so we use a
flash object to do websocket when the browser can't. The flash object needs to get a flash policy file. Flash
forces the file to be in one of two places:
- port 843 (flash hard coded)
- the port of the ws service
The flash protocol is NOT HTTP based.
Amazon ELB does not allow port forwarding for
most ports below 1024, so we
implemented the flash server in the same port via a patch to
mochiweb (https://github.com/nivertech/mochiweb/tree/ori_flash_170811).

Any advice?

答:
mochiweb isn't designed to handle this use case, if it doesn't look
like HTTP then the connection is closed and it gets discarded. You
would have to go around mochiweb_http for this purpose. I'd suggest
using an alternate port, or making it look like HTTP.

If I really wanted to do what you say you want to do, I would copy
mochiweb_http.erl to some other name (e.g. sometimes_not_http.erl) and
make the appropriate changes to loop/2 and request/2… then instead of
adding mochiweb_http to your supervisor you'd add sometimes_not_http.
It is not necessary or recommended to make modifications to mochiweb
in-place.

Title: non-http in mochiweb


问:
Why won't my Django template display the correct date listed in the database?
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why?
All of these problems seem related to the date picker feature. Are Django forms not compatible with the date picker feature?

settings.py:

```<code>TIME_ZONE = 'US/Eastern'
USE_I18N = True
USE_L10N = True
DATE_INPUT_FORMATS = '%m/%d/%y'
</code>```

models.py:

```<code>class DecisionsList(models.Model):
        summary = models.CharField(default="", max_length=75, `
 verbose_name="Decision Summary")
        description = models.CharField(max_length=100, verbose_name="Decision Description")
        valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date")
        date_created = models.DateTimeField(default=timezone.now)
</code>```

views.py:

class UpdateDecisionView(LoginRequiredMixin, UpdateView):

```<code>  model = DecisionsList
    form_class = DecisionForm
    template_name = "users/update_decision.html"
</code>```

forms.py:

```<code>class DecisionForm(forms.ModelForm):
    class Meta:
        model = DecisionsList
        fields = ['summary', 'description', 'valid_until']
        widgets = {
            'valid_until': forms.DateInput(
                format='%m/%d/%y',
                attrs={'type': 'date', 'placeholder': "Select a date"
                       }),
            'description': forms.Textarea(
                attrs={'line-height': '50px',
                       })
        }
</code>```

update_decision.html:

```<code>{% extends "users/base_users.html" %}

{% load crispy_forms_tags %}
{% load crispy_forms_filters %}

<body>

  {% block content %}

      <div class="nav">
        <a id="company" {% block company %} class="selected" {% endblock %} href=""></a>
      </div>

      <div class="containers database-containers">
        <h2>Update a Decision</h2>
      <form method="post">
        <div class="form-group">
                  {% csrf_token %}
                  {{form.summary|as_crispy_field}}
                  <div class="text-area">
                  {{form.description|as_crispy_field}}
                  </div>
                  <div class="short-field">
                  {{form.valid_until|as_crispy_field}}
                  </div>
            <input type="submit" class="btn" value="Update"/>
              <a href="{% url 'users:company' %}" class="btn">Cancel</a>
        </div>
      </form>
      </div>

  {% endblock %}

</body>
</code>```

答:
Here is a valid list of date formats that Django will accept:

```<code>[
    '%Y-%m-%d',  # '2006-10-25'
    '%m/%d/%Y',  # '10/25/2006'
    '%m/%d/%y',  # '10/25/06'
    '%b %d %Y',  # 'Oct 25 2006'
    '%b %d, %Y',  # 'Oct 25, 2006'
    '%d %b %Y',  # '25 Oct 2006'
    '%d %b, %Y',  # '25 Oct, 2006'
    '%B %d %Y',  # 'October 25 2006'
    '%B %d, %Y',  # 'October 25, 2006'
    '%d %B %Y',  # '25 October 2006'
    '%d %B, %Y',  # '25 October, 2006'
]
</code>```

If you use the JQuery UI datepicker, you can change the format on the UI element. Just make sure it complies with what Django accepts - more info

```<code>$( ".selector" ).datepicker({
  dateFormat: "mm/dd/yy"
});
</code>```

Body:
My model contains a datefield, 'valid_until'. Even though an entry contains the date '12/25/2022', the update template literally displays as its contents 'mm/dd/yyyy' when the user tries to modify the date. Why? Also, there seems to be no way to create a placeholder text or even change that date format (it always renders in that same format---even though I specify '%m/%d/%y' in forms.py and settings.py contains the format '%m/%d/%y'). Why?
All of these problems seem related to the date picker feature. Are Django forms not compatible with the date picker feature?

settings.py:

TIME_ZONE = 'US/Eastern'
USE_I18N = True
USE_L10N = True
DATE_INPUT_FORMATS = '%m/%d/%y'

models.py:

class DecisionsList(models.Model):
        summary = models.CharField(default="", max_length=75, `
 verbose_name="Decision Summary")
        description = models.CharField(max_length=100, verbose_name="Decision Description")
        valid_until = models.DateField(default=timezone.now, verbose_name="Voting End Date")
        date_created = models.DateTimeField(default=timezone.now)

views.py:

class UpdateDecisionView(LoginRequiredMixin, UpdateView):

  model = DecisionsList
    form_class = DecisionForm
    template_name = "users/update_decision.html"

forms.py:

class DecisionForm(forms.ModelForm):
    class Meta:
        model = DecisionsList
        fields = ['summary', 'description', 'valid_until']
        widgets = {
            'valid_until': forms.DateInput(
                format='%m/%d/%y',
                attrs={'type': 'date', 'placeholder': "Select a date"
                       }),
            'description': forms.Textarea(
                attrs={'line-height': '50px',
                       })
        }

update_decision.html:

{% extends "users/base_users.html" %}

{% load crispy_forms_tags %}
{% load crispy_forms_filters %}

  {% block content %}

Update a Decision

      <form method="post">

                  {% csrf_token %}
                  {{form.summary|as_crispy_field}}

                  {{form.description|as_crispy_field}}

                  {{form.valid_until|as_crispy_field}}

            <input type="submit" class="btn" value="Update"/>
              Cancel

      </form>

  {% endblock %}

Body:
Here is a valid list of date formats that Django will accept:

[
    '%Y-%m-%d',  # '2006-10-25'
    '%m/%d/%Y',  # '10/25/2006'
    '%m/%d/%y',  # '10/25/06'
    '%b %d %Y',  # 'Oct 25 2006'
    '%b %d, %Y',  # 'Oct 25, 2006'
    '%d %b %Y',  # '25 Oct 2006'
    '%d %b, %Y',  # '25 Oct, 2006'
    '%B %d %Y',  # 'October 25 2006'
    '%B %d, %Y',  # 'October 25, 2006'
    '%d %B %Y',  # '25 October 2006'
    '%d %B, %Y',  # '25 October, 2006'
]

If you use the JQuery UI datepicker, you can change the format on the UI element. Just make sure it complies with what Django accepts - more info

$( ".selector" ).datepicker({
  dateFormat: "mm/dd/yy"
});


问:
How to add create powershell aliases for git commands
I have been tired of doing git add & git commit everyday
I know in Linux you can just edit your bashrc using 1 line command
But since I use windows I am having a hard time creating an alias for

```<code> Fucntion gcd {
    Insert("git commit")
}
Set-Alias gcm gcd
</code>```

But I get an error

```<code>Set-Alias : Alias is not writeable because alias gcm is read-only or constant and cannot be written to.
</code>```

I also tried without using Insert Keyword even without functions still getting an error

答:
Why don't you just try tu use posh-git

posh-git is a PowerShell module that integrates Git and PowerShell by providing Git status summary information that can be displayed in the PowerShell prompt, e.g.:

```<code>C:\Users\Keith\GitHub\posh-git [main ≡ +0 ~1 -0 | +0 ~1 -0 !]>
</code>```

posh-git also provides tab completion support for common git commands, branch names, paths and more. For example, with posh-git, PowerShell can tab complete git commands like checkout by typing git ch and pressing the tab key. That will tab complete to git checkout and if you keep pressing tab, it will cycle through other command matches such as cherry and cherry-pick. You can also tab complete remote names and branch names e.g.: git pull or ma tab completes to git pull origin main.

Body:
I have been tired of doing git add & git commit everyday
I know in Linux you can just edit your bashrc using 1 line command
But since I use windows I am having a hard time creating an alias for

 Fucntion gcd {
    Insert("git commit")
}
Set-Alias gcm gcd

But I get an error

Set-Alias : Alias is not writeable because alias gcm is read-only or constant and cannot be written to.

I also tried without using Insert Keyword even without functions still getting an error

Body:
Why don't you just try tu use posh-git

posh-git is a PowerShell module that integrates Git and PowerShell by providing Git status summary information that can be displayed in the PowerShell prompt, e.g.:

C:\Users\Keith\GitHub\posh-git [main ≡ +0 ~1 -0 | +0 ~1 -0 !]>

posh-git also provides tab completion support for common git commands, branch names, paths and more. For example, with posh-git, PowerShell can tab complete git commands like checkout by typing git ch and pressing the tab key. That will tab complete to git checkout and if you keep pressing tab, it will cycle through other command matches such as cherry and cherry-pick. You can also tab complete remote names and branch names e.g.: git pull or ma tab completes to git pull origin main.


问:
Why are these solid lines appearing below my plot in ggplot?

Here is my code:

```<code>pokemon <- read_csv("https://uwmadison.box.com/shared/static/hf5cmx3ew3ch0v6t0c2x56838er1lt2c.csv")

pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ .) +
  theme(legend.position = "bottom")
</code>```

for this home work assignment we are working with faceting, and everything pretty much looks how it should, but there those two thick lines at the bottom of the plot.  If anyone has any idea why its happening that would be awesome!

答:
Those are your x axis labels. The labels are much longer than the available space after faceting, so they’re overlapping into a big jumble.

Possible solutions:

use coord_flip(), which is often a nice solution to long x axis labels

recode the x variable labels to be shorter

facet to fewer columns using the ncol argument to facet_wrap()

reduce the number of facets by collapsing or removing groups with few cases

I think your issue is compounded by every Pokémon name being repeated for each facet column, even though only a subset actually appears in each facet. You can fix this by setting scales = "free_x" within facet_wrap(), so that only labels included in each facet will be included.

Body:
Here is my code:

pokemon <- read_csv("https://uwmadison.box.com/shared/static/hf5cmx3ew3ch0v6t0c2x56838er1lt2c.csv")

pokemon %>%
  select(Name, type_1, Attack, Defense) %>%
  mutate(AttDefRatio = Attack/Defense) %>%
  ggplot(
    aes(Name, AttDefRatio)
  ) +
  geom_point(size = 0.5) +
  facet_wrap(type_1 ~ .) +
  theme(legend.position = "bottom")

for this home work assignment we are working with faceting, and everything pretty much looks how it should, but there those two thick lines at the bottom of the plot.  If anyone has any idea why its happening that would be awesome!


问:
Scrolling in Android
In my project I want to use scrolling for rendering the pdf in landscape mode.
I have used onscroll method in Android, but when I run the application on a Samsung Galaxy device the scrolling is not smooth.
Can anybody suggest how to get fine and smooth scrolling, and are there any methods other than onscroll?</p>

答:
To get smooth scrolling of a complex image, try caching it to an offscreen bitmap. The trick to minimize memory usage is to only cache a little bit beyond the visible view bounds, and regenerate the cache as the user scrolls.

For sample code, see https://github.com/ldo/view_cache_demo_android

Title: Scrolling in Android


问:
How to call DLL exported functions with @<number> at end of function name from C
I am trying to call functions from ntvdm.lib in Visual Studio 2019 using the Visual Studio 2017 - Windows XP (v141_XP) platform toolset, with the following defined:

```<code>#define _WIN32_WINNT 0x0501
#define i386
</code>```

running dumpbin /exports on the LIB file I get the following output:

```<code>Microsoft (R) COFF/PE Dumper Version 14.29.30037.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file ntvdm.lib

File Type: LIBRARY

     Exports

       ordinal    name

                  _BlockWOWIdle@4
                  _CurrentMonitorTeb
                  _DBGNotifyDebugged@4
                  _DBGNotifyNewTask@8
                  _DBGNotifyRemoteThreadAddress@8
                  _DispatchInterrupts@0
                  _Dos_Flag_Addr
                  _DpmiSetIncrementalAlloc@4
                  _ExpLdt
                  _FlatAddress
                  _GetDOSAppName@4
                  _InitialVdmDbgFlags
                  _InitialVdmTibFlags
                  _IsCdRomFile@4
                  _MGetVdmPointer@12
                  _RedirectLongFileName@12
                  _RedirectShortFileName@12
                  _RegisterWOWIdle@0
                  _ResumeTimerThread@0
                  _SelectorLimit
                  _SetShadowDescriptorEntries@8
                  _ShortPathEnvVar@4
                  _Sim32pGetVDMPointer@8
                  _SoftPcEoi@8
                  _SuspendTimerThread@0
                  _VDDAllocMem@12
                  _VDDAllocateDosHandle@12
                  _VDDAssociateNtHandle@12
                  _VDDDeInstallIOHook@12
                  _VDDDeInstallMemoryHook@12
                  _VDDDeInstallUserHook@4
                  _VDDExcludeMem@12
                  _VDDFreeMem@12
                  _VDDIncludeMem@12
                  _VDDInstallIOHook@16
                  _VDDInstallMemoryHook@16
                  _VDDInstallUserHook@20
                  _VDDQueryDMA@12
                  _VDDReleaseDosHandle@8
                  _VDDReleaseIrqLine@8
                  _VDDRequestDMA@16
                  _VDDReserveIrqLine@8
                  _VDDRetrieveNtHandle@16
                  _VDDSetDMA@16
                  _VDDSimulate16@0
                  _VDDTerminateVDM@0
                  _VdmDbgAttach@0
                  _VdmGetParametersInfoError@0
                  _VdmMapFlat@12
                  _VdmParametersInfo@12
                  _VdmTraceEvent@12
                  _WOWSysErrorBox@20
                  _WaitIfIdle@0
                  _call_ica_hw_interrupt@12
                  _cmdCheckTemp@4
                  _cmdCheckTempInit@0
                  _cpu_createthread@8
                  _demClientErrorEx@12
                  _demFileDelete@4
                  _demFileFindFirst@12
                  _demFileFindNext@4
                  _demGetFileTimeByHandle_WOW@4
                  _demGetPhysicalDriveType@4
                  _demIsShortPathName@8
                  _demLFNCleanup@0
                  _demLFNGetCurrentDirectory@8
                  _demSetCurrentDirectoryGetDrive@8
                  _demWOWLFNAllocateSearchHandle@4
                  _demWOWLFNCloseSearchHandle@4
                  _demWOWLFNEntry@4
                  _demWOWLFNGetSearchHandle@4
                  _demWOWLFNInit@4
                  _fSeparateWow
                  _getAF@0
                  _getAH@0
                  _getAL@0
                  _getAX@0
                  _getBH@0
                  _getBL@0
                  _getBP@0
                  _getBX@0
                  _getCF@0
                  _getCH@0
                  _getCL@0
                  _getCS@0
                  _getCX@0
                  _getDF@0
                  _getDH@0
                  _getDI@0
                  _getDL@0
                  _getDS@0
                  _getDX@0
                  _getEAX@0
                  _getEBP@0
                  _getEBX@0
                  _getECX@0
                  _getEDI@0
                  _getEDX@0
                  _getEFLAGS@0
                  _getEIP@0
                  _getES@0
                  _getESI@0
                  _getESP@0
                  _getFS@0
                  _getGS@0
                  _getIF@0
                  _getIP@0
                  _getIntelRegistersPointer@0
                  _getMSW@0
                  _getOF@0
                  _getPF@0
                  _getSF@0
                  _getSI@0
                  _getSP@0
                  _getSS@0
                  _getZF@0
                  _host_CreateThread@24
                  _host_ExitThread@4
                  _host_com_close@4
                  _host_direct_access_error@4
                  _host_simulate@0
                  _pDeviceChain
                  _setAF@4
                  _setAH@4
                  _setAL@4
                  _setAX@4
                  _setBH@4
                  _setBL@4
                  _setBP@4
                  _setBX@4
                  _setCF@4
                  _setCH@4
                  _setCL@4
                  _setCS@4
                  _setCX@4
                  _setDF@4
                  _setDH@4
                  _setDI@4
                  _setDL@4
                  _setDS@4
                  _setDX@4
                  _setEAX@4
                  _setEBP@4
                  _setEBX@4
                  _setECX@4
                  _setEDI@4
                  _setEDX@4
                  _setEFLAGS@4
                  _setEIP@4
                  _setES@4
                  _setESI@4
                  _setESP@4
                  _setFS@4
                  _setGS@4
                  _setIF@4
                  _setIP@4
                  _setMSW@4
                  _setOF@4
                  _setPF@4
                  _setSF@4
                  _setSI@4
                  _setSP@4
                  _setSS@4
                  _setZF@4

  Summary

          BD .debug$S
          14 .idata$2
          14 .idata$3
           4 .idata$4
           4 .idata$5
           A .idata$6
</code>```

The function definition I'm trying to call in VDDSVC.h is:

```<code>#define GetVDMPointer(Address, Size, Mode) Sim32GetVDMPointer(\
                        Address, Size, Mode)
</code>```

However visual studio error is:

```<code>Error   LNK2019 unresolved external symbol _MGetVdmPointer referenced in function _VddDispatch
</code>```

_MGetVdmPointer is in the lib file but referenced as _MGetVdmPointer@12

I reviewed the options here but couldn't determine which one might apply in my scenario https://learn.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-error-lnk2019?view=msvc-170

In Linker -> General -> Show Progress I tried setting /VERBOSE although no additional information was generated in the logs

I tried changing calling convention to "__stdcall" in C/C++ -> Advanced Calling Convention

I've tried changing files from .C to .CPP although get similar error (Although the symbol looked for is a c++ mangled style name)

答:
The issue was calling convention needs to be modified to "__stdcall" in C/C++ -> Advanced Calling Convention

Which I had tried, however Visual Studio 2019 project properties was defaulting to configuration for "Release" build and not the current build type "Debug(Active)" which effectively made my initial change of that setting ineffective.

As suggested in comments by IInspectable:

When changing global project properties, always make sure the "Configuration" is set to "All Configurations" and "Platform" is set to "All Platforms"

Body:
I am trying to call functions from ntvdm.lib in Visual Studio 2019 using the Visual Studio 2017 - Windows XP (v141_XP) platform toolset, with the following defined:

#define _WIN32_WINNT 0x0501
#define i386

running dumpbin /exports on the LIB file I get the following output:

Microsoft (R) COFF/PE Dumper Version 14.29.30037.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Dump of file ntvdm.lib

File Type: LIBRARY

     Exports

       ordinal    name

                  _BlockWOWIdle@4
                  _CurrentMonitorTeb
                  _DBGNotifyDebugged@4
                  _DBGNotifyNewTask@8
                  _DBGNotifyRemoteThreadAddress@8
                  _DispatchInterrupts@0
                  _Dos_Flag_Addr
                  _DpmiSetIncrementalAlloc@4
                  _ExpLdt
                  _FlatAddress
                  _GetDOSAppName@4
                  _InitialVdmDbgFlags
                  _InitialVdmTibFlags
                  _IsCdRomFile@4
                  _MGetVdmPointer@12
                  _RedirectLongFileName@12
                  _RedirectShortFileName@12
                  _RegisterWOWIdle@0
                  _ResumeTimerThread@0
                  _SelectorLimit
                  _SetShadowDescriptorEntries@8
                  _ShortPathEnvVar@4
                  _Sim32pGetVDMPointer@8
                  _SoftPcEoi@8
                  _SuspendTimerThread@0
                  _VDDAllocMem@12
                  _VDDAllocateDosHandle@12
                  _VDDAssociateNtHandle@12
                  _VDDDeInstallIOHook@12
                  _VDDDeInstallMemoryHook@12
                  _VDDDeInstallUserHook@4
                  _VDDExcludeMem@12
                  _VDDFreeMem@12
                  _VDDIncludeMem@12
                  _VDDInstallIOHook@16
                  _VDDInstallMemoryHook@16
                  _VDDInstallUserHook@20
                  _VDDQueryDMA@12
                  _VDDReleaseDosHandle@8
                  _VDDReleaseIrqLine@8
                  _VDDRequestDMA@16
                  _VDDReserveIrqLine@8
                  _VDDRetrieveNtHandle@16
                  _VDDSetDMA@16
                  _VDDSimulate16@0
                  _VDDTerminateVDM@0
                  _VdmDbgAttach@0
                  _VdmGetParametersInfoError@0
                  _VdmMapFlat@12
                  _VdmParametersInfo@12
                  _VdmTraceEvent@12
                  _WOWSysErrorBox@20
                  _WaitIfIdle@0
                  _call_ica_hw_interrupt@12
                  _cmdCheckTemp@4
                  _cmdCheckTempInit@0
                  _cpu_createthread@8
                  _demClientErrorEx@12
                  _demFileDelete@4
                  _demFileFindFirst@12
                  _demFileFindNext@4
                  _demGetFileTimeByHandle_WOW@4
                  _demGetPhysicalDriveType@4
                  _demIsShortPathName@8
                  _demLFNCleanup@0
                  _demLFNGetCurrentDirectory@8
                  _demSetCurrentDirectoryGetDrive@8
                  _demWOWLFNAllocateSearchHandle@4
                  _demWOWLFNCloseSearchHandle@4
                  _demWOWLFNEntry@4
                  _demWOWLFNGetSearchHandle@4
                  _demWOWLFNInit@4
                  _fSeparateWow
                  _getAF@0
                  _getAH@0
                  _getAL@0
                  _getAX@0
                  _getBH@0
                  _getBL@0
                  _getBP@0
                  _getBX@0
                  _getCF@0
                  _getCH@0
                  _getCL@0
                  _getCS@0
                  _getCX@0
                  _getDF@0
                  _getDH@0
                  _getDI@0
                  _getDL@0
                  _getDS@0
                  _getDX@0
                  _getEAX@0
                  _getEBP@0
                  _getEBX@0
                  _getECX@0
                  _getEDI@0
                  _getEDX@0
                  _getEFLAGS@0
                  _getEIP@0
                  _getES@0
                  _getESI@0
                  _getESP@0
                  _getFS@0
                  _getGS@0
                  _getIF@0
                  _getIP@0
                  _getIntelRegistersPointer@0
                  _getMSW@0
                  _getOF@0
                  _getPF@0
                  _getSF@0
                  _getSI@0
                  _getSP@0
                  _getSS@0
                  _getZF@0
                  _host_CreateThread@24
                  _host_ExitThread@4
                  _host_com_close@4
                  _host_direct_access_error@4
                  _host_simulate@0
                  _pDeviceChain
                  _setAF@4
                  _setAH@4
                  _setAL@4
                  _setAX@4
                  _setBH@4
                  _setBL@4
                  _setBP@4
                  _setBX@4
                  _setCF@4
                  _setCH@4
                  _setCL@4
                  _setCS@4
                  _setCX@4
                  _setDF@4
                  _setDH@4
                  _setDI@4
                  _setDL@4
                  _setDS@4
                  _setDX@4
                  _setEAX@4
                  _setEBP@4
                  _setEBX@4
                  _setECX@4
                  _setEDI@4
                  _setEDX@4
                  _setEFLAGS@4
                  _setEIP@4
                  _setES@4
                  _setESI@4
                  _setESP@4
                  _setFS@4
                  _setGS@4
                  _setIF@4
                  _setIP@4
                  _setMSW@4
                  _setOF@4
                  _setPF@4
                  _setSF@4
                  _setSI@4
                  _setSP@4
                  _setSS@4
                  _setZF@4

  Summary

          BD .debug$S
          14 .idata$2
          14 .idata$3
           4 .idata$4
           4 .idata$5
           A .idata$6

The function definition I'm trying to call in VDDSVC.h is:

#define GetVDMPointer(Address, Size, Mode) Sim32GetVDMPointer(\
                        Address, Size, Mode)

However visual studio error is:

Error   LNK2019 unresolved external symbol _MGetVdmPointer referenced in function _VddDispatch

_MGetVdmPointer is in the lib file but referenced as _MGetVdmPointer@12

I reviewed the options here but couldn't determine which one might apply in my scenario https://learn.microsoft.com/en-us/cpp/error-messages/tool-errors/linker-tools-error-lnk2019?view=msvc-170

In Linker -> General -> Show Progress I tried setting /VERBOSE although no additional information was generated in the logs

I tried changing calling convention to "__stdcall" in C/C++ -> Advanced Calling Convention

I've tried changing files from .C to .CPP although get similar error (Although the symbol looked for is a c++ mangled style name)


问:
How extract all the json content as a attribute in NiFi
I have some flowfiles and their contents are json like this:

```<code>{"Message": "...", "Id":"122", "Size":"123"}
</code>```

I would like to extract this whole json as an attribute in flowfile.

How to achieve it?

答: Use ExtractText processor and add a new property as ff_content = (.*)

Body:
I have some flowfiles and their contents are json like this:

{"Message": "...", "Id":"122", "Size":"123"}

I would like to extract this whole json as an attribute in flowfile.

How to achieve it?


问:
write a bash script to organize files by their type
Given a directory with these files for example.

```<code>bike.png
car.jpg
comedy.mov
error.log
horror.avi
info.txt
interview.mp3
song.flac
tree-small.jpeg
11.10.2017_y
some-directory
nested-file.log
</code>```

I am trying to write a bash script that would create 3 folders "Music, Videos, Images" and organize these files into their type folder and deletes .log files.

Music is all flac/mp3 files, Images are jpeg/png files, and Videos are all avi/mov files.

The final directory structure should look like this.

```<code>images/
     bike.png
     car.jpg
music/
     interview.mp3
     song.flac
videos/
     comedy.mov
     horror.avi
info.txt
tree-small.jpeg
11.10.2017_y
some-directory/
     nested-file.log
</code>```

答:
Wouldn't this do it?

#!/bin/sh

mkdir music videos images
mv *.flac *.mp3 music/
mv *.jpeg *.png images/
mv *.avi *.mov videos/
rm *.log
```

Body:
Given a directory with these files for example.

bike.png
car.jpg
comedy.mov
error.log
horror.avi
info.txt
interview.mp3
song.flac
tree-small.jpeg
11.10.2017_y
some-directory
nested-file.log

I am trying to write a bash script that would create 3 folders "Music, Videos, Images" and organize these files into their type folder and deletes .log files.

Music is all flac/mp3 files, Images are jpeg/png files, and Videos are all avi/mov files.

The final directory structure should look like this.

images/
     bike.png
     car.jpg
music/
     interview.mp3
     song.flac
videos/
     comedy.mov
     horror.avi
info.txt
tree-small.jpeg
11.10.2017_y
some-directory/
     nested-file.log


问:
Waiting for Query Params before Sending Api Call
Trying to use some url parameters in an API call. Eventually my plan is to allow the user to put in a Zip Code and I will transform the zip code into latitude and longitude. This is intended to be a digital signage solution where the user can set up a URL in their signage system and include their location as part of the url.

Here's what I have for my created function in Vue. Admittedly, I am both a novice at Vue and still trying to fully understand async await. I thought that I did, but this is inconsistently not waiting for the latitude and longitude params from the query before sending the API call.

```<code>async created() {
    const lat = await this.$route.query.lat;
    const lon = await this.$route.query.lon;
    try {
      const response = await axios.get(
          'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
          { headers: {"Content-Type": "application/json"} }
      )
      this.weather = response.data
    } catch (err) {
        console.log(err.toJSON());
    }
  }
</code>```

Current Updated code using setup

```<code>setup() {
    const route = useRoute();
    let lat = ref(0);
    let lon = ref(0);
    let weather = ref(null);

    watchEffect(() => {
      lat.value = route.query.lat;
      console.log(lat.value);
      lon.value = route.query.lon;
      console.log(lon.value);

      axios.get(
        'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat.value + '&lon=' + lon.value + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
        { headers: {"Content-Type": "application/json"} }
      ).then( response => {
        weather.value = response.data;
        console.log(weather);
      }).catch(e => {
        console.log(e);
      });
    });

    return {
      lat, lon, weather
    }
  },
</code>```

答:
I would recommend doing this in either the watch function (both in the options and the composition API) or a watchEffect (only in the composition API), the latter is less complicated. It just listens to changes on reactive properties.

```<code><script setup>
import { useRoute } from 'vue-router';
import { ref, watchEffect } from 'vue';

const route = useRoute();

const lat = ref(0);
const long = ref(0);

watchEffect(() => {
  lat.value = route.query.lat;
  lng.value = route.query.lng;
});
</script>
</code>```

You will need to better safeguard the assignments!

Body:
Trying to use some url parameters in an API call. Eventually my plan is to allow the user to put in a Zip Code and I will transform the zip code into latitude and longitude. This is intended to be a digital signage solution where the user can set up a URL in their signage system and include their location as part of the url.

Here's what I have for my created function in Vue. Admittedly, I am both a novice at Vue and still trying to fully understand async await. I thought that I did, but this is inconsistently not waiting for the latitude and longitude params from the query before sending the API call.

async created() {
    const lat = await this.$route.query.lat;
    const lon = await this.$route.query.lon;
    try {
      const response = await axios.get(
          'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
          { headers: {"Content-Type": "application/json"} }
      )
      this.weather = response.data
    } catch (err) {
        console.log(err.toJSON());
    }
  }

Current Updated code using setup

setup() {
    const route = useRoute();
    let lat = ref(0);
    let lon = ref(0);
    let weather = ref(null);

    watchEffect(() => {
      lat.value = route.query.lat;
      console.log(lat.value);
      lon.value = route.query.lon;
      console.log(lon.value);

      axios.get(
        'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat.value + '&lon=' + lon.value + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
        { headers: {"Content-Type": "application/json"} }
      ).then( response => {
        weather.value = response.data;
        console.log(weather);
      }).catch(e => {
        console.log(e);
      });
    });

    return {
      lat, lon, weather
    }
  },

Body:
I would recommend doing this in either the watch function (both in the options and the composition API) or a watchEffect (only in the composition API), the latter is less complicated. It just listens to changes on reactive properties.

<script setup>
import { useRoute } from 'vue-router';
import { ref, watchEffect } from 'vue';

const route = useRoute();

const lat = ref(0);
const long = ref(0);

watchEffect(() => {
  lat.value = route.query.lat;
  lng.value = route.query.lng;
});
</script>

You will need to better safeguard the assignments!


问:
Pass data to custom stateful widget and return validation staus form
I have created a custom stateful widget. I need to use this same widget multiple times in a form. The their are several different forms accessing the same widget. In order to avoid code duplication I extracted the widget

The only thing that changes in the widget is its label (e.g. Instrument Clean), the hint for the TextFormField (e.g. Instrument clean remark) and the TextEdittingController.

The TextFormField is only writable when Not Okay is selected.
Proper validation have been implemented for the same.

My question is how to send label text, hint text and TextEdittingController to this custom Widget and at the same time how to return validation return status to main form.

Code :

```<code>class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  const ToogleRemarkWidget({required this.textController, Key? key})
      : super(key: key);
  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Expanded(
          flex: 2,
          child: Text('Instrument Clean : '),
        ),
        Expanded(
          flex: 3,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  _textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: _textController,
            decoration: const InputDecoration(
              icon: Icon(Icons.note_add),
              label: Text('Instrument Clean Remark'),
              hintText: 'Enter Instrument Clean Remark',
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter Instrument Cleaned By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}
</code>```

答:
You need to add the fields to your Stateful Widget and then add a callback function I believe. It should look similar to this. Let me know if this works for you:

```<code>import 'package:flutter/material.dart';
class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  final String label_text;
  final String hint_text;
  final Function(String) callback; // Assuming it is a string
  const ToogleRemarkWidget(
      {required this.textController,
      Key? key,
      required this.label_text,
      required this.hint_text,
      required this.callback})
      : super(key: key);
    @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}
</code>```

To create one I believe it should be like this:

```<code>ToogleRemarkWidget(textController: textController, label_text:'label text', hint_text: 'hint text', callback: callbackFunction);
</code>```

Body:
I have created a custom stateful widget. I need to use this same widget multiple times in a form. The their are several different forms accessing the same widget. In order to avoid code duplication I extracted the widget

The only thing that changes in the widget is its label (e.g. Instrument Clean), the hint for the TextFormField (e.g. Instrument clean remark) and the TextEdittingController.

The TextFormField is only writable when Not Okay is selected.
Proper validation have been implemented for the same.

My question is how to send label text, hint text and TextEdittingController to this custom Widget and at the same time how to return validation return status to main form.

Code :

class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  const ToogleRemarkWidget({required this.textController, Key? key})
      : super(key: key);
  @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

class _ToogleRemarkWidgetState extends State<ToogleRemarkWidget> {
  final TextEditingController _textController = TextEditingController();
  int _toggleIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.max,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Expanded(
          flex: 2,
          child: Text('Instrument Clean : '),
        ),
        Expanded(
          flex: 3,
          child: Center(
            child: ToggleSwitch(
              totalSwitches: 2,
              initialLabelIndex: _toggleIndex,
              labels: const ['Okay', 'Not Okay'],
              //TODO Change Okay Icon
              activeBgColors: const [
                [Colors.green],
                [Colors.red]
              ],
              minWidth: 100.0,
              animate: true,
              onToggle: (index) {
                if (index == 0) {
                  _textController.clear();
                }
                setState(() {
                  _toggleIndex = index;
                });
              },
              cornerRadius: 20.0,
            ),
          ),
        ),
        Expanded(
          flex: 5,
          child: TextFormField(
            enabled: _toggleIndex == 0 ? false : true,
            controller: _textController,
            decoration: const InputDecoration(
              icon: Icon(Icons.note_add),
              label: Text('Instrument Clean Remark'),
              hintText: 'Enter Instrument Clean Remark',
              border: OutlineInputBorder(),
            ),
            validator: (value) {
              if (_toggleIndex == 1 && (value == null || value.isEmpty)) {
                return 'Please enter Instrument Cleaned By'; //Validation error
              }
              return null; //Validation Success
            },
          ),
        ),
      ],
    );
  }
}

Body:
You need to add the fields to your Stateful Widget and then add a callback function I believe. It should look similar to this. Let me know if this works for you:

import 'package:flutter/material.dart';
class ToogleRemarkWidget extends StatefulWidget {
  final TextEditingController textController;
  final String label_text;
  final String hint_text;
  final Function(String) callback; // Assuming it is a string
  const ToogleRemarkWidget(
      {required this.textController,
      Key? key,
      required this.label_text,
      required this.hint_text,
      required this.callback})
      : super(key: key);
    @override
  State<ToogleRemarkWidget> createState() => _ToogleRemarkWidgetState();
}

To create one I believe it should be like this:

ToogleRemarkWidget(textController: textController, label_text:'label text', hint_text: 'hint text', callback: callbackFunction);