问:
MongoDB query based on count of embedded document
Suppose I have:

```<code>Order: {_id: ..., items: [...]}
</code>```

How to filter orders which have item number greater than 5?

答:
To see if the length is greater than 5, you can test if a 6th element exists:

```<code>db.orders.find({"items.6": {$exists: true}})
</code>```

This is much more efficient than using $where.

Body:
Suppose I have:

Order: {_id: ..., items: [...]}

How to filter orders which have item number greater than 5?

Body:
To see if the length is greater than 5, you can test if a 6th element exists:

db.orders.find({"items.6": {$exists: true}})

This is much more efficient than using $where.


来源: stackexchange

问:
Trouble to only move files and not directories
Trying to move files from logfile_directory to tmp_directory in blocks of 7 using random.sample.
If there are less than 7 files in the folder it will just move the remainder of the files. However when I try and move less that 7 files I get an error as the tmp_folder is trying to copy into itself.

Tried using glob.glob command but can't get that to work either. Not sure what I'm doing wrong to just move the files and not folder. Any help would be appreciated.

Running the same code on a different machine and getting the below message where as before the error message was related to copying the tmp_folder into itself. Nothing special about this file it's creating the error on so don't know why I'm now getting this.

Message=[WinError 5] Access is denied: 'c:\securelog_test\bdlog.txt'
  Source=C:\Users\jarra\source\repos\archive_test\archive_test.py
  StackTrace:
  File "\archive_test.py", line 72, in
    shutil.move(path, tmp_folder)

logfile_directory = 'c:\\securelog_test\\'
archive_folder = 'c:\\securelog_archive\\'
workfiles_folder = 'c:\\securelog_workfiles\\'
tmp_folder = 'c:\\securelog_test\\temp\\'
completed_folder = 'c:\\securelog_test\\completed\\'

#count how many files are in the log file folder
onlyfiles = [f for f in listdir(logfile_directory) if isfile(join(logfile_directory, f))]
print('-----------------')
print (len(onlyfiles))

if len(onlyfiles) > 7:
    #move 7 random files to the temp folder for archiving
    files = os.listdir(logfile_directory)
    for fileName in random.sample(files, min(len(files), 8)):
        path = os.path.join(logfile_directory, fileName)
        shutil.move(path, tmp_folder)
else:
    #if there are less than 7 files move them
    #for file in glob.glob(logfile_directory):
    #    shutil.move(file, tmp_folder)
    for fileName in os.listdir(logfile_directory):
        path = os.path.join(logfile_directory, fileName)
        shutil.move(path, tmp_folder)
```

答: check the os current directory path try to print it for each iteration you get where its getting wrong.</p>

ContentLicense: CC BY-SA 4.0


问:
How pass data from manifest-registered BroadcastReceiver to activity?
I have been looking for solutions for this, but there doesn't seem to be any.  I have a fairly unique use case that I need to be able to pass data between two different apps even when one app isn't active, therefore my BroadcastReceivers need to be registered in the manifest.  However, what I can't seem to figure out is how I pass the received data from my manifest-registered BroadcastReceivers to my activities.  Most of the examples are using dynamically registered BroadcastReceivers, which will not work in my use case.</p>

答: Even though it is hard to say without knowing what you are trying to accomplish, two solutions come into mind; one being receiving with permissions and the other is WorkManager to schedule work regardless of your user is using your app or exited your app.</p>


问:
How to connect an ASP.NET site in IIS to its SQL Server database
I am running my ASP.NET application in IIS as a site. When I go to login to the website through the SQL Server database, it returns an error. I can run the web application through Visual Studio using IIS Express without any issues.

I have looked at tutorials saying to check my connection string.

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VideoStore-20190515111127.mdf;Initial Catalog=aspnet-VideoStore-20190515111127;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>
```

This is the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

I use the Server Explorer to look at the Data Connections>Default Connection (Video Store) to see the database in Visual Studio. Can someone point me in the right direction?

答:
Firstly you have to confirm both IIS and Sql server are running in the same machine or not,
if running in the same you need to change the connection string related to local DB or windows authendication.

if not running in the same machine use like

```<code><add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />
</code>```

and recheck the DB name you enterd and Server details.

I hope connection string you provided is invalid,sorry if i am wrong.

still your facing problem please go through
Connecting to local SQL Server database using C#

Body:
I am running my ASP.NET application in IIS as a site. When I go to login to the website through the SQL Server database, it returns an error. I can run the web application through Visual Studio using IIS Express without any issues.

I have looked at tutorials saying to check my connection string.

<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VideoStore-20190515111127.mdf;Initial Catalog=aspnet-VideoStore-20190515111127;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>

This is the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.)

I use the Server Explorer to look at the Data Connections>Default Connection (Video Store) to see the database in Visual Studio. Can someone point me in the right direction?

Body:
Firstly you have to confirm both IIS and Sql server are running in the same machine or not,
if running in the same you need to change the connection string related to local DB or windows authendication.

if not running in the same machine use like

<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />

and recheck the DB name you enterd and Server details.

I hope connection string you provided is invalid,sorry if i am wrong.

still your facing problem please go through
Connecting to local SQL Server database using C#


问:
How to update a users properties in Azure AD B2C programmatically?
I created a Azure AD B2C Tenant. I registered an application which is an Angular application. I updated the Angular application with the ClientId and other credentials to bring up a new sign in / register policy popup dialog. It is working fine and I can see the user in the Azure AD B2C directory.

I want to access that user and update a custom property that I added called Membership to ReadOnly. The Azure Portal UI does not show this custom property to be updated though it shows other properties like First Name, Last Name etc...

The documentation here says that I can programmatically update the properties of a user. This document is updated in 2017 and not up-to-date. I don't see any option in the Application in the Azure AD B2C Tenant to add permissions to CRUD operations on the user.

How can I update the properties of a user programmatically if I can't modify though the UI?

*************** UPDATE *************

I have a default directory and another directory where the B2C tenant lives. The billing of the B2C tenant is associated with the default directory. The application registrations in the default directory show some unknown applications that I don't know. The other non-default directory shows the applications. But I see an error saying I have to use the Application Registrations Legacy to see them. When I go to the Application Registrations Legacy, I don't see the app that I registered and I see b2c-extensions-app. Do not modify. Used by AADB2C for storing user data. This app has a settings menu.

The following steps are incorrect. I don't see any Settings menu.

The document says (1) Continuing in the Azure portal's App Registrations menu, select your application. (2) In the Settings menu, click on Required permissions.

答:
That article is correct and points to a good GitHub utility that shows you how to do this.

Refer to the "Use custom attributes" section.

Note that custom attributes (called extension attributes) have the form:

extension_55dc0861f9a44eb999e0a8a872204adb_Jersey_Number

when updating programmatically.

The GUID is the ID of the B2C Extensions Application.

You can get this from the utility via:

b2c Get-B2C-Application

"Get the B2C Extensions Application in your B2C directory, so you can retrieve the objectId and pass it to other commands".

Or you can access the application directly in the Azure AD section of the B2C portal.


问:
MKAnnotation - adding url
I'm working through mayurbirari's sample code to generate a mapkit view, I want to add a url to the popup.  I've tried to understand the apple reference to subclass but TBH it just isnt going it.

I need to create a subclass that can have additional variable added to it as MKANNOTATION is core file and cannot be changed - therefore how do I do it?? I'm confused about how to set it up.

the code can be found here --> http://mayurbirari.wordpress.com/2011/02/07/how-to-access-mkmapkit-in-iphone/

if someone could show me the example of the subclass with URL added to it, it would probably sink in, but all the examples I've found seem to be over complicated.

答:
MKAnnotation is a protocol that you have to adopt in your own class -- whichever class you're using to represent an annotation object. This is often a class that's part of your data model. For example, you might have a Person class and want to show instances of Person on a map. You'd adopt MKAnnotation in Person. It's easy to use properties for this:

```<code>@interface Person : NSObject <MKAnnotation>
{
   //...
}
//...
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *subtitle;
@end
</code>```

And then implement the methods from MKAnnotation in your class:

```<code>@implementation Person

@synthesize coordinate;
@synthesize title;
@synthesize subtitle;

//...various methods of Person...

@end
</code>```

Now you can add instances of Person to the map as annotations.

ContentLicense: CC BY-SA 3.0

Title: MKAnnotation - adding url

Body:
MKAnnotation is a protocol that you have to adopt in your own class -- whichever class you're using to represent an annotation object. This is often a class that's part of your data model. For example, you might have a Person class and want to show instances of Person on a map. You'd adopt MKAnnotation in Person. It's easy to use properties for this:

@interface Person : NSObject <MKAnnotation>
{
   //...
}
//...
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *subtitle;
@end

And then implement the methods from MKAnnotation in your class:

@implementation Person

@synthesize coordinate;
@synthesize title;
@synthesize subtitle;

//...various methods of Person...

@end

Now you can add instances of Person to the map as annotations.


问:
How to add/mix Vanilla Javascript with ReactJS
I'm new to React. At the moment I manage to update my simple website from standard HTML, CSS, JS to React, SASS, JSX and so on. The problem I have is that there is a canvas tag where I run an animation made in Vanilla Javascript using the Paperjs library, but I have not idea on how to implement my current JS animation to my React project.

This is what I have in my body tag:

```<code><canvas id='paperjs-canvas' resize></canvas>
<script src="js/libs/paper-full.min.js"></script>
<script src="js/jellies/jelly.min.js"></script>
<script src="js/jellies/tentacle.min.js"></script>
<script src="js/jellies/paper-jellies.min.js"></script>
</code>```

This is just a simple background animation, there is no interaction with DOM elements.

I wander if it would be possible to implement my current code in to React as is, and if so, how?

Any help will be much appreciated.

答:
React needs to be in full control of its DOM branch (usually a
 under ).

As long as you put the <canvas /> outside of the React's DOM branch, you won't have any problem with it.

Example:

```<code><html>
  <head>...</head>
  <body>
    <div id="root"></div> <!-- React branch -->
    <canvas id="paperjs-canvas" resize></canvas> <!-- Here you are in control -->
    ...
  </body>
</html>
</code>```

Body:
I'm new to React. At the moment I manage to update my simple website from standard HTML, CSS, JS to React, SASS, JSX and so on. The problem I have is that there is a canvas tag where I run an animation made in Vanilla Javascript using the Paperjs library, but I have not idea on how to implement my current JS animation to my React project.

This is what I have in my body tag:

<canvas id='paperjs-canvas' resize></canvas>

This is just a simple background animation, there is no interaction with DOM elements.

I wander if it would be possible to implement my current code in to React as is, and if so, how?

Any help will be much appreciated.

Body:
React needs to be in full control of its DOM branch (usually a <div id="root"/> under <body>).

As long as you put the <canvas /> outside of the React's DOM branch, you won't have any problem with it.

Example:

<html>
  <head>...</head>
  <body>
    <div id="root"></div> <!-- React branch -->
    <canvas id="paperjs-canvas" resize></canvas> <!-- Here you are in control -->
    ...
  </body>
</html>


问:
A kafka record is acknowledged but no data returned to consumer
There is a Kafka (version 2.2.0) cluster of 3 nodes. One node becomes artificially unavailable (network disconnection). Then we have the following behaviour:

We send a record to a producer with the given topic-partition (to the specific partition, let's say #0).

We receive a record metadata from the producer what confirms that it has been acknowledged.

Immediately after that we poll a consumer assigned to the same topic-partition and an offset taken from the record's metadata. The poll timeout was set to 30 seconds. No data is returned (an empty set is returned).

This happens inconsistently from time to time (under described circumstances with one Kafka node failure).

Essentially my question is: should data be immediately available for consumers ones it is acknowledged? What the reasonable timeout for that if not?

UPD: some configuration details:

number of partitions for the topic: 1

default replication factor: 3

sync replication factor: 2

acks for producer: all

答:
The default setting of acks on the producer is 1. This means the producer waits for the acknowledgement from the leader replica only. If the leader dies right after acknowledging, the message won't be delivered.

Should data be immediately available for consumers? Yes, in general there should be very little lag per default, should be effectively on the milliseconds range per default and without load.

If you want to make sure that a message can't be lost, you have to configure the producer to "acks=all" in addition to min.insync.replicas=2. This will make sure all in sync replicas acknowledge the message, and that minimum 2 nodes do. So you are still allowed to lose one node and be fine. Lose 2 nodes and you won't be able to send, but even then messages won't be lost.


问:
Menu Button/Text in Wordpress Misaligned with Sticky Menu
I have created a CSS button on the main menu of a site that I adopted (did not design myself) and the button looks great when at the top of the page. However, once I scroll down and the menu compresses into the sticky menu, the text misaligns with the button background. The text drops down to below the button background and I'm not sure how to fix that.

I've tried adjusting the padding, instead of creating a set height & width to the button, but the padding wasn't working on the right and left side so I went back to the static size. My current button code is below.

```<code>.button-menu {
background-color: #0051a3;
width: 100px;
height: 30px;
text-align: center;
vertical-align: central;
border-radius: 10px 10px 10px 10px;
    }
.button-menu:hover {
  background: #fbb714;
  text-decoration: none;
  }
</code>```

I just want the text to be centered within the button background in the vertical alignment when the menu is in scrolling mode.

答:
Your button has a fixed width and height but the text inside of it is going to drop down into multiple lines as that's a browser default behavior. You could try playing around with

```<code>.button-menu{ word-wrap: break-word; }
</code>```

or maybe also try using a min-width and min-height instead of setting the width and height.

Body:
I have created a CSS button on the main menu of a site that I adopted (did not design myself) and the button looks great when at the top of the page. However, once I scroll down and the menu compresses into the sticky menu, the text misaligns with the button background. The text drops down to below the button background and I'm not sure how to fix that.

I've tried adjusting the padding, instead of creating a set height & width to the button, but the padding wasn't working on the right and left side so I went back to the static size. My current button code is below.

.button-menu {
background-color: #0051a3;
width: 100px;
height: 30px;
text-align: center;
vertical-align: central;
border-radius: 10px 10px 10px 10px;
    }
.button-menu:hover {
  background: #fbb714;
  text-decoration: none;
  }

I just want the text to be centered within the button background in the vertical alignment when the menu is in scrolling mode.

Body:
Your button has a fixed width and height but the text inside of it is going to drop down into multiple lines as that's a browser default behavior. You could try playing around with

.button-menu{ word-wrap: break-word; }

or maybe also try using a min-width and min-height instead of setting the width and height.


问:
Node.JS: Cannot connect to Microsoft Azure Database when using Sequelize
I am trying to connect Azure database using the express + Sequelize. I cannot get connection to work.

I have modified the database.json connection file like this:

```<code>"development": {
    "username": "XXX",
    "password": "XXX",
    "database": "XXX",
    "host": "XXX",
    "dialect": "mssql",
    "port": 1433,
    "dialectOptions": {
      "encrypt": true
    }
  }
</code>```

I try to connect with sequelizer like this

```<code>  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}
</code>```

I get error message:
https://i.imgur.com/FQdZCeZ.png

If I directly change Sequelize connection without using the JSON file and connect it like this:

```<code>sequelize = new Sequelize('XXX', 'XXX', 'XXX', { host: 'XXX', dialect: 'mssql', dialectOptions: { options: { encrypt: true } } });
</code>```

I get error about Username being empty:
https://i.imgur.com/JbkOgIU.png

I have tried connection with MySql and everything works in there. Problems are only when connecting to Azure database. Any help would be great guys! Thank you.

答:
I connected as below. It works. </p>

```<code>   const sequelize = new Sequelize(database, username, password, {
  host: config.databaseHost,
  Port: config.databasePort, // 49175 // 1433
  dialect: 'mssql',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
  dialectOptions: {
    instanceName: 'SQLEXPRESS',
    requestTimeout: 60000
  }
});
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });
</code>```

Body:
I am trying to connect Azure database using the express + Sequelize. I cannot get connection to work.

I have modified the database.json connection file like this:

"development": {
    "username": "XXX",
    "password": "XXX",
    "database": "XXX",
    "host": "XXX",
    "dialect": "mssql",
    "port": 1433,
    "dialectOptions": {
      "encrypt": true
    }
  }

I try to connect with sequelizer like this

  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

I get error message:
https://i.imgur.com/FQdZCeZ.png

If I directly change Sequelize connection without using the JSON file and connect it like this:

sequelize = new Sequelize('XXX', 'XXX', 'XXX', { host: 'XXX', dialect: 'mssql', dialectOptions: { options: { encrypt: true } } });

I get error about Username being empty:
https://i.imgur.com/JbkOgIU.png

I have tried connection with MySql and everything works in there. Problems are only when connecting to Azure database. Any help would be great guys! Thank you.

Body:
I connected as below. It works.

   const sequelize = new Sequelize(database, username, password, {
  host: config.databaseHost,
  Port: config.databasePort, // 49175 // 1433
  dialect: 'mssql',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
  dialectOptions: {
    instanceName: 'SQLEXPRESS',
    requestTimeout: 60000
  }
});
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


问:
Where does the snap package version of LXD store containers?
In this tutorial, the author gives the following location of the root directory in a container named c1:

```<code>/var/lib/lxd/containers/c1/rootfs/
</code>```

What is the equivalent directory if I've installed lxd using snap install lxd?

答:
On Ubuntu 18.04, lxd version 3.13, using the dir backend, it was this:

```<code>/var/snap/lxd/common/lxd/storage-pools/default/containers/c1/rootfs/
</code>```

Body:
In this tutorial, the author gives the following location of the root directory in a container named c1:

/var/lib/lxd/containers/c1/rootfs/

What is the equivalent directory if I've installed lxd using snap install lxd?

Body:
On Ubuntu 18.04, lxd version 3.13, using the dir backend, it was this:

/var/snap/lxd/common/lxd/storage-pools/default/containers/c1/rootfs/


问:
How to get rid of first element of store id using pandas?
My data-frame consists of StoreId which needs to be changed for a particular type of store:

```<code>StoreType  StoreId
 A           105
 A           213
 B           401
 B           402
 B           711
 B           910
 B           913
 B           915
</code>```

In this dataframe, just for storeType = B, I want to get rid of all the 4's if the storeId starts with 4,(for example, 401 should change to 01, 402 should change to 02), for any other StoreID with storetype = B, there is no such logic and hence it needs to be hard coded like 711 should change to I0, 910 to 801, 913 to 804, 915 to 814.

How can I write an efficient code using pandas data-frame in python??

答:
You can use a simple regular expression here, along with where to only change columns where a B is found in the other series.

```<code>u = df.StoreId.astype(str)
df.assign(StoreId=u.where(df.StoreType.ne('B'), u.str.replace('^4', '')))
</code>```

```<code>  StoreType StoreId
0         A     105
1         A     213
2         B      01
3         B      02
4         B     711
5         B     910
6         B     913
7         B     915
</code>```

Body:
My data-frame consists of StoreId which needs to be changed for a particular type of store:

StoreType  StoreId
 A           105
 A           213
 B           401
 B           402
 B           711
 B           910
 B           913
 B           915

In this dataframe, just for storeType = B, I want to get rid of all the 4's if the storeId starts with 4,(for example, 401 should change to 01, 402 should change to 02), for any other StoreID with storetype = B, there is no such logic and hence it needs to be hard coded like 711 should change to I0, 910 to 801, 913 to 804, 915 to 814.

How can I write an efficient code using pandas data-frame in python??

Body:
You can use a simple regular expression here, along with where to only change columns where a B is found in the other series.

u = df.StoreId.astype(str)
df.assign(StoreId=u.where(df.StoreType.ne('B'), u.str.replace('^4', '')))

  StoreType StoreId
0         A     105
1         A     213
2         B      01
3         B      02
4         B     711
5         B     910
6         B     913
7         B     915


问:
Paste data from Excel and convert into an array?
I'm new powershell and want to take a list of servers from Excel, and literally paste into an input window. It should segregate it and process it one after other.

ie
give the name of servers:

```
arvdel1
arvdel2
arvdel3
arvdel4
```

and it should take it as

```<code>$a=@(arvdel1,arvdel2,arvdel3,arvdel4)
</code>```

How can I do this?

答:
You can use a required parameter (for Powershell versions less than 5.1 or 'Get-Clipboard' for version 5.1 or greater) that has type of String array [string[]]. It will prompt you for to enter the value of each array element until it detects a blank line that is entered.

I figured this out recently by looking at the input Parameters of a script. For years I was manipulating the text into the PowerShell single line array format with Excel's transpose and replacing 'Tab' characters in Notepad.

Just for reference PowerShell single line array format is ("1", "2", "3", "4", "5")

```<code>...
param
(
    [parameter(Mandatory = $true)]
    [string[]]
    $listOfStrings
)
...
</code>```

Example prompt to fill to a string array

```<code>Supply values for the following parameters:
listOfStrings[0]:
</code>```

I created a list in Notepad (or Excel) of 1 through 5 and directly copied it into PowerShell window. Below is my sample output.

```<code>1
2
3
4
5

Supply values for the following parameters:
listOfStrings[0]: 1
listOfStrings[1]: 2
listOfStrings[2]: 3
listOfStrings[3]: 4
listOfStrings[4]: 5
listOfStrings[5]:
1
2
3
4
5
</code>```

Body:
I'm new powershell and want to take a list of servers from Excel, and literally paste into an input window. It should segregate it and process it one after other.

ie
give the name of servers:

arvdel1
arvdel2
arvdel3
arvdel4

and it should take it as

$a=@(arvdel1,arvdel2,arvdel3,arvdel4)

How can I do this?

Body:
You can use a required parameter (for Powershell versions less than 5.1 or 'Get-Clipboard' for version 5.1 or greater) that has type of String array [string[]]. It will prompt you for to enter the value of each array element until it detects a blank line that is entered.

I figured this out recently by looking at the input Parameters of a script. For years I was manipulating the text into the PowerShell single line array format with Excel's transpose and replacing 'Tab' characters in Notepad.

Just for reference PowerShell single line array format is ("1", "2", "3", "4", "5")

...
param
(
    [parameter(Mandatory = $true)]
    [string[]]
    $listOfStrings
)
...

Example prompt to fill to a string array

Supply values for the following parameters:
listOfStrings[0]:

I created a list in Notepad (or Excel) of 1 through 5 and directly copied it into PowerShell window. Below is my sample output.

1
2
3
4
5

Supply values for the following parameters:
listOfStrings[0]: 1
listOfStrings[1]: 2
listOfStrings[2]: 3
listOfStrings[3]: 4
listOfStrings[4]: 5
listOfStrings[5]:
1
2
3
4
5


答:
So, erlang/elixir are great languages for deconstructing raw packets in binary format--which is what Circuits.UART.read() returns.  You deconstruct a binary, <<...>>, with binary pattern matching, and your datasheet contains the spec for the pattern you will use.  There's no need for base16 encoding, splitting at 424D, nor breaking into chunks of 2:

```<code>defmodule My do

  def match(<<
                66, 77,
                _fr_len::big-integer-size(16),
                data1::big-integer-size(16),
                data2::big-integer-size(16),
                data3::big-integer-size(16),
                data4::big-integer-size(16),
                data5::big-integer-size(16),
                data6::big-integer-size(16),
                data7::big-integer-size(16),
                data8::big-integer-size(16),
                data9::big-integer-size(16),
                data10::big-integer-size(16),
                data11::big-integer-size(16),
                data12::big-integer-size(16),
                _reserved::big-integer-size(16),
                _check_code::big-integer-size(16),
                rest::binary
           >>) do

    IO.puts "pm 1.0 cf: #{data1} ug/m^3"
    IO.puts "pm 2.5 atmospheric: #{data5} ug/m^3"
    match(rest)
  end

  def match(partial_frame) do
    IO.puts "partial_frame:"
    IO.inspect partial_frame
  end

  def go() do
    match(<<66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32,
           17, 124, 4, 211, 0, 171, 0, 8, 0, 0, 0, 0, 151, 0, 4, 5,
           66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32>>)

    :ok
  end

end
</code>```

In iex:

```<code>iex(1)> My.go
pm 1.0 cf: 23 ug/m^3
pm 2.5 atmospheric: 31 ug/m^3
partial_frame:
<<66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32>>
:ok
</code>```

You could write 0x42, 0x4D inside the pattern to exactly match the datasheet spec, however I think it's clearer to use the decimal equivalents, 66, 77, because elixir doesn't output hex codes when outputting a binary, rather elixir outputs decimals--as can be seen in your data (Or, sometimes elixir outputs a double quoted string for a binary, which is really confusing and stupid.)  With 66, 77 in the pattern, you can easily look at the data and see where it matches.

Note that the last segment rest::binary is like writing .* in a regex.

Before trusting any of the data assigned to the variables, you should probably check that the frame length is 28 and verify the check code.  Unfortunately, I can't figure out what the check code represents.  I get 1029 for the check code.

==========

Can you post an example of what you expect the data to look like?

A hex string like "1C" is equivalent to decimal 28.  You can get all the decimal equivalents like this:

```<code>data = [ "00", "1C", "00", "17", "00", "20", "00", "20", "00", "16", "00",
        "1F", "00", "20", "11", "7C", "04", "D3", "00", "AB", "00", "08",
        "00", "00", "00", "00", "97", "00", "04", "05"]

for str <- data do
  Integer.parse(str, 16)
end
|> IO.inspect
|> Enum.map(fn {a, _} -> a end)
</code>```

Integer.parse() returns a tuple, where the first element is an integer and the second element is the "the remainder of the string", i.e. anything that couldn't be interpreted as an integer.

Output:

```<code>[
  {0, ""},
  {28, ""},
  {0, ""},
  {23, ""},
  {0, ""},
  {32, ""},
  {0, ""},
  {32, ""},
  {0, ""},
  {22, ""},
  {0, ""},
  {31, ""},
  {0, ""},
  {32, ""},
  {17, ""},
  {124, ""},
  {4, ""},
  {211, ""},
  {0, ""},
  {171, ""},
  {0, ""},
  {8, ""},
  {0, ""},
  {0, ""},
  {0, ""},
  {0, ""},
  {151, ""},
  {0, ""},
  {4, ""},
  {5, ""}
]
[0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32, 17, 124,
 4, 211, 0, 171, 0, 8, 0, 0, 0, 0, 151, 0, 4, 5]
</code>```

Is that what your data is supposed to look like?

It looks to me like the java code:

```<code>...forEach[b | bts.append(Integer.toHexString(b)]
</code>```

does some bit twiddling with the java's bitwise OR operator: |, which makes no sense to me in that code snippet.  But, in elixir you would do that with Bitwise.bor(a, b). I really think that java code should look like this:

```<code>...forEach(b -> bts.append(Integer.toHexString(b))
</code>```

In other words, forEach() takes a lambda as an argument.  Heck, that has me so curious, I'm going to ask the guy what that means.

Edit:

Alright, the guy responded to me, and that isn't Java--it is the syntax for a lambda though--in some DSL language.

Title: Decoding endian(?) data from a sensor

Body:
I am not sure I even understand what is going on here with this data, but I am trying to replicate functionality like here, here or here to decode the data I am receiving over UART from my Plantower PMS5003 sensor (see datasheet) sensor in Elixir.

It's delimited by 0x42 and 0x4d and starts like this:

iex(mygadget@nerves.local)4> {:ok, data} = Circuits.UART.read(pid, 60000)
{:ok,
 <<66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32, 17, 124, 4, 211, 0,
   171, 0, 8, 0, 0, 0, 0, 151, 0, 4, 5, 66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0,
   22, 0, 31, 0, 32, ...>>}

I then base16 encode it:

iex(mygadget@nerves.local)5> Base.encode16(data)
"424D001C0017002000200016001F0020117C04D300AB00080000000097000405424D001C0017002000200016001F0020117C04D300AB00080000000097000405424D001C0017001F001F0016001E001F115804BE0098000800
000000970003B5424D001C0018002000200016001F002011BB04D8009F0008000000009700043E424D001C0016001F001F0015001E001F11DC04C3009300080000000097000437424D001C0017001E001E0015001D001E11E20
4C300850008000000009700042C424D001C0016001E001E0015001D001E117304B70087000600000000970003B0424D001C0016001D001D0015001D001D111F049B007B00060000000097000331424D001C0017001E001E0016
001E001E10F5048D007D00060000000097000400424D001C0017001E001E0016001E001E10FB0496008B0004000000009700041B424D001C0016001E001E0015001E001E10B304810089000400000000970003BA424D001C001
5001C001C0014001C001C104A045E008000020000000097000319424D001C0016001C001

And split by 424D

decoded |> String.split("424D")
["", "001C0017002000200016001F0020117C04D300AB00080000000097000405",
 "001C0017002000200016001F0020117C04D300AB00080000000097000405",
 "001C0017001F001F0016001E001F115804BE0098000800000000970003B5",
 "001C0018002000200016001F002011BB04D8009F0008000000009700043E",

Then break it into chunks of 2

iex(mygadget@nerves.local)10> "001C0017002000200016001F0020117C04D300AB00080000000097000405" |> String.codepoints |> Enum.chunk(2) |> Enum.map(&Enum.join/1)
["00", "1C", "00", "17", "00", "20", "00", "20", "00", "16", "00", "1F", "00",
 "20", "11", "7C", "04", "D3", "00", "AB", "00", "08", "00", "00", "00", "00",
 "97", "00", "04", "05"]

I am fairly at a loss as to where to go from here. I found this discussion about how to do it in Java but I don't really understand what is going on there with the framebuffers.

Any insight appreciated

EDIT: tags

Body:
So, erlang/elixir are great languages for deconstructing raw packets in binary format--which is what Circuits.UART.read() returns.  You deconstruct a binary, <<...>>, with binary pattern matching, and your datasheet contains the spec for the pattern you will use.  There's no need for base16 encoding, splitting at 424D, nor breaking into chunks of 2:

defmodule My do

  def match(<<
                66, 77,
                _fr_len::big-integer-size(16),
                data1::big-integer-size(16),
                data2::big-integer-size(16),
                data3::big-integer-size(16),
                data4::big-integer-size(16),
                data5::big-integer-size(16),
                data6::big-integer-size(16),
                data7::big-integer-size(16),
                data8::big-integer-size(16),
                data9::big-integer-size(16),
                data10::big-integer-size(16),
                data11::big-integer-size(16),
                data12::big-integer-size(16),
                _reserved::big-integer-size(16),
                _check_code::big-integer-size(16),
                rest::binary
           >>) do

    IO.puts "pm 1.0 cf: #{data1} ug/m^3"
    IO.puts "pm 2.5 atmospheric: #{data5} ug/m^3"
    match(rest)
  end

  def match(partial_frame) do
    IO.puts "partial_frame:"
    IO.inspect partial_frame
  end

  def go() do
    match(<<66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32,
           17, 124, 4, 211, 0, 171, 0, 8, 0, 0, 0, 0, 151, 0, 4, 5,
           66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32>>)

    :ok
  end

end

In iex:

iex(1)> My.go
pm 1.0 cf: 23 ug/m^3
pm 2.5 atmospheric: 31 ug/m^3
partial_frame:
<<66, 77, 0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32>>
:ok

You could write 0x42, 0x4D inside the pattern to exactly match the datasheet spec, however I think it's clearer to use the decimal equivalents, 66, 77, because elixir doesn't output hex codes when outputting a binary, rather elixir outputs decimals--as can be seen in your data (Or, sometimes elixir outputs a double quoted string for a binary, which is really confusing and stupid.)  With 66, 77 in the pattern, you can easily look at the data and see where it matches.

Note that the last segment rest::binary is like writing .* in a regex.

Before trusting any of the data assigned to the variables, you should probably check that the frame length is 28 and verify the check code.  Unfortunately, I can't figure out what the check code represents.  I get 1029 for the check code.

==========

Can you post an example of what you expect the data to look like?

A hex string like "1C" is equivalent to decimal 28.  You can get all the decimal equivalents like this:

data = [ "00", "1C", "00", "17", "00", "20", "00", "20", "00", "16", "00",
        "1F", "00", "20", "11", "7C", "04", "D3", "00", "AB", "00", "08",
        "00", "00", "00", "00", "97", "00", "04", "05"]

for str <- data do
  Integer.parse(str, 16)
end
|> IO.inspect
|> Enum.map(fn {a, _} -> a end)

Integer.parse() returns a tuple, where the first element is an integer and the second element is the "the remainder of the string", i.e. anything that couldn't be interpreted as an integer.

Output:

[
  {0, ""},
  {28, ""},
  {0, ""},
  {23, ""},
  {0, ""},
  {32, ""},
  {0, ""},
  {32, ""},
  {0, ""},
  {22, ""},
  {0, ""},
  {31, ""},
  {0, ""},
  {32, ""},
  {17, ""},
  {124, ""},
  {4, ""},
  {211, ""},
  {0, ""},
  {171, ""},
  {0, ""},
  {8, ""},
  {0, ""},
  {0, ""},
  {0, ""},
  {0, ""},
  {151, ""},
  {0, ""},
  {4, ""},
  {5, ""}
]
[0, 28, 0, 23, 0, 32, 0, 32, 0, 22, 0, 31, 0, 32, 17, 124,
 4, 211, 0, 171, 0, 8, 0, 0, 0, 0, 151, 0, 4, 5]

Is that what your data is supposed to look like?

It looks to me like the java code:

...forEach[b | bts.append(Integer.toHexString(b)]

does some bit twiddling with the java's bitwise OR operator: |, which makes no sense to me in that code snippet.  But, in elixir you would do that with Bitwise.bor(a, b). I really think that java code should look like this:

...forEach(b -> bts.append(Integer.toHexString(b))

In other words, forEach() takes a lambda as an argument.  Heck, that has me so curious, I'm going to ask the guy what that means.

Edit:

Alright, the guy responded to me, and that isn't Java--it is the syntax for a lambda though--in some DSL language.


问:
Converting a repeating binary number to decimal
How do I represent 0.1011111.... or 0.10(1) as a fraction a/b?
With a & b being integers.

I have being trying this method

x = 0.10(1)
x = 10.(1) / 4

Now y = 10.(1)

2y = 101.(1)

which implies 2y - y = 91
y = 91

x = 91/4
But a = 91 & b = 4 is wrong.

How do I go about to solve this?

答:
Here is a generalization of this problem to the frequent situation of repeting patterns.

Assume x=0.001100110011..., where pattern 0011 is repeated infinitely.

Let a be the pattern (0011 for x) and k be its length (ie 4 for x).

x = a×2^-k+a×2^-2k+...

  = a×2^-k×∑i=0∞ (2^-k)^i

  = a×2^-k×limn→∞(1-(2^-k)^n)/(1-2^-k)

as x is the sum of a geometric serie with a 2^k ratio.

When n goes to ∞, (2^-k)^n goes to zero and we have

x = a×2^-k/(1-2^-k) = a/(2^k-1)

If x=0.11111..., a=1, k=1 and x=1/(2-1)=1 and we get the result already presented (in a much simpler way!) by LutzL that answers the original question.

But we can solve more complex problems with any repeating pattern.

For instance if x=0.001100110011..., we have a=0011=3 and k=4.

Hence x=3/(2^-4-1)=1/5=0.2

The generalization to the situation where the repetitive pattern is preceded by a non repeating sequence is immediate.


问:
Deleting a row that is not equal to another row but not considering NA's in R
I Have this file:

```<code>Name Father1 Father2
Joe    1        1
Jan    2        2
Lion  NA       NA
Faire NA        5
jake  5        NA
Stan  3         4
Paul  1         2
</code>```

And I would like to delete the the different fathers between Father1 and 2, except NA's, like this:

```<code> Name Father1 Father2
    Joe    1        1
    Jan    2        2
    Lion  NA       NA
    Faire NA        5
    jake  5        NA
</code>```

I tried this code but didn't work.

```<code>New.file=my.file[!(my.file$Father1 != my.file$Father2),]
</code>```

And I obtained this one:

```<code>Name Father1 Father2
Joe    1        1
Jan    2        2
 NA   NA       NA
 NA   NA       NA
 NA   NA       NA
</code>```

The program deleted the different rows, but replace the another ones with a NA.

What happened?

答:
Can you try this please :

```<code>data_not <-data[!(data$father1 != data$father2),]
data[!(data$Name %in% data_not$Name),]
</code>```

It works when I do it with this example :

```<code>data <- data.table(Name = c("joe", "jan", "lion", "faire"), father1 =
c(1,2,NA,5), father2 = c(1,2,3,4))
output :
    Name father1 father2
1:   joe       1       1
2:   jan       2       2
3:  lion      NA       3
4: faire       5       4

data_not <-data[!(data$father1 != data$father2),]
data[!(data$Name %in% data_not$Name),]

new output :
   Name father1 father2
1:  joe       1       1
2:  jan       2       2
3: lion      NA       3
</code>```

Tell me if it is helping you.

Body:
I Have this file:

Name Father1 Father2
Joe    1        1
Jan    2        2
Lion  NA       NA
Faire NA        5
jake  5        NA
Stan  3         4
Paul  1         2

And I would like to delete the the different fathers between Father1 and 2, except NA's, like this:

 Name Father1 Father2
    Joe    1        1
    Jan    2        2
    Lion  NA       NA
    Faire NA        5
    jake  5        NA

I tried this code but didn't work.

New.file=my.file[!(my.file$Father1 != my.file$Father2),]

And I obtained this one:

Name Father1 Father2
Joe    1        1
Jan    2        2
 NA   NA       NA
 NA   NA       NA
 NA   NA       NA

The program deleted the different rows, but replace the another ones with a NA.

What happened?

Body:
Can you try this please :

data_not <-data[!(data$father1 != data$father2),]
data[!(data$Name %in% data_not$Name),]

It works when I do it with this example :

data <- data.table(Name = c("joe", "jan", "lion", "faire"), father1 =
c(1,2,NA,5), father2 = c(1,2,3,4))
output :
    Name father1 father2
1:   joe       1       1
2:   jan       2       2
3:  lion      NA       3
4: faire       5       4

data_not <-data[!(data$father1 != data$father2),]
data[!(data$Name %in% data_not$Name),]

new output :
   Name father1 father2
1:  joe       1       1
2:  jan       2       2
3: lion      NA       3

Tell me if it is helping you.


问:
Heads up push notification not doing the Pop up function
I am new to Android and I have been trying to show a Heads up action push notification just like whatsapp does.

This is my configuration for my notification:

```<code>NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, ADMIN_CHANNEL)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_foreground))
                        .setSmallIcon(R.drawable.m_icon)
                        .setContentTitle(remoteMessage.getNotification().getTitle())
                        .setTicker(remoteMessage.getNotification().getBody())
                        .setColor(ContextCompat.getColor(getApplicationContext(), R.color.mblue))
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(remoteMessage.getNotification().getBody()))
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setContentIntent(likePendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());
</code>```

I have read in some post that the key to acomplish this is to set high priority to the notification but, It is still not working for me.

答:
For Android Pie (9) on the emulator, I setup my channel with "IMPORTANCE_HIGH", and also set my builder priority to "PRIORITY_HIGH".

But, I still could not get heads-up notifications!

Finally, on the Android 9 emulator, I had to:

swipe down the notifications drawer

tap on "Manage Notifications"

select my app

select my channel

select "Behavior"

enable "Make sound and pop on screen".

Now it works.

Body:
I am new to Android and I have been trying to show a Heads up action push notification just like whatsapp does.

This is my configuration for my notification:

NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, ADMIN_CHANNEL)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_foreground))
                        .setSmallIcon(R.drawable.m_icon)
                        .setContentTitle(remoteMessage.getNotification().getTitle())
                        .setTicker(remoteMessage.getNotification().getBody())
                        .setColor(ContextCompat.getColor(getApplicationContext(), R.color.mblue))
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(remoteMessage.getNotification().getBody()))
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setContentIntent(likePendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0,notificationBuilder.build());

I have read in some post that the key to acomplish this is to set high priority to the notification but, It is still not working for me.


问:
Lookup activity in an Azure Data Factory Data Copy Source - Syntax Error
Working through this https://learn.microsoft.com/en-us/azure/data-factory/tutorial-incremental-copy-portal

I've one Lookup activity called GetCurrentWatermarkValue with sqlReaderQuery:

```<code>Select WaterMarkValue as CurrentWatermarkValue\nfrom WatermarkTable
</code>```

I've another activity called GetNewWatermarkValue with sqlReaderQuery:

```<code>select max(createdon) as NewWatermarkValue from shipment
</code>```

I'm then trying to use them both in the source for a Data Copy activity using

```<code>select *
from Shipment
where CreatedOn > '@{activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue}'
and CreatedOn <= '@{activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}'
</code>```

The Preview data button is greyed (but enabled when i remove the where condition) so there is obviouusly something wrong

After I've set the sink i try to set up the Mapping. Clicking Import schema on the Mapping tab gives:

```<code>A database operation failed with the following error: 'Incorrect syntax near 'GetCurrentWatermarkValue'.'. Activity ID:98794aa9-c866-48d6-b9ff-9cb277bac6ed
</code>```

I thought maybe I should be using the add dynamic content option but that just gives

```<code>Query is required
</code>```

I've read somewhere that the when First Row Only is set on the Lookup activity the text after firstRow. should be [TableName] but that doesn't seem right.

Lookup:

```<code>{
    "name": "GetCurrentWatermarkValue",
    "type": "Lookup",
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": "Select WaterMarkValue as CurrentWatermarkValue\nfrom WatermarkTable"
        },
        "dataset": {
            "referenceName": "WatermarkTable",
            "type": "DatasetReference"
        }
    }
}
</code>```

Lookup:

```<code>{
    "name": "GetNewWatermarkValue",
    "type": "Lookup",
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": "select max(createdon) as NewWatermarkValue from shipment"
        },
        "dataset": {
            "referenceName": "ShipmentsTable",
            "type": "DatasetReference"
        }
    }
}
</code>```

Data Copy:

```<code>{
    "name": "ArchiveShipments",
    "type": "Copy",
    "dependsOn": [
        {
            "activity": "GetCurrentWatermarkValue",
            "dependencyConditions": [
                "Succeeded"
            ]
        },
        {
            "activity": "GetNewWatermarkValue",
            "dependencyConditions": [
                "Succeeded"
            ]
        }
    ],
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": {
                "value": "select *\nfrom Shipment\nwhere CreatedOn > '@{activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue}' \nand CreatedOn <= '@{activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}'",
                "type": "Expression"
            }
        },
        "sink": {
            "type": "AzureSqlSink"
        },
        "enableStaging": false
    },
    "inputs": [
        {
            "referenceName": "ShipmentsTable",
            "type": "DatasetReference"
        }
    ],
    "outputs": [
        {
            "referenceName": "ShipmentArchiveTable",
            "type": "DatasetReference"
        }
    ]
}
</code>```

答:
This looks like a syntax issue, try this is the copy activity query:

```<code>@{CONCAT('select * from Shipment where CreatedOn > ', activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue, ' and CreatedOn <= ', activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}
</code>```

Dont use a mapping unless you want to manually set it, if column names are the same, then just click "Clear".

Hope this helped!

Body:
Working through this https://learn.microsoft.com/en-us/azure/data-factory/tutorial-incremental-copy-portal

I've one Lookup activity called GetCurrentWatermarkValue with sqlReaderQuery:

Select WaterMarkValue as CurrentWatermarkValue\nfrom WatermarkTable

I've another activity called GetNewWatermarkValue with sqlReaderQuery:

select max(createdon) as NewWatermarkValue from shipment

I'm then trying to use them both in the source for a Data Copy activity using

select *
from Shipment
where CreatedOn > '@{activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue}'
and CreatedOn <= '@{activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}'

The Preview data button is greyed (but enabled when i remove the where condition) so there is obviouusly something wrong

After I've set the sink i try to set up the Mapping. Clicking Import schema on the Mapping tab gives:

A database operation failed with the following error: 'Incorrect syntax near 'GetCurrentWatermarkValue'.'. Activity ID:98794aa9-c866-48d6-b9ff-9cb277bac6ed

I thought maybe I should be using the add dynamic content option but that just gives

Query is required

I've read somewhere that the when First Row Only is set on the Lookup activity the text after firstRow. should be [TableName] but that doesn't seem right.

Lookup:

{
    "name": "GetCurrentWatermarkValue",
    "type": "Lookup",
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": "Select WaterMarkValue as CurrentWatermarkValue\nfrom WatermarkTable"
        },
        "dataset": {
            "referenceName": "WatermarkTable",
            "type": "DatasetReference"
        }
    }
}

Lookup:

{
    "name": "GetNewWatermarkValue",
    "type": "Lookup",
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": "select max(createdon) as NewWatermarkValue from shipment"
        },
        "dataset": {
            "referenceName": "ShipmentsTable",
            "type": "DatasetReference"
        }
    }
}

Data Copy:

{
    "name": "ArchiveShipments",
    "type": "Copy",
    "dependsOn": [
        {
            "activity": "GetCurrentWatermarkValue",
            "dependencyConditions": [
                "Succeeded"
            ]
        },
        {
            "activity": "GetNewWatermarkValue",
            "dependencyConditions": [
                "Succeeded"
            ]
        }
    ],
    "policy": ...,
    "typeProperties": {
        "source": {
            "type": "AzureSqlSource",
            "sqlReaderQuery": {
                "value": "select *\nfrom Shipment\nwhere CreatedOn > '@{activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue}' \nand CreatedOn <= '@{activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}'",
                "type": "Expression"
            }
        },
        "sink": {
            "type": "AzureSqlSink"
        },
        "enableStaging": false
    },
    "inputs": [
        {
            "referenceName": "ShipmentsTable",
            "type": "DatasetReference"
        }
    ],
    "outputs": [
        {
            "referenceName": "ShipmentArchiveTable",
            "type": "DatasetReference"
        }
    ]
}

Body:
This looks like a syntax issue, try this is the copy activity query:

@{CONCAT('select * from Shipment where CreatedOn > ', activity('GetCurrentWatermarkValue').output.firstRow.CurrentWatermarkValue, ' and CreatedOn <= ', activity('GetNewWatermarkValue').output.firstRow.NewWatermarkValue}

Dont use a mapping unless you want to manually set it, if column names are the same, then just click "Clear".

Hope this helped!


问:
Receiving "Cannot read property 'value' of undefined" in formControlName property
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}
</code>```

Here is my login.component.html:

```<code><mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">
            <table class="login-full-width" cellspacing="0">
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>
                    </td>
                </tr>
                <p>
                    Value: {{email.value}}
                </p>
                <tr>
                    <td>
                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>
                    </td>
                </tr>
            </table>
        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>
</code>```

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

```<code><input matInput type="text" formControlName="email" placeholder="Email" required>
</code>```

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?

答:
Better approach would be:</p>

```<code> <input  type="text"  [formControl]="loginForm.controls.email" placeholder="Email" required>
</code>```

<p>{{loginForm.controls.email.value}} </p>

Body:
I am using Angular 7 and Google Material Design, and I followed this tutorial for Reactive forms: https://angular.io/guide/reactive-forms#step-1-creating-a-formgroup-instance.

I have used a formGroup, along with formControlName. Here is my login.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  loginForm = new FormGroup({
    email: new FormControl(''),
    password: new FormControl(''),
  });

  ngOnInit() {
  }

  onSubmit() : void {
    console.log(this.loginForm.value);
  }
}

Here is my login.component.html:

<mat-card class="login-card">
    <mat-card-header>
        <mat-card-title>Login</mat-card-title>
    </mat-card-header>
    <mat-card-content>
        <form [formGroup]="loginForm" class="login-form" (ngSubmit)="onSubmit()">

                        <mat-form-field class="login-full-width">
                            <input matInput type="text" formControlName="email" placeholder="Email" required>
                        </mat-form-field>

                    Value: {{email.value}}

                        <mat-form-field class="login-full-width">
                            <input matInput formControlName="password" placeholder="Password" type="password" required>
                        </mat-form-field>

        </form>
        <mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
    </mat-card-content>
    <mat-card-actions>
        <button mat-raised-button [disabled]="!loginForm.valid" color="primary">Login</button>
    </mat-card-actions>
</mat-card>

This is the error I get when navigating to the login page:

LoginComponent.html:11 ERROR TypeError: Cannot read property 'value' of undefined

      at Object.eval [as updateRenderer] (LoginComponent.html:15)

      at Object.debugUpdateRenderer [as updateRenderer] (core.js:23937)

      at checkAndUpdateView (core.js:23312)

      at callViewAction (core.js:23548)

      at execComponentViewsAction (core.js:23490)

      at checkAndUpdateView (core.js:23313)

      at callViewAction (core.js:23548)

      at execEmbeddedViewsAction (core.js:23511)

      at checkAndUpdateView (core.js:23308)

      at callViewAction (core.js:23548)

This is line 11 of login.component.html:

<input matInput type="text" formControlName="email" placeholder="Email" required>

I followed the tutorial step by step, and it was very simple to follow. Did I miss something here that is causing the error?

Body:
Better approach would be:

 <input  type="text"  [formControl]="loginForm.controls.email" placeholder="Email" required>

{{loginForm.controls.email.value}}


问:
Convert from one date-time format to a different date-time format
I want to convert a time which is taken as an argument to the Perl script into a different format.

The input is of the form yyyyMMddHHmmss (e.g. 20190101235010).

The output should be of of the form yyyy-MM-dd-HH:mm:ss (e.g. 2019-01-01-23:50:10).

It would be better if solution doesn't use Perl Modules (except POSIX).

Body:
Here are a few alternatives that will do quite nicely:

my $output =
    sprintf "%s-%s-%s-%s:%s:%s",
       unpack 'a4 a2 a2 a2 a2 a2',
          $input;

my $output = $input =~ s/^(....)(..)(..)(..)(..)(..)\z/$1-$2-$3-$4:$5:$6/sr;

my $output = $input =~ /^(....)(..)(..)(..)(..)(..)\z/s
  ? "$1-$2-$3-$4:$5:$6"
  : die("Bad input\n");


问:
How to change activity in android?

I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

```<code>Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
</code>```

It calls second activity where, second activity has following code:

```<code>setContentView(new MovementView(this));
</code>```

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.

答:
with the MovementView constructor you have to remember the activity, tu use it to launch the third activity.

```<code>private Activity a;

public MovementView(Acitivity a) {
  this.a = a;
  // your code
}
</code>```

somewhere in MovementView, replace

```<code>Intent i = new Intent(this, ThirdActivity.class);
</code>```

by

```<code>Intent i = new Intent(a, ThirdActivity.class);
</code>```

Title: How to change activity in android?

Body:
I am making simple game. I have 3 activities. First activity is main menu (FirstActivity class).

First activity has following code:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);

It calls second activity where, second activity has following code:

setContentView(new MovementView(this));

MovementView class extends SurfaceView. MovementView class is where I write all game code.

So I want to make when lives == 0, it changes to ThirdActivity. How do I do that?

I have tried putting code similar to FirstActivity's class but it doesn't seems to work.

If I put

 ((Activity)getContext()).finish();

it just jumps back to FirstActivity, but that's not what I need, I need it to go to ThirdActivity class.

Body:
with the MovementView constructor you have to remember the activity, tu use it to launch the third activity.

private Activity a;

public MovementView(Acitivity a) {
  this.a = a;
  // your code
}

somewhere in MovementView, replace

Intent i = new Intent(this, ThirdActivity.class);

by

Intent i = new Intent(a, ThirdActivity.class);


问:
How to create a program that converts binary to decimal
I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?

i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.

```<code>package Calculator;
import java.util.Scanner;
public class Calculator {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
            System.out.println("(2) Convert binary to decimal");
            System.out.println("\n\n Please enter your choice: ");
            int choice = scan.nextInt();
            if(choice == 2){
                scan.nextLine();
                //prompt for user input
                System.out.println("Please enter a binary number: ");
                String binary = scan.nextLine();
                char[] binaryArray = binary.toCharArray();
                int i=1;
                int integer=0;
            //potential problem somewhere around here?
            while(i<8){
                if(binaryArray[i]==0) {
                    ++i;
                }else if(binaryArray[i]==1) {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }
        }
            System.out.println("The decimal value of the binary number is: "+ integer);
            scan.close();
    }
}
</code>```

}

The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.

答:
This is happening because you are reading the input, and converting into an array of char.

Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.

```<code>while(i<8){
                if(binaryArray[i]=='0') {
                    ++i;
                }else if(binaryArray[i]=='1') {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }
</code>```

Body:
I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?

i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.

package Calculator;
import java.util.Scanner;
public class Calculator {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
            System.out.println("(2) Convert binary to decimal");
            System.out.println("\n\n Please enter your choice: ");
            int choice = scan.nextInt();
            if(choice == 2){
                scan.nextLine();
                //prompt for user input
                System.out.println("Please enter a binary number: ");
                String binary = scan.nextLine();
                char[] binaryArray = binary.toCharArray();
                int i=1;
                int integer=0;
            //potential problem somewhere around here?
            while(i<8){
                if(binaryArray[i]==0) {
                    ++i;
                }else if(binaryArray[i]==1) {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }
        }
            System.out.println("The decimal value of the binary number is: "+ integer);
            scan.close();
    }
}

}

The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.

Body:
This is happening because you are reading the input, and converting into an array of char.

Anywhere where you are making your comparisons to an int, you should instead be doing a comparison to a char, by wrapping your values in single quotations.

while(i<8){
                if(binaryArray[i]=='0') {
                    ++i;
                }else if(binaryArray[i]=='1') {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }


问:
how to handle Image with serializer
I have some problem in uploading picture in user profile its already extended  onetoone from users ,  when I wanted to upload pic via postman it returned null value

serializer :

```<code>class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = ('user', 'bio', 'avatar')

    def validate(self, data):
        print(data)
        self.context['avatar'] = self.context['request'].FILES.get('avatar')
        return data

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = UserSerializer.create(UserSerializer(), validated_data=user_data)

        validated_data['avatar'] = self.context['avatar']
        validated_data['user'] = user

        profile = UserProfile.objects.create(**validated_data)
        profile.bio = validated_data["bio"]

        profile.save()
        return profile
</code>```

The model:

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile', on_delete=True)
    bio = models.CharField(max_length=50, blank=True)
    avatar = models.ImageField(upload_to="media", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username
</code>```

答:
i found the solution ,the picture in django store in memory at request.FILES

userprofile = UserProfile.objects.create(user=user, bio=validated_data.pop('bio'), user_type=type)
        images_data = self.context.get('view').request.FILES
        for image_data in images_data.values():
            ProfileImage.objects.create(userprofile=userprofile, image=image_data, user_type=type)

Title: how to handle Image with serializer

Body:
I have some problem in uploading picture in user profile its already extended  onetoone from users ,  when I wanted to upload pic via postman it returned null value

serializer :

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = ('user', 'bio', 'avatar')

    def validate(self, data):
        print(data)
        self.context['avatar'] = self.context['request'].FILES.get('avatar')
        return data

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = UserSerializer.create(UserSerializer(), validated_data=user_data)

        validated_data['avatar'] = self.context['avatar']
        validated_data['user'] = user

        profile = UserProfile.objects.create(**validated_data)
        profile.bio = validated_data["bio"]

        profile.save()
        return profile

The model:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile', on_delete=True)
    bio = models.CharField(max_length=50, blank=True)
    avatar = models.ImageField(upload_to="media", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.user.username


问:
How to concat rows based on ID,
Using standard SQL in bigquery:

Given a table such as: Where the values have been counted so only appear once

```<code>| id | key | value |
--------------------
| 1 | read |  aa   |
| 1 | read |  bb   |
| 1 | name |  abc  |
| 2 | read |  bb   |
| 2 | read |  cc   |
| 2 | name |  def  |
| 2 | value|  some |
| 3 | read |  aa   |
</code>```

How can I make it so each row is one user and their respective values? e.g. NEST

So the table would look like:

```<code>| id | key | value |
--------------------
| 1 | read |  aa   |
|   | read |  bb   |
|   | name |  abc  |
| 2 | read |  bb   |
|   | read |  cc   |
|   | name |  def  |
|   | value|  some |
| 3 | read |  aa   |
</code>```

I've tried using ARRAY_AGG on the column, which ends up listing all the values of that column.

I just need to have each row as a single user with multiple values, as shown above.

Like BigQuery does here, this is what I want it to look like:

答:
Below is for BigQuery Standard SQL

```<code>#standardSQL
SELECT id, ARRAY_AGG(STRUCT(key AS key, value AS value)) params
FROM `project.dataset.table`
GROUP BY id
</code>```

if to apply to your sample data  - result is

Title: How to concat rows based on ID,

Body:
Using standard SQL in bigquery:

Given a table such as: Where the values have been counted so only appear once

| id | key | value |
--------------------
| 1 | read |  aa   |
| 1 | read |  bb   |
| 1 | name |  abc  |
| 2 | read |  bb   |
| 2 | read |  cc   |
| 2 | name |  def  |
| 2 | value|  some |
| 3 | read |  aa   |

How can I make it so each row is one user and their respective values? e.g. NEST

So the table would look like:

| id | key | value |
--------------------
| 1 | read |  aa   |
|   | read |  bb   |
|   | name |  abc  |
| 2 | read |  bb   |
|   | read |  cc   |
|   | name |  def  |
|   | value|  some |
| 3 | read |  aa   |

I've tried using ARRAY_AGG on the column, which ends up listing all the values of that column.

I just need to have each row as a single user with multiple values, as shown above.

Like BigQuery does here, this is what I want it to look like:

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT id, ARRAY_AGG(STRUCT(key AS key, value AS value)) params
FROM `project.dataset.table`
GROUP BY id

if to apply to your sample data  - result is


问:
TTLauncherView url to view controllers? - iPhone SDK
Hey, I would like to know how to link a view controller to a item in the TTLauncher? </p>

```<code>[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL://What to write here?]
</code>```

答:
You link it to a URL in your TTURLMap that is linked to the view controller you want.  So you'd call for example:

```<code>[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL:@"tt://apple"]
</code>```

and then when you declare your TTURLMAP:

```<code>TTNavigator *navigator = [TTNavigator navigator];
[navigator.URLMap from:@"tt://apple" toViewController:[YourViewController class]];
</code>```

where YourViewController is the one you want to launch

Hope this helps

Body:
Hey, I would like to know how to link a view controller to a item in the TTLauncher?

[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL://What to write here?]

Body:
You link it to a URL in your TTURLMap that is linked to the view controller you want.  So you'd call for example:

[self launcherItemWithTitle:@"Apple" image:@"bundle://safari_logo.png" URL:@"tt://apple"]

and then when you declare your TTURLMAP:

TTNavigator *navigator = [TTNavigator navigator];
[navigator.URLMap from:@"tt://apple" toViewController:[YourViewController class]];

where YourViewController is the one you want to launch

Hope this helps


问:
how to test the relevant row in the db table has been locked using postgresql
I have one table and i locked it using id for update.

```<code>select name from tablename where id=2 for update
</code>```

how can i test the relevant row in the db table has been locked.

答:
Is for learning or training purposes, and if not what you are trying to accomplish?

Open two connections (using "psql", for example), and in each one run:

```<code>begin; select name from tablename where id=2 for update;
</code>```

The second one should block until the first one does either a rollback or commit.  This blockage is the evidence of the lock.  There are many variations, one or the other or both could be doing an actual UPDATE, rather than a SELECT...FOR UPDATE.

Body:
I have one table and i locked it using id for update.

select name from tablename where id=2 for update

how can i test the relevant row in the db table has been locked.

Body:
Is for learning or training purposes, and if not what you are trying to accomplish?

Open two connections (using "psql", for example), and in each one run:

begin; select name from tablename where id=2 for update;

The second one should block until the first one does either a rollback or commit.  This blockage is the evidence of the lock.  There are many variations, one or the other or both could be doing an actual UPDATE, rather than a SELECT...FOR UPDATE.


问:
QListWidgetItem when button clicked do actions
I have a QListWidget with some items. I did this to select an item from QListWidget:

```<code>connect(ui->mylist,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(onMyListItem(QListWidgetItem*)));
</code>```

Now in onMyListItem function I did this to check the index of the item:

```<code>int index=ui->mylist->currentRow();
    qDebug()<<"index item: "<<index;
</code>```

How can I do some actions when I select an item and click a showBtn button?

答:
I'll assume the button you're adding is a QAction, then you just need to connect its triggered() signal to a slot you create, say makeAction():

```<code>connect(someAction, SIGNAL(triggered()), this, SLOT(makeAction());
</code>```

Inside this slot, assuming it has access to the list, you can get the current item in the list and do the appropriate thing:

void makeAction()
{
    auto item = ui->mylist->currentItem();
    if (item)
    {
        // Do something
    }
}
```

Body:
I have a QListWidget with some items. I did this to select an item from QListWidget:

connect(ui->mylist,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(onMyListItem(QListWidgetItem*)));

Now in onMyListItem function I did this to check the index of the item:

int index=ui->mylist->currentRow();
    qDebug()<<"index item: "<<index;

How can I do some actions when I select an item and click a showBtn button?

Body:
I'll assume the button you're adding is a QAction, then you just need to connect its triggered() signal to a slot you create, say makeAction():

connect(someAction, SIGNAL(triggered()), this, SLOT(makeAction());

Inside this slot, assuming it has access to the list, you can get the current item in the list and do the appropriate thing:

void makeAction()
{
    auto item = ui->mylist->currentItem();
    if (item)
    {
        // Do something
    }
}


问:
How to install pip for python3.7 only?
I have python3.7 and I want to install pip. However when I do the following:

```<code>sudo apt install python3-pip
</code>```

It seems to download python version 3.6 and pip for that. Is there a way to not download python3.6 and just download pip for python3.7? It seems rather strange that pip is download a whole other package.

答:
Download get-pip file

```<code>$curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
</code>```

Install pip for python3.7

```<code>$python3.7 get-pip.py
</code>```

Check versions for both

```<code>$python3.7 -V && pip3 -V
Output:
Python 3.7.3
pip 19.1.1 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)
</code>```

Title: How to install pip for python3.7 only?

Body:
I have python3.7 and I want to install pip. However when I do the following:

sudo apt install python3-pip

It seems to download python version 3.6 and pip for that. Is there a way to not download python3.6 and just download pip for python3.7? It seems rather strange that pip is download a whole other package.

Body:
Download get-pip file

$curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Install pip for python3.7

$python3.7 get-pip.py

Check versions for both

$python3.7 -V && pip3 -V
Output:
Python 3.7.3
pip 19.1.1 from /usr/local/lib/python3.7/dist-packages/pip (python 3.7)


问:
Two values being compared before function returns the value
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

```<code>javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}
</code>```

Expected:

```<code>Returned true
Value was true
</code>```

Actual:

```<code>Value was false
Returned true
</code>```

答:
You are trying to return a promise from inside your function, in the moment you use promises you are working with async code. That means that in order to get the value from the promise, the promise needs to be fulfilled first.

In your case you are evaluating the return value of your function, not the returned value of the promise. Since you do not have an explicit return in your function, it is returning undefined. That is why you see value was false in the console. Then your promise gets fulfilled and you see Returned true in the console, but you never evaluated that value return by the promise.

Supposing that you are invoking your function from the global scope you will need to use .then syntax to get access to the value returned by your promise.

So if your function is something like this:

```<code>function myFunc() {
  return Promise.resolve()
    .then(value => {
      console.log('Returned true');
      return true;
    })
 }
</code>```

Your if statement should turn into something like this:

```<code>myFunc().then(value => {
   if(value) console.log('It is true')
   else console.log('Is it false')
 })
</code>```

Basically you wait for your promise to be fulfilled and when that happens you get the return value by param (in this simple example it is always true but it could be false as well).

I hope this helps you.

Body:
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}

Expected:

Returned true
Value was true

Actual:

Value was false
Returned true

Body:
You are trying to return a promise from inside your function, in the moment you use promises you are working with async code. That means that in order to get the value from the promise, the promise needs to be fulfilled first.

In your case you are evaluating the return value of your function, not the returned value of the promise. Since you do not have an explicit return in your function, it is returning undefined. That is why you see value was false in the console. Then your promise gets fulfilled and you see Returned true in the console, but you never evaluated that value return by the promise.

Supposing that you are invoking your function from the global scope you will need to use .then syntax to get access to the value returned by your promise.

So if your function is something like this:

function myFunc() {
  return Promise.resolve()
    .then(value => {
      console.log('Returned true');
      return true;
    })
 }

Your if statement should turn into something like this:

myFunc().then(value => {
   if(value) console.log('It is true')
   else console.log('Is it false')
 })

Basically you wait for your promise to be fulfilled and when that happens you get the return value by param (in this simple example it is always true but it could be false as well).

I hope this helps you.


问:
Swift: my destinationVC segue is showing nil
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

```<code>// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}
</code>```

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

答:
You can use below code to safely pass data to the ProfileViewController.

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let profile = ProfileController.shared.profile else { return }
        if segue.identifier == "signUpMemicTBC" {
            guard let tabBarController = segue.destination as? UITabBarController else { return }
            guard let profileController = tabBarController.viewControllers?.index(at: 2) as? ProfileViewController else {
                return
            }
            profileController.profile = profile
        }
    }
</code>```

Body:
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

Body:
You can use below code to safely pass data to the ProfileViewController.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let profile = ProfileController.shared.profile else { return }
        if segue.identifier == "signUpMemicTBC" {
            guard let tabBarController = segue.destination as? UITabBarController else { return }
            guard let profileController = tabBarController.viewControllers?.index(at: 2) as? ProfileViewController else {
                return
            }
            profileController.profile = profile
        }
    }


问:
Reading / Writing files in Javascript - IE6
I need a database storage system for Javascript where the state can be maintained on the local disk.

Here comes the spanners in the works :-

It only needs to support Internet Explorer but the minimum version must be IE6

Files need to be written so they can be read in again later (upon closing and re-opening of browser)

There can be no web server (unless it's extremely easy to distribute and does not require a install) since the HTML pages will be distributed on USB.

Does anyone know of any solutions that might help here?

答:
Have fun playing with userData. Apparently it does what you want in IE6/7

Then localStorage for IE8/9

Or you can use the heavier store.js which does the feature detection for you and apparently works in IE6+.

It should work in IE9 but no garantuees. I would recommend store.js as it's easier for maintenance and just works out of the box. You can also support other browsers that way.