问:
SIGILL in Android NDK code
I have an NDK app out on market and got a native crash report about a SIGILL signal. (I use google breakpad to generate native crash reports.) Here are the details:

My app is compiled for armeabi-v7a, with NEON support.

It crashed on a NVIDIA Tegra 2 Processor, which is ARM-7 (Cortex-A9).

It happens every time. (contacted the user)

The crash address was at 0x399cc, the signal was SIGILL, and it's in my code.

Registers and disassembly:

```<code> r4 = 0x001d50f0    r5 = 0x001d50f0    r6 = 0x598e2a3c    r7 = 0x00000000
 r8 = 0x00000001    r9 = 0x001c22b0   r10 = 0x00000000    fp = 0x81216264
 sp = 0x598e2a18    lr = 0x816399cb    pc = 0x816399cc

0x000399c6 <_ZN8Analyzer15setExpAvgFactorEi+22>:    blx 0x30508
0x000399ca <_ZN8Analyzer15setExpAvgFactorEi+26>:    fconstd d16, #7
0x000399ce <_ZN8Analyzer15setExpAvgFactorEi+30>:    vldr    d17, [pc, #32]  ; 0x399f2 <_ZN8Analyzer15setExpAvgFactorEi+66>
</code>```

Full source and assembler available here (it's short, basically 2 lines of C++.)

You can see that 0x399cc is in the middle of the fconstd instruction. According to arm.com this instruction was added in VFP-v3, which should (I think) be available in any modern processor.

What could be going on? Does the fact that the address is in the middle of an instruction point to a corrupt pointer somewhere? (Note that the backtrace makes perfect sense, so it's not like this function was somehow called on accident.) Or is it something else?

答:
Ok, I got it: the NVIDIA Tegra 2 only has 16 64-bit GPU registers, and therefore to target it you must compile using -mfpu=vfpv3-d16. The instruction in question uses register d16, which is "just too many". :(

Here is a reference to an NVIDIA forum where an employee mentions this limitation: http://developer.nvidia.com/tegra/forum/optimal-performance-guidelines

Title: SIGILL in Android NDK code

Body:
I have an NDK app out on market and got a native crash report about a SIGILL signal. (I use google breakpad to generate native crash reports.) Here are the details:

My app is compiled for armeabi-v7a, with NEON support.

It crashed on a NVIDIA Tegra 2 Processor, which is ARM-7 (Cortex-A9).

It happens every time. (contacted the user)

The crash address was at 0x399cc, the signal was SIGILL, and it's in my code.

Registers and disassembly:

 r4 = 0x001d50f0    r5 = 0x001d50f0    r6 = 0x598e2a3c    r7 = 0x00000000
 r8 = 0x00000001    r9 = 0x001c22b0   r10 = 0x00000000    fp = 0x81216264
 sp = 0x598e2a18    lr = 0x816399cb    pc = 0x816399cc

0x000399c6 <_ZN8Analyzer15setExpAvgFactorEi+22>:    blx 0x30508
0x000399ca <_ZN8Analyzer15setExpAvgFactorEi+26>:    fconstd d16, #7
0x000399ce <_ZN8Analyzer15setExpAvgFactorEi+30>:    vldr    d17, [pc, #32]  ; 0x399f2 <_ZN8Analyzer15setExpAvgFactorEi+66>

Full source and assembler available here (it's short, basically 2 lines of C++.)

You can see that 0x399cc is in the middle of the fconstd instruction. According to arm.com this instruction was added in VFP-v3, which should (I think) be available in any modern processor.

What could be going on? Does the fact that the address is in the middle of an instruction point to a corrupt pointer somewhere? (Note that the backtrace makes perfect sense, so it's not like this function was somehow called on accident.) Or is it something else?


来源: stackexchange

问:
Styling infiniteHits with Algolia search
I have an Algolia search widget set up in my site, however the results all have their list number next to them.  How do I style this to remove the numbers?

The docs have this under cssClasses.

```<code>instantsearch.widgets.infiniteHits({
  // ...
  cssClasses: {
    root: 'MyCustomInfiniteHits',
    list: [
      'MyCustomInfiniteHits',
      'MyCustomInfiniteHits--subclass',
    ],
  },
});
</code>```

So I tried something like this.

```<code>instantsearch.widgets.infiniteHits({
  // ...
  cssClasses: {
    list: [
      'list-style: none',
    ],
  },
});
</code>```

but the numbers still appear.

My widget is inside of a Django template if that helps and I am using instantsearch.js.

答:
Ok, I actually figured it out.  The string that you include inside of

```<code>list: [
    'customClass'
]
</code>```

is the class that is applied to the element.  So you can then just add styling to your stylesheet.

ContentLicense: CC BY-SA 4.0

Body:
I have an Algolia search widget set up in my site, however the results all have their list number next to them.  How do I style this to remove the numbers?

The docs have this under cssClasses.

instantsearch.widgets.infiniteHits({
  // ...
  cssClasses: {
    root: 'MyCustomInfiniteHits',
    list: [
      'MyCustomInfiniteHits',
      'MyCustomInfiniteHits--subclass',
    ],
  },
});

So I tried something like this.

instantsearch.widgets.infiniteHits({
  // ...
  cssClasses: {
    list: [
      'list-style: none',
    ],
  },
});

but the numbers still appear.

My widget is inside of a Django template if that helps and I am using instantsearch.js.

Body:
Ok, I actually figured it out.  The string that you include inside of

list: [
    'customClass'
]

is the class that is applied to the element.  So you can then just add styling to your stylesheet.


问:
The action'NAVIGATE' with payload {"name":"Map_map"} was not handled > by any navigator
The error appears when I click on any of the buttons from Primary.js

Error:

The action'NAVIGATE' with payload {"name":"Map_map"} was not handled
by any navigator. Do you have a screen named 'Map_Map?

File structure:

app.js

nav (folder)

MainContainer.js

Screens (folder)

Primary.js /trying to get from this

Secondary.js

Map_map.js  /to this

-App.js (only contains MainContainer.js

MainContainer.js

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;
</code>```

Primary.js

```<code>import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props, {Map_map})
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(itemz => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate(map_map)}                    >
                        {itemz.name}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });
</code>```

答:
You should use the name prop to navigate instead of component name.

<Tab.Screen name={mapa_det} component={Map_map}/>

So, it should be:

navigation.navigate("Mapa_det")

Body:
The error appears when I click on any of the buttons from Primary.js

Error:

The action'NAVIGATE' with payload {"name":"Map_map"} was not handled
by any navigator. Do you have a screen named 'Map_Map?

File structure:

app.js

nav (folder)

MainContainer.js

Screens (folder)

Primary.js /trying to get from this

Secondary.js

Map_map.js  /to this

-App.js (only contains MainContainer.js

MainContainer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;

Primary.js

import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props, {Map_map})
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(itemz => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate(map_map)}                    >
                        {itemz.name}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });


问:
Warning in GCP Cloud SQL Database
Some time ago a warning showed up in loggings, as long as I can see it does not affect the projects workflow but it mess the logs.
The warning is:

```<code>[Warning] User 'mysql.session'@'localhost' was assigned access 0x8000 but was allowed to have only 0x0.
</code>```

What is it about?

Thanks!

答:
I’m gonna list the most common root causes for that error message you are getting:

Permissions: There are user permissions for the database, cloud functions, and the IAM roles. You can make it work by giving "All User" complete access. This is not secure, of course, but works.

Prod vs Dev (emulator): You can recall that access is less strict within the Google ecosystem, so running your functions on your emulator was a bad idea for troubleshooting. There are other ways (such as SSL or VM). As a last scenario, maybe you will have to deploy every time.

ORM: If you are using TypeORM for the first time, you will see that many of the tutorials are outdated.

Title: Warning in GCP Cloud SQL Database

Body:
Some time ago a warning showed up in loggings, as long as I can see it does not affect the projects workflow but it mess the logs.
The warning is:

[Warning] User 'mysql.session'@'localhost' was assigned access 0x8000 but was allowed to have only 0x0.

What is it about?

Thanks!


问:
TypeError: Cannot read properties of undefined (reading 'map') whole component code is not working
When I start the npm code for the cart component is not working and displayed the blank page
map function did not work. When I comment the part which is not working then another component like the header is displayed

```<code>import React  from 'react';
import Header from './Front/Header/Header';

    const Cart = (props ) => {
      const {cartitems} =props;
       const{handleAddProduct}=props;
       const {handleRemoveProduct}=props;
      return (
        <>
           <Header/>
            <div className="cart-items">
              <div className="cart-items-header"> cartitems</div>
              {!cartitems?.length ? (
                <div className="cart-items-empty"> No items added in cart</div>
              ) : null}
              <div>
           //this part of code is not working
                {cartitems.map((item) => (

                <div key={item.id}>

               <div>
                 <img className="cart-items-image"
                    src={item.image}
                    alt={item.name}  />
                    </div>

                   <button className='cart-items-add' onClick={()=>handleAddProduct(item)}>+</button>
                   <button className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>-</button>

                    <div className='cart-items-price'>{item.quantity}* ${item.price}</div>

              </div>
                ))}
                </div>
               </div>

          </>
      );
    }

    export default Cart;
</code>```

here is the code of app.js in this code I got an error that cartitems.find is not a function plz let me know how to fix this issue

```<code>const { productitems } = data;
  const [cartitems, setCartItems] = useState([]);
  const { user } = useContext(UserContext);
  const History = useHistory();

  const handleAddProduct = (product) => {
    //  console.log(product);
     const ProductExist = cartitems.find((item) => item.id === product.id)
    // console.log(ProductExist);
    //  setCartItems(ProductExist);

    if (ProductExist) {
      setCartItems(
         cartitems.map((item )=> item.id ===product.id ?
        {...ProductExist ,quantity:ProductExist.quantity +1}:item)
      )

    }
    else {
      setCartItems([...cartitems,{...product,quantity:1}])
      console.log('ni gya');
    }

  }
  const handleRemoveProduct = (product) => {
    const ProductExist = cartitems.find((item) => item.id === product.id);
    if (ProductExist.quantity === 1) {
      setCartItems(cartitems.filter((item) => item.id !== product.id));
    }
    else {
      setCartItems(
        cartitems.map((item) => item.id === product.id ?
          { ...ProductExist, quantity: ProductExist.quantity - 1 }
          : item)
      );

    }

  }
</code>```

答:
You can see there is a check above the code you commented out:

{
  !cartitems?.length ? (

No items added in cart

  ) : null
}```
</div>
</div>
</p>
<p>It checks to make sure <code>cartitems</code> is an array before attempting to use <code>map()</code> on it. In the ternary statement, instead of returning <code>null</code> if <code>cartitems</code> is empty, you should return the map function so it would read:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{!cartitems?.length ? (
  <div className="cart-items-empty"> No items added in cart</div>
) : cartitems.map(item => (
  // template code...
))}</code>```

Body:
When I start the npm code for the cart component is not working and displayed the blank page
map function did not work. When I comment the part which is not working then another component like the header is displayed

import React  from 'react';
import Header from './Front/Header/Header';

    const Cart = (props ) => {
      const {cartitems} =props;
       const{handleAddProduct}=props;
       const {handleRemoveProduct}=props;
      return (
        <>

 cartitems

              {!cartitems?.length ? (

 No items added in cart

              ) : null}

           //this part of code is not working
                {cartitems.map((item) => (

                   <button className='cart-items-add' onClick={()=>handleAddProduct(item)}>+</button>
                   <button className='cart-items-remove' onClick={()=>handleRemoveProduct(item)}>-</button>

{item.quantity}* ${item.price}

                ))}

          </>
      );
    }

    export default Cart;

here is the code of app.js in this code I got an error that cartitems.find is not a function plz let me know how to fix this issue

const { productitems } = data;
  const [cartitems, setCartItems] = useState([]);
  const { user } = useContext(UserContext);
  const History = useHistory();

  const handleAddProduct = (product) => {
    //  console.log(product);
     const ProductExist = cartitems.find((item) => item.id === product.id)
    // console.log(ProductExist);
    //  setCartItems(ProductExist);

    if (ProductExist) {
      setCartItems(
         cartitems.map((item )=> item.id ===product.id ?
        {...ProductExist ,quantity:ProductExist.quantity +1}:item)
      )

    }
    else {
      setCartItems([...cartitems,{...product,quantity:1}])
      console.log('ni gya');
    }

  }
  const handleRemoveProduct = (product) => {
    const ProductExist = cartitems.find((item) => item.id === product.id);
    if (ProductExist.quantity === 1) {
      setCartItems(cartitems.filter((item) => item.id !== product.id));
    }
    else {
      setCartItems(
        cartitems.map((item) => item.id === product.id ?
          { ...ProductExist, quantity: ProductExist.quantity - 1 }
          : item)
      );

    }

  }

Body:
You can see there is a check above the code you commented out:

{
  !cartitems?.length ? (
    <div className="cart-items-empty">No items added in cart</div>
  ) : null
}

It checks to make sure cartitems is an array before attempting to use map() on it. In the ternary statement, instead of returning null if cartitems is empty, you should return the map function so it would read:

{!cartitems?.length ? (
  <div className="cart-items-empty"> No items added in cart</div>
) : cartitems.map(item => (
  // template code...
))}


问:
How to make a bar chart with two colors for each bin?
I have a data frame with the names of articles, number of samples overall for each article, number of responders for a drug and number of non-responders. All together there are 9 articles:

```<code>Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
             "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)
</code>```

I need to make a bar chart with the Articles Names on the x axis, the overall samples number on the y axis, and color each bin so that for example responders would be blue and non-responders red, for each article.

I built a bar chart I just don't know what to type in the fill segment: (here I just typed the No_Benefit column but I know it's a wrong fill)

```<code>myplot <- ggplot(MyData, aes(x = Articles, y = Samples_number, fill= No_Benefit)) + theme_bw() + geom_col(position = "stack")
print(myplot)
</code>```

答:
I believe the main problem is with the format of the dataframe; your data is in 'wide' format, but ggplot2 works a lot better with 'long' format. You can pivot your dataframe from 'wide' to 'long' with the pivot_longer() function from the tidyr package, e.g.

library(ggplot2)
library(tidyr)

Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
              "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)

MyData_long <- pivot_longer(MyData, -c(Articles, Samples_number), names_to = "response")

ggplot(MyData_long, aes(x = Articles, y = Samples_number, fill= response)) +
  theme_bw() +
  geom_col(position = "stack")
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I have a data frame with the names of articles, number of samples overall for each article, number of responders for a drug and number of non-responders. All together there are 9 articles:

Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
             "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)

I need to make a bar chart with the Articles Names on the x axis, the overall samples number on the y axis, and color each bin so that for example responders would be blue and non-responders red, for each article.

I built a bar chart I just don't know what to type in the fill segment: (here I just typed the No_Benefit column but I know it's a wrong fill)

myplot <- ggplot(MyData, aes(x = Articles, y = Samples_number, fill= No_Benefit)) + theme_bw() + geom_col(position = "stack")
print(myplot)

Body:
I believe the main problem is with the format of the dataframe; your data is in 'wide' format, but ggplot2 works a lot better with 'long' format. You can pivot your dataframe from 'wide' to 'long' with the pivot_longer() function from the tidyr package, e.g.

library(ggplot2)
library(tidyr)

Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
              "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)

MyData_long <- pivot_longer(MyData, -c(Articles, Samples_number), names_to = "response")

ggplot(MyData_long, aes(x = Articles, y = Samples_number, fill= response)) +
  theme_bw() +
  geom_col(position = "stack")

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
How to use `setState` callback on react hooks
React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

```<code>setState(
  { name: "Michael" },
  () => console.log(this.state)
);
</code>```

I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

答:
I think what you need is useState and useCallback:

useState react doc;

useCallback react doc;

Example Code

```<code>import React, { useCallback, useState } from 'react';

const Test = () => {
  const [name, setName] = useState("");
  const testCallback = useCallback(() => console.log(name), [name]);

  return (
    <button onClick={() => {
      setName("Michael")
      testCallback();
    }}>Name</button>
  )
};

export default Test;
</code>```

Body:
React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

setState(
  { name: "Michael" },
  () => console.log(this.state)
);

I want to do something after the state is updated.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

Body:
I think what you need is useState and useCallback:

useState react doc;

useCallback react doc;

Example Code

import React, { useCallback, useState } from 'react';

const Test = () => {
  const [name, setName] = useState("");
  const testCallback = useCallback(() => console.log(name), [name]);

  return (
    <button onClick={() => {
      setName("Michael")
      testCallback();
    }}>Name</button>
  )
};

export default Test;


问:
read specific files names in adf pipeline
I have got requirement saying, blob storage has multiple files with names file_1.csv,file_2.csv,file_3.csv,file_4.csv,file_5.csv,file_6.csv,file_7.csv. From these i have to read only filenames from 5 to 7.

how we can achieve this in ADF/Synapse pipeline.

答:
I took a slightly different approaching using a Filter activity and the endsWith function:

The filter expression is:

```<code>@or(or(endsWith(item().name, '_5.csv'),endsWith(item().name, '_6.csv')),endsWith(item().name, '_7.csv'))
</code>```

Slightly different approaches, similar results, it depends what you need.

Body:
I took a slightly different approaching using a Filter activity and the endsWith function:

The filter expression is:

@or(or(endsWith(item().name, '_5.csv'),endsWith(item().name, '_6.csv')),endsWith(item().name, '_7.csv'))

Slightly different approaches, similar results, it depends what you need.


问:
React Typewriter effect doesn't reset
I have created a typewriting effect with React and it works perfectly fine. However, when I change the language with i18n both texts don't have the same length and it keeps writing until both texts have the same length and  then it changes the language and starts the effect again.

How can I reset the input when the language has changed? How can I reset the input when the component has been destroyed?

I have recorded a video

I have the same issue when I change from one page to another, as both pages have different texts and they don't have the same length.

Here code of my component

```<code>export const ConsoleText = ({text, complete = false}) => {
    const [currentText, setCurrentText] = useState("");
    const translatedText = i18n.t(text);
    const index = useRef(0);
    useEffect(() => {
        if (!complete && currentText.length !== translatedText.length) {
            const timeOut = setTimeout(() => {
                setCurrentText((value) => value + translatedText.charAt(index.current));
                index.current++;
            }, 20);
            return () => {
                clearTimeout(timeOut);
            }
        } else {
            setCurrentText(translatedText);
        }
    }, [translatedText, currentText, complete]);
    return (
        <p className="console-text">
            {currentText}
        </p>
    );
};
</code>```

答:
You are telling react to do setCurrentText(translatedText) only when it is complete or when the compared text lengths are equal, so yes it continues to write until this moment.

To reset your text when text changes, try creating another useEffect that will reset your states :

useEffect(() => {
  index.current = 0;
  setCurrentText('');
}, [text]);
```
<p>Now, I actually did this exact same feature few days ago, here is my component if it can help you :</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react';
import DOMPurify from 'dompurify';
import './text-writer.scss';

interface ITextWriterState {
    writtenText: string,
    index: number;
}

const TextWriter = ({ text, speed }: { text: string, speed: number }) => {
    const initialState = { writtenText: '', index: 0 };
    const sanitizer = DOMPurify.sanitize;

    const [state, setState] = React.useState<ITextWriterState>(initialState);

    React.useEffect(() => {
        if (state.index < text.length - 1) {
            const animKey = setInterval(() => {
                setState(state => {
                    if (state.index > text.length - 1) {
                        clearInterval(animKey);
                        return { ...state };
                    }
                    return {
                        writtenText: state.writtenText + text[state.index],
                        index: state.index + 1
                    };
                });
            }, speed);

            return () => clearInterval(animKey);
        }
    }, []);

    // Reset the state when the text is changed (Language change)
    React.useEffect(() => {
        if (text.length > 0) {
            setState(initialState);
        }
    }, [text])

    return <div className="text-writer-component"><span className="text" dangerouslySetInnerHTML={{ __html: sanitizer(state.writtenText) }} /></div>
}

export default TextWriter;
</code>```

The translation is made outside of the component so you can pass any kind of text to the component.

Title: React Typewriter effect doesn't reset

Body:
I have created a typewriting effect with React and it works perfectly fine. However, when I change the language with i18n both texts don't have the same length and it keeps writing until both texts have the same length and  then it changes the language and starts the effect again.

How can I reset the input when the language has changed? How can I reset the input when the component has been destroyed?

I have recorded a video

I have the same issue when I change from one page to another, as both pages have different texts and they don't have the same length.

Here code of my component

export const ConsoleText = ({text, complete = false}) => {
    const [currentText, setCurrentText] = useState("");
    const translatedText = i18n.t(text);
    const index = useRef(0);
    useEffect(() => {
        if (!complete && currentText.length !== translatedText.length) {
            const timeOut = setTimeout(() => {
                setCurrentText((value) => value + translatedText.charAt(index.current));
                index.current++;
            }, 20);
            return () => {
                clearTimeout(timeOut);
            }
        } else {
            setCurrentText(translatedText);
        }
    }, [translatedText, currentText, complete]);
    return (

            {currentText}

    );
};

Body:
You are telling react to do setCurrentText(translatedText) only when it is complete or when the compared text lengths are equal, so yes it continues to write until this moment.

To reset your text when text changes, try creating another useEffect that will reset your states :

useEffect(() => {
  index.current = 0;
  setCurrentText('');
}, [text]);

Now, I actually did this exact same feature few days ago, here is my component if it can help you :

import React from 'react';
import DOMPurify from 'dompurify';
import './text-writer.scss';

interface ITextWriterState {
    writtenText: string,
    index: number;
}

const TextWriter = ({ text, speed }: { text: string, speed: number }) => {
    const initialState = { writtenText: '', index: 0 };
    const sanitizer = DOMPurify.sanitize;

    const [state, setState] = React.useState<ITextWriterState>(initialState);

    React.useEffect(() => {
        if (state.index < text.length - 1) {
            const animKey = setInterval(() => {
                setState(state => {
                    if (state.index > text.length - 1) {
                        clearInterval(animKey);
                        return { ...state };
                    }
                    return {
                        writtenText: state.writtenText + text[state.index],
                        index: state.index + 1
                    };
                });
            }, speed);

            return () => clearInterval(animKey);
        }
    }, []);

    // Reset the state when the text is changed (Language change)
    React.useEffect(() => {
        if (text.length > 0) {
            setState(initialState);
        }
    }, [text])

    return <div className="text-writer-component"><span className="text" dangerouslySetInnerHTML={{ __html: sanitizer(state.writtenText) }} /></div>
}

export default TextWriter;

The translation is made outside of the component so you can pass any kind of text to the component.


问:
How to convert SQLite Blob field to string with Python
I want to open the Chrome (Login Data) file and use its password field. But this field is stored in byte/blob mode and can not be converted to text.

I also tried codecs and pickle and bytes.encode and str.decode but it didn't work.
Please look at the code below and help :

```<code>import sqlite3

connection_obj = sqlite3.connect('C:/Users/{username}/AppData/Local/Google/Chrome/User
Data/Default/Login Data')

cursor_obj = connection_obj.cursor()

statement = '''SELECT action_url, username_value, password_value  FROM logins'''

cursor_obj.execute(statement)

output = cursor_obj.fetchmany(5)

for url,usr,psw in output:
     # convert psw blob -> ascii text
     # ....
     # ....
     # for example psw filed:
     # b'v10\x7f\xa3\x1a\xd1\x83g\x8c\xc4\x14]\xb6n\xf85\xba\xca\xf5r\x17\xb6D\xed\xf5\x11rM\xbe\xbf\xb1\xc2y\xc5Vr\xc3\xb3NB\xc7J\x14\x95'
     #
     # convert to below text :
     # zarfilm-136342

   print(url, usr, psw,sep='------')
   print('*'*10)

connection_obj.commit()
connection_obj.close()
</code>```

答: Are you surprised to learn that this field is encrypted?  Google would be in for a world of trouble if it wasn't.  Even Chrome doesn't know how to decrypt this.  It's done with the Windows cryptography APIs, and involved your Windows login password.  You can't get them.</p>

Body:
I want to open the Chrome (Login Data) file and use its password field. But this field is stored in byte/blob mode and can not be converted to text.

I also tried codecs and pickle and bytes.encode and str.decode but it didn't work.
Please look at the code below and help :

import sqlite3

connection_obj = sqlite3.connect('C:/Users/{username}/AppData/Local/Google/Chrome/User
Data/Default/Login Data')

cursor_obj = connection_obj.cursor()

statement = '''SELECT action_url, username_value, password_value  FROM logins'''

cursor_obj.execute(statement)

output = cursor_obj.fetchmany(5)

for url,usr,psw in output:
     # convert psw blob -> ascii text
     # ....
     # ....
     # for example psw filed:
     # b'v10\x7f\xa3\x1a\xd1\x83g\x8c\xc4\x14]\xb6n\xf85\xba\xca\xf5r\x17\xb6D\xed\xf5\x11rM\xbe\xbf\xb1\xc2y\xc5Vr\xc3\xb3NB\xc7J\x14\x95'
     #
     # convert to below text :
     # zarfilm-136342

   print(url, usr, psw,sep='------')
   print('*'*10)

connection_obj.commit()
connection_obj.close()


问:
Get last conversations as admin in mongodb
I have a Learning Management System (LMS) where students can ask/chat with admins for each lesson.

As an Admin, I want to get last unseen chats from all lessons sorted by createdAt & seenByAdmin from dashboard.

Here's my Message Model:

{
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Student"
  },
  lessonId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Lesson"
  },
  from: {
    type: String,
    enum: ["student", "admin"]
  },
  content: {
    type: String
  },
  seenByAdmin: {
    type: Boolean,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now()
  }
}
```
<p>A you can see I don't care which admin is replying to the student.</p>
<p>My desired output:</p>
<pre class="lang-js prettyprint-override"><code>[
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
},
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    },
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
}
]
</code>```

OR

[
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  },
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  }
]
```

I have been stuck on writing a mongodb aggregation/query and I would appreciate any help!

答:
The aggregation pipeline:

{
      $sort: {
        seenByAdmin: 1,
        createdAt: -1
      }
    },
    {
      $group: {
        _id: "$studentId",
        messages: {
          $first: "$$ROOT"
        }
      }
    },
    {
      $replaceRoot: {
        newRoot: "$messages"
      }
    },
    {
      $skip: skip || 0
    },
    {
      $limit: limit || 10
    },
    {
      $lookup: {
        from: "students",
        localField: "studentId",
        foreignField: "_id",
        as: "student"
      }
    },
    {
      $project: {
        studentId: 1,
        lessonId: 1,
        from: 1,
        content: { $substr: ["$content", 0, 150] },
        createdAt: 1,
        seenByAdmin: 1,
        student: {
          $arrayElemAt: ["$student", 0]
        }
      }
    },
    {
      $project: {
        studentId: 1,
        lessonId: 1,
        from: 1,
        content: 1,
        createdAt: 1,
        seenByAdmin: 1,
        student: {
          _id: 1,
          name: 1
        }
      }
    }
```

Body:
I have a Learning Management System (LMS) where students can ask/chat with admins for each lesson.

As an Admin, I want to get last unseen chats from all lessons sorted by createdAt & seenByAdmin from dashboard.

Here's my Message Model:

{
  studentId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Student"
  },
  lessonId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Lesson"
  },
  from: {
    type: String,
    enum: ["student", "admin"]
  },
  content: {
    type: String
  },
  seenByAdmin: {
    type: Boolean,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now()
  }
}

A you can see I don't care which admin is replying to the student.

My desired output:

[
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
},
{
  lessonId: ObjectID,
  chats: [
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    },
    {
       studentId: ObjectID,
       createdAt: Date, /* of last message */
       seenByAdmin: Boolean, /* of last message */
       content: String /* content of last message (optional) */
    }
  ]
}
]

OR

[
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  },
  {
    lessonId: ObjectID,
    studentId: ObjectID,
    createdAt: Date, /* of last message */
    seenByAdmin: Boolean, /* of last message */
    content: String /* content of last message (optional) */
  }
]

I have been stuck on writing a mongodb aggregation/query and I would appreciate any help!


问:
How can I make a function to relocate and resize a set of controls
I have 10 panels all visible = false and have 10 buttons

panels name  = p1, p2, p3...etc

buttons name = b1, b2, b3...etc

I wanna when click on button(b1)

make panel(p1) visible = true

relocate and resize panels

The new location and new size for all panels are same,
Can I make a function do the relocate and resize instead of write a code more times like this

```<code>private void b1_Click(object sender, EventArgs e)
{
   p1.Visible = true;
   p1.Location = new System.Drawing.Point(9, 247);
   p1.Size = new System.Drawing.Size(1120, 464);
}
</code>```

答:
You can assign all buttons' click event to the same event handler. The parameter sender is the object that fires the event which in your case it is one of your buttons. Then check the sender's Text or Name property and find which button was clicked. For panels, you could make a method with a Panel type parameter and do what you want.

```<code>    private void btn_Click(object sender, EventArgs e)
    {
        // here put code to hide all panels
        //...

        //then show and relocate the panel related the clicked button as follows
        switch ((sender as Button).Name) //or button's Text
        {
            case "b1":
                showPanel(pl);
                break;
            case"b2":
                showPanel(p2);
                break;
            //other cases
            //...
        }
    }

    private void showPanel(Panel pnl)
    {
        //show and relocate
        pnl.Visible = true; //I consider pnl.Show(); as it's more readable
        //...
    }
</code>```

Don't forget to hide all panels at the beginning of the click event. You can use following method if you do not have any other panel in your control except those 10 ones.

```<code>    private void hidePanels()
    {
        foreach (Control c in yourControl.Controls) //replace yourControl with the control that is the container of your panels e.g. your form
        {
            if (c is Panel) c.Visible = false; //or c.Hide();
        }
    }
</code>```

I haven't tested this code, but it should work.

Body:
I have 10 panels all visible = false and have 10 buttons

panels name  = p1, p2, p3...etc

buttons name = b1, b2, b3...etc

I wanna when click on button(b1)

make panel(p1) visible = true

relocate and resize panels

The new location and new size for all panels are same,
Can I make a function do the relocate and resize instead of write a code more times like this

private void b1_Click(object sender, EventArgs e)
{
   p1.Visible = true;
   p1.Location = new System.Drawing.Point(9, 247);
   p1.Size = new System.Drawing.Size(1120, 464);
}

Body:
You can assign all buttons' click event to the same event handler. The parameter sender is the object that fires the event which in your case it is one of your buttons. Then check the sender's Text or Name property and find which button was clicked. For panels, you could make a method with a Panel type parameter and do what you want.

    private void btn_Click(object sender, EventArgs e)
    {
        // here put code to hide all panels
        //...

        //then show and relocate the panel related the clicked button as follows
        switch ((sender as Button).Name) //or button's Text
        {
            case "b1":
                showPanel(pl);
                break;
            case"b2":
                showPanel(p2);
                break;
            //other cases
            //...
        }
    }

    private void showPanel(Panel pnl)
    {
        //show and relocate
        pnl.Visible = true; //I consider pnl.Show(); as it's more readable
        //...
    }

Don't forget to hide all panels at the beginning of the click event. You can use following method if you do not have any other panel in your control except those 10 ones.

    private void hidePanels()
    {
        foreach (Control c in yourControl.Controls) //replace yourControl with the control that is the container of your panels e.g. your form
        {
            if (c is Panel) c.Visible = false; //or c.Hide();
        }
    }

I haven't tested this code, but it should work.


问:
Returning list of items for a given template in Python
I am curious on how to replace wildcards with multiple elements from a list. For instance:

```<code>template = 'w**er'
some_list = ['a', 't']

# I want to create a loop that gives out the output: ['water', 'wtaer']
</code>```

I tried playing around with my program and it is easy to replace the wildcard ('*') with only one character, however when there are multiple elements in a list, it complicates things and I am not sure how to do it.

Edit:

The loop I made:

```<code>for x in range(len(template)):
    if template[x] == '*':
        for y in range(len(letters)):
            template[x] = letters[y]
            word = ''.join(template)
            store.append(word)

store = ['wa*er', 'wt*er', 'wtaer', 'wtter']
</code>```

Hope someone can help me!

答:
Perhaps you're looking for itertools.permutations? You could replace * with a placeholder and use str.format to fill in:

```<code>from itertools import permutations
template = 'w{}{}er'
some_list = ['a', 't']
out = [template.format(*tpl) for tpl in permutations(some_list)]
</code>```

Output:

```<code>['water', 'wtaer']
</code>```

Body:
I am curious on how to replace wildcards with multiple elements from a list. For instance:

template = 'w**er'
some_list = ['a', 't']

# I want to create a loop that gives out the output: ['water', 'wtaer']

I tried playing around with my program and it is easy to replace the wildcard ('*') with only one character, however when there are multiple elements in a list, it complicates things and I am not sure how to do it.

Edit:

The loop I made:

for x in range(len(template)):
    if template[x] == '*':
        for y in range(len(letters)):
            template[x] = letters[y]
            word = ''.join(template)
            store.append(word)

store = ['wa*er', 'wt*er', 'wtaer', 'wtter']

Hope someone can help me!

Body:
Perhaps you're looking for itertools.permutations? You could replace * with a placeholder and use str.format to fill in:

from itertools import permutations
template = 'w{}{}er'
some_list = ['a', 't']
out = [template.format(*tpl) for tpl in permutations(some_list)]

Output:

['water', 'wtaer']


问:
my react project wont start back up using local host?
I am trying to update my react portfolio but to do that i have to be able to work on it. I have it up on heroku working and online. I pulled it up on my code editor and I do npm start and it compiles successfully but it wont go onto my localhost. Im wondering if anybody has an idea of why it wont come up. thanks a bunch</p>

答: i think you can put your project in github and uplaod it to heroku through your repository and then you can change you code , run it in localhost and changes will automatically get applied to your protfolio online</p>


答:
This type of problem is usually a data reshaping problem. Reshape to long format and the plot a bar graph with geom_col.

Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
              "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)

library(ggplot2)

MyData |>
  tidyr::pivot_longer(c(With_Benefit, No_Benefit)) |>
  ggplot(aes(Articles, value, fill = name)) +
  geom_col(position = position_stack()) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
```

Created on 2022-02-08 by the reprex package (v2.0.1)

Title: How to make a bar chart with two colors for each bin?

Body:
This type of problem is usually a data reshaping problem. Reshape to long format and the plot a bar graph with geom_col.

Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
              "Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)

MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)

library(ggplot2)

MyData |>
  tidyr::pivot_longer(c(With_Benefit, No_Benefit)) |>
  ggplot(aes(Articles, value, fill = name)) +
  geom_col(position = position_stack()) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
How to configure windows for large number of concurrent connections
I have seen many tutorial on how to tune Linux to scale  Node.js or Erlang server to 600K+ concurrent connections.

But I have not found similar tutorial for windows, can someone help with what are the similar knobs that exist for Windows.

/etc/security/limits.d/custom.conf

```<code>In root soft nofile 1000000
root hard nofile 1000000
 * soft nofile 1000000
 * hard nofile 1000000
 * List item
</code>```

/etc/sysctl.conf

```<code> fs.file-max = 1000000
 fs.nr_open = 1000000
 net.ipv4.netfilter.ip_conntrack_max = 1048576
 net.nf_conntrack_max = 1048576
</code>```

“fs.file-max”

The maximum file handles that can be allocated

“fs.nr_open”

Max amount of file handles that can be opened

“net.ipv4.netfilter.ip_conntrack_max”

how many connections the NAT can keep track of in the “tracking” table  Default is: 65536

答:
// Increase total number of connection allowed
[HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
TcpnumConnections =  16,777,214

// increase MaxFreeTcbs to > than number concurrent connection
[HKEY_LOCAL_MACHINE \System \CurrentControlSet \Services \Tcpip
\Parameters] MaxFreeTcbs = 2000 (Default = RAM dependent, but usual
Pro = 1000, Srv=2000)

// Increase hash table size for the hashtable helping TCP lookup
[HKEY_LOCAL_MACHINE \System \CurrentControlSet \services \Tcpip
\Parameters] MaxHashTableSize = 512 (Default = 512, Range = 64-65536)

// reduce tcp delay to limit half-open connection
[HKEY_LOCAL_MACHINE\System \CurrentControlSet \services \Tcpip \Parameters]
TcpTimedWaitDelay = 120 (Default = 240 secs, Range = 30-300)

Body:
I have seen many tutorial on how to tune Linux to scale  Node.js or Erlang server to 600K+ concurrent connections.

But I have not found similar tutorial for windows, can someone help with what are the similar knobs that exist for Windows.

/etc/security/limits.d/custom.conf

In root soft nofile 1000000
root hard nofile 1000000
 * soft nofile 1000000
 * hard nofile 1000000
 * List item

/etc/sysctl.conf

 fs.file-max = 1000000
 fs.nr_open = 1000000
 net.ipv4.netfilter.ip_conntrack_max = 1048576
 net.nf_conntrack_max = 1048576

“fs.file-max”

The maximum file handles that can be allocated

“fs.nr_open”

Max amount of file handles that can be opened

“net.ipv4.netfilter.ip_conntrack_max”

how many connections the NAT can keep track of in the “tracking” table  Default is: 65536


问:
Javascript alert function not displaying message after clicking button
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.</p>
```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <style type="text/css">

      body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

    </style>
    <script type="text/javascript">

      function orderSubmit() {
        var name = document.getElementById("txtName").value;
        var phone = document.getElementById("txtPhone").value;
        phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
        var address = document.getElementById("txtAddress").value;

        var msg = name + ", your order is being prepared. \n";
        msg+= "Your order will be delivered at " + address;
        msg+= "Your contact infromation is: " + phone "\n";
        msg+= "Order details: \n \n";

        for(var i = 0; i < document.frm1.rdoSize.length; i++) {
           if(document.frm1.rdoSize[i].checked) {
             var radioStateSize = document.frm1.rdoSize[i].value;
           }
        }
        for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
           if(document.frm1.rdoCrust[j].checked) {
             var radioStateCrust = document.frm1.rdoCrust[j].value;
           }
        }
        msg+= radioStateSize + ' ' + radioStateCrust + " pizza with the following toppings: \n";

        var chkToppings = document.frm1.chkToppings;

        for(k=0; k < document.frm1.chkToppings; k++) {
           if(document.frm1.chkToppings[k].checked) {
           msg += document.frm1.chkToppings[k].value + ' ';
           }
        }
        alert(msg);
      }

    </script>

  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>
</code>```

答:
Right at the beginning of your orderSubmit function you have a semicolon that has adventured off into a strange location right after the the parentheses like so:

function orderSubmit(); {
```
<p>Whereas it should look like this:</p>
<pre class="lang-js prettyprint-override"><code>function orderSubmit() {
</code>```

Good luck with your project!

Body:
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.

    <!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>

Body:
Right at the beginning of your orderSubmit function you have a semicolon that has adventured off into a strange location right after the the parentheses like so:

function orderSubmit(); {

Whereas it should look like this:

function orderSubmit() {

Good luck with your project!


问:
How test 11ty 404 page?
I've build a 404 page for my 11ty project, as shown in the 11ty quick tips:

```<code>https://www.11ty.dev/docs/quicktips/not-found/
QUICK TIP #006—ADDING A 404 NOT FOUND PAGE TO YOUR STATIC SITE
</code>```

I then added a deliberate link to a non-existing file like so:

[404 test](/error.html)

But when I click on this, I just get a console.log error, not the 404.html.  Note that I'm using eleventy's BrowserSync server.

So how can I test the 404 page?

答: Eleventy itself isn't a web server. It runs one locally while you dev, but in production, it's just files. Your web server/host/etc should provide a way to support 404s and you would set it up there.</p>

Title: How test 11ty 404 page?

Body:
I've build a 404 page for my 11ty project, as shown in the 11ty quick tips:

https://www.11ty.dev/docs/quicktips/not-found/
QUICK TIP #006—ADDING A 404 NOT FOUND PAGE TO YOUR STATIC SITE

I then added a deliberate link to a non-existing file like so:

[404 test](/error.html)

But when I click on this, I just get a console.log error, not the 404.html.  Note that I'm using eleventy's BrowserSync server.

So how can I test the 404 page?


问:
How can I write a where clause in SQL to filter a DATETIME column by the time of day?
I have data that is timestamped with a DATETIME column and I want to filter it down to the set of records where the DATETIME is between 9:30am and 5:30pm for any day.  What's the best way to do this?

UPDATE: Changed because I need precision to the minute, not just hour.  Sorry about that.

答:
Either something like this:

```<code>   ...
WHERE
  (DATEPART(hh, some_date) BETWEEN 10 AND 16)
  OR
  (DATEPART(hh, some_date) = 9 AND DATEPART(mi, some_date) >= 30)
  OR
  (DATEPART(hh, some_date) = 17 AND DATEPART(mi, some_date) <= 30)
</code>```

alternatively:

```<code>   ...
WHERE
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) >= '09:30' AND
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) <= '17:30'
</code>```

or even:

```<code>   ...
WHERE
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) BETWEEN '09:30' AND '17:30'
</code>```

No index can be used for this any of these queries. To use an index, pre-compute the values some way or other and store them in an indexed column.

OwnerDisplayName: Bialecki

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Milen A. Radev

Body:
Either something like this:

   ...
WHERE
  (DATEPART(hh, some_date) BETWEEN 10 AND 16)
  OR
  (DATEPART(hh, some_date) = 9 AND DATEPART(mi, some_date) >= 30)
  OR
  (DATEPART(hh, some_date) = 17 AND DATEPART(mi, some_date) <= 30)

alternatively:

   ...
WHERE
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) >= '09:30' AND
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) <= '17:30'

or even:

   ...
WHERE
  LEFT(CONVERT(VARCHAR, some_date, 8), 5) BETWEEN '09:30' AND '17:30'

No index can be used for this any of these queries. To use an index, pre-compute the values some way or other and store them in an indexed column.

OwnerDisplayName: Tomalak


问:
Display images from array to UIImageView
I am trying to display images from the array to the uiimageview, but it only shows the last image. Any advise?    </p>

```<code>for (int i = 0; i < [fileArr count]; i++)
{
               NSArray *fileNameArr = [[fileArr objectAtIndex:i] componentsSeparatedByString:@"."];
check=line;
                NSString *msg = [textView.text stringByAppendingString:[NSString stringWithFormat:@"Opening image: %@\n",[fileArr objectAtIndex:i]]];

                [textView performSelectorOnMainThread:@selector(setText:) withObject:msg waitUntilDone:NO];

                line=line+1;

                [image removeFromSuperview];
                [image release];
                image = nil;
                //specify the image path, open the image file with UIImage library
                NSString *imagePath = [NSString stringWithFormat:@"%@/%@",jfn1,[fileArr objectAtIndex:i]];
                NSString *imageFile = [NSHomeDirectory() stringByAppendingPathComponent:imagePath];
                NSString *pathExtension = [imageFile pathExtension];
                NSLog(@"----------------------------");
                NSLog(@"ImageFile: %@\n",imageFile);
                NSLog(@"File Extention: %@\n", pathExtension);
                NSLog(@"Interger value: %i\n",i);

                UIImage *myImage = [UIImage imageWithContentsOfFile:imageFile];
                NSLog(@"Image Width: %f", myImage.size.width);
                NSLog(@"Image height: %f", myImage.size.height);

                image = [[UIImageView alloc] initWithImage:myImage];
                image.contentMode = UIViewContentModeScaleAspectFit;
                [scrollView addSubview:image];
</code>```

答:
Because you are always

```<code>[image removeFromSuperview];
</code>```

before you

```<code>[scrollView addSubview:image];
</code>```

in the for loop.

How could it not be only showing the last imageView?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to display images from the array to the uiimageview, but it only shows the last image. Any advise?

for (int i = 0; i < [fileArr count]; i++)
{
               NSArray *fileNameArr = [[fileArr objectAtIndex:i] componentsSeparatedByString:@"."];
check=line;
                NSString *msg = [textView.text stringByAppendingString:[NSString stringWithFormat:@"Opening image: %@\n",[fileArr objectAtIndex:i]]];

                [textView performSelectorOnMainThread:@selector(setText:) withObject:msg waitUntilDone:NO];

                line=line+1;

                [image removeFromSuperview];
                [image release];
                image = nil;
                //specify the image path, open the image file with UIImage library
                NSString *imagePath = [NSString stringWithFormat:@"%@/%@",jfn1,[fileArr objectAtIndex:i]];
                NSString *imageFile = [NSHomeDirectory() stringByAppendingPathComponent:imagePath];
                NSString *pathExtension = [imageFile pathExtension];
                NSLog(@"----------------------------");
                NSLog(@"ImageFile: %@\n",imageFile);
                NSLog(@"File Extention: %@\n", pathExtension);
                NSLog(@"Interger value: %i\n",i);

                UIImage *myImage = [UIImage imageWithContentsOfFile:imageFile];
                NSLog(@"Image Width: %f", myImage.size.width);
                NSLog(@"Image height: %f", myImage.size.height);

                image = [[UIImageView alloc] initWithImage:myImage];
                image.contentMode = UIViewContentModeScaleAspectFit;
                [scrollView addSubview:image];

Body:
Because you are always

[image removeFromSuperview];

before you

[scrollView addSubview:image];

in the for loop.

How could it not be only showing the last imageView?


问:
Loadavg over possible value
Due to my simplified knowledge loadavg on N-core CPU should show max value N.

I've maximized CPU usage to 100% (8 x Temrminal with: $ node --eval 'while(1){}'

Linux built-in loadavg differs from my expectations and my own implementation (details on image)

Question - is my CPU really fully used?:

On my 8-core CPU native linux loadavg shows value over 9 (expected max is 8)

During test my PC was still working smoothly (youtube video run smoothly).

Check details below: .. Thread(s) per core: 2 .. - it still tells nothing because I was able to achievie bigger loadavg than 16, even 20:

Does it means that during test I used only 50% of my CPU potential? That /proc/loadavg tells the truth and system monitor (UI tool) lied about CPU usage?

PC details:

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal
</code>```
```<code>$ cat /proc/version
Linux version 5.13.0-27-generic (buildd@lgw01-amd64-045) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #29~20.04.1-Ubuntu SMP Fri Jan 14 00:32:30 UTC 2022
</code>```
```<code>$ lscpu
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   39 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           140
Model name:                      11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Stepping:                        1
CPU MHz:                         1700.000
CPU max MHz:                     4700,0000
CPU min MHz:                     400,0000
BogoMIPS:                        3379.20
Virtualization:                  VT-x
L1d cache:                       192 KiB
L1i cache:                       128 KiB
L2 cache:                        5 MiB
L3 cache:                        12 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constan
                                 t_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sd
                                 bg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 i
                                 nvpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rd
                                 t_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect
                                 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bit
                                 alg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities
</code>```

答:
Does it means that during test I used only 50% of my CPU potential? That /proc/loadavg tells the truth and system monitor (UI tool) lied about CPU usage?

loadavg and os.cpus()[n].times provide different information, meaning you can not compute one from the other. The former measures the number of tasks in the queue to get the CPU, the latter measures the load of the CPU itself. Indeed, for a very busy system you should expect loadavg to show greater values than the number of CPUs available (or even Thread availables) since the system will be CPU-bounded and more tasks will be waiting in the queue. See this for good answers explaining loadavg.

Question - is my CPU really fully used?

Your CPU is fully used as long as os.cpus()[n].times.idle does not increase. They come from /proc/stat. That is what your GUI is probably using (something like this for example). Your PC runs smoothly because Linux makes a good job providing a responsive system. Important and urgent tasks are given higher priority so that you can still watch videos on youtube while launching 8 infinite loops. This means that your code was not the only application that kept your CPU busy during your tests.

Title: Loadavg over possible value

Body:
Due to my simplified knowledge loadavg on N-core CPU should show max value N.

I've maximized CPU usage to 100% (8 x Temrminal with: $ node --eval 'while(1){}'

Linux built-in loadavg differs from my expectations and my own implementation (details on image)

Question - is my CPU really fully used?:

On my 8-core CPU native linux loadavg shows value over 9 (expected max is 8)

During test my PC was still working smoothly (youtube video run smoothly).

Check details below: .. Thread(s) per core: 2 .. - it still tells nothing because I was able to achievie bigger loadavg than 16, even 20:

Does it means that during test I used only 50% of my CPU potential? That /proc/loadavg tells the truth and system monitor (UI tool) lied about CPU usage?

PC details:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

$ cat /proc/version
Linux version 5.13.0-27-generic (buildd@lgw01-amd64-045) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #29~20.04.1-Ubuntu SMP Fri Jan 14 00:32:30 UTC 2022

$ lscpu
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   39 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           140
Model name:                      11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Stepping:                        1
CPU MHz:                         1700.000
CPU max MHz:                     4700,0000
CPU min MHz:                     400,0000
BogoMIPS:                        3379.20
Virtualization:                  VT-x
L1d cache:                       192 KiB
L1i cache:                       128 KiB
L2 cache:                        5 MiB
L3 cache:                        12 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constan
                                 t_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sd
                                 bg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 i
                                 nvpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rd
                                 t_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect
                                 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bit
                                 alg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities


问:
How to make the functions of necessary database operations?
How do I convert this code into proper function, means create table should be in seperate function, making connection should be seperate and inserting , viewing records too,  I am trying but getting error, if anybody can help me:

```<code>import psycopg2
import pandas as pd
df = pd.read_csv('dataframe.csv')

#  creating connection
conn = psycopg2.connect(database = "postgres",
                        user = "postgres",
                        password = "12345",
                        host = "127.0.0.1",
                        port = "5432")

print("Opened database successfully")

# Creating table stockmarketforecasting
cur = conn.cursor()
cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
      (date           VARCHAR(30)       NOT NULL,
       open           float        NOT NULL,
       high           float        NOT NULL,
       low            float        NOT NULL,
       close          float        NOT NULL);''')
print("Table created successfully")

# Inserting records in database
for i in range(0 ,len(df)):
    values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
    cur.execute("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                values)

conn.commit()
print("Records created successfully")

# View the records
cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
rows = cur.fetchall()
for row in rows:
    print(row)
print("Operation done successfully")
conn.close()
</code>```

Below code is which I am trying to convert into functions but getting error, Please tell me that what thing I am doing wrong.

My code:

```<code>import psycopg2
import pandas as pd
df = pd.read_csv('2_months_dataframe.csv')

#  creating connection
def create_connection():
    conn = psycopg2.connect(database = "postgres",
                            user = "postgres",
                            password = "12345",
                            host = "127.0.0.1",
                            port = "5432")
    print("Opened database successfully")
    return conn
conn = create_connection()

# Creating table stockmarketforecasting
def create_table(conn):
    conn = create_connection()
    cur = conn.cursor(conn)
    cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
          (date           VARCHAR(30)       NOT NULL,
           open           float        NOT NULL,
           high           float        NOT NULL,
           low            float        NOT NULL,
           close          float        NOT NULL);''')
    print("Table created successfully")

    conn.commit()
    return conn, cur
conn, cur = create_table(conn)

# Inserting records in database
def insering_records(df, conn, cur):
    for i in range(0 ,len(df)):
        values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
        cur.execute
        ("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                    values)

    conn.commit()
    print("Records created successfully")
    return cur, conn
conn, cur = insering_records(df, conn, cur)

# View the records
def viewing_records(conn, cur):
    cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
    rows = cur.fetchall()
    for row in rows:
        print(row)
    print("Operation done successfully")
    return rows
    conn.close()
rows = viewing_records(conn, cur)
</code>```

答:
I've made some corrections to your code, and it should work in this form. Let me know if you have any issues.</p>
```<code>import psycopg2 as ps
import pandas as pd

# Here you can put your database credentials
DB_HOST = ''
DB_NAME = ''
DB_USER = ''
DB_PASS = ''

df = pd.read_csv('dataframe.csv')

# Here you create a temporary connection, that closes automatically when the code stops
with ps.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) as conn:
    with conn.cursor() as cur:
        print("Opened database successfully")

        # Creating table stockmarketforecasting
        cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
            (date           VARCHAR(30)       NOT NULL,
            open           float        NOT NULL,
            high           float        NOT NULL,
            low            float        NOT NULL,
            close          float        NOT NULL);''')
        print("Table created successfully")

        # Inserting records in database
        for i in range(0 ,len(df)):
            values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
            cur.execute("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                        values)

        conn.commit()
        print("Records created successfully")

        # View the records
        cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
        rows = cur.fetchall()
        for row in rows:
            print(row)
        print("Operation done successfully")
</code>```

Body:
How do I convert this code into proper function, means create table should be in seperate function, making connection should be seperate and inserting , viewing records too,  I am trying but getting error, if anybody can help me:

import psycopg2
import pandas as pd
df = pd.read_csv('dataframe.csv')

#  creating connection
conn = psycopg2.connect(database = "postgres",
                        user = "postgres",
                        password = "12345",
                        host = "127.0.0.1",
                        port = "5432")

print("Opened database successfully")

# Creating table stockmarketforecasting
cur = conn.cursor()
cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
      (date           VARCHAR(30)       NOT NULL,
       open           float        NOT NULL,
       high           float        NOT NULL,
       low            float        NOT NULL,
       close          float        NOT NULL);''')
print("Table created successfully")

# Inserting records in database
for i in range(0 ,len(df)):
    values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
    cur.execute("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                values)

conn.commit()
print("Records created successfully")

# View the records
cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
rows = cur.fetchall()
for row in rows:
    print(row)
print("Operation done successfully")
conn.close()

Below code is which I am trying to convert into functions but getting error, Please tell me that what thing I am doing wrong.

My code:

import psycopg2
import pandas as pd
df = pd.read_csv('2_months_dataframe.csv')

#  creating connection
def create_connection():
    conn = psycopg2.connect(database = "postgres",
                            user = "postgres",
                            password = "12345",
                            host = "127.0.0.1",
                            port = "5432")
    print("Opened database successfully")
    return conn
conn = create_connection()

# Creating table stockmarketforecasting
def create_table(conn):
    conn = create_connection()
    cur = conn.cursor(conn)
    cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
          (date           VARCHAR(30)       NOT NULL,
           open           float        NOT NULL,
           high           float        NOT NULL,
           low            float        NOT NULL,
           close          float        NOT NULL);''')
    print("Table created successfully")

    conn.commit()
    return conn, cur
conn, cur = create_table(conn)

# Inserting records in database
def insering_records(df, conn, cur):
    for i in range(0 ,len(df)):
        values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
        cur.execute
        ("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                    values)

    conn.commit()
    print("Records created successfully")
    return cur, conn
conn, cur = insering_records(df, conn, cur)

# View the records
def viewing_records(conn, cur):
    cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
    rows = cur.fetchall()
    for row in rows:
        print(row)
    print("Operation done successfully")
    return rows
    conn.close()
rows = viewing_records(conn, cur)

Body:
I've made some corrections to your code, and it should work in this form. Let me know if you have any issues.

import psycopg2 as ps
import pandas as pd

# Here you can put your database credentials
DB_HOST = ''
DB_NAME = ''
DB_USER = ''
DB_PASS = ''

df = pd.read_csv('dataframe.csv')

# Here you create a temporary connection, that closes automatically when the code stops
with ps.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST) as conn:
    with conn.cursor() as cur:
        print("Opened database successfully")

        # Creating table stockmarketforecasting
        cur.execute('''CREATE TABLE STOCK_MARKET_FORECASTING
            (date           VARCHAR(30)       NOT NULL,
            open           float        NOT NULL,
            high           float        NOT NULL,
            low            float        NOT NULL,
            close          float        NOT NULL);''')
        print("Table created successfully")

        # Inserting records in database
        for i in range(0 ,len(df)):
            values = (df['date'][i], df['open'][i], df['high'][i], df['low'][i], df['close'][i])
            cur.execute("INSERT INTO STOCK_MARKET_FORECASTING (date, open, high, low, close) VALUES (%s, %s, %s, %s, %s)",
                        values)

        conn.commit()
        print("Records created successfully")

        # View the records
        cur.execute("SELECT * from STOCK_MARKET_FORECASTING")
        rows = cur.fetchall()
        for row in rows:
            print(row)
        print("Operation done successfully")


问:
Bugs Weka 3.8.6
After loading a dataset diabetes.arff and then choosing a classifier such as J48, I can start one test and after that the button "start" becomes disabled. Even clicking on stop it continues disabled. I changed the classifier to ZeroR and then the button became enabled again, but it does not work.I clicked several times and nothing. I also reinstalled Weka and tried other datasets, but every time the same problem.

I recorded a video to show this bug on https://1drv.ms/v/s!ApZk5TJm2dA3odp28KVQSssv34Lu4Q?e=uyrTD7

答:
As an alternative, you could try the Weka Investigator, a more powerful tool than the Weka Explorer. The Investigator is part of the ADAMS framework. For your purposes, you can download the adams-ml-app snapshot from the snapshot download page

Have a look at the video of my talk from the Weka User Conference 2021, for an introduction to the tool.

Title: Bugs Weka 3.8.6


问:
Numpy transpose weird output
```<code>np.array([3, 2, 3]).T == np.array([[3],[2],[1]])
</code>```

outputs:

```<code>[[ True False  True]
 [False  True False]
 [False False False]]
</code>```

Why isn't this equal and what does this output mean?

答:
So you have two arrays: np.array([3, 2, 3]).T (which is identical to the non-tranposed version: np.array([3, 2, 3])), and np.array([[3],[2],[1]]). Let's look at each one:

```<code>>>> a = np.array([3, 2, 3])
>>> a
array([3, 2, 3])

>>> b = np.array([[3],[2],[1]])
>>> b
array([[3],
       [2],
       [1]])
</code>```

Note how the first (a) is 1D, while the second (b) is 2D. Since they have different dimensions, trying to compare them will do what's called "numpy broadcasting", and it's a really cool feature.

To break it down:

```<code>>>> a == b
array([[ True, False,  True],
       [False,  True, False],
       [False, False, False]])
</code>```

Basically what the does, is for every item E in b, it checks if all the items in a are equal to E. To prove that:

```<code>>>> a == b[0]
array([ True, False,  True])

>>> a == b[1]
array([False,  True, False])

>>> a == b[2]
array([False, False, False])
</code>```

Notice how the above arrays are identical to the whole array made by a == b. That's because a == b is a short, efficient form of doing the above.

Title: Numpy transpose weird output

Body:
np.array([3, 2, 3]).T == np.array([[3],[2],[1]])

outputs:

[[ True False  True]
 [False  True False]
 [False False False]]

Why isn't this equal and what does this output mean?

Body:
So you have two arrays: np.array([3, 2, 3]).T (which is identical to the non-tranposed version: np.array([3, 2, 3])), and np.array([[3],[2],[1]]). Let's look at each one:

>>> a = np.array([3, 2, 3])
>>> a
array([3, 2, 3])

>>> b = np.array([[3],[2],[1]])
>>> b
array([[3],
       [2],
       [1]])

Note how the first (a) is 1D, while the second (b) is 2D. Since they have different dimensions, trying to compare them will do what's called "numpy broadcasting", and it's a really cool feature.

To break it down:

>>> a == b
array([[ True, False,  True],
       [False,  True, False],
       [False, False, False]])

Basically what the does, is for every item E in b, it checks if all the items in a are equal to E. To prove that:

>>> a == b[0]
array([ True, False,  True])

>>> a == b[1]
array([False,  True, False])

>>> a == b[2]
array([False, False, False])

Notice how the above arrays are identical to the whole array made by a == b. That's because a == b is a short, efficient form of doing the above.


问:
Jackson enum deserialize unwanted values to an "else" value
I'm trying to deserialize XML strings to this enum class

```<code>enum class FishType {
    @JsonProperty("fish-trout") TROUT,
    @JsonProperty("fish-salmon") SALMON,
    @JsonProperty("fish-halibut") HALIBUT,
    ...
}
</code>```

There are a lot of types, but I'm only interested in making use of the first three types listed. Is there a way to deserialize any other string to a FishType.ELSE entry, rather than manually enter each possible string?

答:
@JsonEnumDefaultValue works for XML too:

enum class FishType {
    @JsonProperty("fish-trout") TROUT,
    @JsonProperty("fish-salmon") SALMON,
    @JsonProperty("fish-halibut") HALIBUT,
    @JsonEnumDefaultValue ELSE
}

fun main() {
    val mapper = XmlMapper().apply {
        enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE)
    }
    println(mapper.readValue<FishType>("<FishType>fish-trout</FishType>")) //TROUT
    println(mapper.readValue<FishType>("<FishType>abc</FishType>")) //ELSE
}
```

Body:
I'm trying to deserialize XML strings to this enum class

enum class FishType {
    @JsonProperty("fish-trout") TROUT,
    @JsonProperty("fish-salmon") SALMON,
    @JsonProperty("fish-halibut") HALIBUT,
    ...
}

There are a lot of types, but I'm only interested in making use of the first three types listed. Is there a way to deserialize any other string to a FishType.ELSE entry, rather than manually enter each possible string?


问:
Tailwind CSS text over image problems
I'm trying to code as below
https://play.tailwindcss.com/5x8mBABcsW

How I can place the text over the circle image? I need the text centered and rounded on the bottom of the image.

I also want to be able to increase size of the image and everything should stay in proportion.

答:
this is a text

OR-

this is a text

```

I think you will try with this code-
Also, you will change or adjust values-

Title: Tailwind CSS text over image problems

Body:
<div class="relative w-40 h-40 overflow-hidden rounded-full">
    <img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="rounded-full w-full h-full" />
    <div
    class="absolute w-full py-3 bottom-0 inset-x-0 bg-blue-400 text-white text-xs text-center leading-4 hover:translate-y-1 delay-500">this is a text</div>
  </div>

OR-

<div class="relative w-40 h-40">
        <img src="https://www.w3schools.com/howto/img_avatar2.png" alt="Avatar" class="rounded-full w-full h-full" />
        <div class="absolute w-full h-full top-0 left-0 rounded-full bg-blue-400 text-white text-xs flex justify-center items-center opacity-0 hover:opacity-90">this is a text</div>
      </div>

I think you will try with this code-
Also, you will change or adjust values-