问:
foreach with SqlDataReader?
I have the following code:

```<code>SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    foreach (Object ob in reader)
    {
        someText.InnerText = someText.InnerText + " " + ob.ToString();
    }
}
</code>```

The code in the foreach loop does not execute. However, I can do this:

```<code>SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    someText.InnerText = reader[0].ToString();
}
</code>```

Which works.

Obviously I could achieve the same result using a regular for loop rather than a foreach loop, but I think the foreach syntax is clearer, so I use it when possible.

What has gone wrong here? Are foreach loops in c# not as flexible as in more high level languages?

答:
Something like the following. Note that IDataReader derives from IDataRecord which exposes the members used to process the current row:

```<code>IEnumerable<IDataRecord> GetFromReader(IDataReader reader)
{
    while(reader.Read()) yield return reader;
}

foreach(IDataRecord record in GetFromReader(reader))
{
    ... process it ...
}
</code>```

Or even something like the following, to get an enumeration or list of strongly-typed entity objects from a reader:

```<code>IEnumerable<T> GetFromReader<T>(IDataReader reader, Func<IDataRecord, T> processRecord)
{
    while(reader.Read()) yield return processRecord(reader);
}

MyType GetMyTypeFromRecord(IDataRecord record)
{
    MyType myType = new MyType();
    myType.SomeProperty = record[0];
    ...
    return myType;
}

IList<MyType> myResult = GetFromReader(reader, GetMyTypeFromRecord).ToList();
</code>```

UPDATE in response to Caleb Bell's comment.

I agree Enumerate is a better name.

In fact in my personal "common" library, I've now replaced the above by an extension method on IDataReader:

```<code>public static IEnumerable<IDataRecord> Enumerate(this IDataReader reader)
{
    while (reader.Read())
    {
        yield return reader;
    }
}
</code>```

And the caller can get strongly-typed objects using:

```<code>reader.Enumerate.Select(r => GetMyTypeFromRecord(r))
</code>```

Title: foreach with SqlDataReader?

Body:
I have the following code:

SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    foreach (Object ob in reader)
    {
        someText.InnerText = someText.InnerText + " " + ob.ToString();
    }
}

The code in the foreach loop does not execute. However, I can do this:

SqlDataReader reader = getAddressQuery.sqlReader;
while (reader.Read())
{
    someText.InnerText = reader[0].ToString();
}

Which works.

Obviously I could achieve the same result using a regular for loop rather than a foreach loop, but I think the foreach syntax is clearer, so I use it when possible.

What has gone wrong here? Are foreach loops in c# not as flexible as in more high level languages?

Body:
Something like the following. Note that IDataReader derives from IDataRecord which exposes the members used to process the current row:

IEnumerable<IDataRecord> GetFromReader(IDataReader reader)
{
    while(reader.Read()) yield return reader;
}

foreach(IDataRecord record in GetFromReader(reader))
{
    ... process it ...
}

Or even something like the following, to get an enumeration or list of strongly-typed entity objects from a reader:

IEnumerable<T> GetFromReader<T>(IDataReader reader, Func<IDataRecord, T> processRecord)
{
    while(reader.Read()) yield return processRecord(reader);
}

MyType GetMyTypeFromRecord(IDataRecord record)
{
    MyType myType = new MyType();
    myType.SomeProperty = record[0];
    ...
    return myType;
}

IList<MyType> myResult = GetFromReader(reader, GetMyTypeFromRecord).ToList();

UPDATE in response to Caleb Bell's comment.

I agree Enumerate is a better name.

In fact in my personal "common" library, I've now replaced the above by an extension method on IDataReader:

public static IEnumerable<IDataRecord> Enumerate(this IDataReader reader)
{
    while (reader.Read())
    {
        yield return reader;
    }
}

And the caller can get strongly-typed objects using:

reader.Enumerate.Select(r => GetMyTypeFromRecord(r))


来源: stackexchange

问:
Server tag is not well formed error on datagrid row ImageButton
I have come to an issue like the server tag is not well. this code is ASP.NET C# code.</p>
```<code><asp:TemplateColumn HeaderText="Options">
        <ItemTemplate>
            <asp:ImageButton ID="imgbuttEditVendor" runat="server" CommandName="Edit" CommandArgument="<%# Eval("ctpv_id") %>" ImageUrl="~/images/buttons/edit.gif" />
        </ItemTemplate>
    </asp:TemplateColumn>
</code>```

答:
Replace

```<code>CommandArgument="<%# Eval("ctpv_id") %>"
</code>```

with

```<code>CommandArgument='<%# Eval("ctpv_id") %>'
</code>```

Note: Embed double quote in the double quote is not allowed.

ContentLicense: CC BY-SA 4.0

Body:
I have come to an issue like the server tag is not well. this code is ASP.NET C# code.

<asp:TemplateColumn HeaderText="Options">
        <ItemTemplate>
            <asp:ImageButton ID="imgbuttEditVendor" runat="server" CommandName="Edit" CommandArgument="<%# Eval("ctpv_id") %>" ImageUrl="~/images/buttons/edit.gif" />
        </ItemTemplate>
    </asp:TemplateColumn>

Body:
Replace

CommandArgument="<%# Eval("ctpv_id") %>"

with

CommandArgument='<%# Eval("ctpv_id") %>'

Note: Embed double quote in the double quote is not allowed.


问:
pytube: 'NoneType' object has no attribute 'span'
I try to follow pytube example for downloading video from YouTube:

```<code>from pytube import YouTube
video = YouTube('https://www.youtube.com/watch?v=BATOxzbVNno')
video.streams.all()
</code>```

and immediately get this error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-2556eb2eb903> in <module>()
      1 from pytube import YouTube
      2 video = YouTube('https://www.youtube.com/watch?v=BATOxzbVNno')
----> 3 video.streams.all()

5 frames
/usr/local/lib/python3.7/dist-packages/pytube/cipher.py in get_throttling_function_code(js)
    301     # Extract the code within curly braces for the function itself, and merge any split lines
    302     code_lines_list = find_object_from_startpoint(js, match.span()[1]).split('\n')
--> 303     joined_lines = "".join(code_lines_list)
    304
    305     # Prepend function definition (e.g. `Dea=function(a)`)

AttributeError: 'NoneType' object has no attribute 'span'
</code>```

Please help me. It worked fine just yesterday! Thanks a lot!

答:
Just ran into that error myself, seems it occurs quite frequently regardless of it getting temporary fixes.

Found a fix on github: NoneType object has no attribute 'span'

Just replace the function get_throttling_function_name with:

```<code>def get_throttling_function_name(js: str) -> str:
"""Extract the name of the function that computes the throttling parameter.

:param str js:
    The contents of the base.js asset file.
:rtype: str
:returns:
    The name of the function used to compute the throttling parameter.
"""
function_patterns = [
    # https://github.com/ytdl-org/youtube-dl/issues/29326#issuecomment-865985377
    # a.C&&(b=a.get("n"))&&(b=Dea(b),a.set("n",b))}};
    # In above case, `Dea` is the relevant function name
    r'a\.[A-Z]&&\(b=a\.get\("n"\)\)&&\(b=([^(]+)\(b\)',
]
logger.debug('Finding throttling function name')
for pattern in function_patterns:
    regex = re.compile(pattern)
    function_match = regex.search(js)
    if function_match:
        logger.debug("finished regex search, matched: %s", pattern)
        function_name = function_match.group(1)
        is_Array = True if '[' or ']' in function_name else False
        if is_Array:
            index = int(re.findall(r'\d+', function_name)[0])
            name = function_name.split('[')[0]
            pattern = r"var %s=\[(.*?)\];" % name
            regex = re.compile(pattern)
            return regex.search(js).group(1).split(',')[index]
        else:
            return function_name

raise RegexMatchError(
    caller="get_throttling_function_name", pattern="multiple"
)
</code>```

Body:
I try to follow pytube example for downloading video from YouTube:

from pytube import YouTube
video = YouTube('https://www.youtube.com/watch?v=BATOxzbVNno')
video.streams.all()

and immediately get this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-2556eb2eb903> in <module>()
      1 from pytube import YouTube
      2 video = YouTube('https://www.youtube.com/watch?v=BATOxzbVNno')
----> 3 video.streams.all()

5 frames
/usr/local/lib/python3.7/dist-packages/pytube/cipher.py in get_throttling_function_code(js)
    301     # Extract the code within curly braces for the function itself, and merge any split lines
    302     code_lines_list = find_object_from_startpoint(js, match.span()[1]).split('\n')
--> 303     joined_lines = "".join(code_lines_list)
    304
    305     # Prepend function definition (e.g. `Dea=function(a)`)

AttributeError: 'NoneType' object has no attribute 'span'

Please help me. It worked fine just yesterday! Thanks a lot!

Body:
Just ran into that error myself, seems it occurs quite frequently regardless of it getting temporary fixes.

Found a fix on github: NoneType object has no attribute 'span'

Just replace the function get_throttling_function_name with:

def get_throttling_function_name(js: str) -> str:
"""Extract the name of the function that computes the throttling parameter.

:param str js:
    The contents of the base.js asset file.
:rtype: str
:returns:
    The name of the function used to compute the throttling parameter.
"""
function_patterns = [
    # https://github.com/ytdl-org/youtube-dl/issues/29326#issuecomment-865985377
    # a.C&&(b=a.get("n"))&&(b=Dea(b),a.set("n",b))}};
    # In above case, `Dea` is the relevant function name
    r'a\.[A-Z]&&\(b=a\.get\("n"\)\)&&\(b=([^(]+)\(b\)',
]
logger.debug('Finding throttling function name')
for pattern in function_patterns:
    regex = re.compile(pattern)
    function_match = regex.search(js)
    if function_match:
        logger.debug("finished regex search, matched: %s", pattern)
        function_name = function_match.group(1)
        is_Array = True if '[' or ']' in function_name else False
        if is_Array:
            index = int(re.findall(r'\d+', function_name)[0])
            name = function_name.split('[')[0]
            pattern = r"var %s=\[(.*?)\];" % name
            regex = re.compile(pattern)
            return regex.search(js).group(1).split(',')[index]
        else:
            return function_name

raise RegexMatchError(
    caller="get_throttling_function_name", pattern="multiple"
)


问:
How to compare two dataframes and find the combination for which there is value in first dataframe but not in second
I have two pandas dataframes with same columns say name, jan, feb, march, april. I want to compare the two dataframes and find out the name, month combination for which I have value in my first dataframe but not in my second dataframe.

df1:

Name
jan
feb
March

ABC
125
225
NaN

DEF
NaN
30
214

df2:

Name
jan
feb
March

ABC
125
NaN
NaN

XYZ
254
130
NaN

Expected output:

Name
Month

ABC
feb

Def
feb

Def
March

I tried to merge the two dataframes, but it is not giving me the expected result. I'm not sure how to proceed with this.

答:
set_index to "Name" + stack + reset_index the DataFrames and outer merge on name and month. Then filter the merged DataFrame by the condition:

```<code>out = df1.set_index('Name').stack().reset_index().merge(df2.set_index('Name').stack().reset_index(), on=['Name','level_1'], how='outer')
out = out.loc[out['0_x'].notna() & out['0_y'].isna(), ['Name','level_1']].rename(columns={'level_1':'Month'})
</code>```

Output:

```<code>  Name  Month
1  ABC    feb
2  DEF    feb
3  DEF  March
</code>```

Body:
set_index to "Name" + stack + reset_index the DataFrames and outer merge on name and month. Then filter the merged DataFrame by the condition:

out = df1.set_index('Name').stack().reset_index().merge(df2.set_index('Name').stack().reset_index(), on=['Name','level_1'], how='outer')
out = out.loc[out['0_x'].notna() & out['0_y'].isna(), ['Name','level_1']].rename(columns={'level_1':'Month'})

Output:

  Name  Month
1  ABC    feb
2  DEF    feb
3  DEF  March


问:
Register hardware keyboard shortcuts in Android's help menu
Android supports external hardware keyboards as input, which may send keyboard shortcuts (e.g. Ctrl+A) in which there are some ways to program my app to accept shortcuts from external keyboards (e.g. like this: Custom keyboard shortcuts).

I came across this keyboard shortcut "help" screen in Android (activated by pressing OS + /) (see picture below)

and noticed some apps have some keyboard shortcuts directly registered within the system shortcuts help screen(these screens are not provided by the app, they can be found by pressing OS + /).

So far, the apps that I see that have this feature are:

Samsung Internet

Samsung One UI Home

Google Chrome

Chromium-based browsers (e.g. Brave)

Google Docs, Sheets, Slides

I cannot find any way to register my keyboard shortcuts in my app programmatically such that they will be recognised by the system. How can I possibly implement it in my app?

I do know iOS/iPadOS has such a feature.

Perhaps Android does have such a feature too? It seems like it would be quite useful to app developers and users, not sure why it's not documented at all in Android Developer documentation.

Thanks.

答:
This feature is not documented in the Android Developer website, so I had to search around.

Since it is supported by AOSP, this is not a proprietary method/function by Google. No root is required on your users' devices.

Since this feature is available in Chromium-based browsers, I decided to check up the open-source Chromium Android source code (a mirror on GitHub is available here by someone: https://github.com/kuoruan/Chromium-Android) and I have discovered how this feature is implemented.

The relevant lines are here:

https://github.com/kuoruan/Chromium-Android/blob/29ba2966ff145c9cb2492a971f9c03f879c5b9c9/app/src/main/java/org/chromium/chrome/browser/KeyboardShortcuts.java#L117

https://github.com/kuoruan/Chromium-Android/blob/29ba2966ff145c9cb2492a971f9c03f879c5b9c9/app/src/main/java/org/chromium/chrome/browser/ChromeTabbedActivity.java#L2135

In any Activity, you can override the method onProvideKeyboardShortcuts.
It provides 3 parameters: data, menu, and deviceId, in which we only need data here.

Here is the method signature:

fun onProvideKeyboardShortcuts(
        data: MutableList<KeyboardShortcutGroup>?,
        menu: Menu?,
        deviceId: Int
    )
```
<p><strong>This only works on API 24 (Android Nougat) and above.</strong></p>
<p><code>data</code> is a mutable list of <code>KeyboardShortcutGroup</code>, which is a group of keyboard shortcuts.</p>
<p>So, you can have multiple groups containing multiple shortcuts, useful for grouping the shortcuts for your users.</p>
<p>To register your shortcuts,</p>
<ol>
<li>Create a <code>KeyboardShortcutGroup</code>. This is required to store and group your keyboard shortcuts together. The class accepts a <code>CharSequence</code> as a parameter for the name of the group, so you have to use <code>getString(R.string.your_resource)</code> for string resources.</li>
</ol>
<pre class="lang-java prettyprint-override"><code>val keyboardShortcutGroup = KeyboardShortcutGroup(/* the name of your group here: */ "Test Group")
</code>```

Define your keyboard shortcuts. Keyboard shortcuts are defined using KeyboardShortcutInfo objects, which accepts 3 parameters in it's constructor - a label, the key(e.g. A/ Z/ 8/ 9), and the modifier key.

A single keyboard shortcut is created this way:

KeyboardShortcutInfo("Shortcut One" /*label*/, KeyEvent.KEYCODE_Z/*key*/, KeyEvent.META_ALT_ON/*modifier*/)
```
<p>You need to pass in key codes into the constructor for the key and the modifier key.<br>
The key and modifier key must be passed in seperately.</p>
<p>Here are the list of available key codes:
https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_0 (See those prefixed with <code>KEYCODE</code>)</p>
<p>Based on testing, the modifier keys which work are:</p>
<ul>
<li>Ctrl <code>META_CTRL_ON</code></li>
<li>Alt <code>META_ALT_ON</code></li>
<li>Shift <code>META_SHIFT_ON</code></li>
<li>Super/OS/Meta (see https://android.stackexchange.com/a/243218/307843) <code>META_META_ON</code></li>
<li>Function <code>META_FUNCTION_ON</code></li>
<li>Left/Right keys for all of these are also available(i.e. <code>META_ALT_LEFT_ON</code>)</li>
</ul>
<p><code>META_SYM_ON</code> may work(have not tested yet), but Caps Lock doesn't work.</p>
<p>To combine modifier keys,<br>
in Java, use the bitwise operator:
<code>KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_CTRL_ON</code><br>
in Kotlin, use the <code>or</code> operator:
<code>KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_CTRL_ON</code></p>
<ol start="3">
<li>To this <code>KeyboardShortcutGroup</code>, add shortcuts using <code>addItem</code>.</li>
</ol>
<pre class="lang-java prettyprint-override"><code>keyboardShortcutGroup.addItem(shortcut /* <-- the shortcut created earlier */)
</code>```

Add your KeyboardShortcutGroup to data

data.add(keyboardShortcutGroup)
```
<p>Your code should look like this:</p>
<pre class="lang-java prettyprint-override"><code>    override fun onProvideKeyboardShortcuts(
        data: MutableList<KeyboardShortcutGroup>?,
        menu: Menu?,
        deviceId: Int
    ) {
        super.onProvideKeyboardShortcuts(data, menu, deviceId)

        // Requires API 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            val keyboardShortcutGroup = KeyboardShortcutGroup("Test Group")
            keyboardShortcutGroup.addItem(KeyboardShortcutInfo("Shortcut One", KeyEvent.KEYCODE_Z, KeyEvent.META_ALT_ON))
            data?.add(keyboardShortcutGroup)
        }
    }
</code>```

You should see the end result:

You can use this to inform users of available shortcuts. Note that this does not implement them, it merely adds a listing to the Android shortcut menu.

Body:
This feature is not documented in the Android Developer website, so I had to search around.

Since it is supported by AOSP, this is not a proprietary method/function by Google. No root is required on your users' devices.

Since this feature is available in Chromium-based browsers, I decided to check up the open-source Chromium Android source code (a mirror on GitHub is available here by someone: https://github.com/kuoruan/Chromium-Android) and I have discovered how this feature is implemented.

The relevant lines are here:

https://github.com/kuoruan/Chromium-Android/blob/29ba2966ff145c9cb2492a971f9c03f879c5b9c9/app/src/main/java/org/chromium/chrome/browser/KeyboardShortcuts.java#L117

https://github.com/kuoruan/Chromium-Android/blob/29ba2966ff145c9cb2492a971f9c03f879c5b9c9/app/src/main/java/org/chromium/chrome/browser/ChromeTabbedActivity.java#L2135

In any Activity, you can override the method onProvideKeyboardShortcuts.
It provides 3 parameters: data, menu, and deviceId, in which we only need data here.

Here is the method signature:

fun onProvideKeyboardShortcuts(
        data: MutableList<KeyboardShortcutGroup>?,
        menu: Menu?,
        deviceId: Int
    )

This only works on API 24 (Android Nougat) and above.

data is a mutable list of KeyboardShortcutGroup, which is a group of keyboard shortcuts.

So, you can have multiple groups containing multiple shortcuts, useful for grouping the shortcuts for your users.

To register your shortcuts,

Create a KeyboardShortcutGroup. This is required to store and group your keyboard shortcuts together. The class accepts a CharSequence as a parameter for the name of the group, so you have to use getString(R.string.your_resource) for string resources.

val keyboardShortcutGroup = KeyboardShortcutGroup(/* the name of your group here: */ "Test Group")

Define your keyboard shortcuts. Keyboard shortcuts are defined using KeyboardShortcutInfo objects, which accepts 3 parameters in it's constructor - a label, the key(e.g. A/ Z/ 8/ 9), and the modifier key.

A single keyboard shortcut is created this way:

KeyboardShortcutInfo("Shortcut One" /*label*/, KeyEvent.KEYCODE_Z/*key*/, KeyEvent.META_ALT_ON/*modifier*/)

You need to pass in key codes into the constructor for the key and the modifier key.

The key and modifier key must be passed in seperately.

Here are the list of available key codes:
https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_0 (See those prefixed with KEYCODE)

Based on testing, the modifier keys which work are:

Ctrl META_CTRL_ON

Alt META_ALT_ON

Shift META_SHIFT_ON

Super/OS/Meta (see https://android.stackexchange.com/a/243218/307843) META_META_ON

Function META_FUNCTION_ON

Left/Right keys for all of these are also available(i.e. META_ALT_LEFT_ON)

META_SYM_ON may work(have not tested yet), but Caps Lock doesn't work.

To combine modifier keys,

in Java, use the bitwise operator:
KeyEvent.META_ALT_LEFT_ON | KeyEvent.META_CTRL_ON

in Kotlin, use the or operator:
KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_CTRL_ON

To this KeyboardShortcutGroup, add shortcuts using addItem.

keyboardShortcutGroup.addItem(shortcut /* <-- the shortcut created earlier */)

Add your KeyboardShortcutGroup to data

data.add(keyboardShortcutGroup)

Your code should look like this:

    override fun onProvideKeyboardShortcuts(
        data: MutableList<KeyboardShortcutGroup>?,
        menu: Menu?,
        deviceId: Int
    ) {
        super.onProvideKeyboardShortcuts(data, menu, deviceId)

        // Requires API 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            val keyboardShortcutGroup = KeyboardShortcutGroup("Test Group")
            keyboardShortcutGroup.addItem(KeyboardShortcutInfo("Shortcut One", KeyEvent.KEYCODE_Z, KeyEvent.META_ALT_ON))
            data?.add(keyboardShortcutGroup)
        }
    }

You should see the end result:

You can use this to inform users of available shortcuts. Note that this does not implement them, it merely adds a listing to the Android shortcut menu.


问:
Flatten audit table records into one combined record
I'm working with a BigQuery database table that holds history changes to different fields as separate events in a history table.

For example, take a table that has two fields:

Id
Food
Color

6
Bacon
Red

9
Salad
Green

Any changes to the values in this table would be output to a history table like:

History table

Change date
id
Field name
Field Value

17 Jan 2022
6
Food
Steak

19 Jan 2022
9
Color
Yellow

21 Jan 2022
6
Color
Blue

How can I transform the 'history' table so that it flattens the change values into a single inherited view of change state as shown below?

Transformed table

id
Date
Food
Color

6
17 Jan 2022
Steak
Red

9
19 Jan 2022
Salad
Yellow

6
21 jan 2022
Steak
Blue

答:
This requires to first PIVOT history table data then join to current data table. I use Access SQL but maybe can adapt the following:

Query1:

```<code>TRANSFORM First(History.FieldValue) AS FirstOfFieldValue
SELECT History.ChangeDate, History.ID
FROM History
GROUP BY History.ChangeDate, History.ID
PIVOT History.FieldName;
</code>```

Query2:

```<code>SELECT Data.ID, Query1.ChangeDate,
    IIf([Query1].[Color] IS NULL, [Data].[Color], [Query1].[Color]) AS C,
    IIf([Query1].[Food] IS NULL,[Data].[Food], [Query1].[Food]) AS F
FROM Query1 INNER JOIN Data ON Query1.ID = Data.ID;
</code>```

Body:
This requires to first PIVOT history table data then join to current data table. I use Access SQL but maybe can adapt the following:

Query1:

TRANSFORM First(History.FieldValue) AS FirstOfFieldValue
SELECT History.ChangeDate, History.ID
FROM History
GROUP BY History.ChangeDate, History.ID
PIVOT History.FieldName;

Query2:

SELECT Data.ID, Query1.ChangeDate,
    IIf([Query1].[Color] IS NULL, [Data].[Color], [Query1].[Color]) AS C,
    IIf([Query1].[Food] IS NULL,[Data].[Food], [Query1].[Food]) AS F
FROM Query1 INNER JOIN Data ON Query1.ID = Data.ID;


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
name - is unintialized in Base

also you have another problem:

```<code>  Base c = Child("2");
</code>```

I don't think it's what you want. Your code will create an instance of Base from casted Child. But I think you want work with Child instance based on Base interface; you should instead write:

```<code>  Base *c = new Child("2");
</code>```

also, to avoid future bugs, declare destructor in base as virtual.

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
name - is unintialized in Base

also you have another problem:

  Base c = Child("2");

I don't think it's what you want. Your code will create an instance of Base from casted Child. But I think you want work with Child instance based on Base interface; you should instead write:

  Base *c = new Child("2");

also, to avoid future bugs, declare destructor in base as virtual.

OwnerDisplayName: bb

ContentLicense: CC BY-SA 3.0


问:
Subtraction of numbers double and long
In my JAVA program there is code like this:

```<code>int f_part = (int) ((f_num - num) * 100);
</code>```

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.

答: This is one of the most often asked (and answered) questions. Floating point arithmetics can not produce exact results, because it's impossible to have an inifinity of real numbers inside 64 bits. Use BigDecimal if you need arbitrary precision.</p>

Title: Subtraction of numbers double and long

Body:
In my JAVA program there is code like this:

int f_part = (int) ((f_num - num) * 100);

f_num is double and num is long. I just want to take the fractional part out and assign it to f_part. But some times f_part value is one less than it's value. Which means if f_num = 123.55 and num = 123, But f_part equals to 54. And it happens only f_num and num is greater than 100. I don't know why this happening. Please can someone explain why this happens and way to correct it.


问:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()
</code>```

password_generator.kv

```<code>#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()
</code>```

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

```<code>Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'
</code>```

How to resolve?

答:
first the text field has to be limited to support only integers by adding the input_filter: "int"

```<code>TextInput:
    id: input_entry
    text: ''
    multiline: False
    font_family: 'Helvatica'
    font_size: 24
    pos_hint: {'x': .8, 'y':4.5}
    size_hint: (2, .4)
    halign: "center"
    focus: True
    color: 'black'
    input_filter: "int"
</code>```

Body:
I am developing a Kivy password generator. The user is required to input a number (digit) into the app for password generate depending on how many characters are intended. Then, the app will generate a random character from the randint, finally, the output will be displayed into the output entry for a copy to the click board. Following are my code:

password_generator.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.core.window import Window

from random  import randint

Builder.load_file('password_generator.kv')

Window.size = (350, 600)

class MainApp(App):
    title='Password Generator'
    def build(self):
        Window.clearcolor = (255/255, 255/255, 0, 1)
        return Mylayout()

    def password(self):

        self.root.ids.output_entry = ''

        pw_length = int(self.root.ids.input_entry)

        my_password = ''

        for x in range(pw_length):
            my_password += chr(randint(33, 126))

        self.root.ids.output_entry = my_password

    def clip_board(self):
        self.root.clipboard_clear()

        self.root.clipboard_append(self.root.ids.output_entry)

    def delete(self):
        self.root.ids.input_entry = ''
        self.root.ids.output_entry = ''

class Mylayout(Widget):
    pass

if __name__ == '__main__':
    MainApp().run()

password_generator.kv

#:import Factory kivy.factory.Factory

<MyLayout>

    FloatLayout:

        Label:
            id: label_frame
            text: 'How Many Characters?'
            pos_hint: {'x': .8, 'y':5}
            size_hint: (2, .4)
            color: (0, 0, 0, 1)
            font_size: 24

        TextInput:
            id: input_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':4.5}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'

        Button:
            text:'Generate A Strong Password'
            on_press: app.password()
            pos_hint: {'x': .8, 'y':3.8}
            size_hint: (2, .4)
            font_size: 15

        TextInput:
            id: output_entry
            text: ''
            multiline: False
            font_family: 'Helvatica'
            font_size: 24
            pos_hint: {'x': .8, 'y':3}
            size_hint: (2, .4)
            halign: "center"
            focus: True
            color: 'black'
            background_color : (255/255, 255/255, 0, 1)
            #foreground_color:  self.background_color
            color : 'black'

        Button:
            text : 'Copy To Clickboard'
            on_release: Factory.MyPopup().open(),
            on_press: app.clip_board()
            pos_hint: {'x': .8, 'y':2.5}
            size_hint: (2, .4)
            font_size: 15

        Button:
            text : "Reset"
            on_press : app.delete()
            pos_hint: {'x': .8, 'y':1.5}
            size_hint: (2, .4)
            font_size: 15

<MyPopup@Popup>
    # auto_dismiss: False
    auto_dismiss: True
    size_hint: 0.6, 0.2
    pos_hint: {'x':0.2, 'top':0.6}

    title: "Message Informed"

    BoxLayout
        orientation: "vertical"
        size: root.width, root.height
        Label:
            text: "Password Copied!"
            font_size: 15
        Button:
            text: "Close!"
            font_size: 15
            on_release: root.dismiss()

When I click Generate Strong Password button and was required to output a random password character in the output entry, however, the following error was incurred:

Traceback (most recent call last):
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 53, in <module>
     MainApp().run()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Kelvin Loh\Documents\kivyMD\kivy_venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Kelvin Loh\Documents\kivyMD\password_generator.kv", line 30, in <module>
     on_press: app.password()
   File "c:\Users\Kelvin Loh\Documents\kivyMD\password_generator.py", line 24, in password
     pw_length = int(self.root.ids.input_entry)
   File "kivy\weakproxy.pyx", line 254, in kivy.weakproxy.WeakProxy.__int__
 TypeError: int() argument must be a string, a bytes-like object or a number, not 'TextInput'

How to resolve?

Body:
first the text field has to be limited to support only integers by adding the input_filter: "int"

TextInput:
    id: input_entry
    text: ''
    multiline: False
    font_family: 'Helvatica'
    font_size: 24
    pos_hint: {'x': .8, 'y':4.5}
    size_hint: (2, .4)
    halign: "center"
    focus: True
    color: 'black'
    input_filter: "int"


问:
R: Using Qvalue, how do I find the number of SNPS that have FDR adjusted p-values of p<.05?
I want to find the number of SNPS that have FDR adjusted p-values of p<.05. However, my for loop and if statement did not effectively find the # of SNPs with p<.05.

My dataset has a P column which indicates p-value and 1422 observations.

```<code>> dput(dat[1:5,])
structure(list(CHR = c(6L, 6L, 6L, 6L, 6L), SNP = c("rs9257319",
"rs2269553", "rs2894066", "rs3763338", "rs1233508"), BP = c(28959616L,
28984488L, 29001906L, 29002290L, 29005612L), A1 = c(2L, 1L, 1L,
1L, 2L), A2 = c(1L, 2L, 2L, 2L, 1L), T = c(6L, 9L, 13L, 4L, 8L
), U = c(7L, 9L, 9L, 3L, 13L), OR = c(0.8571, 1, 1.444, 1.333,
0.6154), L95 = c(0.2881, 0.397, 0.6174, 0.2984, 0.2551), U95 = c(2.55,
2.519, 3.379, 5.957, 1.485), CHISQ = c(0.07692, 0, 0.7273, 0.1429,
1.19), P = c(0.7815, 1, 0.3938, 0.7055, 0.2752)), row.names = c(NA,
5L), class = "data.frame")
</code>```

I calculated the q-values using the qvalue library.

```<code>library(qvalue)
library(dplyr)

fdr <- qvalue(dat$P, fdr.level=0.05)
</code>```

Finally, I want to find the number of SNPs with FDR adjusted p-values of p<.05.

```<code># SNPs that have FDR adjusted p-values of p<.05

for(i in fdr$qvalues){
  if(i>0.05){
    fdr[!fdr$qvalues %in% i]
  }
}
</code>```

And found that there is one q-value > 0.05 and removed it. However, as shown below, the length of fdr$qvalues remain the same, meaning that I did not remove the q-value > 0.05 element.

```<code>length(fdr$qvalues)
[1] 1422
</code>```

Body:
I want to find the number of SNPS that have FDR adjusted p-values of p<.05. However, my for loop and if statement did not effectively find the # of SNPs with p<.05.

My dataset has a P column which indicates p-value and 1422 observations.

> dput(dat[1:5,])
structure(list(CHR = c(6L, 6L, 6L, 6L, 6L), SNP = c("rs9257319",
"rs2269553", "rs2894066", "rs3763338", "rs1233508"), BP = c(28959616L,
28984488L, 29001906L, 29002290L, 29005612L), A1 = c(2L, 1L, 1L,
1L, 2L), A2 = c(1L, 2L, 2L, 2L, 1L), T = c(6L, 9L, 13L, 4L, 8L
), U = c(7L, 9L, 9L, 3L, 13L), OR = c(0.8571, 1, 1.444, 1.333,
0.6154), L95 = c(0.2881, 0.397, 0.6174, 0.2984, 0.2551), U95 = c(2.55,
2.519, 3.379, 5.957, 1.485), CHISQ = c(0.07692, 0, 0.7273, 0.1429,
1.19), P = c(0.7815, 1, 0.3938, 0.7055, 0.2752)), row.names = c(NA,
5L), class = "data.frame")

I calculated the q-values using the qvalue library.

library(qvalue)
library(dplyr)

fdr <- qvalue(dat$P, fdr.level=0.05)

Finally, I want to find the number of SNPs with FDR adjusted p-values of p<.05.

# SNPs that have FDR adjusted p-values of p<.05

for(i in fdr$qvalues){
  if(i>0.05){
    fdr[!fdr$qvalues %in% i]
  }
}

And found that there is one q-value > 0.05 and removed it. However, as shown below, the length of fdr$qvalues remain the same, meaning that I did not remove the q-value > 0.05 element.

length(fdr$qvalues)
[1] 1422

Body:
library(tidyverse)

# slightly modified p values to see the result
data <- structure(list(CHR = c(6L, 6L, 6L, 6L, 6L), SNP = c(
  "rs9257319",
  "rs2269553", "rs2894066", "rs3763338", "rs1233508"
), BP = c(
  28959616L,
  28984488L, 29001906L, 29002290L, 29005612L
), A1 = c(
  2L, 1L, 1L,
  1L, 2L
), A2 = c(1L, 2L, 2L, 2L, 1L), T = c(6L, 9L, 13L, 4L, 8L), U = c(7L, 9L, 9L, 3L, 13L), OR = c(
  0.8571, 1, 1.444, 1.333,
  0.6154
), L95 = c(0.2881, 0.397, 0.6174, 0.2984, 0.2551), U95 = c(
  2.55,
  2.519, 3.379, 5.957, 1.485
), CHISQ = c(
  0.07692, 0, 0.7273, 0.1429,
  1.19
), P = c(0.001, 1, 0.3, 0.01, 0.5)), row.names = c(
  NA,
  5L
), class = "data.frame")

data
#>   CHR       SNP       BP A1 A2  T  U     OR    L95   U95   CHISQ     P
#> 1   6 rs9257319 28959616  2  1  6  7 0.8571 0.2881 2.550 0.07692 0.001
#> 2   6 rs2269553 28984488  1  2  9  9 1.0000 0.3970 2.519 0.00000 1.000
#> 3   6 rs2894066 29001906  1  2 13  9 1.4440 0.6174 3.379 0.72730 0.300
#> 4   6 rs3763338 29002290  1  2  4  3 1.3330 0.2984 5.957 0.14290 0.010
#> 5   6 rs1233508 29005612  2  1  8 13 0.6154 0.2551 1.485 1.19000 0.500

data %>%
  mutate(q = p.adjust(P, method = "fdr")) %>%
  filter(q < 0.05)
#>   CHR       SNP       BP A1 A2 T U     OR    L95   U95   CHISQ     P     q
#> 1   6 rs9257319 28959616  2  1 6 7 0.8571 0.2881 2.550 0.07692 0.001 0.005
#> 2   6 rs3763338 29002290  1  2 4 3 1.3330 0.2984 5.957 0.14290 0.010 0.025

data %>%
  mutate(q = p.adjust(P, method = "fdr")) %>%
  filter(q < 0.05) %>%
  count()
#>   n
#> 1 2

Created on 2022-02-10 by the reprex package (v2.0.0)


问:
Extracting substring with awk if the string includes regular expressions
I have many strings like this

```<code>i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt
</code>```

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

答:
You have your awk answers, but I felt like contributing a bash idea just for fun.

[[ "$i" =~ ^\./([[:alnum:]]+)(/[[:alnum:]]+){3}/([[:alnum:]]+)/.* ]] \
    && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[3]}"
```
<p><code>BASH_REMATCH</code> array matches the capture groups in the test case. Index <code>0</code> is the complete string.</p>
<hr />
<p>A slightly shorter version yielding the same output:</p>
<pre class="lang-sh prettyprint-override"><code>[[ "$i" =~ ^\./(.+)(/.+){4}/.* ]] \
    && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]:1}"
</code>```

Body:
I have many strings like this

i=./M1/CustomersList/HTP/Boston/FCT/output_GetCaseList_abs.txt

I need to extract the M1 code and the FCT but I am unable to do so, likely due to the regular expressions. FCT I can do with echo ${i:30:3}, but for M1 nothing seems to work - my last try was grep -oP '.*\K(?<=.\/)\w+(?=\/Cus)' $i ;

The length of the string can vary (but it always starts with /F) and /M1/ is always in the same position

Hope somebody can help. Thanks!

Body:
You have your awk answers, but I felt like contributing a bash idea just for fun.

[[ "$i" =~ ^\./([[:alnum:]]+)(/[[:alnum:]]+){3}/([[:alnum:]]+)/.* ]] \
    && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[3]}"

BASH_REMATCH array matches the capture groups in the test case. Index 0 is the complete string.

A slightly shorter version yielding the same output:

[[ "$i" =~ ^\./(.+)(/.+){4}/.* ]] \
    && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]:1}"


问:
Annotate one (or more) values in a typescript string literal union as deprecated
I know it's possible to annotate entire properties as deprecated, but is it possible to annotated one (or more) single values within a string union as deprecated?

For example, given this type declaration:

```<code>export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};
</code>```

...my IDE (VS Code) will warn me that the rounded param is deprecated and will show it as visually "crossed out".

But If I try to annotate one single value of the variant string literal union type, my IDE will suggest all possible options with no warnings or visual treatments indicating that any string is deprecated:

```<code>TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    /** @deprecated */
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey' /** @deprecated */
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | /** @deprecated */ 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};
</code>```

Is this just not possible? Or is there some other syntax that needs to be used to annotate single strings as deprecated? (Or am I missing a VS Code plugin?)

答:
@depecated support has landed with TS 4.0 in 2020.

It was discussed on the ticket about it, but no at the moment union and insertion type members don't support TSDoc at all.

Body:
I know it's possible to annotate entire properties as deprecated, but is it possible to annotated one (or more) single values within a string union as deprecated?

For example, given this type declaration:

export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

...my IDE (VS Code) will warn me that the rounded param is deprecated and will show it as visually "crossed out".

But If I try to annotate one single value of the variant string literal union type, my IDE will suggest all possible options with no warnings or visual treatments indicating that any string is deprecated:

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    /** @deprecated */
    | 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | 'grey' /** @deprecated */
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

// or

TypeScript
export type BoxProps = HTMLAttributes<HTMLDivElement> & {
  /**
   * @deprecated rounded has no effect and will be removed in a future version
   */
  rounded?: boolean;
  variant?:
    | 'neutral'
    | /** @deprecated */ 'grey'
    | 'success'
    | 'warning';
  thickBorder?: boolean;
};

Is this just not possible? Or is there some other syntax that needs to be used to annotate single strings as deprecated? (Or am I missing a VS Code plugin?)


问:
ASP.NET MVC 3 - WebGrid paging problems and general confusion
I am relatively new at using ASP.NET MVC, however I have got experience with using Web Forms.

My page has some cascading selects which in turn ajax load the next and finally reload the contents of the ajax tabs (jQuery UI).

One of the tabs has a search button which when submitted via jQuery loads a partial view into the given div using the code below:

```<code>      $("#frm_Search").submit(function (e) {
          if ($("#frm_Search").valid()) {
              e.preventDefault();
              $.post('@Url.Action("SearchResult", "Info")', {CCode:"", Period:"201108", Type:"XYZ"}, function (result) {
                  $('#div_SearchResult').html(result);
              });
          }

      })
</code>```

However when I click on the paging links for the WebGrid the parameters get nulled and thus no data rendered.

I would be greatful for any advice or guidance as I am unsure if I am going about solving this problem correctly.

See the below diagram for a clearer indication of my page structure.

答:
The problem is the Webgrid's self-generated paging links do not propagate any QSPs other than the ones it needs.  This also causes headaches for people trying to add filtering to the Webgrid.

I have an answer on another question that shows how you can facilitate getting QSPs back into the page links, but it involves generating them yourself via a Razor helper.

Asp.net Mvc3 webgrid and paging
There are code fragments in there to inspire you.

Body:
I am relatively new at using ASP.NET MVC, however I have got experience with using Web Forms.

My page has some cascading selects which in turn ajax load the next and finally reload the contents of the ajax tabs (jQuery UI).

One of the tabs has a search button which when submitted via jQuery loads a partial view into the given div using the code below:

      $("#frm_Search").submit(function (e) {
          if ($("#frm_Search").valid()) {
              e.preventDefault();
              $.post('@Url.Action("SearchResult", "Info")', {CCode:"", Period:"201108", Type:"XYZ"}, function (result) {
                  $('#div_SearchResult').html(result);
              });
          }

      })

However when I click on the paging links for the WebGrid the parameters get nulled and thus no data rendered.

I would be greatful for any advice or guidance as I am unsure if I am going about solving this problem correctly.

See the below diagram for a clearer indication of my page structure.


问:
How to write procedure which will loop the input line N times in TCL
looking for what could be the "proc_of_for_loop"

puts $fp [proc_of_for_loop abc[$i] 5]

output should be like,

```<code>abc0
abc1
abc2
abc3
abc4
abc5
</code>```

答:
Here's the "substitute and collect" approach.  Less general than Donal's solution, but closer to what's requested, and not significantly more complicated IMHO:</p>
```<code>proc string_for {string count} {
    for {set i 1} {$i <= count} {incr i} {
        append result [subst $string]
    }
    return $result
}

puts $fp [string_for {abc$i\n} 5]
</code>```

Body:
looking for what could be the "proc_of_for_loop"

puts $fp [proc_of_for_loop abc[$i] 5]

output should be like,

abc0
abc1
abc2
abc3
abc4
abc5

Body:
Here's the "substitute and collect" approach.  Less general than Donal's solution, but closer to what's requested, and not significantly more complicated IMHO:

proc string_for {string count} {
    for {set i 1} {$i <= count} {incr i} {
        append result [subst $string]
    }
    return $result
}

puts $fp [string_for {abc$i\n} 5]


问:
How to open new tab from background.js in Chrome Extension (Manifest v3)?
I am stuck with creating new tabs in background.js.

chrome.tabs.create({url: 'https://google.com'}) - doesn’t work, because background.js - is service worker in chrome extensions with (Manifest v3).

答:
It happened because I use setTimeut() for executing new tab after some time.

const installationTme = new Date().getTime();
const _timestamp = 10*1000;
function ShowNewPage(){
  if (new Date().getTime() >= installationTme + _timestamp){
     chrome.tabs.create({'url': `https://google.com`}, function(tab) {});
  } else {
     return setTimeout(() => showFeedbackPage(), 2*1000);
  }
}
```


问:
How to know what caused a simple DAG in Apache Airflow to fail?
I am new to Apache Airflow.
I wanted to create a simple DAG with a single Task that launches a python script in a virtual environment:

```<code>from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash import BashOperator
with DAG("Inference_DAG",
        start_date=datetime(2022,1,1),
        schedule_interval=timedelta(hours=12),
        catchup=False,
        max_active_runs=1
        ) as dag:

    task_a = BashOperator(
        task_id="Inference_task_a",
        bash_command="/home/xfd/folder/env/bin/python3 compute.py",
        retries =1,

    )
</code>```

When triggering the DAG, it failed.

How can I know more about what causes the failure? I have seen that Airflow integrates with Sentry (https://airflow.apache.org/docs/apache-airflow/stable/logging-monitoring/errors.html?highlight=error). However, it might be overkill for simple dags like this one.

Ideally, I would like to get the output of the console command /home/xfd/folder/env/bin/python3 compute.py to debug what went wrong easily.
How can I track errors in Apache Airflow for a simple DAG like this one?

答: If you enter into the DAG and click on the task that is in red, you can then click on "Log" and there you will see the error

Body:
I am new to Apache Airflow.
I wanted to create a simple DAG with a single Task that launches a python script in a virtual environment:

from airflow import DAG
from datetime import datetime, timedelta
from airflow.operators.bash import BashOperator
with DAG("Inference_DAG",
        start_date=datetime(2022,1,1),
        schedule_interval=timedelta(hours=12),
        catchup=False,
        max_active_runs=1
        ) as dag:

    task_a = BashOperator(
        task_id="Inference_task_a",
        bash_command="/home/xfd/folder/env/bin/python3 compute.py",
        retries =1,

    )

When triggering the DAG, it failed.

How can I know more about what causes the failure? I have seen that Airflow integrates with Sentry (https://airflow.apache.org/docs/apache-airflow/stable/logging-monitoring/errors.html?highlight=error). However, it might be overkill for simple dags like this one.

Ideally, I would like to get the output of the console command /home/xfd/folder/env/bin/python3 compute.py to debug what went wrong easily.
How can I track errors in Apache Airflow for a simple DAG like this one?


问:
Blazor WebAssembly CSS isolation scoped identities doesn't match
In a Blazor WebAssembly .NET Core hosted application, after changing the {PROJECT NAME}.Client project name to "{PROJECT NAME}.Admin" (changing the client project name), scope identifies for CSS isolation in the {PROJECT NAME}.Admin.styles.css file and rendered objects in the DOM are different.

What I did

I created a .NET core hosted Blazor WebAssembly application with authentication. Ran the application. Worked fine.

Then I changed the project name of {PROJECT NAME}. Client project to "{PROJECT NAME}.Admin". And changed basically everywhere there was "Client" to "Admin".

Everywhere the namespace was mentioned

The Client Folder in the project folder

Then I added the project references.

When I ran the project...
This was the landing page.

The Issue

All the functionality works fine. All the components are rendered. But only Bootstrap styling is applied to the MainLayout and NavMenu components as they use CSS isolation. The isolated CSS files generated files scope identities aren't the same as what is rendered to the DOM.

Image of {PROJECT NAME}.Admin.styles.css file

Image of Rendered HTML

The page renders fine if I change the scope Identities manually. But it resets when I Run the application the next time.

I'm just playing around with Blazor. So I'm expecting a fix to this problem rather than some alternate method or workaround to do the styling. I'm new to online forums. Sorry for providing unnecessary information or providing less information. Please request any additional information needed.

答: I had the same issue. Rebuilding the solution fixed it for me. Possibly rebuilding just the relevant application would have been enough too.


问:
Populate View Model / ModelState.IsValid
I can't quite wrap my head around the model validation. Let's assume the following ViewModel:

```<code>public class UserEditViewModel
{
    public List<Role> AvailableRoles { get; set; }
    public string? SelectedRole { get; set; }
}
</code>```

The goal is to let the user select from a list of roles (think of a dropdown).

In the HttpGet I populate the list of available roles form a database like this:

```<code>UserEditViewModel uevm = new UserEditViewModel();
uevm.AvailableRoles = _db.Roles.ToList();
</code>```

When I get the UserEditViewModel back from the HttpPost event, it will have an invalid model state:

```<code>if (ModelState.IsValid) { ...}
</code>```

The validation will state that while the SelectedRole is valid, the list of available roles is NOT valid.

Now I can think of multiple solutions to this problem but am unsure on how to proceed:

I could create a custom constructor for the UserEditViewModel which populates the AvailableRoles list from a database. But this means that I will need to pass a reference to the database context into the UserEditViewModel

I could simply ignore the ModelState because I know it is invalid? What would I lose in this case?

I had some hope hat the Bind property would maybe help like this:

```<code>public ActionResult EditUser([Bind(include:"SelectedRole")] UserEditViewModel editViewModel, string id)
</code>```

but it appears that ModelState is still invalid even if I specify I only want the SelectedRole.

This leads me to the ultimate question: What is the correct way to approach this issue?

答:
Try to apply [ValidateNever] attribute to remove validate an unused property on the server side:

public class UserEditViewModel
{
    [ValidateNever]
    public List<Role> AvailableRoles { get; set; }
    public string? SelectedRole { get; set; }
}
```

From the documentation:

Indicates that a property or parameter should be excluded from
validation. When applied to a property, the validation system excludes
that property. When applied to a parameter, the validation system
excludes that parameter. When applied to a type, the validation system
excludes all properties within that type.

But if it's necessary to avoid validation only when returning model data from a specific view use ModelState.Remove("AvailableRoles"); before if (ModelState.IsValid) {...}.

Body:
I can't quite wrap my head around the model validation. Let's assume the following ViewModel:

public class UserEditViewModel
{
    public List<Role> AvailableRoles { get; set; }
    public string? SelectedRole { get; set; }
}

The goal is to let the user select from a list of roles (think of a dropdown).

In the HttpGet I populate the list of available roles form a database like this:

UserEditViewModel uevm = new UserEditViewModel();
uevm.AvailableRoles = _db.Roles.ToList();

When I get the UserEditViewModel back from the HttpPost event, it will have an invalid model state:

if (ModelState.IsValid) { ...}

The validation will state that while the SelectedRole is valid, the list of available roles is NOT valid.

Now I can think of multiple solutions to this problem but am unsure on how to proceed:

I could create a custom constructor for the UserEditViewModel which populates the AvailableRoles list from a database. But this means that I will need to pass a reference to the database context into the UserEditViewModel

I could simply ignore the ModelState because I know it is invalid? What would I lose in this case?

I had some hope hat the Bind property would maybe help like this:

public ActionResult EditUser([Bind(include:"SelectedRole")] UserEditViewModel editViewModel, string id)

but it appears that ModelState is still invalid even if I specify I only want the SelectedRole.

This leads me to the ultimate question: What is the correct way to approach this issue?

Body:
Try to apply [ValidateNever] attribute to remove validate an unused property on the server side:

public class UserEditViewModel
{
    [ValidateNever]
    public List<Role> AvailableRoles { get; set; }
    public string? SelectedRole { get; set; }
}

From the documentation:

Indicates that a property or parameter should be excluded from
validation. When applied to a property, the validation system excludes
that property. When applied to a parameter, the validation system
excludes that parameter. When applied to a type, the validation system
excludes all properties within that type.

But if it's necessary to avoid validation only when returning model data from a specific view use ModelState.Remove("AvailableRoles"); before if (ModelState.IsValid) {...}.


问:
regex extract email from strings
I want to know if by using regular expressions I am able to extract emails from the following strings?

The following RE pattern is .*@.*match with all strings. It has worked fine with some of the string, though with not all.

I want to match all strings match with email pattern include all domain like (some-url.com) or (some-url.co.id)

```<code>boleh di kirim ke email saya ekoprasetyo.crb@outlook.com tks...
boleh minta kirim ke db.maulana@gmail.com.
dee.wien@yahoo.com. .
deninainggolan@yahoo.co.id Senior Quantity Surveyor
Fajar.rohita@hotmail.com, terimakasih bu Cindy Hartanto
firmansyah1404@gmail.com saya mau dong bu cindy
fransiscajw@gmail.com
Hi Cindy ...pls share the Salary guide to donny_tri_wardono@yahoo.co.id thank a
</code>```

答:
```<code>\W([\w\-\.]+@[\w\-\.]+)+\W
</code>```

will find all emails in the string

Title: regex extract email from strings

Body:
I want to know if by using regular expressions I am able to extract emails from the following strings?

The following RE pattern is .*@.*match with all strings. It has worked fine with some of the string, though with not all.

I want to match all strings match with email pattern include all domain like (some-url.com) or (some-url.co.id)

boleh di kirim ke email saya ekoprasetyo.crb@outlook.com tks...
boleh minta kirim ke db.maulana@gmail.com.
dee.wien@yahoo.com. .
deninainggolan@yahoo.co.id Senior Quantity Surveyor
Fajar.rohita@hotmail.com, terimakasih bu Cindy Hartanto
firmansyah1404@gmail.com saya mau dong bu cindy
fransiscajw@gmail.com
Hi Cindy ...pls share the Salary guide to donny_tri_wardono@yahoo.co.id thank a

Body:
\W([\w\-\.]+@[\w\-\.]+)+\W

will find all emails in the string


问:
Split Connection String
In a WinForm Application I Store My ConnectionString in App.Confing File.How Can I split this connectionstring to some Data like username,DataBaseName,Password and other thing Dynamically?</p>

答:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.aspx

And what you exactly need is:
http://msdn.microsoft.com/en-us/library/d7z89tex.aspx

Title: Split Connection String


问:
TelephonyManager deprecated listen() CALL_STATE_RINGING on android 12
I'd like to listen if there's a phone call happening while my app is in the foreground.

It was like this before but now listen() is deprecated:

```<code>val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            tm.listen(object : PhoneStateListener() {
                override fun onCallStateChanged(state: Int, phoneNumber: String?) {
                    super.onCallStateChanged(state, phoneNumber)
                    when (state) {
                        TelephonyManager.CALL_STATE_RINGING -> transcribingAudioConsumer.stopTranscription(null)
                        else -> {}
                    }
                }
            }, PhoneStateListener.LISTEN_CALL_STATE)
</code>```

I tried something like this but I couldn't find the correct way to implement it.

```<code>         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        tm.registerTelephonyCallback({ it.run() }, MyPhoneStateListener())
                    }
</code>```
```<code>  @RequiresApi(Build.VERSION_CODES.S)
    class MyPhoneStateListener : TelephonyCallback(), TelephonyCallback.CallStateListener {
        override fun onCallStateChanged(state: Int) {
            when (state) {
                TelephonyManager.CALL_STATE_RINGING -> {
                    Timber.e("omg RING")
                }

                TelephonyManager.CALL_STATE_OFFHOOK -> {
                    Timber.e("omg hook")
                }
                TelephonyManager.CALL_STATE_IDLE -> {
                    Timber.e("omg idle")
                }
            }
        }
    }
</code>```

答:
Since the listen method is deprecated since api 31 android 12 I made a simple way to listen to the telephony callbacks.

val telephonyManager: TelephonyManager =
    context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    telephonyManager.registerTelephonyCallback(
        context.mainExecutor,
        object : TelephonyCallback(), TelephonyCallback.CallStateListener {
            override fun onCallStateChanged(state: Int) {
            }
        })
} else {
    telephonyManager.listen(object : PhoneStateListener() {
        override fun onCallStateChanged(state: Int, phoneNumber: String?) {
        }
    }, PhoneStateListener.LISTEN_CALL_STATE)
}
```
<p>Note that the new callback does not include a phone number.
At least for broadcast receiver the phone number can be retrieved via</p>
```intent.extras.getString("incoming_number")
```

Body:
I'd like to listen if there's a phone call happening while my app is in the foreground.

It was like this before but now listen() is deprecated:

val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            tm.listen(object : PhoneStateListener() {
                override fun onCallStateChanged(state: Int, phoneNumber: String?) {
                    super.onCallStateChanged(state, phoneNumber)
                    when (state) {
                        TelephonyManager.CALL_STATE_RINGING -> transcribingAudioConsumer.stopTranscription(null)
                        else -> {}
                    }
                }
            }, PhoneStateListener.LISTEN_CALL_STATE)

I tried something like this but I couldn't find the correct way to implement it.

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        tm.registerTelephonyCallback({ it.run() }, MyPhoneStateListener())
                    }

  @RequiresApi(Build.VERSION_CODES.S)
    class MyPhoneStateListener : TelephonyCallback(), TelephonyCallback.CallStateListener {
        override fun onCallStateChanged(state: Int) {
            when (state) {
                TelephonyManager.CALL_STATE_RINGING -> {
                    Timber.e("omg RING")
                }

                TelephonyManager.CALL_STATE_OFFHOOK -> {
                    Timber.e("omg hook")
                }
                TelephonyManager.CALL_STATE_IDLE -> {
                    Timber.e("omg idle")
                }
            }
        }
    }

Body:
Since the listen method is deprecated since api 31 android 12 I made a simple way to listen to the telephony callbacks.

val telephonyManager: TelephonyManager =
    context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    telephonyManager.registerTelephonyCallback(
        context.mainExecutor,
        object : TelephonyCallback(), TelephonyCallback.CallStateListener {
            override fun onCallStateChanged(state: Int) {
            }
        })
} else {
    telephonyManager.listen(object : PhoneStateListener() {
        override fun onCallStateChanged(state: Int, phoneNumber: String?) {
        }
    }, PhoneStateListener.LISTEN_CALL_STATE)
}

Note that the new callback does not include a phone number.
At least for broadcast receiver the phone number can be retrieved via

intent.extras.getString("incoming_number")


问:
How to output Get-ADUser as csv without including the fieldnames in the first row using powershell?
I am trying to use the Get-ADUser to get a dump of the users in our system, and then output the contents to a CSV file.

However, I have not yet been able to figure out how to exclude the fieldnames from the first row in the csv file.

I want to have just the data [in csv format] but without the header row.

This code produces the data I want:

```<code>Get-ADUser -Filter * -SearchBase "OU=My,OU=OrganisationName,OU=Accounts,OU=Groups and Accounts,DC=myorg,DC=com" -Properties * |
    Sort-Object -Property sn, GivenName, UserPrincipalName |
        Select-Object name, sn, GivenName, UserPrincipalName |
            Export-Csv -Path "C:\temp1.csv" -NoTypeInformation
</code>```

But it insists on including the header row (despite the -NoTypeInformation flag).

I have tried piping the data through the command:

```<code>Format-Table  -HideTableHeaders
</code>```

Like so:

```<code>Get-ADUser -Filter * -SearchBase "OU=My,OU=OrganisationName,OU=Accounts,OU=Groups and Accounts,DC=myorg,DC=com" -Properties * |
    Sort-Object -Property sn, GivenName, UserPrincipalName |
        Select-Object name, sn, GivenName, UserPrincipalName |
            Format-Table -HideTableHeaders |
                Export-Csv -Path "C:\temp1.csv" -NoTypeInformation
</code>```

But this converts the data in the csv file to gibberish.

Does anyone have any thoughts on how I might get rid of the header row?

thanks heaps,

David :-)

答:
Instead of Export-CSV use ConvertTo-CSV skip the first line using Select-Object -Skip 1 then save the file using Out-File

instead of this:

```<code> [...]Select-Object name, sn, GivenName, UserPrincipalName |
            Export-Csv -Path "C:\temp1.csv" -NoTypeInformation
</code>```

Do:

```<code> [...]Select-Object name, sn, GivenName, UserPrincipalName |
 ConvertTo-Csv -NoTypeInformation | Select -Skip 1 |
 Out-File "C:\temp1.csv"
</code>```

Body:
I am trying to use the Get-ADUser to get a dump of the users in our system, and then output the contents to a CSV file.

However, I have not yet been able to figure out how to exclude the fieldnames from the first row in the csv file.

I want to have just the data [in csv format] but without the header row.

This code produces the data I want:

Get-ADUser -Filter * -SearchBase "OU=My,OU=OrganisationName,OU=Accounts,OU=Groups and Accounts,DC=myorg,DC=com" -Properties * |
    Sort-Object -Property sn, GivenName, UserPrincipalName |
        Select-Object name, sn, GivenName, UserPrincipalName |
            Export-Csv -Path "C:\temp1.csv" -NoTypeInformation

But it insists on including the header row (despite the -NoTypeInformation flag).

I have tried piping the data through the command:

Format-Table  -HideTableHeaders

Like so:

Get-ADUser -Filter * -SearchBase "OU=My,OU=OrganisationName,OU=Accounts,OU=Groups and Accounts,DC=myorg,DC=com" -Properties * |
    Sort-Object -Property sn, GivenName, UserPrincipalName |
        Select-Object name, sn, GivenName, UserPrincipalName |
            Format-Table -HideTableHeaders |
                Export-Csv -Path "C:\temp1.csv" -NoTypeInformation

But this converts the data in the csv file to gibberish.

Does anyone have any thoughts on how I might get rid of the header row?

thanks heaps,

David :-)

Body:
Instead of Export-CSV use ConvertTo-CSV skip the first line using Select-Object -Skip 1 then save the file using Out-File

instead of this:

 [...]Select-Object name, sn, GivenName, UserPrincipalName |
            Export-Csv -Path "C:\temp1.csv" -NoTypeInformation

Do:

 [...]Select-Object name, sn, GivenName, UserPrincipalName |
 ConvertTo-Csv -NoTypeInformation | Select -Skip 1 |
 Out-File "C:\temp1.csv"


问:
Smooth Circular Progressbar Animation Android
I am trying to create a smooth progressbar with a countdown timer. I want the timer will countdown upto 20 sec.I am using the below code but I unable to achieve the smooth decending of the progressbar. Countdown tick function is working fine with the progressbar, but not in case of smooth behaviour. I found the below code from stackoverflow which i used in my project, but can you tell me what i am doing wrong.

```<code> if(android.os.Build.VERSION.SDK_INT >= 11){
        // will update the "progress" propriety of seekbar until it reaches progress
        ObjectAnimator animation = ObjectAnimator.ofInt(progressBarTimer, "progress", 0, 500);
        animation.setDuration(20000); // 0.5 second
        animation.setInterpolator(new LinearInterpolator());
        animation.start();
    }
    else
        progressBarTimer.setProgress(100);
</code>```

答:
I achieved this by following code:</p>
```<code>val ORDER_ACCEPT_TIME = 5000L //5 seconds
val INTERVAL = 30

progressBar.max = ORDER_ACCEPT_TIMER_TIME

private fun startTimer(){
        pauseTimer = object : CountDownTimer(ORDER_ACCEPT_TIMER_TIME, INTERVAL){
            override fun onTick(millisUntilFinished: Long) {

                val secondsInMilli: Long = 1000

                val diff = millisUntilFinished
                val elapsedSeconds = diff / secondsInMilli

                val progress = INTERVAL + progressBar.progress
                progressBar.progress = progress.toInt()

                tvProgress.text = elapsedSeconds.toString() //(optional) to show countdown textview

            }

            override fun onFinish() {

            }
        }

        pauseTimer.start()
    }
</code>```

Body:
I am trying to create a smooth progressbar with a countdown timer. I want the timer will countdown upto 20 sec.I am using the below code but I unable to achieve the smooth decending of the progressbar. Countdown tick function is working fine with the progressbar, but not in case of smooth behaviour. I found the below code from stackoverflow which i used in my project, but can you tell me what i am doing wrong.

 if(android.os.Build.VERSION.SDK_INT >= 11){
        // will update the "progress" propriety of seekbar until it reaches progress
        ObjectAnimator animation = ObjectAnimator.ofInt(progressBarTimer, "progress", 0, 500);
        animation.setDuration(20000); // 0.5 second
        animation.setInterpolator(new LinearInterpolator());
        animation.start();
    }
    else
        progressBarTimer.setProgress(100);

Body:
I achieved this by following code:

val ORDER_ACCEPT_TIME = 5000L //5 seconds
val INTERVAL = 30

progressBar.max = ORDER_ACCEPT_TIMER_TIME

private fun startTimer(){
        pauseTimer = object : CountDownTimer(ORDER_ACCEPT_TIMER_TIME, INTERVAL){
            override fun onTick(millisUntilFinished: Long) {

                val secondsInMilli: Long = 1000

                val diff = millisUntilFinished
                val elapsedSeconds = diff / secondsInMilli

                val progress = INTERVAL + progressBar.progress
                progressBar.progress = progress.toInt()

                tvProgress.text = elapsedSeconds.toString() //(optional) to show countdown textview

            }

            override fun onFinish() {

            }
        }

        pauseTimer.start()
    }


问:
What should be the generic font family for Font-Awesome fonts?
I'm using FontAwesome 4.7 in one of my project and we have SonarQube integration. At few places in my custom CSS files, I've to provide Font-Family manually like:

```<code>.calendar-wrapper:after {
  font-family: 'FontAwesome';
  content: '\f073';
  position: absolute;
  right: 9px;
  top: 9px;
}
</code>```

But at this line, SonarQube shows me bug:
Unexpected missing generic font family (Rule Here)

What should be the generic font-family for FontAwesome? I looked everywhere on the internet but didn't found any solution yet.

答:
Based on the official documentation, you need to have a generic font in your font and font-family values. Generic fonts means serif or sans-serif and they works a fallback fonts in case the main font is not reachable which could be because of some privacy settings on user's browser.

Please check the official documentation here: https://stylelint.io/user-guide/rules/list/font-family-no-missing-generic-family-keyword/

Body:
I'm using FontAwesome 4.7 in one of my project and we have SonarQube integration. At few places in my custom CSS files, I've to provide Font-Family manually like:

.calendar-wrapper:after {
  font-family: 'FontAwesome';
  content: '\f073';
  position: absolute;
  right: 9px;
  top: 9px;
}

But at this line, SonarQube shows me bug:
Unexpected missing generic font family (Rule Here)

What should be the generic font-family for FontAwesome? I looked everywhere on the internet but didn't found any solution yet.


问:
How to limit grep to only search the files that you want
We have a rather large and complex file system and I am trying to generate a list of files containing a particular text string. This should be simple, but I need to exclude the './svn' and './pdv' directories (and probably others) and to only look at files of type *.p, *.w or .i.

I can easily do this with a program, but it is proving very slow to run. I want to speed up the process (so that I'm not searching thousands of files repeatedly) as I need to run such searches against a long list of criteria.

Normally, we search the file system using:

```<code>find . -name "*.[!r]*" -exec grep -i -l "search for me" {} \;
</code>```

This is working, but I'm then having to use a program to exclude the unwanted directories , so it is running very slowly.

After looking at the topics here:
Stack Overflow thread

I've decided to try a few other aproaches:

```<code>grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --exclude "!.{p,w,i*}"
</code>```

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

```<code>grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --include "*.p"
</code>```

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

```<code>find . -name "*.[!r]*" -exec grep -i -l ".svn" | grep -i -l "search for me" {} \;
</code>```

I can't even get this (or variations on it) to run successfully.

```<code>find . ! -name "*.svn*" -prune -print -exec grep -i -l "search for me" {} \;
</code>```

Doesn't return anything. It looks like it stops as soon as it finds the .svn directory.

答:
You can try the following:</p>

```<code>find path_starting_point -type f | grep regex_to_filter_file_names | xargs grep regex_to_find_inside_matched_files
</code>```

Body:
We have a rather large and complex file system and I am trying to generate a list of files containing a particular text string. This should be simple, but I need to exclude the './svn' and './pdv' directories (and probably others) and to only look at files of type *.p, *.w or .i.

I can easily do this with a program, but it is proving very slow to run. I want to speed up the process (so that I'm not searching thousands of files repeatedly) as I need to run such searches against a long list of criteria.

Normally, we search the file system using:

find . -name "*.[!r]*" -exec grep -i -l "search for me" {} \;

This is working, but I'm then having to use a program to exclude the unwanted directories , so it is running very slowly.

After looking at the topics here:
Stack Overflow thread

I've decided to try a few other aproaches:

grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --exclude "!.{p,w,i*}"

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --include "*.p"

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

find . -name "*.[!r]*" -exec grep -i -l ".svn" | grep -i -l "search for me" {} \;

I can't even get this (or variations on it) to run successfully.

find . ! -name "*.svn*" -prune -print -exec grep -i -l "search for me" {} \;

Doesn't return anything. It looks like it stops as soon as it finds the .svn directory.

Body:
You can try the following:

find path_starting_point -type f | grep regex_to_filter_file_names | xargs grep regex_to_find_inside_matched_files


问:
jQuery removechild / hide html element without page refresh
I am trying to customize a Joomla Quiz plugin like this:

a quiz question displays in the description an image / text, but it should disappear after 5 seconds.

I found a solution with Javascript for removechild or timer function to hide after 5 second, and it works properly.

the problem:

this Joomla quiz module is not refreshing the page per questions, because it works with Jquery and I don't have an initial loading point from the timer could count the 5 seconds.
(by the time you reach the question, the time expiries and disappear to early)

I cannot use a page reload, as the whole quiz would restart from first question.

is there any condition or solution with Jquery or Javascript to detect the content load only for that specific question?
(I mean some div or some conditional rule to fulfill before start counting)

I hope it is clear what I want to achieve :)

thanks in advance!

答:
You can check visibility of the element by checking it offset like that in javascript. From the moment element is visible just setTimeout.

Javascript

```<code>document.addEventListener("DOMContentLoaded", checkVisibility);

    function startCount(){alert('IsVisible')}

    function checkVisibility(){
        var div = document.getElementById('Element').offsetLeft
        if(div >0){
            setTimeout(startCount,5000)
        }
    }
</code>```

jQuery

```<code>if(  $("#Element").is(":visible") == true )
{
     alert("Div is visible!!");
}
</code>```

Body:
You can check visibility of the element by checking it offset like that in javascript. From the moment element is visible just setTimeout.

Javascript

document.addEventListener("DOMContentLoaded", checkVisibility);

    function startCount(){alert('IsVisible')}

    function checkVisibility(){
        var div = document.getElementById('Element').offsetLeft
        if(div >0){
            setTimeout(startCount,5000)
        }
    }

jQuery

if(  $("#Element").is(":visible") == true )
{
     alert("Div is visible!!");
}


问:
Only integer scalar arrays can be converted to a scalar index not running under Spyder
I have the following code, which runs well under Visual Studio Code with python 3.9.10, opencv 4.5.5 and numpy 1.22.1.

I would like to migrate this code into the Spyder IDE (Version 5, another notebook), python 3.8, opencv 4.5.1 and numpy 1.22.2.

In spyder, I get the error message TypeError: only integer scalar arrays can be converted a scalar index in line: output_layers = [layer_names[i-1]...] (marked line down in the code section)

I have already checked other answers on this site such as
TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index
which suggests list comprehension, but in my understanding I am already implemented this.

What is the reason for running currectly in on environment but not in the other?

```<code>import cv2
import numpy as np

def get_output_layers(net):
   layer_names = net.getLayerNames()
</code>```

output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

```<code>   return output_layers

def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):

   label = str(classes[class_id])

   color = COLORS[class_id]

cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)

cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

image = cv2.imread('horses.jpg')

Width = image.shape[1]
Height = image.shape[0]
scale = 0.00392

classes = None

with open(r'yolov3.txt', 'r') as f:
   classes = [line.strip() for line in f.readlines()]

COLORS = np.random.uniform(0, 255, size=(len(classes), 3))

net = cv2.dnn.readNet('yolov3.weights','yolov3.cfg')
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
net.setInput(blob)

outs = net.forward(get_output_layers(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4

for out in outs:
   for detection in out:
    scores = detection[5:]
    class_id = np.argmax(scores)
    confidence = scores[class_id]
    if confidence > 0.5:
        center_x = int(detection[0] * Width)
        center_y = int(detection[1] * Height)
        w = int(detection[2] * Width)
        h = int(detection[3] * Height)
        x = center_x - w / 2
        y = center_y - h / 2
        class_ids.append(class_id)
        confidences.append(float(confidence))
        boxes.append([x, y, w, h])

indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

for i in indices:

   box = boxes[i]
   x = box[0]
   y = box[1]
   w = box[2]
   h = box[3]
  draw_prediction(image, class_ids[i], confidences[i], round(x), round(y),
  round(x+w), round(y+h))

cv2.imshow("object detection", image)
cv2.waitKey()

cv2.imwrite("object-detection.jpg", image)
cv2.destroyAllWindows()
</code>```

答:
there were subtle, recent api changes wrt handling std::vector in python

(4.5.1 still expects a 2d array, but it's 1d in 4.5.5)

to avoid the whole trouble, please simply use:

```<code>output_layers = net.getUnconnectedOutLayersNames()
</code>```

(like it is done in the sample)

Body:
I have the following code, which runs well under Visual Studio Code with python 3.9.10, opencv 4.5.5 and numpy 1.22.1.

I would like to migrate this code into the Spyder IDE (Version 5, another notebook), python 3.8, opencv 4.5.1 and numpy 1.22.2.

In spyder, I get the error message TypeError: only integer scalar arrays can be converted a scalar index in line: output_layers = [layer_names[i-1]...] (marked line down in the code section)

I have already checked other answers on this site such as
TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index
which suggests list comprehension, but in my understanding I am already implemented this.

What is the reason for running currectly in on environment but not in the other?

import cv2
import numpy as np

def get_output_layers(net):
   layer_names = net.getLayerNames()

output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

   return output_layers

def draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):

   label = str(classes[class_id])

   color = COLORS[class_id]

cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)

cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

image = cv2.imread('horses.jpg')

Width = image.shape[1]
Height = image.shape[0]
scale = 0.00392

classes = None

with open(r'yolov3.txt', 'r') as f:
   classes = [line.strip() for line in f.readlines()]

COLORS = np.random.uniform(0, 255, size=(len(classes), 3))

net = cv2.dnn.readNet('yolov3.weights','yolov3.cfg')
blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)
net.setInput(blob)

outs = net.forward(get_output_layers(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4

for out in outs:
   for detection in out:
    scores = detection[5:]
    class_id = np.argmax(scores)
    confidence = scores[class_id]
    if confidence > 0.5:
        center_x = int(detection[0] * Width)
        center_y = int(detection[1] * Height)
        w = int(detection[2] * Width)
        h = int(detection[3] * Height)
        x = center_x - w / 2
        y = center_y - h / 2
        class_ids.append(class_id)
        confidences.append(float(confidence))
        boxes.append([x, y, w, h])

indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

for i in indices:

   box = boxes[i]
   x = box[0]
   y = box[1]
   w = box[2]
   h = box[3]
  draw_prediction(image, class_ids[i], confidences[i], round(x), round(y),
  round(x+w), round(y+h))

cv2.imshow("object detection", image)
cv2.waitKey()

cv2.imwrite("object-detection.jpg", image)
cv2.destroyAllWindows()

Body:
there were subtle, recent api changes wrt handling std::vector in python

(4.5.1 still expects a 2d array, but it's 1d in 4.5.5)

to avoid the whole trouble, please simply use:

output_layers = net.getUnconnectedOutLayersNames()

(like it is done in the sample)


问:
GraalVM TypeHint not included in reflect-config.json
As mentioned above, when I try to include a Hint, Spring-AOT plugin (spring-aot:generate) is not detecting the annotation and the reflection is not included in the reflect-config.json

Here is the code where I use the annotation.

```<code>@TypeHint(
        typeNames = "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi",
        access= AccessBits.PUBLIC_CONSTRUCTORS | AccessBits.PUBLIC_METHODS
)
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
</code>```

Has this happened to anyone else?

What am I doing wrong here?

答:
Try using this. It worked for me</p>
```<code>@TypeHint(
    types = {RoutesDto.class, RouteDto.class, TrainJourney.class},
    access= {TypeAccess.PUBLIC_CONSTRUCTORS, TypeAccess.PUBLIC_METHODS}
)
</code>```

Body:
As mentioned above, when I try to include a Hint, Spring-AOT plugin (spring-aot:generate) is not detecting the annotation and the reflection is not included in the reflect-config.json

Here is the code where I use the annotation.

@TypeHint(
        typeNames = "org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi",
        access= AccessBits.PUBLIC_CONSTRUCTORS | AccessBits.PUBLIC_METHODS
)
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Has this happened to anyone else?

What am I doing wrong here?

Body:
Try using this. It worked for me

@TypeHint(
    types = {RoutesDto.class, RouteDto.class, TrainJourney.class},
    access= {TypeAccess.PUBLIC_CONSTRUCTORS, TypeAccess.PUBLIC_METHODS}
)


问:
If I use a class more than once in an application, will it be compiled just once into the exe?
I'm evaluating the many possibilities for a trial protection system and came up with the following question:

If I use my "trial check" class more than once (scattered several times over the application), will it be compiled just once into the exe?

The reason why I'm asking is that if it's only compiled once into the exe, then patching this single class will invalidate all places where it is used.

If it's compiled just once, are there any viable alternatives to prevent this?

Thanks!

EDIT: I'm actually not trying to roll my own protection system, I'm looking at several existing solutions like OnGuard, mxProtector and TRegWare. It was while looking at the various solutions source-code, that I came up with this question.

答:
Yes. The standard workaround is to put the code in an .inc and include that in multiple units.

But that makes less sense in a security setting. Since if sb has learned to search for a pattern, he can simply repeat the search to find the other occurrences, making it a minor nuisance at best.

This is one of the reasons why DIY protection is often a waste of time, and I agree fully with Ain. (both the onguard thing, and the fact that if functionality IS in the exe, it will be unlocked sooner or later, giving sufficient motivation)