问:
Android Camera Intent not working in OnePlus devices
I was trying to use the native camera app that comes pre-installed in Android devices to capture the images for my app. For this I've been using this code:

A function is called when the user taps on button

```<code>take_img_btn.setOnClickListener {
    dispatchTakePictureIntent()
}
</code>```

That function is supposed to do this:

```<code>    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            takePictureIntent.resolveActivity(packageManager)?.also {
                // Create the File where the photo should go
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    // Error occurred while creating the File
                    ex.printStackTrace()
                    null
                }
                // Continue only if the File was successfully created
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        this,
                        "com.example.android.fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        }
    }

    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yy-MM-dd-HH-mm-ss-SS",Locale.getDefault()).format(System.currentTimeMillis())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "FNL_${timeStamp}_",
            ".jpg",
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            currentPhotoPath = absolutePath
            currentPhotoName = name
        }
    }
</code>```

And the FileProvider is configured in the Manifest like so

```<code><application>
   ...
   <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
    ...
</application>
</code>```

I am also asking for Camera feature in Manifest

```<code><manifest>
    ...
    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
    ...
</manifest>
</code>```

When I run this app on my android device (Realme 6 Pro) and tap the button then:

The app opens the native camera app

I can capture the image

The image is saved to the location where it was specified

But when this same app is deployed on OnePlus devices (in our case OnePlus Nord) and tap the button then nothing happens. It feels like the button is not programmed.

This code is taken from here: https://developer.android.com/training/camera/photobasics

It would be really helpful if someone help.

答:
in higher version devices like Oneplus nord with android 11 or 12 the camera intent not working i added this code it is worked for me

Add this line in AndroidManifest.xml

```<code><queries>
        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>
    </queries>
</code>```

and also add your other permission required for camera

Body:
I was trying to use the native camera app that comes pre-installed in Android devices to capture the images for my app. For this I've been using this code:

A function is called when the user taps on button

take_img_btn.setOnClickListener {
    dispatchTakePictureIntent()
}

That function is supposed to do this:

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            takePictureIntent.resolveActivity(packageManager)?.also {
                // Create the File where the photo should go
                val photoFile: File? = try {
                    createImageFile()
                } catch (ex: IOException) {
                    // Error occurred while creating the File
                    ex.printStackTrace()
                    null
                }
                // Continue only if the File was successfully created
                photoFile?.also {
                    val photoURI: Uri = FileProvider.getUriForFile(
                        this,
                        "com.example.android.fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
                }
            }
        }
    }

    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yy-MM-dd-HH-mm-ss-SS",Locale.getDefault()).format(System.currentTimeMillis())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "FNL_${timeStamp}_",
            ".jpg",
            storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            currentPhotoPath = absolutePath
            currentPhotoName = name
        }
    }

And the FileProvider is configured in the Manifest like so

<application>
   ...
   <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
    ...
</application>

I am also asking for Camera feature in Manifest

<manifest>
    ...
    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
    ...
</manifest>

When I run this app on my android device (Realme 6 Pro) and tap the button then:

The app opens the native camera app

I can capture the image

The image is saved to the location where it was specified

But when this same app is deployed on OnePlus devices (in our case OnePlus Nord) and tap the button then nothing happens. It feels like the button is not programmed.

This code is taken from here: https://developer.android.com/training/camera/photobasics

It would be really helpful if someone help.

Body:
in higher version devices like Oneplus nord with android 11 or 12 the camera intent not working i added this code it is worked for me

Add this line in AndroidManifest.xml

<queries>
        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>
    </queries>

and also add your other permission required for camera


来源: stackexchange

问:
What is the purpose of sx prop in Material UI?
```<code><Box style={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>
</code>```
```<code><Box sx={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>
</code>```

React.js + Material UI

The above two examples do the same thing, one uses sx prop in material UI, the other is regular inline styling using css, so what is the point of "sx"? and should it always be used over style={{}} when using Material UI?

答:
The sx prop is a shortcut for defining custom style that has access
to the theme

It can accept any CSS properties plus a few extra from MUI.

There are differences like :

shortHand: padding-top can be written as pt.

access to theme: If you define your theme in material UI, sx prop can directly access its properties like color.
Example from the doc :

```<code>import * as React from 'react';
import { Box, ThemeProvider, createTheme } from '@mui/system';

const theme = createTheme({
  palette: {
    background: {
      paper: '#fff',
    },
    text: {
      primary: '#173A5E',
      secondary: '#46505A',
    },
    action: {
      active: '#001E3C',
    },
    success: {
      dark: '#009688',
    },
  },
});

export default function Example() {
  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={{
          bgcolor: 'background.paper',
          boxShadow: 1,
          borderRadius: 2,
          p: 2,
          minWidth: 300,
        }}
      >
        <Box sx={{ color: 'text.secondary' }}>Sessions</Box>
        <Box sx={{ color: 'text.primary', fontSize: 34, fontWeight: 'medium' }}>
          98.3 K
        </Box>
        <Box
          sx={{
            color: 'success.dark',
            display: 'inline',
            fontWeight: 'bold',
            mx: 0.5,
            fontSize: 14,
          }}
        >
          +18.77%
        </Box>
        <Box sx={{ color: 'text.secondary', display: 'inline', fontSize: 14 }}>
          vs. last week
        </Box>
      </Box>
    </ThemeProvider>
  );
}
</code>```

Properties in sx object can have functions as valuse. These functions have access to theme too.

```<code><Box sx={{ height: (theme) => theme.spacing(10) }} />
</code>```

Grid properties: gap, rowGap and columnGap are available in sx.

Responsive styles: You can define properties according to the different MUI device size shorthands:

```<code>borderColor : { xs: "red", sm: "green" },
</code>```

Access to child components: You can change styles of chlid components using nested styles:

```<code><TextField
  variant="outlined"
  sx={{
    '& .MuiInputBase-input': {
      color: 'white',
    },
  }}
/>
</code>```

Much more than CSS: The sx prop also supports CSS syntax including child and pseudo-selectors, media queries etc.
Eg:

```<code><Box
  sx={{
    // some styles
    ":hover": {  //psuedo-selectors
      boxShadow: 6,
    },
    '@media print': {  //media-queries
      width: 300,
    },
  }}
>
</code>```

Sources:

1.

2.

ContentLicense: CC BY-SA 4.0

Body:
<Box style={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>

<Box sx={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>

React.js + Material UI

The above two examples do the same thing, one uses sx prop in material UI, the other is regular inline styling using css, so what is the point of "sx"? and should it always be used over style={{}} when using Material UI?

Body:
The sx prop is a shortcut for defining custom style that has access
to the theme

It can accept any CSS properties plus a few extra from MUI.

There are differences like :

shortHand: padding-top can be written as pt.

access to theme: If you define your theme in material UI, sx prop can directly access its properties like color.
Example from the doc :

import * as React from 'react';
import { Box, ThemeProvider, createTheme } from '@mui/system';

const theme = createTheme({
  palette: {
    background: {
      paper: '#fff',
    },
    text: {
      primary: '#173A5E',
      secondary: '#46505A',
    },
    action: {
      active: '#001E3C',
    },
    success: {
      dark: '#009688',
    },
  },
});

export default function Example() {
  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={{
          bgcolor: 'background.paper',
          boxShadow: 1,
          borderRadius: 2,
          p: 2,
          minWidth: 300,
        }}
      >
        <Box sx={{ color: 'text.secondary' }}>Sessions</Box>
        <Box sx={{ color: 'text.primary', fontSize: 34, fontWeight: 'medium' }}>
          98.3 K
        </Box>
        <Box
          sx={{
            color: 'success.dark',
            display: 'inline',
            fontWeight: 'bold',
            mx: 0.5,
            fontSize: 14,
          }}
        >
          +18.77%
        </Box>
        <Box sx={{ color: 'text.secondary', display: 'inline', fontSize: 14 }}>
          vs. last week
        </Box>
      </Box>
    </ThemeProvider>
  );
}

Properties in sx object can have functions as valuse. These functions have access to theme too.

<Box sx={{ height: (theme) => theme.spacing(10) }} />

Grid properties: gap, rowGap and columnGap are available in sx.

Responsive styles: You can define properties according to the different MUI device size shorthands:

borderColor : { xs: "red", sm: "green" },

Access to child components: You can change styles of chlid components using nested styles:

<TextField
  variant="outlined"
  sx={{
    '& .MuiInputBase-input': {
      color: 'white',
    },
  }}
/>

Much more than CSS: The sx prop also supports CSS syntax including child and pseudo-selectors, media queries etc.
Eg:

<Box
  sx={{
    // some styles
    ":hover": {  //psuedo-selectors
      boxShadow: 6,
    },
    '@media print': {  //media-queries
      width: 300,
    },
  }}
>

Sources:

1.

2.


问:
Is there any charting library in elixir?
I want to plot a bar graph in elixir and save it as an image.

Is there any good charting library for doing this ?

I tried searching on elixir.libhunt.com and github.com/h4cc/awesome-elixir, but didn't find a single package for my need.

Thanks in advance.

答:
As an update to this question, you can now use the vega_lite package and LiveBook to easily plot with Elixir.

https://livebook.dev/

https://github.com/livebook-dev/vega_lite

ContentLicense: CC BY-SA 3.0


问:
onmousemove Event is not able to pass event-data in JavaScript Example
In this example, when I move mouse inside a div, I want to show the (x and y co-ordinates) of mouse current position, but it is showing error. Why?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}</code>```

onmousemove
```

答:
In your HTML just change "ev" to event and it will work.</p>
```<code>   <div id="div1" onmousemove="fifa(event)">onmousemove</div>
</code>```

Body:
In this example, when I move mouse inside a div, I want to show the (x and y co-ordinates) of mouse current position, but it is showing error. Why?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}

div {
  height:200px;
  width:200px;
  border:2px solid #000;
  background:green;
  display:inline-block;
  margin:20px;
}

onmousemove

Body:
In your HTML just change "ev" to event and it will work.

   <div id="div1" onmousemove="fifa(event)">onmousemove</div>


问:
Typescript - Type predicate / Check if instance property matches interface value
Is there a way to check that an instance property matches an interface property whose value can only ever be a single value?

```<code>enum ThingType {
  ThingA = 'thing a',
  ThingB = 'thing b',
  ...
}

interface IParent {
  type: ThingType,
}

interface IChildA extends IParent {
   type: ThingType.ThingA;
}

interface IChildB extends IParent {
   type: ThingType.ThingB;
}

const isChildThing = <T extends IChildA | IChildB>(item: IParent): item is T => {
  return item.type === T['type']; // <-- This is invalid
};

const child = {
  type: ThingType.ThingA,
};

// intended usage
isChildThing<IChildA>(child);
</code>```

I can pass in a type to the predicate check, but that seems prone to error and doesn't use any actual information about the type itself to do the check:

```<code>// works, but this relies on passing in the correct `T/type` pair
const isChildThing = <T extends IChildA | IChildB>(item: IParent, type: ThingType): item is T => {
  return item.type === type;
};

isChildThing<IChildA>(child, ThingType.ThingA);
</code>```

答:
How about having an identity function that enforces intended type-constraints...

```<code>
enum ThingType {
  ThingA = 'thing a',
  ThingB = 'thing b',
  ThingC = 'thing c'
}

interface IParent {
  type: ThingType,
}

interface IChildA extends IParent {
   type: ThingType.ThingA;
}

interface IChildAA extends IChildA {

}

interface IChildB extends IParent {
   type: ThingType.ThingB;
}

interface IChildBB extends IChildB {

}

interface IChildC extends IParent {
   type: ThingType.ThingC;
}

// const isChildThing = <T extends IChildA | IChildB>(item: IParent): item is T => {
//   return item.type === T['type']; // <-- This is invalid
// };

const reifyThing = <T extends IChildA | IChildB>(item: T): T => item;

const child = {
  type: ThingType.ThingA
}

const childA: IChildA = {
  type: ThingType.ThingA,
};

const childAA: IChildAA = childA;

const childB: IChildB = {
  type: ThingType.ThingB,
};

const childBB: IChildBB = childB;

const childC: IChildC = {
  type: ThingType.ThingC
};

// intended usage
reifyThing<IChildA>(childA);   // Ok
reifyThing<IChildA>(childAA);  // Ok
reifyThing<IChildAA>(childA);  // Ok
reifyThing<IChildAA>(childAA); // Ok
reifyThing<IChildA>(childB);   // Error
reifyThing<IChildAA>(childB);  // Error
reifyThing<IChildA>(childC);   // Error
reifyThing<IChildAA>(childC);  // Error

reifyThing<IChildB>(childB);   // Ok
reifyThing<IChildB>(childBB);  // Ok
reifyThing<IChildBB>(childB);  // Ok
reifyThing<IChildBB>(childBB); // Ok
reifyThing<IChildB>(childA);   // Error
reifyThing<IChildBB>(childA);  // Error
reifyThing<IChildB>(childC);   // Error
reifyThing<IChildBB>(childC);  // Error

reifyThing<IChildC>(childC);  // Error
reifyThing<IChildC>(childA);  // Error
reifyThing<IChildC>(childB);  // Error

</code>```

Assumptions

Static Checking

We are looking for a type-check which is actually a covariance closed over IClassA | IClassB.

On Stackoverflow, WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Body:
Is there a way to check that an instance property matches an interface property whose value can only ever be a single value?

enum ThingType {
  ThingA = 'thing a',
  ThingB = 'thing b',
  ...
}

interface IParent {
  type: ThingType,
}

interface IChildA extends IParent {
   type: ThingType.ThingA;
}

interface IChildB extends IParent {
   type: ThingType.ThingB;
}

const isChildThing = <T extends IChildA | IChildB>(item: IParent): item is T => {
  return item.type === T['type']; // <-- This is invalid
};

const child = {
  type: ThingType.ThingA,
};

// intended usage
isChildThing<IChildA>(child);

I can pass in a type to the predicate check, but that seems prone to error and doesn't use any actual information about the type itself to do the check:

// works, but this relies on passing in the correct `T/type` pair
const isChildThing = <T extends IChildA | IChildB>(item: IParent, type: ThingType): item is T => {
  return item.type === type;
};

isChildThing<IChildA>(child, ThingType.ThingA);

Body:
How about having an identity function that enforces intended type-constraints...

enum ThingType {
  ThingA = 'thing a',
  ThingB = 'thing b',
  ThingC = 'thing c'
}

interface IParent {
  type: ThingType,
}

interface IChildA extends IParent {
   type: ThingType.ThingA;
}

interface IChildAA extends IChildA {

}

interface IChildB extends IParent {
   type: ThingType.ThingB;
}

interface IChildBB extends IChildB {

}

interface IChildC extends IParent {
   type: ThingType.ThingC;
}

// const isChildThing = <T extends IChildA | IChildB>(item: IParent): item is T => {
//   return item.type === T['type']; // <-- This is invalid
// };

const reifyThing = <T extends IChildA | IChildB>(item: T): T => item;

const child = {
  type: ThingType.ThingA
}

const childA: IChildA = {
  type: ThingType.ThingA,
};

const childAA: IChildAA = childA;

const childB: IChildB = {
  type: ThingType.ThingB,
};

const childBB: IChildBB = childB;

const childC: IChildC = {
  type: ThingType.ThingC
};

// intended usage
reifyThing<IChildA>(childA);   // Ok
reifyThing<IChildA>(childAA);  // Ok
reifyThing<IChildAA>(childA);  // Ok
reifyThing<IChildAA>(childAA); // Ok
reifyThing<IChildA>(childB);   // Error
reifyThing<IChildAA>(childB);  // Error
reifyThing<IChildA>(childC);   // Error
reifyThing<IChildAA>(childC);  // Error

reifyThing<IChildB>(childB);   // Ok
reifyThing<IChildB>(childBB);  // Ok
reifyThing<IChildBB>(childB);  // Ok
reifyThing<IChildBB>(childBB); // Ok
reifyThing<IChildB>(childA);   // Error
reifyThing<IChildBB>(childA);  // Error
reifyThing<IChildB>(childC);   // Error
reifyThing<IChildBB>(childC);  // Error

reifyThing<IChildC>(childC);  // Error
reifyThing<IChildC>(childA);  // Error
reifyThing<IChildC>(childB);  // Error

Assumptions

Static Checking

We are looking for a type-check which is actually a covariance closed over IClassA | IClassB.

On Stackoverflow, WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


问:
GCC hidden optimizations
The GCC manual lists all optimization flags being applied for the different levels of optimizations (-O1, -O2, etc.). However when compiling and measuring a benchmark program (e.g. cBench's automotive_bitcount) there is a significant difference when applying an optimization level instead of turning on all the listed optimizations manually. For -O1 with the automotive_bitcount program, I measured a speedup of roughly 100% when compiling with -O1 instead of manually applying all the listed flags. Those "hidden" optimizations seem in fact to be the main part of the optimization work GCC does for -O1. When applying the flags manually, I only get a speedup of about 10% compared to no optimizations.
The same can be observed when applying all enabled flags from gcc -c -Q -O3 --help=optimizers.

In the GCC manual I found this section which would explain this behavior:

Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.
Most optimizations are completely disabled at -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified.

Since I couldn't find any further documentation on those optimizations, I wonder if there is a way of controlling them and what the optimizations are in detail?

答:
Some optimizations are directly gated by -O flags e.g. complete unroller:

```<code>{
public:
  pass_complete_unrolli (gcc::context *ctxt)
    : gimple_opt_pass (pass_data_complete_unrolli, ctxt)
  {}

  /* opt_pass methods: */
  virtual bool gate (function *) { return optimize >= 2; }
  virtual unsigned int execute (function *);

}; // class pass_complete_unrolli
</code>```

and for others -O influences their internal algorithms e.g. in optimization of expressions:

```<code>         /* If FROM is a SUBREG, put it into a register.  Do this
            so that we always generate the same set of insns for
            better cse'ing; if an intermediate assignment occurred,
            we won't be doing the operation directly on the SUBREG.  */
         if (optimize > 0 && GET_CODE (from) == SUBREG)
           from = force_reg (from_mode, from);
</code>```

There is no way to work around this, you have to use -O.

Title: GCC hidden optimizations

Body:
Some optimizations are directly gated by -O flags e.g. complete unroller:

{
public:
  pass_complete_unrolli (gcc::context *ctxt)
    : gimple_opt_pass (pass_data_complete_unrolli, ctxt)
  {}

  /* opt_pass methods: */
  virtual bool gate (function *) { return optimize >= 2; }
  virtual unsigned int execute (function *);

}; // class pass_complete_unrolli

and for others -O influences their internal algorithms e.g. in optimization of expressions:

         /* If FROM is a SUBREG, put it into a register.  Do this
            so that we always generate the same set of insns for
            better cse'ing; if an intermediate assignment occurred,
            we won't be doing the operation directly on the SUBREG.  */
         if (optimize > 0 && GET_CODE (from) == SUBREG)
           from = force_reg (from_mode, from);

There is no way to work around this, you have to use -O.


问:
How to split dynamic string and then apply pivot operation
I need to perform split operation on a dynamic string like this,

```<code>'John Smith, US, 1001'
</code>```

It seems simple at first but this string might be dynamic in nature, which means sometimes it can have more comma-separated values.

For example:

```<code>'Conrad Smith, UK, 1005, Permanent, 2021'
</code>```

How can I split this dynamic string and perform pivot where I don't have specific number of values to make columns.

答:
Firstly you have to use a dynamic query for dynamic string:

You store the split data in cols variable then use the cols for pivot

```<code>declare @cols nvarchar(max)
declare @strSql nvarchar(max)

set @cols = STUFF((SELECT distinct ',' + QUOTENAME(value)
        from string_split(@split_data,',')
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')
set @strSql = 'SELECT '+ @cols +' from
        (
            select LeaveTypeNo,MaxBalance from table1 p
            INNER  join table2 tei on p.Id = tei.Id
        ) x
        pivot
        (
             max(MaxBalance)
            for LeaveTypeNo in ('+ @cols +')
        ) p'
   EXEC (@strSql)
</code>```

Body:
I need to perform split operation on a dynamic string like this,

'John Smith, US, 1001'

It seems simple at first but this string might be dynamic in nature, which means sometimes it can have more comma-separated values.

For example:

'Conrad Smith, UK, 1005, Permanent, 2021'

How can I split this dynamic string and perform pivot where I don't have specific number of values to make columns.

Body:
Firstly you have to use a dynamic query for dynamic string:

You store the split data in cols variable then use the cols for pivot

declare @cols nvarchar(max)
declare @strSql nvarchar(max)

set @cols = STUFF((SELECT distinct ',' + QUOTENAME(value)
        from string_split(@split_data,',')
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')
set @strSql = 'SELECT '+ @cols +' from
        (
            select LeaveTypeNo,MaxBalance from table1 p
            INNER  join table2 tei on p.Id = tei.Id
        ) x
        pivot
        (
             max(MaxBalance)
            for LeaveTypeNo in ('+ @cols +')
        ) p'
   EXEC (@strSql)


问:
Uncaught ReferenceError: process is not defined
I am using node.js to create a web application. When I run the application (either by opening index.html on the browser or using the command "npm start" on the terminal) I get two errors:

Uncaught ReferenceError: process is not defined

Uncaught ReferenceError: require is not defined

I solved the "require is not defined" error by specifically including in my index.html head tag the link to this script, where the require function is defined.
However, I cannot find something similar for the process function.

My question is doublefold:

Why do built-in node.js modules need to be re-defined? Why are they not recognized as they are, that is "built-in modules"? Doesn't the term "built-in module" mean that a module need not be redefined externaly/second-handedly?

Is there a way to solve this problem? My script is very simple, I am just trying to use a basic function of node.js, so I cannot figure out what errors I might have done.

If anyone has come about this problem and has found a way around it or a reason this happens, you would be of great help.

答: I was just getting this error (Uncaught ReferenceError: process is not defined) in a local hot-reloading Quasar (Vue) app when calling a particular endpoint.  The fix for me ended up being to just restart the hot-reloading server (I hadn't reloaded it since adding the process.env.MY_VARIABLE code).


问:
Rails 3: Drop a table using migration
I have a table that I created using the migrations, now I want to get rid of this table.  I'm pretty sure I can just back out that migration, but I can't find the syntax to do that.  I found this question from searching Rails DB Migration - How To Drop a Table?

but he basically says you can find what you need and provides a link.  I read that link and I didn't see anything that says how to do it.  I saw pieces of it, but I don't know how to put them together.

I see in the migration it has a self.down method, I really just need to know how to call that.

答:
Try to create an empty migration and use:</p>

```<code>drop_table :table_name
</code>```

Title: Rails 3: Drop a table using migration

Body:
Try to create an empty migration and use:

drop_table :table_name


问:
how to simplify if elseif statement to get particular search data from laravel MySQL database
I am collecting all the data like id, name, date, empid from the controller in variable data

```<code>$data = $request->all();

</code>```

now i want to select all the rows from the mysql table base on the input value i receive from request like this.

if no value is given then select all from DB

```<code>if ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

           $country =  country::get();

</code>```

if only certain input value is given

```<code>elseif ($data['keyvalue'] !== '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] !=='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] !=='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] !=='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();

}

</code>```

and if all input value is given

```<code>elseif ($data['keyvalue'] !== '' && $data['datefrom'] !=='' && $data['dateto'] !=='' && $data['prepid'] !=='' ){

           $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();
}

</code>```

everything working fine i just want to simplify this code..

答:
You can use when() method which is conditional.

https://laravel.com/docs/8.x/queries#conditional-clauses

$countries = Country::when($request->filled('status'), function ($query) use ($request) {
    $query->where('sr_status', 'LIKE', "%{$request->input('status')}%");
})->when($request->filled('datefrom'), function ($query) use ($request) {
    $query->whereDate('created_at', '>=', $request->input('datefrom'));
})->when($request->filled('dateto'), function ($query) use ($request) {
    $query->whereDate('created_at', '<=', $request->input('dateto'));
})->when($request->filled('keyvalue'), function ($query) use ($request) {
    $query->Where('sr_name', 'LIKE', "%{$request->input('keyvalue')}%")
        ->orWhere('tel_code', 'LIKE', "%{$request->input('keyvalue')}%")
        ->orWhere('country_code', 'LIKE', "%{$request->input('keyvalue')}%")
        ->orWhere('currency_name', 'LIKE', "%{$request->input('keyvalue')}%");
})->when($request->filled('prepid'), function ($query) use ($request) {
    $query->where('prep_emp', 'LIKE', "%{$request->input('prepid')}%");
})->orderBy('sr_id')->get();
```

Body:
I am collecting all the data like id, name, date, empid from the controller in variable data

$data = $request->all();

now i want to select all the rows from the mysql table base on the input value i receive from request like this.

if no value is given then select all from DB

if ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

           $country =  country::get();

if only certain input value is given

elseif ($data['keyvalue'] !== '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] !=='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] !=='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] !=='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();

}

and if all input value is given

elseif ($data['keyvalue'] !== '' && $data['datefrom'] !=='' && $data['dateto'] !=='' && $data['prepid'] !=='' ){

           $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();
}

everything working fine i just want to simplify this code..


问:
how to delete all lines containing Letters and characters for a textfile
I have a textfile containing words, numbers, and characters. I want to delete all lines with the characters and words, and keep the lines with numbers.
I found out that all those lines with words and characters have the letter of "r". so I wrote my code as:

The textfile contains these lines as an example:

```<code>-- for example
-- 7 Febraury 2022
5 7 1 5 3.0 2
3*2 3 5 7.0 3
</code>```

and I want to keep these 2 lines:

```<code>5 7 1 5 3.0 2
3*2 3 5 7.0 3
</code>```

This is the code written:
textfile = open('test.txt', 'r')
A = textfile.readlines()

```<code>L = []
for index,name in enumerate(A):
    if 'r' in name:
        L.append(index)

for idx in sorted(L, reverse = True):
    del A[idx]
</code>```

I know it is not a good way to do that, is there any suggestion to do that?

答:
If you want to do this without importing anything (e.g., re) then you could do this:

```<code>keep_these = []

def is_valid(t):
    try:
        float(t.replace('*', '0'))
        return True
    except ValueError:
        pass
    return False

with open('test.txt', encoding='utf-8') as infile:
    for line in infile:
        if all(is_valid(t) for t in line.strip().split()):
            keep_these.append(line)

print(keep_these)
</code>```

Thus the keep_these list will contain references to the lines you want to keep which you could, for example, use to re-write the file

Body:
I have a textfile containing words, numbers, and characters. I want to delete all lines with the characters and words, and keep the lines with numbers.
I found out that all those lines with words and characters have the letter of "r". so I wrote my code as:

The textfile contains these lines as an example:

-- for example
-- 7 Febraury 2022
5 7 1 5 3.0 2
3*2 3 5 7.0 3

and I want to keep these 2 lines:

5 7 1 5 3.0 2
3*2 3 5 7.0 3

This is the code written:
textfile = open('test.txt', 'r')
A = textfile.readlines()

L = []
for index,name in enumerate(A):
    if 'r' in name:
        L.append(index)

for idx in sorted(L, reverse = True):
    del A[idx]

I know it is not a good way to do that, is there any suggestion to do that?

Body:
If you want to do this without importing anything (e.g., re) then you could do this:

keep_these = []

def is_valid(t):
    try:
        float(t.replace('*', '0'))
        return True
    except ValueError:
        pass
    return False

with open('test.txt', encoding='utf-8') as infile:
    for line in infile:
        if all(is_valid(t) for t in line.strip().split()):
            keep_these.append(line)

print(keep_these)

Thus the keep_these list will contain references to the lines you want to keep which you could, for example, use to re-write the file


问:
Bash syntax errors like `syntax error: operand expected (error token is "{1 % 2 ")`
Please tell why printing odd numbers in bash script with the following code gives the error:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

```<code>for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done
</code>```

答:
One liner:

for odd in {1..99..2}; do echo "${odd}"; done
```
<p>Or print in a cluster.</p>
<pre class="lang-sh prettyprint-override"><code>for odd in {1..99..2}; do echo -n " ${odd} "; done
</code>```

Likewise, to print even numbers only:

for even in {2..100..2}; do echo "${even}"; done
```
<p>OR</p>
<pre class="lang-sh prettyprint-override"><code>for even in {2..100..2}; do echo -n " ${even} "; done
</code>```

Body:
Please tell why printing odd numbers in bash script with the following code gives the error:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done

Body:
One liner:

for odd in {1..99..2}; do echo "${odd}"; done

Or print in a cluster.

for odd in {1..99..2}; do echo -n " ${odd} "; done

Likewise, to print even numbers only:

for even in {2..100..2}; do echo "${even}"; done

OR

for even in {2..100..2}; do echo -n " ${even} "; done


问:
How do I declare a view so it's initialization and itself are NOT in the representable view?
I have a UIKit representable view for using Mapbox in my SwiftUI app and control the mapView from inside the Coordinator by passing the MapboxViewRepresentable View itself when making the coordinator.

The problem I am having is that the mapView, its coordinator and subscriptions are all being created TWICE! While trying to figure out what the problem was someone commented that my problem was "holding on to the view in a variable in the representable. Then the initialization and the view are in the make. Don’t put it on a variable at struct level"

So I adjusted my code and passed the mapView inside makeUIView instead of declaring it in MapboxMapViewRepresentable and used didSet inside of the Coordinator to create/save the subscriptions once the view was passed.

Since I need to manipulate the environmentObjects via MapboxMapViewRepresentable.Coordinator methods, I have a control property (also REQUIRED by super.init() ) declared in the Coordinator.

I have no idea why everything is still being created twice, I don't think the fact I used extensions is doing it??

Anything else I could think of to check???

Thank you

PARENT STRUCT & REPRESENTABLE

```<code>struct MapboxMapView: View {
    @ObservedObject var mapVM : MapViewModel
    @ObservedObject var popupVM : PopupProfileViewModel

    var body: some View {
        ZStack{
            MapboxMapViewRepresentable()
                .environmentObject(self.mapVM)
                .environmentObject(self.popupVM)
        }
    }
}

struct MapboxMapViewRepresentable: UIViewRepresentable {
    @EnvironmentObject var session: SessionStore
    @EnvironmentObject var mapVM : MapViewModel
    @EnvironmentObject var popupVM: PopupProfileViewModel

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator(control: self)
        return coordinator
    }

    func makeUIView(context: Context) -> MGLMapView {
        let view = MGLMapView(frame: .zero, styleURL: URL(string: MAPBOX_STYLE_URL))
        context.coordinator.mapView = view
        view.showsUserLocation = true
        view.setCenter(CLLocationCoordinate2D(latitude: mapVM.usersCurrentLat, longitude: mapVM.usersCurrentLong), zoomLevel: MapViewModel.startAtZoomLevel, animated: false)
        view.delegate = context.coordinator
        view.maximumZoomLevel = MapViewModel.maxZoomLevel
        view.allowsRotating = false
        view.direction =  0.0
        view.allowsTilting = false
        mapVM.zoomLevel = view.zoomLevel
        return view
    }

    func updateUIView(_ mapView: MGLMapView, context: Context) { }

}

</code>```

Coordinator (extension of MapboxMapViewRepresentable)

```<code>
extension MapboxMapViewRepresentable {

    class Coordinator: NSObject  {
        var control: MapboxMapViewRepresentable
        let locationManager = CLLocationManager()
        var subscriptions = Set<AnyCancellable>()

        // MARK: NEW
        var mapView : MGLMapView? {
           didSet {
               guard let mapView = mapView else { return }

                // all of these run twice since map and coordinator are created twice
               control.mapVM.placePublisher.sink { bool in
                   guard let self = self else { return }
                   // control.mapVM.doSomething
                   print(bool)
               }.store(in: &subscriptions)

               Self.showRandomPlace.sink { location in
                  // mapView.setCenter....
                  // control.popupVM.doSomething()
                   print(location)
               }.store(in: &subscriptions)

               control.mapVM.newUserSelectedPublisher.sink { nearestPlaceCoords in
                   DispatchQueue.main.async {
                       mapView.zoomLevel = 15.9
                       mapView.setCenter(CLLocationCoordinate2D(latitude: nearestPlaceCoords.lat, longitude: nearestPlaceCoords.long), animated: false)
                   }
               }.store(in: &subscriptions)
           }
        }

        // publishes zoomLevel with coordiantor method regionIsChanging to update viewModel with current zoomLevel
        let zoomLevelPublisher = PassthroughSubject<Double, Never>()

        var previosZoomLevel = MapViewModel.maxZoomLevel

        init(control: MapboxMapViewRepresentable) {
            self.control = control
            super.init()
            setupLocationManager()

            // set inital map view's center to user's/device's current location
            if let coordinate = locationManager.location?.coordinate  {
                guard let mapView = mapView else { return }

                self.setCenterAt(coordinate: coordinate)
                control.mapVM.mapCenterCoordinate = mapView.centerCoordinate
            }
        } // END INIT

        deinit {
            subscriptions.forEach{$0.cancel()}
            subscriptions.removeAll()
        }
    }
}

</code>```

How delegate methods are declared

```<code>extension MapboxMapViewRepresentable.Coordinator  {

    func mapView(_: MGLMapView, didFinishLoading style: MGLStyle) {
        print("DID FINISH LOADING STYLE")

        self.control.mapVM.didFinishLoadingUrlStyle = true

        self.control.mapVM.loadCurrentUsersPlaces()
        self.control.mapVM.loadNearestPlaces()

    }
}
</code>```

答:
You can pass a reference to the UIView to your Coordinator. That might look like this:

```<code>struct MapboxMapViewRepresentable: UIViewRepresentable {
    @EnvironmentObject var session: SessionStore
    @EnvironmentObject var mapVM : MapViewModel
    @EnvironmentObject var popupVM: PopupProfileViewModel

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator(control: self)
        return coordinator
    }

    func makeUIView(context: Context) -> MGLMapView {
        let view = MGLMapView(frame: .zero, styleURL: URL(string: MAPBOX_STYLE_URL))
        context.coordinator.mapView = view
        return view
    }

    func updateUIView(_ mapView: MGLMapView, context: Context) {
        //code
    }

    class Coordinator: NSObject  {

        let locationManager = CLLocationManager()
        var control: MapboxMapViewRepresentable
        var subscriptions = Set<AnyCancellable>()

        var mapView : MGLMapView? = nil {
            didSet {
                // subscriber receives data via publisher to manipulate map
                mapView?.addAnnotations.sink { annotations in
                    //annotation sink
                }.store(in: &subscriptions)
            }
        }

        init(control: MapboxMapViewRepresentable) {
            self.control = control
            super.init()
            setupLocationManager()
        }
    }
}
</code>```

Body:
I have a UIKit representable view for using Mapbox in my SwiftUI app and control the mapView from inside the Coordinator by passing the MapboxViewRepresentable View itself when making the coordinator.

The problem I am having is that the mapView, its coordinator and subscriptions are all being created TWICE! While trying to figure out what the problem was someone commented that my problem was "holding on to the view in a variable in the representable. Then the initialization and the view are in the make. Don’t put it on a variable at struct level"

So I adjusted my code and passed the mapView inside makeUIView instead of declaring it in MapboxMapViewRepresentable and used didSet inside of the Coordinator to create/save the subscriptions once the view was passed.

Since I need to manipulate the environmentObjects via MapboxMapViewRepresentable.Coordinator methods, I have a control property (also REQUIRED by super.init() ) declared in the Coordinator.

I have no idea why everything is still being created twice, I don't think the fact I used extensions is doing it??

Anything else I could think of to check???

Thank you

PARENT STRUCT & REPRESENTABLE

struct MapboxMapView: View {
    @ObservedObject var mapVM : MapViewModel
    @ObservedObject var popupVM : PopupProfileViewModel

    var body: some View {
        ZStack{
            MapboxMapViewRepresentable()
                .environmentObject(self.mapVM)
                .environmentObject(self.popupVM)
        }
    }
}

struct MapboxMapViewRepresentable: UIViewRepresentable {
    @EnvironmentObject var session: SessionStore
    @EnvironmentObject var mapVM : MapViewModel
    @EnvironmentObject var popupVM: PopupProfileViewModel

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator(control: self)
        return coordinator
    }

    func makeUIView(context: Context) -> MGLMapView {
        let view = MGLMapView(frame: .zero, styleURL: URL(string: MAPBOX_STYLE_URL))
        context.coordinator.mapView = view
        view.showsUserLocation = true
        view.setCenter(CLLocationCoordinate2D(latitude: mapVM.usersCurrentLat, longitude: mapVM.usersCurrentLong), zoomLevel: MapViewModel.startAtZoomLevel, animated: false)
        view.delegate = context.coordinator
        view.maximumZoomLevel = MapViewModel.maxZoomLevel
        view.allowsRotating = false
        view.direction =  0.0
        view.allowsTilting = false
        mapVM.zoomLevel = view.zoomLevel
        return view
    }

    func updateUIView(_ mapView: MGLMapView, context: Context) { }

}

Coordinator (extension of MapboxMapViewRepresentable)

extension MapboxMapViewRepresentable {

    class Coordinator: NSObject  {
        var control: MapboxMapViewRepresentable
        let locationManager = CLLocationManager()
        var subscriptions = Set<AnyCancellable>()

        // MARK: NEW
        var mapView : MGLMapView? {
           didSet {
               guard let mapView = mapView else { return }

                // all of these run twice since map and coordinator are created twice
               control.mapVM.placePublisher.sink { bool in
                   guard let self = self else { return }
                   // control.mapVM.doSomething
                   print(bool)
               }.store(in: &subscriptions)

               Self.showRandomPlace.sink { location in
                  // mapView.setCenter....
                  // control.popupVM.doSomething()
                   print(location)
               }.store(in: &subscriptions)

               control.mapVM.newUserSelectedPublisher.sink { nearestPlaceCoords in
                   DispatchQueue.main.async {
                       mapView.zoomLevel = 15.9
                       mapView.setCenter(CLLocationCoordinate2D(latitude: nearestPlaceCoords.lat, longitude: nearestPlaceCoords.long), animated: false)
                   }
               }.store(in: &subscriptions)
           }
        }

        // publishes zoomLevel with coordiantor method regionIsChanging to update viewModel with current zoomLevel
        let zoomLevelPublisher = PassthroughSubject<Double, Never>()

        var previosZoomLevel = MapViewModel.maxZoomLevel

        init(control: MapboxMapViewRepresentable) {
            self.control = control
            super.init()
            setupLocationManager()

            // set inital map view's center to user's/device's current location
            if let coordinate = locationManager.location?.coordinate  {
                guard let mapView = mapView else { return }

                self.setCenterAt(coordinate: coordinate)
                control.mapVM.mapCenterCoordinate = mapView.centerCoordinate
            }
        } // END INIT

        deinit {
            subscriptions.forEach{$0.cancel()}
            subscriptions.removeAll()
        }
    }
}

How delegate methods are declared

extension MapboxMapViewRepresentable.Coordinator  {

    func mapView(_: MGLMapView, didFinishLoading style: MGLStyle) {
        print("DID FINISH LOADING STYLE")

        self.control.mapVM.didFinishLoadingUrlStyle = true

        self.control.mapVM.loadCurrentUsersPlaces()
        self.control.mapVM.loadNearestPlaces()

    }
}

Body:
You can pass a reference to the UIView to your Coordinator. That might look like this:

struct MapboxMapViewRepresentable: UIViewRepresentable {
    @EnvironmentObject var session: SessionStore
    @EnvironmentObject var mapVM : MapViewModel
    @EnvironmentObject var popupVM: PopupProfileViewModel

    func makeCoordinator() -> Coordinator {
        let coordinator = Coordinator(control: self)
        return coordinator
    }

    func makeUIView(context: Context) -> MGLMapView {
        let view = MGLMapView(frame: .zero, styleURL: URL(string: MAPBOX_STYLE_URL))
        context.coordinator.mapView = view
        return view
    }

    func updateUIView(_ mapView: MGLMapView, context: Context) {
        //code
    }

    class Coordinator: NSObject  {

        let locationManager = CLLocationManager()
        var control: MapboxMapViewRepresentable
        var subscriptions = Set<AnyCancellable>()

        var mapView : MGLMapView? = nil {
            didSet {
                // subscriber receives data via publisher to manipulate map
                mapView?.addAnnotations.sink { annotations in
                    //annotation sink
                }.store(in: &subscriptions)
            }
        }

        init(control: MapboxMapViewRepresentable) {
            self.control = control
            super.init()
            setupLocationManager()
        }
    }
}


问:
Lisp: How to set element in list of lists?
I am familiar with how to set elements in a 2D array, which can be done using the following statement.

```<code>(setf (aref array2D 0 0) 3)
</code>```

However, I am not familiar how to set elements in a list of lists, such as the following input: '((1) (2) (2) (1)). I can't use aref, since it only works on arrays.

答:
As mentioned, while aref works on arrays, elt works on sequences which can be:

an ordered collection of elements

a vector or a list.

```<code>* (setf test-list '((1) (2) (2) (1)))
((1) (2) (2) (1))
* (setf (elt test-list 2) 'hi)
HI
* test-list
((1) (2) HI (1))
</code>```

You can indeed use variables in place of fixed offsets:

```<code>* (setf test-list '((1) (2) (2) (1)))
((1) (2) (2) (1))
* (setf offset 2)
2
* (setf (elt test-list offset) 'hi)
HI
* test-list
((1) (2) HI (1))
</code>```

Body:
I am familiar with how to set elements in a 2D array, which can be done using the following statement.

(setf (aref array2D 0 0) 3)

However, I am not familiar how to set elements in a list of lists, such as the following input: '((1) (2) (2) (1)). I can't use aref, since it only works on arrays.

Body:
As mentioned, while aref works on arrays, elt works on sequences which can be:

an ordered collection of elements

a vector or a list.

* (setf test-list '((1) (2) (2) (1)))
((1) (2) (2) (1))
* (setf (elt test-list 2) 'hi)
HI
* test-list
((1) (2) HI (1))

You can indeed use variables in place of fixed offsets:

* (setf test-list '((1) (2) (2) (1)))
((1) (2) (2) (1))
* (setf offset 2)
2
* (setf (elt test-list offset) 'hi)
HI
* test-list
((1) (2) HI (1))


问:
Javascript Textbox "Scrubber"
I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.

I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.

答:
```<code><script type="text/javascript">
function scrub(text) {
    var commands = new Array{"someCommand","anotherCommand",...};
    for (var i = 0; i <= commands.length; i++) {
        if (text.value.toLowerCase().equals(commands[i])) {
            //command is valid; do something here
        } else {
           alert("Invalid command");
        }
    }
    text.value = ""; //clears the text box
}
</script>
</code>```

For your textarea do this:

```<code><textarea onblur="scrub(this);" ...></textarea>
</code>```

Title: Javascript Textbox "Scrubber"

Body:
<script type="text/javascript">
function scrub(text) {
    var commands = new Array{"someCommand","anotherCommand",...};
    for (var i = 0; i <= commands.length; i++) {
        if (text.value.toLowerCase().equals(commands[i])) {
            //command is valid; do something here
        } else {
           alert("Invalid command");
        }
    }
    text.value = ""; //clears the text box
}
</script>

For your textarea do this:

<textarea onblur="scrub(this);" ...></textarea>


问:
HTML5 Video — limiting buffer for an MP4
Is it possible to use an HTML5 Video tag to load an MP4, but control how much of the file is downloaded/buffered from the server (assume it supports byte ranges).

Essentially, I'd like to be able to say "only download 60 seconds ahead" so I can avoid the browser downloading an entire 2 GB file when the user is going to end up bouncing anyway.

答:
Source: https://stackoverflow.com/a/65501042/2982234

You could use the media-fragment syntax in the url to let the browser know which portion of the media it should play.

document.querySelector("button").onclick = ({target}) => {
  target.remove();
  document.querySelector("video").play();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>video { max-height: 100vh; }</code>```

<button>play</button>
<video muted src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm#t=0,60"></video>```

Body:
Source: https://stackoverflow.com/a/65501042/2982234

You could use the media-fragment syntax in the url to let the browser know which portion of the media it should play.

document.querySelector("button").onclick = ({target}) => {
  target.remove();
  document.querySelector("video").play();
};

video { max-height: 100vh; }

<button>play</button>
<video muted src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm#t=0,60"></video>


问:
open viewcontroller on half screen
I want to open a segue, but only on a half screen, the rest I want to be an ImageView, I tried searching up segue padding, but couldn't find what I was looking for, In figma, I've added an IOS extension, where I got an asset( picture below ), what I see on picture is a view opened on half screen, is there any other way beside UIView to achive my end result?

答:
For half view controller we have to set height and width.

HalfViewController.swift

```<code>    import Foundation
    import UIKit

    class HalfSizePresentationController: UIPresentationController {
        override var frameOfPresentedViewInContainerView: CGRect {
            guard let bounds = containerView?.bounds else { return .zero }
            return CGRect(x: 0, y: bounds.height / 2, width: bounds.width, height: bounds.height / 2)
        }
    }
</code>```

Now call HalfViewController.swift in view controller

```<code>  @IBAction func addGoalButton(_ sender: Any) {
        movetoAddgaolModal()
            }
func movetoAddgaolModal(){
        let storyboard = UIStoryboard(name: "Stopwatch", bundle: nil)
                let pvc = storyboard.instantiateViewController(withIdentifier: "TimersetViewController") as! TimersetViewController
                pvc.modalPresentationStyle = .custom
                pvc.transitioningDelegate = self
                present(pvc, animated: true)
    }
            func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
                return HalfSizePresentationController(presentedViewController: presented, presenting: presentingViewController)
            }
</code>```

Title: open viewcontroller on half screen

Body:
For half view controller we have to set height and width.

HalfViewController.swift

    import Foundation
    import UIKit

    class HalfSizePresentationController: UIPresentationController {
        override var frameOfPresentedViewInContainerView: CGRect {
            guard let bounds = containerView?.bounds else { return .zero }
            return CGRect(x: 0, y: bounds.height / 2, width: bounds.width, height: bounds.height / 2)
        }
    }

Now call HalfViewController.swift in view controller

  @IBAction func addGoalButton(_ sender: Any) {
        movetoAddgaolModal()
            }
func movetoAddgaolModal(){
        let storyboard = UIStoryboard(name: "Stopwatch", bundle: nil)
                let pvc = storyboard.instantiateViewController(withIdentifier: "TimersetViewController") as! TimersetViewController
                pvc.modalPresentationStyle = .custom
                pvc.transitioningDelegate = self
                present(pvc, animated: true)
    }
            func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
                return HalfSizePresentationController(presentedViewController: presented, presenting: presentingViewController)
            }


答:
The sx props allows you to use all the mui system properties along with CSS properites.
with style={{}} aproch you add the CSS properties directly but you cannot use the mui properties in it. e.g. theme properties.

with SX props: you can set color in theme once. then use same color in all your app. then in future you want to change color you can change it in theme only once and it will apply to all the app automatically.

```<code>sx={{ color: 'primary.main' }}
</code>```

with Style: but then you have to remember exact colorcode while coding your app and then in future if you decided to change you have to change everywhere in app.

```<code>style={{ color: '#00ff00' }}
</code>```

also some CSS properties you can directly add to components.

e.g.

```<code><Box height="100px" >... </Box> is same as
<Box sx={{height: '100px'}}>...</Box>
</code>```

check below pages for more details.

https://mui.com/system/basics/#all-inclusive

https://mui.com/system/the-sx-prop/

Title: What is the purpose of sx prop in Material UI?

Body:
<Box style={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>

<Box sx={{ padding: "20px" }}>
  <Post post={post} setCurrentId={setCurrentId} />
</Box>

React.js + Material UI

The above two examples do the same thing, one uses sx prop in material UI, the other is regular inline styling using css, so what is the point of "sx"? and should it always be used over style={{}} when using Material UI?

Body:
The sx props allows you to use all the mui system properties along with CSS properites.
with style={{}} aproch you add the CSS properties directly but you cannot use the mui properties in it. e.g. theme properties.

with SX props: you can set color in theme once. then use same color in all your app. then in future you want to change color you can change it in theme only once and it will apply to all the app automatically.

sx={{ color: 'primary.main' }}

with Style: but then you have to remember exact colorcode while coding your app and then in future if you decided to change you have to change everywhere in app.

style={{ color: '#00ff00' }}

also some CSS properties you can directly add to components.

e.g.

<Box height="100px" >... </Box> is same as
<Box sx={{height: '100px'}}>...</Box>

check below pages for more details.

https://mui.com/system/basics/#all-inclusive

https://mui.com/system/the-sx-prop/


问:
In postgres, how to sort on, among others, a result value of a string_agg function, without selecting that field? Subquery not possible
I have this query (already stripped down but more complex in reality):

```<code>SELECT
    e.id,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) AS condition_set_descriptions
FROM event e
JOIN event_trigger_version etv ON e.event_trigger_version_id = etv.id
LEFT JOIN event_condition_set ecs ON ecs.event_id = e.id
JOIN condition_set cs ON cs.id = ecs.condition_set_id
JOIN condition_set_base csb ON cs.condition_set_base_id = csb.id
JOIN subject s ON e.subject_id = s.id
GROUP BY
    e.id, event_level, s.name
ORDER BY s.name ASC, condition_set_descriptions ASC, event_level DESC
LIMIT 20 OFFSET 0
</code>```

Now I can have a dynamic ORDER BY including other columns too (that are omitted in this example), but always including condition_set_descriptions somewhere in the order. This column is the result of a string_agg function. I cannot move this to a subquery because the LIMIT that is set should apply to the result of the combination of ORDER BY columns that are defined.

The example works fine, but the downside is that the condition_set_descriptions column is also returned as a result of the query, but this is a lot of data and it's not actually needed (as the actual descriptions are looked up in another way using some of the omitted data). All that is needed is that the result is sorted. How can I do this without selecting this in a subquery that would ruin the correctness of the multi-sort limited result set?

答:
ORDER BY can work on calculated expressions too; it doesn't have to be that you calculate something in the SELECT that you then alias and reference the alias in the ORDER BY

Take a look at doing:

```<code>SELECT
    e.id
FROM
  ...
ORDER BY
    s.name ASC,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) ASC,
    event_level DESC
LIMIT 20 OFFSET 0
</code>```

Also double check that left join you have there in the middle of the inner joins; any nulls it produces will be removed again when the next table is inner joined into it, so you can either inner join it or if you're losing data adopt a pattern of:

```<code>w
JOIN x
LEFT JOIN (
  y
  JOIN z
) a
</code>```

ie don't left join y to x then inner join z to y, inner join y and z first then left join the result onto x

Body:
I have this query (already stripped down but more complex in reality):

SELECT
    e.id,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) AS condition_set_descriptions
FROM event e
JOIN event_trigger_version etv ON e.event_trigger_version_id = etv.id
LEFT JOIN event_condition_set ecs ON ecs.event_id = e.id
JOIN condition_set cs ON cs.id = ecs.condition_set_id
JOIN condition_set_base csb ON cs.condition_set_base_id = csb.id
JOIN subject s ON e.subject_id = s.id
GROUP BY
    e.id, event_level, s.name
ORDER BY s.name ASC, condition_set_descriptions ASC, event_level DESC
LIMIT 20 OFFSET 0

Now I can have a dynamic ORDER BY including other columns too (that are omitted in this example), but always including condition_set_descriptions somewhere in the order. This column is the result of a string_agg function. I cannot move this to a subquery because the LIMIT that is set should apply to the result of the combination of ORDER BY columns that are defined.

The example works fine, but the downside is that the condition_set_descriptions column is also returned as a result of the query, but this is a lot of data and it's not actually needed (as the actual descriptions are looked up in another way using some of the omitted data). All that is needed is that the result is sorted. How can I do this without selecting this in a subquery that would ruin the correctness of the multi-sort limited result set?

Body:
ORDER BY can work on calculated expressions too; it doesn't have to be that you calculate something in the SELECT that you then alias and reference the alias in the ORDER BY

Take a look at doing:

SELECT
    e.id
FROM
  ...
ORDER BY
    s.name ASC,
    string_agg(csb.description, ',' ORDER BY cs.id ASC) ASC,
    event_level DESC
LIMIT 20 OFFSET 0

Also double check that left join you have there in the middle of the inner joins; any nulls it produces will be removed again when the next table is inner joined into it, so you can either inner join it or if you're losing data adopt a pattern of:

w
JOIN x
LEFT JOIN (
  y
  JOIN z
) a

ie don't left join y to x then inner join z to y, inner join y and z first then left join the result onto x


问:
Laravel migration problem : Foreign key constraint is incorrectly formed in l
I make the same data type for both of that table but there is a problem. But for another table I didn't get any error. what is the problem behind?

General error: 1005 Can't create table meal_system.amounts (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table amounts add constraint amounts_member_id_foreign foreign key (member_id) references members (member_id) on delete cascade)

答:
You need first to migrate members before amounts table case your foreign is with member_id to migrate members first just change the date of the migration file to be before the amount

For example :

```<code>2021_01_01_000000_create_members_table

2021_02_02_100000_create_amounts_table
</code>```

Body:
You need first to migrate members before amounts table case your foreign is with member_id to migrate members first just change the date of the migration file to be before the amount

For example :

2021_01_01_000000_create_members_table

2021_02_02_100000_create_amounts_table


问:
Personal hotspot blue bar problem
When I launch my application while some device is connected to my iPhone (hence, a blue bar showing the number of connection will be shown), my launch image (Default.png) gets deformed and the size no longer fits the screen size.

How can I solve this problem? I have tried to check the "status bar initially hidden" but it only helps after the startup image is loaded.

Thanks in advance.

答: There isn’t really a way around this. If I remember correctly, the system adjusts the launch image for double-height status bars by cutting out some portion of its middle; your only option to mitigate this problem is to figure out which part of your Default.png is getting cut out and change the image so that that removal isn’t as noticeable.</p>

Title: Personal hotspot blue bar problem


问:
List split and join
Below is my list

```<code>MY_TXT= [
    'User enters validusername "MAXI" And password "768"',
    'User enters phonenumber "76567898" And ZIPcode "97656"',
    'User Verifys Country "ENGLAND" And City "LONDON"  And  street "Brick Lane And avenue  "2A"',
    'User clicks ok']
</code>```

I want split the list from 'And' and  join with base name , my list to be looks like this:

```<code>New_list= [
    'User enters validusername "MAXI"',
    'User enter password "768"',
    'User enters phonenumber "76567898"',
    'User enters ZIPcode "97656"',
    'User Verifys Country "ENGLAND",
    'User Verifys City "LONDON"',
    'User Verifys street "Brick Lane"',
    'User Verifys  avenue  "2A"',
    'User clicks ok']
</code>```

答:
If you do a nested list comprehension you can get what you're after:

```<code>In [6]: ['User verifys '+j if 'User'!=j[:4] else j for i in MY_TXT for j in i.split('And ')]
Out[6]:
['User enters validusername "MAXI" ',
 'User verifys password "768"',
 'User enters phonenumber "76567898" ',
 'User verifys ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User verifys City "LONDON" ',
 'User verifys street "Brick Lane ',
 'User verifys avenue "2A"',
 'User clicks ok']
</code>```

------- EDIT --------

I see that it's not always 'verify'. In this case you'll need to track the variable which is the one you want to use at the start of the string ('verifys', 'enter', etc)

```<code>In [17]: myList = []

In [18]: for i in MY_TXT:
    ...:     for j in i.split('And '):
    ...:         if 'User' in j:
    ...:             entryStr = j.split()[1] #extract the action of the user - enters, verifys, etc
    ...:             myList.append(j)
    ...:         else:
    ...:             myList.append('User {:s} {:s}'.format(entryStr,j))
    ...:
In [19]: myList
Out[19]:
['User enters validusername "MAXI" ',
 'User enters password "768"',
 'User enters phonenumber "76567898" ',
 'User enters ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User Verifys City "LONDON" ',
 'User Verifys street "Brick Lane ',
 'User Verifys avenue "2A"',
 'User clicks ok']
</code>```

Title: List split and join

Body:
Below is my list

MY_TXT= [
    'User enters validusername "MAXI" And password "768"',
    'User enters phonenumber "76567898" And ZIPcode "97656"',
    'User Verifys Country "ENGLAND" And City "LONDON"  And  street "Brick Lane And avenue  "2A"',
    'User clicks ok']

I want split the list from 'And' and  join with base name , my list to be looks like this:

New_list= [
    'User enters validusername "MAXI"',
    'User enter password "768"',
    'User enters phonenumber "76567898"',
    'User enters ZIPcode "97656"',
    'User Verifys Country "ENGLAND",
    'User Verifys City "LONDON"',
    'User Verifys street "Brick Lane"',
    'User Verifys  avenue  "2A"',
    'User clicks ok']

Body:
If you do a nested list comprehension you can get what you're after:

In [6]: ['User verifys '+j if 'User'!=j[:4] else j for i in MY_TXT for j in i.split('And ')]
Out[6]:
['User enters validusername "MAXI" ',
 'User verifys password "768"',
 'User enters phonenumber "76567898" ',
 'User verifys ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User verifys City "LONDON" ',
 'User verifys street "Brick Lane ',
 'User verifys avenue "2A"',
 'User clicks ok']

------- EDIT --------

I see that it's not always 'verify'. In this case you'll need to track the variable which is the one you want to use at the start of the string ('verifys', 'enter', etc)

In [17]: myList = []

In [18]: for i in MY_TXT:
    ...:     for j in i.split('And '):
    ...:         if 'User' in j:
    ...:             entryStr = j.split()[1] #extract the action of the user - enters, verifys, etc
    ...:             myList.append(j)
    ...:         else:
    ...:             myList.append('User {:s} {:s}'.format(entryStr,j))
    ...:
In [19]: myList
Out[19]:
['User enters validusername "MAXI" ',
 'User enters password "768"',
 'User enters phonenumber "76567898" ',
 'User enters ZIPcode "97656"',
 'User Verifys Country "ENGLAND" ',
 'User Verifys City "LONDON" ',
 'User Verifys street "Brick Lane ',
 'User Verifys avenue "2A"',
 'User clicks ok']


问:
To Highlight a word/text and drag to other text box in React
Is it possible to highlight a word or text in One text box and be able to drag the highlighted(selected) text or word to other text from a complete sentence that would be present in the first text box in React?

I have seen a package but that's for React Native not for the web.

答:
You can Use React-DnD and use a Drag and Drop Operation,
https://react-dnd.github.io/react-dnd/docs/overview

You have to implement the same with text so that you can Drag and Drop them

```<code>function collect(connect, monitor) {
  return {
    highlighted: monitor.canDrop(),
    hovered: monitor.isOver(),
    connectDropTarget: connect.dropTarget()
  }
}
</code>```

Body:
You can Use React-DnD and use a Drag and Drop Operation,
https://react-dnd.github.io/react-dnd/docs/overview

You have to implement the same with text so that you can Drag and Drop them

function collect(connect, monitor) {
  return {
    highlighted: monitor.canDrop(),
    hovered: monitor.isOver(),
    connectDropTarget: connect.dropTarget()
  }
}


问:
Segmentation Fault on eraseFromParent() LLVM
```<code>bool runOnFunction(Function &F) override {
  outs() << "Inside Function: "<<F.getName()<<"\n";
  int i = 0;
  map<int, Instruction*> work;
  for(BasicBlock &BB : F)
      for(Instruction &I : BB){
          if(i == 15)
              work.insert({i, &I});
          i++;
      }

  std::map<int, Instruction*>::iterator it = work.begin();
  it->second->eraseFromParent();

  return true;
}
</code>```

The above is my code snippet. Here, in the above code, I would like to remove an instruction randomly.. just for the sake of knowing how to use this api. But, It is ending up with segmentation fault!!, no matter what I try. Need some guidance, here please

```<code>Inside Function: change_g
While deleting: i32 %
Use still stuck around after Def is destroyed:  %add = add nsw i32 <badref>, %l
opt: /home/user/llvm-project/llvm/lib/IR/Value.cpp:103: llvm::Value::~Value(): Assertion `materialized_use_empty() && "Uses remain when a value is destroyed!"' failed.
</code>```

答:
First of all, it's not a segmentation fault but an assertion which tells you that something went wrong. In particular the message explains that you can not erase an instruction until any of its uses is still present in function.

Usually you'd first create a new instruction, replace all uses of to-be-removed instruction with new result (via Value::replaceAllUsesWith()) and only then erase.

Body:
bool runOnFunction(Function &F) override {
  outs() << "Inside Function: "<<F.getName()<<"\n";
  int i = 0;
  map<int, Instruction*> work;
  for(BasicBlock &BB : F)
      for(Instruction &I : BB){
          if(i == 15)
              work.insert({i, &I});
          i++;
      }

  std::map<int, Instruction*>::iterator it = work.begin();
  it->second->eraseFromParent();

  return true;
}

The above is my code snippet. Here, in the above code, I would like to remove an instruction randomly.. just for the sake of knowing how to use this api. But, It is ending up with segmentation fault!!, no matter what I try. Need some guidance, here please

Inside Function: change_g
While deleting: i32 %
Use still stuck around after Def is destroyed:  %add = add nsw i32 <badref>, %l
opt: /home/user/llvm-project/llvm/lib/IR/Value.cpp:103: llvm::Value::~Value(): Assertion `materialized_use_empty() && "Uses remain when a value is destroyed!"' failed.


答: Create an empty list new_list. Using a for loop, split each string using MY_TXT[i].split("And"). Then new_list = new_list + results

Title: List split and join


问:
Can several JOIN clauses in a MySQL query exponentiate number of rows it has to check?
So I was on tech support with our host provider about slow database response that I'd been experiencing on a crucial search page and after some investigating he told me that the query that I'm using was checking 67,998,176 rows. Now the largest table that appears on this query has at most 116 rows and the rest of them have an average of 25 rows each.

Here's the SQL of my query

```<code> SELECT COUNT( DISTINCT `A`.`id`) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 LEFT JOIN `admin_site_organization_resource` AS `B` ON `B`.`res_id`=`A`.`id`
 LEFT JOIN `admin_site_organizations` AS `C` ON `B`.`org_id`=`C`.`id`
 LEFT JOIN `admin_site_resource_res_topic` AS `D` ON `D`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_topics` AS `E` ON `E`.`id`=`D`.`res_topic_id`
 LEFT JOIN `admin_site_resource_audience` AS `F` ON `F`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_audiences` AS `G` ON `G`.`id`=`F`.`audience_id`
 LEFT JOIN `admin_site_resource_curriculum_topic` AS `H` ON `H`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_topics` AS `I` ON `I`.`id`=`H`.`curriculum_topic_id`
 LEFT JOIN `admin_site_resource_curriculum_grade` AS `J` ON `J`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_grades` AS `K` ON `K`.`id`=`J`.`curriculum_grade_id`
 LEFT JOIN `admin_site_resource_curriculum_subject` AS `L` ON `L`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_subjects` AS `M` ON `M`.`id`=`L`.`curriculum_subject_id`
 LEFT JOIN `admin_site_resource_res_type` AS `N` ON `N`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_types` AS `O` ON `O`.`id`=`N`.`res_type_id`
 LEFT JOIN `admin_site_resource_res_area_location` AS `P` ON `P`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_area_locations` AS `Q` ON `Q`.`id`=`P`.`res_area_location_id`

 WHERE `A`.`post_status`='approved' AND (
`A`.`resource_name` LIKE '%alpha%'
OR `A`.`aliases` LIKE '%alpha%'
OR `A`.`short_desc` LIKE '%alpha%'
OR `A`.`resource_url` LIKE '%alpha%'
OR `A`.`other_resource_type` LIKE '%alpha%'
OR `C`.`org_name` LIKE '%alpha%'
OR `E`.`topic_label` LIKE '%alpha%'
OR `G`.`audience_label` LIKE '%alpha%'
OR `I`.`topic_label` LIKE '%alpha%'
OR `K`.`grade_label` LIKE '%alpha%'
OR `M`.`subject_label` LIKE '%alpha%'
OR `O`.`type_label` LIKE '%alpha%'
OR `Q`.`area_location_label` LIKE '%alpha%' );
</code>```

Yes, I understand this query is pretty long and ugly but I guess it's a result of all the normalization that had to be done for it. What I can't understand is how a few rows suddenly turned to almost 68 million rows. Are the LEFT JOINS to blame for this?

答:
Rewrite it as:</p>

```<code> SELECT COUNT(*) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 WHERE `A`.`post_status`='approved' AND
   ( `A`.`resource_name` LIKE '%alpha%'
  OR `A`.`aliases` LIKE '%alpha%'
  OR `A`.`short_desc` LIKE '%alpha%'
  OR `A`.`resource_url` LIKE '%alpha%'
  OR `A`.`other_resource_type` LIKE '%alpha%'
  OR EXISTS ( SELECT *
              FROM `admin_site_organization_resource` AS `B`
                JOIN `admin_site_organizations` AS `C`
                  ON `B`.`org_id`=`C`.`id`
              WHERE `B`.`res_id`=`A`.`id`
                AND `C`.`org_name` LIKE '%alpha%'
            )
  OR EXISTS (
             ...
            )
  OR EXISTS (
             ...
            )
  ...
    )
</code>```

Body:
So I was on tech support with our host provider about slow database response that I'd been experiencing on a crucial search page and after some investigating he told me that the query that I'm using was checking 67,998,176 rows. Now the largest table that appears on this query has at most 116 rows and the rest of them have an average of 25 rows each.

Here's the SQL of my query

 SELECT COUNT( DISTINCT `A`.`id`) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 LEFT JOIN `admin_site_organization_resource` AS `B` ON `B`.`res_id`=`A`.`id`
 LEFT JOIN `admin_site_organizations` AS `C` ON `B`.`org_id`=`C`.`id`
 LEFT JOIN `admin_site_resource_res_topic` AS `D` ON `D`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_topics` AS `E` ON `E`.`id`=`D`.`res_topic_id`
 LEFT JOIN `admin_site_resource_audience` AS `F` ON `F`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_audiences` AS `G` ON `G`.`id`=`F`.`audience_id`
 LEFT JOIN `admin_site_resource_curriculum_topic` AS `H` ON `H`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_topics` AS `I` ON `I`.`id`=`H`.`curriculum_topic_id`
 LEFT JOIN `admin_site_resource_curriculum_grade` AS `J` ON `J`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_grades` AS `K` ON `K`.`id`=`J`.`curriculum_grade_id`
 LEFT JOIN `admin_site_resource_curriculum_subject` AS `L` ON `L`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_curriculum_subjects` AS `M` ON `M`.`id`=`L`.`curriculum_subject_id`
 LEFT JOIN `admin_site_resource_res_type` AS `N` ON `N`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_types` AS `O` ON `O`.`id`=`N`.`res_type_id`
 LEFT JOIN `admin_site_resource_res_area_location` AS `P` ON `P`.`resource_id`=`A`.`id`
 LEFT JOIN `admin_site_resource_area_locations` AS `Q` ON `Q`.`id`=`P`.`res_area_location_id`

 WHERE `A`.`post_status`='approved' AND (
`A`.`resource_name` LIKE '%alpha%'
OR `A`.`aliases` LIKE '%alpha%'
OR `A`.`short_desc` LIKE '%alpha%'
OR `A`.`resource_url` LIKE '%alpha%'
OR `A`.`other_resource_type` LIKE '%alpha%'
OR `C`.`org_name` LIKE '%alpha%'
OR `E`.`topic_label` LIKE '%alpha%'
OR `G`.`audience_label` LIKE '%alpha%'
OR `I`.`topic_label` LIKE '%alpha%'
OR `K`.`grade_label` LIKE '%alpha%'
OR `M`.`subject_label` LIKE '%alpha%'
OR `O`.`type_label` LIKE '%alpha%'
OR `Q`.`area_location_label` LIKE '%alpha%' );

Yes, I understand this query is pretty long and ugly but I guess it's a result of all the normalization that had to be done for it. What I can't understand is how a few rows suddenly turned to almost 68 million rows. Are the LEFT JOINS to blame for this?

Body:
Rewrite it as:

 SELECT COUNT(*) AS `total_num_resource_rows`
 FROM `admin_site_resources` AS `A`
 WHERE `A`.`post_status`='approved' AND
   ( `A`.`resource_name` LIKE '%alpha%'
  OR `A`.`aliases` LIKE '%alpha%'
  OR `A`.`short_desc` LIKE '%alpha%'
  OR `A`.`resource_url` LIKE '%alpha%'
  OR `A`.`other_resource_type` LIKE '%alpha%'
  OR EXISTS ( SELECT *
              FROM `admin_site_organization_resource` AS `B`
                JOIN `admin_site_organizations` AS `C`
                  ON `B`.`org_id`=`C`.`id`
              WHERE `B`.`res_id`=`A`.`id`
                AND `C`.`org_name` LIKE '%alpha%'
            )
  OR EXISTS (
             ...
            )
  OR EXISTS (
             ...
            )
  ...
    )


问:
How can I call second largest number from arrayList using collections
I need highest, second highest and third highest numbers from my ArrayList. I am getting max value (i.e. highest number) by calling Collections.max() but I also need the second largest and the third largest values.

My Code:

maxPartyid =
Collections.max(electionresdashlist.get(k).getPartyNamesDTO());  //1st Highest

System.out.println( "maxPartyid:::"+maxPartyid);

in DTO :
public class PartyNamesDTO implements Comparable<PartyNamesDTO>{

    private String partyId;
    public String getPartyId() {
        return partyId;
    }
    public void setPartyId(String partyId) {
        this.partyId = partyId;
    }
    private Integer votes;

    public Integer getVotes() {
        return votes;
    }
    public void setVotes(Integer votes) {
        this.votes = votes;
    }

    @Override
        public int compareTo(PartyNamesDTO emp) {
            return this.votes.compareTo(emp.getVotes());
        }

        public String toString(){
            return partyId;
        }
}

             ```

答:
I have a simple solution to find an nth highest element from the Array List:

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(12,44,76,1,8,9,9));

int highest = arr.stream().sorted(Collections.reverseOrder()).collect(Collectors.toList()).get(n-1);
```


问:
Spring framework default-lazy-init all beans
Is there a spring property to lazy-init all beans that spring framework loads ?

I know about these properties

```<code> - lazy-init="true"
 - default-lazy-init="true"
</code>```

however there are multiple spring config xml files and some are packaged within jar so dont have liberty to change neither <bean> nor <beans> tag.

Any other way to tackle this via configuration ? or programatically ?

答:
Starting with Spring Boot 2 you can use the spring.main.lazy-initialization property to configure lazy initialization across the whole application.

Setting the property value to true means that all the beans in the application will use lazy initialization.

in application.yaml

```<code>spring:
  main:
    lazy-initialization: true
</code>```

or in application.properties

```<code>spring.main.lazy-initialization=true
</code>```

Body:
Is there a spring property to lazy-init all beans that spring framework loads ?

I know about these properties

 - lazy-init="true"
 - default-lazy-init="true"

however there are multiple spring config xml files and some are packaged within jar so dont have liberty to change neither <bean> nor <beans> tag.

Any other way to tackle this via configuration ? or programatically ?

Body:
Starting with Spring Boot 2 you can use the spring.main.lazy-initialization property to configure lazy initialization across the whole application.

Setting the property value to true means that all the beans in the application will use lazy initialization.

in application.yaml

spring:
  main:
    lazy-initialization: true

or in application.properties

spring.main.lazy-initialization=true


问:
react simple keyboard not able to type in multiple input
I have following code of Calculator.jsx where everything looks fine.The main thing I want to achieve is keyboard to displayed only on input click which is done but the keyboard does not seem to type though the following code looks fine. Are there any other way to show/hide keyboard only on input click as well as make keyboard be able to type. My code for Calculator.jsx is
Calculator.jsx</p>
```<code>import React, { useState, useRef, useEffect } from 'react';
import './Calculator.css'
import { Link } from 'react-router-dom';
import Keyboard from "react-simple-keyboard";
import "react-simple-keyboard/build/css/index.css";

const Calculator = () => {

  const [inputs, setInputs] = useState({});
  const [layoutName, setLayoutName] = useState("default");
  const [inputName, setInputName] = useState("default");
  const keyboard = useRef();
    const [keyboardVisibility, setKeyboardVisibility] = useState(false);

    useEffect(() => {
      function clickHanlder(e) {
        if (
          !(e.target.nodeName === "INPUT") &&
          !e.target.classList.contains("hg-button") &&
          !e.target.classList.contains("hg-row")
        ) {
          setKeyboardVisibility(false);
        }
      }

      window.addEventListener("click", clickHanlder);
      return window.removeEventListener("click", clickHanlder, true);
    }, []);

  const onChangeAll = inputs => {

    setInputs({ ...inputs });
    console.log("Inputs changed", inputs);
  };

  const handleShift = () => {
    const newLayoutName = layoutName === "default" ? "shift" : "default";
    setLayoutName(newLayoutName);
  };

  const onKeyPress = button => {
    console.log("Button pressed", button);

    if (button === "{shift}" || button === "{lock}") handleShift();
  };

  const onChangeInput = event => {
    const inputVal = event.target.value;

    setInputs({
      ...inputs,
      [inputName]: inputVal
    });

    keyboard.current.setInput(inputVal);
  };

  const getInputValue = inputName => {
    return inputs[inputName] || "";
  };

    return (
        <div>
        <div className="bg">
         <div className="deposit">
            <div className="header">

             <h1>Deposit Calculator</h1>
                <div className="form">
                 <form  className="calculator">
                     <div className="form-group">
                    <label for="depositAmount">Deposit Amount:</label>
                    <span className="rupees">Rs</span>
                    <input className="IInput"
                     type="text"
                     name='depositAmount'
                          placeholder='0'
                          value={getInputValue("depositAmount")}

                      onChange={onChangeInput}
                      onFocus={() => {
                         setKeyboardVisibility(true);
                        setInputName("depositAmount")
                      }}

                        />

                     </div>
                      <div className="form-group">
                      <label for="interestRate">Interest Rate:</label>
                     <input className= "IIinput"
                     type="text"
                    name='Interest'
                                        placeholder='0'
                                        value={getInputValue("interestRate")}

                      onChange={onChangeInput}
                      onFocus={() => {
                        setKeyboardVisibility(true);
                        setInputName("interestRate")
                      }}
                     />

                     <span className= "percent">%</span>
                </div>
                <div class="form-group">
                    <label for="Tenure">Tenure:</label>
                    <input className="Input"
                      type='number'
                      min='1'
                      max='5'

                      name='tenure'
                      placeholder='1 year'
                      value={getInputValue("tenure")}

                      onChange={onChangeInput}
                      onFocus={() => {
                        setKeyboardVisibility(true);
                        setInputName("tenure")
                      }}

                                    />

                                </div>
                  { keyboardVisibility && (
                                  <Keyboard
                                    keyboardRef={(r) => (keyboard.current = r)}
                                    layoutName={layoutName}
                                    onChange={onChangeAll}
                                    onKeyPress={onKeyPress}
                                  />
                                )}

                            </form>

                <button className="calculate">Calculate
                            </button>

             </div>
          <div className="given">
            <p >
            Total Deposit: Rs 0
         </p>
         <p>
        Interest: Rs 0
         </p>
         <p>
         Maturity Amount: Rs 0
                            </p>

                        </div>

                    </div>

                </div>

  </div>

 <Link to="/">
 <button className="Back">
  <i class="fas fa-angle-double-left"></i>
         </button>
     </Link>
        </div>
    );
};

export default Calculator;
</code>```

答:
You are setting the inputs state by spreading input string from keyboard onChangeAll into an object setInputs({ ...inputs }). If I enter ab it will set as {0: "a", 1:"b"}.

Update the onChange prop in Keyboard to onChangeAll and pass inputName prop with your inputName state value. Read react-simple-keyboard DOCS.

onChangeAll

```<code> const onChangeAll = (inputs) => {
    console.log("Inputs changed", inputs);
    setInputs(inputs);
  };
</code>```

Keyboard

```<code>{keyboardVisibility && (
              <Keyboard
                keyboardRef={(r) => (keyboard.current = r)}
                layoutName={layoutName}
                onChangeAll={onChangeAll}
                onKeyPress={onKeyPress}
                inputName={inputName}
              />
            )}
</code>```

CodeSandbox link

Body:
I have following code of Calculator.jsx where everything looks fine.The main thing I want to achieve is keyboard to displayed only on input click which is done but the keyboard does not seem to type though the following code looks fine. Are there any other way to show/hide keyboard only on input click as well as make keyboard be able to type. My code for Calculator.jsx is
Calculator.jsx

import React, { useState, useRef, useEffect } from 'react';
import './Calculator.css'
import { Link } from 'react-router-dom';
import Keyboard from "react-simple-keyboard";
import "react-simple-keyboard/build/css/index.css";

const Calculator = () => {

  const [inputs, setInputs] = useState({});
  const [layoutName, setLayoutName] = useState("default");
  const [inputName, setInputName] = useState("default");
  const keyboard = useRef();
    const [keyboardVisibility, setKeyboardVisibility] = useState(false);

    useEffect(() => {
      function clickHanlder(e) {
        if (
          !(e.target.nodeName === "INPUT") &&
          !e.target.classList.contains("hg-button") &&
          !e.target.classList.contains("hg-row")
        ) {
          setKeyboardVisibility(false);
        }
      }

      window.addEventListener("click", clickHanlder);
      return window.removeEventListener("click", clickHanlder, true);
    }, []);

  const onChangeAll = inputs => {

    setInputs({ ...inputs });
    console.log("Inputs changed", inputs);
  };

  const handleShift = () => {
    const newLayoutName = layoutName === "default" ? "shift" : "default";
    setLayoutName(newLayoutName);
  };

  const onKeyPress = button => {
    console.log("Button pressed", button);

    if (button === "{shift}" || button === "{lock}") handleShift();
  };

  const onChangeInput = event => {
    const inputVal = event.target.value;

    setInputs({
      ...inputs,
      [inputName]: inputVal
    });

    keyboard.current.setInput(inputVal);
  };

  const getInputValue = inputName => {
    return inputs[inputName] || "";
  };

    return (

Deposit Calculator

                 <form  className="calculator">

                    Deposit Amount:
                    Rs
                    <input className="IInput"
                     type="text"
                     name='depositAmount'
                          placeholder='0'
                          value={getInputValue("depositAmount")}

                      onChange={onChangeInput}
                      onFocus={() => {
                         setKeyboardVisibility(true);
                        setInputName("depositAmount")
                      }}

                        />

                      Interest Rate:
                     <input className= "IIinput"
                     type="text"
                    name='Interest'
                                        placeholder='0'
                                        value={getInputValue("interestRate")}

                      onChange={onChangeInput}
                      onFocus={() => {
                        setKeyboardVisibility(true);
                        setInputName("interestRate")
                      }}
                     />

                     %

                    Tenure:
                    <input className="Input"
                      type='number'
                      min='1'
                      max='5'

                      name='tenure'
                      placeholder='1 year'
                      value={getInputValue("tenure")}

                      onChange={onChangeInput}
                      onFocus={() => {
                        setKeyboardVisibility(true);
                        setInputName("tenure")
                      }}

                                    />

                  { keyboardVisibility && (
                                  <Keyboard
                                    keyboardRef={(r) => (keyboard.current = r)}
                                    layoutName={layoutName}
                                    onChange={onChangeAll}
                                    onKeyPress={onKeyPress}
                                  />
                                )}

                            </form>

                <button className="calculate">Calculate
                            </button>

            Total Deposit: Rs 0

        Interest: Rs 0

         Maturity Amount: Rs 0

 <Link to="/">
 <button className="Back">

         </button>
     </Link>

    );
};

export default Calculator;

Body:
You are setting the inputs state by spreading input string from keyboard onChangeAll into an object setInputs({ ...inputs }). If I enter ab it will set as {0: "a", 1:"b"}.

Update the onChange prop in Keyboard to onChangeAll and pass inputName prop with your inputName state value. Read react-simple-keyboard DOCS.

onChangeAll

 const onChangeAll = (inputs) => {
    console.log("Inputs changed", inputs);
    setInputs(inputs);
  };

Keyboard

{keyboardVisibility && (
              <Keyboard
                keyboardRef={(r) => (keyboard.current = r)}
                layoutName={layoutName}
                onChangeAll={onChangeAll}
                onKeyPress={onKeyPress}
                inputName={inputName}
              />
            )}

CodeSandbox link