问:
Need a way for tests to run sequentially in TestNG using xmlSuites
I do not run my testcases through testng xml but use

```<code>TestListener listener=new TestListener();
    XmlSuite suite=new XmlSuite();
    suite.setName("Test Results");
    suite.setParallel(ParallelMode.NONE);
    suite.setThreadCount(Integer.parseInt(TestProperties.THREAD_COUNT.toString()));
    List<XmlSuite> suits=new ArrayList<XmlSuite>();
    suits.add(suite);

    List<XmlPackage> xpackage=new ArrayList<XmlPackage>();
    xpackage.add(new XmlPackage(TestProperties.TESTNG_PACKAGE.toString()));

    XmlTest test=new XmlTest(suite);
    test.setPackages(xpackage);
    //test.setParallel(ParallelMode.NONE);
    String groups=TestProperties.TESTNG_GROUP.toString();
    System.out.println("groups are:"+groups);
    String groupArray[]=groups.split(",");
    List<String> includedGroups=new ArrayList<String>();
    includedGroups.addAll(Arrays.asList(groupArray));
    test.setIncludedGroups(includedGroups);

    TestNG tng=new TestNG();
    tng.setOutputDirectory("test-output");
    tng.setXmlSuites(suits);
    //tng.addListener((ITestNGListener) listener);
    tng.run();
    System.exit(0)
</code>```

I need my tests to run sequentially because of a lot of factors. I tried giving parallelMode.none, preserve order etc, but my testcases are being run in a weird way usually numerical. For eg after 200, my testcase order in code would be 211,212,213 etc and after that 201,202 etc. I need it run in that order. But right now, after 200, the testcase run would be 201. How can i make the testcase run with the order in which they are specified.

I also tried giving priority to the testcases 211,212 etc, but that too didnt work. I added method inteceptor but my line number always give 1.

```<code>public class PriorityInterceptor implements IMethodInterceptor {

public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {

    Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() {
        private int getLineNo(IMethodInstance mi) {
        int result = 0;

        String methodName = mi.getMethod().getMethodName();
        String className  = mi.getMethod().getConstructorOrMethod().getDeclaringClass().getCanonicalName();
        ClassPool pool    = ClassPool.getDefault();

        try {
            CtClass cc        = pool.get(className);
            CtMethod ctMethod = cc.getDeclaredMethod(methodName);
            System.out.println(methodName);
            result            = ctMethod.getMethodInfo().getLineNumber(0);
            System.out.println("result:"+result+"and method:"+ctMethod);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        return result;
        }

        public int compare(IMethodInstance m1, IMethodInstance m2) {
            System.out.println(getLineNo(m1) - getLineNo(m2));
        return getLineNo(m1) - getLineNo(m2);
        }
    };

    IMethodInstance[] array = methods.toArray(new IMethodInstance[methods.size()]);
    Arrays.sort(array, comparator);
    System.out.println("22222222222222222222222222222222222222222222222222222222");
    System.out.println(Arrays.asList(array));
    return Arrays.asList(array);
    }
</code>```

答:
There is something called preserve-order = true in testng XML file. You could use that one to preserve the execution order.

For programmatic execution of testng: Setting preserve order at suite level

```<code>    XmlSuite xmlsuite = new XmlSuite();
    xmlsuite.setPreserveOrder(true);
</code>```

Setting preserve order at test level The test here means the test tag not the @Test annotation.

```<code>List<XmlTest> tests = xmlsuite.getTests();
        for (XmlTest test : tests) {
            test.setPreserveOrder(true);
            .....
}
</code>```

If you want some order in the execution of @Test, you could always use priority and dependsOnMethods along with your @Test annotation. If you use dependsOnMethods as specified in the below example, then the method2 will only start after the method1 has successfully run. If method1 failed due to some reason method2 will be marked as skipped.

Example:

```<code>@Test(priority=1)
public void method1(){}

@Test(priority=2)
public void method2(){}

@Test
public void method1(){}

@Test(dependsOnMethods="method1")
public void method2(){}
</code>```

For execution using testng XML file

```<code><suite name="Test_Suite_Name" verbose="1" preserve-order="true">
    <test name="TEST_TESTCLASSA" preserve-order="true">
        <classes>
            <class name="testpackage.TestClassA"/>
        </classes>
    </test>
    <test name="TEST_OTHER_TESTS" preserve-order="true">
        <classes>
            <class name="testpackage.TestClassB"/>
            <class name ="testpackage.TestClassC"/>
            <class name="testpackage.TestClassD"/>
            <class name="testpackage.TestClassE"/>
            <class name="testpackage.TestClassF"/>
            <class name="testpackage.TestClassG"/>
        </classes>
    </test>
</suite>
</code>```

An important note
If you use the preserve-order flag, execution will happen in the order as they appear in the List in case of programmatic execution and in the order as they appear in the testng xml file.

One suggestion
While using programmatic execution of testng, please do not hardcode classes in your code. You could always parse an existing testng XML file and tweak it as per your requirement during the runtime using programmatic testng then trigger the test execution.

Body:
I do not run my testcases through testng xml but use

TestListener listener=new TestListener();
    XmlSuite suite=new XmlSuite();
    suite.setName("Test Results");
    suite.setParallel(ParallelMode.NONE);
    suite.setThreadCount(Integer.parseInt(TestProperties.THREAD_COUNT.toString()));
    List<XmlSuite> suits=new ArrayList<XmlSuite>();
    suits.add(suite);

    List<XmlPackage> xpackage=new ArrayList<XmlPackage>();
    xpackage.add(new XmlPackage(TestProperties.TESTNG_PACKAGE.toString()));

    XmlTest test=new XmlTest(suite);
    test.setPackages(xpackage);
    //test.setParallel(ParallelMode.NONE);
    String groups=TestProperties.TESTNG_GROUP.toString();
    System.out.println("groups are:"+groups);
    String groupArray[]=groups.split(",");
    List<String> includedGroups=new ArrayList<String>();
    includedGroups.addAll(Arrays.asList(groupArray));
    test.setIncludedGroups(includedGroups);

    TestNG tng=new TestNG();
    tng.setOutputDirectory("test-output");
    tng.setXmlSuites(suits);
    //tng.addListener((ITestNGListener) listener);
    tng.run();
    System.exit(0)

I need my tests to run sequentially because of a lot of factors. I tried giving parallelMode.none, preserve order etc, but my testcases are being run in a weird way usually numerical. For eg after 200, my testcase order in code would be 211,212,213 etc and after that 201,202 etc. I need it run in that order. But right now, after 200, the testcase run would be 201. How can i make the testcase run with the order in which they are specified.

I also tried giving priority to the testcases 211,212 etc, but that too didnt work. I added method inteceptor but my line number always give 1.

public class PriorityInterceptor implements IMethodInterceptor {

public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {

    Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() {
        private int getLineNo(IMethodInstance mi) {
        int result = 0;

        String methodName = mi.getMethod().getMethodName();
        String className  = mi.getMethod().getConstructorOrMethod().getDeclaringClass().getCanonicalName();
        ClassPool pool    = ClassPool.getDefault();

        try {
            CtClass cc        = pool.get(className);
            CtMethod ctMethod = cc.getDeclaredMethod(methodName);
            System.out.println(methodName);
            result            = ctMethod.getMethodInfo().getLineNumber(0);
            System.out.println("result:"+result+"and method:"+ctMethod);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        return result;
        }

        public int compare(IMethodInstance m1, IMethodInstance m2) {
            System.out.println(getLineNo(m1) - getLineNo(m2));
        return getLineNo(m1) - getLineNo(m2);
        }
    };

    IMethodInstance[] array = methods.toArray(new IMethodInstance[methods.size()]);
    Arrays.sort(array, comparator);
    System.out.println("22222222222222222222222222222222222222222222222222222222");
    System.out.println(Arrays.asList(array));
    return Arrays.asList(array);
    }

Body:
There is something called preserve-order = true in testng XML file. You could use that one to preserve the execution order.

For programmatic execution of testng: Setting preserve order at suite level

    XmlSuite xmlsuite = new XmlSuite();
    xmlsuite.setPreserveOrder(true);

Setting preserve order at test level The test here means the test tag not the @Test annotation.

List<XmlTest> tests = xmlsuite.getTests();
        for (XmlTest test : tests) {
            test.setPreserveOrder(true);
            .....
}

If you want some order in the execution of @Test, you could always use priority and dependsOnMethods along with your @Test annotation. If you use dependsOnMethods as specified in the below example, then the method2 will only start after the method1 has successfully run. If method1 failed due to some reason method2 will be marked as skipped.

Example:

@Test(priority=1)
public void method1(){}

@Test(priority=2)
public void method2(){}

@Test
public void method1(){}

@Test(dependsOnMethods="method1")
public void method2(){}

For execution using testng XML file

<suite name="Test_Suite_Name" verbose="1" preserve-order="true">
    <test name="TEST_TESTCLASSA" preserve-order="true">
        <classes>
            <class name="testpackage.TestClassA"/>
        </classes>
    </test>
    <test name="TEST_OTHER_TESTS" preserve-order="true">
        <classes>
            <class name="testpackage.TestClassB"/>
            <class name ="testpackage.TestClassC"/>
            <class name="testpackage.TestClassD"/>
            <class name="testpackage.TestClassE"/>
            <class name="testpackage.TestClassF"/>
            <class name="testpackage.TestClassG"/>
        </classes>
    </test>
</suite>

An important note
If you use the preserve-order flag, execution will happen in the order as they appear in the List in case of programmatic execution and in the order as they appear in the testng xml file.

One suggestion
While using programmatic execution of testng, please do not hardcode classes in your code. You could always parse an existing testng XML file and tweak it as per your requirement during the runtime using programmatic testng then trigger the test execution.


来源: stackexchange

问:
What does ! after a parameter/variable name mean in Kotlin?
In Android Studio, I see the following auto-complete suggestion:

Why is Intent marked as Intent! (note the exclamation mark)? I guess that means non-nullable, but aren't Kotlin variables non-nullable by default so isn't this superfluous?

答:
! means it's maybe nullable and maybe not, but the Java code didn't specify nullability (with annotations). With such parameters, Kotlin will not force you to pass a non-nullable reference, and it's up to you to look at the documentation for the method to see if it's safe to pass null. If the documentation doesn't mention it, you should assume null values are not safe. In this particular case, it is not safe to pass a null Intent, though I don't know if it throws NullPointerException or ActivityNotFoundException because the documentation doesn't mention it.

If I had to guess, they chose not to add the nullability notation for the Intent argument to avoid breaking old code, since they didn't explicitly forbid it before they started adding nullability notations to the AOSP.

See here for the Kotlin documentation about this notation.

ContentLicense: CC BY-SA 4.0


问:
Using Winforms to connect to SQL Server to easily filter data
I have a Winforms that is connecting to a SQL Server 2008 database.

I would like to be able to easily filter through data in one table.

Here is an example of what I would like:

there are 3 columns in the table, and I will have three textboxes (or any other useful control) on a form that will correspond to those three columns.

the user will be able to input a value in any one of those fields and retrieve the rest of the values pertaining to that field.

Is there already an easy solution for this?

答:
I don't think there is a yet unique way of doing this. Anyways, you can simply use a SqlCommand it will allow you to execute a storedprocedure or a query as you like. The you pass the three filter values as SqlParameters.

Here is a little example:

```<code>private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT * FROM MyTable Where (FieldOne == @ParameterOne Or FieldTwo = @ParameterTwo Or FieldThree = @ParameterThree)";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        // Create the command
        SqlCommand command = new SqlCommand(
            queryString, connection);
        // Add the parameters

        command.Parameters.Add(new SqlParameter("ParameterOne", txtMyTextBox1.Text));
        command.Parameters.Add(new SqlParameter("ParameterTwo", txtMyTextBox2.Text));
        command.Parameters.Add(new SqlParameter("ParameterThree", txtMyTextBox3.Text));
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}
</code>```

Then you use the SqlDataReader to get the values.

ContentLicense: CC BY-SA 3.0

Body:
I don't think there is a yet unique way of doing this. Anyways, you can simply use a SqlCommand it will allow you to execute a storedprocedure or a query as you like. The you pass the three filter values as SqlParameters.

Here is a little example:

private static void ReadOrderData(string connectionString)
{
    string queryString =
        "SELECT * FROM MyTable Where (FieldOne == @ParameterOne Or FieldTwo = @ParameterTwo Or FieldThree = @ParameterThree)";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        // Create the command
        SqlCommand command = new SqlCommand(
            queryString, connection);
        // Add the parameters

        command.Parameters.Add(new SqlParameter("ParameterOne", txtMyTextBox1.Text));
        command.Parameters.Add(new SqlParameter("ParameterTwo", txtMyTextBox2.Text));
        command.Parameters.Add(new SqlParameter("ParameterThree", txtMyTextBox3.Text));
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Then you use the SqlDataReader to get the values.


问:
How to invoke the map functional from a javascript Array
Why is the map() not being invoked here?

let N = 16;
let fullSizeBufs = Array(2).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)```
</div>
</div>
</p>

<p>We get </p>

```[undefined, undefined]
```

I even put a breakpoint on the  Array(N).fill(-1) : it is not hit. The map() is just skipped.  What is the correct syntax for this?

答:
You could use a spread operator with the first array to make it iterable.

let N = 16;
let fullSizeBufs = [...Array(2)].map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)```

Body:
Why is the map() not being invoked here?

let N = 16;
let fullSizeBufs = Array(2).map((x) =>
  Array(N).fill(-1)
)
console.log(fullSizeBufs)

We get

[undefined, undefined]

I even put a breakpoint on the  Array(N).fill(-1) : it is not hit. The map() is just skipped.  What is the correct syntax for this?


问:
Use multiple @font-face rules in CSS
How can I use more than @font-face rule in my CSS?

I've inserted this into my stylesheet:

```<code>body {
    background: #fff url(../images/body-bg-corporate.gif) repeat-x;
    padding-bottom: 10px;
    font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}

@font-face {
    font-family: 'GestaReFogular';
    src: url('gestareg-webfont.eot');
    src: local('☺'),
         url('gestareg-webfont.woff') format('woff'),
         url('gestareg-webfont.ttf') format('truetype'),
         url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}
</code>```

This currently only applies for the whole body of text on the site. But, I would like to specify h1 to use a different font. How can I do this?

答:
Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

```<code>/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}
</code>```

Declared rules can be used by following

```<code>/* Regular */
font-family: Montserrat;

/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;
</code>```

Title: Use multiple @font-face rules in CSS

Body:
How can I use more than @font-face rule in my CSS?

I've inserted this into my stylesheet:

body {
    background: #fff url(../images/body-bg-corporate.gif) repeat-x;
    padding-bottom: 10px;
    font-family: 'GestaRegular', Arial, Helvetica, sans-serif;
}

@font-face {
    font-family: 'GestaReFogular';
    src: url('gestareg-webfont.eot');
    src: local('☺'),
         url('gestareg-webfont.woff') format('woff'),
         url('gestareg-webfont.ttf') format('truetype'),
         url('gestareg-webfont.svg#webfontg8dbVmxj') format('svg');
}

This currently only applies for the whole body of text on the site. But, I would like to specify h1 to use a different font. How can I do this?

Body:
Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;

/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;


问:
"Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
I have my User struct declared like this. How can we decode an array using JSONdecoder?

I get an error of typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

```<code>This is my json data:

// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc

[
  {
    "id": "5eca2fa01583786f1c0ee1bc",
    "fullName": "Raj Shrestha",
    "emailAddress": "raj@yahoo.com",
    "following": [

    ],
    "followers": [
      {
        "id": "5eca2f451583786f1c0ee1ba",
        "fullName": "Udin Rajkarnikar",
        "emailAddress": "udin@gmail.com"
      }
    ],
    "isFollowing": true
  },
  [
    {
      "createdAt": 1590581837003,
      "updatedAt": 1590581837003,
      "id": "5ece5a4d6e2e801e95365d50",
      "text": "I love waterfalls",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590334928984,
      "updatedAt": 1590334928984,
      "id": "5eca95d08538288438c63779",
      "text": "Creating post from iphone",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590308888243,
      "updatedAt": 1590308888243,
      "id": "5eca30181583786f1c0ee1bf",
      "text": "asdasd",
      "imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    }
  ]
]

struct User: Decodable {
    let id : String
    let fullName: String
    let emailAddress: String
    var isFollowing: Bool?
    var followers, following: [User]?
    var post: [Post]?
}

struct Post: Decodable {
    let id: String
    let createdAt: Int
    let text: String
    let user: User
    let imageUrl: String
}

let user = try JSONDecoder().decode([User].self, from: data)

print(user)

</code>```

答:
Need to see the JSON, but an obvious mistake here could be that your json is an array of users, in which case you would want the following:</p>

```<code>let users = try JSONDecoder().decode([User].self, from: data)
</code>```

Body:
I have my User struct declared like this. How can we decode an array using JSONdecoder?

I get an error of typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

This is my json data:

// http://localhost:1337/user/5eca2fa01583786f1c0ee1bc

[
  {
    "id": "5eca2fa01583786f1c0ee1bc",
    "fullName": "Raj Shrestha",
    "emailAddress": "raj@yahoo.com",
    "following": [

    ],
    "followers": [
      {
        "id": "5eca2f451583786f1c0ee1ba",
        "fullName": "Udin Rajkarnikar",
        "emailAddress": "udin@gmail.com"
      }
    ],
    "isFollowing": true
  },
  [
    {
      "createdAt": 1590581837003,
      "updatedAt": 1590581837003,
      "id": "5ece5a4d6e2e801e95365d50",
      "text": "I love waterfalls",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/a121f7-6854-4fe9-bc8e-defce029d",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590334928984,
      "updatedAt": 1590334928984,
      "id": "5eca95d08538288438c63779",
      "text": "Creating post from iphone",
      "imageUrl": "https://nepgram-bucket.s3.amazonaws.com/2badfb0e-de49-4b6c-ae1-0c6",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    },
    {
      "createdAt": 1590308888243,
      "updatedAt": 1590308888243,
      "id": "5eca30181583786f1c0ee1bf",
      "text": "asdasd",
      "imageUrl": "https://nepgram-bucket.s3.ap-south-1.amazonaws.com/83b7e688b-4d37-a368-3b8b4526bd58.png",
      "user": {
        "id": "5eca2fa01583786f1c0ee1bc",
        "fullName": "Raj Shrestha",
        "emailAddress": "raj@yahoo.com"
      }
    }
  ]
]

struct User: Decodable {
    let id : String
    let fullName: String
    let emailAddress: String
    var isFollowing: Bool?
    var followers, following: [User]?
    var post: [Post]?
}

struct Post: Decodable {
    let id: String
    let createdAt: Int
    let text: String
    let user: User
    let imageUrl: String
}

let user = try JSONDecoder().decode([User].self, from: data)

print(user)

Body:
Need to see the JSON, but an obvious mistake here could be that your json is an array of users, in which case you would want the following:

let users = try JSONDecoder().decode([User].self, from: data)


问:
Generate SAS token using Key Vault in Java
Is there any way we can generate SAS token (to access the file storage) using Key Vault?</p>

答: Key Vault is not used to generate a SAS token. SAS generation is a well-doc'd algorithm that uses one crypto primitive - an HMAC, but that's nothing to do with KV. The Storage Account SAS alg is available here https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas</p>


问:
Worker pool implementation to limit http requests per second
I am new to Go lang and am trying to implement restrained GCP API calls. i.e. to limit the number of API calls per second my app makes, so Google won't block me.

I've been following the worker pool pattern exemplified here.

A design in a fashion similar to the linked example would be:

make two channels (jobs, results) of capacity the same as the total number of API calls to make

create a worker pool of a certain size (say 10 workers)

each worker goes through the jobs channel while making API calls, and storing responses into the results channel, with 1 second waiting period

My questions are:

am I understanding things correctly, that 10 workers each having a 1 second waiting period means my app makes approximately 10 API calls per second?

how do the 10 workers communicate with each other so they don't step on each other's toes, i.e. two workers don't query the same GCS path.

And of course the ultimate question: is it an overkill using worker pools?

Thank you!

答:
Maybe you can implement a Throttler using Sync.Mutex and time.After something like below</p>

```<code>package main

import (
    "fmt"
    "os"
    "os/signal"
    "sync"
    "syscall"
    "time"
)

type Throttler struct {
    invocations int
    duration time.Duration
    m sync.Mutex
    max int
}

func (t *Throttler) Throttle() {
    t.m.Lock()
    defer t.m.Unlock()
    t.invocations += 1
    if t.invocations >= t.max {
        <-time.After(t.duration) // This block until the time period expires
        t.invocations = 0
    }
}

func main() {
    t := &Throttler{
        max: 2,
        duration: time.Second,
    }
    // Launch your workers passing in the throttler created above.
    for i := 0; i < 10; i++ {
        fmt.Println("starting worker")
        go Worker(t);
    }

    // This just to prevent the main from exiting.
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    <-c // This will block until you manually exists with CRl-C
}

// worker
func Worker(t *Throttler)  {
    t.Throttle()
    fmt.Println("Work done!!")
}
</code>```

Body:
Maybe you can implement a Throttler using Sync.Mutex and time.After something like below

package main

import (
    "fmt"
    "os"
    "os/signal"
    "sync"
    "syscall"
    "time"
)

type Throttler struct {
    invocations int
    duration time.Duration
    m sync.Mutex
    max int
}

func (t *Throttler) Throttle() {
    t.m.Lock()
    defer t.m.Unlock()
    t.invocations += 1
    if t.invocations >= t.max {
        <-time.After(t.duration) // This block until the time period expires
        t.invocations = 0
    }
}

func main() {
    t := &Throttler{
        max: 2,
        duration: time.Second,
    }
    // Launch your workers passing in the throttler created above.
    for i := 0; i < 10; i++ {
        fmt.Println("starting worker")
        go Worker(t);
    }

    // This just to prevent the main from exiting.
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    <-c // This will block until you manually exists with CRl-C
}

// worker
func Worker(t *Throttler)  {
    t.Throttle()
    fmt.Println("Work done!!")
}


问:
How can I start mysql by command service mysql start
I can start mysql by following command

```<code>/etc/init.d/mysql.server start
</code>```

But I want to start it by command "service mysql start"

Server is debian 10.

Mariadb, which was originally installed, was uninstalled and mysql 5.5 was reinstalled.

答: Using sysvinit, the service name should be the name of the file inside /etc/init.d. In your case, the file name is mysql.server, so "sudo service mysql.server start{stop, status, restart}" should be the command used. If it isn't referenced anywhere else, you could even rename the file from "mysql.server" to "mysql" and just run "sudo service mysql start".</p>

Body:
I can start mysql by following command

/etc/init.d/mysql.server start

But I want to start it by command "service mysql start"

Server is debian 10.

Mariadb, which was originally installed, was uninstalled and mysql 5.5 was reinstalled.


问:
Right way to update state with react socket hooks
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

```<code>  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }
</code>```

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

```<code>Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

        <div>
          <p> Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId} </p>
          <p>{JSON.stringify(gameState)}</p>
        </div>

      );
    } else {
      return (
        <div>
          <p> Game state is not created </p>
        </div>
      )
    }
  }
</code>```

答:
```<code> export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE);

    function socketConnection(){
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }
    useEffect(() => {
      socketConnection();
    }, []);

    return {gameState, isConnected, socketId}
  }
</code>```

When you connect to the socket, you don't need to use useEffect() anymore.

Body:
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

 Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId}

{JSON.stringify(gameState)}

      );
    } else {
      return (

 Game state is not created

      )
    }
  }

Body:
 export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE);

    function socketConnection(){
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }
    useEffect(() => {
      socketConnection();
    }, []);

    return {gameState, isConnected, socketId}
  }

When you connect to the socket, you don't need to use useEffect() anymore.


问:
how can i modify spring.redis.host config and neednot restart springboot project?
My old config like

```<code>spring.redis.host=192.168.1.1
</code>```

Now I want to modify

```<code>spring.redis.host=192.168.1.2
</code>```

But need not restart My project, How can I do that?

答:
ok, I found the answer:</p>

```<code>        RedisTemplate template = (RedisTemplate) applicationContext.getBean("redisTemplate");
        JedisConnectionFactory redisConnectionFactory = (JedisConnectionFactory) template.getConnectionFactory();
        //关闭连接池
        redisConnectionFactory.destroy();
        redisConnectionFactory.setShardInfo(null);
        redisConnectionFactory.setHostName(host);
        redisConnectionFactory.setPort(port);
        redisConnectionFactory.setPassword(password);
        redisConnectionFactory.setDatabase(database);
        //重新创建连接池
        redisConnectionFactory.afterPropertiesSet();
        template.setConnectionFactory(redisConnectionFactory);
</code>```

Body:
My old config like

spring.redis.host=192.168.1.1

Now I want to modify

spring.redis.host=192.168.1.2

But need not restart My project, How can I do that?

Body:
ok, I found the answer:

        RedisTemplate template = (RedisTemplate) applicationContext.getBean("redisTemplate");
        JedisConnectionFactory redisConnectionFactory = (JedisConnectionFactory) template.getConnectionFactory();
        //关闭连接池
        redisConnectionFactory.destroy();
        redisConnectionFactory.setShardInfo(null);
        redisConnectionFactory.setHostName(host);
        redisConnectionFactory.setPort(port);
        redisConnectionFactory.setPassword(password);
        redisConnectionFactory.setDatabase(database);
        //重新创建连接池
        redisConnectionFactory.afterPropertiesSet();
        template.setConnectionFactory(redisConnectionFactory);


问:
Play one video at a time on html page
I have a html page.
I have used a video tag for playing video online
I have used two video tags,
But when I play both videos, then
both videos play at same time

I want a solution that, if I play one video and then click on the second one then the first one should be paused and the second one starts playing.
Any help would be appreciated.

答:
 // AUTO STOP WHEN CURRENT VIDEO IS PLAYING..

//JAVASCRIPT

    document.addEventListener('play', function(e){
      var videos = document.getElementsByTagName('video');
      for(var i = 0, len = videos.length; i < len;i++){
          if(videos[i] != e.target){
              videos[i].pause();
          }
      }
    }, true);

  ///REACT

 // componentDidMount() {
  //  document.addEventListener('play', function(e){
    //  var videos = document.getElementsByTagName('video');
   //   for(var i = 0, len = videos.length; i < len;i++){
     //     if(videos[i] != e.target){
      //        videos[i].pause();
      //    }
   //   }
  //  }, true);

 // }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video height="169" width="300" preload="none" controls="controls">
  <source type="video/webm"   src="https://www.w3schools.com/html/mov_bbb.mp4"></source>
</video>

<video height="169" width="300" preload="none" controls="controls">
  <source type="video/webm"   src="https://archive.org/download/ElephantsDream/ed_hd.mp4"></source>
</video></code>```

Title: Play one video at a time on html page

Body:
 // AUTO STOP WHEN CURRENT VIDEO IS PLAYING..

//JAVASCRIPT

    document.addEventListener('play', function(e){
      var videos = document.getElementsByTagName('video');
      for(var i = 0, len = videos.length; i < len;i++){
          if(videos[i] != e.target){
              videos[i].pause();
          }
      }
    }, true);

  ///REACT

 // componentDidMount() {
  //  document.addEventListener('play', function(e){
    //  var videos = document.getElementsByTagName('video');
   //   for(var i = 0, len = videos.length; i < len;i++){
     //     if(videos[i] != e.target){
      //        videos[i].pause();
      //    }
   //   }
  //  }, true);

 // }

<video height="169" width="300" preload="none" controls="controls">
  <source type="video/webm"   src="https://www.w3schools.com/html/mov_bbb.mp4"></source>
</video>

<video height="169" width="300" preload="none" controls="controls">
  <source type="video/webm"   src="https://archive.org/download/ElephantsDream/ed_hd.mp4"></source>
</video>


问:
Unable to transform `google_dns_record_set` from count to for_each
Attempting to upgrade my module to Tf0.12
After running the terraform 0.12upgrade, now failing to convert count to for_each

Original Module with count

```<code>resource "google_dns_record_set" "default" {
  count        = length(var.account_fqdns)
  name         = "${element(var.account_fqdns, count.index)}."
  type         = "A"
  ttl          = 300
  managed_zone = var.dns_managed_zone
  project      = var.dns_project
  rrdatas      = [element(google_compute_address.default2.*.address, count.index)]

}
</code>```

My New module

```<code>resource "google_dns_record_set" "default" {
  for_each     = {for fqdn in var.account_fqdns: fqdn => fqdn}
  name         = each.key
  type         = "A"
  ttl          = 300
  managed_zone = var.dns_managed_zone
  project      = var.dns_project
  rrdatas      = [google_compute_address.default2.*.address]
}
</code>```

I keep running into the error below when I run plan

```<code>Error: Incorrect attribute value type

  on main.tf line 285, in resource "google_dns_record_set" "default":
 285:   rrdatas      = [google_compute_address.default2.*.address]
    |----------------
    | google_compute_address.default2 is object with 3 attributes

Inappropriate value for attribute "rrdatas": element 0: string required.

Error: Unsupported attribute

  on main.tf line 285, in resource "google_dns_record_set" "default":
 285:   rrdatas      = [google_compute_address.default2.*.address]

This object does not have an attribute named "address".
</code>```

答:
I was able to solve my problem by doing this below</p>

```<code>rrdatas      = [for ip in google_compute_address.default2: ip.address]
</code>```

Body:
Attempting to upgrade my module to Tf0.12
After running the terraform 0.12upgrade, now failing to convert count to for_each

Original Module with count

resource "google_dns_record_set" "default" {
  count        = length(var.account_fqdns)
  name         = "${element(var.account_fqdns, count.index)}."
  type         = "A"
  ttl          = 300
  managed_zone = var.dns_managed_zone
  project      = var.dns_project
  rrdatas      = [element(google_compute_address.default2.*.address, count.index)]

}

My New module

resource "google_dns_record_set" "default" {
  for_each     = {for fqdn in var.account_fqdns: fqdn => fqdn}
  name         = each.key
  type         = "A"
  ttl          = 300
  managed_zone = var.dns_managed_zone
  project      = var.dns_project
  rrdatas      = [google_compute_address.default2.*.address]
}

I keep running into the error below when I run plan

Error: Incorrect attribute value type

  on main.tf line 285, in resource "google_dns_record_set" "default":
 285:   rrdatas      = [google_compute_address.default2.*.address]
    |----------------
    | google_compute_address.default2 is object with 3 attributes

Inappropriate value for attribute "rrdatas": element 0: string required.

Error: Unsupported attribute

  on main.tf line 285, in resource "google_dns_record_set" "default":
 285:   rrdatas      = [google_compute_address.default2.*.address]

This object does not have an attribute named "address".

Body:
I was able to solve my problem by doing this below

rrdatas      = [for ip in google_compute_address.default2: ip.address]


问:
Low FPS in Voxel land generation with OpenGL & LibGDX
I'm having some performance issues related to my implementation of voxel land generation.

I've separated the cubes into chunks of 16x16, and am building these chunks as 1 individual model instance to render. The only faces created for each chunk are the ones exposed to air (meaning no neighboring block on that side).

For some reason I'm only getting about 26-32 FPS when looking at all 36 chunks rendered. If I only render 4 chunks, I get over 300 FPS. I'm trying to figure out what optimization I'm missing in order to get a reasonable FPS considering not much is being rendered.

This is my render code for the world.

```<code>public void render(ModelBatch modelBatch, Player player) {
    modelBatch.begin(player.getCamera());
    for (Chunk chunk : chunks) {
        if (chunk.canSee(player.getCamera())) {
            chunk.render(modelBatch);
        }
    }
    modelBatch.end();
}
</code>```

As for my chunk render function...

```<code>public void render(ModelBatch modelBatch) {
    modelBatch.render(chunkModelInstance);
}
</code>```

I'm using a ModelBuilder and appending all the needed faces for each block. Then using that to build a Model and instantiating a ModelInstance for rendering. This is being done during world.create() and not while rendering.

```<code>private void appendBlock(ModelBuilder modelBuilder, Block block) {
    Vector3 chunkLocation = block.getChunkLocation();

    Block topBlock = block.getAdjacentBlock(BlockFace.TOP);
    Block bottomBlock = block.getAdjacentBlock(BlockFace.BOTTOM);
    Block backBlock = block.getAdjacentBlock(BlockFace.BACK);
    Block frontBlock = block.getAdjacentBlock(BlockFace.FRONT);
    Block leftBlock = block.getAdjacentBlock(BlockFace.LEFT);
    Block rightBlock = block.getAdjacentBlock(BlockFace.RIGHT);

    if (frontBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getFront());
        modelBuilder.part("front", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        0,0,-1);
    }
    if (backBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getBack());
        modelBuilder.part("back", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        0,0,1);
    }
    if (bottomBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getBottom());
        modelBuilder.part("bottom", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        0,-1,0);
    }
    if (topBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getTop());
        modelBuilder.part("top", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x -0.5f,chunkLocation.y + 0.5f,chunkLocation.z -0.5f,
                        chunkLocation.x -0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z -0.5f,
                        0,1,0);
    }
    if (leftBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getLeft());
        modelBuilder.part("left", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        -1,0,0);
    }
    if (rightBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getRight());
        modelBuilder.part("right", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        1,0,0);
    }
}
</code>```

Any help would be greatly appreciated.

答:
You are creating a MeshPart instance per every block face. Each of them potentially has different material bound to it. That results in one render call + texture bind per every single block face.

Proper voxel renderer would aim to have one render call per whole chunk or chunklet per render pass. You are potentially doing several thousands of render calls per chunk.

Do not create multiple Mesh/MeshPart instances per chunk. Keep just single one and append face vertices to it instead.

You should also ditch Model/Mesh Builder, it's not optimized for your use case.

Take a look at LibGDX voxel demo:
https://github.com/libgdx/libgdx/tree/master/tests/gdx-tests/src/com/badlogic/gdx/tests/g3d/voxel

You should take this approach. It doesn't have textures though, but if you want to add textures: create a texture atlas with all your block textures and then refer to their (texture regions) uv coordinates in vertex data.

Alternative to texture atlas is a technique called bindless, where you bind all textures at once to multiple units and refer to those (their unit) from vertex data.

Body:
I'm having some performance issues related to my implementation of voxel land generation.

I've separated the cubes into chunks of 16x16, and am building these chunks as 1 individual model instance to render. The only faces created for each chunk are the ones exposed to air (meaning no neighboring block on that side).

For some reason I'm only getting about 26-32 FPS when looking at all 36 chunks rendered. If I only render 4 chunks, I get over 300 FPS. I'm trying to figure out what optimization I'm missing in order to get a reasonable FPS considering not much is being rendered.

This is my render code for the world.

public void render(ModelBatch modelBatch, Player player) {
    modelBatch.begin(player.getCamera());
    for (Chunk chunk : chunks) {
        if (chunk.canSee(player.getCamera())) {
            chunk.render(modelBatch);
        }
    }
    modelBatch.end();
}

As for my chunk render function...

public void render(ModelBatch modelBatch) {
    modelBatch.render(chunkModelInstance);
}

I'm using a ModelBuilder and appending all the needed faces for each block. Then using that to build a Model and instantiating a ModelInstance for rendering. This is being done during world.create() and not while rendering.

private void appendBlock(ModelBuilder modelBuilder, Block block) {
    Vector3 chunkLocation = block.getChunkLocation();

    Block topBlock = block.getAdjacentBlock(BlockFace.TOP);
    Block bottomBlock = block.getAdjacentBlock(BlockFace.BOTTOM);
    Block backBlock = block.getAdjacentBlock(BlockFace.BACK);
    Block frontBlock = block.getAdjacentBlock(BlockFace.FRONT);
    Block leftBlock = block.getAdjacentBlock(BlockFace.LEFT);
    Block rightBlock = block.getAdjacentBlock(BlockFace.RIGHT);

    if (frontBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getFront());
        modelBuilder.part("front", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        0,0,-1);
    }
    if (backBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getBack());
        modelBuilder.part("back", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        0,0,1);
    }
    if (bottomBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getBottom());
        modelBuilder.part("bottom", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        0,-1,0);
    }
    if (topBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getTop());
        modelBuilder.part("top", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x -0.5f,chunkLocation.y + 0.5f,chunkLocation.z -0.5f,
                        chunkLocation.x -0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z -0.5f,
                        0,1,0);
    }
    if (leftBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getLeft());
        modelBuilder.part("left", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x - 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        -1,0,0);
    }
    if (rightBlock == null) {
        Material material = AssetWrapper.getInstance().getMaterial(block.getBlockMaterial().getRight());
        modelBuilder.part("right", GL20.GL_TRIANGLES, RENDER_ATTRIBUTES, material)
                .rect(chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z + 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y - 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z - 0.5f,
                        chunkLocation.x + 0.5f,chunkLocation.y + 0.5f,chunkLocation.z + 0.5f,
                        1,0,0);
    }
}

Any help would be greatly appreciated.


问:
How to schedule a task to run only at a specific time?

I'm using Windows 10 Task Scheduler to run my python script daily and it runs fine. But I want that script to run only on weekdays Start time: 8.15 AM and End time: 4.15 PM. So here I have configured https://imgur.com/GYuQNdl
But it runs for every 8hrs, i.e, 8.15, 4.15, 12.15 but I want to run it only once a day at a specific time Start time: 8.15 AM and End time: 4.15 PM. So how can I achieve that?

One more thing, If I achieve a solution for the 1st ques next thing is, I don't want to run the script on public holidays or when I'm on leave. So I think that I should sync it with my calendar. First of all, I wanna know is it possible to run the script in that way is there any option for that?

答:
You should not schedule the task to run every 8 hours if you want it to run only once a day. You should only care about the start time but not the end time.

Depends on you want to read your outlook using COM or you want to tap into Exchange server to read your calendar, you can try this to check your calendar in your script.


问:
Is there are a way to display text from UNSELECTED radio buttons?
I am working in android, I am wondering if there is a way to append a TextView with texts from the radio buttons that were not selected. As a list that would look like "Not selected: Item A, Item b" etc.

I wanted to try something like this:

```<code> if (radioButtonId == 1) {
        notSelected.append(optionsContainer.getCheckedRadioButtonId(3).getText().toString());
</code>```

But I am presented with an error that reads

```<code>getCheckedRadioButtonId() in RadioGroup cannot be applied to int()
</code>```

Any help or advice would be greatly appreciated. I'm not even sure this is something that can be done

答:
RadioButtons can be selected once at time, so you can't "decide" which index you want check.

```<code>getCheckedRadioButtonId()
</code>```

return the view id that is actually selected.

Docs:

https://developer.android.com/reference/android/widget/RadioGroup#getCheckedRadioButtonId()

Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.

As i say on comments consider read https://stackoverflow.com/a/50955546/4628993

Body:
I am working in android, I am wondering if there is a way to append a TextView with texts from the radio buttons that were not selected. As a list that would look like "Not selected: Item A, Item b" etc.

I wanted to try something like this:

 if (radioButtonId == 1) {
        notSelected.append(optionsContainer.getCheckedRadioButtonId(3).getText().toString());

But I am presented with an error that reads

getCheckedRadioButtonId() in RadioGroup cannot be applied to int()

Any help or advice would be greatly appreciated. I'm not even sure this is something that can be done

Body:
RadioButtons can be selected once at time, so you can't "decide" which index you want check.

getCheckedRadioButtonId()

return the view id that is actually selected.

Docs:

https://developer.android.com/reference/android/widget/RadioGroup#getCheckedRadioButtonId()

Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.

As i say on comments consider read https://stackoverflow.com/a/50955546/4628993


问:
C# converting collections to lists and into 1d dapper ORM
looking for some advice and explanations.

Im using Micro-ORM Dapper to take a table out of SQLite and do stuff with it.

Bind:

```<code>public static List<Airport> LoadAirports()
    {
        using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
            return output.ToList();
        }
    }
</code>```

Class:

```<code>class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationName { get; set; }
    public string IATA { get; set; }
    public string PortType { get; set; }
    public string PortOwner { get; set; }
    public string MotherPort { get; set; }
    public bool Active { get; set; }
    public bool IsApplyMeetAndGreet { get; set; }
    public decimal MeetAndGreet { get; set; }
}
</code>```

Main:

```<code>private void LoadAirportsList()
    {
        Airports = SqliteDataAccess.LoadAirports();
    }
</code>```

This creates a variable "Airports" which i believe is a collection of arrays. My problem is that i can never seem to extract any specific information from them.

For example i want to acquire the name of every airport in the list I only seem to be able to return the entire collection, ive been reading into multidimensional arrays and flattening 2d arrays but i always get errors about types where functions cant be iterated over them.

I would try

```<code>for (int i = 0; i < Airports.Count; i++)
        {
            Assigner = Airports[i];
        }
</code>```

With the intention of then iterating through all the airports to then assign each .Name to a list variable. Sigh as of yet no avail. Grateful for any assistance anyone can provide.

答:
So after some direction from @Chetan Ranpariya, Eventually figured it out.

```<code>var PortNames = Airports.Select(airport => airport.Name);
</code>```

Solved the initial acquisition of the specific element within the object list.

Initially i thought you could iterate over the PortNames variable at this stage but its still considered a method and you cannot operate over methods.

So: List<string> PortNameList = PortNames.ToList();

Even though the collection is output as a list its a list of objects so once you've parsed the element you then to make THAT a list of strings. Which you can then operate over using for (int i = 0; i < PortNameList.Count; i++) doing whatever you need with those individual string values, in my instance i used the loop to add them to a comboBox.

If im mistaken about any of this please let me know.

Body:
looking for some advice and explanations.

Im using Micro-ORM Dapper to take a table out of SQLite and do stuff with it.

Bind:

public static List<Airport> LoadAirports()
    {
        using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
        {
            var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
            return output.ToList();
        }
    }

Class:

class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationName { get; set; }
    public string IATA { get; set; }
    public string PortType { get; set; }
    public string PortOwner { get; set; }
    public string MotherPort { get; set; }
    public bool Active { get; set; }
    public bool IsApplyMeetAndGreet { get; set; }
    public decimal MeetAndGreet { get; set; }
}

Main:

private void LoadAirportsList()
    {
        Airports = SqliteDataAccess.LoadAirports();
    }

This creates a variable "Airports" which i believe is a collection of arrays. My problem is that i can never seem to extract any specific information from them.

For example i want to acquire the name of every airport in the list I only seem to be able to return the entire collection, ive been reading into multidimensional arrays and flattening 2d arrays but i always get errors about types where functions cant be iterated over them.

I would try

for (int i = 0; i < Airports.Count; i++)
        {
            Assigner = Airports[i];
        }

With the intention of then iterating through all the airports to then assign each .Name to a list variable. Sigh as of yet no avail. Grateful for any assistance anyone can provide.

Body:
So after some direction from @Chetan Ranpariya, Eventually figured it out.

var PortNames = Airports.Select(airport => airport.Name);

Solved the initial acquisition of the specific element within the object list.

Initially i thought you could iterate over the PortNames variable at this stage but its still considered a method and you cannot operate over methods.

So: List<string> PortNameList = PortNames.ToList();

Even though the collection is output as a list its a list of objects so once you've parsed the element you then to make THAT a list of strings. Which you can then operate over using for (int i = 0; i < PortNameList.Count; i++) doing whatever you need with those individual string values, in my instance i used the loop to add them to a comboBox.

If im mistaken about any of this please let me know.


问:
Java applet: run native code from browser?
Is it still possible to start a 'native' application under windows via a java applet in a browser? IE "Click here to start notepad.exe" on a web page. The most recent reference I could find for this was dated 2002. Im wondering if this model / concept is no longer supported. </p>

答:
Yes, but the applet has to be signed.

Signed applets will prompt the user to give them permission.  Once given, the applet has the same rights as any application running on the machine, including the ability to launch native apps (or link native libraries, which I've had to do in the past).


问:
Conversion of wkt to wkb in postgresql
I have a column named wkt_geometry in a table in Postgres with data converted from latitude and longitude. But I want to convert the wkt_geometry to wkb_geometry using sql commands.
If I convert it directly from Lat and long it would even better.
Also I have seen the ST_AsBinary(geometry) but I dont understand the parameters involved.</p>

答:
WKT and WKT are two formats that represent Geometry (or Geography) type.

To convert between various formats, you need to construct Geometry type and then export it to desired format. In this case ST_AsBinary(ST_GeomFromText(wkt_text)) should generally work.

If you want to produce WKB directly from lat/lng - something like ST_AsBinary(ST_MakePoint(lng, lat)) should work too. Pay attention to argument order, SQL functions use lng / lat order.

Title: Conversion of wkt to wkb in postgresql


问:
Test Time Augmentation throwing a value error
I am trying to use the Test Time Augmentation on my Classifier:

```<code>log_preds,y = learn.TTA(scale=1.1, ds_type=DatasetType.Valid, with_loss=True)
</code>```

And this is the error that it threw:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-f33d9737819a> in <module>()
----> 1 log_preds,y = learn.TTA(scale=1.1, ds_type=DatasetType.Valid, with_loss=True)
      2 probs = np.mean(np.exp(log_preds),0)
      3
      4 accuracy(probs, y)

ValueError: too many values to unpack (expected 2)
</code>```

Initially, I tried to find a way to use my custom test set in TTA but couldn’t figure out how to do it and DatasetType.Test was throwing an error so I decided to go with DatasetType.Valid and after running 8 epochs, I got the above error.

答:
The error message indicate that learn.TTA returns more than 2 values,but you only got log_predsand y for them.
You want to find out what exactly does learn.TTA return

Body:
I am trying to use the Test Time Augmentation on my Classifier:

log_preds,y = learn.TTA(scale=1.1, ds_type=DatasetType.Valid, with_loss=True)

And this is the error that it threw:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-f33d9737819a> in <module>()
----> 1 log_preds,y = learn.TTA(scale=1.1, ds_type=DatasetType.Valid, with_loss=True)
      2 probs = np.mean(np.exp(log_preds),0)
      3
      4 accuracy(probs, y)

ValueError: too many values to unpack (expected 2)

Initially, I tried to find a way to use my custom test set in TTA but couldn’t figure out how to do it and DatasetType.Test was throwing an error so I decided to go with DatasetType.Valid and after running 8 epochs, I got the above error.


问:
How to fix Unexpected token error, expected “}”
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help

Code is below

```<code>import React from 'react';
import react, { Component } from 'react'
import { Plateform, StyleSheet, View,Text } from 'react-native';

function Header() {
  return (
    <div>
    <this.View style={style}/>
    <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>
      <header className="header">
        <div className="col1">
        </div>
        <div className="col2">
        <div className="menu">
        <h3>About</h3>
        <h3>Cars</h3>
        <h3>Contact</h3>
        <h3>Search</h3>
        <header/>
        <View/>
      </div>
      </div>

**Here is where the error seems to be happing**

  );
}
export default Header;

App = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  setFontSize: {
    fontSize: 20,
    fontWeight : 'bold'
  },
  setColorRed : {
    color: '#f44336'
  }
});
</code>```

Error is below as well

Line 37:12:  Parsing error: Unexpected token, expected "}"

35 |    36 | App = StyleSheet.create({

37 |   container: {
         |            ^   38 |     flex: 1,   39 |     justifyContent: 'center',   40 |     alignItems: 'center'

答:
You need to enclose header HTML element and then wrap the component with

```<code>function Header() {
  return (
    <div>
      <this.View style={style} />
      <Text style={[styles.setFontSize.setColorRed]}>
        Welcome to the dealership!
      </Text>
      <header className="header">
        <div className="col1"></div>
        <div className="col2">
          <div className="menu">
            <h3>About</h3>
            <h3>Cars</h3>
            <h3>Contact</h3>
            <h3>Search</h3>
            <header />
            <View />
          </div>
        </div>
      </header>
    </div>
  )
}
</code>```

There are some really useful editor extensions can add and rename close tag for you, like Auto Close Tag and Auto Rename Tag.

Body:
I keep on getting an error saying unexpected token but have no idea where that unexpected token is at? Please help

Code is below

import React from 'react';
import react, { Component } from 'react'
import { Plateform, StyleSheet, View,Text } from 'react-native';

function Header() {
  return (

    <this.View style={style}/>
    <Text style={[styles.setFontSize.setColorRed]}>Welcome to the dealership!</Text>

About

Cars

Contact

Search

        <View/>

**Here is where the error seems to be happing**

  );
}
export default Header;

App = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  setFontSize: {
    fontSize: 20,
    fontWeight : 'bold'
  },
  setColorRed : {
    color: '#f44336'
  }
});

Error is below as well

Line 37:12:  Parsing error: Unexpected token, expected "}"

35 |    36 | App = StyleSheet.create({

37 |   container: {
         |            ^   38 |     flex: 1,   39 |     justifyContent: 'center',   40 |     alignItems: 'center'

Body:
You need to enclose header HTML element and then wrap the component with <div>

function Header() {
  return (
    <div>
      <this.View style={style} />
      <Text style={[styles.setFontSize.setColorRed]}>
        Welcome to the dealership!
      </Text>
      <header className="header">
        <div className="col1"></div>
        <div className="col2">
          <div className="menu">
            <h3>About</h3>
            <h3>Cars</h3>
            <h3>Contact</h3>
            <h3>Search</h3>
            <header />
            <View />
          </div>
        </div>
      </header>
    </div>
  )
}

There are some really useful editor extensions can add and rename close tag for you, like Auto Close Tag and Auto Rename Tag.


问:
Basic React: why is a variable in local storage resetting to undefined after briefly being the desired value?
I am new to React and was writing some toy code whose desired behavior is to allow a user to enter their name in the form and the page will display "Hello {user's name}" after submitting.

However, the observed behavior is that the page flickers briefly to render "Hello {user's name}" and then returns to the default rendering as if no name had been submitted.

My current approach is to save the user's name in local storage upon submission with a useEffect. However, from observing console logs, the local storage appears to be resetting the "name" variable to undefined immediately after setting it to the inputted name. Below is the code.

```<code>function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);
  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          setName(event.target.elements.usernameInput.value);
          return false;
        }}
      >
        <label>Enter your name</label>
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>
      <h1>Hello {name}</h1>
    </>
  );
}
export default function App() {
  return (
    <div className="App">
      <NameForm />
    </div>
  );
}
</code>```

Here is also the codesandbox used to run the code. https://codesandbox.io/s/modern-hill-gfkrp?file=/src/App.js:76-773

Why is this unexpected behavior occuring and how can I fix it?

Thanks!

答:
why unexpected behavior
window.localStorage.setItem("name", name) returns undefined. So you are essencially doing setName(undefined) in your useEffect. Hence the issue.

how to fix?
You can fix in a number of ways. One way is to simply get rid of your useEffect and do localStorage.setItem in onSubmit and then do setName immediately.

Updated codesandbox link

<>
      <form
        onSubmit={event => {
          event.preventDefault();
          window.localStorage.setItem(
            "name",
            event.target.elements.usernameInput.value
          );
          setName(event.target.elements.usernameInput.value);
        }}
      >
        Enter your name
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>

Hello {name}

    </>
```

You can solve your issue with controlled input.

Body:
I am new to React and was writing some toy code whose desired behavior is to allow a user to enter their name in the form and the page will display "Hello {user's name}" after submitting.

However, the observed behavior is that the page flickers briefly to render "Hello {user's name}" and then returns to the default rendering as if no name had been submitted.

My current approach is to save the user's name in local storage upon submission with a useEffect. However, from observing console logs, the local storage appears to be resetting the "name" variable to undefined immediately after setting it to the inputted name. Below is the code.

function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);
  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          setName(event.target.elements.usernameInput.value);
          return false;
        }}
      >
        Enter your name
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>

Hello {name}

    </>
  );
}
export default function App() {
  return (

      <NameForm />

  );
}

Here is also the codesandbox used to run the code. https://codesandbox.io/s/modern-hill-gfkrp?file=/src/App.js:76-773

Why is this unexpected behavior occuring and how can I fix it?

Thanks!

Body:
why unexpected behavior
window.localStorage.setItem("name", name) returns undefined. So you are essencially doing setName(undefined) in your useEffect. Hence the issue.

how to fix?
You can fix in a number of ways. One way is to simply get rid of your useEffect and do localStorage.setItem in onSubmit and then do setName immediately.

Updated codesandbox link

<>
      <form
        onSubmit={event => {
          event.preventDefault();
          window.localStorage.setItem(
            "name",
            event.target.elements.usernameInput.value
          );
          setName(event.target.elements.usernameInput.value);
        }}
      >
        <label>Enter your name</label>
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>
      <h1>Hello {name}</h1>
    </>

You can solve your issue with controlled input.


问:
Can we use python 32 bit for Microsoft visual code 64bit?
Can we use python 32 bit latest version for Microsoft visualCode
64 bit ? Can it work?</p>

答: Yes you can, there is no relation between the version of VS Code and Python 3 (32 or 64 bit). VS Code is just a editor. I recommend you use the version of Python same as your CPU architecture (32 or 64 bit).</p>


问:
Update Events Dynamically
i have a couple of queries regarding the fullcalendar by arshaw..

when i select a particular stretch of dates and give an appropriate title as shown here
i get the event rendered in the calendar.. but when i want to save the event (I'm using asp.net) ie say after the user clicks on a save button,the title,startdate,end date has to be written into the events[{}] of the script..for this im using
response.write("script /script(with the tags of course)") after the button click which doesnt work..  would anyone suggest a better or a simpler working way?

also how to disable the selectable property? eg only an admin can set the event and a user can only see the event and not edit it..

答:
I don't think that you can update fullcalendar event JavaScript object with Response.Write() method.

You should use ajax to save event on server side and update calendar on client side.
Do something like this

```<code> function saveEvent() {

    var event = { startDate: $('#txtDate').val(), description: $('#txtDescription').val(), id: id }

    $.ajax({
        type: "POST",
        async: false,
        url: "../UserCalendarService.asmx/SaveEvent",
        data: "{'startDate': '" + event.startDate + "','description':'" + event.description + "','id':'" + event.id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            result = result.d;
            eventFound = $('#calendar').fullCalendar('clientEvents', result.id).length;
            if (eventFound == 1) {
                existingEvent = $('#calendar').fullCalendar('clientEvents', result.id);
                existingEvent[0].title = result.title;
                existingEvent[0].start = result.start;
                existingEvent[0].editable = result.editable;
                existingEvent[0].allday = true;
                $('#calendar').fullCalendar('updateEvent', existingEvent[0]);
            }
            else {
                $('#calendar').fullCalendar('renderEvent', {
                    title: result.title,
                    start: result.start,
                    id: result.id,
                    editable: result.editable,
                    allday: true
                },
             false // make the event "stick"
            );
            }
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            if (err.Message == 'SomeErrorMessage') {
                //handleError, redirect or popup message
            }
        }
    });

}
</code>```

As for your second question, event object has editable property. It is true or false.
You can found more about it in proper documentation.

Title: Update Events Dynamically

Body:
I don't think that you can update fullcalendar event JavaScript object with Response.Write() method.

You should use ajax to save event on server side and update calendar on client side.
Do something like this

 function saveEvent() {

    var event = { startDate: $('#txtDate').val(), description: $('#txtDescription').val(), id: id }

    $.ajax({
        type: "POST",
        async: false,
        url: "../UserCalendarService.asmx/SaveEvent",
        data: "{'startDate': '" + event.startDate + "','description':'" + event.description + "','id':'" + event.id + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            result = result.d;
            eventFound = $('#calendar').fullCalendar('clientEvents', result.id).length;
            if (eventFound == 1) {
                existingEvent = $('#calendar').fullCalendar('clientEvents', result.id);
                existingEvent[0].title = result.title;
                existingEvent[0].start = result.start;
                existingEvent[0].editable = result.editable;
                existingEvent[0].allday = true;
                $('#calendar').fullCalendar('updateEvent', existingEvent[0]);
            }
            else {
                $('#calendar').fullCalendar('renderEvent', {
                    title: result.title,
                    start: result.start,
                    id: result.id,
                    editable: result.editable,
                    allday: true
                },
             false // make the event "stick"
            );
            }
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            if (err.Message == 'SomeErrorMessage') {
                //handleError, redirect or popup message
            }
        }
    });

}

As for your second question, event object has editable property. It is true or false.
You can found more about it in proper documentation.


问:
Change cell values containing dates to the text shown after date formatting
I have a column of dates in excel that show up as mmm/yy (the left column) because of the cell formatting, when in actuality the cell values are full dd/mm/yyyy dates (as shown in the right column) [image here].

How do I get the actual cell values of the left column to be of the same mmm/yy text they are showing? I've tried looping through the column and using cell.value = cell.text but it ends up changing the day of the date to its year for some reason.

答:
You can just change the format of the left column for your need. Or you can use the following to format your dates:</p>

```<code>=TEXT([your date],"mmm-yy")
</code>```

Body:
You can just change the format of the left column for your need. Or you can use the following to format your dates:

=TEXT([your date],"mmm-yy")


问:
SQL for multiple rows with unique values from multiple unique values
I have the following update SQL that works for a single row.

```<code>UPDATE myshcema.my_table
SET emp_id = '000987654321'
WHERE cust_id = '000123456789';
</code>```

But I have over 6500 unique cust_ids that = 6500 unique emp_id.  I would like to update all of my emp_id column with the corresponding cust_id in the cust_id coulmn.  This table has other information in it but I'm missing about 5000 emp_id.  I have a .csv that has the cust_id, emp_id.

Any help would be appreciated.

答:
From the basic information you've provided, it sounds like you need to use a from statement in your update. First you need to load that CSV into a table on your DB.

This statement can be different based on what db you're using, but you should get the gist of it

```<code>UPDATE my_table tbl
SET emp_id = csv.emp_id
FROM your_new_csv_table csv
WHERE tbl.cust_id = csv.cust_id;
</code>```

Body:
I have the following update SQL that works for a single row.

UPDATE myshcema.my_table
SET emp_id = '000987654321'
WHERE cust_id = '000123456789';

But I have over 6500 unique cust_ids that = 6500 unique emp_id.  I would like to update all of my emp_id column with the corresponding cust_id in the cust_id coulmn.  This table has other information in it but I'm missing about 5000 emp_id.  I have a .csv that has the cust_id, emp_id.

Any help would be appreciated.

Body:
From the basic information you've provided, it sounds like you need to use a from statement in your update. First you need to load that CSV into a table on your DB.

This statement can be different based on what db you're using, but you should get the gist of it

UPDATE my_table tbl
SET emp_id = csv.emp_id
FROM your_new_csv_table csv
WHERE tbl.cust_id = csv.cust_id;


问:
How to Access Private Github Repo File (.csv) in Python using Pandas or Requests
I had to switch my public Github repository to private and cannot access files, not with access tokens that I was able to with the public Github repo.

I can access my private repo's CSV with curl:
'''
curl -s https://{token}@raw.githubusercontent.com/username/repo/master/file.csv

'''

However, I want to access this information in my python file. When the repo was public I could simply use:
'''
url = 'https://raw.githubusercontent.com/username/repo/master/file.csv'
df = pd.read_csv(url, error_bad_lines=False)

'''

This no longer works now that the repo is private, and I cannot find a work around to download this CSV in python instead of pulling from terminal.

If I try:
'''
requests.get(https://{token}@raw.githubusercontent.com/username/repo/master/file.csv)
'''
I get a 404 response, which is basically the same thing that is happening with the pd.read_csv(). If I click on the raw file I see that a temporary token is created and the URL is:
'''
https://raw.githubusercontent.com/username/repo/master/file.csv?token=TEMPTOKEN
'''
Is there a way to attach my permanent private access token so that I can always pull this data from github?

答:
Have you looked at the pygithub? Very useful for accessing repos, files, pull requests, history, etc. Docs are here. Here's an example script, which opens a pull request, a new branch off a base branch (you'll need that Access Token, or generate a new one!), and removes a file:

```<code>from github import Github
my_reviewers = ['usernames', 'of_reviewers']
gh = Github("<token string>")
repo_name = '<my_org>/<my_repo>'
repo = gh.get_repo(repo_name)
default_branch_name = repo.default_branch
base = repo.get_branch(default_branch_name)
new_branch_name = "my_new_branchname"
new_branch = repo.create_git_ref(ref=f'refs/heads/{new_branch_name}',sha=base.commit.sha)
contents = repo.get_contents("some_script_in_repo.sh", ref=new_branch_name)
repo.delete_file(contents.path, "commit message", contents.sha, branch=new_branch_name)
pr = repo.create_pull(
    title="PR to Remove some_script_in_repo.sh",
    body="This is the text in the main body of your pull request",
    head=new_branch_name,
    base=default_branch_name,
)
pr.create_review_request(reviewers=my_reviewers)
</code>```

Hope that helps, happy coding!

Body:
Have you looked at the pygithub? Very useful for accessing repos, files, pull requests, history, etc. Docs are here. Here's an example script, which opens a pull request, a new branch off a base branch (you'll need that Access Token, or generate a new one!), and removes a file:

from github import Github
my_reviewers = ['usernames', 'of_reviewers']
gh = Github("<token string>")
repo_name = '<my_org>/<my_repo>'
repo = gh.get_repo(repo_name)
default_branch_name = repo.default_branch
base = repo.get_branch(default_branch_name)
new_branch_name = "my_new_branchname"
new_branch = repo.create_git_ref(ref=f'refs/heads/{new_branch_name}',sha=base.commit.sha)
contents = repo.get_contents("some_script_in_repo.sh", ref=new_branch_name)
repo.delete_file(contents.path, "commit message", contents.sha, branch=new_branch_name)
pr = repo.create_pull(
    title="PR to Remove some_script_in_repo.sh",
    body="This is the text in the main body of your pull request",
    head=new_branch_name,
    base=default_branch_name,
)
pr.create_review_request(reviewers=my_reviewers)

Hope that helps, happy coding!


问:
make local copy of global variable
I'm probably missing something really obvious, but how do I create a local copy of a global vaiable with the same name?
I have something like:

d = {"one": 1, "two": 2, "three": 3}

def foo():
    d = d.copy()
    d["four"] = 4
```

I want to create a copy of d in the inner scope that I can modify as I like without affecting the global version. This will complain that d is reference before assignment, which makes perfect sense because it is being interpreted as a local variable. If I declare it global though, this will modify it.

This would be trivial if I didn't mind if it had a different name eg: d_local = d.copy(), but that would be a big hassle in this situation and not just a find and replace one either.

If the only solution is to use a new name and deal with the consequences let me know.

答:
You'd have to use another identifier if you are doing it this way. A variable can be either local or global but not both ... That's the whole point of scope. When you assign to something in a function, it will default to local. But if you make it global, i.e. by using the global statement, it will re-assign your global variable, which presumably you don't want (although, it would mutate a new object not the one being referenced by your global variable prior to calling the function).

The most reasonable thing here would be to take d as an argument. Then simply do d = d.copy()

so:

```<code>d = {"one": 1, "two": 2, "three": 3}

def foo(d):
    d = d.copy()
    d["four"] = 4

foo(d)
</code>```

This would be trivial if I didn't mind if it had a different name eg:
  d_local = d.copy(), but that would be a big hassle in this situation
  and not just a find and replace one either.

That sounds like a fundamental problem with your code. Identifiers should not really matter other than to help you understand your own code. If your logic depends on identifiers, that is almost always bad. Read Keep Data Out of Your Variable Names which is yet another excellent tutorial by Ned Batchelder.

Title: make local copy of global variable

Body:
I'm probably missing something really obvious, but how do I create a local copy of a global vaiable with the same name?
I have something like:

d = {"one": 1, "two": 2, "three": 3}

def foo():
    d = d.copy()
    d["four"] = 4

I want to create a copy of d in the inner scope that I can modify as I like without affecting the global version. This will complain that d is reference before assignment, which makes perfect sense because it is being interpreted as a local variable. If I declare it global though, this will modify it.

This would be trivial if I didn't mind if it had a different name eg: d_local = d.copy(), but that would be a big hassle in this situation and not just a find and replace one either.

If the only solution is to use a new name and deal with the consequences let me know.

Body:
You'd have to use another identifier if you are doing it this way. A variable can be either local or global but not both ... That's the whole point of scope. When you assign to something in a function, it will default to local. But if you make it global, i.e. by using the global statement, it will re-assign your global variable, which presumably you don't want (although, it would mutate a new object not the one being referenced by your global variable prior to calling the function).

The most reasonable thing here would be to take d as an argument. Then simply do d = d.copy()

so:

d = {"one": 1, "two": 2, "three": 3}

def foo(d):
    d = d.copy()
    d["four"] = 4

foo(d)

This would be trivial if I didn't mind if it had a different name eg:
  d_local = d.copy(), but that would be a big hassle in this situation
  and not just a find and replace one either.

That sounds like a fundamental problem with your code. Identifiers should not really matter other than to help you understand your own code. If your logic depends on identifiers, that is almost always bad. Read Keep Data Out of Your Variable Names which is yet another excellent tutorial by Ned Batchelder.


问:
Right way to update state with react socket hooks
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

```<code>  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }
</code>```

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

```<code>Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

        <div>
          <p> Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId} </p>
          <p>{JSON.stringify(gameState)}</p>
        </div>

      );
    } else {
      return (
        <div>
          <p> Game state is not created </p>
        </div>
      )
    }
  }
</code>```

答:
Socket connection needed be made when component is mounted. So, you'll need second parameter of useEffect:

```<code>useEffect(() => {
  // ... connection
}, []) // run on component mount
</code>```

You may also use useEffect when some variable changes:

```<code>useEffect(() => { // additional useEffect hook
  // ... changes being detected
}, [gameState])
</code>```

Body:
I am a beginner to react and I feel this question has been asked several times in the past but I can't see to understand what I am missing to get this working.

I am writing a simple browser based game. I am using socket-io to connect to the server and I am using a custom hook for obtaining state sent by the server

  export const useSocketState = (serverUrl: string) => {
    const [isConnected, setConnected] = useState(false)
    const [socketId, setSocketId] = useState('')
    const [gameState, setGameState] = useState(DEFAULT_INITIAL_STATE)
    useEffect(() => {
      const client = socket.connect(serverUrl)
      client.on("connect", () => {
        console.log("connected with id " + client.id)
        setConnected(true)
        setSocketId(client.id)
      });
      client.on("disconnect", () => {
        setConnected(false)
      });
      client.on("gameStateUpdate", (data: ClientGameState) => {
        console.dir("Recieved new state from server" + data);
        console.dir("GameState is " + gameState);
        setGameState(prevState => {
          const newState = data
          console.log(" new state is " + newState)
          return newState
        })
      });
    }, gameState);

    return {gameState, isConnected, socketId}
  }

I am using this hook in a component where I am referrring to the gameState returned by this hook.

I am expecting that when server sends a new state my gameState is actually set with a new state. I do see the log statement where a newState is printed when the server returns a new state but I am not seeing it being reflected in the component I am using.

Game component

  import React from "react";
  import {useSocketState} from "./useSocket";
  import {ClientGameState} from "../game/GameState";

  export function GameComponent(props: any) {
  const {gameState, isConnected, socketId} = useSocketState("http://127.0.0.1:8080");

    if (gameState.state === 'created') {
      return (

 Game id for this game: {props.location.state.gameId} and playerId:  {props.location.state.playerId}

{JSON.stringify(gameState)}

      );
    } else {
      return (

 Game state is not created

      )
    }
  }

Body:
Socket connection needed be made when component is mounted. So, you'll need second parameter of useEffect:

useEffect(() => {
  // ... connection
}, []) // run on component mount

You may also use useEffect when some variable changes:

useEffect(() => { // additional useEffect hook
  // ... changes being detected
}, [gameState])


问:
Receiving the error "undefined symbol" when loading C++ dynamic library from C executable
I am trying to write a plugin for a popular program whose code and compilation process I do not have control over. The program is written in C. However, I have written parts of my plugin in C++, since I use the QT5 library for graphics capabilities. The functions that the C program calls are written in C.

When the C program tries to load the plugin (shared library), it produces this error:

```<code>dlopen('build/libfoo.so') failed: build/libfoo.so: undefined symbol: _ZTV13JoystickPanel
</code>```

JoystickPanel is a class in the C++ part of the program.

I've tried rewriting parts of the program in C, but the error was unaffected. I know that I could rewrite the entire program in C, but I'd rather not have to switch to another, more C-friendly GUI framework. I've also opened up libfoo.so in a text editor and search for JoystickPanel, but it appears to be mangled as _ZN13JoystickPanel.

Are there any compiler options or solutions that I'm missing?

答:
Apparently, I'd forgetten to put the #include "moc_controller.cpp" line at the bottom of a file that needed it.

For anyone else chasing this issue while using Qt on CMake, consider making sure that the proper lines are added.

Body:
I am trying to write a plugin for a popular program whose code and compilation process I do not have control over. The program is written in C. However, I have written parts of my plugin in C++, since I use the QT5 library for graphics capabilities. The functions that the C program calls are written in C.

When the C program tries to load the plugin (shared library), it produces this error:

dlopen('build/libfoo.so') failed: build/libfoo.so: undefined symbol: _ZTV13JoystickPanel

JoystickPanel is a class in the C++ part of the program.

I've tried rewriting parts of the program in C, but the error was unaffected. I know that I could rewrite the entire program in C, but I'd rather not have to switch to another, more C-friendly GUI framework. I've also opened up libfoo.so in a text editor and search for JoystickPanel, but it appears to be mangled as _ZN13JoystickPanel.

Are there any compiler options or solutions that I'm missing?