答:
Try this!

<item name="colorOnPrimary">@color/white</item>

just update the color name here in your Menu Layout XML CODE and before Debugging the project Try "Clean Project". and after that Run your project might be it will work.

Title: Menu item not showing titles in android


来源: stackexchange

问:
Query with ORDER BY clause and sending certain rows at the end of the results separately
Given that I want to query over a single table and this table has this structure and data

```<code>price | weight
 100      0
 200     10
 500      0
 300     10
</code>```

I would like to apply an ORDER BY price DESC but I want also results with weight = 10 to be at the end of the results (and these results also applying the ORDER BY price DESC).

```<code>Results Query A         WHERE weight <> 10
----------------
price | weight
100       0
500       0

Results Query B         WHERE weight = 10
----------------
price | weight
200       10
300       10
</code>```

I have thought in using UNION but I can't achieve this  which is what I want:

```<code>EXPECTED RESULT      <= order by price DESC
----------------
price | weight
500       0
100       0
300      10      <=
200      10      <= but maintaining rows with weight 10 at the end of the results
</code>```

How would you do that? Thanks in advance

答:
If you sort first by the boolean expression weight = 10, all such rows will be placed at the bottom of the resultset:

```<code>ORDER BY weight = 10,
         price DESC
</code>```

because weight = 10 is evaluated as 1 for true and 0 for false.

ContentLicense: CC BY-SA 4.0

Body:
Given that I want to query over a single table and this table has this structure and data

price | weight
 100      0
 200     10
 500      0
 300     10

I would like to apply an ORDER BY price DESC but I want also results with weight = 10 to be at the end of the results (and these results also applying the ORDER BY price DESC).

Results Query A         WHERE weight <> 10
----------------
price | weight
100       0
500       0

Results Query B         WHERE weight = 10
----------------
price | weight
200       10
300       10

I have thought in using UNION but I can't achieve this  which is what I want:

EXPECTED RESULT      <= order by price DESC
----------------
price | weight
500       0
100       0
300      10      <=
200      10      <= but maintaining rows with weight 10 at the end of the results

How would you do that? Thanks in advance

Body:
If you sort first by the boolean expression weight = 10, all such rows will be placed at the bottom of the resultset:

ORDER BY weight = 10,
         price DESC

because weight = 10 is evaluated as 1 for true and 0 for false.


问:
Objective-C: Load "Library" using reflection
I'm tasked with creating an application using XCode for OSX. This application needs to be able to load and run separate "modules" which will be determined dynamically (i.e., one user may have purchased modules 1 & 2, while user 2 would have purchased modules 3 and 6 -- only purchased modules should "run").

In C#, I would create a "library" project (that compiles to just a DLL). When the user purchases a module, I'd supply the appropriate DLL files and then my app would look for and load/run the DLL using reflection.

What would be the equivalent to this in XCode? Can I create a "library" and then load it using reflection? Keeping in mind that the app can't have prior knowledge of the module since in some cases, the user wouldn't even own the module files. I see various options such as "Cocoa Framework" and "Cocoa Library" as well as "C/C++ Library." What does each do and would any work to do what I need?

答:
You can create a bundle. Xcode has templates for this (it is called "Loadable Bundle" and the icon is a Lego brick). You typically load a bundle using NSBundle's load method.

An example of loading it would be:

```<code>- (BOOL)loadPluginAtURL:(NSURL *)URL {
  NSBundle *pluginBundle = [NSBundle bundleWithURL:URL];
  if (![pluginBundle load]) { // is false if pluginBundle == nil automatically.
    return NO;
  }
  id plugin = nil;
  @try { // Use @try-@catch in case the principle class doesn't respond to +alloc or -init. Otherwise the host application would crash and that kinda sucks.
    plugin = [[pluginBundle principalClass] alloc] init]; // Set the principle class in the bundle's info plist.
  } @catch (id e) {
    [bundle unload];
    return NO;
  }
  if (plugin) {
    [self.loadedPlugins addObject:plugin];// Define this as an NSMutableSet object.
    return YES;
  }
  [pluginBundle unload];
  return NO;
}
</code>```

You can eventually provide a framework that the plugins can use, which can include protocols and classes. You may, for example check if the principle class of the bundle is a subclass of a specific class in your framework, so you don't send any messages the plugin doesn't respond to.

ContentLicense: CC BY-SA 3.0

Body:
You can create a bundle. Xcode has templates for this (it is called "Loadable Bundle" and the icon is a Lego brick). You typically load a bundle using NSBundle's load method.

An example of loading it would be:

- (BOOL)loadPluginAtURL:(NSURL *)URL {
  NSBundle *pluginBundle = [NSBundle bundleWithURL:URL];
  if (![pluginBundle load]) { // is false if pluginBundle == nil automatically.
    return NO;
  }
  id plugin = nil;
  @try { // Use @try-@catch in case the principle class doesn't respond to +alloc or -init. Otherwise the host application would crash and that kinda sucks.
    plugin = [[pluginBundle principalClass] alloc] init]; // Set the principle class in the bundle's info plist.
  } @catch (id e) {
    [bundle unload];
    return NO;
  }
  if (plugin) {
    [self.loadedPlugins addObject:plugin];// Define this as an NSMutableSet object.
    return YES;
  }
  [pluginBundle unload];
  return NO;
}

You can eventually provide a framework that the plugins can use, which can include protocols and classes. You may, for example check if the principle class of the bundle is a subclass of a specific class in your framework, so you don't send any messages the plugin doesn't respond to.


问:
Swift - Button text color won't change with setTitleColor
I can not seem to get the text in two of my buttons to change to white, unless I manually do it through the storyboard. Any ideas?

class AppUIButton: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        backgroundColor = Theme.tintColor
        layer.cornerRadius = frame.height / 2
        setTitleColor(UIColor.white, for: .normal)
    }
}

class AddTripViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var tripTextField: UITextField!
    @IBOutlet weak var cencelButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!

    var doneSaving: (() -> ())?

    override func viewDidLoad() {
        super.viewDidLoad()

        titleLabel.font = UIFont(name: Theme.mainFontName, size: 24)

        //I can force the text color to change with the bellow
        //cencelButton.setTitle("Cancel", for: .normal)
        //cencelButton.setTitleColor(UIColor.white, for: .normal)

        //saveButton.setTitle("Add", for: .normal)
        //saveButton.setTitleColor(UIColor.white, for: .normal)

    }

    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true)
    }

    @IBAction func save(_ sender: Any) {
        TripFunctions.createTrip(tripModel: TripModel(title: tripTextField.text!))
        if let doneSaving = doneSaving {
            doneSaving()
        }
        dismiss(animated: true)
    }
}
```

答:
This should work for you:</p>
```<code>yourButton.tintColor = .white
</code>```

Body:
This should work for you:

yourButton.tintColor = .white


问:
Next.js production build doesn't apply css variables
I have the next postcss config

```<code>module.exports = {
  plugins: [
    [
      'postcss-preset-env',
      {
        browsers: 'last 2 versions, IE 11, not dead',
        preserve: false,
        features: {
          'custom-media-queries': true,
          'custom-properties': true,
          'nesting-rules': true
        },
        importFrom: ['src/styles/variables.css']
      }
    ]
  ]
}

</code>```

And this file with css variables

```<code>@custom-media --desktop screen and (min-width: 768px);
@custom-media --mobile screen and (max-width: 767px);

:root {
  --montserrat: montserrat, sans-serif;
  --sfProDisplay: sf pro display, sans-serif;
  --helvetica: helvetica, sans-serif;
  --blue: #315efb;
  --middleBlue: #2c54e2;
  --darkBlue: #274bc8;
  --lightBlue: #e0ebff;
  --green: #21a038;
  --grey: #62687f;
  --darkGray: #343b4c;
  --blueGray: #8d96b2;
  --cloudGray: #f3f4f7;
  --cloudGray7: #afb6c9;
  --darkCarbone: #1f2431;
  --paleYellow: #fffde5;
  --red: #ff564e;
}

</code>```

After i built my project via next build && next export, colors are not displayed correctly. For example, color: var(--blueGray), instead color: #8d96b2. Has anybody idea what's wrong?

答:
Global CSS needs to be included in the /pages/_app file.

From the Adding a Global Stylesheet
 documentation:

To add a (global) stylesheet to your application, import the CSS file within
pages/_app.js.

(...) In development, expressing stylesheets this way allows your
styles to be hot reloaded as you edit them—-meaning you can keep
application state.

In production, all CSS files will be automatically concatenated into a
single minified .css file.

Make sure you import the file where the CSS variables are defined in your custom _app.

import '../styles/globals.css'
import '../styles/variables.css'

function MyApp({ Component, pageProps }) {
    return <Component {...pageProps} />;
}

export default MyApp;
```

Body:
I have the next postcss config

module.exports = {
  plugins: [
    [
      'postcss-preset-env',
      {
        browsers: 'last 2 versions, IE 11, not dead',
        preserve: false,
        features: {
          'custom-media-queries': true,
          'custom-properties': true,
          'nesting-rules': true
        },
        importFrom: ['src/styles/variables.css']
      }
    ]
  ]
}

And this file with css variables

@custom-media --desktop screen and (min-width: 768px);
@custom-media --mobile screen and (max-width: 767px);

:root {
  --montserrat: montserrat, sans-serif;
  --sfProDisplay: sf pro display, sans-serif;
  --helvetica: helvetica, sans-serif;
  --blue: #315efb;
  --middleBlue: #2c54e2;
  --darkBlue: #274bc8;
  --lightBlue: #e0ebff;
  --green: #21a038;
  --grey: #62687f;
  --darkGray: #343b4c;
  --blueGray: #8d96b2;
  --cloudGray: #f3f4f7;
  --cloudGray7: #afb6c9;
  --darkCarbone: #1f2431;
  --paleYellow: #fffde5;
  --red: #ff564e;
}

After i built my project via next build && next export, colors are not displayed correctly. For example, color: var(--blueGray), instead color: #8d96b2. Has anybody idea what's wrong?


问:
How to use a function from a nodejs module inside a Python script
I need to use a function from a nodejs library (import { signLimitOrder } from '@sorare/crypto';) from a Python script.
Is there a way to do such a thing?

I am trying to use the subprocess python library in order to launch a node command, but I am not sure if that is the best approach

答:
Sure, subprocess module will work.

Or you could run a REST / gRPC server from Node and communicate with that


问:
Can I still using android library that depends on jCenter after the jCenter deprecation?
I have an app that displays pdf and I'm using barteksc android pdfviewer library:
implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'

it depends on jcenter and jcenter is dperecated.
I have added jcenter and android studio display a warning that it is deprecated.
The question: Can I still use this library and publish my app safely despite jcenter deprecation?

答:
Yes, you can still use it I know I'm 9 months late but you can first delete the jCenter because its deprecated then just add the following code in "settings.gradle" file:</p>
```<code>gradlePluginPortal()
</code>```

Body:
Yes, you can still use it I know I'm 9 months late but you can first delete the jCenter because its deprecated then just add the following code in "settings.gradle" file:

gradlePluginPortal()


问:
502 Bad Gateway in elasticbeanstalk of AWS
I have deployed a spring boot application in elasticbeanstalk.
In the "application.properties" file, I have set,

server.port=5000

I have added a RDS db and set the following environment properties.

I have also added an inbound rule in the security group of the environment as shown in the image below:

I am still getting the 502 Bad Gateway error when I click on the URL.

答:
Your rule is incorrect.

0.0.0.0/32 means that you accept traffic only from the IP address 0.0.0.0 which basically doesn't exist.

What you want to do is allow traffic from 0.0.0.0/0 which means accept traffic from anywhere in the world.


问:
MySQL High CPU usage and persistent links
I am having very high CPU spikes on mysqld process (greater than 100%, and even saw a 300% at one point).  My load average is around: .25, .34, .28.

I read this great post about this issue: MySQL high CPU usage

One of the main things to do is disable persistent connections.  So I checked my php.ini and mysql.allow_persistent = on and mysql.max_persistent = -1 -- which means no limit.

This raises a few questions for me before changing anything just to be sure:

If my mysqld process is spiking over 100% every couple seconds shouldn't my load average be higher then they are?

What will disabling persistent links do - will my scripts continue to function as is?

If I turn this off and reload php what does this mean for my current users as there will be many active users.

EDIT:

CPU Info: Core2Quad q9400 2.6 Ghz

答:
Spikes are fine.  This is MySQL doing work.  Your load average seems appropriate.

Disabling persistent links simply means that the scripts cannot use an existing connection to the database.  I wouldn't recommend disabling this.  At the very least, if you want to disable them, do it on the application later, rather than on MySQL.  This might even increase load slightly, depending on the conditions.

Finally, DB persistence has nothing to do with the users on your site (generally).  Users make a request, and once all of the page resources are loaded, that is it, until the next request.  (Except in a few specific cases.)  In any case, while the request is happening, the script will still be connected to the DB.


问:
Disposing of a collection of IDisposable
I have a method that returns a collection of DirectoryEntry objects.

```<code>static IEnumerable<DirectoryEntry> Bar(){ ... }
</code>```

I've been iterating through the collection when I'm finished with it and disposing of each item, but I'm wondering what the best practice is.

Ex.

```<code>var foo = Bar();
\\ Do some work
foreach (var f in foo)
{
    f.Dispose();
}
</code>```

答:
Almost.  You should take responsibility to Dispose() disposable objects returned from functions, see eg here, probably in a finally block.

There's no guarantee that you get the same set of DirectoryEntry object every time you enumerate the IEnumerable (ie with foo.GetEnumerator() or foreach).  You could get new ones every time, and re-enumerating could cause unnecessarary IO. eg this

```<code>    static int n = 0;
    static IEnumerable<int> Bar()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return n++;
        }

    }

    static void Main(string[] args)
    {
        var foo = Bar();

        var count = foo.Count();
        foreach(var i in foo)
        {
            Console.WriteLine(i);
        }
        foreach (var i in foo)
        {
            Console.WriteLine(i);
        }

    }
</code>```

will iterate the IEnumrable three times, generating 30 different ints.

For this reason, you often need to collect an IEnumerable in a List or other ICollection.

```<code>var foo = Bar().ToList();
try
{
    // Do some work
}
finally
{
    foreach (var f in foo)
    {
        f.Dispose();
    }
}
</code>```

Something like this

```<code>foreach (var f in Bar())
{
    using (f)
    {
        //Do some work
    }
}
</code>```

is risky because if Bar() returns a collection, and you have an exception, the un-enumerated objects won't get disposed.

Body:
I have a method that returns a collection of DirectoryEntry objects.

static IEnumerable<DirectoryEntry> Bar(){ ... }

I've been iterating through the collection when I'm finished with it and disposing of each item, but I'm wondering what the best practice is.

Ex.

var foo = Bar();
\\ Do some work
foreach (var f in foo)
{
    f.Dispose();
}

Body:
Almost.  You should take responsibility to Dispose() disposable objects returned from functions, see eg here, probably in a finally block.

There's no guarantee that you get the same set of DirectoryEntry object every time you enumerate the IEnumerable (ie with foo.GetEnumerator() or foreach).  You could get new ones every time, and re-enumerating could cause unnecessarary IO. eg this

    static int n = 0;
    static IEnumerable<int> Bar()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return n++;
        }

    }

    static void Main(string[] args)
    {
        var foo = Bar();

        var count = foo.Count();
        foreach(var i in foo)
        {
            Console.WriteLine(i);
        }
        foreach (var i in foo)
        {
            Console.WriteLine(i);
        }

    }

will iterate the IEnumrable three times, generating 30 different ints.

For this reason, you often need to collect an IEnumerable in a List or other ICollection.

var foo = Bar().ToList();
try
{
    // Do some work
}
finally
{
    foreach (var f in foo)
    {
        f.Dispose();
    }
}

Something like this

foreach (var f in Bar())
{
    using (f)
    {
        //Do some work
    }
}

is risky because if Bar() returns a collection, and you have an exception, the un-enumerated objects won't get disposed.


问:
How do i bold a text in JavaScript?
I am trying to change text to bold, which is really hard.
I tried many times using various ways,
for example:

```<code>//1:

document.getElementById('boldtext').innerHTML = "<b>" += document.getElementById('boldtext').innerHTML += "</b>"; //which dosent work

//2:

document.getElementById('boldtext').bold(); //dosent work too

</code>```

Any ideas on how to bold text in Javascript?

```<code>//My code so far:
The whole code is this: function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } alert(text); }; let BoldButton = document.createElement('input'); /*boldbuttonlol*/ BoldButton.type = 'button'; BoldButton.value = 'bold highlighted text'; BoldButton.onclick = () => { getSelectionText(); }; document.body.appendChild(BoldButton);
</code>```

Thank you!!

答:
Please try this

function makeMeBold() {
        document.getElementById('boldtext').style.fontWeight = "bold";
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="makeBold" type="button" onclick="makeMeBold()" value="Click me"/>
<div id="boldtext">Sample text to make bold</div></code>```

Title: How do i bold a text in JavaScript?

Body:
I am trying to change text to bold, which is really hard.
I tried many times using various ways,
for example:

//1:

document.getElementById('boldtext').innerHTML = "" += document.getElementById('boldtext').innerHTML += ""; //which dosent work

//2:

document.getElementById('boldtext').bold(); //dosent work too

Any ideas on how to bold text in Javascript?

//My code so far:
The whole code is this: function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } alert(text); }; let BoldButton = document.createElement('input'); /*boldbuttonlol*/ BoldButton.type = 'button'; BoldButton.value = 'bold highlighted text'; BoldButton.onclick = () => { getSelectionText(); }; document.body.appendChild(BoldButton);

Thank you!!

Body:
Please try this

function makeMeBold() {
        document.getElementById('boldtext').style.fontWeight = "bold";
   }

<input id="makeBold" type="button" onclick="makeMeBold()" value="Click me"/>
<div id="boldtext">Sample text to make bold</div>


问:
P value in backward elimination > 0.05 are eliminated from the features, why do we eliminate? (multi variable linear regression)
In general if the p value is less than 0.05 significance level we reject the null,
In backward elimination we delete the features whose p value is greater than 0.05, why not delete the delete the terms whose p value is less.

and on what condition do the regression model calculate the p value ?

can anyone explain in simple and clear terms.

Thanks for ur time and help.

答:
Your answer and the assumption are not right, because in Backward Elimination the very first Step is to set SL (significance level) for your model to a constant value (usually SL = 0.05).

The answer is simple. The goal is to keep the significant occurrences. so if for example you set the SL = 0.1, the P_values greater 0.1 are insignificant and the P_values smaller or equal to 0.1 are considered significant.

The higher the P_value, more insignificant the predictor (occurrence) and the coefficient closer to zero (H_0). Such an occurrence is not suitable for the model to train with.


问:
Python: every n of list of list replace new list
My curent list looks like this in csv file:

```<code>4IMWQ;1PLZT;AYNQV;NRTF7;T4AXP
4SCUM;3EYFC;6MT9H;R2Z9Y;N91K1
H8EF1;JO4HZ;MJTOF;KMFPP;925EF
9VYY1;4FG81;VI4US;79R6F;7804A
29GHY;U47WA;VY6SF;WRSLS;HPAU5
TKEA0;6ST9T;JYD4B;5A55Y;NZKVN
</code>```

But i need to replace evey nth of list to numeric value.
If i use this method i end up with wrong solution and lists aint same lenght anymore.

```<code>char = 5
rows = 50
cols = 5
def id_generator(size= char, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
def nr_generator(size= char, chars=string.octdigits):
    return ''.join(random.choice(chars) for x in range(size))
nums = 3
data = []
nums1 = nums - 1
for i in range(rows):
    sublist = []
    for y in range(cols):
        sublist.append(id_generator())
    data.append(sublist)
data[nums1::nums] = [[nr_generator()] for x in data[nums1::nums]]

>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'],
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'],
>>>['66257'],
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'],
>>>['45024']...]
</code>```

Should look like:

```<code>>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'],
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'],
>>>['66257', '58478', '87415', '58446', '87115'],
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'],
>>>['45024', '14587', '58461', '54786', '98524']...]
</code>```

答:
You can do this in a list comprehension.  Select which generator to use based on the row number:

```<code>nums  = 3
nums1 = nums - 1
data  = [ [ nr_generator() if r%nums==nums-1 else id_generator()
            for _ in range(cols) ]
         for r in range(rows*cols)]

print(*data,sep='\n')

['HN7VD', 'Z57K3', 'L6F5O', 'VU77R', 'V6ANV']
['5A9SG', 'OJGNH', 'XPWHA', 'VWECX', 'PCO3A']
['03751', '50217', '63143', '27251', '73064']
['1YMYT', 'DLQ21', '8ZXY0', 'KEJF8', 'AV040']
['QGEHO', 'DNNYO', 'QNMDU', '5VDF1', '2GIF3']
['50435', '41373', '60173', '65517', '71325']
['92KS3', 'ZVRPK', '8VURD', 'KKHU5', 'U28LL']
['QOYSM', 'UB9Q2', 'VYC6J', 'ADUJL', 'FXC8I']
['26041', '37426', '13752', '76574', '65502']
['0TQOH', 'VBN77', 'QG3VV', 'WWWDO', 'PF5BN']
...
</code>```

You could make is a bit more concise by playing with a list of generator functions corresponding to the cycle of rows.

```<code>nums  = 3
gens  = [id_generator]*(nums-1)+[nr_generator]
data  = [[gens[r%nums]() for _ in range(cols)] for r in range(rows*cols)]
</code>```

Body:
My curent list looks like this in csv file:

4IMWQ;1PLZT;AYNQV;NRTF7;T4AXP
4SCUM;3EYFC;6MT9H;R2Z9Y;N91K1
H8EF1;JO4HZ;MJTOF;KMFPP;925EF
9VYY1;4FG81;VI4US;79R6F;7804A
29GHY;U47WA;VY6SF;WRSLS;HPAU5
TKEA0;6ST9T;JYD4B;5A55Y;NZKVN

But i need to replace evey nth of list to numeric value.
If i use this method i end up with wrong solution and lists aint same lenght anymore.

char = 5
rows = 50
cols = 5
def id_generator(size= char, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
def nr_generator(size= char, chars=string.octdigits):
    return ''.join(random.choice(chars) for x in range(size))
nums = 3
data = []
nums1 = nums - 1
for i in range(rows):
    sublist = []
    for y in range(cols):
        sublist.append(id_generator())
    data.append(sublist)
data[nums1::nums] = [[nr_generator()] for x in data[nums1::nums]]

>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'],
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'],
>>>['66257'],
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'],
>>>['45024']...]

Should look like:

>>>[['UOL9P', 'TAZI6', 'NIYRK', 'V8Z1B', 'PCFK8'],
>>>['IHBV2', 'UULQK', '88J9L', 'AEBP6', '656U9'],
>>>['66257', '58478', '87415', '58446', '87115'],
>>>['ST2P2', 'FO1VT', '583CM', 'GQY1Q', '3BBRC']
>>>['RQCKB', 'X2A6W', 'XMNM7', '16OP1', '4VYMZ'],
>>>['45024', '14587', '58461', '54786', '98524']...]

Body:
You can do this in a list comprehension.  Select which generator to use based on the row number:

nums  = 3
nums1 = nums - 1
data  = [ [ nr_generator() if r%nums==nums-1 else id_generator()
            for _ in range(cols) ]
         for r in range(rows*cols)]

print(*data,sep='\n')

['HN7VD', 'Z57K3', 'L6F5O', 'VU77R', 'V6ANV']
['5A9SG', 'OJGNH', 'XPWHA', 'VWECX', 'PCO3A']
['03751', '50217', '63143', '27251', '73064']
['1YMYT', 'DLQ21', '8ZXY0', 'KEJF8', 'AV040']
['QGEHO', 'DNNYO', 'QNMDU', '5VDF1', '2GIF3']
['50435', '41373', '60173', '65517', '71325']
['92KS3', 'ZVRPK', '8VURD', 'KKHU5', 'U28LL']
['QOYSM', 'UB9Q2', 'VYC6J', 'ADUJL', 'FXC8I']
['26041', '37426', '13752', '76574', '65502']
['0TQOH', 'VBN77', 'QG3VV', 'WWWDO', 'PF5BN']
...

You could make is a bit more concise by playing with a list of generator functions corresponding to the cycle of rows.

nums  = 3
gens  = [id_generator]*(nums-1)+[nr_generator]
data  = [[gens[r%nums]() for _ in range(cols)] for r in range(rows*cols)]


问:
How to migrate "build.gradle" configurations in Android Studio for both project level and module level in Android Studio Bumblebee release?
For now [13th Feb 2022] , latest android studio's stable version is BumbleBee . With this version, there are a lot of changes in build.gradle (project level) .

So, I wonder if there is any guideline on how to adopt these changes with respect to older build.gradle (project level) will be a relief.

答:
to add  Admob and Firebase crashlytics to Android studio bumble bee and other such things

```<code>buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
     classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}
</code>```

for maven jitpack, the JitPack repository needs to be added into the root level file settings.gradle instead of build.gradle:

```<code>dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}
</code>```

these are initial changes more may be required as per your own requirements

Body:
to add  Admob and Firebase crashlytics to Android studio bumble bee and other such things

buildscript {
  dependencies {
    // Add our classpath
     classpath 'com.google.gms:google-services:4.3.10'
     classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
 }
}
 plugins {
      id 'com.android.application' version '7.1.0' apply false
      id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
   delete rootProject.buildDir
}

for maven jitpack, the JitPack repository needs to be added into the root level file settings.gradle instead of build.gradle:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
      // ...
        maven { url 'https://jitpack.io' }
    }
}

these are initial changes more may be required as per your own requirements


问:
Android studio com.google.ar.sceneform.ux.ArFragment is incompatible with androidx.fragment.app.Fragment
Does android studio don't support sceneform library anymore? because whenever I instantiate ArFragment with (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment) I get an error that says Inconvertible types; cannot cast 'androidx.fragment.app.Fragment' to 'com.google.ar.sceneform.ux.ArFragment

I already put <meta-data android:name="com.google.ar.core" android:value="required" /> in manifest and all the stuff needed

This is my xml code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:name="com.google.ar.sceneform.ux.ArFragment" />

</LinearLayout>
</code>```

This is my Java code

```<code>package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.ar.sceneform.ux.ArFragment;

public class MainActivity extends AppCompatActivity {
    ArFragment arFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    }
}
</code>```

This is my gradle dependencies look like

```<code>    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'
</code>```

答: Google stopped the development in 2020. Please use the current maintained version</p>

Body:
Does android studio don't support sceneform library anymore? because whenever I instantiate ArFragment with (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment) I get an error that says Inconvertible types; cannot cast 'androidx.fragment.app.Fragment' to 'com.google.ar.sceneform.ux.ArFragment

I already put <meta-data android:name="com.google.ar.core" android:value="required" /> in manifest and all the stuff needed

This is my xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:name="com.google.ar.sceneform.ux.ArFragment" />

</LinearLayout>

This is my Java code

package com.example.test;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.google.ar.sceneform.ux.ArFragment;

public class MainActivity extends AppCompatActivity {
    ArFragment arFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    }
}

This is my gradle dependencies look like

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'


问:
Does this variation of the Strategy Pattern have a name?
I have a standard GOF Strategy Pattern: client code holds a reference to an AbstractStrategy, which points to any one of several ConcreteStrategies deriving from or implementing the AbstractStrategy.

One ConcreteStrategy delegates to any of several other ConcreteStrategies, depending on its passed parameters, e.g.:

```<code>public class ConcreteStrategy0 {
public void doStrategy(SomeType someData) {
   switch( somefunc(someData ) {
    case 0: ConcreteStrategy1.singleton.doStrategy(someData); break;
    case 1: ConcreteStrategy2.singleton.doStrategy(someData); break;
    default: ConcreteStrategy3.singleton.doStrategy(someData); break;
   }
}
</code>```

This isn't quite a Coplien Envelope/Letter (as the intent isn't quite the same).

But does it have a name?

答:
It looks like a combination of Strategy and Factory method pattern. I doubt it has a name on its own.
But why do you really need the switch statement? I think an Abstract Factory pattern would be nicer here.</p>

OwnerDisplayName: tpdi

ContentLicense: CC BY-SA 2.5

Body:
I have a standard GOF Strategy Pattern: client code holds a reference to an AbstractStrategy, which points to any one of several ConcreteStrategies deriving from or implementing the AbstractStrategy.

One ConcreteStrategy delegates to any of several other ConcreteStrategies, depending on its passed parameters, e.g.:

public class ConcreteStrategy0 {
public void doStrategy(SomeType someData) {
   switch( somefunc(someData ) {
    case 0: ConcreteStrategy1.singleton.doStrategy(someData); break;
    case 1: ConcreteStrategy2.singleton.doStrategy(someData); break;
    default: ConcreteStrategy3.singleton.doStrategy(someData); break;
   }
}

This isn't quite a Coplien Envelope/Letter (as the intent isn't quite the same).

But does it have a name?

OwnerDisplayName: Igor Brejc


问:
Matching pattern and adding values to a list in Tcl
I wondered if I could get some advice, I'm trying to create a list by reading a file with input shown below

Example from input file

```<code>Parameter.Coil = 1
Parameter.Coil.Info = Coil
BaseUTC.TimeSet_v0 = 1
BaseUTC.TimeSet_v0.Info = TimeSet_v0
BaseUTC.TimeSet_v1 = 1
BaseUTC.TimeSet_v1.Info = TimeSet_v1
BaseUTC.TimeSet_v14 = 1
BaseUTC.TimeSet_v14.Info = TimeSet_v14
BaseUTC.TimeSet_v32 = 1
BaseUTC.TimeSet_v32.Info = TimeSet_v32
VC.MILES = 1
VC.MILES.Info = MILES_version1
</code>```

I am interested in any line with prefix of "BaseUTC." and ".Info" and would like to save value after "=" in a list

Desired:

```<code>output = TimeSet_v0 TimeSet_v1 TimeSet_v14 TimeSet_v32
</code>```

I've tried the following but not getting the desired output.

```<code>set input [open "[pwd]/Data/Input" r]

set list ""
while { [gets $input line] >= 0 } {
   incr number
   set sline [split $line "\n"]
   if {[regexp -- {BaseUTC.} $sline]} {
      #puts "lines = $sline"
      if {[regexp -- {.Info} $sline]} {
         set output [lindex [split $sline "="] 1]
         lappend list $output
}}}
puts "output = $list"
close $input
</code>```

I get output as

```<code>output = \ TimeSet_v0\} \ TimeSet_v1\} \ TimeSet_v14\} \ TimeSet_v32\}
</code>```

Can any help identify my mistake, please.

Thank you in advance.

答:
A lot of your code doesn't seem to match your description (Steering? I thought you were looking for BaseUTC lines?), or just makes no sense (Why split what you already know is a single line on newline characters?), but one thing that will really help simplify things is a regular expression capture group. Something like:

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

proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        if {[regexp {^BaseUTC\..*\.Info\s+=\s+(.*)} $line -> arg]} {
            lappend list $arg
        }
    }
    close $in
    return $list
}

puts [process Data/Input]
</code>```

Or using wildcards instead of regular expressions:

```<code>proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        lassign [split $line =] var arg
        if {[string match {BaseUTC.*.Info} [string trim $var]]} {
            lappend list [string trim $arg]
        }
    }
    close $in
    return $list
}
</code>```

Body:
I wondered if I could get some advice, I'm trying to create a list by reading a file with input shown below

Example from input file

Parameter.Coil = 1
Parameter.Coil.Info = Coil
BaseUTC.TimeSet_v0 = 1
BaseUTC.TimeSet_v0.Info = TimeSet_v0
BaseUTC.TimeSet_v1 = 1
BaseUTC.TimeSet_v1.Info = TimeSet_v1
BaseUTC.TimeSet_v14 = 1
BaseUTC.TimeSet_v14.Info = TimeSet_v14
BaseUTC.TimeSet_v32 = 1
BaseUTC.TimeSet_v32.Info = TimeSet_v32
VC.MILES = 1
VC.MILES.Info = MILES_version1

I am interested in any line with prefix of "BaseUTC." and ".Info" and would like to save value after "=" in a list

Desired:

output = TimeSet_v0 TimeSet_v1 TimeSet_v14 TimeSet_v32

I've tried the following but not getting the desired output.

set input [open "[pwd]/Data/Input" r]

set list ""
while { [gets $input line] >= 0 } {
   incr number
   set sline [split $line "\n"]
   if {[regexp -- {BaseUTC.} $sline]} {
      #puts "lines = $sline"
      if {[regexp -- {.Info} $sline]} {
         set output [lindex [split $sline "="] 1]
         lappend list $output
}}}
puts "output = $list"
close $input

I get output as

output = \ TimeSet_v0\} \ TimeSet_v1\} \ TimeSet_v14\} \ TimeSet_v32\}

Can any help identify my mistake, please.

Thank you in advance.

Body:
A lot of your code doesn't seem to match your description (Steering? I thought you were looking for BaseUTC lines?), or just makes no sense (Why split what you already know is a single line on newline characters?), but one thing that will really help simplify things is a regular expression capture group. Something like:

#!/usr/bin/env tclsh

proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        if {[regexp {^BaseUTC\..*\.Info\s+=\s+(.*)} $line -> arg]} {
            lappend list $arg
        }
    }
    close $in
    return $list
}

puts [process Data/Input]

Or using wildcards instead of regular expressions:

proc process {filename} {
    set in [open $filename]
    set list {}
    while {[gets $in line] >= 0} {
        lassign [split $line =] var arg
        if {[string match {BaseUTC.*.Info} [string trim $var]]} {
            lappend list [string trim $arg]
        }
    }
    close $in
    return $list
}


问:
Get reference to existing OpenSeadragon Viewer
I need to add an overlay to an existing OpenSeadragon viewer object which isn't created by my code, but elsewhere in the application.

I have got to a point where I know that the viewer has been created as I can access the various html elements that are created via jQuery. However I can't work out if there's any way to create a viewer from an existing reference.

I've tried using the id of the viewer div in:

```<code>var viewer = OpenSeadragon(id: "open-seadragon-viewer-id");
</code>```

but this doesn't seem to work.

Is there any way to do this or can you only get the viewer within the code that initialised it?

答:
This solution does not directly answer the question, as it relies on your own code creating the OpenSeaDragon object. It is an implementation of @iangilman's mention of storing the viewer in a global variable. However others may find it useful. (Note that passing a global variable to a function requires a workaround - see Passing a global variable to a function)

The code demonstrates how to use the same OpenSeaDragon object to display different pictures.

```<code>var viewer3=null; //global variable

var newURL1='image/imageToDisplay1.png';
var newURL2='image/imageToDisplay2.png';
var elementID='myID';

//the loadScan function will display the picture using openSeaDragon and can be called as many times as you want.
loadScan("viewer3",newURL1,elementID);
loadScan("viewer3",newURL2,elementID);

//the actual function
function loadScan(theViewer,newURL,theID) {
    //if object has already been created, then just change the image
    if (window[theViewer]!=null) {
            window[theViewer].open({
                type: 'image',
                url: newURL
            });
        } else {
            //create a new OpenSeadragon object
            window[theViewer] = OpenSeadragon({
                prefixUrl: "/myapp/vendor/openseadragon/images/",
                id: theID,
                defaultZoomLevel: 1,
                tileSources: {
                    url: newURL,
                    type: 'image'
                }
            });

        }

}
</code>```

Body:
I need to add an overlay to an existing OpenSeadragon viewer object which isn't created by my code, but elsewhere in the application.

I have got to a point where I know that the viewer has been created as I can access the various html elements that are created via jQuery. However I can't work out if there's any way to create a viewer from an existing reference.

I've tried using the id of the viewer div in:

var viewer = OpenSeadragon(id: "open-seadragon-viewer-id");

but this doesn't seem to work.

Is there any way to do this or can you only get the viewer within the code that initialised it?

Body:
This solution does not directly answer the question, as it relies on your own code creating the OpenSeaDragon object. It is an implementation of @iangilman's mention of storing the viewer in a global variable. However others may find it useful. (Note that passing a global variable to a function requires a workaround - see Passing a global variable to a function)

The code demonstrates how to use the same OpenSeaDragon object to display different pictures.

var viewer3=null; //global variable

var newURL1='image/imageToDisplay1.png';
var newURL2='image/imageToDisplay2.png';
var elementID='myID';

//the loadScan function will display the picture using openSeaDragon and can be called as many times as you want.
loadScan("viewer3",newURL1,elementID);
loadScan("viewer3",newURL2,elementID);

//the actual function
function loadScan(theViewer,newURL,theID) {
    //if object has already been created, then just change the image
    if (window[theViewer]!=null) {
            window[theViewer].open({
                type: 'image',
                url: newURL
            });
        } else {
            //create a new OpenSeadragon object
            window[theViewer] = OpenSeadragon({
                prefixUrl: "/myapp/vendor/openseadragon/images/",
                id: theID,
                defaultZoomLevel: 1,
                tileSources: {
                    url: newURL,
                    type: 'image'
                }
            });

        }

}


问:
Putting two functions in the same "onclick"
I'm trying to display a group of users in a table, and I'm using a library called "ReactTable", and I have an "approve" button, when the user clicks on the "approve" button two things should happen:

The first will be a dispatch of the approveUser function

The second thing, a message will appear that "acceptance has been completed".

The problem is that I want to put two functions in the same button and the same "onClick", and when I did that the site was no longer working,

How can I solve the problem?

```<code>function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

const useStyles = makeStyles({
  button1: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#43a047",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#43a047",
    },
  },
  button2: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#e53935",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#e53935",
    },
  },
});

function ContactsList(props) {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  useEffect(() => {
    dispatch(getUsersRequests());
  }, [dispatch]);

  const usersRequestsState = useSelector(
    (state) => state.usersRequestsApp["usersRequests"]
  );

  console.log(
    "requests inside Contacts List: ",
    usersRequestsState["usersRequests"]
  );

  const columns = useMemo(
    () => [
      {
        Header: "",
        // this is function or property
        accessor: "avatar",
        Cell: ({ row }) => {
          return (
            <Avatar
              className="mx-8"
              alt={row.original.name}
              src={row.original.avatar}
              style={{ height: "7rem", width: "7rem" }}
            />
          );
        },
        className: "justify-center",
        width: 64,
        sortable: false,
      },
      {
        Header: "First Name",
        accessor: "firstName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Last Name",
        accessor: "lastName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Email",
        accessor: "email",
        sortable: true,
      },
      {
        Header: "Phone Number",
        accessor: "phoneNumber",
        sortable: true,
      },
      {
        Header: "actions",
        accessor: "",
        sortable: true,
        id: "action",
        // width: 100,
        Cell: ({ row }) => (
          <div className="flex items-center">
            <ButtonGroup
              style={{
                maxWidth: "206px",
                maxHeight: "40px",
                minWidth: "206px",
                minHeight: "40px",
              }}
              aria-label="outlined primary button group"
            >
              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}
                className={classes.button1}
              >
                approve
              </Button>

              <Snackbar
                open={open}
                autoHideDuration={6000}
                onClose={handleClose}
              >
                <Alert onClose={handleClose} severity="success">
                  acceptance has been completed!
                </Alert>
              </Snackbar>

              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  dispatch(rejectUser(row.original.id));
                }}
                className={classes.button2}
              >
                reject
              </Button>
            </ButtonGroup>
          </div>
        ),
      },
    ],
    []
  );

  const dataResponse = useMemo(() => usersRequestsState["data"]);

  console.log("dataResponse: ", dataResponse);

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1, transition: { delay: 0.2 } }}
    >
      <ContactsTable columns={columns} data={dataResponse} />
    </motion.div>
  );
}

export default ContactsList;
</code>```

答:
There is no use of just putting a function reference and not using it

```<code>onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}
</code>```

You should invoke the function by putting () at the end of the handleClick as:

```<code>onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick(ev);    // INVOCATION
                  dispatch(approveUser(row.original.id));
                }}
</code>```

This is just personal preference

You are handling onClick inline and trying to invoke the function handleClick, so It would be much cleaner if you could just set the state of Open inside the handler.

```<code>setOpen(true);
</code>```

Below code is much more readable

```<code>onClick={(ev) => {
  ev.stopPropagation();
  setOpen(true);
  dispatch(approveUser(row.original.id));
}}
</code>```

Body:
I'm trying to display a group of users in a table, and I'm using a library called "ReactTable", and I have an "approve" button, when the user clicks on the "approve" button two things should happen:

The first will be a dispatch of the approveUser function

The second thing, a message will appear that "acceptance has been completed".

The problem is that I want to put two functions in the same button and the same "onClick", and when I did that the site was no longer working,

How can I solve the problem?

function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

const useStyles = makeStyles({
  button1: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#43a047",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#43a047",
    },
  },
  button2: {
    backgroundColor: "none",
    "&:hover": {
      backgroundColor: "#e53935",
      color: "#e8e4e4",
      transition: "0.3s",
      borderColor: "#e53935",
    },
  },
});

function ContactsList(props) {
  const classes = useStyles();
  const dispatch = useDispatch();
  const [open, setOpen] = React.useState(false);

  const handleClick = () => {
    setOpen(true);
  };

  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }

    setOpen(false);
  };

  useEffect(() => {
    dispatch(getUsersRequests());
  }, [dispatch]);

  const usersRequestsState = useSelector(
    (state) => state.usersRequestsApp["usersRequests"]
  );

  console.log(
    "requests inside Contacts List: ",
    usersRequestsState["usersRequests"]
  );

  const columns = useMemo(
    () => [
      {
        Header: "",
        // this is function or property
        accessor: "avatar",
        Cell: ({ row }) => {
          return (
            <Avatar
              className="mx-8"
              alt={row.original.name}
              src={row.original.avatar}
              style={{ height: "7rem", width: "7rem" }}
            />
          );
        },
        className: "justify-center",
        width: 64,
        sortable: false,
      },
      {
        Header: "First Name",
        accessor: "firstName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Last Name",
        accessor: "lastName",
        className: "font-medium",
        sortable: true,
      },
      {
        Header: "Email",
        accessor: "email",
        sortable: true,
      },
      {
        Header: "Phone Number",
        accessor: "phoneNumber",
        sortable: true,
      },
      {
        Header: "actions",
        accessor: "",
        sortable: true,
        id: "action",
        // width: 100,
        Cell: ({ row }) => (

            <ButtonGroup
              style={{
                maxWidth: "206px",
                maxHeight: "40px",
                minWidth: "206px",
                minHeight: "40px",
              }}
              aria-label="outlined primary button group"
            >
              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}
                className={classes.button1}
              >
                approve
              </Button>

              <Snackbar
                open={open}
                autoHideDuration={6000}
                onClose={handleClose}
              >
                <Alert onClose={handleClose} severity="success">
                  acceptance has been completed!
                </Alert>
              </Snackbar>

              <Button
                style={{
                  maxWidth: "100px",
                  minWidth: "100px",
                }}
                onClick={(ev) => {
                  ev.stopPropagation();
                  dispatch(rejectUser(row.original.id));
                }}
                className={classes.button2}
              >
                reject
              </Button>
            </ButtonGroup>

        ),
      },
    ],
    []
  );

  const dataResponse = useMemo(() => usersRequestsState["data"]);

  console.log("dataResponse: ", dataResponse);

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1, transition: { delay: 0.2 } }}
    >
      <ContactsTable columns={columns} data={dataResponse} />
    </motion.div>
  );
}

export default ContactsList;

Body:
There is no use of just putting a function reference and not using it

onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick;
                  dispatch(approveUser(row.original.id));
                }}

You should invoke the function by putting () at the end of the handleClick as:

onClick={(ev) => {
                  ev.stopPropagation();
                  handleClick(ev);    // INVOCATION
                  dispatch(approveUser(row.original.id));
                }}

This is just personal preference

You are handling onClick inline and trying to invoke the function handleClick, so It would be much cleaner if you could just set the state of Open inside the handler.

setOpen(true);

Below code is much more readable

onClick={(ev) => {
  ev.stopPropagation();
  setOpen(true);
  dispatch(approveUser(row.original.id));
}}


问:
Flutter Bloc and Http Library bloc state not updating
I use bloc 8.0.1 and http ^0.13.4.

When you run the application, only the WeatherInitial() status appears on the screen. I can't see other states. debugPrint("debug3"); I can't see the line of code in console. The try catch doesn't go inside the line of code. Can you find out what the problem is?

BLOC

```<code>class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {
final WeatherRepository repository = locator<WeatherRepository>();

WeatherBloc() : super(WeatherInitial()) {
  on<WeatherEvent>((event, emit) async {
   if (event is FetchWeatherEvent) {
     WeatherLoadingState();
    try {
     final Weather? weather = await repository.getWeather(event.cityName);
      WeatherLoadedState(weather: weather!);
      debugPrint("debug3");
     } catch (_) {
      WeatherErrorState();
    }
   }
  });
  }
}
</code>```

EVENT

```<code> abstract class WeatherEvent extends Equatable {
 const WeatherEvent();

 @override
 List<Object> get props => [];
 }

 class FetchWeatherEvent extends WeatherEvent {
  final String cityName;

 const FetchWeatherEvent({required this.cityName});
}
</code>```

State

```<code> abstract class WeatherState extends Equatable {
  const WeatherState();

  @override
  List<Object> get props => [];
  }

 class WeatherInitial extends WeatherState {}

 class WeatherLoadingState extends WeatherState {}

 class WeatherLoadedState extends WeatherState {
  final Weather weather;

const WeatherLoadedState({required this.weather});
 }
class WeatherErrorState extends WeatherState {}
</code>```

Body

```<code> class WeatherApp extends StatelessWidget {
     String? selectedCity;
    @override
     Widget build(BuildContext context) {
    final _weatherBloc = BlocProvider.of<WeatherBloc>(context);
    return Scaffold(
     appBar: AppBar(
       title: const Text("WeatherApp"),
        actions: [
       IconButton(
        onPressed: () async {
          selectedCity = await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const CityChoose(),
            ),
          );
          if (selectedCity != null) {
            _weatherBloc.add(FetchWeatherEvent(cityName:
     selectedCity!));
          }
        },
        icon: const Icon(Icons.search),
      ),
     ],
    ),
   body: Center(
    child: BlocBuilder(
      bloc: _weatherBloc,
      builder: (context, WeatherState state) {
        if (state is WeatherInitial) {
          return const Center(
            child: Text("Select City"),
          );
        }
         if (state is WeatherLoadingState) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
         if (state is WeatherLoadedState) {
          final weather = state.weather;
          debugPrint(weather.title);
          return ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                    child: LocationWidget(
                  selectedCity: weather.title,
                )),
              ),
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: LastUpdateWidget()),
              ),
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: WeatherImageWiddget()),
              ),
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Center(child: TemperatureCondition()),
              ),
            ],
          );
        } else {
          return const Center(
            child: Text("Error"),
          );
        }
         },
        ),
      ),
</code>```

答:
You need to use emit to emit a state in the Bloc. emit is declared in the closure of on<T>.

```<code>emit(WeatherLoadedState(weather: weather!));
emit(WeatherErrorState());
</code>```

Body:
I use bloc 8.0.1 and http ^0.13.4.

When you run the application, only the WeatherInitial() status appears on the screen. I can't see other states. debugPrint("debug3"); I can't see the line of code in console. The try catch doesn't go inside the line of code. Can you find out what the problem is?

BLOC

class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {
final WeatherRepository repository = locator<WeatherRepository>();

WeatherBloc() : super(WeatherInitial()) {
  on<WeatherEvent>((event, emit) async {
   if (event is FetchWeatherEvent) {
     WeatherLoadingState();
    try {
     final Weather? weather = await repository.getWeather(event.cityName);
      WeatherLoadedState(weather: weather!);
      debugPrint("debug3");
     } catch (_) {
      WeatherErrorState();
    }
   }
  });
  }
}

EVENT

 abstract class WeatherEvent extends Equatable {
 const WeatherEvent();

 @override
 List<Object> get props => [];
 }

 class FetchWeatherEvent extends WeatherEvent {
  final String cityName;

 const FetchWeatherEvent({required this.cityName});
}

State

 abstract class WeatherState extends Equatable {
  const WeatherState();

  @override
  List<Object> get props => [];
  }

 class WeatherInitial extends WeatherState {}

 class WeatherLoadingState extends WeatherState {}

 class WeatherLoadedState extends WeatherState {
  final Weather weather;

const WeatherLoadedState({required this.weather});
 }
class WeatherErrorState extends WeatherState {}

Body

 class WeatherApp extends StatelessWidget {
     String? selectedCity;
    @override
     Widget build(BuildContext context) {
    final _weatherBloc = BlocProvider.of<WeatherBloc>(context);
    return Scaffold(
     appBar: AppBar(
       title: const Text("WeatherApp"),
        actions: [
       IconButton(
        onPressed: () async {
          selectedCity = await Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const CityChoose(),
            ),
          );
          if (selectedCity != null) {
            _weatherBloc.add(FetchWeatherEvent(cityName:
     selectedCity!));
          }
        },
        icon: const Icon(Icons.search),
      ),
     ],
    ),
   body: Center(
    child: BlocBuilder(
      bloc: _weatherBloc,
      builder: (context, WeatherState state) {
        if (state is WeatherInitial) {
          return const Center(
            child: Text("Select City"),
          );
        }
         if (state is WeatherLoadingState) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
         if (state is WeatherLoadedState) {
          final weather = state.weather;
          debugPrint(weather.title);
          return ListView(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Center(
                    child: LocationWidget(
                  selectedCity: weather.title,
                )),
              ),
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: LastUpdateWidget()),
              ),
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: WeatherImageWiddget()),
              ),
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Center(child: TemperatureCondition()),
              ),
            ],
          );
        } else {
          return const Center(
            child: Text("Error"),
          );
        }
         },
        ),
      ),

Body:
You need to use emit to emit a state in the Bloc. emit is declared in the closure of on<T>.

emit(WeatherLoadedState(weather: weather!));
emit(WeatherErrorState());


问:
Dynamic CSS for 2 columns
Is there a way to create a dynamic CSS for 2 columns? What I mean is, there are 2 columns in my webpage, the left and right column. It is similar to Facebook, where the profile picture is the left column and the right column is where your feeds are located. When a link is selected from the left column, without refreshing the page, the right column will display the page automatically. The left column is where my links are located and it is fixed. The only change factor is my right column. How can I create and apply the CSS?</p>

答:
You don't need a CSS template in order to use columns. All you need to do is set your column widths to percentages instead of pixels. If you're using a three column grid, with one div taking one column and the other spanning two, then the percentage for the first column would be 33.3333333% (don't bother rounding up, the browser will take care of it) and the second div would be 66.6666666%.

Also, in order for your second div to refresh without loading another page, you'll have to use Ajax.

Title: Dynamic CSS for 2 columns


问:
Swashbuckle and .Net Core Web API – Flatten schema for Optional<T>
I'm using Optional<T> and a Custom Converter to implement PATCH with Text.Json on a resource according to Distinguish between NULL and not present using JSON Merge Patch with NetCore WebApi and System.Text.Json

Let's take this example for the DTO:

```<code>public class PatchGroupDTO
    {
        public Optional<string?> Name { get; init; }
        public Optional<string?> NickName{ get; init; }
    }
</code>```

Swagger then shows for the 'Example Value'

```<code>{
  "name": {
    "value": "string"
  },
  "nickName": {
    "value": "string"
  }
}
</code>```

and the 'Schema':

```<code>PatchGroupDTO{
   name     StringOptional{...}
   nickName StringOptional{...}
}
</code>```

How can I achieve that Swagger shows the correct input format of the JSON?

```<code>{
  "name": "string",
  "nickName": "string"
}

PatchGroupDTO{
   name     string nullable:true
   nickName string nullable:true
}
</code>```

Is it possible to generally flatten all Optional<T> types?

答:
to flatten an Optional for a specific instance of T is easy by using MapType and a solution using your Optional-type is:

```<code>services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Elwis.API", Version = "v1" });
        c.MapType<Optional<Guid?>>(() => new OpenApiSchema { Type = "string", Format = "uuid" });
        c.MapType<Optional<DateTime?>>(() => new OpenApiSchema { Type = "string", Format= "date-time" });
        c.MapType<Optional<string?>>(() => new OpenApiSchema { Type = "string" });
        c.MapType<Optional<bool?>>(() => new OpenApiSchema { Type = "boolean" });
        c.MapType<Optional<int?>>(() => new OpenApiSchema { Type = "integer" });

</code>```

My solution is based on:
Change property type as exported by Swagger/Swashbuckle.

If you use Nullable Types you also have to map the nullable types, as mentioned in the article: Swashbuckle MapType<Type> doesn't work with parameters.

The general problem "flatten all Optional types" is discussed in this article: How to expose a custom generic type as a string in Swagger schema using Swashbuckle.AspNetCore.

It seems to be possible by using a custom SchemaFilter, but i never tried it and would recommend to stay by mapping the concrete instances needed in your program.

Body:
I'm using Optional<T> and a Custom Converter to implement PATCH with Text.Json on a resource according to Distinguish between NULL and not present using JSON Merge Patch with NetCore WebApi and System.Text.Json

Let's take this example for the DTO:

public class PatchGroupDTO
    {
        public Optional<string?> Name { get; init; }
        public Optional<string?> NickName{ get; init; }
    }

Swagger then shows for the 'Example Value'

{
  "name": {
    "value": "string"
  },
  "nickName": {
    "value": "string"
  }
}

and the 'Schema':

PatchGroupDTO{
   name     StringOptional{...}
   nickName StringOptional{...}
}

How can I achieve that Swagger shows the correct input format of the JSON?

{
  "name": "string",
  "nickName": "string"
}

PatchGroupDTO{
   name     string nullable:true
   nickName string nullable:true
}

Is it possible to generally flatten all Optional<T> types?

Body:
to flatten an Optional for a specific instance of T is easy by using MapType and a solution using your Optional-type is:

services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Elwis.API", Version = "v1" });
        c.MapType<Optional<Guid?>>(() => new OpenApiSchema { Type = "string", Format = "uuid" });
        c.MapType<Optional<DateTime?>>(() => new OpenApiSchema { Type = "string", Format= "date-time" });
        c.MapType<Optional<string?>>(() => new OpenApiSchema { Type = "string" });
        c.MapType<Optional<bool?>>(() => new OpenApiSchema { Type = "boolean" });
        c.MapType<Optional<int?>>(() => new OpenApiSchema { Type = "integer" });

My solution is based on:
Change property type as exported by Swagger/Swashbuckle.

If you use Nullable Types you also have to map the nullable types, as mentioned in the article: Swashbuckle MapType<Type> doesn't work with parameters.

The general problem "flatten all Optional types" is discussed in this article: How to expose a custom generic type as a string in Swagger schema using Swashbuckle.AspNetCore.

It seems to be possible by using a custom SchemaFilter, but i never tried it and would recommend to stay by mapping the concrete instances needed in your program.


问:
python csvwriter outputs strings on seperate rows instead of being on the same row
Been a while and i'm getting back into coding for a research project, i'm currently doing a practice site to see what I need to do for the actual site.

I've got everything working how I want, but when the scraped data is outputted to csv it puts the value into a new row instead of the column beside the row it was meant to be on.

I've added links to the output below. Let me know what I need changing as I can't figure it out.

```<code>import csv, re
import requests
from bs4 import BeautifulSoup

URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
with open('testScraperEX.csv', 'w') as f:
    write = csv.writer(f)
    soup = BeautifulSoup(page.content, "html.parser")
    write.writerow(['Title', 'Company', 'Location'])
    results = soup.find(id="ResultsContainer")
    job_elements = results.find_all("div", class_="card-content")
    for job_element in job_elements:
        title_element = job_element.find("h2", class_="title")
        company_element = job_element.find("h3", class_="company")
        location_element = job_element.find("p", class_="location")
        Title = title_element.text.strip()
        Company = company_element.text.strip()
        Location = location_element.text.strip()
        write.writerows([[Title],[Company],[Location]])
</code>```

This is the current output

This is how I want the output to be

Thanks :)

答:
```<code>import csv
import requests
from bs4 import BeautifulSoup

URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
with open('testScraperEX.csv', 'w', newline='') as f:
    write = csv.writer(f)
    soup = BeautifulSoup(page.content, "html.parser")
    write.writerow(['Title', 'Company', 'Location'])
    results = soup.find(id="ResultsContainer")
    job_elements = results.find_all("div", class_="card-content")
    for job_element in job_elements:
        title_element = job_element.find("h2", class_="title")
        company_element = job_element.find("h3", class_="company")
        location_element = job_element.find("p", class_="location")
        Title = title_element.text.strip()
        Company = company_element.text.strip()
        Location = location_element.text.strip()
        write.writerow([Title, Company, Location])
</code>```

output in the csv file:

```<code>Title,Company,Location
Senior Python Developer,"Payne, Roberts and Davis","Stewartbury, AA"
Energy engineer,Vasquez-Davidson,"Christopherville, AA"
Legal executive,"Jackson, Chambers and Levy","Port Ericaburgh, AA"
Fitness centre manager,Savage-Bradley,"East Seanview, AP"
Product manager,Ramirez Inc,"North Jamieview, AP"
... and many more lines ...
</code>```

This line in your code

```<code>write.writerows([[Title],[Company],[Location]])
</code>```

writes 3 rows, because each element unnecessarily is inside a list (i.e. you have list of 3 one-element lists). This

```<code>write.writerow([Title, Company, Location])
</code>```

writes one line - a list of 3 elements.

Note wrte.writerows vs write.writerow and [[Title],[Company],[Location]] vs [Title, Company, Location]

Body:
Been a while and i'm getting back into coding for a research project, i'm currently doing a practice site to see what I need to do for the actual site.

I've got everything working how I want, but when the scraped data is outputted to csv it puts the value into a new row instead of the column beside the row it was meant to be on.

I've added links to the output below. Let me know what I need changing as I can't figure it out.

import csv, re
import requests
from bs4 import BeautifulSoup

URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
with open('testScraperEX.csv', 'w') as f:
    write = csv.writer(f)
    soup = BeautifulSoup(page.content, "html.parser")
    write.writerow(['Title', 'Company', 'Location'])
    results = soup.find(id="ResultsContainer")
    job_elements = results.find_all("div", class_="card-content")
    for job_element in job_elements:
        title_element = job_element.find("h2", class_="title")
        company_element = job_element.find("h3", class_="company")
        location_element = job_element.find("p", class_="location")
        Title = title_element.text.strip()
        Company = company_element.text.strip()
        Location = location_element.text.strip()
        write.writerows([[Title],[Company],[Location]])

This is the current output

This is how I want the output to be

Thanks :)

Body:
import csv
import requests
from bs4 import BeautifulSoup

URL = "https://realpython.github.io/fake-jobs/"
page = requests.get(URL)
with open('testScraperEX.csv', 'w', newline='') as f:
    write = csv.writer(f)
    soup = BeautifulSoup(page.content, "html.parser")
    write.writerow(['Title', 'Company', 'Location'])
    results = soup.find(id="ResultsContainer")
    job_elements = results.find_all("div", class_="card-content")
    for job_element in job_elements:
        title_element = job_element.find("h2", class_="title")
        company_element = job_element.find("h3", class_="company")
        location_element = job_element.find("p", class_="location")
        Title = title_element.text.strip()
        Company = company_element.text.strip()
        Location = location_element.text.strip()
        write.writerow([Title, Company, Location])

output in the csv file:

Title,Company,Location
Senior Python Developer,"Payne, Roberts and Davis","Stewartbury, AA"
Energy engineer,Vasquez-Davidson,"Christopherville, AA"
Legal executive,"Jackson, Chambers and Levy","Port Ericaburgh, AA"
Fitness centre manager,Savage-Bradley,"East Seanview, AP"
Product manager,Ramirez Inc,"North Jamieview, AP"
... and many more lines ...

This line in your code

write.writerows([[Title],[Company],[Location]])

writes 3 rows, because each element unnecessarily is inside a list (i.e. you have list of 3 one-element lists). This

write.writerow([Title, Company, Location])

writes one line - a list of 3 elements.

Note wrte.writerows vs write.writerow and [[Title],[Company],[Location]] vs [Title, Company, Location]


问:
How do I find out what code is causing JavaScript heap out of memory
I'm trying to run yarn start but get this:

Starting the development server...

ts-loader: Using typescript@3.9.10 and C:\DevTools\git\mymoto\tsconfig.json

<--- Last few GCs --->

[9076:000001F4910F0DA0]   120343 ms: Mark-sweep (reduce) 2045.0 (2051.8) -> 2044.3 (2053.0) MB, 1410.7 / 0.0 ms  (average mu = 0.123, current mu = 0.011) allocation failure scavenge might not succeed
[9076:000001F4910F0DA0]   122662 ms: Mark-sweep (reduce) 2045.4 (2052.0) -> 2044.6 (2053.0) MB, 2288.3 / 0.0 ms  (average mu = 0.057, current mu = 0.013) allocation failure scavenge might not succeed

<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
1: 00007FF79BA7021F napi_wrap+109311
2: 00007FF79BA15286 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NumberOfElementsOffset+33302
3: 00007FF79BA16056 node::OnFatalError+294
4: 00007FF79C2E054E v8::Isolate::ReportExternalAllocationLimitReached+94
5: 00007FF79C2C53CD v8::SharedArrayBuffer::Externalize+781
6: 00007FF79C16F85C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1516
7: 00007FF79C17AB9A v8::internal::Heap::ProtectUnprotectedMemoryChunks+1258
8: 00007FF79C177D49 v8::internal::Heap::PageFlagsAreConsistent+2457
9: 00007FF79C16C971 v8::internal::Heap::CollectGarbage+2033
10: 00007FF79C16AB75 v8::internal::Heap::AllocateExternalBackingStore+1317
11: 00007FF79C18AF67 v8::internal::Factory::NewFillerObject+183
12: 00007FF79BEBAFF1 v8::internal::interpreter::JumpTableTargetOffsets::iterator::operator=+1409
13: 00007FF79C368EFD v8::internal::SetupIsolateDelegate::SetupHeap+463949
14: 000001177FAE26D4

I've seen a few questions on here they all seem to suggest something along the lines of node --max_old_space_size=8048. In most cases the question has highlighted the code which causes this. I can't figure out what this is. How do I find out what is causing the issue? I'd like to initially see if there's anything wrong there rather than blindly trying something.

Could having a copy of my node_modules folder in the project folder cause this in any way?

答:
Had this issue a while back. This helped me

```<code> node --max-old-space-size=8048
</code>```

Have you tried using NVM? Downgrading your Node/Typescript version can help you. I used Node v14.15.5 btw.

Body:
Had this issue a while back. This helped me

 node --max-old-space-size=8048

Have you tried using NVM? Downgrading your Node/Typescript version can help you. I used Node v14.15.5 btw.


问:
Left Join Overrides Non-Null Value with Null value when record is empty on second table
I have two tables:

Table 1: qtrade
qtrade columns
qtrade values

Table 2: qsale
qsale columns
qsale values

These two table have common "tid" which is unique trade id. I need to get tid's with their qsale values if it is available. So, i tried to LEFT JOIN method like this:

```<code>'SELECT *
FROM `qtrade`
LEFT JOIN `qsale` ON qtrade.tid = qsale.tid'
</code>```

The query retrieves joined data, but for tid=11 there is no qsale record, so it retrieves NULL valeus as expected, but also overrides tid with NULL value as not expected. It gets tid NULL.

I have serached that and found COALESCE trick. It might work, but i would write down all column names in qtrade and qsale, these are around 32 columns. Too long. If there any trick to overcome this issue. I think 'SELECT *, COALESCE(qsale.tid, qtrade.tid) tid' will not work. Meaning only coalesce tid, and get all column data. Is there any other way ?

答:
What you describe does work.

Demo:

```<code>mysql> create table qtrade (tid int);
Query OK, 0 rows affected (0.01 sec)

mysql> create table qsale (tid int);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into qtrade set tid=42;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT *
    -> FROM `qtrade`
    -> LEFT JOIN `qsale` ON qtrade.tid = qsale.tid;
+------+------+
| tid  | tid  |
+------+------+
|   42 | NULL |
+------+------+
1 row in set (0.00 sec)

mysql> SELECT *, COALESCE(qsale.tid, qtrade.tid) AS tid
 FROM `qtrade` LEFT JOIN `qsale` ON qtrade.tid = qsale.tid;
+------+------+------+
| tid  | tid  | tid  |
+------+------+------+
|   42 | NULL |   42 |
+------+------+------+
1 row in set (0.00 sec)
</code>```

MySQL query result sets allow multiple columns to have the same name.

But the problem arises when you have a client that fetches the results into an associative array or hashmap, which only allows one entry per name.

In that case, the only alternative is to change the client code to fetch results into an ordinal array instead of an associative array, and then reference the columns of the result by position instead of by name.

I never use SELECT * in production code anyway. Just write out the columns. If typing 32 column names is the bottleneck in your programming productivity, then you're doing it wrong.

Body:
I have two tables:

Table 1: qtrade
qtrade columns
qtrade values

Table 2: qsale
qsale columns
qsale values

These two table have common "tid" which is unique trade id. I need to get tid's with their qsale values if it is available. So, i tried to LEFT JOIN method like this:

'SELECT *
FROM `qtrade`
LEFT JOIN `qsale` ON qtrade.tid = qsale.tid'

The query retrieves joined data, but for tid=11 there is no qsale record, so it retrieves NULL valeus as expected, but also overrides tid with NULL value as not expected. It gets tid NULL.

I have serached that and found COALESCE trick. It might work, but i would write down all column names in qtrade and qsale, these are around 32 columns. Too long. If there any trick to overcome this issue. I think 'SELECT *, COALESCE(qsale.tid, qtrade.tid) tid' will not work. Meaning only coalesce tid, and get all column data. Is there any other way ?

Body:
What you describe does work.

Demo:

mysql> create table qtrade (tid int);
Query OK, 0 rows affected (0.01 sec)

mysql> create table qsale (tid int);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into qtrade set tid=42;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT *
    -> FROM `qtrade`
    -> LEFT JOIN `qsale` ON qtrade.tid = qsale.tid;
+------+------+
| tid  | tid  |
+------+------+
|   42 | NULL |
+------+------+
1 row in set (0.00 sec)

mysql> SELECT *, COALESCE(qsale.tid, qtrade.tid) AS tid
 FROM `qtrade` LEFT JOIN `qsale` ON qtrade.tid = qsale.tid;
+------+------+------+
| tid  | tid  | tid  |
+------+------+------+
|   42 | NULL |   42 |
+------+------+------+
1 row in set (0.00 sec)

MySQL query result sets allow multiple columns to have the same name.

But the problem arises when you have a client that fetches the results into an associative array or hashmap, which only allows one entry per name.

In that case, the only alternative is to change the client code to fetch results into an ordinal array instead of an associative array, and then reference the columns of the result by position instead of by name.

I never use SELECT * in production code anyway. Just write out the columns. If typing 32 column names is the bottleneck in your programming productivity, then you're doing it wrong.


问:
Accessing private members of surrounding class
I have two classes like this:

#include <iostream>

class A {
    public:
        class B {
            public:
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
    private:
        int x;
};
```
<p>Obviously this piece of code doesn't work because <code>B</code> can't access <code>x</code>, but is there a way to make it work?</p>
<p>I've tried using <code>friend class</code> keyword in both classes like this:</p>
<pre class="lang-c prettyprint-override"><code>class A {
    public:
        class B {
            public:
            friend class A;
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
        friend class B;
    private:
        int x;
};
</code>```

But it didn't work either, and I can't figure out if it's even possible.

答:
According to the C++ 17 Standard (14.7 Nested classes)

1 A nested class is a member and as such has the same access rights as
any other member. The members of an enclosing class have no special
access to members of a nested class; the usual access rules (Clause
14) shall be obeyed.

The problem with the provided code is that x is not a static data member of the class A. You need to provide an object of the class A the data member x of which will be accessed within an object of the nested class.

For example

```<code>    class A {
    public:
        class B {
        public:
            void    printX( const A &a ) const { std::cout << a.x << std::endl; }
        };
    private:
        int x;
    };

    A::B().printX( A() );
</code>```

Body:
I have two classes like this:

#include <iostream>

class A {
    public:
        class B {
            public:
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
    private:
        int x;
};

Obviously this piece of code doesn't work because B can't access x, but is there a way to make it work?

I've tried using friend class keyword in both classes like this:

class A {
    public:
        class B {
            public:
            friend class A;
                void    printX(void) const { std::cout << A::x << std::endl; }
        };
        friend class B;
    private:
        int x;
};

But it didn't work either, and I can't figure out if it's even possible.

Body:
According to the C++ 17 Standard (14.7 Nested classes)

1 A nested class is a member and as such has the same access rights as
any other member. The members of an enclosing class have no special
access to members of a nested class; the usual access rules (Clause
14) shall be obeyed.

The problem with the provided code is that x is not a static data member of the class A. You need to provide an object of the class A the data member x of which will be accessed within an object of the nested class.

For example

    class A {
    public:
        class B {
        public:
            void    printX( const A &a ) const { std::cout << a.x << std::endl; }
        };
    private:
        int x;
    };

    A::B().printX( A() );


问:
Add a delimiter at the end of each line in csv.writer
I use the function below, but I get problem when reading it with as a dict for example. But if I add a delimiter as a last character in the header it works.

The code produce csv as:

```<code>Username;Name;Lastname
</code>```

I use this function to create the csv's:

```<code>def create_csv_with_data(data, dst):
    '''
    Create a CSV from a list with lists.
    '''
    with open(dst, 'w', encoding='UTF8', newline='') as f:
        writer = csv.writer(f, delimiter=';')
        for i in data:
            writer.writerow(i)
    print(str(dst) + ' file created.')
</code>```

Expected output:

```<code>Username;Name;Lastname;
</code>```

答:
You can use the lineterminator option:

```<code>writer = csv.writer(f, delimiter=';', lineterminator=';\n')
</code>```

Body:
I use the function below, but I get problem when reading it with as a dict for example. But if I add a delimiter as a last character in the header it works.

The code produce csv as:

Username;Name;Lastname

I use this function to create the csv's:

def create_csv_with_data(data, dst):
    '''
    Create a CSV from a list with lists.
    '''
    with open(dst, 'w', encoding='UTF8', newline='') as f:
        writer = csv.writer(f, delimiter=';')
        for i in data:
            writer.writerow(i)
    print(str(dst) + ' file created.')

Expected output:

Username;Name;Lastname;

Body:
You can use the lineterminator option:

writer = csv.writer(f, delimiter=';', lineterminator=';\n')


问:
Round up from .5 in a %
Ceiling rounds up no matter if you get .1, .3, .5, .7. or whatever the value is for the decimal.

I need to know how to only round up if you have .5.  So for example [number].5 round up.

Anyone know how to do this?

答: Math.Round() uses banker's rounding by default, so it will round to the nearest even number when dealing with [number].5. In other words, Math.Round(0.5) is 0, while Math.Round(1.5) is 2. You can make it always round up by saying Math.Round(0.5, MidpointRounding.AwayFromZero);

Title: Round up from .5 in a %


问:
How to enable "Always show crash dialog" in developer options on an Android emulator via adb commands?
How to enable or disable a specific developer options using adb?

I have found some posts saying to enable developer settings via adb shell settings put global development_settings_enabled 1. But how to enable a specific developer option?

For example, suppose I want to enable "Always show crash dialog" on an Android emulator. Except of physically switching the button, is it possible to programmatically enable it like using adb commands?

答:
Try adb shell settings list global ...once with the option enabled and once with it disabled.

Maybe this one?

```<code>private static final String SHOW_FIRST_CRASH_DIALOG_KEY = "show_first_crash_dialog";
</code>```

https://github.com/aosp-mirror/platform_packages_apps_settings/tree/master/src/com/android/settings/development

Body:
Try adb shell settings list global ...once with the option enabled and once with it disabled.

Maybe this one?

private static final String SHOW_FIRST_CRASH_DIALOG_KEY = "show_first_crash_dialog";

https://github.com/aosp-mirror/platform_packages_apps_settings/tree/master/src/com/android/settings/development


问:
Tcl: test for nested list
How can I efficiently test whether a Tcl list is nested (i.e. contains lists as elements)?

Based on https://wiki.tcl-lang.org/page/Depth+of+a+list I constructed the following proc:

```<code>proc isNestedList {l} {
    return [expr ![string equal $l [concat {*}$l]]]
}
</code>```

This gives the desired behavior (except for the case {A} which generally cannot be handled differently as far as I know, see https://stackoverflow.com/a/66799916/3852630):

% isNestedList A
0
% isNestedList {A}
0
% isNestedList {{A}}
1
% isNestedList {A B}
0
% isNestedList {{A B}}
1
% isNestedList {A {B C}}
1
```

However, for long lists which are not nested, isNestedList is slow, probably due to the conversion from list to string. I tried a different version where I compare $l and [concat {*}$l] by ::struct::list equal (https://tools.ietf.org/doc/tcllib/html/struct_list.html) to avoid this conversion, but that is even slower.

Thanks a lot for your help!

答:
I realised that my earlier answer is overcomplicated and less than optimal.  I think this is better:</p>
```<code>proc isNestedList l {
    foreach a $l {
        if {$a ne [lindex $a 0]} {
            return true
        }
    }
    return false
}
</code>```

Title: Tcl: test for nested list

Body:
How can I efficiently test whether a Tcl list is nested (i.e. contains lists as elements)?

Based on https://wiki.tcl-lang.org/page/Depth+of+a+list I constructed the following proc:

proc isNestedList {l} {
    return [expr ![string equal $l [concat {*}$l]]]
}

This gives the desired behavior (except for the case {A} which generally cannot be handled differently as far as I know, see https://stackoverflow.com/a/66799916/3852630):

% isNestedList A
0
% isNestedList {A}
0
% isNestedList {{A}}
1
% isNestedList {A B}
0
% isNestedList {{A B}}
1
% isNestedList {A {B C}}
1

However, for long lists which are not nested, isNestedList is slow, probably due to the conversion from list to string. I tried a different version where I compare $l and [concat {*}$l] by ::struct::list equal (https://tools.ietf.org/doc/tcllib/html/struct_list.html) to avoid this conversion, but that is even slower.

Thanks a lot for your help!

Body:
I realised that my earlier answer is overcomplicated and less than optimal.  I think this is better:

proc isNestedList l {
    foreach a $l {
        if {$a ne [lindex $a 0]} {
            return true
        }
    }
    return false
}