Title: How to change the date_format in Pyspark?

Body:
I'm currently working on pyspark and I've a csv file(having a few columns among which I'll display only the date datatype columns) which when opened in Excel looks like this:

Date received   Date sent to company
11/13/2014  11/13/2014
11/13/2014  11/13/2014
11/13/2014  11/13/2014
11/13/2014  11/13/2014
12-11-2014  11/13/2014
12-11-2014  11/13/2014
12-11-2014  11/13/2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014
12-11-2014  11-12-2014

Here is the screenshot for more clear understanding

As you can see I've used this csv file for my pyspark but I really want to have the date columns in one particular format say: "dd-mm-yyyy".

Can somebody help me with it?!

Although I've tried:

df.select(col("Date_received"),to_date(col("Date_received"),"dd-MM-yyyy").alias("date")) \
  .show()

Which gives the following ouput:

+-------------+----------+
|Date_received|      date|
+-------------+----------+
|   11/13/2014|      null|
|   11/13/2014|      null|
|   11/13/2014|      null|
|   11/13/2014|      null|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
|   12-11-2014|2014-11-12|
+-------------+----------+
only showing top 20 rows

Observe how the output  for first 4 rows is "null". And also I'm providing "dd-mm-yyyy" then how come the output has a "yyyy-mm-dd" format?

How to tackle this problem? Coz I want to change the date_format here(to "dd-mm-yyyy").

Body:
To tackle multiple date_formats available within your data , you can parse each one of them into a new column(s) using to_date and then finally coalesce the first non-null value

You can find more on this - Parse Date Format

Available Date Parsing Formats within Spark - https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html

A typical example is as below -

Data Preparation

df = pd.read_csv(StringIO("""
Date received,Date sent to company
11/13/2014,11/13/2014
11/13/2014,11/13/2014
11/13/2014,11/13/2014
11/13/2014,11/13/2014
12-11-2014,11/13/2014
12-11-2014,11/13/2014
12-11-2014,11/13/2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
12-11-2014,11-12-2014
"""),delimiter=",")

sparkDF = sql.createDataFrame(df)

sparkDF.show()

+-------------+--------------------+
|Date received|Date sent to company|
+-------------+--------------------+
|   11/13/2014|          11/13/2014|
|   11/13/2014|          11/13/2014|
|   11/13/2014|          11/13/2014|
|   11/13/2014|          11/13/2014|
|   12-11-2014|          11/13/2014|
|   12-11-2014|          11/13/2014|
|   12-11-2014|          11/13/2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
|   12-11-2014|          11-12-2014|
+-------------+--------------------+

To Date

sparkDF = sparkDF.withColumn('p1',F.to_date(F.col('Date received'),'MM/dd/yyyy'))\
                 .withColumn('p2',F.to_date(F.col('Date received'),'MM-dd-yyyy'))

sparkDF.show()

+-------------+--------------------+----------+----------+
|Date received|Date sent to company|        p1|        p2|
+-------------+--------------------+----------+----------+
|   11/13/2014|          11/13/2014|2014-11-13|      null|
|   11/13/2014|          11/13/2014|2014-11-13|      null|
|   11/13/2014|          11/13/2014|2014-11-13|      null|
|   11/13/2014|          11/13/2014|2014-11-13|      null|
|   12-11-2014|          11/13/2014|      null|2014-12-11|
|   12-11-2014|          11/13/2014|      null|2014-12-11|
|   12-11-2014|          11/13/2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
|   12-11-2014|          11-12-2014|      null|2014-12-11|
+-------------+--------------------+----------+----------+

Coalesce

sparkDF = sparkDF.withColumn('date_received_parsed',F.coalesce(F.col('p1'),F.col('p2')))\
                 .drop(*['p1','p2'])

sparkDF.show()

+-------------+--------------------+--------------------+
|Date received|Date sent to company|date_received_parsed|
+-------------+--------------------+--------------------+
|   11/13/2014|          11/13/2014|          2014-11-13|
|   11/13/2014|          11/13/2014|          2014-11-13|
|   11/13/2014|          11/13/2014|          2014-11-13|
|   11/13/2014|          11/13/2014|          2014-11-13|
|   12-11-2014|          11/13/2014|          2014-12-11|
|   12-11-2014|          11/13/2014|          2014-12-11|
|   12-11-2014|          11/13/2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
|   12-11-2014|          11-12-2014|          2014-12-11|
+-------------+--------------------+--------------------+


来源: stackexchange

问:
Should I leave small values in my rotation matrix?

My matrix

```<code>6.12303176911189E-17 1 0
-1 6.12303176911189E-17 0
0 0 1
</code>```

Rotation matrix calculated here

```<code>0       1       0
-1      0       0
0       0       1
</code>```

Question

Should I leave my matrix as it is, or should I set the small values to zero?

The function I use to generate rotation matrices

```<code>public void SetRotate(Vector axis, double angle)
{
    double angleSin = Math.Sin(angle);
    double angleCos = Math.Cos(angle);

    double a = 1.0 - angleCos;
    double ax = a * axis.X;
    double ay = a * axis.Y;
    double az = a * axis.Z;

    _m11 = ax * axis.X + angleCos;
    _m12 = ax * axis.Y + axis.Z * angleSin;
    _m13 = ax * axis.Z - axis.Y * angleSin;

    _m21 = ay * axis.X - axis.Z * angleSin;
    _m22 = ay * axis.Y + angleCos;
    _m23 = ay * axis.Z + axis.X * angleSin;

    _m31 = az * axis.X + axis.Y * angleSin;
    _m32 = az * axis.Y - axis.X * angleSin;
    _m33 = az * axis.Z + angleCos;
}
</code>```

答: It all depends, if that does not causes you any drawbacks (Z-Fighting between aligned planes, less readable code) and you need smooth transitions then leave it. Otherwise you might want to make rotations/scaling round to next degree/0.1 step.</p>

ContentLicense: CC BY-SA 3.0

Body:
My matrix

6.12303176911189E-17 1 0
-1 6.12303176911189E-17 0
0 0 1

Rotation matrix calculated here

0       1       0
-1      0       0
0       0       1

Question

Should I leave my matrix as it is, or should I set the small values to zero?

The function I use to generate rotation matrices

public void SetRotate(Vector axis, double angle)
{
    double angleSin = Math.Sin(angle);
    double angleCos = Math.Cos(angle);

    double a = 1.0 - angleCos;
    double ax = a * axis.X;
    double ay = a * axis.Y;
    double az = a * axis.Z;

    _m11 = ax * axis.X + angleCos;
    _m12 = ax * axis.Y + axis.Z * angleSin;
    _m13 = ax * axis.Z - axis.Y * angleSin;

    _m21 = ay * axis.X - axis.Z * angleSin;
    _m22 = ay * axis.Y + angleCos;
    _m23 = ay * axis.Z + axis.X * angleSin;

    _m31 = az * axis.X + axis.Y * angleSin;
    _m32 = az * axis.Y - axis.X * angleSin;
    _m33 = az * axis.Z + angleCos;
}


问:
Azure Data Factory - Setting up variables for Cosmos DB
I am using dataflow to insert data into Cosmos DB. My dataflow is linked to two Cosmos databases and I want to specify a variable to insert data into one Cosmos DB at a time when I trigger the pipeline. Whats the best way to do that?</p>

答:
You can have a parameterized Cosmos linked service connection at sink dataset, this will prompt to input value to the parameter when pipeline is triggered. Here you can manually enter value at pipeline trigger prompt or set value to a variable dynamically or default and execute the pipeline.

Example:

Edit linked service:

Set CosmosDB name property to a parameter:

Create a Dataset parameter and assign it to linked service parameter:

Now...in pipeline

OR

OR

ContentLicense: CC BY-SA 4.0


Title: How to modify the size of a <g> (SVG element)?

Body:
I can not seem to succeed at modifying the size of my  element that is rendered inside a recharts graph as X axis. I want it to be 20px height and width. I couldn't even succeed by making modifications in the console css to the element. Could anyone help me out?

Here's the element:

    <svg
          style={{ cursor: 'pointer',  }} width="20px" height="20px"
        >
          <g transform={`translate(10,10)`} fill="green" stroke="green">
            <path
              fill="current"
              fillRule="evenodd"
              d="M8,0 C3.58862306,0 0,3.58862306 0,8 C0,12.4113769 3.58862306,16 8,16 C12.4113769,16 16,12.4113769 16,8 C16,3.58862306 12.4113769,0 8,0 Z M12.0546875,6.3046875 L7.72131347,10.6379394 C7.59130859,10.7679443 7.42065431,10.833374 7.25,10.833374 C7.07934569,10.833374 6.90869141,10.7679443 6.77868653,10.6379394 L4.61206056,8.47131347 C4.35131837,8.21069338 4.35131837,7.78930663 4.61206056,7.52868653 C4.87268066,7.26794434 5.29394531,7.26794434 5.5546875,7.52868653 L7.25,9.22399903 L11.1120606,5.36206056 C11.3726807,5.10131837 11.7939453,5.10131837 12.0546875,5.36206056 C12.3153076,5.62268066 12.3153076,6.04394531 12.0546875,6.3046875 Z"
              transform="translate(.5)"
            />
          </g>
        </svg>

Body:
As @enxaneta recommended, a negative viewBox offset like  viewBox="-0.5 -0.5 17 17" is a straight forward solution.

Alternatively, you could scale your <g> (or your path) like so:

.svg{
  display:inline-block;
  width:10em;
  border: 1px solid #ccc
}

<svg class="svg" viewBox="0 0 16 16">
  <g transform="scale(0.94117647)" transform-origin="8 8" stroke-width="1" fill="green" stroke="green">
    <path  d="M8,0 C3.58862306,0 0,3.58862306 0,8 C0,12.4113769 3.58862306,16 8,16 C12.4113769,16 16,12.4113769 16,8 C16,3.58862306 12.4113769,0 8,0 Z M12.0546875,6.3046875 L7.72131347,10.6379394 C7.59130859,10.7679443 7.42065431,10.833374 7.25,10.833374 C7.07934569,10.833374 6.90869141,10.7679443 6.77868653,10.6379394 L4.61206056,8.47131347 C4.35131837,8.21069338 4.35131837,7.78930663 4.61206056,7.52868653 C4.87268066,7.26794434 5.29394531,7.26794434 5.5546875,7.52868653 L7.25,9.22399903 L11.1120606,5.36206056 C11.3726807,5.10131837 11.7939453,5.10131837 12.0546875,5.36206056 C12.3153076,5.62268066 12.3153076,6.04394531 12.0546875,6.3046875 Z" ></path>
  </g>
</svg>

Edit: correct scaling value

As @Carsten Massmann has pointed out it should be:

The scaling factor 0.94117647 is the result of

16/17 (original svg width / svg width + stroke-width)

transform-origin="8 8" ensures we're scaling from the center of our viewBox.

Another workaround might be to set overflow to visible to avoid any cropping:

.svg{
  display:inline-block;
  width:10em;
  border: 1px solid #ccc
}

<svg overflow="visible" class="svg" viewBox="0 0 16 16">
    <path  stroke-width="1" fill="green" stroke="green" d="M8,0 C3.58862306,0 0,3.58862306 0,8 C0,12.4113769 3.58862306,16 8,16 C12.4113769,16 16,12.4113769 16,8 C16,3.58862306 12.4113769,0 8,0 Z M12.0546875,6.3046875 L7.72131347,10.6379394 C7.59130859,10.7679443 7.42065431,10.833374 7.25,10.833374 C7.07934569,10.833374 6.90869141,10.7679443 6.77868653,10.6379394 L4.61206056,8.47131347 C4.35131837,8.21069338 4.35131837,7.78930663 4.61206056,7.52868653 C4.87268066,7.26794434 5.29394531,7.26794434 5.5546875,7.52868653 L7.25,9.22399903 L11.1120606,5.36206056 C11.3726807,5.10131837 11.7939453,5.10131837 12.0546875,5.36206056 C12.3153076,5.62268066 12.3153076,6.04394531 12.0546875,6.3046875 Z" ></path>
</svg>

Caveats: your icon will be displayed larger than your original design and might cause layout inconsistencies when used with other elements that fit the 16x16 boundaries.


问:
Firestore: Could not reach Cloud Firestore backend. Connection failed 1 times
I have a Firebase real-time database integrated with React Native where I can create users. But my problem is that when I try to log in I get an error. I run my app on IOS if it makes any difference. I have followed this guide: How to Build a React Native App and Integrate It with Firebase. I use the method Email/Password for login. I use Firebase version 9.6.4.

I have looked through this thread: Could not reach Cloud Firestore backend. and tried all the solutions but nothing works for me.

Any suggestions on what possibly could cause the error and how do I solve it?

Error message:

[2022-01-29T10:35:40.257Z]  @firebase/firestore:, Firestore (9.6.4):
Could not reach Cloud Firestore backend. Connection failed 1 times.
Most recent error: FirebaseError: [code=permission-denied]: Cloud
Firestore API has not been used in project xxxx before or it
is disabled.
If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry. This typically
indicates that your device does not have a healthy Internet connection
at the moment. The client will operate in offline mode until it is
able to successfully connect to the backend.

Firebase config.ts file:

```<code>import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: 'XXXXXXXXX',
  authDomain: 'XXXXXXXXX.firebaseapp.com',
  databaseURL: 'https://XXXXXXXXX.firebasedatabase.app',
  projectId: 'XXXXXXXXX',
  storageBucket: 'gs://XXXXXXXXX.appspot.com',
  messagingSenderId: 'XXXXXXXXX',
  appId: 'XXXXXXXXX',
};

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
}

export { firebase };
</code>```

LoginScreen.tsx

```<code>import React, { useState } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import { firebase } from '../../firebase/config';

export default function LoginScreen({navigation}) {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const onFooterLinkPress = () => {
        navigation.navigate('Registration')
    }

    const onLoginPress = () => {
        firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then((response) => {
                const uid = response.user.uid
                const usersRef = firebase.firestore().collection('users')
                usersRef
                    .doc(uid)
                    .get()
                    .then(firestoreDocument => {
                        if (!firestoreDocument.exists) {
                            alert("User does not exist anymore.")
                            return;
                        }
                        const user = firestoreDocument.data()
                        navigation.navigate('Home', {user})
                    })
                    .catch(error => {
                        alert(error)
                    });
            })
            .catch(error => {
                alert(error)
            })
    }

    return (
        <View style={styles.container}>
            <KeyboardAwareScrollView
                style={{ flex: 1, width: '100%' }}
                keyboardShouldPersistTaps="always">
                <Image
                    style={styles.logo}
                    source={require('../../assets/images/logo.png')}
                />
                <TextInput
                    style={styles.input}
                    placeholder='E-mail'
                    placeholderTextColor="#aaaaaa"
                    onChangeText={(text) => setEmail(text)}
                    value={email}
                    underlineColorAndroid="transparent"
                    autoCapitalize="none"
                />
                <TextInput
                    style={styles.input}
                    placeholderTextColor="#aaaaaa"
                    secureTextEntry
                    placeholder='Password'
                    onChangeText={(text) => setPassword(text)}
                    value={password}
                    underlineColorAndroid="transparent"
                    autoCapitalize="none"
                />
                <TouchableOpacity
                    style={styles.button}
                    onPress={() => onLoginPress()}>
                    <Text style={styles.buttonTitle}>Log in</Text>
                </TouchableOpacity>
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>Don't have an account? <Text onPress={onFooterLinkPress} style={styles.footerLink}>Sign up</Text></Text>
                </View>
            </KeyboardAwareScrollView>
        </View>
    )
}
</code>```

答:
Your error message says FirebaseError: [code=permission-denied]: Cloud Firestore API has not been used in project xxxx before or it is disabled.
The app tries to read a user document after signing in, but seems to have no access.

Check your firestore rules in your firebase console to see if read rules are valid. Firestore may have initialized with rules that allow only admin users to read/write, or rules that allow all read/write only for a month after its creation.

To make your app work, your firestore rules need to allow read access on users collection. Here are the rules you can set on your firestore. The more specific rules you set, the more secure the app is.

Allow unauthenticated access on all collections

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}
</code>```

Allow authenticated access on all collections

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

Allow authenticated access on users collection

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

See the firestore security doc for more.

Body:
I have a Firebase real-time database integrated with React Native where I can create users. But my problem is that when I try to log in I get an error. I run my app on IOS if it makes any difference. I have followed this guide: How to Build a React Native App and Integrate It with Firebase. I use the method Email/Password for login. I use Firebase version 9.6.4.

I have looked through this thread: Could not reach Cloud Firestore backend. and tried all the solutions but nothing works for me.

Any suggestions on what possibly could cause the error and how do I solve it?

Error message:

[2022-01-29T10:35:40.257Z]  @firebase/firestore:, Firestore (9.6.4):
Could not reach Cloud Firestore backend. Connection failed 1 times.
Most recent error: FirebaseError: [code=permission-denied]: Cloud
Firestore API has not been used in project xxxx before or it
is disabled.
If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry. This typically
indicates that your device does not have a healthy Internet connection
at the moment. The client will operate in offline mode until it is
able to successfully connect to the backend.

Firebase config.ts file:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseConfig = {
  apiKey: 'XXXXXXXXX',
  authDomain: 'XXXXXXXXX.firebaseapp.com',
  databaseURL: 'https://XXXXXXXXX.firebasedatabase.app',
  projectId: 'XXXXXXXXX',
  storageBucket: 'gs://XXXXXXXXX.appspot.com',
  messagingSenderId: 'XXXXXXXXX',
  appId: 'XXXXXXXXX',
};

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig);
}

export { firebase };

LoginScreen.tsx

import React, { useState } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import { firebase } from '../../firebase/config';

export default function LoginScreen({navigation}) {
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const onFooterLinkPress = () => {
        navigation.navigate('Registration')
    }

    const onLoginPress = () => {
        firebase
            .auth()
            .signInWithEmailAndPassword(email, password)
            .then((response) => {
                const uid = response.user.uid
                const usersRef = firebase.firestore().collection('users')
                usersRef
                    .doc(uid)
                    .get()
                    .then(firestoreDocument => {
                        if (!firestoreDocument.exists) {
                            alert("User does not exist anymore.")
                            return;
                        }
                        const user = firestoreDocument.data()
                        navigation.navigate('Home', {user})
                    })
                    .catch(error => {
                        alert(error)
                    });
            })
            .catch(error => {
                alert(error)
            })
    }

    return (
        <View style={styles.container}>
            <KeyboardAwareScrollView
                style={{ flex: 1, width: '100%' }}
                keyboardShouldPersistTaps="always">
                <Image
                    style={styles.logo}
                    source={require('../../assets/images/logo.png')}
                />
                <TextInput
                    style={styles.input}
                    placeholder='E-mail'
                    placeholderTextColor="#aaaaaa"
                    onChangeText={(text) => setEmail(text)}
                    value={email}
                    underlineColorAndroid="transparent"
                    autoCapitalize="none"
                />
                <TextInput
                    style={styles.input}
                    placeholderTextColor="#aaaaaa"
                    secureTextEntry
                    placeholder='Password'
                    onChangeText={(text) => setPassword(text)}
                    value={password}
                    underlineColorAndroid="transparent"
                    autoCapitalize="none"
                />
                <TouchableOpacity
                    style={styles.button}
                    onPress={() => onLoginPress()}>
                    <Text style={styles.buttonTitle}>Log in</Text>
                </TouchableOpacity>
                <View style={styles.footerView}>
                    <Text style={styles.footerText}>Don't have an account? <Text onPress={onFooterLinkPress} style={styles.footerLink}>Sign up</Text></Text>
                </View>
            </KeyboardAwareScrollView>
        </View>
    )
}

Body:
Your error message says FirebaseError: [code=permission-denied]: Cloud Firestore API has not been used in project xxxx before or it is disabled.
The app tries to read a user document after signing in, but seems to have no access.

Check your firestore rules in your firebase console to see if read rules are valid. Firestore may have initialized with rules that allow only admin users to read/write, or rules that allow all read/write only for a month after its creation.

To make your app work, your firestore rules need to allow read access on users collection. Here are the rules you can set on your firestore. The more specific rules you set, the more secure the app is.

Allow unauthenticated access on all collections

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Allow authenticated access on all collections

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

Allow authenticated access on users collection

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

See the firestore security doc for more.


问:
Django Deployment: ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
Hi All and thank you for taking the time to look at my question.

I'm a newbie to Python, thought I have experience in php/mysql.

I was just handed a code repository of a django site and asked to get it up and running on a server.
I've been able to run syncdb and migrate.
Now I'm trying to navigate to my site in the browser and this is the error that I get:

```<code>ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py
</code>```

My apach2.conf python config looks like this:

```<code><Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonOption django.root /myproject
SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"
PythonDebug on
</code>```

The settings.py file is in the directory /home/ubuntu/venvs/live/myproject.

Can someone please help me here?

Thanks!

答:
I think you should flip the order of the following lines:

```<code>SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"
</code>```

First set the Python path where settings.py can be found, and then set the env to that file.

But, you should really just install on the mod-wsgi as very well documented.

Body:
Hi All and thank you for taking the time to look at my question.

I'm a newbie to Python, thought I have experience in php/mysql.

I was just handed a code repository of a django site and asked to get it up and running on a server.
I've been able to run syncdb and migrate.
Now I'm trying to navigate to my site in the browser and this is the error that I get:

ImportError: Could not import settings 'settings.py' (Is it on sys.path?): No module named settings.py

My apach2.conf python config looks like this:

<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonOption django.root /myproject
SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"
PythonDebug on

The settings.py file is in the directory /home/ubuntu/venvs/live/myproject.

Can someone please help me here?

Thanks!

Body:
I think you should flip the order of the following lines:

SetEnv DJANGO_SETTINGS_MODULE settings.py
PythonPath "['/home/ubuntu/envs/live/','/home/ubuntu/envs/live/myproject','/home/ubuntu/envs/live/myproject/apps', '/home/ubuntu/envs/stage/myproject', '/home/ubuntu/envs/', '/var/www'] + sys.path"

First set the Python path where settings.py can be found, and then set the env to that file.

But, you should really just install on the mod-wsgi as very well documented.


问:
solving positional argument error in python
I am attempting to write a program in python that simulates a game of cheating hangman, but am receiving positional argument errors upon compilation. I wrote the class and methods in hangman.py and called the play method in play_hangman.py. When I attempt to run it, it gives the following error:

play() missing 9 required positional arguments: 'askForWordLength', 'askForNumberOfGuesses', 'remainingWords', 'words', 'wordStatus', 'printCountOfRemainingWords', 'printGameStats', 'askPlayerForGuess', and 'retrieveRemainingWords'

play_hangman.py

```<code>from hangman import Hangman

game = Hangman()
game.play()
y = input("Would you like to play again? yes or no: ")
while y == 'yes':
    game.play()
    y = input("Would you like to play again? yes or no: ")
</code>```

hangman.py

```<code>import re
class Hangman:
    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, file_lines, length):
        words = []
        for word in file_lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')```
```

答:
Your play() method requires many arguments:

def play(
    self,
    askForWordLength,
    askForNumberOfGuesses,
    remainingWords,
    words,
    wordStatus,
    printCountOfRemainingWords,
    printGameStats,
    askPlayerForGuess,
    retrieveRemainingWords
):
    ...
```

When you call the function, you need to provide all of those arguments, aside from self, otherwise, Python won't know what the value of those variables should be.

Body:
I am attempting to write a program in python that simulates a game of cheating hangman, but am receiving positional argument errors upon compilation. I wrote the class and methods in hangman.py and called the play method in play_hangman.py. When I attempt to run it, it gives the following error:

play() missing 9 required positional arguments: 'askForWordLength', 'askForNumberOfGuesses', 'remainingWords', 'words', 'wordStatus', 'printCountOfRemainingWords', 'printGameStats', 'askPlayerForGuess', and 'retrieveRemainingWords'

play_hangman.py

from hangman import Hangman

game = Hangman()
game.play()
y = input("Would you like to play again? yes or no: ")
while y == 'yes':
    game.play()
    y = input("Would you like to play again? yes or no: ")

hangman.py

import re
class Hangman:
    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, file_lines, length):
        words = []
        for word in file_lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')```

Body:
Your play() method requires many arguments:

def play(
    self,
    askForWordLength,
    askForNumberOfGuesses,
    remainingWords,
    words,
    wordStatus,
    printCountOfRemainingWords,
    printGameStats,
    askPlayerForGuess,
    retrieveRemainingWords
):
    ...

When you call the function, you need to provide all of those arguments, aside from self, otherwise, Python won't know what the value of those variables should be.


问:
Pushing API Data into Chart.js
I'm trying to push my API data into my chart, but there seems to be a problem with the timing of when the data is updated versus when the chart is rendered. I'm console.logging my two arrays, and it isn't showing anything in the array. Does anyone know what I need to change in order for my data to be updated to the state, before the chart renders with that data?</p>
```<code>function SmallBox(props) {
    const [chartNums, setChartNums] = useState([])
    const [chartLabels, setChartLabels] = useState([])
    const [chartData, setChartData] = useState({})
    const x = [];
    const y = [];

    const fetchData = async () => {
      await fetch(`https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        for (let i = 0; i < data.prices.length; i++){
          x.push(data.prices[i][0])
          setChartLabels(x)
        }

        for (let i = 0; i < data.prices.length; i++){
          y.push(data.prices[i][1])
          setChartNums(y)
        }

      })
    };

    const chart = async () => {
        await fetchData()
        console.log(chartNums)
        console.log(chartLabels)

        setChartData({
            labels: chartLabels,
            datasets: [
                {
                    label: '$',
                    data: chartNums,
                    backgroundColor: ['rgba(0,0,0,0.09)'],
                    borderColor: `${props.color}`,
                    borderWidth: 4,
                    borderJoinStyle: 'round',
                    borderCapStyle: 'round',
                    borderWidth: 3,
                    pointRadius: 0,
                    pointHitRadius: 10,
                    lineTension: .2,
                }
            ]
        })
    }

    useEffect(() =>{
      chart();
    }, []);

    return (
        <div id={props.id} className="smallBox">
            <div className="smallBox_info">
                <img className="smallBox-icon" src={props.image} alt={props.symbol}/>
                <h2>{props.title}</h2>
            </div>

            <div className="smallBox_numbers">
                <h2 className="smallBox-price">$ {props.currentPrice}</h2>
                <h5 className="smallBox-roc">{props.percentChange}</h5>
            </div>

            <div className="smallBox_graph">
                <Line data={chartData} options={{
                    responsive: true,
                    maintainAspectRatio: false,
                    title: {text: 'ThickBoyz', display: false},
                    legend: {display: false},
                    layout: {
                        padding: {
                          left: 0,
                          right: 0,
                          top: 0,
                          bottom: 0
                        }
                      },
                      scales: {
                        xAxes: [{
                          display: false,
                          gridLines: {}
                        }],
                        yAxes: [{
                          display: false,
                          gridLines: {}
                        }]
                      },
                      tooltips: {
                        callbacks: {
                          //This removes the tooltip title
                          title: function() {}
                       },
                        //this removes legend color
                        displayColors: false,
                        yPadding: 10,
                        xPadding: 10,
                        position: 'nearest',
                        caretSize: 10,
                        backgroundColor: 'rgba(255,255,255,.9)',
                        bodyFontSize: 15,
                        bodyFontColor: '#303030'
                      }
                    }}/>
            </div>
        </div>
    )
}

export default SmallBox

</code>```

答:
```<code>  const [chartLabels, setChartLabels] = useState([]);
  const [chartData, setChartData] = useState({});
  const x = [];
  const y = [];
  const props = {
    id: "bitcoin"
  };

  const fetchData = useCallback(async () => {
    const response = await fetch(
      `https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`
    );
    const data = await response.json();
    if (data && data.prices) {
      console.log(data.prices);
      for (let i = 0; i < data.prices.length; i++) {
        x.push(data.prices[i][0]);
        setChartLabels(x);
      }

      for (let i = 0; i < data.prices.length; i++) {
        y.push(data.prices[i][1]);
        setChartNums(y);
      }
    }
  }, [props,x,y]);
</code>```

Referring to the solution provided above you can init the x and y arrays wrapping useMemo Hook to return and more optimal solution and prevent
Warnings like this

Pro tip: if you add the dependencies incorrectly or none at all repetitive API calls might get you block.

Title: Pushing API Data into Chart.js

Body:
I'm trying to push my API data into my chart, but there seems to be a problem with the timing of when the data is updated versus when the chart is rendered. I'm console.logging my two arrays, and it isn't showing anything in the array. Does anyone know what I need to change in order for my data to be updated to the state, before the chart renders with that data?

function SmallBox(props) {
    const [chartNums, setChartNums] = useState([])
    const [chartLabels, setChartLabels] = useState([])
    const [chartData, setChartData] = useState({})
    const x = [];
    const y = [];

    const fetchData = async () => {
      await fetch(`https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        for (let i = 0; i < data.prices.length; i++){
          x.push(data.prices[i][0])
          setChartLabels(x)
        }

        for (let i = 0; i < data.prices.length; i++){
          y.push(data.prices[i][1])
          setChartNums(y)
        }

      })
    };

    const chart = async () => {
        await fetchData()
        console.log(chartNums)
        console.log(chartLabels)

        setChartData({
            labels: chartLabels,
            datasets: [
                {
                    label: '$',
                    data: chartNums,
                    backgroundColor: ['rgba(0,0,0,0.09)'],
                    borderColor: `${props.color}`,
                    borderWidth: 4,
                    borderJoinStyle: 'round',
                    borderCapStyle: 'round',
                    borderWidth: 3,
                    pointRadius: 0,
                    pointHitRadius: 10,
                    lineTension: .2,
                }
            ]
        })
    }

    useEffect(() =>{
      chart();
    }, []);

    return (

{props.title}

$ {props.currentPrice}

{props.percentChange}

                <Line data={chartData} options={{
                    responsive: true,
                    maintainAspectRatio: false,
                    title: {text: 'ThickBoyz', display: false},
                    legend: {display: false},
                    layout: {
                        padding: {
                          left: 0,
                          right: 0,
                          top: 0,
                          bottom: 0
                        }
                      },
                      scales: {
                        xAxes: [{
                          display: false,
                          gridLines: {}
                        }],
                        yAxes: [{
                          display: false,
                          gridLines: {}
                        }]
                      },
                      tooltips: {
                        callbacks: {
                          //This removes the tooltip title
                          title: function() {}
                       },
                        //this removes legend color
                        displayColors: false,
                        yPadding: 10,
                        xPadding: 10,
                        position: 'nearest',
                        caretSize: 10,
                        backgroundColor: 'rgba(255,255,255,.9)',
                        bodyFontSize: 15,
                        bodyFontColor: '#303030'
                      }
                    }}/>

    )
}

export default SmallBox

Body:
  const [chartLabels, setChartLabels] = useState([]);
  const [chartData, setChartData] = useState({});
  const x = [];
  const y = [];
  const props = {
    id: "bitcoin"
  };

  const fetchData = useCallback(async () => {
    const response = await fetch(
      `https://api.coingecko.com/api/v3/coins/${props.id}/market_chart?vs_currency=usd&days=1`
    );
    const data = await response.json();
    if (data && data.prices) {
      console.log(data.prices);
      for (let i = 0; i < data.prices.length; i++) {
        x.push(data.prices[i][0]);
        setChartLabels(x);
      }

      for (let i = 0; i < data.prices.length; i++) {
        y.push(data.prices[i][1]);
        setChartNums(y);
      }
    }
  }, [props,x,y]);

Referring to the solution provided above you can init the x and y arrays wrapping useMemo Hook to return and more optimal solution and prevent
Warnings like this

Pro tip: if you add the dependencies incorrectly or none at all repetitive API calls might get you block.


问:
Change direction of layout to RTL in Ant Design Blazor
How can I change direction of layout to RTL in Ant Blazor? There is not documentation about this. I mean changing direction to RTL similar the way Ant Blazor website changes direction by a button in header and using ConfigProvider.</p>

答:
After spending much time, I found that Router tag in App.razor should be wrapped inside ConfigProvider tag.

```<code><ConfigProvider>
   <Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
   </Router>
</ConfigProvider>
<AntContainer />
</code>```

After that you could use ConfigProvider as a CascadingParameter in your razor files.

```<code>[CascadingParameter] public ConfigProvider ConfigProvider { get; set; }
</code>```

Body:
After spending much time, I found that Router tag in App.razor should be wrapped inside ConfigProvider tag.

<ConfigProvider>
   <Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
   </Router>
</ConfigProvider>
<AntContainer />

After that you could use ConfigProvider as a CascadingParameter in your razor files.

[CascadingParameter] public ConfigProvider ConfigProvider { get; set; }


问:
asp.net string with different format to datetime when save to database
I want to save the string value of textbox to database as datetime and for updating/edit I want to display it again in textbox as string. This is due to the datetime that will be inputted will be copied from outlook and be pasted in textbox to be use easily by the user. I have no idea how to do it. Please help me with this. Thank you

Sample string: Thu 1/27/2022 8:37 AM

.cshtml part

```<code><input id="txtDateTime" maxlenght="25" type="text" class="form-control" />
......
</code>```

.js part (saving call cs)

```<code>SaveData: function(){
   var datetime = $("#txtDateTime").val();

   if(datetime == null || datetime == ""){
      alert("Datetime is required");
      return;
   }

   $.ajax({
      url: url,
      type: "POST",
      datatype: "JSON"
      data: {
         ......,
         DateTime: datetime
      }
   }).done(function(data)){
     ...........,
   }
}
</code>```

.cs part (saving to db)

```<code>public int AddData(Model data, out string outMessage)
{
   using (SqlConnection cn = new SqlConnect(Common.DBConnection))
   {
     cn.Open();
     using (SqlCommand cmd = cn.CreateCommand())
     {
       cmd.CommandText = "sp_add_data";
       cmd.CommandType = System.Data.CommandType.StoredProcedure;
       cmd.Parameters.AddWithValue("@DateTime", data.DateTime);
       .......,

       SqlParameter paramStatus = new SqlParameter();
       .......,

       SqlParameter paramMessage = new SqlParameter();
       .......,

       outMessage = paramMessage.Value.ToString();
       return Convert.ToInt32(paramStatus.Value.ToString());
     }
   }
}
</code>```

sp_add_data

```<code>@DateTime datetime,
.....,
//insert script
</code>```

Hope you can help me with this thank you.

答:
Try this:

```<code>cmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = DateTime.Parse(data.DateTime);
</code>```

It should figure out, and accept the day of week part you have.

Body:
I want to save the string value of textbox to database as datetime and for updating/edit I want to display it again in textbox as string. This is due to the datetime that will be inputted will be copied from outlook and be pasted in textbox to be use easily by the user. I have no idea how to do it. Please help me with this. Thank you

Sample string: Thu 1/27/2022 8:37 AM

.cshtml part

<input id="txtDateTime" maxlenght="25" type="text" class="form-control" />
......

.js part (saving call cs)

SaveData: function(){
   var datetime = $("#txtDateTime").val();

   if(datetime == null || datetime == ""){
      alert("Datetime is required");
      return;
   }

   $.ajax({
      url: url,
      type: "POST",
      datatype: "JSON"
      data: {
         ......,
         DateTime: datetime
      }
   }).done(function(data)){
     ...........,
   }
}

.cs part (saving to db)

public int AddData(Model data, out string outMessage)
{
   using (SqlConnection cn = new SqlConnect(Common.DBConnection))
   {
     cn.Open();
     using (SqlCommand cmd = cn.CreateCommand())
     {
       cmd.CommandText = "sp_add_data";
       cmd.CommandType = System.Data.CommandType.StoredProcedure;
       cmd.Parameters.AddWithValue("@DateTime", data.DateTime);
       .......,

       SqlParameter paramStatus = new SqlParameter();
       .......,

       SqlParameter paramMessage = new SqlParameter();
       .......,

       outMessage = paramMessage.Value.ToString();
       return Convert.ToInt32(paramStatus.Value.ToString());
     }
   }
}

sp_add_data

@DateTime datetime,
.....,
//insert script

Hope you can help me with this thank you.

Body:
Try this:

cmd.Parameters.Add("@DateTime", SqlDbType.DateTime).Value = DateTime.Parse(data.DateTime);

It should figure out, and accept the day of week part you have.


问:
Counting values based on certain conditions in R?
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

```<code>patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56
</code>```

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

答:
Assuming you have a data.table called dt have variables patient and code.

```<code>library(data.table)
dt <- data.table(patient = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
                                 3L, 3L, 3L, 4L, 4L, 4L, 4L), code = c(25L, 26L, 39L, 26L, 86L,
                                                                       26L, 24L, 89L, 56L, 45L, 26L, 89L, 56L, 25L, 66L, 56L))

with(dt[code == 26], ftable(patient))
</code>```

Here is the output

```<code>patient 1 2 3

        2 1 1
</code>```

Body:
I have a dataset and I'm trying to count the number of codes each patient has, as well as the number of codes of interest that each patient has.

Let's say that I have this table below and my code of interest is 26.

patient code
1       25
1       26
1       39
1       26
1       86
2       26
2       24
2       89
3       56
3       45
3       26
3       89
4       56
4       25
4       66
4       56

Patient 1 total code: 5 total codes, 2 codes of interest

Patient 2 total code: 3 total codes, 1 code of interest

Patient 3 total code: 4 total codes, 1 code of interest

Patient 4 total code: 4 total codes, 0 codes of interest

How can I do this in R? Thank you!

Body:
Assuming you have a data.table called dt have variables patient and code.

library(data.table)
dt <- data.table(patient = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L,
                                 3L, 3L, 3L, 4L, 4L, 4L, 4L), code = c(25L, 26L, 39L, 26L, 86L,
                                                                       26L, 24L, 89L, 56L, 45L, 26L, 89L, 56L, 25L, 66L, 56L))

with(dt[code == 26], ftable(patient))

Here is the output

patient 1 2 3

        2 1 1


问:
Theory of storing a number and text in same SQL field
I have a three tables

Results:
TestID
TestCode
Value

Tests:
TestID
TestType
SysCodeID

SystemCodes
SysCodeID
ParentSysCodeID
Description

The question I have is for when the user is entering data into the results table.

The formatting code when the row gets the focus changes the value field to a dropdown combobox if the testCode is of type SystemList.  The drop down has a list of all the system codes that have a parentsyscodeID of the test.SysCodeID.  When the user chooses a value in the list it translates into a number which goes into the value field.

The datatype of the Results.Value field is integer.  I made it an integer instead of a string because when reporting it is easier to do calculations and sorting if it is a number.  There are issues if you are putting integer/decimal value into a string field.  As well, when the system was being designed they only wanted numbers in there.

The users now want to put strings into the value field as well as numbers/values from a list and I'm wondering what the best way of doing that would be.

Would it be bad practice to convert the field over to a string and then store both strings and integers in the same field?  There are different issues related to this one but i'm not sure if any are a really big deal.

Should I add another column into the table of string datatype and  if the test is a string type then put the data the user enters into the different field.

Another option would be to create a 1-1 relationship to another table and if the user types in a string into the value field it adds it into the new table with a key of a number.

Anyone have any interesting ideas?

答: I'd convert the value field to string and add a column indicating what the datatype should be treated as for post processing and reporting.</p>

OwnerDisplayName: Jaydel Gluckie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: TrickyNixon


问:
Zend : Error Occurs when create html file from zend phtml file for multiple employee
```<code>//controller function
function sendBulkMailAction(){
       $template = "estimated-festival-bill-single.phtml";
       foreach ($employeeArr as $profile_id => $employeeValue) {

            $someData = array(); //here include some salary data
            $model = new ViewModel($someData);
            $model->setTemplate($template);

             $htmlContent = "<!DOCTYPE html>\n\r<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\r<head>
                            <meta charset=\"utf-8\">
                        </head>
                        <body>"
            . $this->getServiceLocator()->get('viewrenderer')->render($model)
            . "</body>
                    </html>";

          //create html file

           //create pdf link from html by wkhtmlToPdf

          //send this link via email to employee

     }
 }

//estimated-festival-bill-single.phtml
//simple code
<div> Employee Name</div>
<br>
<div><?php echo  _get_salary_html(); ?></div>
 <?php
function _get_salary_html(){
   return "Salary Data";
}
?>
</code>```

error show

Fatal error:  Cannot redeclare _get_salary_html() (previously declared in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml:9) in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml on line 10

hints: when single employee its ok but for multiple employee show error

答:
Because you are re-declaring function unknowingly. Add a condition around the function like below.</p>
```<code>if (!function_exists('_get_salary_html'))   {
  function _get_salary_html()  {
    ........
  }
}
</code>```

Body:
//controller function
function sendBulkMailAction(){
       $template = "estimated-festival-bill-single.phtml";
       foreach ($employeeArr as $profile_id => $employeeValue) {

            $someData = array(); //here include some salary data
            $model = new ViewModel($someData);
            $model->setTemplate($template);

             $htmlContent = "<!DOCTYPE html>\n\r\n\r
                            <meta charset=\"utf-8\">

                        "
            . $this->getServiceLocator()->get('viewrenderer')->render($model)
            . "
                    ";

          //create html file

           //create pdf link from html by wkhtmlToPdf

          //send this link via email to employee

     }
 }

//estimated-festival-bill-single.phtml
//simple code

 Employee Name

<?php echo  _get_salary_html(); ?>

 <?php
function _get_salary_html(){
   return "Salary Data";
}
?>

error show

Fatal error:  Cannot redeclare _get_salary_html() (previously declared in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml:9) in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml on line 10

hints: when single employee its ok but for multiple employee show error

Body:
Because you are re-declaring function unknowingly. Add a condition around the function like below.

if (!function_exists('_get_salary_html'))   {
  function _get_salary_html()  {
    ........
  }
}


问:
Editing Span labels in Spacy doc
This is my first time asking a question so please let me know if there's more information that you might need.
I have a spacy doc and a list of tags that looks like ['O', 'O', 'PERSON','O','GPE',...] and would like to edit the entity labels in the doc object to match the tags.
I understand that the doc consists of tokens and also entities Doc.ents, but there seems to be a lot of different components where if I change one artificially it might break the integrity of the Doc.
My question is, what would be the best way to go about this? Is there a certain constructor I can use or a method? Can I just change the label directly?

Thanks!

答:
Normally the easiest way to set entities from IOB tags besides using a file converter is to use the Doc constructor. But it looks like your tags don't have the IOB part (they should have like B-PERSON, not just PERSON), so that won't work.

You can set the entity label correctly, but you can't set the IOB tag directly, and without updates to the IOB tags the entities won't be recognized correctly.

Since it sounds like these tags are coming from outside spaCy, tokenization is also an issue. Are you sure the tokens will always align with spaCy tokens?

If alignment is not an issue, and you never have the same entity occur twice in a row with nothing in between, I guess you could automatically convert your labels to BIO just by making the first item B and the second item O. If you do that then you can use the Doc constructor.

Example:

```<code>original: O PERSON PERSON O O
cleaned:  O B-PERSON I-PERSON O O
</code>```

Title: Editing Span labels in Spacy doc

Body:
Normally the easiest way to set entities from IOB tags besides using a file converter is to use the Doc constructor. But it looks like your tags don't have the IOB part (they should have like B-PERSON, not just PERSON), so that won't work.

You can set the entity label correctly, but you can't set the IOB tag directly, and without updates to the IOB tags the entities won't be recognized correctly.

Since it sounds like these tags are coming from outside spaCy, tokenization is also an issue. Are you sure the tokens will always align with spaCy tokens?

If alignment is not an issue, and you never have the same entity occur twice in a row with nothing in between, I guess you could automatically convert your labels to BIO just by making the first item B and the second item O. If you do that then you can use the Doc constructor.

Example:

original: O PERSON PERSON O O
cleaned:  O B-PERSON I-PERSON O O


问:
Not able to create theme using Material UI's ThemeProvider and createTheme
I kept getting a failed to compile error:

Attempted import error: 'createTheme' is not exported from
'@material-ui/core/styles'.

Code:

```<code>import React, { Suspense, lazy } from "react";
import "./App.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import useToken from "./util/useToken";
import Page404 from "./pages/404";
import { ThemeProvider } from "@material-ui/styles";
import { createTheme } from "@material-ui/core/styles";

const Landing = lazy(() => import("./pages/Landing/Landing"));
const Login = lazy(() => import("./pages/Login"));
const Homepage = lazy(() => import("./pages/Homepage/Homepage"));
const UserProfile = lazy(() => import("./pages/User/UserProfile"));
const Post = lazy(() => import("./pages/Post"));

const theme = createTheme({
  palette: {
    primary: {
      // Purple and green play nicely together.
      main: "red",
    },
    secondary: {
      // This is green.A700 as hex.
      main: "#11cb5f",
    },
  },
});

function App() {
  const { setToken, token } = useToken();

  return (
    <>
      <ThemeProvider theme={theme}>
        <BrowserRouter>
          <Suspense
            fallback={
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  flexDirection: "column",
                  justifyContent: "center",
                  height: "100vh",
                }}
              >
                Page is Loading...
              </div>
            }
          >
            <Switch>
              <Route exact path="/">
                <Landing token={token} />
              </Route>
              <Route exact path="/home">
                <Homepage setToken={setToken} />
              </Route>
              <Route exact path="/login">
                <Login token={token} />
              </Route>
              <Route exact path="/posts/:postId">
                <Post token={token} />
              </Route>
              <Route exact path="/users/:userId">
                <UserProfile token={token} />
              </Route>
              <Route component={Page404} />
            </Switch>
          </Suspense>
        </BrowserRouter>
      </ThemeProvider>
    </>
  );
}

export default App;
</code>```

Using these versions of MaterialUI packages:

```<code>"@material-ui/core": "^4.11.2",
"@material-ui/icons": "^4.11.2",
"@material-ui/lab": "^4.0.0-alpha.57",
"@material-ui/styles": "^4.11.2",
</code>```

I've tried importing directly from @material-ui/styles still getting same error.

PLEASE IGNORE: Adding additional text as StackOverflow says that post is mostly code and that I should add more details, even thought there is enough details provided :)

答:
There is no function createtheme in material-ui/core/style
Instead use

```<code>import {createMuiTheme} from '@material-ui/core';
const theme = createMuiTheme({
palette: {
primary: {
  main: "HEXADECIMAL COLOR"
},
secondary: {
  main: "HEXADECIMAL COLOR"
}
</code>```

}
});

Body:
I kept getting a failed to compile error:

Attempted import error: 'createTheme' is not exported from
'@material-ui/core/styles'.

Code:

import React, { Suspense, lazy } from "react";
import "./App.css";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import useToken from "./util/useToken";
import Page404 from "./pages/404";
import { ThemeProvider } from "@material-ui/styles";
import { createTheme } from "@material-ui/core/styles";

const Landing = lazy(() => import("./pages/Landing/Landing"));
const Login = lazy(() => import("./pages/Login"));
const Homepage = lazy(() => import("./pages/Homepage/Homepage"));
const UserProfile = lazy(() => import("./pages/User/UserProfile"));
const Post = lazy(() => import("./pages/Post"));

const theme = createTheme({
  palette: {
    primary: {
      // Purple and green play nicely together.
      main: "red",
    },
    secondary: {
      // This is green.A700 as hex.
      main: "#11cb5f",
    },
  },
});

function App() {
  const { setToken, token } = useToken();

  return (
    <>
      <ThemeProvider theme={theme}>
        <BrowserRouter>
          <Suspense
            fallback={

                Page is Loading...

            }
          >
            <Switch>
              <Route exact path="/">
                <Landing token={token} />
              </Route>
              <Route exact path="/home">
                <Homepage setToken={setToken} />
              </Route>
              <Route exact path="/login">
                <Login token={token} />
              </Route>
              <Route exact path="/posts/:postId">
                <Post token={token} />
              </Route>
              <Route exact path="/users/:userId">
                <UserProfile token={token} />
              </Route>
              <Route component={Page404} />
            </Switch>
          </Suspense>
        </BrowserRouter>
      </ThemeProvider>
    </>
  );
}

export default App;

Using these versions of MaterialUI packages:

"@material-ui/core": "^4.11.2",
"@material-ui/icons": "^4.11.2",
"@material-ui/lab": "^4.0.0-alpha.57",
"@material-ui/styles": "^4.11.2",

I've tried importing directly from @material-ui/styles still getting same error.

PLEASE IGNORE: Adding additional text as StackOverflow says that post is mostly code and that I should add more details, even thought there is enough details provided :)

Body:
There is no function createtheme in material-ui/core/style
Instead use

import {createMuiTheme} from '@material-ui/core';
const theme = createMuiTheme({
palette: {
primary: {
  main: "HEXADECIMAL COLOR"
},
secondary: {
  main: "HEXADECIMAL COLOR"
}

}
});


问:
Dismiss dialog after screen orientation change
1) I launch a background task (via AsyncTask)

```<code>new FindJourneyTask().execute(); // FindJourneyTask extends AsyncTask
</code>```

2) Still in the main thread (just before new thread is launched) I create a dialog with showDialog(dialogId)

```<code>// this method is in FindJourneyTask
protected void onPreExecute() {
    showDialog(DIALOG_FINDING_JOURNEY);
}
</code>```

3) Screen orientation changes and the Activity is recreated

4) How can I now dismiss the dialog from the FindJourneyTask? Calling dismissDialog(dialogId) does nothing.

```<code>// this method is in FindJourneyTask
protected void onPostExecute(FindJourneyResult result) {
    dismissDialog(DIALOG_FINDING_JOURNEY); // does nothing
}
</code>```

答:
Just add this line to specific activity in your Manifest to solve this problem            android:configChanges="orientation|screenSize|smallestScreenSize"

like this,

```<code>        <activity
            android:name=".PDFTools"
            android:exported="false"
            android:configChanges="orientation|screenSize|smallestScreenSize"
            android:theme="@style/Theme.DocScanner.NoActionBar" />
</code>```

Body:
1) I launch a background task (via AsyncTask)

new FindJourneyTask().execute(); // FindJourneyTask extends AsyncTask

2) Still in the main thread (just before new thread is launched) I create a dialog with showDialog(dialogId)

// this method is in FindJourneyTask
protected void onPreExecute() {
    showDialog(DIALOG_FINDING_JOURNEY);
}

3) Screen orientation changes and the Activity is recreated

4) How can I now dismiss the dialog from the FindJourneyTask? Calling dismissDialog(dialogId) does nothing.

// this method is in FindJourneyTask
protected void onPostExecute(FindJourneyResult result) {
    dismissDialog(DIALOG_FINDING_JOURNEY); // does nothing
}

Body:
Just add this line to specific activity in your Manifest to solve this problem            android:configChanges="orientation|screenSize|smallestScreenSize"

like this,

        <activity
            android:name=".PDFTools"
            android:exported="false"
            android:configChanges="orientation|screenSize|smallestScreenSize"
            android:theme="@style/Theme.DocScanner.NoActionBar" />


问:
Grouping of API methods in documentation - is there some custom attribute
I have controller like

```<code>public class UserController : ApiController
{
  [Route("api/user")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  IHttpActionResult GetResumes() { ... }
}
</code>```

Which on swagger generates output like

Is there a way (besides overriding default implementation by rolling out your own ISwaggerProvider or merging two controllers into one) to enforce the group name ? Something like

```<code>public class UserController : ApiController
{
  [Route("api/user")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetResumes() { ... }
}
</code>```

答:
I know it is very late but leaving the answer thinking it would be useful.
You can use the ApiExplorerSettings, this is your magic attribute.
Something like this...

```<code>public class UserController : ApiController
{
  [Route("api/user")]
  [ApiExplorerSettings(GroupName="User")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  [ApiExplorerSettings(GroupName="User")]
  IHttpActionResult GetResumes() { ... }
}
</code>```

Body:
I have controller like

public class UserController : ApiController
{
  [Route("api/user")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  IHttpActionResult GetResumes() { ... }
}

Which on swagger generates output like

Is there a way (besides overriding default implementation by rolling out your own ISwaggerProvider or merging two controllers into one) to enforce the group name ? Something like

public class UserController : ApiController
{
  [Route("api/user")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  [MagicalAttributeName(Group="User")]
  IHttpActionResult GetResumes() { ... }
}

Body:
I know it is very late but leaving the answer thinking it would be useful.
You can use the ApiExplorerSettings, this is your magic attribute.
Something like this...

public class UserController : ApiController
{
  [Route("api/user")]
  [ApiExplorerSettings(GroupName="User")]
  IHttpActionResult GetUser() { ... }
}

public class ResumeController : ApiController
{
  [Route("api/user/resumes")]
  [ApiExplorerSettings(GroupName="User")]
  IHttpActionResult GetResumes() { ... }
}


问:
I got this error while installing npm on my my angular project folder
Installing packages (npm)...npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/@babel%2fplugin-proposal-nullish-coalescing-operator: Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\faizan\AppData\Local\npm-cache_logs\2021-12-07T00_42_46_255Z-debug-0.log
× Package install failed, see above.
The Schematic workflow failed. See above.

答:
This scenario sounds like you may have a slow internet connection.

I solved my this error like SS

in the following way:

Try increasing the timeout from 60s to 90s by adding this to your .npmrc file:

You need create .npmrc file if you do not have it

C:\Users{username}.npmrc (for Windows)

~/.npmrc (for Linux/Mac)

timeout=60000

And you could also try adding if you have a slow internet connection or want to save bandwidth

```<code>prefer-offline=true
</code>```

Or you can create/update one in the same directory as the project's package.json file as well.

Body:
This scenario sounds like you may have a slow internet connection.

I solved my this error like SS

in the following way:

Try increasing the timeout from 60s to 90s by adding this to your .npmrc file:

You need create .npmrc file if you do not have it

C:\Users{username}.npmrc (for Windows)

~/.npmrc (for Linux/Mac)

timeout=60000

And you could also try adding if you have a slow internet connection or want to save bandwidth

prefer-offline=true

Or you can create/update one in the same directory as the project's package.json file as well.


问:
How to send SMS from asp.net application

Possible Duplicate:

  sms from our site

I want to send SMS from my asp.net application. Suppose there will be 2 text boxes in my UI, one for mobile or cell phone number and another one is for message writing. When I will click the submit button then this SMS will be send to that cell number.
I want to use my cell phone number as transmission number.
Please inform me the possible ways.
I am using asp.net C#

答:
use "AT command"

http://www.codeproject.com/KB/IP/Sending_SMS_using_Net.aspx

  http://www.smssolutions.net/tutorials/gsm/sendsmsat/


问:
VIM: Open all folds around current line
I'm trying to write a vim function, which would fold everything except current line/block/method.

Here is what I already wrote:

```<code>set foldemethod=indent
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" FOCUS ON BLOCK OF CODE (fold everything else)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! FocusOnBock()
  :normal! zM                 " close all folds
  :normal! zozozozozozozozozo " I hope enough to open all nested folds :)
  :normal! zz                 " center the current line
endfunction
:command! FocusOnBock :call FocusOnBock()
:map <leader>F :FocusOnBock<CR>
</code>```

Here I close all folds, then open many folds (more then usually exists in good code), and then I center the current line. BTW, you can see it in action - http://ascii.io/a/1771

I don't like :norm! zozozozozozozozozo line. Is there a command to open all folds around current line without moving the cursor?

答:
If you want to open all folds recursively within the current line, zO works

from https://vim.fandom.com/wiki/Folding
The commands zc (close), zo (open), and za (toggle) operate on one level of folding, at the cursor. The commands zC, zO and zA are similar, but operate on all folding levels (for example, the cursor line may be in an open fold, which is inside another open fold; typing zC would close all folds at the cursor).

Title: VIM: Open all folds around current line

Body:
I'm trying to write a vim function, which would fold everything except current line/block/method.

Here is what I already wrote:

set foldemethod=indent
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" FOCUS ON BLOCK OF CODE (fold everything else)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! FocusOnBock()
  :normal! zM                 " close all folds
  :normal! zozozozozozozozozo " I hope enough to open all nested folds :)
  :normal! zz                 " center the current line
endfunction
:command! FocusOnBock :call FocusOnBock()
:map <leader>F :FocusOnBock<CR>

Here I close all folds, then open many folds (more then usually exists in good code), and then I center the current line. BTW, you can see it in action - http://ascii.io/a/1771

I don't like :norm! zozozozozozozozozo line. Is there a command to open all folds around current line without moving the cursor?