问:
Unit testing dynamic queries in Entity Framework 4
When implementing a Unit of Work pattern with entity framework 4.0, what is the correct design to give the ability to create dynamic queries with CreateQuery method of the object context? And by correct I mean designing somehow that I can use it in unit test with mock objects.

Thanks.

答:
Don't know what you mean by "correct" it depends on your situation, but the general answer is that you will need some abstractions that can be replaced during test. For some inspiration, here is what we use (we use self tracking poco entities)

///
/// Object context interface for abstracting the service layer from the
/// implementation details of object storage.
///
public interface IObjectContext : IDisposable
{
    ///
    /// Returns the entity objects of the given type known by this object context.
    ///
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <returns>The instances of the given type already loaded into this object context</returns>
    IEnumerable<TEntity> GetManagedEntities<TEntity>() where TEntity : EntityBase;

    ///
    /// Creates an object set for the provided entity type.
    ///
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <returns></returns>
    IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : EntityBase;

    ///
    /// Applies the changes made to the provided entity object graph to this object context.
    ///
    /// <typeparam name="TEntity">The type of entity (inferred).</typeparam>
    /// <param name="entity">The entity object graph that has been modified.</param>
    void ApplyChanges<TEntity>(TEntity entity) where TEntity : EntityBase, IObjectWithChangeTracker;

    ///
    /// Saves the changes known by this object context instance to the database.
    ///
    void Save();

    ///
    /// Creates a new logical unit of work spanning a single business transaction.
    ///
    IUnitOfWork CreateUnitOfWork();

    ///
    /// Creates a new logical unit of work spanning a single business transaction.
    ///
    /// <param name="isolationLevel">The transaction isolation level used by the
    /// unit of work ambient transaction.</param>
    /// <returns></returns>
    IUnitOfWork CreateUnitOfWork(IsolationLevel isolationLevel);
}
```

<p>and for abstracting transactions</p>

<pre class="lang-cs prettyprint-override"><code>/// <summary>
/// Interface abstraction for a unit of work, aka all persistent work spanning a single
/// business transaction and to be performed in unity.
/// </summary>
/// <remarks>Used to support outer and inner units of work where one outer UoW may consist
/// of multiple nested inner UoW instances and have all of them share a transaction.</remarks>
public interface IUnitOfWork : IDisposable
{
    /// <summary>
    /// Gets the transaction isolation level used by the unit of work ambient transaction.
    /// </summary>
    /// <value>The isolation level.</value>
    IsolationLevel IsolationLevel { get; }

    /// <summary>
    /// Gets the transaction timeout time span used by the unit of work ambient transaction.
    /// </summary>
    /// <value>The transaction timeout duration.</value>
    TimeSpan TransactionTimeout { get; }

    /// <summary>
    /// Completes the unit of work that this instance represents.
    /// </summary>
    /// <remarks>
    /// For an outer unit of work, will persist all changes represented by this business
    /// transaction and will then signal the ambient transaction in use as complete.
    /// For an inner unit of work, will signal itself as completed to the outer unit of
    /// work that it is part of.
    /// </remarks>
    void Complete();
}
</code>```

then modify the object context generation code to support these interfaces + implement your UoW according to your needs (our implementation omitted for brevity). HTH

Body:
Don't know what you mean by "correct" it depends on your situation, but the general answer is that you will need some abstractions that can be replaced during test. For some inspiration, here is what we use (we use self tracking poco entities)

/// <summary>
/// Object context interface for abstracting the service layer from the
/// implementation details of object storage.
/// </summary>
public interface IObjectContext : IDisposable
{
    /// <summary>
    /// Returns the entity objects of the given type known by this object context.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <returns>The instances of the given type already loaded into this object context</returns>
    IEnumerable<TEntity> GetManagedEntities<TEntity>() where TEntity : EntityBase;

    /// <summary>
    /// Creates an object set for the provided entity type.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <returns></returns>
    IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : EntityBase;

    /// <summary>
    /// Applies the changes made to the provided entity object graph to this object context.
    /// </summary>
    /// <typeparam name="TEntity">The type of entity (inferred).</typeparam>
    /// <param name="entity">The entity object graph that has been modified.</param>
    void ApplyChanges<TEntity>(TEntity entity) where TEntity : EntityBase, IObjectWithChangeTracker;

    /// <summary>
    /// Saves the changes known by this object context instance to the database.
    /// </summary>
    void Save();

    /// <summary>
    /// Creates a new logical unit of work spanning a single business transaction.
    /// </summary>
    IUnitOfWork CreateUnitOfWork();

    /// <summary>
    /// Creates a new logical unit of work spanning a single business transaction.
    /// </summary>
    /// <param name="isolationLevel">The transaction isolation level used by the
    /// unit of work ambient transaction.</param>
    /// <returns></returns>
    IUnitOfWork CreateUnitOfWork(IsolationLevel isolationLevel);
}

and for abstracting transactions

/// <summary>
/// Interface abstraction for a unit of work, aka all persistent work spanning a single
/// business transaction and to be performed in unity.
/// </summary>
/// <remarks>Used to support outer and inner units of work where one outer UoW may consist
/// of multiple nested inner UoW instances and have all of them share a transaction.</remarks>
public interface IUnitOfWork : IDisposable
{
    /// <summary>
    /// Gets the transaction isolation level used by the unit of work ambient transaction.
    /// </summary>
    /// <value>The isolation level.</value>
    IsolationLevel IsolationLevel { get; }

    /// <summary>
    /// Gets the transaction timeout time span used by the unit of work ambient transaction.
    /// </summary>
    /// <value>The transaction timeout duration.</value>
    TimeSpan TransactionTimeout { get; }

    /// <summary>
    /// Completes the unit of work that this instance represents.
    /// </summary>
    /// <remarks>
    /// For an outer unit of work, will persist all changes represented by this business
    /// transaction and will then signal the ambient transaction in use as complete.
    /// For an inner unit of work, will signal itself as completed to the outer unit of
    /// work that it is part of.
    /// </remarks>
    void Complete();
}

then modify the object context generation code to support these interfaces + implement your UoW according to your needs (our implementation omitted for brevity). HTH


来源: stackexchange

问:
SwiftUI: double-click in Table row on macOS
I am using a Table with multiple columns (new in SwiftUI 3.0) to show my data, and I want to be able to double-click on the row to open a new window with another view (with information passed in through the row that was double-clicked). What's the simplest way to achieve that? I can't seem to find any way to handle double-click on a selected row.

This is my current code to display the table:

```<code>      Table(item, selection: $selection, sortOrder: $sorting) {
            TableColumn("RecordName") { itemModel in
                Text("\(itemModel.recordName ?? "no name")")
            }
            TableColumn("Model") { item in
                Text("\(item.deviceName ?? "no model")")
            }
            TableColumn("CreatedAt") { item in
                Text("\(item.deviceCreatedDate?.formatted() ?? "no date")")
            }
      }
</code>```

How do I handle a double-select action? Also, how do I open another view in another "window"?

答:
Using the onTapGesture with the count of 2 is actually handling double clicking.
Here is a simplified example.</p>
```<code>//
//  ContentView.swift
//  SUITable
//
//  Created by Hezi Shahmoon on 10/02/2022.
//

import SwiftUI

struct ContentView: View {
    @State private var items: [ItemModel] = Array(0...100).map { ItemModel(id: $0, recordName: "item \($0)", age: $0) }
    @State private var selection = Set<ItemModel.ID>()
    @State private var sorting = [KeyPathComparator(\ItemModel.age)]

    @State private var showingAlert = false

    var body: some View {
        Table(items, selection: $selection, sortOrder: $sorting) {
               TableColumn("RecordName") { itemModel in
                   Text("\(itemModel.recordName)")
                       .onTapGesture(count: 2, perform: {
                           showingAlert = true
                       })
                       .alert("Important message", isPresented: $showingAlert) {
                                   Button("OK", role: .cancel) { }
                       }
               }
         }
    }
}

struct ItemModel: Identifiable {
    var id: Int
    var recordName: String
    var age: Int
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using a Table with multiple columns (new in SwiftUI 3.0) to show my data, and I want to be able to double-click on the row to open a new window with another view (with information passed in through the row that was double-clicked). What's the simplest way to achieve that? I can't seem to find any way to handle double-click on a selected row.

This is my current code to display the table:

      Table(item, selection: $selection, sortOrder: $sorting) {
            TableColumn("RecordName") { itemModel in
                Text("\(itemModel.recordName ?? "no name")")
            }
            TableColumn("Model") { item in
                Text("\(item.deviceName ?? "no model")")
            }
            TableColumn("CreatedAt") { item in
                Text("\(item.deviceCreatedDate?.formatted() ?? "no date")")
            }
      }

How do I handle a double-select action? Also, how do I open another view in another "window"?

Body:
Using the onTapGesture with the count of 2 is actually handling double clicking.
Here is a simplified example.

//
//  ContentView.swift
//  SUITable
//
//  Created by Hezi Shahmoon on 10/02/2022.
//

import SwiftUI

struct ContentView: View {
    @State private var items: [ItemModel] = Array(0...100).map { ItemModel(id: $0, recordName: "item \($0)", age: $0) }
    @State private var selection = Set<ItemModel.ID>()
    @State private var sorting = [KeyPathComparator(\ItemModel.age)]

    @State private var showingAlert = false

    var body: some View {
        Table(items, selection: $selection, sortOrder: $sorting) {
               TableColumn("RecordName") { itemModel in
                   Text("\(itemModel.recordName)")
                       .onTapGesture(count: 2, perform: {
                           showingAlert = true
                       })
                       .alert("Important message", isPresented: $showingAlert) {
                                   Button("OK", role: .cancel) { }
                       }
               }
         }
    }
}

struct ItemModel: Identifiable {
    var id: Int
    var recordName: String
    var age: Int
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
Setting up React environment variables for dev and local
I am new to react and setting up environment variables for my project. Here is what I did..

added .env-cmdrc.json as follows

```<code>{
 "development":{
 "REACT_APP_BASE_URL": "https://servername:port/"
 },
 "staging":{
 "REACT_APP_BASE_URL": "http://servername:port/"
 },
  "local":{
  "REACT_APP_BASE_URL": "http://localhost:port/"
  }
 }
</code>```

installed npm

npm install env-cmd or npm install -g env-cmd

edited package.json as follows:

```<code> "start:development": "env-cmd -e development react-scripts start",
 "start:staging": "env-cmd -e staging react-scripts start",
 "start:local": "env-cmd -e local react-scripts start",
 "build:development": "env-cmd -e development react-scripts build",
 "build:staging": "env-cmd -e staging react-scripts build",
</code>```

tried - npm run start:development

was giving me env-cmd error

again ran

npm install env-cmd

Now tried - npm run start:development

Failed to find .rc file at default paths: [./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

I am doing it first time and would appreciate any help..what am I missing here..

答:
I tried your code, but it works well.

Check your code, ensure the location of your config file .env-cmdrc.json, it should be placed under root dict of your project (the same level with package.json)

Body:
I am new to react and setting up environment variables for my project. Here is what I did..

added .env-cmdrc.json as follows

{
 "development":{
 "REACT_APP_BASE_URL": "https://servername:port/"
 },
 "staging":{
 "REACT_APP_BASE_URL": "http://servername:port/"
 },
  "local":{
  "REACT_APP_BASE_URL": "http://localhost:port/"
  }
 }

installed npm

npm install env-cmd or npm install -g env-cmd

edited package.json as follows:

 "start:development": "env-cmd -e development react-scripts start",
 "start:staging": "env-cmd -e staging react-scripts start",
 "start:local": "env-cmd -e local react-scripts start",
 "build:development": "env-cmd -e development react-scripts build",
 "build:staging": "env-cmd -e staging react-scripts build",

tried - npm run start:development

was giving me env-cmd error

again ran

npm install env-cmd

Now tried - npm run start:development

Failed to find .rc file at default paths: [./.env-cmdrc,./.env-cmdrc.js,./.env-cmdrc.json] at getRCFile

I am doing it first time and would appreciate any help..what am I missing here..


问:
How to install a specific version of Node on Ubuntu?
I would like to install NodeJS version 0.8.18 on Ubuntu 12.04. I tried to install the newest version and then reverting to 0.8.18 by using nvm, but when I run my code apparently there is some problem with the packages installed and the two versions (latest and 0.8.18). Since I don't know how to solve that problem, I cleaned the machine from the Node installation and thought about installing directly the version I'm interested in (v0.8.18).

答:
In ubuntu specific version of node can be installed with help of nvm

install nvm

```<code>sudo apt install curl
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.bashrc
</code>```

To install a particular version of node, use the command nvm install and add the number of the version.

```<code>nvm install 10.15.2
node -v
</code>```

Body:
In ubuntu specific version of node can be installed with help of nvm

install nvm

sudo apt install curl
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.bashrc

To install a particular version of node, use the command nvm install and add the number of the version.

nvm install 10.15.2
node -v


问:
HTML Emails: The Use Case for Nested Tables
I'm relatively new to HTML Email Development, and I'm trying to wrap my head around nested tables, specifically WHEN to nest a table, create a tr tag pair, or add a td tag pair.
Below is a code snippet from a real-world example of an HTML Email located at this URL to illustrate the basis of my confusion: https://reallygoodemails.com/emails/save-30-for-our-winter-sale/live

Our Winter Sale gets better

WINTER SALE: 30% OFF. FREE SHIPPING AVAILABLE WITH AN ACCOUNT. LEARN MORE.

```

There are SIX tables here and—although I understand what Table 1 and Table 6 are doing—the other four tables are confusing.

Table 2 looks like it defines the wrapper for the page. But doesn’t Table 1 do that already? If so, why is it there?

Table 3 and Table 4 look like they both act as the main container for the HTML email template, since they both define the width of the main table. But I don’t understand why Table 3 is necessary when Table 4 specifies the same width of 600px?

Table 5 has a class of “Column-1”, but there isn’t a class labelled “Column-1” in the stylesheets found in the head of the document, so why is it there?

These observations, among others, have made me realize that there is a TON of variation in HTML Email Development whenever nested tables are concerned. So much so that it makes it difficult to derive a general rule of thumb for table, tr, and td use. But from what I can see:

Tables are used for cutting the page into blocks and specifying the size of said blocks.

Tr tag pairs are used for defining separate sections in an HTML Email Template.

Td tag pairs are used for content placement (in child tables) or content formatting (in parent tables).

Can anyone validate my observations or, better yet, give me a more detailed explanation of WHEN to make a new table, tr, or td in the context of HTML Email Development?

Thanks in advance!

P.S. Please correct me if I am wrong on any of my observations. I truly want to learn the nuances of this field to the best of my ability.

答:
The one and only reason we still need to use tables in HTML emails today is… Outlook. And more specifically: Outlook on Windows. And even more specifically: Outlook on Windows, versions 2007 and up.

In 2007, Microsoft decided to change Outlook’s rendering engine from Internet Explorer to… Word. And Word is not very good at rendering HTML and CSS. Not only does it only support partial CSS from up to 2007 (so no flexbox, no border-radius, etc.), but it usually does a poor job at what it is supposed to support. For example, the padding property works, but not on
 elements.

With time, I’ve come to use tables only in the following cases:

To set a fixed width on an element (using
).

To set two elements side by side (using two siblings ).

To set a padding, background-color or a border style.

Back to your post and example, all your observations on tables 1-6 seem right to me. The code looks really bloated (with lots of unecessary styles too). My guess is this comes from the build process of this email. Either it was coded manually from a previous template that needed all these tables and the developer wasn't adventurous enough to remove any of them. Or maybe the email is the output of an email builder (which very often add way too many code because their goal is to cover as many options as possible with a similar output code). The second option seems more possible to me considering the code from the text (with all the nested ).

I tried to recode the sample you copied above. And here’s what it looks like.

            WINTER SALE: 30% OFF. FREE SHIPPING AVAILABLE WITH AN ACCOUNT. LEARN MORE.

```

Only two tables are needed. The first one is specifically for Outlook inside a conditional comment. It is used to set the width of the container. The second one is use for both the background:#000; and the padding:10px.

If you want to learn more about Outlook and HTML emails in general, I wrote the following posts:

Email Coding Guidelines

Making sense of Outlook’s rendering engine

And I can’t recommend enough the #emailgeeks Slack and its #email-code channel filled with passionate email developers helping and learning from each others.

Body:
I'm relatively new to HTML Email Development, and I'm trying to wrap my head around nested tables, specifically WHEN to nest a table, create a tr tag pair, or add a td tag pair.
Below is a code snippet from a real-world example of an HTML Email located at this URL to illustrate the basis of my confusion: https://reallygoodemails.com/emails/save-30-for-our-winter-sale/live

Our Winter Sale gets better

WINTER SALE: 30% OFF. FREE SHIPPING AVAILABLE WITH AN ACCOUNT. LEARN MORE.

There are SIX tables here and—although I understand what Table 1 and Table 6 are doing—the other four tables are confusing.

Table 2 looks like it defines the wrapper for the page. But doesn’t Table 1 do that already? If so, why is it there?

Table 3 and Table 4 look like they both act as the main container for the HTML email template, since they both define the width of the main table. But I don’t understand why Table 3 is necessary when Table 4 specifies the same width of 600px?

Table 5 has a class of “Column-1”, but there isn’t a class labelled “Column-1” in the stylesheets found in the head of the document, so why is it there?

These observations, among others, have made me realize that there is a TON of variation in HTML Email Development whenever nested tables are concerned. So much so that it makes it difficult to derive a general rule of thumb for table, tr, and td use. But from what I can see:

Tables are used for cutting the page into blocks and specifying the size of said blocks.

Tr tag pairs are used for defining separate sections in an HTML Email Template.

Td tag pairs are used for content placement (in child tables) or content formatting (in parent tables).

Can anyone validate my observations or, better yet, give me a more detailed explanation of WHEN to make a new table, tr, or td in the context of HTML Email Development?

Thanks in advance!

P.S. Please correct me if I am wrong on any of my observations. I truly want to learn the nuances of this field to the best of my ability.

Body:
The one and only reason we still need to use tables in HTML emails today is… Outlook. And more specifically: Outlook on Windows. And even more specifically: Outlook on Windows, versions 2007 and up.

In 2007, Microsoft decided to change Outlook’s rendering engine from Internet Explorer to… Word. And Word is not very good at rendering HTML and CSS. Not only does it only support partial CSS from up to 2007 (so no flexbox, no border-radius, etc.), but it usually does a poor job at what it is supposed to support. For example, the padding property works, but not on <div> elements.

With time, I’ve come to use tables only in the following cases:

To set a fixed width on an element (using <table style="width:600px">).

To set two elements side by side (using two siblings <td>).

To set a padding, background-color or a border style.

Back to your post and example, all your observations on tables 1-6 seem right to me. The code looks really bloated (with lots of unecessary styles too). My guess is this comes from the build process of this email. Either it was coded manually from a previous template that needed all these tables and the developer wasn't adventurous enough to remove any of them. Or maybe the email is the output of an email builder (which very often add way too many code because their goal is to cover as many options as possible with a similar output code). The second option seems more possible to me considering the code from the text (with all the nested <span><span><u><i><a>).

I tried to recode the sample you copied above. And here’s what it looks like.

<!--[if mso]><table cellpadding="0" cellspacing="0" border="0" style="width:600px;" role="presentation"><tr><td><![endif]-->
  <div style="margin:0 auto; width:100%; max-width:600px;">
    <table border="0" cellpadding="0" cellspacing="0" role="presentation" style="width:100%; background:#000;">
      <tr>
        <td style="padding:10px;">
          <p style="margin:0; text-align:center; letter-spacing:2px; color:#fff; font:italic 12px/18px neusanextpro-condensedlight, sans-serif;">
            <a href="https://www.example.com" target="_blank" style="color:#fff; text-decoration:none;">WINTER SALE: 30% OFF.</a>&nbsp;FREE SHIPPING AVAILABLE WITH AN ACCOUNT. <a href="https://www.example.com" target="_blank" style="color:#fff; text-decoration:underline;">LEARN MORE.</a>
          </p>
        </td>
      </tr>
    </table>
  </div>
  <!--[if mso]></td></tr></table><![endif]-->

Only two tables are needed. The first one is specifically for Outlook inside a conditional comment. It is used to set the width of the container. The second one is use for both the background:#000; and the padding:10px.

If you want to learn more about Outlook and HTML emails in general, I wrote the following posts:

Email Coding Guidelines

Making sense of Outlook’s rendering engine

And I can’t recommend enough the #emailgeeks Slack and its #email-code channel filled with passionate email developers helping and learning from each others.


问:
insert PCDATA from the child element into an attribute
I want to insert PCDATA from the child element into a selected node attribute

XML

```<code><root>
  <tag>
     <tag1>SOME TEXT</tag1>
  </tag>
</root>
</code>```

MY XSL

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xi="http://www.w3.org/2001/XInclude" version="1.0">

    <xsl:template match="root">
        <tag-out>
            <xsl:attribute name="text">
                <!-- What should I select? -->
                <xsl:value-of select="tag/tag1/???"/>
            </xsl:attribute>
        <tag-out>
    </xsl:template>

    ...........

</xsl:stylesheet>
</code>```

Desired output XML

```<code><root-out text="SOME TEXT">
   <tag-out/>
</root-out>
</code>```

Thanks

答:
What's wrong with simply doing

```<code>   <tag-out text="{tag/tag1}"></tag-out>
</code>```

? Of course your sample with

```<code>    <tag-out>
        <xsl:attribute name="text">

            <xsl:value-of select="tag/tag1"/>
        </xsl:attribute>
    <tag-out>
</code>```

is also possible. But as your post is tagged XSLT 2.0 I would at least do

```<code>    <tag-out>
        <xsl:attribute name="text" select="tag/tag1"/>
    <tag-out>
</code>```

if you really need xsl:attribute.

ContentLicense: CC BY-SA 3.0

Body:
I want to insert PCDATA from the child element into a selected node attribute

XML

<root>
  <tag>
     <tag1>SOME TEXT</tag1>
  </tag>
</root>

MY XSL

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xi="http://www.w3.org/2001/XInclude" version="1.0">

    <xsl:template match="root">
        <tag-out>
            <xsl:attribute name="text">

                <xsl:value-of select="tag/tag1/???"/>
            </xsl:attribute>
        <tag-out>
    </xsl:template>

    ...........

</xsl:stylesheet>

Desired output XML

<root-out text="SOME TEXT">
   <tag-out/>
</root-out>

Thanks

Body:
What's wrong with simply doing

   <tag-out text="{tag/tag1}"></tag-out>

? Of course your sample with

    <tag-out>
        <xsl:attribute name="text">

            <xsl:value-of select="tag/tag1"/>
        </xsl:attribute>
    <tag-out>

is also possible. But as your post is tagged XSLT 2.0 I would at least do

    <tag-out>
        <xsl:attribute name="text" select="tag/tag1"/>
    <tag-out>

if you really need xsl:attribute.


问:
Github actions: How to cache dependencies between workflow runs of different branches?
I have a CI that runs at every pull request created and at every push of a new commit. This CI installs Python dependencies and then run some tests. I use two separate requirements.txt files because one of them contains heavier packages and they are handled differently in Docker.
I am trying to use the actions/cache@v2 action to cache the dependencies but from what I could understand, it only caches between runs in the same branch. So when I create a new PR, for example, cache is not detected from another branch and everything is installed from scratch.
Is there a way to cache dependencies across workflow runs? So the cache created by the CI in one branch can be used by another branch if nothing was changed in the requirements?

Looking at the logs of the workflow that ran in two different branches the cache key is the same:

Workflow in branchA

```<code>Cache not found for input keys: /opt/hostedtoolcache/Python/3.8.12/x64-03a86b868f006751e123da18168c989ab4c3c2713de4f5c87cf732ffbb6fb4ae-cd1b416332d9d5b55f413e2bd74c2efce6107aef1ce3f497fa5a81b9abc83deb
</code>```

Workflow in branchB

```<code>Cache not found for input keys: /opt/hostedtoolcache/Python/3.8.12/x64-03a86b868f006751e123da18168c989ab4c3c2713de4f5c87cf732ffbb6fb4ae-cd1b416332d9d5b55f413e2bd74c2efce6107aef1ce3f497fa5a81b9abc83deb
</code>```

This is my workflow:

name: ci

on:
  pull_request:
    types: [opened, synchronize]
    branches-ignore:
      - "master"
      - "staging"

  push:
    branches-ignore:
      - "master"
      - "staging"

jobs:
  run-tests:
    name: Run tests
    runs-on: ubuntu-latest

    steps:
      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Cache dependencies
        uses: actions/cache@v2
        with:
          path: ${{ env.pythonLocation }}
          key: ${{ env.pythonLocation }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('requirements-ml.txt') }}

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install -r requirements.txt
          python -m pip install -r requirements-ml.txt
```

答:
The solution to my problem was very silly but effective. I created a specific workflow for the staging branch for every commit push that will update the cache (if needed). This is helpful because all the development branches are created off of the staging branch, and every cache available in a base branch is also available to the derived branches. So at the end, the solution is like the original post but with the event's updated.

From github's docs:

A workflow can access and restore a cache created in the current branch, the base branch (including base branches of forked repositories), or the default branch (usually main). For example, a cache created on the default branch would be accessible from any pull request. Also, if the branch feature-b has the base branch feature-a, a workflow triggered on feature-b would have access to caches created in the default branch (main), feature-a, and feature-b.

name: update-cache

on:
  push:
    branches:
      - "staging"

jobs:
  # This workflow builds the Python package dependencies every time that the requirements
  # files are modified and store it in cache to be accessible by all the CI in all other
  # branches.
  build-cache:
    name: Build Cache
    runs-on: ubuntu-latest

    steps:
      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Cache dependencies
        uses: actions/cache@v2
        id: cache
        with:
          path: ${{ env.pythonLocation }}
          key: ${{ env.pythonLocation }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('requirements-ml.txt') }}
          restore-keys:
            ${{ env.pythonLocation }}-

      - if: steps.cache.outputs.cache-hit != 'true'
        name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install -r requirements.txt
          python -m pip install -r requirements-ml.txt

```

Body:
I have a CI that runs at every pull request created and at every push of a new commit. This CI installs Python dependencies and then run some tests. I use two separate requirements.txt files because one of them contains heavier packages and they are handled differently in Docker.
I am trying to use the actions/cache@v2 action to cache the dependencies but from what I could understand, it only caches between runs in the same branch. So when I create a new PR, for example, cache is not detected from another branch and everything is installed from scratch.
Is there a way to cache dependencies across workflow runs? So the cache created by the CI in one branch can be used by another branch if nothing was changed in the requirements?

Looking at the logs of the workflow that ran in two different branches the cache key is the same:

Workflow in branchA

Cache not found for input keys: /opt/hostedtoolcache/Python/3.8.12/x64-03a86b868f006751e123da18168c989ab4c3c2713de4f5c87cf732ffbb6fb4ae-cd1b416332d9d5b55f413e2bd74c2efce6107aef1ce3f497fa5a81b9abc83deb

Workflow in branchB

Cache not found for input keys: /opt/hostedtoolcache/Python/3.8.12/x64-03a86b868f006751e123da18168c989ab4c3c2713de4f5c87cf732ffbb6fb4ae-cd1b416332d9d5b55f413e2bd74c2efce6107aef1ce3f497fa5a81b9abc83deb

This is my workflow:

name: ci

on:
  pull_request:
    types: [opened, synchronize]
    branches-ignore:
      - "master"
      - "staging"

  push:
    branches-ignore:
      - "master"
      - "staging"

jobs:
  run-tests:
    name: Run tests
    runs-on: ubuntu-latest

    steps:
      - name: Set up Python 3.8
        uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Cache dependencies
        uses: actions/cache@v2
        with:
          path: ${{ env.pythonLocation }}
          key: ${{ env.pythonLocation }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('requirements-ml.txt') }}

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install -r requirements.txt
          python -m pip install -r requirements-ml.txt


问:
Remove whole parent div if contained child div is empty
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

<div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
   <div class="et_pb_column"><div class="et_pb_text"></div></div>
</div>

</code>```

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

```<code><div class="et_pb_row_inner">
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
</div>

<div class="et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

<div class=".et_pb_row_inner"> <!-- second column text empty, remove whole row -->
   <div class="et_pb_column"><div class="et_pb_text">HAS TEXT</div></div>
   <div class="et_pb_column"><div class="et_pb_text">EMPTY</div></div>
</div>

</code>```

I found a code snippet and tried the following:

```<code>$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});
</code>```

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?

答: Try accessing the _inner div using the Child Nodes of the div with no text. You can run the _inner class selector on these with the .find function on the parent div.</p>

Body:
I'm trying to achieve the following:

I have multiple divs with the class "et_pb_row_inner" that contain two columns each. Each of the columns contain a text container with the class "et_pb_text".

Here's the basic html:

I need a way to check if the text in the second column of each row is empty and if so remove the whole row. Like so:

HAS TEXT

HAS TEXT

HAS TEXT

EMPTY

HAS TEXT

EMPTY

I found a code snippet and tried the following:

$(function() {
    $('.et_pb_row_inner').each(function() {
        if ($('.et_pb_text', this).text() == "" ) {
            $('.et_pb_row_inner').hide();
        }
    });
});

It kind of works, but it removes ALL divs with the class "et_pb_row_inner", not just the ones that contain the empty text div.

I guess it's just tweaking the code a little, but I can't get it working.

Any ideas?


问:
Is there a cleaner way to map an object to a class (e.g. using a dictionary)?

public static class SceneToGame{
    public static GameParentServer Server(int scene, Server server){
        switch (scene){
            case 1:
                return new SnapGameServer(server);
            default:
                return null;
        }
    }
}
```

I'm currently using this to map ints to classes with a common parent. Is there a cleaner way to do this? From what I've read you can't because C# is type safe despite this being type safe.

答:
Applying the changes suggested by @clemens and @richard-deeming in comments on the original post, here is a possible implementation; using an enum rather than int for scene, and a switch expression (available from C# 8 [docs]) rather than a switch statement.

```<code>public enum SceneType
{
    Undefined, //Undefined = 0,
    Snap,      //Snap = 1,
    Ultra,     //Ultra = 2,
    Ninja      //Ninja = 3
}
</code>```

As pointed out by @oliver in the comments to this answer, adding a default value (in this example, Undefined) in your enum will ensure that if any SceneType variable in your code is not populated, the value of that variable will default to Undefined rather than e.g. Snap.

Unless you really need to make sure that SceneType.Snap has the numerical value of 1 (and so on), your enum does not need to define specific numerical values for each enum value.

```<code>public static GameParentServer Server(SceneType scene, Server server)
{
    return scene switch
    {
        Snap  => new SnapGameServer(server),
        Ultra => new UltraGameServer(server),
        Ninja => new NinjaGameServer(server),
        _ => null
    }
}
</code>```

Body:
public static class SceneToGame{
    public static GameParentServer Server(int scene, Server server){
        switch (scene){
            case 1:
                return new SnapGameServer(server);
            default:
                return null;
        }
    }
}

I'm currently using this to map ints to classes with a common parent. Is there a cleaner way to do this? From what I've read you can't because C# is type safe despite this being type safe.

Body:
Applying the changes suggested by @clemens and @richard-deeming in comments on the original post, here is a possible implementation; using an enum rather than int for scene, and a switch expression (available from C# 8 [docs]) rather than a switch statement.

public enum SceneType
{
    Undefined, //Undefined = 0,
    Snap,      //Snap = 1,
    Ultra,     //Ultra = 2,
    Ninja      //Ninja = 3
}

As pointed out by @oliver in the comments to this answer, adding a default value (in this example, Undefined) in your enum will ensure that if any SceneType variable in your code is not populated, the value of that variable will default to Undefined rather than e.g. Snap.

Unless you really need to make sure that SceneType.Snap has the numerical value of 1 (and so on), your enum does not need to define specific numerical values for each enum value.

public static GameParentServer Server(SceneType scene, Server server)
{
    return scene switch
    {
        Snap  => new SnapGameServer(server),
        Ultra => new UltraGameServer(server),
        Ninja => new NinjaGameServer(server),
        _ => null
    }
}


问:
How to run useEffect before render for authentication
I have reading component which must show only when user is loggedIn. I now redirect the user to /login page if the user is not authenticated. But during the redirect, the reading page is displayed for a few milli seconds allowing the un-authenticated user to see a flickering of the reading page during redirection.

I tried using useLayoutEffect instead of useEffect but the same flickering happens. Also tried without using useEffect or useLayoutEffect and within a function, but still the same

I get the userInfo from a global state, which gets the userInfo from the cookie. For state management I use recoil.

Reading Page: (which must be protected and if no user, redirect to login page)

```<code>function index() {
  const router = useRouter();
  const userInfo = useRecoilValue(userAtom);   ---> userInfo is recoil global state

  useLayoutEffect(() => {
    if (!userInfo) {
      router.push("/login?redirect=/reading");
    }
  }, []);

  return (//some code)
</code>```

Note:
Adding a Loader worked, but is there any better way?

答:
Check the authentication state

show loader based on authentication state

Redirect the user

Body:
I have reading component which must show only when user is loggedIn. I now redirect the user to /login page if the user is not authenticated. But during the redirect, the reading page is displayed for a few milli seconds allowing the un-authenticated user to see a flickering of the reading page during redirection.

I tried using useLayoutEffect instead of useEffect but the same flickering happens. Also tried without using useEffect or useLayoutEffect and within a function, but still the same

I get the userInfo from a global state, which gets the userInfo from the cookie. For state management I use recoil.

Reading Page: (which must be protected and if no user, redirect to login page)

function index() {
  const router = useRouter();
  const userInfo = useRecoilValue(userAtom);   ---> userInfo is recoil global state

  useLayoutEffect(() => {
    if (!userInfo) {
      router.push("/login?redirect=/reading");
    }
  }, []);

  return (//some code)

Note:
Adding a Loader worked, but is there any better way?


问:
How to change a Flutter app language without restarting the app?
In the settings page of my app, I would like to add an option that controls the app language.

I can set the language before starting the app like this:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // other arguments
      locale: Locale('ar'),
    );
  }
```

But is it possible to change the language without restarting the app?

答:
You can use the most popular GetX library as well.

Call Get.updateLocale(locale) to update the locale. Translations then automatically use the new locale.

```<code>var locale = Locale('en', 'US');
Get.updateLocale(locale);
</code>```

Body:
In the settings page of my app, I would like to add an option that controls the app language.

I can set the language before starting the app like this:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // other arguments
      locale: Locale('ar'),
    );
  }

But is it possible to change the language without restarting the app?

Body:
You can use the most popular GetX library as well.

Call Get.updateLocale(locale) to update the locale. Translations then automatically use the new locale.

var locale = Locale('en', 'US');
Get.updateLocale(locale);


问:
Hadoop release missing /conf directory
I am trying to install a single node setup of Hadoop on Ubuntu.
I started following the instructions on the Hadoop 2.3 docs.

But I seem to be missing something very simple.

First, it says to

To get a Hadoop distribution, download a recent stable release from one of the Apache Download Mirrors.

Then,

Unpack the downloaded Hadoop distribution. In the distribution, edit the file conf/hadoop-env.sh to define at least JAVA_HOME to be the root of your Java installation.

However, I can't seem to find the conf directory.

I downloaded a release of 2.3 at one of the mirrors. Then unpacked the tarball, an ls of the inside returns:

```<code>$ ls
bin  etc  include  lib  libexec  LICENSE.txt  NOTICE.txt  README.txt  sbin  share
</code>```

I was able to find the file they were referencing, just not in a conf directory:

```<code>$ find . -name hadoop-env.sh
./etc/hadoop/hadoop-env.sh
</code>```

Am I missing something, or am I grabbing the wrong package? Or are the docs just outdated?

If so, anyone know where some more up-to date docs are?

答:
The conf directory for Hadoop's (2022) version 3.3.1 is located in src/main directory:

$HOME/hadoop/hadoop3.3/hadoop-common-project/hadoop-common/src/main/

Title: Hadoop release missing /conf directory

Body:
I am trying to install a single node setup of Hadoop on Ubuntu.
I started following the instructions on the Hadoop 2.3 docs.

But I seem to be missing something very simple.

First, it says to

To get a Hadoop distribution, download a recent stable release from one of the Apache Download Mirrors.

Then,

Unpack the downloaded Hadoop distribution. In the distribution, edit the file conf/hadoop-env.sh to define at least JAVA_HOME to be the root of your Java installation.

However, I can't seem to find the conf directory.

I downloaded a release of 2.3 at one of the mirrors. Then unpacked the tarball, an ls of the inside returns:

$ ls
bin  etc  include  lib  libexec  LICENSE.txt  NOTICE.txt  README.txt  sbin  share

I was able to find the file they were referencing, just not in a conf directory:

$ find . -name hadoop-env.sh
./etc/hadoop/hadoop-env.sh

Am I missing something, or am I grabbing the wrong package? Or are the docs just outdated?

If so, anyone know where some more up-to date docs are?


问:
How i Scroll web browser control in wp7
i want to swipe webbrowser Control which is on pivot item ,each pivot item
has a web control .i want to swipe with web browser control .
but i don't have any idea.but swiping is necessary in my project .is there any method to doing this if yes then please send me sample code for this .. </p>

答:
This is a bind if you have some different sections of HTML you want to display in a Pivot. If you are targetting WP7 Mango it might be possible for you to convert your HTML to RTF and then use a RichTextBox instead of a WebBrowser. However if your HTML is fairly complex, this probably isn't going to work for you.

Alternatively you could place your WebBrowser in a pivot item with a transparent Rectangle above it in the Z-order. Make sure that Rectangle swallows any gestures and doesn't pass them through to the WebBrowser control - that way you will be able to swipe left and right on the WebBrowser to get the pivot to move.

Next you can use the GestureService on this transparent rectangle to recognize vertical pans/swipes and taps to take you to a full page view of your WebBrowser content. In this full page view you would have a fully interactive WebBrowser control.

Title: How i Scroll web browser control in wp7


问:
Multiple loop in list comprehension
I have a problem set in hand, the description is something like:

We have 2 lists ie "nums1" and "nums2" and 2 integers m and n

```<code>nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2
</code>```

Here "m" denotes number of elements to be picked from "nums1" and "n" denotes the number of elements to be picked from "nums2".
There are other ways ofcourse, but I want to create a list with only "list comprehension" on the above conditions.

With a simple for loop I can achieve that with:

```<code>li = []
for i in range(m):
  li.append(nums1[i])
for j in range(n):
  li.append(nums2[j])
print(li)
</code>```

I tried the following but the outcome result is not as expected:

```<code>[a for a in nums1 for b in nums2]
</code>```

Expected output:
[1, 2, 2, 3, 5]

Also, does list comprehension supports multiple loop?

Title: Multiple loop in list comprehension

Body:
I have a problem set in hand, the description is something like:

We have 2 lists ie "nums1" and "nums2" and 2 integers m and n

nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2

Here "m" denotes number of elements to be picked from "nums1" and "n" denotes the number of elements to be picked from "nums2".
There are other ways ofcourse, but I want to create a list with only "list comprehension" on the above conditions.

With a simple for loop I can achieve that with:

li = []
for i in range(m):
  li.append(nums1[i])
for j in range(n):
  li.append(nums2[j])
print(li)

I tried the following but the outcome result is not as expected:

[a for a in nums1 for b in nums2]

Expected output:
[1, 2, 2, 3, 5]

Also, does list comprehension supports multiple loop?

Body:
nums1 = [1, 2, 3, 7, 8, 9]
m = 3
nums2 = [2, 5, 6]
n = 2

ll = sorted([a for b in [nums1[:m], nums2[:n]] for a in b])

print(ll)

Output

[1, 2, 2, 3, 5]


问:
STRING_AGG with Union All
I want to do STRING_AGG with union all. here are my tables.

```<code>        SELECT
            C1 = P1
        FROM
            elt.Api

        UNION ALL

        SELECT
            C1 = E1
        FROM
            elt.Api2
</code>```

for one table STRING_AGG is working fine.

```<code>SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(P1,'N/A')), ',') AS C1 FROM
    elt.Api
</code>```

how should I do same with UNION ALL? Do I have to write the cursor for this ?

答:
Try Something like this</p>
```<code>SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(c1,'N/A')), ',') AS C1
FROM
(SELECT
        C1 = P1
    FROM
        elt.Api

    UNION ALL

    SELECT
        C1 = E1
    FROM
        elt.Api2
) A
</code>```

Title: STRING_AGG with Union All

Body:
I want to do STRING_AGG with union all. here are my tables.

        SELECT
            C1 = P1
        FROM
            elt.Api

        UNION ALL

        SELECT
            C1 = E1
        FROM
            elt.Api2

for one table STRING_AGG is working fine.

SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(P1,'N/A')), ',') AS C1 FROM
    elt.Api

how should I do same with UNION ALL? Do I have to write the cursor for this ?

Body:
Try Something like this

SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(c1,'N/A')), ',') AS C1
FROM
(SELECT
        C1 = P1
    FROM
        elt.Api

    UNION ALL

    SELECT
        C1 = E1
    FROM
        elt.Api2
) A


问:
Could not access file: Could not access file: Could not access file: PHP Mailer issue
Code is working fine without attachments. and attachment code is working fine on another page anybody can help to solve this?
<?php</p>
```<code>require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port     = 465;
$mail->Username = "info@guildsconnect.org";
$mail->Password = "Guildsconnect";
$mail->Host     = "webs10rdns1.websouls.net";
$mail->Mailer   = "smtp";
$mail->SetFrom($contact_email, $contact_name);
$mail->AddReplyTo($contact_email, $contact_name);
$mail->AddAddress("hashimbhatti906@gmail.com");
$mail->Subject = $sub1;
$mail->WordWrap   = 80;
$mail->MsgHTML($emailbodyis);

foreach ($_FILES["attachment"]["name"] as $k => $v) {
    $mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}

$mail->IsHTML(true);

if(!$mail->Send()) {
    $_SESSION["error"] = "Problem in Sending Mail.";
} else {
    $_SESSION["success"] = "Mail Sent Successfully.";
}

?>
</code>```

答:
Firstly, you're using a very old and unsupported version of PHPMailer, so upgrade. It also looks like you have based your code on a very old example.

You are not handling the file upload safely, not validating the uploaded file before trying to use it, as per the PHP docs.

PHPMailer provides an example that shows how to handle and upload and attach it correctly. The key parts are to use move_uploaded_file() to validate the upload before using it, and not to trust the supplied filename. To paraphrase the example:

    //Extract an extension from the provided filename
    $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
    //Define a safe location to move the uploaded file to, preserving the extension
    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'])) . '.' . $ext;

    if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
        //Now create a message
        $mail = new PHPMailer();
...
        //Attach the uploaded file
        if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
            $msg .= 'Failed to attach file ' . $_FILES['attachment']['name'];
        }
        if (!$mail->send()) {
            $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
        } else {
            $msg .= 'Message sent!';
        }
    } else {
        $msg .= 'Failed to move file to ' . $uploadfile;
    }
```

You don't need to set Mailer yourself; it's already done for you by isSMTP().

Body:
Code is working fine without attachments. and attachment code is working fine on another page anybody can help to solve this?
<?php

require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port     = 465;
$mail->Username = "info@guildsconnect.org";
$mail->Password = "Guildsconnect";
$mail->Host     = "webs10rdns1.websouls.net";
$mail->Mailer   = "smtp";
$mail->SetFrom($contact_email, $contact_name);
$mail->AddReplyTo($contact_email, $contact_name);
$mail->AddAddress("hashimbhatti906@gmail.com");
$mail->Subject = $sub1;
$mail->WordWrap   = 80;
$mail->MsgHTML($emailbodyis);

foreach ($_FILES["attachment"]["name"] as $k => $v) {
    $mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}

$mail->IsHTML(true);

if(!$mail->Send()) {
    $_SESSION["error"] = "Problem in Sending Mail.";
} else {
    $_SESSION["success"] = "Mail Sent Successfully.";
}

?>

Body:
Firstly, you're using a very old and unsupported version of PHPMailer, so upgrade. It also looks like you have based your code on a very old example.

You are not handling the file upload safely, not validating the uploaded file before trying to use it, as per the PHP docs.

PHPMailer provides an example that shows how to handle and upload and attach it correctly. The key parts are to use move_uploaded_file() to validate the upload before using it, and not to trust the supplied filename. To paraphrase the example:

    //Extract an extension from the provided filename
    $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
    //Define a safe location to move the uploaded file to, preserving the extension
    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'])) . '.' . $ext;

    if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
        //Now create a message
        $mail = new PHPMailer();
...
        //Attach the uploaded file
        if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
            $msg .= 'Failed to attach file ' . $_FILES['attachment']['name'];
        }
        if (!$mail->send()) {
            $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
        } else {
            $msg .= 'Message sent!';
        }
    } else {
        $msg .= 'Failed to move file to ' . $uploadfile;
    }

You don't need to set Mailer yourself; it's already done for you by isSMTP().


问:
Sum Up the Elements of a Collection
I have a userform that has a series of comboboxes (the number of boxes changes depending on another combobox in another userform) and when the user changes the comboboxes and clicks the button, the code looks up the price of each item associated with the selection and passes it to a collection. This part of the code works.

I want to take each of the prices in the collection and add them together.

Private Sub Button_Add_Click()

Dim coll as Collection
Dim priceColl As Collection
Dim item As Variant
Dim i As Long
Dim d As Long
Dim priceDrawer As Integer
Dim tableArray As Range
Dim ws As Worksheet

Set coll = New Collection
Set priceColl = New Collection
d = Me.cbo_DrawerNumber.Value
Set ws = ThisWorkbook.Sheets("LookupTables")
With ws
    Set tableArray = .Range(.Cells(3, 7), .Cells(100000, 9))
End With

'adds items from combobox to a collection
For i = 1 To d
    item = Me.Controls("ComboBox" & i).Value
    coll.Add item
Next i

'looks up price associated with each item and adds it to a different collection
For Each item In coll
    priceDrawer = WorksheetFunction.VLookup(item, tableArray, 3, False)
    priceColl.Add priceDrawer
    MsgBox priceDrawer & vbNewLine
Next item

'here I want to take all the prices in the second collection and add them together.
' Note, the  number of times in this collection will vary depending on how many
' comboboxes have shown up in the userform

End Sub
```

答:
Sum Up the Elements of a Collection

Dim Item As Variant
Dim Total As Double

For Each Item In priceColl
    If IsNumeric(Item) Then
        Total = Total + Item
    End If
Next Item
```
<ul>
<li><p>But maybe it is simpler just to use the <code>Total</code> variable in your <code>For Each...Next</code> loop right below the line <code>priceColl.Add priceDrawer</code>:</p>
```Total = Total + priceDrawer
```

if you are sure that it's a number.

Title: Sum Up the Elements of a Collection

Body:
Sum Up the Elements of a Collection

Dim Item As Variant
Dim Total As Double

For Each Item In priceColl
    If IsNumeric(Item) Then
        Total = Total + Item
    End If
Next Item

But maybe it is simpler just to use the Total variable in your For Each...Next loop right below the line priceColl.Add priceDrawer:

Total = Total + priceDrawer

if you are sure that it's a number.


问:
help in uniquely identifying combine columns
How can I uniquely identify two or more columns, that I have used table named address in the database, now address is has fields like street name, suite name and street num.

strnum   | strnam  |  sutname

1        | xyz     | 32

1        | xyz     | 32

now how can I uniquely these three columns. That is I want to check whether these three column are already inserted or not. If any field valus is changed than its ok, it will insert new one. but in case all three similar field..Help me to combinely identify these three fields.

答:
You do it by adding unique constraint.

```<code>ALTER TABLE your_table ADD UNIQUE(strnum, strnam, sutname);
</code>```

Then you do the following:

```<code>INSERT IGNORE INTO your_table (strnum, strnam, sutname) VALUES ('1', 'xyz', 'etc');
</code>```

If the value exists already - no insert will happen and no errors will be raised (that's what the IGNORE part is).

By the way why do you use such short and vague column names? It's not the DOS era any more, you can be descriptive with your column names.

Body:
You do it by adding unique constraint.

ALTER TABLE your_table ADD UNIQUE(strnum, strnam, sutname);

Then you do the following:

INSERT IGNORE INTO your_table (strnum, strnam, sutname) VALUES ('1', 'xyz', 'etc');

If the value exists already - no insert will happen and no errors will be raised (that's what the IGNORE part is).

By the way why do you use such short and vague column names? It's not the DOS era any more, you can be descriptive with your column names.


问:
How to install the Bumblebee 2021.1.1 Android Studio Patch?
When I open Android Studio I receive a notification saying that an update is available:

```<code>The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes
</code>```

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.

答:
The problem was fixed.
You can now update through the IDE without any webpage redirects or workarounds.
https://issuetracker.google.com/issues/217880228</p>

Body:
When I open Android Studio I receive a notification saying that an update is available:

The latest stable release of Android Studio is now available for download.

Android Studio Bumblebee | 2021.1.1 Patch 1 is a major new release and includes performance improvements, bug fixes and new features.

- Intellij 2021.1.1 Platform Update
- New Device Manager
- ADB over Wi-Fi
- Run Instrumented Tests in Android Studio using Gradle
- Android Gradle Plugin Upgrade Assistant now updates API usage
- Non-Transitive R classes on for new projects
- Apple Silicon Support Update
- Jank detection track in Profilers
- Profileable app profiling support in Studio Profilers
- Network Inspection and ability to capture Layout Inspector snapshots
- Support for Compose semantics in the Layout Inspector
- Interactive Preview
- Animated Vector Drawables Preview
- Updated Device picker for Design Tools

Important After updating, you need to restart Android Studio to apply any memory settings you migrate from an earlier version of the IDE.
Release Notes

However when I click on the Download button it opens a web page to re-download the whole program instead of updating it. It's a bit confusing because it's a minor update.


问:
Add date time of build/run to title text in Flutter app
My current code in lib/main.dart looks like this:

import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: LoginForm(),
    );
  }
}

class CustomFieldBlocValidators implements FieldBlocValidators {
  CustomFieldBlocValidators._();
  static String? number(dynamic value) {
    if (kDebugMode) {
      print(value);
      print(value is num);
    }
    if (value == null || value == false || num.tryParse(value) == null) {
      return "Number input is required";
    }
    return null;
  }
}

class LoginFormBloc extends FormBloc<String, String> {
  final num1 = TextFieldBloc(
    validators: [
      FieldBlocValidators.required,
      CustomFieldBlocValidators.number
    ],
  );

  final num2 = TextFieldBloc(
    validators: [
      FieldBlocValidators.required,
      CustomFieldBlocValidators.number
    ],
  );

  LoginFormBloc() {
    addFieldBlocs(
      fieldBlocs: [
        num1,
        num2,
      ],
    );
  }

  @override
  void onSubmitting() async {
    if (kDebugMode) {
      print(DateTime.now());
      print(num1.value);
      print(num2.value);
    }

    await Future<void>.delayed(const Duration(seconds: 1));

    if (Random().nextDouble() > 0.5) {
      emitSuccess();
    } else {
      emitFailure(failureResponse: 'This is an awesome error!');
    }
  }
}

class LoginForm extends StatelessWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => LoginFormBloc(),
      child: Builder(
        builder: (context) {
          final loginFormBloc = context.read<LoginFormBloc>();
          return Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(title: const Text('Basic Calculator - ')),
            body: FormBlocListener<LoginFormBloc, String, String>(
              onSubmitting: (context, state) {
                LoadingDialog.show(context);
              },
              onSuccess: (context, state) {
                LoadingDialog.hide(context);

                Navigator.of(context).pushReplacement(
                    MaterialPageRoute(builder: (_) => const SuccessScreen()));
              },
              onFailure: (context, state) {
                LoadingDialog.hide(context);

                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(state.failureResponse!)));
              },
              child: SingleChildScrollView(
                physics: const ClampingScrollPhysics(),
                child: AutofillGroup(
                  child: Column(
                    children: <Widget>[
                      TextFieldBlocBuilder(
                        textFieldBloc: loginFormBloc.num1,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: 'Number 1',
                          prefixIcon: Icon(Icons.dialpad),
                        ),
                      ),
                      TextFieldBlocBuilder(
                        textFieldBloc: loginFormBloc.num2,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: 'Number 2',
                          prefixIcon: Icon(Icons.dialpad),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          ElevatedButton(
                            onPressed: loginFormBloc.submit,
                            child: const Text('ADD'),
                          ),
                          ElevatedButton(
                            onPressed: loginFormBloc.submit,
                            child: const Text('SUBTRACT'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

class LoadingDialog extends StatelessWidget {
  static void show(BuildContext context, {Key? key}) => showDialog<void>(
        context: context,
        useRootNavigator: false,
        barrierDismissible: false,
        builder: (_) => LoadingDialog(key: key),
      ).then((_) => FocusScope.of(context).requestFocus(FocusNode()));

  static void hide(BuildContext context) => Navigator.pop(context);

  const LoadingDialog({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: Center(
        child: Card(
          child: Container(
            width: 80,
            height: 80,
            padding: const EdgeInsets.all(12.0),
            child: const CircularProgressIndicator(),
          ),
        ),
      ),
    );
  }
}

class SuccessScreen extends StatelessWidget {
  const SuccessScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Icon(Icons.tag_faces, size: 100),
            const SizedBox(height: 10),
            const Text(
              'Success',
              style: TextStyle(fontSize: 54, color: Colors.black),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 10),
            ElevatedButton.icon(
              onPressed: () => Navigator.of(context).pushReplacement(
                  MaterialPageRoute(builder: (_) => const LoginForm())),
              icon: const Icon(Icons.replay),
              label: const Text('AGAIN'),
            ),
          ],
        ),
      ),
    );
  }
}
```

In my class LoginForm where I set appBar: AppBar(title: const Text('Basic Calculator - ')), I want to show the date and time of build/run in front of the hypen. I am not able to achieve it any way.

I have tried:

const Text('Basic Calculator - '+DateTime.now())

assigned the DateTime.now() to a variable and used the variable

but to no avail.

答:
Remove const and add toString()

```<code>Text('Basic Calculator - '+ DateTime.now().toString())
</code>```

This works during run-time.

Body:
My current code in lib/main.dart looks like this:

import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_bloc/flutter_form_bloc.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: LoginForm(),
    );
  }
}

class CustomFieldBlocValidators implements FieldBlocValidators {
  CustomFieldBlocValidators._();
  static String? number(dynamic value) {
    if (kDebugMode) {
      print(value);
      print(value is num);
    }
    if (value == null || value == false || num.tryParse(value) == null) {
      return "Number input is required";
    }
    return null;
  }
}

class LoginFormBloc extends FormBloc<String, String> {
  final num1 = TextFieldBloc(
    validators: [
      FieldBlocValidators.required,
      CustomFieldBlocValidators.number
    ],
  );

  final num2 = TextFieldBloc(
    validators: [
      FieldBlocValidators.required,
      CustomFieldBlocValidators.number
    ],
  );

  LoginFormBloc() {
    addFieldBlocs(
      fieldBlocs: [
        num1,
        num2,
      ],
    );
  }

  @override
  void onSubmitting() async {
    if (kDebugMode) {
      print(DateTime.now());
      print(num1.value);
      print(num2.value);
    }

    await Future<void>.delayed(const Duration(seconds: 1));

    if (Random().nextDouble() > 0.5) {
      emitSuccess();
    } else {
      emitFailure(failureResponse: 'This is an awesome error!');
    }
  }
}

class LoginForm extends StatelessWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => LoginFormBloc(),
      child: Builder(
        builder: (context) {
          final loginFormBloc = context.read<LoginFormBloc>();
          return Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(title: const Text('Basic Calculator - ')),
            body: FormBlocListener<LoginFormBloc, String, String>(
              onSubmitting: (context, state) {
                LoadingDialog.show(context);
              },
              onSuccess: (context, state) {
                LoadingDialog.hide(context);

                Navigator.of(context).pushReplacement(
                    MaterialPageRoute(builder: (_) => const SuccessScreen()));
              },
              onFailure: (context, state) {
                LoadingDialog.hide(context);

                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text(state.failureResponse!)));
              },
              child: SingleChildScrollView(
                physics: const ClampingScrollPhysics(),
                child: AutofillGroup(
                  child: Column(
                    children: <Widget>[
                      TextFieldBlocBuilder(
                        textFieldBloc: loginFormBloc.num1,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: 'Number 1',
                          prefixIcon: Icon(Icons.dialpad),
                        ),
                      ),
                      TextFieldBlocBuilder(
                        textFieldBloc: loginFormBloc.num2,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: 'Number 2',
                          prefixIcon: Icon(Icons.dialpad),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          ElevatedButton(
                            onPressed: loginFormBloc.submit,
                            child: const Text('ADD'),
                          ),
                          ElevatedButton(
                            onPressed: loginFormBloc.submit,
                            child: const Text('SUBTRACT'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

class LoadingDialog extends StatelessWidget {
  static void show(BuildContext context, {Key? key}) => showDialog<void>(
        context: context,
        useRootNavigator: false,
        barrierDismissible: false,
        builder: (_) => LoadingDialog(key: key),
      ).then((_) => FocusScope.of(context).requestFocus(FocusNode()));

  static void hide(BuildContext context) => Navigator.pop(context);

  const LoadingDialog({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: Center(
        child: Card(
          child: Container(
            width: 80,
            height: 80,
            padding: const EdgeInsets.all(12.0),
            child: const CircularProgressIndicator(),
          ),
        ),
      ),
    );
  }
}

class SuccessScreen extends StatelessWidget {
  const SuccessScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Icon(Icons.tag_faces, size: 100),
            const SizedBox(height: 10),
            const Text(
              'Success',
              style: TextStyle(fontSize: 54, color: Colors.black),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 10),
            ElevatedButton.icon(
              onPressed: () => Navigator.of(context).pushReplacement(
                  MaterialPageRoute(builder: (_) => const LoginForm())),
              icon: const Icon(Icons.replay),
              label: const Text('AGAIN'),
            ),
          ],
        ),
      ),
    );
  }
}

In my class LoginForm where I set appBar: AppBar(title: const Text('Basic Calculator - ')), I want to show the date and time of build/run in front of the hypen. I am not able to achieve it any way.

I have tried:

const Text('Basic Calculator - '+DateTime.now())

assigned the DateTime.now() to a variable and used the variable

but to no avail.

Body:
Remove const and add toString()

Text('Basic Calculator - '+ DateTime.now().toString())

This works during run-time.


问:
How can distribute one table data to another table
I have two tables Orderapproval and stock:

Table 1:  Orderapproval

itemcode
approvalqty

1
25

2
10

Table 2: stock

itemcode
stockqty
batch
date

1
5
aa
2021-02-01

1
10
bb
2021-02-10

1
15
cc
2021-02-02

2
5
dd
2021-02-01

2
20
aa
2021-02-05

we have stock batch-wise.
when we get an order request for an item
we are trying to pick up items from the old batch first & so on
How can I get a result set like this:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

I am trying as......

Declare @StockTable table
(ItemCode int,BranchCode int,Qty int)
Insert Into @StockTable values
(1,       101,          5),
(1,       102,           10),
(1,       101,          15),
(2,       102,           5),
(2,       103,           20)

Declare @Orderapproval table (ItemCode int,Qty int)
Insert Into @Orderapproval values
(1,25),
(2,10)

;with T1 as (
Select A.*
,ToDist  = cast(D.Qty as int),
running_total = SUM(D.Qty) OVER (PARTITION BY  A.ItemCode,BranchCode  ORDER BY  BranchCode  DESC
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)

```<code>     From  @StockTable A

     Join  @Orderapproval D on A.ItemCode=D.ItemCode    )
</code>```

, T2 as (
Select *,   prev_running_total = LAG(Qty,1,0) OVER (PARTITION BY  ItemCode ORDER BY  BranchCode  DESC) From T1

)

select *,
CASE WHEN prev_running_total >= ToDist THEN 0

WHEN running_total > ToDist THEN ToDist - prev_running_total

ELSE qty
END 'qty'
from T2;

I didn't get the right output.
Please suggest  a better way

答:
SQL CODE---(Tested)</p>
```<code>Select stock.itemcode
       ,stock.stockqty AS qty
       ,stock.batch,stock.date
from stock
join orderapproval on stock.stockqty <= orderapproval.approvalgty
group by stock.batch;
</code>```

Body:
I have two tables Orderapproval and stock:

Table 1:  Orderapproval

itemcode
approvalqty

1
25

2
10

Table 2: stock

itemcode
stockqty
batch
date

1
5
aa
2021-02-01

1
10
bb
2021-02-10

1
15
cc
2021-02-02

2
5
dd
2021-02-01

2
20
aa
2021-02-05

we have stock batch-wise.
when we get an order request for an item
we are trying to pick up items from the old batch first & so on
How can I get a result set like this:

itemcode
qty
batch
date

1
5
aa
2021-02-01

1
15
cc
2021-02-02

1
5
bb
2021-02-10

2
5
dd
2021-02-01

I am trying as......

Declare @StockTable table
(ItemCode int,BranchCode int,Qty int)
Insert Into @StockTable values
(1,       101,          5),
(1,       102,           10),
(1,       101,          15),
(2,       102,           5),
(2,       103,           20)

Declare @Orderapproval table (ItemCode int,Qty int)
Insert Into @Orderapproval values
(1,25),
(2,10)

;with T1 as (
Select A.*
,ToDist  = cast(D.Qty as int),
running_total = SUM(D.Qty) OVER (PARTITION BY  A.ItemCode,BranchCode  ORDER BY  BranchCode  DESC
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)

     From  @StockTable A

     Join  @Orderapproval D on A.ItemCode=D.ItemCode    )

, T2 as (
Select *,   prev_running_total = LAG(Qty,1,0) OVER (PARTITION BY  ItemCode ORDER BY  BranchCode  DESC) From T1

)

select *,
CASE WHEN prev_running_total >= ToDist THEN 0

WHEN running_total > ToDist THEN ToDist - prev_running_total

ELSE qty
END 'qty'
from T2;

I didn't get the right output.
Please suggest  a better way

Body:
SQL CODE---(Tested)

Select stock.itemcode
       ,stock.stockqty AS qty
       ,stock.batch,stock.date
from stock
join orderapproval on stock.stockqty <= orderapproval.approvalgty
group by stock.batch;


问:
Is there any benefit of using html5shim library  over document.createElement('header')?
What is difference between using </p>

```<code><!--[if IE]>
<script>
  document.createElement('header');
  document.createElement('footer');
  document.createElement('section');
  document.createElement('nav');
</script>
<![endif]-->
</code>```

<p>instead </p>

```<code><!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</code>```

答: I believe that the HTML shim library also includes the IE print Protector</p>

Body:
What is difference between using

instead


问:
I can't get this MS Access SQL UPDATE statement to work
I am currently making a case tracker within MS Access and cannot get the below UPDATE code that is located in a subform to work. I've tried Googling this but to no avail.

All the data is stored in a main table called tblCaseTrackerLoad. This table has 98 columns in it. I also have a subform called tblBulkAssign subform which reads from 5 columns from within tblCaseTrackerLoad with the following query (which is placed in the Record Source fields of the Data tab):

```<code>SELECT tblCaseTrackerLoad.[Select], tblCaseTrackerLoad.[Case Status], tblCaseTrackerLoad.
[Customer Name], tblCaseTrackerLoad.Account_Key, tblCaseTrackerLoad.[Case_Owner] FROM
tblCaseTrackerLoad WHERE (((tblCaseTrackerLoad.[Case Status])="To be assigned"));
</code>```

Here are the field types:

tblCaseTrackerLoad.[Select] is a Yes/No field

tblCaseTrackerLoad.[Case Status] is a Short Text field

tblCaseTrackerLoad.[Customer Name] is a Short Text field

tblCaseTrackerLoad.Account_Key is a Large Number field

tblCaseTrackerLoad.[Case_Owner] is a Short Text field

The above code works perfectly and when the subform is loaded, I can see the rows of data that where the "Case Status = To Be Assigned". This is shown in a table format.

What I am trying to make happen in when the subform is loaded, the user ticks boxes in the Select field (as many or as few as they need to select), then they click a button which loads a different form containing all the users that the case could be assigned to. A user is selected and then the code executes and is supposed to assign the cases to the users by way of an update statement to update the table "tblCaseTrackerLoad".

Here is my code for the execution of the UPDATE statement:

```<code>strSQL = "UPDATE tblCaseTrackerLoad SET [Case_Owner] = " & "'" &
txtAssignToFromAssignToUserForm & "'" & ", [Case Status] = ""Assigned"", tblCaseTrackerLoad.
[Date Assigned] = " & Assigned Timestamp & ", WHERE [Select] = Yes AND [Case_Owner] IS NULL;"

Debug. Print strSQL

' Execute the SQL Command
DoCmd.RunSQL strSQL
</code>```

When ran, the error I get says "Run-Time error '3144': Syntax error in UPDATE statement."

Here is the output of Debug. Print

```<code>UPDATE tblCaseTrackerLoad SET [Case_Owner] = 'Craig Hogan', [Case Status] = "Assigned", tblCaseTrackerLoad.[Date Assigned] = 10/02/2022 07:36:13, WHERE [Select] = Yes AND [Case_Owner] IS NULL;
</code>```

For reference:

txtAssignToFromAssignToUserForm is the value that is passed from the form to select who to assign the cases to, back into this subform. This box is successfully receiving the users name.

AssignedTimeStamp is a bit of code just above the UPDATE query which says Dim AssignedTimeStamp As Date  AssignedTimeStamp = Now

Although the tblCaseTrackerLoad.[Date Assigned] field is not referenced within the subform, it is still a valid field in the main table tblCaseTrackerLoad and is of type "Date/Time".

It's bound to be some silly little thing that I haven't done but I have spent approx. 4 hours trying to sort this out now and cannot seem to find the solution.

Please can someone educate me on where I have gone wrong?

答:
You have a comma before the "WHERE" clause.  Remove that comma.</p>
```<code>UPDATE tblCaseTrackerLoad
SET [Case_Owner] = 'Craig Hogan', [Case Status] = "Assigned", tblCaseTrackerLoad.[Date Assigned] = 10/02/2022 07:36:13
WHERE [Select] = Yes AND [Case_Owner] IS NULL;
</code>```

Body:
I am currently making a case tracker within MS Access and cannot get the below UPDATE code that is located in a subform to work. I've tried Googling this but to no avail.

All the data is stored in a main table called tblCaseTrackerLoad. This table has 98 columns in it. I also have a subform called tblBulkAssign subform which reads from 5 columns from within tblCaseTrackerLoad with the following query (which is placed in the Record Source fields of the Data tab):

SELECT tblCaseTrackerLoad.[Select], tblCaseTrackerLoad.[Case Status], tblCaseTrackerLoad.
[Customer Name], tblCaseTrackerLoad.Account_Key, tblCaseTrackerLoad.[Case_Owner] FROM
tblCaseTrackerLoad WHERE (((tblCaseTrackerLoad.[Case Status])="To be assigned"));

Here are the field types:

tblCaseTrackerLoad.[Select] is a Yes/No field

tblCaseTrackerLoad.[Case Status] is a Short Text field

tblCaseTrackerLoad.[Customer Name] is a Short Text field

tblCaseTrackerLoad.Account_Key is a Large Number field

tblCaseTrackerLoad.[Case_Owner] is a Short Text field

The above code works perfectly and when the subform is loaded, I can see the rows of data that where the "Case Status = To Be Assigned". This is shown in a table format.

What I am trying to make happen in when the subform is loaded, the user ticks boxes in the Select field (as many or as few as they need to select), then they click a button which loads a different form containing all the users that the case could be assigned to. A user is selected and then the code executes and is supposed to assign the cases to the users by way of an update statement to update the table "tblCaseTrackerLoad".

Here is my code for the execution of the UPDATE statement:

strSQL = "UPDATE tblCaseTrackerLoad SET [Case_Owner] = " & "'" &
txtAssignToFromAssignToUserForm & "'" & ", [Case Status] = ""Assigned"", tblCaseTrackerLoad.
[Date Assigned] = " & Assigned Timestamp & ", WHERE [Select] = Yes AND [Case_Owner] IS NULL;"

Debug. Print strSQL

' Execute the SQL Command
DoCmd.RunSQL strSQL

When ran, the error I get says "Run-Time error '3144': Syntax error in UPDATE statement."

Here is the output of Debug. Print

UPDATE tblCaseTrackerLoad SET [Case_Owner] = 'Craig Hogan', [Case Status] = "Assigned", tblCaseTrackerLoad.[Date Assigned] = 10/02/2022 07:36:13, WHERE [Select] = Yes AND [Case_Owner] IS NULL;

For reference:

txtAssignToFromAssignToUserForm is the value that is passed from the form to select who to assign the cases to, back into this subform. This box is successfully receiving the users name.

AssignedTimeStamp is a bit of code just above the UPDATE query which says Dim AssignedTimeStamp As Date  AssignedTimeStamp = Now

Although the tblCaseTrackerLoad.[Date Assigned] field is not referenced within the subform, it is still a valid field in the main table tblCaseTrackerLoad and is of type "Date/Time".

It's bound to be some silly little thing that I haven't done but I have spent approx. 4 hours trying to sort this out now and cannot seem to find the solution.

Please can someone educate me on where I have gone wrong?

Body:
You have a comma before the "WHERE" clause.  Remove that comma.

UPDATE tblCaseTrackerLoad
SET [Case_Owner] = 'Craig Hogan', [Case Status] = "Assigned", tblCaseTrackerLoad.[Date Assigned] = 10/02/2022 07:36:13
WHERE [Select] = Yes AND [Case_Owner] IS NULL;


问:
Application Insights project literal value of severityLevel
Is there a way to project literal value of severityLevel in Application Insights query?

Consider following query:

```<code>union
customEvents,
dependencies,
exceptions,
performanceCounters,
traces
| order by timestamp desc
| project timestamp, operation_Name, itemType, severityLevel, message = strcat(name, message, outerMessage), customDimensions, ['details']
</code>```

In the output, severityLevel value is numeric, I want the equivalent descriptive value in according with SeverityLevel Enum definition

答:
I am able to get the severityLevel descriptive value.

Use the below query snippet

union
customEvents,
dependencies,
exceptions,
performanceCounters,
traces
| order by timestamp desc
| project timestamp, operation_Name, itemType, severityLevel, message = strcat(name, message, outerMessage), customDimensions, ['details']

| extend severityLevel = case(severityLevel == 0, "Verbose",
                       severityLevel == 1, "Information",
                       severityLevel == 2, "Warning",
                       severityLevel == 3, "Error",
                       severityLevel == 4, "Critical",
                       "-")
```

Body:
Is there a way to project literal value of severityLevel in Application Insights query?

Consider following query:

union
customEvents,
dependencies,
exceptions,
performanceCounters,
traces
| order by timestamp desc
| project timestamp, operation_Name, itemType, severityLevel, message = strcat(name, message, outerMessage), customDimensions, ['details']

In the output, severityLevel value is numeric, I want the equivalent descriptive value in according with SeverityLevel Enum definition


问:
Extract values from first few lines then skip for reading .txt file
Say I have two files, file1.txt and file2.txt that looks like this:

file1.txt

```<code>blablabla
lorem ipsum
year: 2007
Jan Feb Mar
1   2   3
4   5   6
</code>```

file2.txt

```<code>blablabla
lorem ipsum
year: 2008
Jan Feb Mar
7   8   9
10  11  12
</code>```

I can read these files with purrr::map_df(read_table,skip=3)
But what I want to do is extract the year from each file and assign it on a new year column so that my final dataframe looks like this:

```<code>Jan Feb Mar Year
1   2   3   2007
4   5   6   2007
7   8   9   2008
10  11  12  2008
</code>```

I am looking somewhere in the line of using readr::read_lines first then readr::read_table using rlang::exec but don't know how exactly to do this.

答:
Base R implements streaming connections with readLines:

f <- function(path) {
    ## Open connection and close on exit
    zzz <- file(path, open = "rt")
    on.exit(close(zzz))
    ## Read first three lines into character vector and extract year
    y <- as.integer(gsub("\\D", "", readLines(zzz, n = 3L)[3L]))
    ## Read remaining lines into data frame
    d <- read.table(zzz, header = TRUE)
    d$Year <- y
    d
}

nms <- c("file1.txt", "file2.txt")
do.call(rbind, lapply(nms, f))
```
<pre class="lang-none prettyprint-override"><code>  Jan Feb Mar Year
1   1   2   3 2007
2   4   5   6 2007
3   7   8   9 2008
4  10  11  12 2008
</code>```

It's not clear to me that readr has this functionality:

library("readr")
zzz <- file("file1.txt", open = "rb")

read_lines(zzz, skip = 2L, n_max = 1L)
## [1] "year: 2007"

read_table(zzz)
## # A tibble: 0 × 0

close(zzz)
```

Even though we only asked read_lines for the third line of file1.txt, it seems to have (invisibly) read all of the lines, leaving nothing for read_table.

On the other hand, this GitHub issue was "fixed" last year, so it is strange not to see support for streaming connections in the latest release version of readr. Maybe I'm missing something...?

Body:
Say I have two files, file1.txt and file2.txt that looks like this:

file1.txt

blablabla
lorem ipsum
year: 2007
Jan Feb Mar
1   2   3
4   5   6

file2.txt

blablabla
lorem ipsum
year: 2008
Jan Feb Mar
7   8   9
10  11  12

I can read these files with purrr::map_df(read_table,skip=3)
But what I want to do is extract the year from each file and assign it on a new year column so that my final dataframe looks like this:

Jan Feb Mar Year
1   2   3   2007
4   5   6   2007
7   8   9   2008
10  11  12  2008

I am looking somewhere in the line of using readr::read_lines first then readr::read_table using rlang::exec but don't know how exactly to do this.

Body:
Base R implements streaming connections with readLines:

f <- function(path) {
    ## Open connection and close on exit
    zzz <- file(path, open = "rt")
    on.exit(close(zzz))
    ## Read first three lines into character vector and extract year
    y <- as.integer(gsub("\\D", "", readLines(zzz, n = 3L)[3L]))
    ## Read remaining lines into data frame
    d <- read.table(zzz, header = TRUE)
    d$Year <- y
    d
}

nms <- c("file1.txt", "file2.txt")
do.call(rbind, lapply(nms, f))

  Jan Feb Mar Year
1   1   2   3 2007
2   4   5   6 2007
3   7   8   9 2008
4  10  11  12 2008

It's not clear to me that readr has this functionality:

library("readr")
zzz <- file("file1.txt", open = "rb")

read_lines(zzz, skip = 2L, n_max = 1L)
## [1] "year: 2007"

read_table(zzz)
## # A tibble: 0 × 0

close(zzz)

Even though we only asked read_lines for the third line of file1.txt, it seems to have (invisibly) read all of the lines, leaving nothing for read_table.

On the other hand, this GitHub issue was "fixed" last year, so it is strange not to see support for streaming connections in the latest release version of readr. Maybe I'm missing something...?


问:
How to change package name in flutter?
Is there any way to change Package Name of Flutter project?

I want to change package name and application name in flutter project.

答:
First, run this in your terminal

dart pub global activate rename

Run this in your Flutter Project Root Directory

dart pub global run rename --bundleId com.company.appname --target android

This will update the gradle build file with right id in defaultConfig

```<code> defaultConfig {
        applicationId "com.company.appname"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode flutterVersionCode.toInteger()
 }
</code>```

And that's everything, now you changed your package name :)

Title: How to change package name in flutter?

Body:
First, run this in your terminal

dart pub global activate rename

Run this in your Flutter Project Root Directory

dart pub global run rename --bundleId com.company.appname --target android

This will update the gradle build file with right id in defaultConfig

 defaultConfig {
        applicationId "com.company.appname"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode flutterVersionCode.toInteger()
 }

And that's everything, now you changed your package name :)


问:
How to describe object properties parameters for a function in typescript TSDoc?
How do I add descriptions for a and b in TSDoc? I want the description be shown when I hover on a property argument in a function call like fn({ a }).

```<code>// This does not work

/**
 * @param props
 * @param props.a docs for a
 * @param props.b docs for b
 */
function fn({a, b}: {a: string, b: string}) {}

fn({ a })
//   ~
// Expecting hover info for `a`.
</code>```

答:
This does works</p>
```<code>interface Params {
  /** Desc for a */
  a?:string;
  b?:string;
}

/**
 * Desc for fn
 */
function fn({a, b}: Params) {}
</code>```

Body:
How do I add descriptions for a and b in TSDoc? I want the description be shown when I hover on a property argument in a function call like fn({ a }).

// This does not work

/**
 * @param props
 * @param props.a docs for a
 * @param props.b docs for b
 */
function fn({a, b}: {a: string, b: string}) {}

fn({ a })
//   ~
// Expecting hover info for `a`.

Body:
This does works

interface Params {
  /** Desc for a */
  a?:string;
  b?:string;
}

/**
 * Desc for fn
 */
function fn({a, b}: Params) {}


问:
Accessing a float value in AsyncTask
Here is a pseudo code :

```
class MoWeFi extends Activity</p>

```    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);
```

<p>class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);</p>

```    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);
```

<p>class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }</p>

<p>class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!</p>

<p>class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));</p>

<code>MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!
</code>```

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing

答:
Are you sure your AsyncTask accesses the property after the value was changed? If yes, AsyncTask runs code on a separate thread so probably you're facing a race condition where the value updated in one thread is not yet available in another. Try to make the zoom property volatile:

```<code> public static volatile float zoom = 1.f;
</code>```

or use synchronized get/set methods to mutate and access the property.

Title: Accessing a float value in AsyncTask

Body:
Here is a pseudo code :

class MoWeFi extends Activity

    static TouchSurfaceView TSV;
    static DrawRenderer mRenderer;
    static UserInterface mUI;
    DownloadData mDD = new DownloadData();
    static float zoom = 1.f;

    mDD.execute();
    mUI = new UserInterface();
    setContentView(mUI);

class UserInterface extends LinearLayout
    MoWeFi.TSV = new TouchSurfaceView(context);
    MoWeFi.mRenderer = new DrawRenderer(context);
    MoWeFi.TSV.setRenderer(MoWeFi.mRenderer);
    MoWeFi.TSV.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    this.addView(MoWeFi.TSV);

    TextView tv = new TextView(context);
    this.addView(tv);

    TextView tv2 = new TextView(context);
    this.addView(tv2);

class DownloadData extends AsyncTask
    protected Void doInBackground(){
        do{
        this.publishProgress();
        try{Thread.sleep(1000);catch (InterruptedException e){}
        }while(running)
    }
    @Override
    protected void onProgressUpdate(){
    //...
    MoWeFi.TSV.requestRender();
    MoWeFi.mUI.tv.setText("zoom="+MoWeFi.zoom); // IT DOES NOT WORK !!! ALWAYS GET 1.f.
    }

class TouchSurfaceView extends GLSurfaceView
    gl.glTranslatef(0, 0, -1.f / MoWeFi.zoom); // IT WORKS !!!

class DrawRenderer implements GLSurfaceView.Renderer
    //Pinch-zoom
    ...
    MoWeFi.zoom *= detector.getScaleFactor();
        MoWeFi.zoom = Math.max(0.5f, Math.min(MoWeFi.zoom, 5.0f));

MoWeFi.mUI.tv2.setText("zoom="+MoWeFi.zoom); // IT WORKS !!!

So no error whatsoever. Just not able to access my zoom variable everywhere.
I am new to Java, I am surely missing important concept.

EDIT add float in the first lines

EDIT 2 add publishProgress in the asyncTask

EDIT 3 logcat shows nothing

Body:
Are you sure your AsyncTask accesses the property after the value was changed? If yes, AsyncTask runs code on a separate thread so probably you're facing a race condition where the value updated in one thread is not yet available in another. Try to make the zoom property volatile:

 public static volatile float zoom = 1.f;

or use synchronized get/set methods to mutate and access the property.