问:
System.Text.JSON doesn't deserialize what Newtonsoft does
I have a json that the new System.Text.Json.JsonSerializer.Deserialize<T>(json_data) serialize as List<T> with the correct numbers of elements, but then the objects inside have all the values null or 0

Same json with Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json_data) is correctly filled.

Class:

```<code>public class SensorValue
    {
        public string StationCode { get; set; }
        public string SensorCode { get; set; }
        public string SensorNameIt { get; set; }
        public string SensorNameDe { get; set; }
        public string SensorNameLd { get; set; }
        public string SensorUnitMeasure { get; set; }
        public DateTime SamplingDateTime { get; set; }
        public Decimal SamplingValue { get; set; }
    }
</code>```

JSON

```<code>[{"stationCode":"89190MS","sensorCode":"LT","sensorNameIt":"Temperatura dell´aria","sensorNameDe":"Lufttemperatur","sensorNameLd":"Temperatura dl’aria","sensorUnitMeasure":"°C","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.3},{"stationCode":"89190MS","sensorCode":"N","sensorNameIt":"Precipitazioni","sensorNameDe":"Niederschlag","sensorNameLd":"plueia","sensorUnitMeasure":"mm","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.4},{"stationCode":"89190MS","sensorCode":"WR","sensorNameIt":"Direzione del vento","sensorNameDe":"Windrichtung","sensorNameLd":"Direzion dl vënt","sensorUnitMeasure":"° ","samplingDateTime":"2019-11-15T15:10:00","samplingValue":165.7},{"stationCode":"89190MS","sensorCode":"WG","sensorNameIt":"Velocità del vento","sensorNameDe":"Windgeschwindigkeit","sensorNameLd":"Slune dl vënt","sensorUnitMeasure":"m/s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.7},{"stationCode":"89190MS","sensorCode":"WG.BOE","sensorNameIt":"Velocitá raffica","sensorNameDe":"Windgeschwindigkeit Böe","sensorNameLd":"Slune dl vënt","sensorUnitMeasure":"m/s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":1.3},{"stationCode":"89190MS","sensorCode":"LF","sensorNameIt":"Umidità relativa","sensorNameDe":"relative Luftfeuchte","sensorNameLd":"Tume relatif","sensorUnitMeasure":"%","samplingDateTime":"2019-11-15T15:10:00","samplingValue":100.0},{"stationCode":"89190MS","sensorCode":"LD.RED","sensorNameIt":"Pressione atmosferica","sensorNameDe":"Luftdruck","sensorNameLd":"Druch dl’aria","sensorUnitMeasure":"hPa","samplingDateTime":"2019-11-15T15:10:00","samplingValue":1006.9},{"stationCode":"89190MS","sensorCode":"GS","sensorNameIt":"Radiazione globale ","sensorNameDe":"Globalstrahlung","sensorNameLd":"Nraiazion globala ","sensorUnitMeasure":"W/m²","samplingDateTime":"2019-11-15T15:10:00","samplingValue":3.8},{"stationCode":"89190MS","sensorCode":"SD","sensorNameIt":"Durata soleggiamento","sensorNameDe":"Sonnenscheindauer","sensorNameLd":"Dureda dl surëdl","sensorUnitMeasure":"s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.0}]
</code>```

Any help ?
consoleapp project .net core 3.0.0
newtonsoft 12.0.3

答: I had a problem getting default values instead of real ones. When I forgot to add an identifier to the properties of the model in the current project (set). Prior to using serialization/deserialization, only the identifier (get) was required for properties in the model. But for me both libraries (System.Text.Json and NewtonSoft )returned the default value. This is not the case of the topic starter.

Body:
I have a json that the new System.Text.Json.JsonSerializer.Deserialize<T>(json_data) serialize as List<T> with the correct numbers of elements, but then the objects inside have all the values null or 0

Same json with Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json_data) is correctly filled.

Class:

public class SensorValue
    {
        public string StationCode { get; set; }
        public string SensorCode { get; set; }
        public string SensorNameIt { get; set; }
        public string SensorNameDe { get; set; }
        public string SensorNameLd { get; set; }
        public string SensorUnitMeasure { get; set; }
        public DateTime SamplingDateTime { get; set; }
        public Decimal SamplingValue { get; set; }
    }

JSON

[{"stationCode":"89190MS","sensorCode":"LT","sensorNameIt":"Temperatura dell´aria","sensorNameDe":"Lufttemperatur","sensorNameLd":"Temperatura dl’aria","sensorUnitMeasure":"°C","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.3},{"stationCode":"89190MS","sensorCode":"N","sensorNameIt":"Precipitazioni","sensorNameDe":"Niederschlag","sensorNameLd":"plueia","sensorUnitMeasure":"mm","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.4},{"stationCode":"89190MS","sensorCode":"WR","sensorNameIt":"Direzione del vento","sensorNameDe":"Windrichtung","sensorNameLd":"Direzion dl vënt","sensorUnitMeasure":"° ","samplingDateTime":"2019-11-15T15:10:00","samplingValue":165.7},{"stationCode":"89190MS","sensorCode":"WG","sensorNameIt":"Velocità del vento","sensorNameDe":"Windgeschwindigkeit","sensorNameLd":"Slune dl vënt","sensorUnitMeasure":"m/s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.7},{"stationCode":"89190MS","sensorCode":"WG.BOE","sensorNameIt":"Velocitá raffica","sensorNameDe":"Windgeschwindigkeit Böe","sensorNameLd":"Slune dl vënt","sensorUnitMeasure":"m/s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":1.3},{"stationCode":"89190MS","sensorCode":"LF","sensorNameIt":"Umidità relativa","sensorNameDe":"relative Luftfeuchte","sensorNameLd":"Tume relatif","sensorUnitMeasure":"%","samplingDateTime":"2019-11-15T15:10:00","samplingValue":100.0},{"stationCode":"89190MS","sensorCode":"LD.RED","sensorNameIt":"Pressione atmosferica","sensorNameDe":"Luftdruck","sensorNameLd":"Druch dl’aria","sensorUnitMeasure":"hPa","samplingDateTime":"2019-11-15T15:10:00","samplingValue":1006.9},{"stationCode":"89190MS","sensorCode":"GS","sensorNameIt":"Radiazione globale ","sensorNameDe":"Globalstrahlung","sensorNameLd":"Nraiazion globala ","sensorUnitMeasure":"W/m²","samplingDateTime":"2019-11-15T15:10:00","samplingValue":3.8},{"stationCode":"89190MS","sensorCode":"SD","sensorNameIt":"Durata soleggiamento","sensorNameDe":"Sonnenscheindauer","sensorNameLd":"Dureda dl surëdl","sensorUnitMeasure":"s","samplingDateTime":"2019-11-15T15:10:00","samplingValue":0.0}]

Any help ?
consoleapp project .net core 3.0.0
newtonsoft 12.0.3


来源: stackexchange

问:
Because app requires SDK version >=2.15.1 <3.0.0, version solving failed
Can anyone tell me why am I getting this error?

```<code>The current Dart SDK version is 2.12.0.

Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.
pub get failed (1; Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.)
</code>```

here is my flutter --version

```<code>Flutter 2.10.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision db747aa133 (2 days ago) • 2022-02-09 13:57:35 -0600
Engine • revision ab46186b24
Tools • Dart 2.16.1 • DevTools 2.9.2

</code>```

答:
You should not update the dart version of this project, please open pubspec.yaml file and update

environment:
sdk: ">=2.12.0 <3.0.0"

to

environment:
sdk: ">=2.16.0 <3.0.0"

ContentLicense: CC BY-SA 4.0

Body:
Can anyone tell me why am I getting this error?

The current Dart SDK version is 2.12.0.

Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.
pub get failed (1; Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.)

here is my flutter --version

Flutter 2.10.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision db747aa133 (2 days ago) • 2022-02-09 13:57:35 -0600
Engine • revision ab46186b24
Tools • Dart 2.16.1 • DevTools 2.9.2


问:
Yocto Service Not Starting
It took me a long time to get here. I have a custom application saved in GitLab and building in my VM. I am trying to add my application to my Linux build and start it as a service. My issue is the service is not starting and I cannot find my code on the target device.

In my applicaiton.bb I have the following line, I can confirm the application is being built when I use bitbake.

```<code>IMAGE_INSTALL_append = " helloworld "
</code>```

My folder layout for the custom layer application is as follows.

I have updated my application bb file to include the service folder and files. The service file is very basic.

```<code> LICENSE = "MIT"
    LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

    FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

    SRC_URI = "file://src \
          file://src/app \
          "

    SRC_URI += "file://helloworld.service \
            "

    S = "${WORKDIR}/src"

    inherit systemd
    SYSTEMD_AUTO_ENABLE = "enable"
    SYSTEMD_SERVICE_${PN} = "helloworld.service"

    SRC_URI_append = " file://helloworld.service "
    FILES_${PN} += "${systemd_unitdir}/system/helloworld.service"

    do_install_append() {
      install -d ${D}/${systemd_unitdir}/system
      install -D -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_unitdir}/system
  sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_unitdir}/helloworld.service
    }
</code>```

Service File

```<code>[Unit]
Description=Example service

[Service]
Type=forking
ExecStart=@BINDIR@/helloworld

[Install]
WantedBy=multi-user.target
</code>```

I have searched GitHub for examples of bb files that have SYSTEMD_AUTO_ENABLE and a service added. They are doing nothing special and I am confused as to why my service does not start, or appear on my device.

Update:
The code is on the device but was installed in /lib/systemd/system/helloworld.service

The service file is looking for it in ExecStart=/usr/bin/helloworld
This looks like an easy fix and I will update!

Update 2:
I added the SED command which is supposed to copy the file from the systemd folder to the bin folder. I have yet to get this command working correctly.

答:
I finally found the answer!</p>
```<code>LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

SRC_URI = "\
    file://helloworld.service \
    file://helloworld.c \
    "

S = "${WORKDIR}"

inherit systemd
SYSTEMD_AUTO_ENABLE = "enable"
SYSTEMD_SERVICE_${PN} = "helloworld.service"

do_compile () {
    ${CC} ${LDFLAGS} helloworld.c -o helloworld
}

do_install_append() {
  install -d ${D}${bindir}
  install -m 0755 ${WORKDIR}/helloworld ${D}${bindir}

  install -d ${D}${systemd_unitdir}/system
  install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_unitdir}/system
  sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_unitdir}/system/helloworld.service
}
</code>```

Title: Yocto Service Not Starting

Body:
It took me a long time to get here. I have a custom application saved in GitLab and building in my VM. I am trying to add my application to my Linux build and start it as a service. My issue is the service is not starting and I cannot find my code on the target device.

In my applicaiton.bb I have the following line, I can confirm the application is being built when I use bitbake.

IMAGE_INSTALL_append = " helloworld "

My folder layout for the custom layer application is as follows.

I have updated my application bb file to include the service folder and files. The service file is very basic.

 LICENSE = "MIT"
    LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

    FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

    SRC_URI = "file://src \
          file://src/app \
          "

    SRC_URI += "file://helloworld.service \
            "

    S = "${WORKDIR}/src"

    inherit systemd
    SYSTEMD_AUTO_ENABLE = "enable"
    SYSTEMD_SERVICE_${PN} = "helloworld.service"

    SRC_URI_append = " file://helloworld.service "
    FILES_${PN} += "${systemd_unitdir}/system/helloworld.service"

    do_install_append() {
      install -d ${D}/${systemd_unitdir}/system
      install -D -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_unitdir}/system
  sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_unitdir}/helloworld.service
    }

Service File

[Unit]
Description=Example service

[Service]
Type=forking
ExecStart=@BINDIR@/helloworld

[Install]
WantedBy=multi-user.target

I have searched GitHub for examples of bb files that have SYSTEMD_AUTO_ENABLE and a service added. They are doing nothing special and I am confused as to why my service does not start, or appear on my device.

Update:
The code is on the device but was installed in /lib/systemd/system/helloworld.service

The service file is looking for it in ExecStart=/usr/bin/helloworld
This looks like an easy fix and I will update!

Update 2:
I added the SED command which is supposed to copy the file from the systemd folder to the bin folder. I have yet to get this command working correctly.

Body:
I finally found the answer!

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

FILESEXTRAPATHS:prepend := "${THISDIR}/files/src:${THISDIR}/files/src/app:${THISDIR}/files/services:"

SRC_URI = "\
    file://helloworld.service \
    file://helloworld.c \
    "

S = "${WORKDIR}"

inherit systemd
SYSTEMD_AUTO_ENABLE = "enable"
SYSTEMD_SERVICE_${PN} = "helloworld.service"

do_compile () {
    ${CC} ${LDFLAGS} helloworld.c -o helloworld
}

do_install_append() {
  install -d ${D}${bindir}
  install -m 0755 ${WORKDIR}/helloworld ${D}${bindir}

  install -d ${D}${systemd_unitdir}/system
  install -m 0644 ${WORKDIR}/helloworld.service ${D}${systemd_unitdir}/system
  sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_unitdir}/system/helloworld.service
}


问:
The application theme is not saved
I have a code that switches themes. But if I restart the application, the standard theme is set. Help me how to make sure that the theme is saved, which was selected last time.</p>
```<code>class MainActivity : AppCompatActivity(), KodeinAware, SharedPreferences.OnSharedPreferenceChangeListener  {

    override val kodein by closestKodein()
    private val fusedLocationProviderClient: FusedLocationProviderClient by instance()

    private lateinit var binding: ActivityMainBinding

    private val locationCallBack = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult) {
            super.onLocationResult(p0)
        }
    }

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        //setContentView(R.layout.activity_main)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        PreferenceManager.getDefaultSharedPreferences(this)
            .registerOnSharedPreferenceChangeListener(this)

        navController = Navigation.findNavController(this, R.id.nav_host_fragment)

        bottom_nav.setupWithNavController(navController)

        NavigationUI.setupActionBarWithNavController(this,navController)

        if (hasLocationPermission()) {
            bindLocationManager()
        }
        else {
            requestLocationPermission()
        }
        //AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        if (key == "dark_mode"){
            val prefs = sharedPreferences?.getString(key, "1")

            when(prefs?.toInt()){
                1->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                }
                2->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                }
                3->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_TIME)
                }
                4->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
                }
            }
        }
    }
}
This my ListPreference

<ListPreference
            android:key="dark_mode"
            android:title="Темы"
            android:defaultValue="1"
            app:useSimpleSummaryProvider="true"
            android:entries="@array/dark_mode_entries"
            android:entryValues="@array/dark_mode_entries_values"/>
</code>```

答:
Your problem is you only apply the theme in onSharedPreferenceChanged(), which will only be called at the moment when the setting is modified. You should also do this in onCreate so the setting is applied every time the Activity opens. Since you're doing it in two places, you should break it out into a separate function.

I also cleaned your code a bit. Call this function inside onCreate(), and also call it inside onSharedPreferenceChanged() instead of the code you currently have in that function.

```<code>private fun applyDarkModeSetting() {
    val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    val settingValue = sharedPreferences.getString("dark_mode", null)?.toIntOrNull() ?: 1
    val mode = when (settingValue) {
        1 -> AppCompatDelegate.MODE_NIGHT_YES
        2 -> AppCompatDelegate.MODE_NIGHT_NO
        3 -> AppCompatDelegate.MODE_NIGHT_AUTO_TIME
        else -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
    }
    AppCompatDelegate.setDefaultNightMode(mode)
}
</code>```

Title: The application theme is not saved

Body:
I have a code that switches themes. But if I restart the application, the standard theme is set. Help me how to make sure that the theme is saved, which was selected last time.

class MainActivity : AppCompatActivity(), KodeinAware, SharedPreferences.OnSharedPreferenceChangeListener  {

    override val kodein by closestKodein()
    private val fusedLocationProviderClient: FusedLocationProviderClient by instance()

    private lateinit var binding: ActivityMainBinding

    private val locationCallBack = object : LocationCallback() {
        override fun onLocationResult(p0: LocationResult) {
            super.onLocationResult(p0)
        }
    }

    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        //setContentView(R.layout.activity_main)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        PreferenceManager.getDefaultSharedPreferences(this)
            .registerOnSharedPreferenceChangeListener(this)

        navController = Navigation.findNavController(this, R.id.nav_host_fragment)

        bottom_nav.setupWithNavController(navController)

        NavigationUI.setupActionBarWithNavController(this,navController)

        if (hasLocationPermission()) {
            bindLocationManager()
        }
        else {
            requestLocationPermission()
        }
        //AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        if (key == "dark_mode"){
            val prefs = sharedPreferences?.getString(key, "1")

            when(prefs?.toInt()){
                1->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                }
                2->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                }
                3->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_TIME)
                }
                4->{
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
                }
            }
        }
    }
}
This my ListPreference

<ListPreference
            android:key="dark_mode"
            android:title="Темы"
            android:defaultValue="1"
            app:useSimpleSummaryProvider="true"
            android:entries="@array/dark_mode_entries"
            android:entryValues="@array/dark_mode_entries_values"/>

Body:
Your problem is you only apply the theme in onSharedPreferenceChanged(), which will only be called at the moment when the setting is modified. You should also do this in onCreate so the setting is applied every time the Activity opens. Since you're doing it in two places, you should break it out into a separate function.

I also cleaned your code a bit. Call this function inside onCreate(), and also call it inside onSharedPreferenceChanged() instead of the code you currently have in that function.

private fun applyDarkModeSetting() {
    val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    val settingValue = sharedPreferences.getString("dark_mode", null)?.toIntOrNull() ?: 1
    val mode = when (settingValue) {
        1 -> AppCompatDelegate.MODE_NIGHT_YES
        2 -> AppCompatDelegate.MODE_NIGHT_NO
        3 -> AppCompatDelegate.MODE_NIGHT_AUTO_TIME
        else -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
    }
    AppCompatDelegate.setDefaultNightMode(mode)
}


问:
SGE Setting to Slow Down Specific Job
One of the SGE job was running slow and killed by qmaster to enforce the h_rt=1200.

Is that possible SGE admin dynamically change the setting to make the job(id=2771780) running slow? If yes, what could be the setting to do so? If not, what could cause this?

```<code>qname        test.q
hostname     abc
group        domain
owner        jenkins
project      NONE
department   defaultdepartment
jobname      top
jobnumber    2771780
taskid       undefined
account      sge
priority     0
qsub_time    Mon Dec 20 11:46:06 2021
start_time   Mon Dec 20 11:46:07 2021
end_time     Mon Dec 20 12:06:08 2021
granted_pe   NONE
slots        1
failed       37  : qmaster enforced h_rt, h_cpu, or h_vmem limit
exit_status  137                  (Killed)
ru_wallclock 1201s
ru_utime     0.088s
ru_stime     8.797s
ru_maxrss    5.559KB
ru_ixrss     0.000B
ru_ismrss    0.000B
ru_idrss     0.000B
ru_isrss     0.000B
ru_minflt    23574
ru_majflt    0
ru_nswap     0
ru_inblock   128
ru_oublock   240
ru_msgsnd    0
ru_msgrcv    0
ru_nsignals  0
ru_nvcsw     24156
ru_nivcsw    66
cpu          1454.650s
mem          54.658GBs
io           495.010GB
iow          0.000s
maxvmem      1014.082MB
arid         undefined
ar_sub_time  undefined
category     -U arusers,digital -q test.q -l h_rt=1200

</code>```

答: If you are saying that usually the job finishes in 1200s, but ran slowly on this particular occasion, this could be for various external factors such as contention for storage or network bandwidth. You may have also landed on a different compute node type that had slower CPU. An SGE admin can change various resource settings before the job starts executing such as the number of cores, but the more likely issue is contention for storage/io or even throttled cpu for thermal reasons.</p>

Title: SGE Setting to Slow Down Specific Job

Body:
One of the SGE job was running slow and killed by qmaster to enforce the h_rt=1200.

Is that possible SGE admin dynamically change the setting to make the job(id=2771780) running slow? If yes, what could be the setting to do so? If not, what could cause this?

qname        test.q
hostname     abc
group        domain
owner        jenkins
project      NONE
department   defaultdepartment
jobname      top
jobnumber    2771780
taskid       undefined
account      sge
priority     0
qsub_time    Mon Dec 20 11:46:06 2021
start_time   Mon Dec 20 11:46:07 2021
end_time     Mon Dec 20 12:06:08 2021
granted_pe   NONE
slots        1
failed       37  : qmaster enforced h_rt, h_cpu, or h_vmem limit
exit_status  137                  (Killed)
ru_wallclock 1201s
ru_utime     0.088s
ru_stime     8.797s
ru_maxrss    5.559KB
ru_ixrss     0.000B
ru_ismrss    0.000B
ru_idrss     0.000B
ru_isrss     0.000B
ru_minflt    23574
ru_majflt    0
ru_nswap     0
ru_inblock   128
ru_oublock   240
ru_msgsnd    0
ru_msgrcv    0
ru_nsignals  0
ru_nvcsw     24156
ru_nivcsw    66
cpu          1454.650s
mem          54.658GBs
io           495.010GB
iow          0.000s
maxvmem      1014.082MB
arid         undefined
ar_sub_time  undefined
category     -U arusers,digital -q test.q -l h_rt=1200


问:
Updating table based on same table with a max value
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

```<code>update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1
</code>```

But doesn't work, only does the first regid group.

答:
Use a self join in the update statement:

```<code>UPDATE tablename t1
INNER JOIN tablename t2
ON t2.regid = t1.regid AND t2.docid > t1.docid
SET t1.archived = 1;
</code>```

See the demo.

Body:
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1

But doesn't work, only does the first regid group.

Body:
Use a self join in the update statement:

UPDATE tablename t1
INNER JOIN tablename t2
ON t2.regid = t1.regid AND t2.docid > t1.docid
SET t1.archived = 1;

See the demo.


问:
Find file in directory with the max number given a set of different file names
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

```<code>#!/usr/bin/env python

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()
</code>```

答:
Why do you think it is complicated and ugly?

You could use a list comprehension instead of these 3 lines:

    new_list_of_files = []
    # [...]
    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))
```
<p>Like so:</p>
<pre class="lang-py prettyprint-override"><code>new_list_of_files = [max(value) for value in list_of_files.values()]
</code>```

Alternatively you can sort the list of files in reverse, then iterate over the list, adding only the first instance (which will be the highest) of each filename prefix to a new list, using a set to keep track of what filename prefixes have already been added.

files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
files.sort(reverse=True)

already_seen = set()
new_filenames = []
for file in files:
    prefix = file.split("_")[0]
    if prefix not in already_seen:
        already_seen.add(prefix)
        new_filenames.append(file)

print(new_filenames)
```
<p>Output: <code>['FC_2', 'FB_2', 'FA_2']</code></p>
<p>You can get it down to 2 lines with a complicated and ugly list comprehension:</p>
<pre class="lang-py prettyprint-override"><code>files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
already_seen = set()
new_filenames = [(file, already_seen.add(prefix))[0] for file in files[::-1] if (prefix := file.split("_")[0]) not in already_seen]
print(new_filenames)
</code>```

Body:
Problem Description

I have a list of files ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]. That list has 3 different file names FA, FB and FC. For each of FA, FB and FC, I am trying to retrieve the one with the max number.  The following script that I coded does that. But it's so complicated and ugly.

Is there a way to make it simpler?

A similar question was asked in Find file in directory with the highest number in the filename. But, they are only using the same file name.

#!/usr/bin/env python

import sys
import os
from collections import defaultdict

def load_newest_files():
    # Retrieve all files for the component in question
    list_of_files = defaultdict(list)
    new_list_of_files = []
    files = ["FA_1","FA_2","FB_1","FB_2","FC_1","FC_2"]

    # Split files and take the filename without the id.
    # The files are not separated in bucket of FA, FB and FC
    # I can now retrieve the file with the max number and put
    # it in a list
    for file in files:
        list_of_files[file.split("_")[0]].append(file)

    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

    print(new_list_of_files)

def main():
    load_newest_files()

if __name__ == "__main__":
    main()

Body:
Why do you think it is complicated and ugly?

You could use a list comprehension instead of these 3 lines:

    new_list_of_files = []
    # [...]
    for key,value in list_of_files.items():
        new_list_of_files.append(max(value))

Like so:

new_list_of_files = [max(value) for value in list_of_files.values()]

Alternatively you can sort the list of files in reverse, then iterate over the list, adding only the first instance (which will be the highest) of each filename prefix to a new list, using a set to keep track of what filename prefixes have already been added.

files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
files.sort(reverse=True)

already_seen = set()
new_filenames = []
for file in files:
    prefix = file.split("_")[0]
    if prefix not in already_seen:
        already_seen.add(prefix)
        new_filenames.append(file)

print(new_filenames)

Output: ['FC_2', 'FB_2', 'FA_2']

You can get it down to 2 lines with a complicated and ugly list comprehension:

files = ["FA_1", "FA_2", "FB_1", "FB_2", "FC_1", "FC_2"]
already_seen = set()
new_filenames = [(file, already_seen.add(prefix))[0] for file in files[::-1] if (prefix := file.split("_")[0]) not in already_seen]
print(new_filenames)


问:
Template Specialization VS Function Overloading
A textbook I have notes that you can provide your own implementation for standard library functions like swap(x,y) via template specialization or function overloading.  This would be useful for any types which can benefit from something other than an assignment swap, like STL containers for example (which already have swaps written, I know).

My questions are the following:

What's better: template specialization to give your specialized
swap implementation, or function overloading providing the exact
parameters you wish to use without a template?

Why is it better? Or if they're equal, why is this?

答:
You aren't allowed to overload functions in the std namespace, but you are allowed to specialize templates (as I recall), so that's one option.

The other option is to put your swap function in the same namespace as the thing it's operating on and using std::swap; before calling an unqualified swap.

ContentLicense: CC BY-SA 3.0


问:
Postges command exection without password
I want to use rundeck to allow app user to reset their own password without admin access.
So I would like to execute this type of command:

```<code>export PASSFILE=/usr/pgsql-13/.pgpass ; /usr/pgsql-13/bin/psql -h hostname -U postgres -c """alter user ${job.username} PASSWORD '${option.Password}';"""
</code>```

But the script fails because postgres ask for password
Any one have a workaround? The postgres DB is not a classic DB but aws aurora DB, so I don't have access to pg_hba file

Many thanks

答:
The environment valuable is called PGPASSFILE.

An alternative and simpler way is to specify the passfile connection parameter:

/usr/pgsql-13/bin/psql 'host=hostname user=postgres passfile=/usr/pgsql-13/.pgpass' -c "alter user ${job.username} PASSWORD '${option.Password}';"

```

You can also use the password parameter to specify the password in the connect string.

Body:
I want to use rundeck to allow app user to reset their own password without admin access.
So I would like to execute this type of command:

export PASSFILE=/usr/pgsql-13/.pgpass ; /usr/pgsql-13/bin/psql -h hostname -U postgres -c """alter user ${job.username} PASSWORD '${option.Password}';"""

But the script fails because postgres ask for password
Any one have a workaround? The postgres DB is not a classic DB but aws aurora DB, so I don't have access to pg_hba file

Many thanks

Body:
The environment valuable is called PGPASSFILE.

An alternative and simpler way is to specify the passfile connection parameter:

/usr/pgsql-13/bin/psql 'host=hostname user=postgres passfile=/usr/pgsql-13/.pgpass' -c "alter user ${job.username} PASSWORD '${option.Password}';"

You can also use the password parameter to specify the password in the connect string.


问:
How can i refresh form after submit?
i have form like

```<code><form id="abc">
<div>
<select >
<option id= "1"> ha1 </option>
<option id= "1"> ha2 </option>
<option id= "1"> ha3 </option>
<option id= "1"> ha4 </option>
</select>
<input type="submit">
</div>
</form>
</code>```

for form submit i have used like

```<code> $(document).ready(function() {

        $('#abc').submit(function(){

            $.post('filter.php', $(this).serialize(), function(data){

          $('#abc').reset();  //(this).reset();

            });

            return false;

        });

    });
</code>```

Here reset is not working. Any problem with reset i am not getting.
After form submit, i want to refresh form with db values (to display values selected just now).

how can i refresh page after submit or either div refresh.

答:
Reset form fields using Pure JavaScript.

document.getElementById("formid").reset();

Title: How can i refresh form after submit?

Body:
i have form like

<form id="abc">

<select >
<option id= "1"> ha1 </option>
<option id= "1"> ha2 </option>
<option id= "1"> ha3 </option>
<option id= "1"> ha4 </option>
</select>
<input type="submit">

</form>

for form submit i have used like

 $(document).ready(function() {

        $('#abc').submit(function(){

            $.post('filter.php', $(this).serialize(), function(data){

          $('#abc').reset();  //(this).reset();

            });

            return false;

        });

    });

Here reset is not working. Any problem with reset i am not getting.
After form submit, i want to refresh form with db values (to display values selected just now).

how can i refresh page after submit or either div refresh.


问:
MS Graph | PHP | GET Photo - Laravel 404 exception
I'm building a website with Azure authentication using MS Graph.
As you can see below I want to login and get my own data as well as my managers which is working fine, however the issue begins when I want to select the photo.

```<code>$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());

$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
   ->addHeaders(array("Content-Type" => "application/json"))
   ->setReturnType(Model\User::class)
   ->execute();

$photo = $graph->createRequest('GET', '/me/photo/$value')
   ->addHeaders(array("Content-Type" => "image/jpeg"))
   ->execute();

$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
</code>```

When a user does not have a profile photo set it will return a 404 Not Found which is ok, but I don't want my script to stop if there is no photo. What I want is something like this:

```<code>if($photo->getStatus(404)){
     $avatar = null;
}
else{
     $photo = $photo->getRawBody();
     $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}
</code>```

If there is no photo I want to set $avatar to null instead of getting the following error:

Thanks in advance!

FULL FUNCTION

```<code>public function callback(Request $request)
  {
    // Validate state
    $expectedState = session('oauthState');
    $request->session()->forget('oauthState');
    $providedState = $request->query('state');

    if (!isset($expectedState)) {
      // If there is no expected state in the session,
      // do nothing and redirect to the home page.
      return redirect('/');
    }

    if (!isset($providedState) || $expectedState != $providedState) {
      return redirect('/')
        ->with('error', 'Invalid auth state')
        ->with('errorDetail', 'The provided auth state did not match the expected value');
    }

    // Authorization code should be in the "code" query param
    $authCode = $request->query('code');
    if (isset($authCode)) {
      // Initialize the OAuth client
      $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => config('azure.appId'),
        'clientSecret'            => config('azure.appSecret'),
        'redirectUri'             => config('azure.redirectUri'),
        'urlAuthorize'            => config('azure.authority').config('azure.authorizeEndpoint'),
        'urlAccessToken'          => config('azure.authority').config('azure.tokenEndpoint'),
        'urlResourceOwnerDetails' => '',
        'scopes'                  => config('azure.scopes')
      ]);

      try {
        // Make the token request
        $accessToken = $oauthClient->getAccessToken('authorization_code', [
          'code' => $authCode
        ]);

        $graph = new Graph();
        $graph->setAccessToken($accessToken->getToken());

        $user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
          ->addHeaders(array("Content-Type" => "application/json"))
          ->setReturnType(Model\User::class)
          ->execute();

        $photo = $graph->createRequest('GET', '/me/photo/$value')
          ->addHeaders(array("Content-Type" => "image/jpeg"))
          ->execute();
          $photo = $photo->getRawBody();
          $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

        $manager = $user->getManager();

        $tokenCache = new TokenCache();
        $tokenCache->storeTokens($accessToken, $user, $manager, $avatar);

        // Define user details and manager details
        $userFirstName = $user->getGivenName();
        $userSurname = $user->getSurname();
        $userEmail = $user->getMail();

        $managerFirstName = $manager->getGivenName();
        $managerSurname = $manager->getSurname();
        $managerEmail = $manager->getMail();

        return redirect('/');
      }
      catch (Exception $e) {
        $avatar = null;
        return redirect('/')
          ->with('error', 'Error requesting access token')
          ->with('errorDetail', json_encode($e->getResponseBody()));
      }
    }

    return redirect('/')
      ->with('error', $request->query('error'))
      ->with('errorDetail', $request->query('error_description'));
  }
</code>```

答:
Please use the try/catch block. This serves the purpose of handling errors at your end rather than the server handling them for you.

Also I have noticed '/me/photo/$value' this will not replace $value using single quotes properly. Please use double quotes here "/me/photo/$value".

```<code>use Exception; //import right after namespace
try {
    $photo = $graph->createRequest('GET', '/me/photo/$value')
       ->addHeaders(array("Content-Type" => "image/jpeg"))
       ->execute();
    $photo = $photo->getRawBody();
    $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
} catch (Exception $e) {
    //in-case of error
    $avatar = null;
}
</code>```

Body:
I'm building a website with Azure authentication using MS Graph.
As you can see below I want to login and get my own data as well as my managers which is working fine, however the issue begins when I want to select the photo.

$graph = new Graph();
$graph->setAccessToken($accessToken->getToken());

$user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
   ->addHeaders(array("Content-Type" => "application/json"))
   ->setReturnType(Model\User::class)
   ->execute();

$photo = $graph->createRequest('GET', '/me/photo/$value')
   ->addHeaders(array("Content-Type" => "image/jpeg"))
   ->execute();

$photo = $photo->getRawBody();
$avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

When a user does not have a profile photo set it will return a 404 Not Found which is ok, but I don't want my script to stop if there is no photo. What I want is something like this:

if($photo->getStatus(404)){
     $avatar = null;
}
else{
     $photo = $photo->getRawBody();
     $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
}

If there is no photo I want to set $avatar to null instead of getting the following error:

Thanks in advance!

FULL FUNCTION

public function callback(Request $request)
  {
    // Validate state
    $expectedState = session('oauthState');
    $request->session()->forget('oauthState');
    $providedState = $request->query('state');

    if (!isset($expectedState)) {
      // If there is no expected state in the session,
      // do nothing and redirect to the home page.
      return redirect('/');
    }

    if (!isset($providedState) || $expectedState != $providedState) {
      return redirect('/')
        ->with('error', 'Invalid auth state')
        ->with('errorDetail', 'The provided auth state did not match the expected value');
    }

    // Authorization code should be in the "code" query param
    $authCode = $request->query('code');
    if (isset($authCode)) {
      // Initialize the OAuth client
      $oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
        'clientId'                => config('azure.appId'),
        'clientSecret'            => config('azure.appSecret'),
        'redirectUri'             => config('azure.redirectUri'),
        'urlAuthorize'            => config('azure.authority').config('azure.authorizeEndpoint'),
        'urlAccessToken'          => config('azure.authority').config('azure.tokenEndpoint'),
        'urlResourceOwnerDetails' => '',
        'scopes'                  => config('azure.scopes')
      ]);

      try {
        // Make the token request
        $accessToken = $oauthClient->getAccessToken('authorization_code', [
          'code' => $authCode
        ]);

        $graph = new Graph();
        $graph->setAccessToken($accessToken->getToken());

        $user = $graph->createRequest('GET', '/me?$expand=manager($levels=1;$select=displayName,givenName,surname,mail)&$select=displayName,givenName,surname,mail&$count=true')
          ->addHeaders(array("Content-Type" => "application/json"))
          ->setReturnType(Model\User::class)
          ->execute();

        $photo = $graph->createRequest('GET', '/me/photo/$value')
          ->addHeaders(array("Content-Type" => "image/jpeg"))
          ->execute();
          $photo = $photo->getRawBody();
          $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';

        $manager = $user->getManager();

        $tokenCache = new TokenCache();
        $tokenCache->storeTokens($accessToken, $user, $manager, $avatar);

        // Define user details and manager details
        $userFirstName = $user->getGivenName();
        $userSurname = $user->getSurname();
        $userEmail = $user->getMail();

        $managerFirstName = $manager->getGivenName();
        $managerSurname = $manager->getSurname();
        $managerEmail = $manager->getMail();

        return redirect('/');
      }
      catch (Exception $e) {
        $avatar = null;
        return redirect('/')
          ->with('error', 'Error requesting access token')
          ->with('errorDetail', json_encode($e->getResponseBody()));
      }
    }

    return redirect('/')
      ->with('error', $request->query('error'))
      ->with('errorDetail', $request->query('error_description'));
  }

Body:
Please use the try/catch block. This serves the purpose of handling errors at your end rather than the server handling them for you.

Also I have noticed '/me/photo/$value' this will not replace $value using single quotes properly. Please use double quotes here "/me/photo/$value".

use Exception; //import right after namespace
try {
    $photo = $graph->createRequest('GET', '/me/photo/$value')
       ->addHeaders(array("Content-Type" => "image/jpeg"))
       ->execute();
    $photo = $photo->getRawBody();
    $avatar = 'data:image/jpeg;base64,'.base64_encode($photo).'';
} catch (Exception $e) {
    //in-case of error
    $avatar = null;
}


问:
Highcharts: How to add another(custom) label/ legend/ something else to the top right of the graph?
In my highcharts, I already have a legend at the bottom left of the graph but want to add a custom status indicator for the entire graph. It's going to be a colored oval with a colored dot and a status on it like in the picture.

Should I be trying to use a custom legend or something else? I don't need to hide/show abiliity of the legend so maybe I'm thinking a label is more appropriate but it seems like those only go in the graph. I want something on the top right of the graph. I'm looking through the API to see what else is available but haven't found one that suites my needs.

edit-
seems like I might have to do "chart.renderer.text" but I'm not sure how to convert and make it work in typescript http://jsfiddle.net/phpdeveloperrahul/HW7Rm/

```<code>function (chart) {

var point = chart.series[0].data[8],
    text = chart.renderer.text(
        'Max',
        point.plotX + chart.plotLeft + 10,
        point.plotY + chart.plotTop - 10
    ).attr({
        zIndex: 5
    }).add(),
    box = text.getBBox();

chart.renderer.rect(box.x - 5, box.y - 5, box.width + 10, box.height + 10, 5)
    .attr({
        fill: '#FFFFEF',
        stroke: 'gray',
        'stroke-width': 1,
        zIndex: 4
    })
    .add();
</code>```

});

答: I decided to just get rid of the title and add custom css to the top of it.</p>

Body:
In my highcharts, I already have a legend at the bottom left of the graph but want to add a custom status indicator for the entire graph. It's going to be a colored oval with a colored dot and a status on it like in the picture.

Should I be trying to use a custom legend or something else? I don't need to hide/show abiliity of the legend so maybe I'm thinking a label is more appropriate but it seems like those only go in the graph. I want something on the top right of the graph. I'm looking through the API to see what else is available but haven't found one that suites my needs.

edit-
seems like I might have to do "chart.renderer.text" but I'm not sure how to convert and make it work in typescript http://jsfiddle.net/phpdeveloperrahul/HW7Rm/

function (chart) {

var point = chart.series[0].data[8],
    text = chart.renderer.text(
        'Max',
        point.plotX + chart.plotLeft + 10,
        point.plotY + chart.plotTop - 10
    ).attr({
        zIndex: 5
    }).add(),
    box = text.getBBox();

chart.renderer.rect(box.x - 5, box.y - 5, box.width + 10, box.height + 10, 5)
    .attr({
        fill: '#FFFFEF',
        stroke: 'gray',
        'stroke-width': 1,
        zIndex: 4
    })
    .add();

});


问:
Update user information and image through http request in Xamarin
Good day,
I have a function in my Xamarin app where the user will click on after updating his information and image in order to change it in the server thorough http request. In my web API, the PUT function has following signature:

```<code>[HttpPut("{id}")]
[Authorize]
public IActionResult UpdateUserInfo(int id, [FromForm] User user)
{
}
</code>```

The image in the User class is of type iFromFile and in my Xamarin app I'm using MediaPicker to choose the image from the local storage. After updating the image and the user information, the following function is called to send the http request from Xamarin:

```<code>public static async Task<int> UpdateUserInformation(int UserId, UpdateUserInfo userInfo)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(userInfo);
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
var response = await httpClient.PutAsync(AppSettings.ApiUrl + "api/Accounts/UpdateUserInfo/" + UserId, content);
}
</code>```

I'm getting the image from the device using below function and my question how can I pass the image as iFromFile in the UpdateUserInfo class before triggering above UpdateUserInformation function:

```<code>private async void updateUserImage_Tapped(object sender, EventArgs e)
{
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
 {
                Title = "Choose image"

 });

    if (result != null)
            {
               var stream  = await result.OpenReadAsync();

                userImage.ImageSource = ImageSource.FromStream(() => stream);
            }
        }
</code>```

Your kind help is appreciated.

答:
You can access file path like this:

```<code>var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
 {
   Title = "Choose image"
 });

if (result != null)
{
   var Source = result.Path;
   userImage.ImageSource = ImageSource.FromFile(Source);
}

</code>```

HTTP REQUEST

```<code>using (var httpClient = new HttpClient())
{

  var request = new HttpRequestMessage(HttpMethod.Post, url);
  var bytes = System.IO.File.ReadAllBytes(Source) // you can get it from the first code i wrote. var Source = result.Path;
  request.Content = new ByteArrayContent(bytes);

  var response = await httpClient.SendAsync(request);
  var content = await response.Content.ReadAsStringAsync();

}
</code>```

Body:
Good day,
I have a function in my Xamarin app where the user will click on after updating his information and image in order to change it in the server thorough http request. In my web API, the PUT function has following signature:

[HttpPut("{id}")]
[Authorize]
public IActionResult UpdateUserInfo(int id, [FromForm] User user)
{
}

The image in the User class is of type iFromFile and in my Xamarin app I'm using MediaPicker to choose the image from the local storage. After updating the image and the user information, the following function is called to send the http request from Xamarin:

public static async Task<int> UpdateUserInformation(int UserId, UpdateUserInfo userInfo)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(userInfo);
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Preferences.Get("accessToken", string.Empty));
var response = await httpClient.PutAsync(AppSettings.ApiUrl + "api/Accounts/UpdateUserInfo/" + UserId, content);
}

I'm getting the image from the device using below function and my question how can I pass the image as iFromFile in the UpdateUserInfo class before triggering above UpdateUserInformation function:

private async void updateUserImage_Tapped(object sender, EventArgs e)
{
var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
 {
                Title = "Choose image"

 });

    if (result != null)
            {
               var stream  = await result.OpenReadAsync();

                userImage.ImageSource = ImageSource.FromStream(() => stream);
            }
        }

Your kind help is appreciated.

Body:
You can access file path like this:

var result = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
 {
   Title = "Choose image"
 });

if (result != null)
{
   var Source = result.Path;
   userImage.ImageSource = ImageSource.FromFile(Source);
}

HTTP REQUEST

using (var httpClient = new HttpClient())
{

  var request = new HttpRequestMessage(HttpMethod.Post, url);
  var bytes = System.IO.File.ReadAllBytes(Source) // you can get it from the first code i wrote. var Source = result.Path;
  request.Content = new ByteArrayContent(bytes);

  var response = await httpClient.SendAsync(request);
  var content = await response.Content.ReadAsStringAsync();

}


问:
Get the first character of the first string in a list?
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

```<code>>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'
</code>```

答:
You almost had it right. The simplest way is

```<code>mylist[0][0]   # get the first character from the first item in the list
</code>```

but

```<code>mylist[0][:1]  # get up to the first character in the first item in the list
</code>```

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

Body:
How would I get the first character from the first string in a list in Python?

It seems that I could use mylist[0][1:] but that does not give me the first character.

>>> mylist = []
>>> mylist.append("asdf")
>>> mylist.append("jkl;")
>>> mylist[0][1:]
'sdf'

Body:
You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.


问:
Simulate mouseenter with pure css
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

```<code>*:hover {
    border-color: red;
}
</code>```

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div>

    </div>
  </article>
</main></code>```

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

答:
Update your CSS (demo):

div:hover {
    border-color: red;
}
```
<p>Alternatively, add a class to elements you want to share a common style (demo).</p>
<pre class="lang-html prettyprint-override"><code><main>
  <article>
    <div class="highlight-on-hover">

    </div>
    <div>

    </div>
    <div class="highlight-on-hover">

    </div>
  </article>
</main>
</code>```

.highlight-on-hover:hover {
    border-color: red;
}
```

Title: Simulate mouseenter with pure css

Body:
I need to style an element when I hover with the mouse above it. But, I don't want to style its parent DOM elements. However, when I use :hover the element in question is styled just as I want, but unfortunately, all of its parents are styled too

*:hover {
    border-color: red;
}

DEMO

main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

*:hover {
  border-color: red;
}

The outer border shall be red only if the cursor is between the outer border and the middle border. The middle order shall be red only if the cursor is between the middle border and the inner border. The inner border shall be red only if the cursor is inside the inner border.

Is there a way to only style the DOM element being hovered (which can be any element)? or can I only achieve this goal with javascript?

Body:
Update your CSS (demo):

div:hover {
    border-color: red;
}

Alternatively, add a class to elements you want to share a common style (demo).

<main>
  <article>
    <div class="highlight-on-hover">

    </div>
    <div>

    </div>
    <div class="highlight-on-hover">

    </div>
  </article>
</main>

.highlight-on-hover:hover {
    border-color: red;
}


问:
React Filtering based on user input -State, setState, useState, Hooks
I have a fun project that is filter data using .filter .map etc etc - At the moment I have a select -> option that changes the state of the data presented to the user but I also want to filter based an onChange event but have issues with the whole filter part

https://j121b.csb.app/ is the code sandbox and this is the issue:

Type Error - data.instName.contains is not a function

Could someone look over code and point me in the right direction please? Thank you and happy Friday :)

答: Use includes instead of contains.

Body: Use includes instead of contains.


问:
testing .net4.8 in VScode using dotnet CLI
I am trying to transform an old non-SDK-style mstest project that was generated with Visual Studio into a new SDK-style project using only Visual Studio Code.

I read and followed this little how-to, but this is only for .NET core and newer; not for .NET framework.

I need my project to target both. If I do it like this

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>net48;netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net48'">
    <PackageReference Include="Microsoft.VisualStudio.UnitTesting" Version="11.0.50727.1" />
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' != 'net48'">
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="2.2.7" />
    <PackageReference Include="MSTest.TestFramework" Version="2.2.7" />
    <PackageReference Include="coverlet.collector" Version="3.1.0" />
  </ItemGroup>

</Project>
</code>```

and add some test like this

```<code>using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyTests {

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestTwoPlusTwoIsFour()
        {
            Assert.IsTrue(2 + 2 == 4);
        }
    }

}
</code>```

and run dotnet test on my csproj, then only netcoreapp3.1, net5.0, net6.0 get tested. The net48 does not occur anywhere in my console output.

What do I need to do in order to test all four frameworks?

答:
Seems I cannot use dotnet test for it but need msbuild. (Thanks for the comment, @Heinzi.)

I can run it like so:

```<code>"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\mstest.exe" /testcontainer:"$(MSBuildProjectDirectory)\$(OutputPath)$(ProjectName).dll"
</code>```

It would be nice if this can somehow be incorporated into my dotnet test call, so I don't need two calls...

Body:
I am trying to transform an old non-SDK-style mstest project that was generated with Visual Studio into a new SDK-style project using only Visual Studio Code.

I read and followed this little how-to, but this is only for .NET core and newer; not for .NET framework.

I need my project to target both. If I do it like this

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>net48;netcoreapp3.1;net5.0;net6.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net48'">
    <PackageReference Include="Microsoft.VisualStudio.UnitTesting" Version="11.0.50727.1" />
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' != 'net48'">
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="2.2.7" />
    <PackageReference Include="MSTest.TestFramework" Version="2.2.7" />
    <PackageReference Include="coverlet.collector" Version="3.1.0" />
  </ItemGroup>

</Project>

and add some test like this

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MyTests {

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestTwoPlusTwoIsFour()
        {
            Assert.IsTrue(2 + 2 == 4);
        }
    }

}

and run dotnet test on my csproj, then only netcoreapp3.1, net5.0, net6.0 get tested. The net48 does not occur anywhere in my console output.

What do I need to do in order to test all four frameworks?

Body:
Seems I cannot use dotnet test for it but need msbuild. (Thanks for the comment, @Heinzi.)

I can run it like so:

"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\mstest.exe" /testcontainer:"$(MSBuildProjectDirectory)\$(OutputPath)$(ProjectName).dll"

It would be nice if this can somehow be incorporated into my dotnet test call, so I don't need two calls...


问:
Getting "AccessDenied: Access Denied" inside lambda when getting an object from s3

Update 2

I've tried changing our custom policy to allow access to the particular bucket that's giving the AccessDenied error, without any luck. Imagine that bucket1 is a bucket that the lambda normally accesses, and bucket2 is the bucket that's throwing AccessDenied when the lambda accesses it. I've changed the Resource block from

```<code>{
        ...
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
            "Effect": "Allow"
        }
        ...
</code>```

to

```<code>{
        ...
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::us-east-1-bucket1/*",
                "arn:aws:s3:::us-east-1-bucket2/*"
            ],
            "Effect": "Allow"
        }
        ...
</code>```

I'm still getting the AccessDenied error.

Update

Per @Caldazar's comment about IAM users vs roles, the lambda's execution role has 3 policies:

the AWS managed arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess, specifically:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords",
                "xray:GetSamplingRules",
                "xray:GetSamplingTargets",
                "xray:GetSamplingStatisticSummaries"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
</code>```

the AWS managed arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole, specifically:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

our custom policy, specifically:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:*"
            ],
            "Resource": "arn:aws:logs:us-east-1:*:log-group:/aws/lambda/*:*:*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
            "Effect": "Allow"
        }
    ]
}
</code>```

In lambda@edge I have an origin-response response lambda that is trying to pull an object out of s3 to be used as the response. However I'm getting this AccessDenied error when I try to list the contents of the bucket using a particular prefix. This is my code:

const getVidS3 = (s3, bucketName, fileName) =>
    new Promise((res, rej) => {
        const start = Date.now();
        s3.listObjects(
            {
                Bucket: bucketName,
                Delimiter: '/',
                Prefix: `${fileName}/`,
                MaxKeys: 1,
            },
            function (err, data) {
                console.log(
                    '================ milliseconds to list objects:',
                    Date.now() - start
                );
                if (err) return rej(err);
                if (!Array.isArray(data.Contents) || data.Contents.length < 1) {
                    return rej('original raw video not found');
                }
                console.log('============= s3 objects:', data);
                const rawVidFileKey = data.Contents[0].Key;
                s3.getObject(
                    {
                        Bucket: bucketName,
                        Key: rawVidFileKey,
                    },
                    (err, data) => {
                        console.log(
                            '================ milliseconds to get video object:',
                            Date.now() - start
                        );
                        if (err) {
                            return rej(err);
                        }

                        const contentType = data.ContentType;
                        const video = data.Body;
                        console.log('=============== S3 video data', data);
                        return res({ video, contentType });
                    }
                );
            }
        );
    });
```

The error is from listObjects. I've gone over this set of suggestions but I'm not sure I took the right steps because I used the IAM user that I use to access the dashboard, which may have higher permissions than the one the lambda uses. More so, I recreated this getVidS3 function locally using my admin credentials and it works, so I think I need help determining how to give the lambda the appropriate permissions. I didn't create the system and I'm not very proficient with aws, so bear with me if this feels incomplete. What/where else can I check to see why this is happening? Thanks in advance.

答:
The problem is in your policy. The policy allows GET of the objects, but not List. You're missing the ListBucket action on the bucket itself.

You need to change this:

```<code>{
        "Action": [
            "s3:GetObject"
        ],
        "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
        "Effect": "Allow"
    }
</code>```

To this:

```<code>{
        "Action": [
            "s3:GetObject",
            "s3:ListBucket"
        ],
        "Resource": [
             "arn:aws:s3:::us-east-1-bucket1/*",
             "arn:aws:s3:::us-east-1-bucket1"
         ]
        "Effect": "Allow"
    }
</code>```

Body:
Update 2

I've tried changing our custom policy to allow access to the particular bucket that's giving the AccessDenied error, without any luck. Imagine that bucket1 is a bucket that the lambda normally accesses, and bucket2 is the bucket that's throwing AccessDenied when the lambda accesses it. I've changed the Resource block from

{
        ...
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
            "Effect": "Allow"
        }
        ...

to

{
        ...
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::us-east-1-bucket1/*",
                "arn:aws:s3:::us-east-1-bucket2/*"
            ],
            "Effect": "Allow"
        }
        ...

I'm still getting the AccessDenied error.

Update

Per @Caldazar's comment about IAM users vs roles, the lambda's execution role has 3 policies:

the AWS managed arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess, specifically:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords",
                "xray:GetSamplingRules",
                "xray:GetSamplingTargets",
                "xray:GetSamplingStatisticSummaries"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

the AWS managed arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole, specifically:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

our custom policy, specifically:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:*"
            ],
            "Resource": "arn:aws:logs:us-east-1:*:log-group:/aws/lambda/*:*:*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
            "Effect": "Allow"
        }
    ]
}

In lambda@edge I have an origin-response response lambda that is trying to pull an object out of s3 to be used as the response. However I'm getting this AccessDenied error when I try to list the contents of the bucket using a particular prefix. This is my code:

const getVidS3 = (s3, bucketName, fileName) =>
    new Promise((res, rej) => {
        const start = Date.now();
        s3.listObjects(
            {
                Bucket: bucketName,
                Delimiter: '/',
                Prefix: `${fileName}/`,
                MaxKeys: 1,
            },
            function (err, data) {
                console.log(
                    '================ milliseconds to list objects:',
                    Date.now() - start
                );
                if (err) return rej(err);
                if (!Array.isArray(data.Contents) || data.Contents.length < 1) {
                    return rej('original raw video not found');
                }
                console.log('============= s3 objects:', data);
                const rawVidFileKey = data.Contents[0].Key;
                s3.getObject(
                    {
                        Bucket: bucketName,
                        Key: rawVidFileKey,
                    },
                    (err, data) => {
                        console.log(
                            '================ milliseconds to get video object:',
                            Date.now() - start
                        );
                        if (err) {
                            return rej(err);
                        }

                        const contentType = data.ContentType;
                        const video = data.Body;
                        console.log('=============== S3 video data', data);
                        return res({ video, contentType });
                    }
                );
            }
        );
    });

The error is from listObjects. I've gone over this set of suggestions but I'm not sure I took the right steps because I used the IAM user that I use to access the dashboard, which may have higher permissions than the one the lambda uses. More so, I recreated this getVidS3 function locally using my admin credentials and it works, so I think I need help determining how to give the lambda the appropriate permissions. I didn't create the system and I'm not very proficient with aws, so bear with me if this feels incomplete. What/where else can I check to see why this is happening? Thanks in advance.

Body:
The problem is in your policy. The policy allows GET of the objects, but not List. You're missing the ListBucket action on the bucket itself.

You need to change this:

{
        "Action": [
            "s3:GetObject"
        ],
        "Resource": "arn:aws:s3:::us-east-1-bucket1/*",
        "Effect": "Allow"
    }

To this:

{
        "Action": [
            "s3:GetObject",
            "s3:ListBucket"
        ],
        "Resource": [
             "arn:aws:s3:::us-east-1-bucket1/*",
             "arn:aws:s3:::us-east-1-bucket1"
         ]
        "Effect": "Allow"
    }


问:
Python function call with Class name instead of object
```<code>class MyClass:
    def func1(a,b):
         print(a,b)

MyClass.func1(4,5)
</code>```

I thought the above piece of code will throw error because we are accessing a method that is declared without @staticmethod decorator using class.

So does that mean the function called with class name will act like a static method ?

答:
Yes, if used as a class property, there is no special mechanism instated to use it as a method:

```<code>>>> class A:
...     def f(a, b):
...         print(a,b)
...
>>> type(A.f)
<class 'function'>
</code>```

However:

```<code>>>> a=A()
>>> type(a.f)
<class 'method'>
>>> a.f('only one arg because a itself is supplied as first arg')
<__main__.A object at 0x76992b70> only one arg because a itself is supplied as first arg
</code>```

When a plain (no staticmethod, no classmethod) function defined inside a class is called through an instance of the class, then it is called as a method, meaning the first argument (in this case a but typically self) will be automatically provided as the instance itself.

Body:
class MyClass:
    def func1(a,b):
         print(a,b)

MyClass.func1(4,5)

I thought the above piece of code will throw error because we are accessing a method that is declared without @staticmethod decorator using class.

So does that mean the function called with class name will act like a static method ?

Body:
Yes, if used as a class property, there is no special mechanism instated to use it as a method:

>>> class A:
...     def f(a, b):
...         print(a,b)
...
>>> type(A.f)
<class 'function'>

However:

>>> a=A()
>>> type(a.f)
<class 'method'>
>>> a.f('only one arg because a itself is supplied as first arg')
<__main__.A object at 0x76992b70> only one arg because a itself is supplied as first arg

When a plain (no staticmethod, no classmethod) function defined inside a class is called through an instance of the class, then it is called as a method, meaning the first argument (in this case a but typically self) will be automatically provided as the instance itself.


问:
ASP.NET: How to use contentplaceholder in attribute values without editor/designer errors?
I am using a contentplaceholder control in a master page to allow the content editor to specify the URL of an image used as a background to a div.

```<code><div id="content-left-column"
     style="background-image: url('<wc:UrlContentPlaceHolder runat='server' ID='leftContentBackgroundUrl'></wc:UrlContentPlaceHolder>');">
</code>```

The placeholder is referenced on the content page like:

```<code><asp:Content ID="Content1" ContentPlaceHolderID="leftContentBackgroundUrl" runat="server">/img/left-content.jpg</asp:Content>
</code>```

The page renders just fine using this approach.  However, when I look at the content page in source view, the ContentPlaceHolderId attribute value is underlined and there is a warning "Could not find 'leftContentBackgroundUrl' in the current master page or pages."

Design view will not render the content page due to this error.

Is there a way to use ContentPlaceHolder for attribute values such that no errors are reported in the Visual Studio editor and design surface?

*Note.  I am aware of the issues with this approach.  If the content editor puts in spaces, carriage returns or performs a document format in visual studio, the rendered attribute value is broken.  I have created a subclass of ContentPlaceHolder that trims its values and uses ResolveClientUrl to address these issues.  For the sake of discussion I have described the issue which affects a normal ContentPlaceHolder control.

The following stack overflow question addresses the fact that ContentPlaceHolder can be used with attribute values but does not address the design surface issues.
Why can't I use a ContentPlaceholder inside HTML attributes in ASP.NET?

答:
This solution was inspired by @atticae's response.

On the master page, I included a normal ContentPlaceholder control with visible="false".  Where I was previously using that ContentPlaceholder as an attribute value, I instead reference a property of the MasterPage, LeftBackgroundImageUrl.

```<code><asp:ContentPlaceHolder runat='server' ID='leftContentBackgroundUrl' Visible="false"/>
<div id="content-left-column" style="background-image: url('<%: LeftBackgroundImageUrl%>');">
</code>```

Using a subclass of ContentPlaceholder causes errors in the design surface of content pages which is why I went back to using a normal ContentPlaceholder.

The LeftBackgroundImageUrl property code looks like:

```<code>ReadOnly Property LeftBackgroundImageUrl As String
    Get
        Return RenderResolvedUrl(leftContentBackgroundUrl)
    End Get
End Property

Private Function RenderedResolvedUrl(control As Control) As String
    Dim visible As Boolean = control.Visible
    control.Visible = True
    Dim result As String = Nothing
    Using writer As New System.IO.StringWriter()
        Using htmlWriter As New System.Web.UI.HtmlTextWriter(writer)
            control.RenderControl(htmlWriter)
            htmlWriter.Flush()
        End Using
        result = Page.ResolveClientUrl(writer.ToString.Trim).Trim
    End Using
    control.Visible = visible
    Return result
End Function
</code>```

This solution allows the image url to be specified declaratively, and without the user having to add a MasterType directive.  This is not perfect in the sense that it does not, at edit/design time, validate that the content the editor provides is just a URL or application relative URL.  But, it does keep the user from having to write code.

Body:
I am using a contentplaceholder control in a master page to allow the content editor to specify the URL of an image used as a background to a div.

<div id="content-left-column"
     style="background-image: url('<wc:UrlContentPlaceHolder runat='server' ID='leftContentBackgroundUrl'></wc:UrlContentPlaceHolder>');">

The placeholder is referenced on the content page like:

<asp:Content ID="Content1" ContentPlaceHolderID="leftContentBackgroundUrl" runat="server">/img/left-content.jpg</asp:Content>

The page renders just fine using this approach.  However, when I look at the content page in source view, the ContentPlaceHolderId attribute value is underlined and there is a warning "Could not find 'leftContentBackgroundUrl' in the current master page or pages."

Design view will not render the content page due to this error.

Is there a way to use ContentPlaceHolder for attribute values such that no errors are reported in the Visual Studio editor and design surface?

*Note.  I am aware of the issues with this approach.  If the content editor puts in spaces, carriage returns or performs a document format in visual studio, the rendered attribute value is broken.  I have created a subclass of ContentPlaceHolder that trims its values and uses ResolveClientUrl to address these issues.  For the sake of discussion I have described the issue which affects a normal ContentPlaceHolder control.

The following stack overflow question addresses the fact that ContentPlaceHolder can be used with attribute values but does not address the design surface issues.
Why can't I use a ContentPlaceholder inside HTML attributes in ASP.NET?

Body:
This solution was inspired by @atticae's response.

On the master page, I included a normal ContentPlaceholder control with visible="false".  Where I was previously using that ContentPlaceholder as an attribute value, I instead reference a property of the MasterPage, LeftBackgroundImageUrl.

<asp:ContentPlaceHolder runat='server' ID='leftContentBackgroundUrl' Visible="false"/>
<div id="content-left-column" style="background-image: url('<%: LeftBackgroundImageUrl%>');">

Using a subclass of ContentPlaceholder causes errors in the design surface of content pages which is why I went back to using a normal ContentPlaceholder.

The LeftBackgroundImageUrl property code looks like:

ReadOnly Property LeftBackgroundImageUrl As String
    Get
        Return RenderResolvedUrl(leftContentBackgroundUrl)
    End Get
End Property

Private Function RenderedResolvedUrl(control As Control) As String
    Dim visible As Boolean = control.Visible
    control.Visible = True
    Dim result As String = Nothing
    Using writer As New System.IO.StringWriter()
        Using htmlWriter As New System.Web.UI.HtmlTextWriter(writer)
            control.RenderControl(htmlWriter)
            htmlWriter.Flush()
        End Using
        result = Page.ResolveClientUrl(writer.ToString.Trim).Trim
    End Using
    control.Visible = visible
    Return result
End Function

This solution allows the image url to be specified declaratively, and without the user having to add a MasterType directive.  This is not perfect in the sense that it does not, at edit/design time, validate that the content the editor provides is just a URL or application relative URL.  But, it does keep the user from having to write code.


问:
Increase and reduce index withing a fixed circular range in JS
I have a circular range of ascii values of a-z, from 97 to 122.

I am having trouble with decreasing the value, suppose the current value is 100 and i want to reduce it by 4 and it should return 122.

```<code>const startIndex=97
const endIndex=122

let increaseBy=reduceBy=5
let currentIndex=122
// increment
// this works
currentIndex=startIndex+((currentIndex-startIndex+increaseBy)%26)

// decrement
// need help
currentIndex=attempted_something_that_you_will_find_it_as_dumb
</code>```

答:
Modulo will walk your modulo-class as you wish, if you just keep adding your

startIndex + (currentIndex%26)

Now, you just make sure, your currentIndex want go below 0

you modify only the currentIndex

```<code>let startIndex = 97;
let currentIndex = 0;

for(let inc = 0; inc < 10; inc++) {
   currentIndex += 5;
   console.log(startIndex + (currentIndex%26));
}

for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   console.log(startIndex + (currentIndex%26));
}

console.log("index will go below zero -> will break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   console.log(startIndex + (currentIndex%26));
}

console.log("index will stop at zero -> will not break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex = Math.max(0, currentIndex - 5);
   console.log(startIndex + (currentIndex%26));
}

console.log("index will reset to modulo at zero -> will not break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   currentIndex = (currentIndex < 0) ? (26 + currentIndex) : currentIndex;
   console.log(startIndex + (currentIndex%26));
}

</code>```

Body:
I have a circular range of ascii values of a-z, from 97 to 122.

I am having trouble with decreasing the value, suppose the current value is 100 and i want to reduce it by 4 and it should return 122.

const startIndex=97
const endIndex=122

let increaseBy=reduceBy=5
let currentIndex=122
// increment
// this works
currentIndex=startIndex+((currentIndex-startIndex+increaseBy)%26)

// decrement
// need help
currentIndex=attempted_something_that_you_will_find_it_as_dumb

Body:
Modulo will walk your modulo-class as you wish, if you just keep adding your

startIndex + (currentIndex%26)

Now, you just make sure, your currentIndex want go below 0

you modify only the currentIndex

let startIndex = 97;
let currentIndex = 0;

for(let inc = 0; inc < 10; inc++) {
   currentIndex += 5;
   console.log(startIndex + (currentIndex%26));
}

for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   console.log(startIndex + (currentIndex%26));
}

console.log("index will go below zero -> will break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   console.log(startIndex + (currentIndex%26));
}

console.log("index will stop at zero -> will not break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex = Math.max(0, currentIndex - 5);
   console.log(startIndex + (currentIndex%26));
}

console.log("index will reset to modulo at zero -> will not break");
for(let inc = 0; inc < 10; inc++) {
   currentIndex -= 5;
   currentIndex = (currentIndex < 0) ? (26 + currentIndex) : currentIndex;
   console.log(startIndex + (currentIndex%26));
}


问:
AWS CLI to get only Volumeid and tagvalue
From AWS using CLI to get volume details via describe-volumes

Sample volume Details

```<code>VolumeId = Vol-********
Attachments.InstanceId = i-*********
Tags : Key = Name     Value = sometext
</code>```

Expected Output via AWS CLI:

```<code>Vol-********   i-*********   sometext
</code>```

Codes I tried:

```<code>aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,Tag:Tags}" --output text
</code>```

Output what I am getting:

```<code>Vol-********   i-*********
TAG    Name    sometext
</code>```

Looking for help to get output as below.

Expected Output via AWS CLI:

```<code>Vol-********   i-*********   sometext
</code>```

答:
If you are looking for a specific tag value of a volume:

```<code>aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[0].Value}" --output text

vol-*******   i-******     second
</code>```

If you are looking for all the tags value, it will come as below: format= text

```<code>aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[].Value}" --output text

vol-0fa1417c2369e7440   i-0533e831213cf0cc4
TAG     second
TAG     test
</code>```

If you are looking for all the tags value, it will come as below. format= json

```<code>aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[].Value}" --output json

[
    {
        "InstanceId": "i-******",
        "tag": [
            "second",
            "test"
        ],
        "ID": "vol-******"
    }
]
</code>```

Body:
From AWS using CLI to get volume details via describe-volumes

Sample volume Details

VolumeId = Vol-********
Attachments.InstanceId = i-*********
Tags : Key = Name     Value = sometext

Expected Output via AWS CLI:

Vol-********   i-*********   sometext

Codes I tried:

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,Tag:Tags}" --output text

Output what I am getting:

Vol-********   i-*********
TAG    Name    sometext

Looking for help to get output as below.

Expected Output via AWS CLI:

Vol-********   i-*********   sometext

Body:
If you are looking for a specific tag value of a volume:

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[0].Value}" --output text

vol-*******   i-******     second

If you are looking for all the tags value, it will come as below: format= text

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[].Value}" --output text

vol-0fa1417c2369e7440   i-0533e831213cf0cc4
TAG     second
TAG     test

If you are looking for all the tags value, it will come as below. format= json

aws ec2 describe-volumes --query "Volumes[*].{ID:VolumeId,InstanceId:Attachments[0].InstanceId,tag:Tags[].Value}" --output json

[
    {
        "InstanceId": "i-******",
        "tag": [
            "second",
            "test"
        ],
        "ID": "vol-******"
    }
]


问:
Snakemake Error with MissingOutputException
I am trying to run STAR with snakemake in a server,
My smk file is that one :

```<code>import pandas as pd

configfile: 'config.yaml'

#Read sample to batch dataframe mapping batch to sample (here with zip)
sample_to_batch = pd.read_csv("/mnt/DataArray1/users/zisis/STAR_mapping/snakemake_STAR_index/all_samples_test.csv", sep = '\t')

#rule spcifying output
rule all_STAR:
    input:
        #expand("{sample}/Aligned.sortedByCoord.out.bam", sample = sample_to_batch['sample'])
        expand(config['path_to_output']+"{sample}/Aligned.sortedByCoord.out.bam", sample = sample_to_batch['sample'])

rule STAR_align:
    #specify input fastq files
    input:
        fq1 = config['path_to_output']+"{sample}_1.fastq.gz",
        fq2 = config['path_to_output']+"{sample}_2.fastq.gz"
    params:
        #location of indexed genome andl location to save the ouput
        genome = directory(config['path_to_reference']+config['ref_assembly']+".STAR_index"),
        prefix_outdir = directory(config['path_to_output']+"{sample}/")
    threads: 12
    output:
        config['path_to_output']+"{sample}/Aligned.sortedByCoord.out.bam"
    log:
        config['path_to_output']+"logs/{sample}.log"
    message:
        "--- Mapping STAR---"
    shell:
        """
        STAR --runThreadN {threads} \
        --readFilesCommand zcat \
        --readFilesIn {input} \
        --genomeDir {params.genome} \
        --outSAMtype BAM SortedByCoordinate \
        --outSAMunmapped Within \
        --outSAMattributes Standard
        """
</code>```

While STAR starts normally at the end i have this error:

```<code>Waiting at most 5 seconds for missing files.
MissingOutputException in line 14 of /mnt/DataArray1/users/zisis/STAR_mapping/snakemake/STAR_snakefile_align.smk:
Job Missing files after 5 seconds:
/mnt/DataArray1/users/zisis/STAR_mapping/snakemake/001_T1/Aligned.sortedByCoord.out.bam
This might be due to filesystem latency. If that is the case, consider to increase the wait time with --latency-wait.
Job id: 1 completed successfully, but some output files are missing. 1
Shutting down, this might take some time.
Exiting because a job execution failed. Look above for error message
</code>```

I tried --latency-wait but is not working.
In order to execute snake make i run the command

```<code>users/zisis/STAR_mapping/snakemake_STAR_index$ snakemake --snakefile STAR_new_snakefile.smk --cores all --printshellcmds
</code>```

Technically i am in my directory with full access and permissions
Do you think that this is happening due to strange rights in the execution of snakemake or when it tries to create directories ?
It creates the directory and the files but i can see that there is a files Aligned.sortedByCoord.out.bamAligned.sortedByCoord.out.bam .

IS this the problem ?

答:
I think your STAR command does not have the option that says which file and directory to write to, presumably it is writing the default filename to the current directory. Try something like:

```<code>rule STAR_align:
    input: ...
    output: ...
    ...
    shell:
        r"""
        outprefix=`dirname {output}`

        STAR --outFileNamePrefix $outprefix \
            --runThreadN {threads} \
            etc...
        """
</code>```

I am runing the command from my directory in which i am sudo user

I don't think that is the problem but it is strongly recommended to work as regular user and use sudo only in special circumstances (e.g. installing system-wide programs but if you use conda you shouldn't need that).

Body:
I am trying to run STAR with snakemake in a server,
My smk file is that one :

import pandas as pd

configfile: 'config.yaml'

#Read sample to batch dataframe mapping batch to sample (here with zip)
sample_to_batch = pd.read_csv("/mnt/DataArray1/users/zisis/STAR_mapping/snakemake_STAR_index/all_samples_test.csv", sep = '\t')

#rule spcifying output
rule all_STAR:
    input:
        #expand("{sample}/Aligned.sortedByCoord.out.bam", sample = sample_to_batch['sample'])
        expand(config['path_to_output']+"{sample}/Aligned.sortedByCoord.out.bam", sample = sample_to_batch['sample'])

rule STAR_align:
    #specify input fastq files
    input:
        fq1 = config['path_to_output']+"{sample}_1.fastq.gz",
        fq2 = config['path_to_output']+"{sample}_2.fastq.gz"
    params:
        #location of indexed genome andl location to save the ouput
        genome = directory(config['path_to_reference']+config['ref_assembly']+".STAR_index"),
        prefix_outdir = directory(config['path_to_output']+"{sample}/")
    threads: 12
    output:
        config['path_to_output']+"{sample}/Aligned.sortedByCoord.out.bam"
    log:
        config['path_to_output']+"logs/{sample}.log"
    message:
        "--- Mapping STAR---"
    shell:
        """
        STAR --runThreadN {threads} \
        --readFilesCommand zcat \
        --readFilesIn {input} \
        --genomeDir {params.genome} \
        --outSAMtype BAM SortedByCoordinate \
        --outSAMunmapped Within \
        --outSAMattributes Standard
        """

While STAR starts normally at the end i have this error:

Waiting at most 5 seconds for missing files.
MissingOutputException in line 14 of /mnt/DataArray1/users/zisis/STAR_mapping/snakemake/STAR_snakefile_align.smk:
Job Missing files after 5 seconds:
/mnt/DataArray1/users/zisis/STAR_mapping/snakemake/001_T1/Aligned.sortedByCoord.out.bam
This might be due to filesystem latency. If that is the case, consider to increase the wait time with --latency-wait.
Job id: 1 completed successfully, but some output files are missing. 1
Shutting down, this might take some time.
Exiting because a job execution failed. Look above for error message

I tried --latency-wait but is not working.
In order to execute snake make i run the command

users/zisis/STAR_mapping/snakemake_STAR_index$ snakemake --snakefile STAR_new_snakefile.smk --cores all --printshellcmds

Technically i am in my directory with full access and permissions
Do you think that this is happening due to strange rights in the execution of snakemake or when it tries to create directories ?
It creates the directory and the files but i can see that there is a files Aligned.sortedByCoord.out.bamAligned.sortedByCoord.out.bam .

IS this the problem ?

Body:
I think your STAR command does not have the option that says which file and directory to write to, presumably it is writing the default filename to the current directory. Try something like:

rule STAR_align:
    input: ...
    output: ...
    ...
    shell:
        r"""
        outprefix=`dirname {output}`

        STAR --outFileNamePrefix $outprefix \
            --runThreadN {threads} \
            etc...
        """

I am runing the command from my directory in which i am sudo user

I don't think that is the problem but it is strongly recommended to work as regular user and use sudo only in special circumstances (e.g. installing system-wide programs but if you use conda you shouldn't need that).


答:
main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

div:hover {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <article>
    <div id='myDiv'>

    </div>
  </article>
</main></code>```

Title: Simulate mouseenter with pure css

Body:
main,
article,
div {
  border: 1px solid lightgrey;
  padding: 30px;
}

div:hover {
  border-color: red;
}

<main>
  <article>
    <div id='myDiv'>

    </div>
  </article>
</main>