问:
Object() takes no Parameters ; however, __init__() exists
I am working in a Jupyter notebook trying to implement simple CRUD operations for a collection using Pymongo.  The code for the CRUD class so far is:

```<code>from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
    """ CRUD operations for Animal collection in MongoDB """

    def __init_(self, username, password):
        # Initializing the MongoClient. This helps to
        # access the MongoDB databases and collections.
        self.client = MongoClient('mongodb://%s:%s@localhost:54933' % (username, password))
        self.database = self.client['AAC']

# Complete this create method to implement the C in CRUD.
    def create(self, data):
        if data is not None:
            self.database.animals.insert(data)  # data should be dictionary
            return True
        else:
            raise Exception("Nothing to save, because data parameter is empty")

# Create method to implement the R in CRUD.
    def read(self, data):
        if data is not None:
            self.database.animal.find(data)
            return True
        else:
            raise Exception("Nothing to find, because data parameter is empty")
</code>```

The code for the main py file is:

```<code>from module4_markw import AnimalShelter

def main():
    username = 'aacuser'
    password = 'acc355!'
    aShelter = AnimalShelter(username, password)
    data = [""]
    aShelter.create(data)
    aShelter.read(data)
</code>```

When I run main, however, I get an "Object() takes no parameters" message. I'm not really sure what is causing this.  Others posts have stated that this means that their is no init() in the class code, but this is definitely there.  This error did occur after I reset the kernel in Jupyter, so something may have gone awry during that.  Thanks!

答:
Typo:

```<code>__init_
</code>```

Put another underscore

Body:
I am working in a Jupyter notebook trying to implement simple CRUD operations for a collection using Pymongo.  The code for the CRUD class so far is:

from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
    """ CRUD operations for Animal collection in MongoDB """

    def __init_(self, username, password):
        # Initializing the MongoClient. This helps to
        # access the MongoDB databases and collections.
        self.client = MongoClient('mongodb://%s:%s@localhost:54933' % (username, password))
        self.database = self.client['AAC']

# Complete this create method to implement the C in CRUD.
    def create(self, data):
        if data is not None:
            self.database.animals.insert(data)  # data should be dictionary
            return True
        else:
            raise Exception("Nothing to save, because data parameter is empty")

# Create method to implement the R in CRUD.
    def read(self, data):
        if data is not None:
            self.database.animal.find(data)
            return True
        else:
            raise Exception("Nothing to find, because data parameter is empty")

The code for the main py file is:

from module4_markw import AnimalShelter

def main():
    username = 'aacuser'
    password = 'acc355!'
    aShelter = AnimalShelter(username, password)
    data = [""]
    aShelter.create(data)
    aShelter.read(data)

When I run main, however, I get an "Object() takes no parameters" message. I'm not really sure what is causing this.  Others posts have stated that this means that their is no init() in the class code, but this is definitely there.  This error did occur after I reset the kernel in Jupyter, so something may have gone awry during that.  Thanks!

Body:
Typo:

__init_

Put another underscore


来源: stackexchange

问:
Consistency level of GlobalKTable
What consistency level does a GlobalKTable have? I need strong consistency to ensure that values which contain a list are updated one at a time.

My guess is that it is at most eventually consistent, since the table is fully replicated for any number of partitions.

I just wanted to make sure, to justify extra effort required if its not the case.

答: The table is built from a compacted topic. Consuming from this, or any topic, results in an eventually consistent model, yes.</p>

ContentLicense: CC BY-SA 4.0

Title: Consistency level of GlobalKTable


问:
Intercepting context.SaveChanges() in MVC 3 so that I can modify and use a custom sql query instead
I am working on an MVC3 project whose model is designed using Code First approach. I am using EF4 for ORM and have a need where I need two thing -
1. Intercept the context.SaveChages method
2.Do my own custom update query for one specific entity type only.

I got the first part working by overriding the SaveChanges() method like -

```<code>    public  override  int SaveChanges()
    {
var modifiedItems = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Modified && e.Entity is myEntityName);
        foreach (var item in modifiedItems)
        {
           //ToDo: Write UPDATE Sql Query here
        }

        return base.SaveChanges();
}
</code>```

How can I write my update query?
Thanks!

答: This is not possible. You can only map custom stored procedures to be used instead of CUD operations (only with EDMX) generated by EF but still you will have single stored procedure call per each operation and entity instance.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am working on an MVC3 project whose model is designed using Code First approach. I am using EF4 for ORM and have a need where I need two thing -
1. Intercept the context.SaveChages method
2.Do my own custom update query for one specific entity type only.

I got the first part working by overriding the SaveChanges() method like -

    public  override  int SaveChanges()
    {
var modifiedItems = this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Modified && e.Entity is myEntityName);
        foreach (var item in modifiedItems)
        {
           //ToDo: Write UPDATE Sql Query here
        }

        return base.SaveChanges();
}

How can I write my update query?
Thanks!


问:
Does Yugabyte's YSQL support type BLOB?
I see that from Is there support for BLOBs in YugabyteDB like in Oracle or Postgres?, it says BLOB type is not supported. It is from two years ago so I am wondering if it's still true.

From https://github.com/yugabyte/yugabyte-db/issues/3576, I see that the ticket for BLOB support is still open but from https://docs.yugabyte.com/latest/api/ycql/type_blob/, it seems like it's supported?

I should mention that I tried to create a table with a column typed BLOB but got:

```<code>create table small_files(file_id bigint, file_size bigint, file_name text, content blob);
ERROR:  type "blob" does not exist
</code>```

Does it just mean that the cloud version of yugabyte supports it, ie using YCQL but not YSQL? Is using BYTEA the current alternative for type BLOB? Thank you.

答:
The link you shared (https://docs.yugabyte.com/latest/api/ycql/type_blob/) is for YCQL which is based on the Cassandra API (and not YSQL, YugabyteDB's Postgres-compatible API).

Even with YCQL, the blob type is not intended for use for very large objects. For example, unlike BLOBs in Oracle, YCQL blob sizes are generally restricted to 32MB in size (but recommended sizes are 4MB or so). It is not really designed for storing very large objects.

Also at this time YSQL support for BLOBs does not exist in YugabyteDB.

Title: Does Yugabyte's YSQL support type BLOB?

Body:
I see that from Is there support for BLOBs in YugabyteDB like in Oracle or Postgres?, it says BLOB type is not supported. It is from two years ago so I am wondering if it's still true.

From https://github.com/yugabyte/yugabyte-db/issues/3576, I see that the ticket for BLOB support is still open but from https://docs.yugabyte.com/latest/api/ycql/type_blob/, it seems like it's supported?

I should mention that I tried to create a table with a column typed BLOB but got:

create table small_files(file_id bigint, file_size bigint, file_name text, content blob);
ERROR:  type "blob" does not exist

Does it just mean that the cloud version of yugabyte supports it, ie using YCQL but not YSQL? Is using BYTEA the current alternative for type BLOB? Thank you.


问:
How to export a Hive table into a CSV file?
I used this Hive query to export a table into a CSV file.

```<code>INSERT OVERWRITE DIRECTORY '/user/data/output/test' select column1, column2 from table1;
</code>```

The file generated '000000_0' does not have comma separator

Is this the right way to generate CSV file? If no, please let me know how can I generate the CSV file?

答:
None of the above options work perfect for me. Few issues I want to solve

If there's tab in the value, it shouldn't break CSV output

I need the head to be automatically added without any manual work

Struct, array or map field should be JSON encoded

So I create the UDF to do that. (A bit surprised Hive didn't have this build in support)

Usage:

```<code>ADD JAR ivy://org.jsonex:HiveUDF:0.1.24?transitive=true;
CREATE TEMPORARY FUNCTION to_csv AS 'org.jsonex.hiveudf.ToCSVUDF';
SELECT to_csv(*) FROM someTable;  -- Default separator and headers
SELECT to_csv('{noHead:true}', *) FROM someTable;  -- No headers
SELECT to_csv('{headers:[,,,col3,]}', *) FROM someTable; -- Custom Headers
SELECT to_csv('{fieldSep:|,quoteChar:\"\\'\"}', *) FROM someTable" -- Custom fieldSep and quoteChar
</code>```

Body:
I used this Hive query to export a table into a CSV file.

INSERT OVERWRITE DIRECTORY '/user/data/output/test' select column1, column2 from table1;

The file generated '000000_0' does not have comma separator

Is this the right way to generate CSV file? If no, please let me know how can I generate the CSV file?

Body:
None of the above options work perfect for me. Few issues I want to solve

If there's tab in the value, it shouldn't break CSV output

I need the head to be automatically added without any manual work

Struct, array or map field should be JSON encoded

So I create the UDF to do that. (A bit surprised Hive didn't have this build in support)

Usage:

ADD JAR ivy://org.jsonex:HiveUDF:0.1.24?transitive=true;
CREATE TEMPORARY FUNCTION to_csv AS 'org.jsonex.hiveudf.ToCSVUDF';
SELECT to_csv(*) FROM someTable;  -- Default separator and headers
SELECT to_csv('{noHead:true}', *) FROM someTable;  -- No headers
SELECT to_csv('{headers:[,,,col3,]}', *) FROM someTable; -- Custom Headers
SELECT to_csv('{fieldSep:|,quoteChar:\"\\'\"}', *) FROM someTable" -- Custom fieldSep and quoteChar


问:
How to correctly call a function from Node.JS to Express.JS
I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)</p>
```<code>    const express = require('express')
    const runParser = require("./parser");
    const app = express()
    const port = 3000

    app.get('/', async (req, res,next) => {
      await runParser()
        next()
    })

    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })
</code>```

答:
All you need for Express is this:

```<code>const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;

app.get("/", (req, res) => {
   runParser().then(results => {
      res.json(results);
   }).catch(err => {
      console.log(err);
      res.status(500).send("error");
   });
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});
</code>```

And, then you can access that either by just going to:

```<code>http://localhost:3000
</code>```

from your local host or

```<code>http://yourdomain.com:3000
</code>```

in the browser or by issuing an ajax call to the desired URL from webpage Javascript.

I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...

It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:

```<code>app.post("/runparser", (req, res) => {
    // put your code here
});
</code>```

And, then use a form submission or ajax call to that URL to trigger it.

Body:
I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)

    const express = require('express')
    const runParser = require("./parser");
    const app = express()
    const port = 3000

    app.get('/', async (req, res,next) => {
      await runParser()
        next()
    })

    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })

Body:
All you need for Express is this:

const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;

app.get("/", (req, res) => {
   runParser().then(results => {
      res.json(results);
   }).catch(err => {
      console.log(err);
      res.status(500).send("error");
   });
});

app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

And, then you can access that either by just going to:

http://localhost:3000

from your local host or

http://yourdomain.com:3000

in the browser or by issuing an ajax call to the desired URL from webpage Javascript.

I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...

It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:

app.post("/runparser", (req, res) => {
    // put your code here
});

And, then use a form submission or ajax call to that URL to trigger it.


问:
How to Add Custom Objects in to listbox of VB 2010
I am developing one vb application. In that I have one list box. I want to add different types of Items. Like Different Colored and differently aligned text(Like one item item is right aligned and one more is left aligned). Can you please tell me how can i do the same.

Thanks.

答:
This is how I did it in one of my projects (the original code is in c#):</p>

```<code>Public Class ColoringStepCommandListBox
    Inherits CommandListBox

    Const ItemHeight As Integer = 20

    Public Sub New()
        listBox.ItemHeight = ItemHeight
        listBox.DrawMode = DrawMode.OwnerDrawFixed
    End Sub

    Protected Overrides Sub OnDrawItem(sender As Object, e As DrawItemEventArgs)
        Const  textFormatFlags__1 As TextFormatFlags = TextFormatFlags.EndEllipsis Or TextFormatFlags.PreserveGraphicsClipping Or TextFormatFlags.VerticalCenter
        Const  colorRectangleWidth As Integer = 100, textLeft As Integer = 110

        If e.Index >= 0 Then
            'Cast the listbox item to your custom type (ColoringStep in my example).
            Dim coloringStep = TryCast(listBox.Items(e.Index), ColoringStep)

            e.DrawBackground()

            'Do custom coloring and rendering, draw icons etc.
            Dim colorRect = New Rectangle(2, e.Bounds.Top + 2, colorRectangleWidth, ItemHeight - 5)
            Dim innerRect = New Rectangle(colorRect.Left + 1, colorRect.Top + 1, colorRect.Width - 1, colorRect.Height - 1)
            e.Graphics.DrawRectangle(Pens.Black, colorRect)
            DrawingHelper.DrawGradient(coloringStep, e.Graphics, innerRect, LinearGradientMode.Horizontal)

            'Draw the text (this does not happen automatically any more with owner draw modes).
            Dim textRect = New Rectangle(textLeft, e.Bounds.Top, e.Bounds.Width - textLeft, e.Bounds.Height)
            TextRenderer.DrawText(e.Graphics, coloringStep.ToString(), e.Font, textRect, e.ForeColor, textFormatFlags__1)

            e.DrawFocusRectangle()
        End If
    End Sub
End Class
</code>```

Body:
This is how I did it in one of my projects (the original code is in c#):

Public Class ColoringStepCommandListBox
    Inherits CommandListBox

    Const ItemHeight As Integer = 20

    Public Sub New()
        listBox.ItemHeight = ItemHeight
        listBox.DrawMode = DrawMode.OwnerDrawFixed
    End Sub

    Protected Overrides Sub OnDrawItem(sender As Object, e As DrawItemEventArgs)
        Const  textFormatFlags__1 As TextFormatFlags = TextFormatFlags.EndEllipsis Or TextFormatFlags.PreserveGraphicsClipping Or TextFormatFlags.VerticalCenter
        Const  colorRectangleWidth As Integer = 100, textLeft As Integer = 110

        If e.Index >= 0 Then
            'Cast the listbox item to your custom type (ColoringStep in my example).
            Dim coloringStep = TryCast(listBox.Items(e.Index), ColoringStep)

            e.DrawBackground()

            'Do custom coloring and rendering, draw icons etc.
            Dim colorRect = New Rectangle(2, e.Bounds.Top + 2, colorRectangleWidth, ItemHeight - 5)
            Dim innerRect = New Rectangle(colorRect.Left + 1, colorRect.Top + 1, colorRect.Width - 1, colorRect.Height - 1)
            e.Graphics.DrawRectangle(Pens.Black, colorRect)
            DrawingHelper.DrawGradient(coloringStep, e.Graphics, innerRect, LinearGradientMode.Horizontal)

            'Draw the text (this does not happen automatically any more with owner draw modes).
            Dim textRect = New Rectangle(textLeft, e.Bounds.Top, e.Bounds.Width - textLeft, e.Bounds.Height)
            TextRenderer.DrawText(e.Graphics, coloringStep.ToString(), e.Font, textRect, e.ForeColor, textFormatFlags__1)

            e.DrawFocusRectangle()
        End If
    End Sub
End Class


问:
Finding balanced open/close tags based on their positions
How do you figure out the structure of nested open close pairs based on their positions?

I have 2 arrays of open and closed positions like this:

```<code>closearr: (3) [3, 5, 6]
openarr: (3) [1, 2, 4]
</code>```

For example from these values you can figure out the structure is something like this:

```<code><tag>
    <tag></tag>
    <tag></tag>
</tag>
</code>```

These values are their positions relative to each other. Since openarr[1] > closearr[0] for example you know that the second tag is nested within the first.

I'm trying to figure out an algorithm that will get me the index of the closing tag based on the index of the open tag. It should work for any type of nesting so long as the values are in the arrays.

function findClosingTag (openindex, openarr, closearr) {
return close
}

findClosingTag(1, openarr, closearr) should output 6

findClosingTag(2, openarr, closearr) should output 3

Another example of another set of values:

```<code>closearr: (3) [3, 6, 7, 8]
openarr: (3) [1, 2, 4, 5]
</code>```

from here the structure you can figure out is like this:

```<code><tag>
    <tag></tag>
    <tag>
        <tag></tag>
    </tag>
</tag>
</code>```

So if I do

findClosingTag(4, openarr, closearr) should output 7

findClosingTag(1, openarr, closearr) should output 8

答:
You can easily achieve solve this similarly like a bracket matching algorithm.

You have to sort it as per the position

If the type is open then you just have to push it into the stack

If the type is closed then you can grab the top item from the stack, and pop it. This is the paired tag that you are looking for

function findClosingTag(pos, openArr, closedArr) {
  const closed = closedArr.map((position) => ({ type: 'closed', position }));
  const open = openArr.map((position) => ({ type: 'open', position }));

  const arr = [...open, ...closed].sort((a, b) => a.position - b.position);

  const stack = [];
  for (let { type, position } of arr) {
    if (type === 'open') stack.push(position);
    else {
      const lastOpenItemIndexInStack = stack.pop();
      if (lastOpenItemIndexInStack === pos) return position;
    }
  }
}

const closearr = [3, 6, 7, 8];
const openarr = [1, 2, 4, 5];
console.log(findClosingTag(4, openarr, closearr));```
</div>
</div>
</p>
<p><strong><code>Full Algorithm to find all pairs</code></strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function findAllMatchingTag(pos, openArr, closedArr) {
  const closed = closedArr.map((position) => ({ type: 'closed', position }));
  const open = openArr.map((position) => ({ type: 'open', position }));

  const arr = [...open, ...closed].sort((a, b) => a.position - b.position);

  const stack = [];
  let map = new Map();

  for (let { type, position } of arr) {
    type === 'open' ? stack.push(position) : map.set(stack.pop(), position);
  }
  return map;
}

const closearr = [3, 6, 7, 8];
const openarr = [1, 2, 4, 5];
const allMatchingPairs = findAllMatchingTag(4, openarr, closearr);
console.log(`2 - ${allMatchingPairs.get(2)}`);
console.log(`1 - ${allMatchingPairs.get(1)}`);
console.log(`4 - ${allMatchingPairs.get(4)}`);
console.log(`5 - ${allMatchingPairs.get(5)}`);</code>```

Body:
How do you figure out the structure of nested open close pairs based on their positions?

I have 2 arrays of open and closed positions like this:

closearr: (3) [3, 5, 6]
openarr: (3) [1, 2, 4]

For example from these values you can figure out the structure is something like this:

<tag>
    <tag></tag>
    <tag></tag>
</tag>

These values are their positions relative to each other. Since openarr[1] > closearr[0] for example you know that the second tag is nested within the first.

I'm trying to figure out an algorithm that will get me the index of the closing tag based on the index of the open tag. It should work for any type of nesting so long as the values are in the arrays.

function findClosingTag (openindex, openarr, closearr) {
return close
}

findClosingTag(1, openarr, closearr) should output 6

findClosingTag(2, openarr, closearr) should output 3

Another example of another set of values:

closearr: (3) [3, 6, 7, 8]
openarr: (3) [1, 2, 4, 5]

from here the structure you can figure out is like this:

<tag>
    <tag></tag>
    <tag>
        <tag></tag>
    </tag>
</tag>

So if I do

findClosingTag(4, openarr, closearr) should output 7

findClosingTag(1, openarr, closearr) should output 8

Body:
You can easily achieve solve this similarly like a bracket matching algorithm.

You have to sort it as per the position

If the type is open then you just have to push it into the stack

If the type is closed then you can grab the top item from the stack, and pop it. This is the paired tag that you are looking for

function findClosingTag(pos, openArr, closedArr) {
  const closed = closedArr.map((position) => ({ type: 'closed', position }));
  const open = openArr.map((position) => ({ type: 'open', position }));

  const arr = [...open, ...closed].sort((a, b) => a.position - b.position);

  const stack = [];
  for (let { type, position } of arr) {
    if (type === 'open') stack.push(position);
    else {
      const lastOpenItemIndexInStack = stack.pop();
      if (lastOpenItemIndexInStack === pos) return position;
    }
  }
}

const closearr = [3, 6, 7, 8];
const openarr = [1, 2, 4, 5];
console.log(findClosingTag(4, openarr, closearr));

Full Algorithm to find all pairs

function findAllMatchingTag(pos, openArr, closedArr) {
  const closed = closedArr.map((position) => ({ type: 'closed', position }));
  const open = openArr.map((position) => ({ type: 'open', position }));

  const arr = [...open, ...closed].sort((a, b) => a.position - b.position);

  const stack = [];
  let map = new Map();

  for (let { type, position } of arr) {
    type === 'open' ? stack.push(position) : map.set(stack.pop(), position);
  }
  return map;
}

const closearr = [3, 6, 7, 8];
const openarr = [1, 2, 4, 5];
const allMatchingPairs = findAllMatchingTag(4, openarr, closearr);
console.log(`2 - ${allMatchingPairs.get(2)}`);
console.log(`1 - ${allMatchingPairs.get(1)}`);
console.log(`4 - ${allMatchingPairs.get(4)}`);
console.log(`5 - ${allMatchingPairs.get(5)}`);


问:
invalid assignment to const 'setMessage'
I am having this issue with TextField from Material UI. I am trying to change state with React with the props onChange. Sadly I keep having this message "invalid assignment to const 'setMessage'" I use the same code that I have use in other components of my code so I really don't know why now I can't use setMessage.

```<code>
    const [message, setMessage] = useState("");

                <TextField
                    name="message"
                    placeholder="Écrire un message..."
                    onChange={ e =>
                        setMessage=(e.target.value)
                    }
                    onKeyPress={(event) => {
                        event.key === 'Enter' && sendMessage();
                    }}
                />
</code>```

答:
You have a typo in the onChange prop. You should remove the = from this line

```<code>setMessage=(e.target.value)
</code>```

The onChange prop should look like this

```<code>onChange={ e =>
    setMessage(e.target.value)
}
</code>```

Body:
I am having this issue with TextField from Material UI. I am trying to change state with React with the props onChange. Sadly I keep having this message "invalid assignment to const 'setMessage'" I use the same code that I have use in other components of my code so I really don't know why now I can't use setMessage.

    const [message, setMessage] = useState("");

                <TextField
                    name="message"
                    placeholder="Écrire un message..."
                    onChange={ e =>
                        setMessage=(e.target.value)
                    }
                    onKeyPress={(event) => {
                        event.key === 'Enter' && sendMessage();
                    }}
                />

Body:
You have a typo in the onChange prop. You should remove the = from this line

setMessage=(e.target.value)

The onChange prop should look like this

onChange={ e =>
    setMessage(e.target.value)
}


问:
Align the components horizontally in the card header of dash bootstrap
I want to arrange three components html.div, dbc.Checklist and dbc.Button horizontally in the card header of dash bootstrap.

The following is the current arrangement, with the three elements lined up vertically.

Is there any way to arrange the entire component or part of it horizontally in the style element of the card header?

Thank you.

here is my source code.

```<code>import dash
import dash_bootstrap_components as dbc
from dash import html, dcc
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        dbc.Row(
            [
                dbc.Col(
                    dbc.Card(
                        [
                            dbc.CardHeader(
                                [
                                    html.Div("card header"),
                                    dbc.Checklist(
                                        options=[{"label": "edge color", "value": 1},],
                                        value=[1],
                                        id="switches-input",
                                        switch=True,
                                        inline=True,
                                    ),
                                    dbc.Button("button"),
                                ]
                            ),
                            dbc.CardBody(html.Div("card body"))
                        ]
                    ),
                ),
            ],
        ),
    ],
    style={"height": "95vh", "background-color": "grey"},
)

if __name__ == "__main__":
    app.run_server(debug=True)
</code>```

答:
Place dbc.Row and dbc.Col accordingly in the card header children component to align your components. Here is an example to align your card header components horizontally:

import dash
import dash_bootstrap_components as dbc
from dash import html, dcc
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        dbc.Row(
            [
                dbc.Col(
                    dbc.Card(
                        [
                            dbc.CardHeader(
                                [
                                    dbc.Row([
                                        dbc.Col([html.Div("card header"), ]),
                                        dbc.Col([dbc.Checklist(
                                            options=[
                                                {"label": "edge color", "value": 1}, ],
                                            value=[1],
                                            id="switches-input",
                                            switch=True,
                                            inline=True,
                                        ), ]),
                                        dbc.Col([dbc.Button("button"), ]),
                                    ]),
                                ]
                            ),
                            dbc.CardBody(html.Div("card body"))
                        ]
                    ),
                ),
            ],
        ),
    ],
    style={"height": "95vh", "background-color": "grey"},
)

if __name__ == "__main__":
    app.run_server(debug=True)
```

Body:
I want to arrange three components html.div, dbc.Checklist and dbc.Button horizontally in the card header of dash bootstrap.

The following is the current arrangement, with the three elements lined up vertically.

Is there any way to arrange the entire component or part of it horizontally in the style element of the card header?

Thank you.

here is my source code.

import dash
import dash_bootstrap_components as dbc
from dash import html, dcc
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        dbc.Row(
            [
                dbc.Col(
                    dbc.Card(
                        [
                            dbc.CardHeader(
                                [
                                    html.Div("card header"),
                                    dbc.Checklist(
                                        options=[{"label": "edge color", "value": 1},],
                                        value=[1],
                                        id="switches-input",
                                        switch=True,
                                        inline=True,
                                    ),
                                    dbc.Button("button"),
                                ]
                            ),
                            dbc.CardBody(html.Div("card body"))
                        ]
                    ),
                ),
            ],
        ),
    ],
    style={"height": "95vh", "background-color": "grey"},
)

if __name__ == "__main__":
    app.run_server(debug=True)


问:
How to decrease the execution time of multiple requests in Dynamics 365
I'm in big trouble. The execution time of my multiple requests in the code is being longer than the azure app timeout. I need to update a lot of records and in the end return some data to the web site in azure. I'm sending batches of 200 requests to update 200 records. I need a faster way to batch update records.

My code:

```<code>public static Boolean BulkUpdateNoSorteado(CrmServiceClient service, EntityCollection entities)
{
    // Create an ExecuteMultipleRequest object.
    var multipleRequest = new ExecuteMultipleRequest()
            {
                // Assign settings that define execution behavior: continue on error, return responses.
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },

                // Create an empty organization request collection.
                Requests = new OrganizationRequestCollection()
            };

    try
    {
        var countRequest = Int32.Parse(ConfigurationManager.AppSettings["requestCount"]);

        // Add a UpdateRequest for each entity to the request collection.
        foreach (var entity in entities.Entities)
        {
            SetStateRequest request = new SetStateRequest
                    {
                        EntityMoniker = new EntityReference(entity.LogicalName, entity.Id),
                        State = new OptionSetValue(1),
                        Status = new OptionSetValue((int)Domain.Enum.EnumStatusTicket.Nao_sorteado)
                    };
            multipleRequest.Requests.Add(request);

            if (multipleRequest.Requests.Count == countRequest || entity == entities.Entities.Last())
            {
                if (service.OrganizationServiceProxy == null)
                {
                    service = FactoryGetService.AccessTokenGeneratorAsync();
                }

                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

                multipleRequest = new ExecuteMultipleRequest()
                        {
                            // Assign settings that define execution behavior: continue on error, return responses.
                            Settings = new ExecuteMultipleSettings()
                            {
                                ContinueOnError = false,
                                ReturnResponses = true
                            },
                            // Create an empty organization request collection.
                            Requests = new OrganizationRequestCollection()
                        };
                }
       }

       return true;
    }
    catch (Exception)
    {
         throw;
    }
}
</code>```

答:
Try to refactor your code to use:

Parallel programming (like Parallel.ForEach, Parallel.For in C# for example or,

Pure multi-threading hence letting multiple worker threads cooperate on the multiple updates at the same time. In that regard you can share the EntityCollection in a concurrent queue (ConcurrentQueue<T> in C# for example).

You can test easier for Azure timeout if you configure the number of threads and the batch size of the multiple updates in your solution.

As much as possible CRM organization URLs for the threads.

Here's what the code in 2. might look like:

using System;
using System.Threading;
using System.Data;
using System.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;

public class EntitiesPage : List<Entity> { }

public class MultiThreadedDynamicsCrmUpdate
{
    //EntityCollection ec = ...;
    //CrmServiceClient service = FactoryGetService.AccessTokenGeneratorAsync();
    //int statusOptionSetValue = (int)Domain.Enum.EnumStatusTicket.Nao_sorteado;

    int updatesPageSize = 200;
    int threadsNumber = 10;
    ConcurrentQueue<EntitiesPage> cq = new ConcurrentQueue<EntitiesPage>();

    public static void Main(string[] args)
    {
        UpdateAll();
    }

    public static void UpdateAll()
    {
        PaginateEntities(ec);

        List<Thread> threads = new List<Thread>();
        for (int i = 0; i < threadsNumber; i++)
        {
            threads.Add(new Thread(UpdateACrmEntitiesPageByThread));
        }

        foreach (Thread thread in threads)
        {
            thread.Start();
        }

        foreach (Thread thread in threads)
        {
            thread.Join();
        }
    }

    public static void PaginateEntities(EntityCollection ec)
    {
        EntitiesPage page = new EntitiesPage();

        foreach (Entity e in ec.Entities)
        {
            page.Add(e);
            if (page.Count == updatesPageSize)
            {
                cq.Enqueue(page);
                page = new EntitiesPage();
            }
        }
        cq.Enqueue(page);
    }

    public static void UpdateACrmEntitiesPageByThread()
    {
        EntitiesPage page = new EntitiesPage();

        while (!cq.IsEmpty)
        {
            if (cq.TryDequeue(out page))
            {
                var multipleRequest = new ExecuteMultipleRequest()
                {
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    },
                    Requests = new OrganizationRequestCollection()
                };

                foreach (Entity e in page)
                {
                    SetStateRequest request = new SetStateRequest
                    {
                        EntityMoniker = new EntityReference(e.LogicalName, e.Id),
                        State = new OptionSetValue(1),
                        Status = new OptionSetValue(...)
                    };
                    multipleRequest.Requests.Add(request);
                }

                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
            }
        }
    }
}
```

Body:
I'm in big trouble. The execution time of my multiple requests in the code is being longer than the azure app timeout. I need to update a lot of records and in the end return some data to the web site in azure. I'm sending batches of 200 requests to update 200 records. I need a faster way to batch update records.

My code:

public static Boolean BulkUpdateNoSorteado(CrmServiceClient service, EntityCollection entities)
{
    // Create an ExecuteMultipleRequest object.
    var multipleRequest = new ExecuteMultipleRequest()
            {
                // Assign settings that define execution behavior: continue on error, return responses.
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },

                // Create an empty organization request collection.
                Requests = new OrganizationRequestCollection()
            };

    try
    {
        var countRequest = Int32.Parse(ConfigurationManager.AppSettings["requestCount"]);

        // Add a UpdateRequest for each entity to the request collection.
        foreach (var entity in entities.Entities)
        {
            SetStateRequest request = new SetStateRequest
                    {
                        EntityMoniker = new EntityReference(entity.LogicalName, entity.Id),
                        State = new OptionSetValue(1),
                        Status = new OptionSetValue((int)Domain.Enum.EnumStatusTicket.Nao_sorteado)
                    };
            multipleRequest.Requests.Add(request);

            if (multipleRequest.Requests.Count == countRequest || entity == entities.Entities.Last())
            {
                if (service.OrganizationServiceProxy == null)
                {
                    service = FactoryGetService.AccessTokenGeneratorAsync();
                }

                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);

                multipleRequest = new ExecuteMultipleRequest()
                        {
                            // Assign settings that define execution behavior: continue on error, return responses.
                            Settings = new ExecuteMultipleSettings()
                            {
                                ContinueOnError = false,
                                ReturnResponses = true
                            },
                            // Create an empty organization request collection.
                            Requests = new OrganizationRequestCollection()
                        };
                }
       }

       return true;
    }
    catch (Exception)
    {
         throw;
    }
}


问:
How do you detect if a list has exactly 3 items in Haskell?
I have this but I got an error:</p>

```<code>-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs   | [_ , _ , _] = True
          | otherwise = False
</code>```

答:
I'd write something like</p>
```<code>hasLength3 :: [a] -> Bool
hasLength3 xs = xs `hasLength` 3

hasLength :: [a] -> Int -> Bool
hasLength = foldr go stop
  where
    go _ r n = n > 0 && r (n - 1)
    stop n = n == 0
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this but I got an error:

-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs   | [_ , _ , _] = True
          | otherwise = False

Body:
I'd write something like

hasLength3 :: [a] -> Bool
hasLength3 xs = xs `hasLength` 3

hasLength :: [a] -> Int -> Bool
hasLength = foldr go stop
  where
    go _ r n = n > 0 && r (n - 1)
    stop n = n == 0


问:
Are there good reasons to wrap a single property in a #region in c#?
I recently inherited some C# code where nearly every item in a file was wrapped in an individual #region/#endregion block -- every class, every function, every property, every enum, but not the fields.  Each of these was in turn wrapped in a "grouping" #region (e.g. "Properties", "Constructor", "Methods", etc.).  There are multiple overloads of a single function with different argument lists, but they're each wrapped in individual regions with the same name, rather than a single region for all three overloads.  The person who wrote this code is no longer with the company, and from the history in source control, it appears that these were present in the initial submission, and the practice continues through successive versions of the code as new properties and methods are added.

Any idea why this might be done?  Some thoughts:

An overzealous VS feature (or code-cleanup tool) automatically inserted the #region/#endregion blocks, and the author didn't remove them.

There's an IDE that folds regions but not functions, so this was necessary to get syntax folding.

This is a method of stubbing out the structure of your code prior to implementing it.

EDIT: I chose Jonathan's answer because it contributed a new reason why someone might have chosen to do this.  Thanks for the discussion!

答:
When it comes to non-auto-implemented properties it can make the code easier to navigate. For instance a lot of the following code (inside the region) is just extraenuous fluff - which always looks the same (as properties really shouldn't have side-effects). Having a single line saying "Property - Name" is much nicer to navigate.

```<code>#region Property - Name
private string _name;
/// <summary>
/// Gets or sets the name of the customer.
/// </summary>
/// <remarks>
/// This should always be the full name of the customer in the format {First Name} {Last Name}.
/// </remarks>
/// <example>
/// customer.Name = "Joe Bloggs";
/// </example>
/// <seealso cref="Customer"/>
/// <value>
/// The name of the customer.
/// </value>
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}
#endregion
</code>```

However, as far as the 'member type' (Methods, Properties, Constructors, Fields) go I feel it makes the code harder to navigate; however other people feel it makes it easier.

In the end it's a coding standard and religous. If you don't like it, don't use it one your personal projects. If you are required to use it due to a standard then use it.

Body:
When it comes to non-auto-implemented properties it can make the code easier to navigate. For instance a lot of the following code (inside the region) is just extraenuous fluff - which always looks the same (as properties really shouldn't have side-effects). Having a single line saying "Property - Name" is much nicer to navigate.

#region Property - Name
private string _name;
/// <summary>
/// Gets or sets the name of the customer.
/// </summary>
/// <remarks>
/// This should always be the full name of the customer in the format {First Name} {Last Name}.
/// </remarks>
/// <example>
/// customer.Name = "Joe Bloggs";
/// </example>
/// <seealso cref="Customer"/>
/// <value>
/// The name of the customer.
/// </value>
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}
#endregion

However, as far as the 'member type' (Methods, Properties, Constructors, Fields) go I feel it makes the code harder to navigate; however other people feel it makes it easier.

In the end it's a coding standard and religous. If you don't like it, don't use it one your personal projects. If you are required to use it due to a standard then use it.


问:
Flex box column not equal width with flex: 1
Hi I am trying to make flex columns equal width but it doesn't seem to be working with flex: 1.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

Box 1

Box 1 Flexbox 00000000

Box 2

Box 2 Flexbox 0

Box 3

Box 4 Flexbox 000

```

I want it to be the size of the flex col with the widest content.

答:
The flex: 1 isn't applied to flex item siblings.

It's applied to the children of those siblings (i.e., cousins).

Therefore, there's no association between the items with flex: 1, and there's no reason for them to be equal length.

Body:
Hi I am trying to make flex columns equal width but it doesn't seem to be working with flex: 1.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet" />

Box 1

Box 1 Flexbox 00000000

Box 2

Box 2 Flexbox 0

Box 3

Box 4 Flexbox 000

I want it to be the size of the flex col with the widest content.


问:
Extern struct builds on aCC (HP-UX) but not on macOS (Xcode)
I have the following headers file that I share across two source files:

sth.h:

```<code>#define NBALLS 10
#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}bots[NBOTS];

struct {
    float px, py, pz, vx, vy, vz;
}balls[NBALLS];
</code>```

That I consume the same way across two source files:
a.c:

```<code>#include "sth.h"
void makeBalls(void) {
    int i;
    srand(time(NULL));
    for (i=1;i<NBALLS;i++) {
        balls[i].px = MIN + randf()*(MAX-MIN);
        balls[i].py = MIN + randf()*(MAX-MIN);
        //pz[i] = 0.9;
        balls[i].pz = MIN + randf()*(MAX-MIN);
        balls[i].vx = -1.5+randf()*3.0;
        balls[i].vy = -1.5+randf()*3.0;
        balls[i].vz = -1.0+randf()*2.0;
    }
}
</code>```

and b.c:

```<code>#include "sth.h"
void makeBots(void) {
    int i;
    srand(time(NULL));
    for (i=1;i<NBOTS;i++) {
        bots[i].px = MIN + randf()*(MAX-MIN);
        bots[i].py = MIN + randf()*(MAX-MIN);
        //pz[i] = 0.9;
        bots[i].pz = MIN + randf()*(MAX-MIN);
        bots[i].vx = -1.5+randf()*3.0;
        bots[i].vy = -1.5+randf()*3.0;
        bots[i].vz = -1.0+randf()*2.0;
    }
}
</code>```

In HP-UX, it builds and runs fine.
In latest macOS, it complains of duplicate symbols.

If I make the following change in sth.h:

```<code>static struct {
    float px, py, pz, vx, vy, vz;
}bots[NBOTS];

static struct {
    float px, py, pz, vx, vy, vz;
}balls[NBALLS];
</code>```

It builds and runs fine. However, naturally, my program doesn't work.

I tried following the recommendation here:
Declaring an extern struct template in header file for global use in c files

But then Xcode complains that

```<code>bots[i].px = MIN + randf()*(MAX-MIN);
</code>```

is not a vector or pointer.

I'm very puzzled to why it works under HP-UX. I'm learning C (very beginner) and trying to make sure my code remains portable and also learning how to handle endianness issues.

Thanks, as always.

edit:
The change I made according to the recommendation, answering to the comment below:
sth.h:

```<code>#define NBALLS 10
#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}botsZ[NBOTS];

struct {
    float px, py, pz, vx, vy, vz;
}ballsZ[NBALLS];

extern struct botsZ bots;
extern struct ballsZ balls;
</code>```

Xcode returns on a.c and b.c: "Subscripted value is not an array, pointer, or vector" on every line of the function inside the for loop.

And why does aCC build it fine? I think MIPSPro also builds it ok (I will test once I return from trip)

答:
botsZ is an array of 2 instances of an anonymous struct defined like htis:

struct {
    float px, py, pz, vx, vy, vz;
};
```
<p>and here's the definition of that array, in the header file:</p>
<pre class="lang-c prettyprint-override"><code>#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}botsZ[NBOTS];
</code>```

The following

extern struct botsZ bots;
```
<p>declares an extern variable named <code>bots</code> with the type <code>struct botsZ</code>, but there is no such type. <code>botsZ</code> is an instance.</p>
<hr />
<p>Suggestion:</p>
<ul>
<li>Define the <code>struct</code>s and <code>typedef</code>s you need in the <code>.h</code> file</li>
<li><code>extern</code> declare the instances</li>
<li><em>define</em> instances in the <code>.c</code> file</li>
</ul>
<p>Example:</p>
<p><strong>sth.h</strong></p>
<pre class="lang-c prettyprint-override"><code>#ifndef STH_H
#define STH_H

#define NBALLS 10
#define NBOTS 2

typedef struct {
    float px, py, pz, vx, vy, vz;
} botsZ;

typedef struct {
    float px, py, pz, vx, vy, vz;
} ballsZ;

extern botsZ bots[NBOTS];
extern ballsZ balls[NBALLS];

#endif
</code>```

sth.c

#include "std.h"

botsZ bots[NBOTS] = {0};
ballsZ balls[NBALLS] = {0};
```

Body:
I have the following headers file that I share across two source files:

sth.h:

#define NBALLS 10
#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}bots[NBOTS];

struct {
    float px, py, pz, vx, vy, vz;
}balls[NBALLS];

That I consume the same way across two source files:
a.c:

#include "sth.h"
void makeBalls(void) {
    int i;
    srand(time(NULL));
    for (i=1;i<NBALLS;i++) {
        balls[i].px = MIN + randf()*(MAX-MIN);
        balls[i].py = MIN + randf()*(MAX-MIN);
        //pz[i] = 0.9;
        balls[i].pz = MIN + randf()*(MAX-MIN);
        balls[i].vx = -1.5+randf()*3.0;
        balls[i].vy = -1.5+randf()*3.0;
        balls[i].vz = -1.0+randf()*2.0;
    }
}

and b.c:

#include "sth.h"
void makeBots(void) {
    int i;
    srand(time(NULL));
    for (i=1;i<NBOTS;i++) {
        bots[i].px = MIN + randf()*(MAX-MIN);
        bots[i].py = MIN + randf()*(MAX-MIN);
        //pz[i] = 0.9;
        bots[i].pz = MIN + randf()*(MAX-MIN);
        bots[i].vx = -1.5+randf()*3.0;
        bots[i].vy = -1.5+randf()*3.0;
        bots[i].vz = -1.0+randf()*2.0;
    }
}

In HP-UX, it builds and runs fine.
In latest macOS, it complains of duplicate symbols.

If I make the following change in sth.h:

static struct {
    float px, py, pz, vx, vy, vz;
}bots[NBOTS];

static struct {
    float px, py, pz, vx, vy, vz;
}balls[NBALLS];

It builds and runs fine. However, naturally, my program doesn't work.

I tried following the recommendation here:
Declaring an extern struct template in header file for global use in c files

But then Xcode complains that

bots[i].px = MIN + randf()*(MAX-MIN);

is not a vector or pointer.

I'm very puzzled to why it works under HP-UX. I'm learning C (very beginner) and trying to make sure my code remains portable and also learning how to handle endianness issues.

Thanks, as always.

edit:
The change I made according to the recommendation, answering to the comment below:
sth.h:

#define NBALLS 10
#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}botsZ[NBOTS];

struct {
    float px, py, pz, vx, vy, vz;
}ballsZ[NBALLS];

extern struct botsZ bots;
extern struct ballsZ balls;

Xcode returns on a.c and b.c: "Subscripted value is not an array, pointer, or vector" on every line of the function inside the for loop.

And why does aCC build it fine? I think MIPSPro also builds it ok (I will test once I return from trip)

Body:
botsZ is an array of 2 instances of an anonymous struct defined like htis:

struct {
    float px, py, pz, vx, vy, vz;
};

and here's the definition of that array, in the header file:

#define NBOTS 2

struct {
    float px, py, pz, vx, vy, vz;
}botsZ[NBOTS];

The following

extern struct botsZ bots;

declares an extern variable named bots with the type struct botsZ, but there is no such type. botsZ is an instance.

Suggestion:

Define the structs and typedefs you need in the .h file

extern declare the instances

define instances in the .c file

Example:

sth.h

#ifndef STH_H
#define STH_H

#define NBALLS 10
#define NBOTS 2

typedef struct {
    float px, py, pz, vx, vy, vz;
} botsZ;

typedef struct {
    float px, py, pz, vx, vy, vz;
} ballsZ;

extern botsZ bots[NBOTS];
extern ballsZ balls[NBALLS];

#endif

sth.c

#include "std.h"

botsZ bots[NBOTS] = {0};
ballsZ balls[NBALLS] = {0};


问:
First login attempt works if it's correct, but if it's incorrect then other correct attempts don't work
```<code>void __fastcall TFormLogin::btnLoginClick(TObject *Sender)
{
    UnicodeString query = "select * from admin where korisnickoIme = '" + editKorisnicko->Text +
                     "' AND lozinka = '" + editLozinka->Text + "'";
    AnsiString ansiQuery = query;

    ADOQuery1->ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KnjiznicaManagement;Data Source=KUKICRO\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=KUKICRO;Use Encryption for Data=False;Tag with column collation when possible=False";
    ADOQuery1->SQL->Add(ansiQuery);

    ADOQuery1->Prepared = true;

    try
    {
        ADOQuery1->Active = true;
    }
    catch (EADOError& e)
    {
        MessageDlg("Error spajanja", mtError,
                      TMsgDlgButtons() << mbOK, 0);
        return;
    }

    TDataSource* Src = new TDataSource(this);
    Src->DataSet = ADOQuery1;
    Src->Enabled = true;

    if(Src->DataSet->RecordCount < 1){
        labelPrijava->Visible = true;
        ADOQuery1->Prepared = false;

        Src->Enabled = false;

        try{
            ADOQuery1->Active = false;
        }
        catch (EADOError& e){
            MessageDlg("Error odspajanja", mtError,
                  TMsgDlgButtons() << mbOK, 0);
        }
        return;
    }

    FormMain->labelUlogiran->Caption = Src->DataSet->FieldByName("korisnickoIme")->AsString;
    FormLogin->Close();
}
</code>```

Code from above is my OnClick button event code. It should simulate login from a database table "admin" that contains "korisnickoIme" in the username field and "lozinka" in the password field. When I type in the correct username and password, the first attempt works, but if I type in the wrong username and password and then the correct one, it doesn't work. When I go through with the debugger, the last if is true but it shouldn't be.

答:
This line:

```<code>ADOQuery1->SQL->Add(ansiQuery);
</code>```

adds the ansiQuery to the end of the SQL collection for ADOQuery. When you  click the button a second time, the new query is added to the end, but the original incorrect query is still at the start of the collection, so it is run first.

Solution: Clear out the collection on each button click. Add the following before the Add line:

```<code>ADOQuery1->SQL->Clear()
</code>```

Body:
void __fastcall TFormLogin::btnLoginClick(TObject *Sender)
{
    UnicodeString query = "select * from admin where korisnickoIme = '" + editKorisnicko->Text +
                     "' AND lozinka = '" + editLozinka->Text + "'";
    AnsiString ansiQuery = query;

    ADOQuery1->ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KnjiznicaManagement;Data Source=KUKICRO\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=KUKICRO;Use Encryption for Data=False;Tag with column collation when possible=False";
    ADOQuery1->SQL->Add(ansiQuery);

    ADOQuery1->Prepared = true;

    try
    {
        ADOQuery1->Active = true;
    }
    catch (EADOError& e)
    {
        MessageDlg("Error spajanja", mtError,
                      TMsgDlgButtons() << mbOK, 0);
        return;
    }

    TDataSource* Src = new TDataSource(this);
    Src->DataSet = ADOQuery1;
    Src->Enabled = true;

    if(Src->DataSet->RecordCount < 1){
        labelPrijava->Visible = true;
        ADOQuery1->Prepared = false;

        Src->Enabled = false;

        try{
            ADOQuery1->Active = false;
        }
        catch (EADOError& e){
            MessageDlg("Error odspajanja", mtError,
                  TMsgDlgButtons() << mbOK, 0);
        }
        return;
    }

    FormMain->labelUlogiran->Caption = Src->DataSet->FieldByName("korisnickoIme")->AsString;
    FormLogin->Close();
}

Code from above is my OnClick button event code. It should simulate login from a database table "admin" that contains "korisnickoIme" in the username field and "lozinka" in the password field. When I type in the correct username and password, the first attempt works, but if I type in the wrong username and password and then the correct one, it doesn't work. When I go through with the debugger, the last if is true but it shouldn't be.

Body:
This line:

ADOQuery1->SQL->Add(ansiQuery);

adds the ansiQuery to the end of the SQL collection for ADOQuery. When you  click the button a second time, the new query is added to the end, but the original incorrect query is still at the start of the collection, so it is run first.

Solution: Clear out the collection on each button click. Add the following before the Add line:

ADOQuery1->SQL->Clear()


问:
How to stack Text vertically with rotation using Jetpack Compose?
Trying to align text elements as shown in the image below:

How to do it in Jetpack Compose?

Normally I would use a Linear Layout with vertical orientation and TextViews with a rotation of 90. Wondering how to achieve this in compose.

答:
The solution with a custom modifier from How to show vertical text with proper size/layout in jetpack compose worked for me:

fun Modifier.vertical() = layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout(placeable.height, placeable.width) {
        placeable.place(
            x = -(placeable.width / 2 - placeable.height / 2),
            y = -(placeable.height / 2 - placeable.width / 2)
        )
    }
}
```
<p>Used as</p>
<pre class="lang-kotlin prettyprint-override"><code>Text(
    modifier = Modifier.vertical().rotate(-90f),
    text = "Vertical aligned element"
)
</code>```

Credits to Sergei S's answer.

Body:
The solution with a custom modifier from How to show vertical text with proper size/layout in jetpack compose worked for me:

fun Modifier.vertical() = layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout(placeable.height, placeable.width) {
        placeable.place(
            x = -(placeable.width / 2 - placeable.height / 2),
            y = -(placeable.height / 2 - placeable.width / 2)
        )
    }
}

Used as

Text(
    modifier = Modifier.vertical().rotate(-90f),
    text = "Vertical aligned element"
)

Credits to Sergei S's answer.


问:
Ffmpeg compilation fails due to undefined symbol _x264_encoder_open_112 for architecture x86_64
I am compiling ffmpeg on Snow Leopard from source. Using Macport is not an option since I have some custom modification in ffmpeg. The make commands are:

```<code>$ ./configure --enable-gpl --enable-libmp3lame --enable-static \
            --disable-shared --enable-libx264 --enable-pthreads \
            --disable-doc --enable-avfilter
$ make
</code>```

The error:

```<code>CC  ffplay.o
ffplay.c: In function ‘SDL_main’:
ffplay.c:3157: warning: assignment discards qualifiers from pointer target type
LD  ffplay_g
Undefined symbols for architecture x86_64:
  "_x264_encoder_open_112", referenced from:
      _X264_init in libavcodec.a(libx264.o)
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [ffplay_g] Error 1
</code>```

I have compiled libx264 from source, which went fine.

```<code>$ cd x264-snapshot-20101228-2245; ./configure && make && sudo make install
</code>```

... and it contains the symbol "_x264_encoder_open_112"

```<code>$ nm ./libx264.a | grep _x264_encoder_open_112
0000000000003ef0 T _x264_encoder_open_112
000000000000d7b0 S _x264_encoder_open_112.eh
</code>```

What might be going wrong?

答:
There was a conflict between similarly named libs from /opt/local/lib and /usr/lib. The former is maintained by Macport and the latter was my own dev area. Since I wanted to use the latter location, I had to remove / temporarily rename the ones in /opt/local/lib to force gcc to pick them up from /usr/lib

In your case, the paths may vary, but you get the idea.

If you have a cleaner way to achieve this, I am all ears

Body:
I am compiling ffmpeg on Snow Leopard from source. Using Macport is not an option since I have some custom modification in ffmpeg. The make commands are:

$ ./configure --enable-gpl --enable-libmp3lame --enable-static \
            --disable-shared --enable-libx264 --enable-pthreads \
            --disable-doc --enable-avfilter
$ make

The error:

CC  ffplay.o
ffplay.c: In function ‘SDL_main’:
ffplay.c:3157: warning: assignment discards qualifiers from pointer target type
LD  ffplay_g
Undefined symbols for architecture x86_64:
  "_x264_encoder_open_112", referenced from:
      _X264_init in libavcodec.a(libx264.o)
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make: *** [ffplay_g] Error 1

I have compiled libx264 from source, which went fine.

$ cd x264-snapshot-20101228-2245; ./configure && make && sudo make install

... and it contains the symbol "_x264_encoder_open_112"

$ nm ./libx264.a | grep _x264_encoder_open_112
0000000000003ef0 T _x264_encoder_open_112
000000000000d7b0 S _x264_encoder_open_112.eh

What might be going wrong?


问:
GCP VPC-Peering setup for CloudSQL fails with "INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid"
I am following this guide https://cloud.google.com/sql/docs/mysql/configure-private-services-access#gcloud to setup a VPC private peering connection so my GKE nodes can connect to the CloudSQL instance.

However when following the steps I receive an error that stops me from continuing.
Here are the steps I take:

#1 Check if addresses exist

➜  google-cloud-sdk gcloud compute addresses list
Listed 0 items.
```
<p>#2 Setup an new address range</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--network=projects/barbarus-game/global/networks/default
Created [https://www.googleapis.com/compute/v1/projects/barbarus-game/global/addresses/google-managed-services-default].
</code>```

#3 Assert success

➜  google-cloud-sdk gcloud compute addresses list
NAME                             ADDRESS/RANGE  TYPE      PURPOSE      NETWORK  REGION  SUBNET  STATUS
google-managed-services-default  10.77.0.0/16   INTERNAL  VPC_PEERING  default                  RESERVED
```
<p>#4 Continue with next stop of creating a private connection</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=projects/barbarus-game/global/networks/default \
--project=barbarus-game
ERROR: (gcloud.services.vpc-peerings.connect) INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid.
Help Token: Ae-hA1NzWbuVH5BSUV2Fn4IdzVTSjiWy2a10u_PyDO5qRIWbTeWzT7-2ybQxgtW_RojO1_XzicJW-NW80qKFglNlqLZKmym7S8A1mp_d2UGfwsP8
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: ?error_code=210001&resource_id=917163699144/global/networks/projects/barbarus-game
    type: googleapis.com
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: servicenetworking.googleapis.com
  metadata:
    resource_id: 917163699144/global/networks/projects/barbarus-game
  reason: RESOURCES_INVALID_RESOURCE_ID
</code>```

To verify I use the proper project id:

➜  google-cloud-sdk gcloud projects list
PROJECT_ID            NAME                  PROJECT_NUMBER
barbarus-game         Barbarus              917163699144
```
<p>Also additionally here is the VPC network description:</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud compute networks describe default
autoCreateSubnetworks: false
creationTimestamp: '2021-12-01T00:17:59.241-08:00'
description: Default network for the project
id: '1930871717275275608'
kind: compute#network
name: default
peerings:
- autoCreateRoutes: true
  exchangeSubnetRoutes: true
  exportCustomRoutes: false
  exportSubnetRoutesWithPublicIp: false
  importCustomRoutes: false
  importSubnetRoutesWithPublicIp: false
  name: servicenetworking-googleapis-com
  network: https://www.googleapis.com/compute/v1/projects/m3b741e040bfc8610p-tp/global/networks/servicenetworking
  state: ACTIVE
  stateDetails: '[2021-12-09T07:56:58.748-08:00]: Connected.'
routingConfig:
  routingMode: REGIONAL
selfLink: https://www.googleapis.com/compute/v1/projects/barbarus-game/global/networks/default
subnetworks:
- [...]
x_gcloud_bgp_routing_mode: REGIONAL
x_gcloud_subnet_mode: CUSTOM
</code>```

As you can see here the magic stops and I have no idea why. The project name is equivalent in the previous step (and any gcloud commands I've used before) so I have no idea why it fails.

Note
The error message is kind of confusing

```<code>The resource id 1071923183712/global/networks/projects/barbarus-game is invalid.
</code>```

I've never seen the network url to have projects path segment in between. It should look like this I expect (just how I passed the argument to the command):

```<code>071923183712/global/networks/barbarus-game
</code>```

答:
So it seems that the documentation is a bit wrong.

Instead of using this argument:

```<code>--network=projects/barbarus-game/global/networks/default
</code>```

I could get it to work with simply giving the network name with the project as a separate argument

```<code>--network=default
--project=barbarus
</code>```

Body:
I am following this guide https://cloud.google.com/sql/docs/mysql/configure-private-services-access#gcloud to setup a VPC private peering connection so my GKE nodes can connect to the CloudSQL instance.

However when following the steps I receive an error that stops me from continuing.
Here are the steps I take:

#1 Check if addresses exist

➜  google-cloud-sdk gcloud compute addresses list
Listed 0 items.

#2 Setup an new address range

➜  google-cloud-sdk gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--network=projects/barbarus-game/global/networks/default
Created [https://www.googleapis.com/compute/v1/projects/barbarus-game/global/addresses/google-managed-services-default].

#3 Assert success

➜  google-cloud-sdk gcloud compute addresses list
NAME                             ADDRESS/RANGE  TYPE      PURPOSE      NETWORK  REGION  SUBNET  STATUS
google-managed-services-default  10.77.0.0/16   INTERNAL  VPC_PEERING  default                  RESERVED

#4 Continue with next stop of creating a private connection

➜  google-cloud-sdk gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=projects/barbarus-game/global/networks/default \
--project=barbarus-game
ERROR: (gcloud.services.vpc-peerings.connect) INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid.
Help Token: Ae-hA1NzWbuVH5BSUV2Fn4IdzVTSjiWy2a10u_PyDO5qRIWbTeWzT7-2ybQxgtW_RojO1_XzicJW-NW80qKFglNlqLZKmym7S8A1mp_d2UGfwsP8
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: ?error_code=210001&resource_id=917163699144/global/networks/projects/barbarus-game
    type: googleapis.com
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: servicenetworking.googleapis.com
  metadata:
    resource_id: 917163699144/global/networks/projects/barbarus-game
  reason: RESOURCES_INVALID_RESOURCE_ID

To verify I use the proper project id:

➜  google-cloud-sdk gcloud projects list
PROJECT_ID            NAME                  PROJECT_NUMBER
barbarus-game         Barbarus              917163699144

Also additionally here is the VPC network description:

➜  google-cloud-sdk gcloud compute networks describe default
autoCreateSubnetworks: false
creationTimestamp: '2021-12-01T00:17:59.241-08:00'
description: Default network for the project
id: '1930871717275275608'
kind: compute#network
name: default
peerings:
- autoCreateRoutes: true
  exchangeSubnetRoutes: true
  exportCustomRoutes: false
  exportSubnetRoutesWithPublicIp: false
  importCustomRoutes: false
  importSubnetRoutesWithPublicIp: false
  name: servicenetworking-googleapis-com
  network: https://www.googleapis.com/compute/v1/projects/m3b741e040bfc8610p-tp/global/networks/servicenetworking
  state: ACTIVE
  stateDetails: '[2021-12-09T07:56:58.748-08:00]: Connected.'
routingConfig:
  routingMode: REGIONAL
selfLink: https://www.googleapis.com/compute/v1/projects/barbarus-game/global/networks/default
subnetworks:
- [...]
x_gcloud_bgp_routing_mode: REGIONAL
x_gcloud_subnet_mode: CUSTOM

As you can see here the magic stops and I have no idea why. The project name is equivalent in the previous step (and any gcloud commands I've used before) so I have no idea why it fails.

Note
The error message is kind of confusing

The resource id 1071923183712/global/networks/projects/barbarus-game is invalid.

I've never seen the network url to have projects path segment in between. It should look like this I expect (just how I passed the argument to the command):

071923183712/global/networks/barbarus-game

Body:
So it seems that the documentation is a bit wrong.

Instead of using this argument:

--network=projects/barbarus-game/global/networks/default

I could get it to work with simply giving the network name with the project as a separate argument

--network=default
--project=barbarus


问:
Rails Digital ocean Managed App `extract_credentials_provider': missing credentials
I'm swimming into Digital ocean managed app since a couple of weeks. SO far everything is working flawlessly. Today I successfully implemented Active storage with Spaces in my local environment using the following configuration:

storage.yml

```<code>test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

digital_ocean:
  service: S3
  endpoint: https://ams3.digitaloceanspaces.com
  access_key_id: <%= Rails.application.credentials.dig(:digital_ocean, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:digital_ocean, :secret_access_key) %>
  bucket: my-servername
  region: unused
</code>```

production.rb / development.rb

```<code>  config.active_storage.service = :digital_ocean
</code>```

Where digital_ocean config in credentials.yml looks like that (before being encrypted) through EDITOR=VI rails credentials:edit

```<code>digital_ocean:
  access_key_id: the_key
  secret_access_key: the_secret
...
</code>```

Locally, everything works like a charm, so I'm assuming it's not about the configuration itself but more about the deployment phase in DO managed app.

Digital ocean deployment:

```<code>[2022-02-13 23:34:45] /layers/heroku_ruby/gems/vendor/bundle/ruby/3.1.0/gems/aws-sigv4-1.4.0/lib/aws-sigv4/signer.rb:627:in `extract_credentials_provider': missing credentials, provide credentials with one of the following options: (Aws::Sigv4::Errors::MissingCredentialsError)
[2022-02-13 23:34:45]   - :access_key_id and :secret_access_key
[2022-02-13 23:34:45]   - :credentials
[2022-02-13 23:34:45]   - :credentials_provider
</code>```

As the whole S3/Space thing works perfectly locally through the same :access_key_id / :secret_access_key mechanism and I can interact with the space from localhost, i'm assuming this issue happens during deploy because rails is not able to decrypt credentials.yml.enc file, so I tried 3 things without success:

add a RAILS_MASTER_KEY env var at application level

adding master.key during build stage by adding the build command in DO settings with echo "${RAILS_MASTER_KEY}" > config/master.key

adding master.key on the run stage by prepending the run command such as echo "${RAILS_MASTER_KEY}" > config/master.key && rails server -p $PORT -e ${RAILS_ENV:-production}

I have been skimming through the internet for hours now and I cannot understand why it would go wrong even tho I'm following all the steps. Something I noticed is the RAILS_MASTER_KEY Env var does not seem to be available as it doesn't appear when I run echo $RAILS_MASTER_KEY in do console, even tho it appears to be set in App Spec env vars:

```<code>envs:
- key: RAILS_MASTER_KEY
</code>```

Any input infinitely appreciated

答:
Mkay, one have to add to digital ocean app ENV variables the folowing requirements of the aws-sdk-ruby gem (used by heroku during deployment), which are:

```<code>AWS_ACCESS_KEY_ID=<your DO space access key id>
AWS_SECRET_ACCESS_KEY= <your DO space secret access key>
</code>```

Hope it helps someone as it's frankly not obvious...

Body:
I'm swimming into Digital ocean managed app since a couple of weeks. SO far everything is working flawlessly. Today I successfully implemented Active storage with Spaces in my local environment using the following configuration:

storage.yml

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

digital_ocean:
  service: S3
  endpoint: https://ams3.digitaloceanspaces.com
  access_key_id: <%= Rails.application.credentials.dig(:digital_ocean, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:digital_ocean, :secret_access_key) %>
  bucket: my-servername
  region: unused

production.rb / development.rb

  config.active_storage.service = :digital_ocean

Where digital_ocean config in credentials.yml looks like that (before being encrypted) through EDITOR=VI rails credentials:edit

digital_ocean:
  access_key_id: the_key
  secret_access_key: the_secret
...

Locally, everything works like a charm, so I'm assuming it's not about the configuration itself but more about the deployment phase in DO managed app.

Digital ocean deployment:

[2022-02-13 23:34:45] /layers/heroku_ruby/gems/vendor/bundle/ruby/3.1.0/gems/aws-sigv4-1.4.0/lib/aws-sigv4/signer.rb:627:in `extract_credentials_provider': missing credentials, provide credentials with one of the following options: (Aws::Sigv4::Errors::MissingCredentialsError)
[2022-02-13 23:34:45]   - :access_key_id and :secret_access_key
[2022-02-13 23:34:45]   - :credentials
[2022-02-13 23:34:45]   - :credentials_provider

As the whole S3/Space thing works perfectly locally through the same :access_key_id / :secret_access_key mechanism and I can interact with the space from localhost, i'm assuming this issue happens during deploy because rails is not able to decrypt credentials.yml.enc file, so I tried 3 things without success:

add a RAILS_MASTER_KEY env var at application level

adding master.key during build stage by adding the build command in DO settings with echo "${RAILS_MASTER_KEY}" > config/master.key

adding master.key on the run stage by prepending the run command such as echo "${RAILS_MASTER_KEY}" > config/master.key && rails server -p $PORT -e ${RAILS_ENV:-production}

I have been skimming through the internet for hours now and I cannot understand why it would go wrong even tho I'm following all the steps. Something I noticed is the RAILS_MASTER_KEY Env var does not seem to be available as it doesn't appear when I run echo $RAILS_MASTER_KEY in do console, even tho it appears to be set in App Spec env vars:

envs:
- key: RAILS_MASTER_KEY

Any input infinitely appreciated

Body:
Mkay, one have to add to digital ocean app ENV variables the folowing requirements of the aws-sdk-ruby gem (used by heroku during deployment), which are:

AWS_ACCESS_KEY_ID=<your DO space access key id>
AWS_SECRET_ACCESS_KEY= <your DO space secret access key>

Hope it helps someone as it's frankly not obvious...


问:
Pandas - Getting a Key Error when the Key Exists
I'm trying to join two dataframes in Pandas.

The first frame is called Trades and has these columns:

```<code>TRADE DATE
ACCOUNT
COMPANY
COST CENTER
CURRENCY
</code>```

The second frame is called Company_Mapping and has these columns:

```<code>ACTUAL_COMPANY_ID
MAPPED_COMPANY_ID
</code>```

I'm trying to join them with this code:

```<code>trade_df = pd.merge(left=Trades, right = Company_Mapping, how = 'left', left_on = 'COMPANY', right_on = 'ACTUAL_COMPANY_ID'
</code>```

This returns:

```<code>KeyError: 'COMPANY'
</code>```

I've double checked the spelling and COMPANY is clearly in Trades, and I have no clue what would cause this.

Any ideas?

Thanks!

答:
Just in case someone have the same problem, sometimes you need to transpose your dataframe:

    import pandas as pd

    df = pd.read_csv('file.csv')
    # A  B  C
    # -------
    # 1  2  3
    # 4  5  6

    new_df = pd.DataFrame([df['A'], df['B']])
    # A | 1 4
    # B | 2 5

    new_df['A'] # KeyError

    new_df = new_df.T
    # A B
    # ---
    # 1 2
    # 4 5

    new_df['A'] # KeyError
    # A
    # -
    # 1
    # 4

```

Body:
I'm trying to join two dataframes in Pandas.

The first frame is called Trades and has these columns:

TRADE DATE
ACCOUNT
COMPANY
COST CENTER
CURRENCY

The second frame is called Company_Mapping and has these columns:

ACTUAL_COMPANY_ID
MAPPED_COMPANY_ID

I'm trying to join them with this code:

trade_df = pd.merge(left=Trades, right = Company_Mapping, how = 'left', left_on = 'COMPANY', right_on = 'ACTUAL_COMPANY_ID'

This returns:

KeyError: 'COMPANY'

I've double checked the spelling and COMPANY is clearly in Trades, and I have no clue what would cause this.

Any ideas?

Thanks!


问:
Comparing elements at different indices in array Swift
In swift, I want to compare two different indexes in the same array. Right now, My code is something like:

```<code>var myArray:[String] = ["1" , "1", "2"]

for i in myArray{
     if(myArray[i] == myArray[i + 1]){
     // do something
     }
}
</code>```

From this, I get an error:

```<code>Cannot convert value of type 'String' to expected argument type 'Int'
</code>```

How do I go about fixing this?

答:
Not a direct answer to your question but if what you want is to compare adjacent elements in a collection what you need is to zip the collection with the same collection dropping the first element:

```<code>let array = ["1" , "1", "2"]

for (lhs,rhs) in zip(array, array.dropFirst()) {
     if lhs == rhs {
         print("\(lhs) = \(rhs)")
         print("do something")
     } else {
         print("\(lhs) != \(rhs)")
         print("do nothing")
     }
}
</code>```

This will print:

1 = 1

do something

1 != 2

do nothing

Body:
In swift, I want to compare two different indexes in the same array. Right now, My code is something like:

var myArray:[String] = ["1" , "1", "2"]

for i in myArray{
     if(myArray[i] == myArray[i + 1]){
     // do something
     }
}

From this, I get an error:

Cannot convert value of type 'String' to expected argument type 'Int'

How do I go about fixing this?

Body:
Not a direct answer to your question but if what you want is to compare adjacent elements in a collection what you need is to zip the collection with the same collection dropping the first element:

let array = ["1" , "1", "2"]

for (lhs,rhs) in zip(array, array.dropFirst()) {
     if lhs == rhs {
         print("\(lhs) = \(rhs)")
         print("do something")
     } else {
         print("\(lhs) != \(rhs)")
         print("do nothing")
     }
}

This will print:

1 = 1

do something

1 != 2

do nothing


问:
Movement controls using "WASD" in JavaScript
I am making a game right now, and the current movement is really choppy because when you press a button e.g. 'W'. it will take away from the 'top' position to give it the effect of moving up.

I was hoping to use 'this.x' and 'this.y' but I don't know much about it.

This is the current code I have:

```<code>window.addEventListener('keydown', (e) =>{
switch(e.key){
        case 'a':
        player.style.left = parseInt(player.style.left) - movePlayer + 'px';
        break;
        case 'd':
        player.style.left = parseInt(player.style.left) + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = parseInt(player.style.top) - movePlayer + 'px';
        break;
        case 's':
        player.style.top = parseInt(player.style.top) + movePlayer + 'px';
        break;
         }
   });
</code>```

答:
Try this by using window.getComputedStyle.getPropertyValue

You could still replace it with player.style.left and player.style.top if you think it is necessary, but I highly suggest you to use window.getComputedStyle.getPropertyValue since this is always the stable way to do it.

Check more here

let player = document.getElementById('player')
let movePlayer = 10
window.addEventListener('keydown', (e) =>{
let leftpos = parseInt(window.getComputedStyle(player).getPropertyValue("left"))
let toppos = parseInt(window.getComputedStyle(player).getPropertyValue("top"))
switch(e.key){
        case 'a':
        player.style.left = leftpos - movePlayer + 'px';
        break;
        case 'd':
        player.style.left =leftpos + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = toppos - movePlayer + 'px';
        break;
        case 's':
        player.style.top =toppos + movePlayer + 'px';
        break;
         }
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#player{
width:100px;
height:100px;
background-color:black;
position:absolute;
}</code>```

```

Body:
I am making a game right now, and the current movement is really choppy because when you press a button e.g. 'W'. it will take away from the 'top' position to give it the effect of moving up.

I was hoping to use 'this.x' and 'this.y' but I don't know much about it.

This is the current code I have:

window.addEventListener('keydown', (e) =>{
switch(e.key){
        case 'a':
        player.style.left = parseInt(player.style.left) - movePlayer + 'px';
        break;
        case 'd':
        player.style.left = parseInt(player.style.left) + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = parseInt(player.style.top) - movePlayer + 'px';
        break;
        case 's':
        player.style.top = parseInt(player.style.top) + movePlayer + 'px';
        break;
         }
   });

Body:
Try this by using window.getComputedStyle.getPropertyValue

You could still replace it with player.style.left and player.style.top if you think it is necessary, but I highly suggest you to use window.getComputedStyle.getPropertyValue since this is always the stable way to do it.

Check more here

let player = document.getElementById('player')
let movePlayer = 10
window.addEventListener('keydown', (e) =>{
let leftpos = parseInt(window.getComputedStyle(player).getPropertyValue("left"))
let toppos = parseInt(window.getComputedStyle(player).getPropertyValue("top"))
switch(e.key){
        case 'a':
        player.style.left = leftpos - movePlayer + 'px';
        break;
        case 'd':
        player.style.left =leftpos + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = toppos - movePlayer + 'px';
        break;
        case 's':
        player.style.top =toppos + movePlayer + 'px';
        break;
         }
   });

#player{
width:100px;
height:100px;
background-color:black;
position:absolute;
}

<div id='player'><div>


问:
DirectX - when to use instancing and when not?
I'm making an application using directx 11. I wanted to make use of instancing in the first place, so I've organized my whole pipeline to always work with instancing for simplicity. This means that currently if I want to draw a single occurrence of a geometry in my scene it would still go through instanced rendering.

My question(s) is(are) what overhead does instancing introduce? Is this approach a bad practice in general? If so, is there a rule on how to decide when it's beneficial to use instancing and when not?

One similar question that did not help me: What overhead is associated with instanced rendering?

答:
Over the years the "knee" in the performance graph of when hardware instancing is a win vs. just drawing multiple times has changed. In the early days of hardware instancing, it was almost never a win on those first generation cards. As GPU's have evolved and put more hardware support in to make this faster, it's improved significantly.

For DirectX 12 class hardware (minimum Direct3d Hardware Feature level 11.0), you can count on instancing being a good win for drawing the same objects thousands of times. If you are talking about tens of times, then it's going to depend on many factors you can really only account for by running performance trials.

Specifically for 'point-sprites' i.e. particles systems for special effects, there are a number of different approaches. For Xbox One class GPU hardware, just drawing a bunch for vertices is very fast and vertex hardware instancing only wins over it for huge numbers of particles (although it will use less VRAM so that may be a consideration). For "DirectX 12 Ultimate" class GPU hardware, a Mesh Shader is actually the fastest way to draw particle systems. See the PointSprites sample on GitHub.


问:
Web Api Not recognizing RestClient framework
I am trying to do a test post to a 3rd party web api.
The code how to post was provided by the documentation from 3rd party.

```<code>'RestClient' is a namespace but is used like a type
The type or namespace name 'RestRequest' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'IRestResponse' could not be found (are you missing a using directive or an assembly reference?)
The name 'ParameterType' does not exist in the current context
The name 'Method' does not exist in the current context
</code>```

The method I am working with:

```<code>public void CreatePanelists (Newtonsoft.Json.Linq.JObject data)
{

    Parameters parameters = JsonConvert.DeserializeObject<Parameters>(data.ToString())
    IList<Panelist> panelistList = parameters.panelists;
    string id = parameters.id;

    var client = new RestClient("https://3rdparty.com/v2/events/5893/atendees");
    var request = new RestRequest(Method.POST);
    request.AddHeader("content-type", "application/json");
    request.AddHeader("authorization", "Bearer vJRMZ92lsOE1sKGVF7_4zCezTjxO2RoFeOVGULSJS2_dRhgU5QfZeKqGaoS0ogPv0WISEuZ1RcNzJDUsv27uGA");
    request.AddParameter("application/json", "{\"attendees\":[{\"name\":\"Mary\",\"email\":\"maryjkdfdsgfshdgf@jdfdkjdglfk.jkfgdj\"},{\"name\":\"Mike\",\"email\":\"dfdsgfsdhf@jkgfdgfkdhgfdjg.fkjgdf\"}]}", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
}
</code>```

I installed RestClient 4.0.0 but that did not remove the errors.

I am not using .Net not .net Core. What am I missing?

First time developing this type of project, please pardon if my technical language is not correct.

Your help is much appreciated.

Thank you,
Erasmo

UPDATE - I was able to install RestSharp Version 106.11.4.0, and RestClient Version 2.5.0.6.

The only error that persists is

```<code>'RestClient' is a namespace but is used like a type
</code>```

答:
The RestSharp code you're using is out of date for .Net Full Framework < 5.0.

The new RestSharp syntax looks like this: https://restsharp.dev/intro.html#basic-usage

```<code>using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.twitter.com/1.1");
client.Authenticator = new HttpBasicAuthenticator("username", "password");

var request = new RestRequest("statuses/home_timeline.json", DataFormat.Json);

var timeline = await client.GetAsync<HomeTimeline>(request, cancellationToken);
</code>```

I've raised a support request #98090 to PostMan to update the RestSharp Code Generated.

Body:
I am trying to do a test post to a 3rd party web api.
The code how to post was provided by the documentation from 3rd party.

'RestClient' is a namespace but is used like a type
The type or namespace name 'RestRequest' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'IRestResponse' could not be found (are you missing a using directive or an assembly reference?)
The name 'ParameterType' does not exist in the current context
The name 'Method' does not exist in the current context

The method I am working with:

public void CreatePanelists (Newtonsoft.Json.Linq.JObject data)
{

    Parameters parameters = JsonConvert.DeserializeObject<Parameters>(data.ToString())
    IList<Panelist> panelistList = parameters.panelists;
    string id = parameters.id;

    var client = new RestClient("https://3rdparty.com/v2/events/5893/atendees");
    var request = new RestRequest(Method.POST);
    request.AddHeader("content-type", "application/json");
    request.AddHeader("authorization", "Bearer vJRMZ92lsOE1sKGVF7_4zCezTjxO2RoFeOVGULSJS2_dRhgU5QfZeKqGaoS0ogPv0WISEuZ1RcNzJDUsv27uGA");
    request.AddParameter("application/json", "{\"attendees\":[{\"name\":\"Mary\",\"email\":\"maryjkdfdsgfshdgf@jdfdkjdglfk.jkfgdj\"},{\"name\":\"Mike\",\"email\":\"dfdsgfsdhf@jkgfdgfkdhgfdjg.fkjgdf\"}]}", ParameterType.RequestBody);
    IRestResponse response = client.Execute(request);
}

I installed RestClient 4.0.0 but that did not remove the errors.

I am not using .Net not .net Core. What am I missing?

First time developing this type of project, please pardon if my technical language is not correct.

Your help is much appreciated.

Thank you,
Erasmo

UPDATE - I was able to install RestSharp Version 106.11.4.0, and RestClient Version 2.5.0.6.

The only error that persists is

'RestClient' is a namespace but is used like a type

Body:
The RestSharp code you're using is out of date for .Net Full Framework < 5.0.

The new RestSharp syntax looks like this: https://restsharp.dev/intro.html#basic-usage

using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api.twitter.com/1.1");
client.Authenticator = new HttpBasicAuthenticator("username", "password");

var request = new RestRequest("statuses/home_timeline.json", DataFormat.Json);

var timeline = await client.GetAsync<HomeTimeline>(request, cancellationToken);

I've raised a support request #98090 to PostMan to update the RestSharp Code Generated.


问:
Error on uploading app to play console- "Upload failed The Android App Bundle was not signed ."
When I upload the signed bundle of the app to play store it gives an error-
"Upload failed
The Android App Bundle was not signed."</p>

答: like said above, make debuggable be false , and also , when generating signed bundle , be sure you pressed the "export encrypted key for enrolling..." .</p>


问:
What is the effect of instantiating the object from the subclass?
```<code>    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class SubClass : BaseClass
    {
        public decimal Price { get; set; }
    }
</code>```
```<code>    BaseClass o1 = new SubClass();
    SubClass o2 = new SubClass();

    Console.WriteLine(o1.GetType().Name);
    Console.WriteLine(o2.GetType().Name);
</code>```

Outputs are

```<code>    SubClass
    SubClass
</code>```

What is the main difference between o1 and o2? In which cases is it necessary to define an object with BaseClass and instantiate it with SubClass?

答:
In the context of your question the type of the variable is irrelevant. For a more common example, you can have an interface:

```<code>interface IExample { ... }
</code>```

and a class that implements the interface:

```<code>class Example : IExample { ... }
</code>```

Obviously, if you manually instantiating the variable, or if you are using DI, it would have the class; but you typically assign it to the interface type:

```<code>IExample ex = new Example();
</code>```

But any reflection tool will show you actual class.

Body:
    public class BaseClass
    {
        public string Name { get; set; }
    }

    public class SubClass : BaseClass
    {
        public decimal Price { get; set; }
    }

    BaseClass o1 = new SubClass();
    SubClass o2 = new SubClass();

    Console.WriteLine(o1.GetType().Name);
    Console.WriteLine(o2.GetType().Name);

Outputs are

    SubClass
    SubClass

What is the main difference between o1 and o2? In which cases is it necessary to define an object with BaseClass and instantiate it with SubClass?

Body:
In the context of your question the type of the variable is irrelevant. For a more common example, you can have an interface:

interface IExample { ... }

and a class that implements the interface:

class Example : IExample { ... }

Obviously, if you manually instantiating the variable, or if you are using DI, it would have the class; but you typically assign it to the interface type:

IExample ex = new Example();

But any reflection tool will show you actual class.


问:
Add a 1-hour expiration to the current time/date
```<code>//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration
</code>```

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

```<code>$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");
</code>```

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

答:
Why don't you just check if the current hour is 23 ? Something like (I'm not sure about the PHP syntax of ternary operator though) :

```<code>$onehour = date("G) > 22 ? 0 : date("G) + 1;
</code>```

Then you also want to change the current day, and check if you change year.

Body:
//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

Body:
Why don't you just check if the current hour is 23 ? Something like (I'm not sure about the PHP syntax of ternary operator though) :

$onehour = date("G) > 22 ? 0 : date("G) + 1;

Then you also want to change the current day, and check if you change year.


问:
Move file and directory into a sub-directory along with commit history
How can I move a directory and files to a sub-directory along with commit history?

For example:

Source directory structure: [project]/x/[files & sub-dirs]

Target directory structure: [project]/x/p/q/[files & sub-dirs]

答: My own suggestion: git fast-export then edit the export file, then git fast-import.