问:
Trying to merge a picture into an OpenTBS template fails with "failed to found the picture" (sic)
Im using OpenTBS to merge data from PHP into a word template.

All the normal variables merge fine, however I fail to succeed at merging an image file.

The placeholder for my image in my Word file looks like this:

```<code>[onshow.logo;ope=changepic]
</code>```

When running the PHP script, I always get

TinyButStrong Error OpenTBS Plugin: Parameter ope=changepic used in the field [onshow.logo] has failed to found the picture. The process is ending, unless you set NoErr property to true.

I tried setting my php variable to the URL of the picture or to the absolute path of the picture on the server, both fail:

https://path.to.my.picture/picture.jpg

/var/drupal/platform/html/sites/default/files/2022-02/picture.jpg"

Is there anything obvious I am missing here?

答:
By default OpenTBS expects the TBS field to be placed after the picture.
You can tune this relative placement using parameter tagpos, so it can after, before or inside (in an image property).

More details ate the documentation.

Body:
Im using OpenTBS to merge data from PHP into a word template.

All the normal variables merge fine, however I fail to succeed at merging an image file.

The placeholder for my image in my Word file looks like this:

[onshow.logo;ope=changepic]

When running the PHP script, I always get

TinyButStrong Error OpenTBS Plugin: Parameter ope=changepic used in the field [onshow.logo] has failed to found the picture. The process is ending, unless you set NoErr property to true.

I tried setting my php variable to the URL of the picture or to the absolute path of the picture on the server, both fail:

https://path.to.my.picture/picture.jpg

/var/drupal/platform/html/sites/default/files/2022-02/picture.jpg"

Is there anything obvious I am missing here?


来源: stackexchange

问:
propbem the mysqlconnection when using public variable in class level
I have c# class that make me to connect the database and make some operations on it.

```<code>#region Var
        private readonly string DbPath;
        public MySqlConnection DbConn;

        #endregion

        #region Constructor

        public ClsDb()
        {
            DbPath = "SERVER= " + Db.Default.ServerName + "; " +
                    "DATABASE= " + Db.Default.DbName + "; " +
                    "UID= " + Db.Default.UserName + "; " +
                    "PWD= " + Db.Default.UserPass + "; " +
                    "PORT= " + Db.Default.ThePort+"; sslmode=none";
            DbConn = new MySqlConnection(DbPath);
        }
        #endregion
</code>```

as you see I declared (mysqlconnection) :

```<code>DbConn = new MySqlConnection(DbPath);
</code>```

so after that I check the connection:

```<code>public bool CheckConn()
{
    try
    {
        if (DbConn.State == ConnectionState.Open)
        {
            DbConn.Close();
        }

        if (DbConn.State == ConnectionState.Closed)
        {
            DbConn.Open();
            return true;
        }
        return false;
    }
    catch
    {
        MessageBox.Show(Msgs.Default.ConnErr,
                          Settings.Default.ComName,
                          MessageBoxButtons.OK,
                          MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
        return false;
    }

}
</code>```

and after that I'm trying to execute SQL statement by method:

```<code>public void RunSql(string xSql, MySqlParameter[] xPar)
        {
            //...
            MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);

            // ....
            if (xPar != null)
            {
                xCmd.Parameters.AddRange(xPar);
            }

            //...
            xCmd.ExecuteNonQuery();
        }
</code>```

but it gives me the following error:

"Connection must be valid and open."

when I checked the code by the breakpoints I got that everything is ok and it opens the connection very well but when it execute (public void RunSql) and exactly on the line:

```<code>MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);
</code>```

when I tried to solve it I changed (public MySqlConnection DbConn) to (public Static MySqlConnection DbConn) and it worked but I needed to know why that happened although I declared the variable as public?? and why it worked when I changed to Static??

答:
I'm using my own class for this. In it isn't necessary to close the connection because uses the 'using'.

The class:

Connection (return open connection)

```<code>public static MySqlConnection GetConn()
    {
        MySqlConnection conn = new MySqlConnection(ConnString);

        try
        {
            conn.Open();
        }
        catch (MySqlException)
        {
            throw;
        }

        return conn;
    }
</code>```

Insert Commands (accept params)

```<code>public static int InsertSqlCommand(string db, params (string param, object value)[] listParams)
    {
        using (MySqlConnection conn = GetConn())
        {
            using (MySqlCommand cmd = new MySqlCommand(db, conn))
            {

                foreach ((string dbLocal, object incremento) in listParams)
                    cmd.Parameters.AddWithValue(dbLocal, incremento);

                int linhasAfetadas = cmd.ExecuteNonQuery();

                return linhasAfetadas;
            }
        }
    }
</code>```

Select Command (accept params)

```<code> public static DataTable SelectSqlCommand(string db, params (string param, object value)[] listParams)
    {
        DataTable dttoken = new DataTable();

        using (MySqlConnection conn = GetConn())
        {
            using (MySqlCommand cmd = new MySqlCommand(db, conn))
            {

                foreach ((string dbLocal, object incremento) in listParams)
                     cmd.Parameters.AddWithValue(dbLocal, incremento);

                using (MySqlDataAdapter sqlDA = new MySqlDataAdapter(cmd))
                {
                    sqlDA.Fill(dttoken);
                    return dttoken;
                }
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have c# class that make me to connect the database and make some operations on it.

#region Var
        private readonly string DbPath;
        public MySqlConnection DbConn;

        #endregion

        #region Constructor

        public ClsDb()
        {
            DbPath = "SERVER= " + Db.Default.ServerName + "; " +
                    "DATABASE= " + Db.Default.DbName + "; " +
                    "UID= " + Db.Default.UserName + "; " +
                    "PWD= " + Db.Default.UserPass + "; " +
                    "PORT= " + Db.Default.ThePort+"; sslmode=none";
            DbConn = new MySqlConnection(DbPath);
        }
        #endregion

as you see I declared (mysqlconnection) :

DbConn = new MySqlConnection(DbPath);

so after that I check the connection:

public bool CheckConn()
{
    try
    {
        if (DbConn.State == ConnectionState.Open)
        {
            DbConn.Close();
        }

        if (DbConn.State == ConnectionState.Closed)
        {
            DbConn.Open();
            return true;
        }
        return false;
    }
    catch
    {
        MessageBox.Show(Msgs.Default.ConnErr,
                          Settings.Default.ComName,
                          MessageBoxButtons.OK,
                          MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
        return false;
    }

}

and after that I'm trying to execute SQL statement by method:

public void RunSql(string xSql, MySqlParameter[] xPar)
        {
            //...
            MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);

            // ....
            if (xPar != null)
            {
                xCmd.Parameters.AddRange(xPar);
            }

            //...
            xCmd.ExecuteNonQuery();
        }

but it gives me the following error:

"Connection must be valid and open."

when I checked the code by the breakpoints I got that everything is ok and it opens the connection very well but when it execute (public void RunSql) and exactly on the line:

MySqlCommand xCmd = new MySqlCommand(xSql, DbConn);

when I tried to solve it I changed (public MySqlConnection DbConn) to (public Static MySqlConnection DbConn) and it worked but I needed to know why that happened although I declared the variable as public?? and why it worked when I changed to Static??

Body:
I'm using my own class for this. In it isn't necessary to close the connection because uses the 'using'.

The class:

Connection (return open connection)

public static MySqlConnection GetConn()
    {
        MySqlConnection conn = new MySqlConnection(ConnString);

        try
        {
            conn.Open();
        }
        catch (MySqlException)
        {
            throw;
        }

        return conn;
    }

Insert Commands (accept params)

public static int InsertSqlCommand(string db, params (string param, object value)[] listParams)
    {
        using (MySqlConnection conn = GetConn())
        {
            using (MySqlCommand cmd = new MySqlCommand(db, conn))
            {

                foreach ((string dbLocal, object incremento) in listParams)
                    cmd.Parameters.AddWithValue(dbLocal, incremento);

                int linhasAfetadas = cmd.ExecuteNonQuery();

                return linhasAfetadas;
            }
        }
    }

Select Command (accept params)

 public static DataTable SelectSqlCommand(string db, params (string param, object value)[] listParams)
    {
        DataTable dttoken = new DataTable();

        using (MySqlConnection conn = GetConn())
        {
            using (MySqlCommand cmd = new MySqlCommand(db, conn))
            {

                foreach ((string dbLocal, object incremento) in listParams)
                     cmd.Parameters.AddWithValue(dbLocal, incremento);

                using (MySqlDataAdapter sqlDA = new MySqlDataAdapter(cmd))
                {
                    sqlDA.Fill(dttoken);
                    return dttoken;
                }
            }
        }
    }


问:
How to add same dataset in Quicksight to join with multiple datasets while creating joined dataset?
I have few datasets which are created in aws quicksight from s3 containing json data. I have a requirement to join for ex alpha dataset with beta and gamma without duplicating the fields. Is there any way I can achieve this?

If not is there an alternative to achieve this maybe using Athena?

Thanks!!

答:
This is the way database joins work: If multiple rows satisfy the join condition due to there being a one-to-many or many-to-many relationship between the table, then rows are duplicated. See Why do multiple-table joins produce duplicate rows?

In the context of QuickSight see https://community.amazonquicksight.com/t/duplicated-data-in-qs-left-join/1393 for a possible workaround for this.


问:
How to pull snapshot key & values into list through Map<>?
I've been following the official Firebase tutorial for using a real-time database: https://www.youtube.com/watch?v=sXBJZD0fBa4

I am able to pull all the data from the firebase real-time database. However, the method below to do so, provides a list of the data, with no reference to the parent keys (snapshot.key). An ideal scenario would be to have a key property within the Item class (item.key), so I can call upon it directly from the list.

```<code>class DatabaseModel {

  final itemsRef = FirebaseDatabase.instance.ref().child('/Contents');

  Stream<List<Items>> getItemssStream() {

    final itemsStream = itemsRef.onValue;

    final streamToPublish = itemsStream.map((event) {

      final itemsMap = Map<String, dynamic>.from(event.snapshot.value as Map<String, dynamic>);

      final itemsList = itemsMap.entries.map((element) {
        return Items.fromRTDB(Map<String, dynamic>.from(element.value));
      }).toList();

      return itemsList;

    });

    return streamToPublish;
  }

}
</code>```
```<code>class Items{
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(Map<String, dynamic> data) {
    return Items(
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }

}
</code>```

答:
In this code you only use the element.value of each node in your results:

```<code>return Items.fromRTDB(Map<String, dynamic>.from(element.value));
</code>```

If you also want to get the key of each item, you will have to also use element.key in there and pass that to your Items object.

Something like this:

```<code>Items.fromRTDB(element.key, Map<String, dynamic>.from(element.value));

...

class Items{
  final String key;
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.key, required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(String key, Map<String, dynamic> data) {
    return Items(
      key: key,
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }
}
</code>```

Body:
I've been following the official Firebase tutorial for using a real-time database: https://www.youtube.com/watch?v=sXBJZD0fBa4

I am able to pull all the data from the firebase real-time database. However, the method below to do so, provides a list of the data, with no reference to the parent keys (snapshot.key). An ideal scenario would be to have a key property within the Item class (item.key), so I can call upon it directly from the list.

class DatabaseModel {

  final itemsRef = FirebaseDatabase.instance.ref().child('/Contents');

  Stream<List<Items>> getItemssStream() {

    final itemsStream = itemsRef.onValue;

    final streamToPublish = itemsStream.map((event) {

      final itemsMap = Map<String, dynamic>.from(event.snapshot.value as Map<String, dynamic>);

      final itemsList = itemsMap.entries.map((element) {
        return Items.fromRTDB(Map<String, dynamic>.from(element.value));
      }).toList();

      return itemsList;

    });

    return streamToPublish;
  }

}

class Items{
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(Map<String, dynamic> data) {
    return Items(
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }

}

Body:
In this code you only use the element.value of each node in your results:

return Items.fromRTDB(Map<String, dynamic>.from(element.value));

If you also want to get the key of each item, you will have to also use element.key in there and pass that to your Items object.

Something like this:

Items.fromRTDB(element.key, Map<String, dynamic>.from(element.value));

...

class Items{
  final String key;
  final String item;
  final String expiryDate;
  final String quantity;
  final String user;

  Items({required this.key, required this.item, required this.expiryDate, required this.quantity, required this.user});

  //Mapping from real-time database
  factory Items.fromRTDB(String key, Map<String, dynamic> data) {
    return Items(
      key: key,
      item: data['item'],
      expiryDate: data['exp'],
      quantity: data['qty'],
      user: data['user'],
    );
  }
}


问:
Could managed code (specifically .NET) ever become 'unmanaged'?
Recently I was talking with a friend of mine who had started a C++ class a couple months ago (his first exposure to programming). We got onto the topic of C# and .NET generally, and he made the point to me that he felt it was 'doomed' for all of the commonly-cited issues (low speed, breakable bytecode, etc). I agreed with him on all those issues, but I held back in saying it was doomed, only because I felt that, in time, languages like C# could instead become native code (if Microsoft so chose to change the implementation of .NET from a bytecode, JIT runtime environemnent to one which compiles directly to native code like your C++ program does).

My question is, am I out to lunch here? I mean, it may take a lot of work (and may break too many things), but there isn't some type of magical barrier which prevents C# code from being compiled natively (if one wanted to do it), right? There was a time where C++ was considered a very high-level language (which it still is, but not as much as in the past) yet now it's the bedrock (along with C) for Microsoft's native APIs. The idea that .NET could one day be on the same level as C++ in that respect seems only to be a matter of time and effort to me, not some fundamental flaw in the design of the language.

EDIT: I should add that if native compilation of .NET is possible, why does Microsoft choose not to go that route? Why have they chosen the JIT bytecode path?

答:
Java uses bytecode.  C#, while it uses IL as an intermediate step, has always compiled to native code.  IL is never directly interpreted for execution as Java bytecode is.  You can even pre-compile the IL before distribution, if you really want to (hint: performance is normally better in the long run if you don't).

The idea that C# is slow is laughable.  Some of the winforms components are slow, but if you know what you're doing C# itself is a very speedy language.  In this day and age it generally comes down to the algorithm anyway;  language choice won't help you if you implement a bad bubble sort.  If C# helps you use more efficient algorithms from a higher level (and in my experience it generally does) that will trump any of the other speed concerns.

Based on your edit, I also want to explain the (typical) compilation path again.

C# is compiled to IL.  This IL is distributed to local machines.   A user runs the program, and that program is then JIT-compiled to native code for that machine once.  The next time the user runs the program on that machine they're running a fully-native app.  There is also a JIT optimizer that can muddy things a bit, but that's the general picture.

The reason you do it this way is to allow individual machines to make compile-time optimizations appropriate to that machine.  You end up with faster code on average than if you distributed the same fully-compiled app to everyone.

Regarding decompilation:

The first thing to note is that you can pre-compile to native code before distribution if you really want to.  At this point you're close to the same level as if you had distributed a native app.  However, that won't stop a determined individual.

It also largely misunderstands the economics at play.  Yes, someone might perhaps reverse-engineer your work.  But this assumes that all the value of the app is in the technology.  It's very common for a programmer to over-value the code, and undervalue the execution of the product: interface design, marketing, connecting with users, and on-going innovation.  If you do all of that right, a little extra competition will help you as much as it hurts by building up demand in your market.  If you do it wrong, hiding your algorithm won't save you.

If you're more worried about your app showing up on warez sites, you're even more misguided.  It'll show up there anyway.  A much better strategy is to engage those users.

At the moment, the biggest impediment to adoption (imo) is that the framework redistributable has become mammoth in size.  Hopefully they'll address that in a relatively near release.

OwnerDisplayName: GRB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Joel Coehoorn


问:
Static UILabel not showing in uiview
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

```<code>#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end
</code>```

答:
Make sure you have saved your project.
Also check whether you have done addSubView ion your code.
Clean and then run...
This will solve your issue

hope it helps....

ContentLicense: CC BY-SA 3.0

Title: Static UILabel not showing in uiview

Body:
I have create a few static UILabel text in Interface Builder, but when running the application. the label is not shown in the application itself, i do not know why.

all other stuff like textfield, buttons except the label is not working
can anybody advise me what had gone wrong ?

This is in IB

this is in App

#import "SettingsViewController.h"

@implementation SettingsViewController

@synthesize drinkLimitText;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    appDelegate = (DrinkTabsAndNavAppDelegate *)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];

    NSLog(@"subView:%d",[self.view.subviews count]);
}

- (void) viewWillAppear:(BOOL)animated {

    if ([appDelegate.drinkLimit floatValue] >= 0)
        drinkLimitText.text = [NSString stringWithFormat:@"%.0f", [appDelegate.drinkLimit floatValue]];
    else
        drinkLimitText.text = @"0";

    [super viewWillAppear:animated];
}

- (IBAction)textFieldDoneEditing:(id)sender{
    NSDecimalNumber *tempValue = [[NSDecimalNumber alloc] initWithString:drinkLimitText.text];
    if (tempValue == [NSDecimalNumber notANumber] || [tempValue doubleValue] < 0) {
        NSString *msg = [[NSString alloc] initWithFormat: @"Make sure to enter a positive number."];
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Hang on..."
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"Ok"
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        [msg release];
    } else {
        [sender resignFirstResponder];
        [self updateDrinkLimit];
    }
    [tempValue release];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)updateDrinkLimit {

    NSDecimalNumber *newLimit = [[NSDecimalNumber alloc] initWithString:[drinkLimitText text]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([newLimit floatValue] >= 0) {
        [defaults setFloat:[newLimit floatValue] forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = newLimit;
    } else {
        [defaults setFloat:0 forKey:kDrinkLimitKey];
        appDelegate.drinkLimit = 0;
    }
    [newLimit release];
}

- (IBAction)openOntrackWebsite {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.ontrack.org.au/"]];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [drinkLimitText release];

    [super dealloc];
}

@end


问:
JavaScript Class with same name for property and method
When researching a problem I ran into when trying to remove an event listener that uses bind() similar to the syntax in use by the class constructor below (I am not trying to remove this one, but it would not be successful if I tried), I found two sources that show a solution to that similar to that in use by the onDown method below (I do want this one removed once no longer needed) that creates a separte function that does the binding and the addEventListener attaches the function by its name:

class TestClass {
    constructor(el) {
        el.addEventListener('mousedown', function () { this.onDown(el.id) }.bind(this));
    }

    onDown(id) {
        // Here a property named onUp is created:
        this.onUp = this.onUp.bind(this, id);
        document.addEventListener('mouseup', this.onUp);
    }
    // Here a method named onUp is defined in the class:
    onUp(id) {
        document.removeEventListener('mouseup', this.onUp);
        console.log("Mouse down on " + id + " and then mouse up.");
    }
}

const d1 = new TestClass(document.getElementById("div1"));
const d2 = new TestClass(document.getElementById("div2"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1">Div 1: Click me and let go!</div>
<div id="div2">Div 2: Click me and let go!</div></code>```

This code works and achieves my desired results, but what I observed is this creates a both property and a method with the same name, named onUp, in the objects created.  This can also be verified by looking at the properties of the objects created (see image below).  This is not otherwise possible as confirmed by the error received when calling the method that uses the same name as a property here:

class Test {
    sameName = "property";
    sameName() { return "method"; }
}

const testObject = new Test();
console.log(testObject.sameName); // Here Console outputs the value of the sameName property
console.log(testObject.sameName()); // This fails calling the sameName() method```
</div>
</div>
</p>
<p>Can someone help explain to me how this is working in the first example where an object has a property and method both with the same name?  Is this a problem?</p>
<p>Note, I have alternate ways of doing this too. I can otherwise simply give one of them a different name:</p>
```onDown(el) {
    this._onUp = this.onUp.bind(this, el);
    document.addEventListener('mouseup', this._onUp);
}

onUp(el) {
    document.removeEventListener('mouseup', this._onUp);
    console.log("Mouse down on " + el.id + " and then mouse up.");
}
```
<p>Or, the <code>{ once: true }</code> option works for the example, but not in the actual code I am writing that uses different events (this is just a simplified example):</p>
```onDown(el) {
    document.addEventListener('mouseup', function () { this.onUp(el) }.bind(this), { once: true });
}

onUp(el) {
    console.log("Mouse down on " + el.id + " and then mouse up.");
}
```

Adding an image that shows the output properties of one of the TestClass objects.  It first lists the property values.  Since my example only had 1 property, I added another (named anotherProperty) to show the collection of properties, for control purposes.  And under Prototype, it lists all the methods in the object.  Both sections have an entry named onUp.

And here is another image if the output of the other Test object I built expecting to fail.  In here you can see it is built with the same design; it has a property named sameName (which can be referenced) and it has a method under Prototype also names sameName (which fails when calling).

This failure is as expected.  But again, in my first example, there is both a property and a method, both with the same name, onUp, and the method does function.

答:
A method is just a property with a function for its value.

A property is a named “thing” attached to an object.

When you create an instance of a class in JavaScript (i.e. call a function with the new keyword) it creates an object with a prototype which is a reference to the class.

When you try to access a property on an object, it first checks the object itself to see if it has such a property. If it can’t find it, it looks at the prototype and checks that object for a property with that name. Then it checks the prototype of that object and so on until it runs out of objects on the prototype chain.

This is how inheritance works in JavaScript.

———

So when you call new TestClass you create an object which has a prototype which has an onUp method.

When the mousedown event fires, you say:

```<code>this.onUp = this.onUp.bind(this, id);
</code>```

Which:

Looks for onUp on the object and doesn’t find it

Looks up the prototype chain

Finds it on the call

Calls bind on it to create a new function

Copies that function to the onUp property of the object itself (creating it)

Now you have an onUp property on the object itself and on the object up the prototype chain.

This generally isn’t a problem but in your specific case, it creates an inefficiency.

The second time you trigger the mousedown event it finds onUp on the object itself, but still calls bind on it to create a new function (which calls the previous function which calls the previous function).

Every time there is another mousedown event you get an additional layer of binding.

You could avoid this by testing with the hasOwnProperty method (which will tell you if the value exists on the object itself and not up the prototype chain).

Body:
When researching a problem I ran into when trying to remove an event listener that uses bind() similar to the syntax in use by the class constructor below (I am not trying to remove this one, but it would not be successful if I tried), I found two sources that show a solution to that similar to that in use by the onDown method below (I do want this one removed once no longer needed) that creates a separte function that does the binding and the addEventListener attaches the function by its name:

class TestClass {
    constructor(el) {
        el.addEventListener('mousedown', function () { this.onDown(el.id) }.bind(this));
    }

    onDown(id) {
        // Here a property named onUp is created:
        this.onUp = this.onUp.bind(this, id);
        document.addEventListener('mouseup', this.onUp);
    }
    // Here a method named onUp is defined in the class:
    onUp(id) {
        document.removeEventListener('mouseup', this.onUp);
        console.log("Mouse down on " + id + " and then mouse up.");
    }
}

const d1 = new TestClass(document.getElementById("div1"));
const d2 = new TestClass(document.getElementById("div2"));

Div 1: Click me and let go!

Div 2: Click me and let go!

This code works and achieves my desired results, but what I observed is this creates a both property and a method with the same name, named onUp, in the objects created.  This can also be verified by looking at the properties of the objects created (see image below).  This is not otherwise possible as confirmed by the error received when calling the method that uses the same name as a property here:

class Test {
    sameName = "property";
    sameName() { return "method"; }
}

const testObject = new Test();
console.log(testObject.sameName); // Here Console outputs the value of the sameName property
console.log(testObject.sameName()); // This fails calling the sameName() method

Can someone help explain to me how this is working in the first example where an object has a property and method both with the same name?  Is this a problem?

Note, I have alternate ways of doing this too. I can otherwise simply give one of them a different name:

onDown(el) {
    this._onUp = this.onUp.bind(this, el);
    document.addEventListener('mouseup', this._onUp);
}

onUp(el) {
    document.removeEventListener('mouseup', this._onUp);
    console.log("Mouse down on " + el.id + " and then mouse up.");
}

Or, the { once: true } option works for the example, but not in the actual code I am writing that uses different events (this is just a simplified example):

onDown(el) {
    document.addEventListener('mouseup', function () { this.onUp(el) }.bind(this), { once: true });
}

onUp(el) {
    console.log("Mouse down on " + el.id + " and then mouse up.");
}

Adding an image that shows the output properties of one of the TestClass objects.  It first lists the property values.  Since my example only had 1 property, I added another (named anotherProperty) to show the collection of properties, for control purposes.  And under Prototype, it lists all the methods in the object.  Both sections have an entry named onUp.

And here is another image if the output of the other Test object I built expecting to fail.  In here you can see it is built with the same design; it has a property named sameName (which can be referenced) and it has a method under Prototype also names sameName (which fails when calling).

This failure is as expected.  But again, in my first example, there is both a property and a method, both with the same name, onUp, and the method does function.

Body:
A method is just a property with a function for its value.

A property is a named “thing” attached to an object.

When you create an instance of a class in JavaScript (i.e. call a function with the new keyword) it creates an object with a prototype which is a reference to the class.

When you try to access a property on an object, it first checks the object itself to see if it has such a property. If it can’t find it, it looks at the prototype and checks that object for a property with that name. Then it checks the prototype of that object and so on until it runs out of objects on the prototype chain.

This is how inheritance works in JavaScript.

———

So when you call new TestClass you create an object which has a prototype which has an onUp method.

When the mousedown event fires, you say:

this.onUp = this.onUp.bind(this, id);

Which:

Looks for onUp on the object and doesn’t find it

Looks up the prototype chain

Finds it on the call

Calls bind on it to create a new function

Copies that function to the onUp property of the object itself (creating it)

Now you have an onUp property on the object itself and on the object up the prototype chain.

This generally isn’t a problem but in your specific case, it creates an inefficiency.

The second time you trigger the mousedown event it finds onUp on the object itself, but still calls bind on it to create a new function (which calls the previous function which calls the previous function).

Every time there is another mousedown event you get an additional layer of binding.

You could avoid this by testing with the hasOwnProperty method (which will tell you if the value exists on the object itself and not up the prototype chain).


问:
jQuery Validation on dynamic form
I'm working on a legacy app that uses jquery validation on a dynamic form. Now I'm trying to pass the name of each textarea input to the validation but doesn't work or maybe I'm doing it wrong. I want to the fieldName variable inside validate(see below).</p>
```<code><form class="comment_form" id="update_comment">
  @foreach($user as $key => user)
   <textarea class="form-control" name="comment[$key]"></textarea>
  @endforeach
</form>

<script>
 var $fieldName;
    $.validator.addMethod("allowedChars", function (value) {
        var reg = /^[A-Za-z0-9 _@./*!'"#&+-]*$/;
        return reg.test(value);
    });

    //foreach loop here
    var comment = document.getElementsByTagName("textarea");
    for($i=0; $i < comment.length; $i++) {
        fieldName = comment.name; // I want to the field name insode validate below
        console.log(fieldName);
        $("#update_comment").validate({
            rules: {
                fieldName: {
                    allowedChars: true
                }
            },
            messages: {
                fieldName: "Allowed special characters: _@./*!\'\"#&+-"
            }
    });

};
</code>```

答:
Consider the following.

```<code>var $fieldName;
$.validator.addMethod("allowedChars", function(value) {
  var reg = /^[A-Za-z0-9 _@./*!'"#&+-]*$/;
  return reg.test(value);
});
var opts = {
  rules: {},
  messages: {}
};

//foreach loop here
$("textarea").each(function(i, el) {
  $fieldName = $(el).attr("name");
  console.log($fieldName);
  opts.rules[$filedname] = {
    allowedChars: true
  }
  opts.messages[$fieldName] = "Allowed special characters: _@./*!\'\"#&+-";
});

$("#update_comment").validate(opts);
</code>```

Based on the following Docs: https://jqueryvalidation.org/validate/

Not sure if that is the correct library or version, since you didn't include them, but I think it's right.

Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions.

For example, if you have 3 Text Areas with Names: Text1, Text2, Text3. The resulting Object should look like this.

```<code>{
  rules: {
    Text1: {
      allowedChars: true
    },
    Text2: {
      allowedChars: true
    },
    Text3: {
      allowedChars: true
    }
  },
  messages: {
    Text1: "Allowed special characters: _@./*!\'\"#&+-",
    Text2: "Allowed special characters: _@./*!\'\"#&+-",
    Text3: "Allowed special characters: _@./*!\'\"#&+-",
  }
}
</code>```

Title: jQuery Validation on dynamic form

Body:
I'm working on a legacy app that uses jquery validation on a dynamic form. Now I'm trying to pass the name of each textarea input to the validation but doesn't work or maybe I'm doing it wrong. I want to the fieldName variable inside validate(see below).

<form class="comment_form" id="update_comment">
  @foreach($user as $key => user)
   <textarea class="form-control" name="comment[$key]"></textarea>
  @endforeach
</form>

Body:
Consider the following.

var $fieldName;
$.validator.addMethod("allowedChars", function(value) {
  var reg = /^[A-Za-z0-9 _@./*!'"#&+-]*$/;
  return reg.test(value);
});
var opts = {
  rules: {},
  messages: {}
};

//foreach loop here
$("textarea").each(function(i, el) {
  $fieldName = $(el).attr("name");
  console.log($fieldName);
  opts.rules[$filedname] = {
    allowedChars: true
  }
  opts.messages[$fieldName] = "Allowed special characters: _@./*!\'\"#&+-";
});

$("#update_comment").validate(opts);

Based on the following Docs: https://jqueryvalidation.org/validate/

Not sure if that is the correct library or version, since you didn't include them, but I think it's right.

Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions.

For example, if you have 3 Text Areas with Names: Text1, Text2, Text3. The resulting Object should look like this.

{
  rules: {
    Text1: {
      allowedChars: true
    },
    Text2: {
      allowedChars: true
    },
    Text3: {
      allowedChars: true
    }
  },
  messages: {
    Text1: "Allowed special characters: _@./*!\'\"#&+-",
    Text2: "Allowed special characters: _@./*!\'\"#&+-",
    Text3: "Allowed special characters: _@./*!\'\"#&+-",
  }
}


问:
Trying to send pagination information in response object but only passing through data property c#
I have been attempting to send pagination information to the front end from a c# backend. I have found this tutorial that I have followed directly: https://codewithmukesh.com/blog/pagination-in-aspnet-core-webapi/

I am using ASP.NET from my understanding and the class I'm working with extends ControllerBase.

I am able to get my backend setup and create the Response and PagedResponse wrapper classes that have been introduced. I don't go further as I don't have a need for the additional features the guide provides.

Just to clarify what I'd like, a response object looks like this when I sent it to the frontend:

Snippet of Response Object

```<code>RESPONSE OBJECT
{
  config
  data
  headers
  request
  status
  statusText
}
</code>```

Usually inside of the data property of this object you would see the actual data that the front end is interested. By following the tutorial I was expecting to learn how to add a property to the response object "pageCount", and result in something like this:

```<code>RESPONSE OBJECT
{
  config
  data
  headers
  request
  status
  statusText
  pageCount
}
</code>```

However, the actual result has the same response object, but with a different data property. Inside of the data property, this is what it looks like:

```<code>DATA PROPERTY
{
  data
  errors
  message
  pageCount
  succeeded
}
</code>```

I don't like this approach as the data property of the response object has additional information inside of it that's not the data. I'd instead like to be able to add the page count to response. Ideally the front end would be able to get pages from assigning a variable like 'response' to the response object and doing something like response.pageCount to determine the available pages as well as response.data to get the actual data.

I have been searching for a way to add the information to the response object and haven't found any luck. I did find a solution talking about adding it to headers but that's not where I want to add it. Additionally, I did find some outdated code that no longer works on my version.

Ideally, once I find a solution to send the pageCount back, the whole response and data structure will look like this:

```<code>RESPONSE OBJECT
{
  config
  data:
    [Array of Items] (No additional information inside of data)
  headers
  request
  status
  statusText
  pageCount
}
</code>```

Please let me know if any additional information is needed. Any help is appreciated! Thank you in advance!

EDIT Additional Code & Information:

```<code>[HttpGet("[action]")]
public IActionResult GetAll([FromHeader(Name = "itemsPerPage")] int? itemsPerPage, [FromHeader(Name = "sortBy")] string? sortBy, [FromHeader(Name = "page")] int? page) {
    List<Things> things = repo.GetAll(itemsPerPage, sortBy, page);
    return new JsonResult(new PagedResponse<List<Things>>(things, things.Count));

}
</code>```

If you were to console.log() a regular response from the backend on the front end without any pagination information, the response object would look like this

Snippet of Items

This is what I'm calling the "Response" Object.

As you can see there is a data property on this Response Object:

enter image description here

And as you can see from the picture, it is an array of items. There is no additional information inside of the data property. An example of something extra would be pagination information like "PageCount". I do not want the "Page Count" property inside of the data property. However, when following the guide I linked above, that is the result I get.

Here is what I would like my response object to look like:

Snippet of Ideal Response Object

As you can see the PageCount property is a property of the Response Object, and not inside of the data property.

Now this is what my response object looks like after I what I've attempted through the tutorial:

Snippet of Response after finishing tutorail

As you can see inside of the data property, there is another data property. You can see that the pagesCount is inside of the top level data property. And the additional attributes such as errors and message are additional properties that the tutorial added.

Hopefully that gives you an idea of what I've done and how the result is not what I would've expected.

So my direct question right now is either How can I overwrite the Response Object completely so that I can directly control what it looks like including adding a pageCount property. Or Alternatively, how can I add a single property pageCount to the already existing response object?

答:
@Andrew Williamson was the one who really answered my question. He pointed out that the response Object I was assuming was coming from the backend was actually not the response. And the information inside of the data property was what was actually being returned by the backend.

I've discovered that the reason I'm seeing that wrapper object is actually because I'm using axios through npm to access responses.

Basically the Axios NPM package describes the Response Schema:
https://www.npmjs.com/package/axios#response-schema

This shows the response object I was looking at.

The solution that I settled on was using response headers to add the page count there.

To add the response headers, I did this code:

```<code>public List<Things> GetAll([FromHeader(Name = "itemsPerPage")] int? itemsPerPage, [FromHeader(Name = "sortBy")] string? sortBy, [FromHeader(Name = "page")] int? page) {

    List<Things> things = repo.GetAll(itemsPerPage, sortBy, page);
    Response.Headers.Add("Pages", things.Count.ToString());
    return things;

}
</code>```

And this is how I accessed the pages header on the front end using AXIOS

```<code>useEffect(() => {
  endPointServiceMethod(query).then((response: any) => {
    console.log('Pages Headers');
    console.log(response.headers['pages']);
    console.log('Data');
    console.log(response.data);
    setItems(response);
  });
}, []);
</code>```

Once again, thank you Andrew Williamson for pointing out the answer!

Body:
I have been attempting to send pagination information to the front end from a c# backend. I have found this tutorial that I have followed directly: https://codewithmukesh.com/blog/pagination-in-aspnet-core-webapi/

I am using ASP.NET from my understanding and the class I'm working with extends ControllerBase.

I am able to get my backend setup and create the Response and PagedResponse wrapper classes that have been introduced. I don't go further as I don't have a need for the additional features the guide provides.

Just to clarify what I'd like, a response object looks like this when I sent it to the frontend:

Snippet of Response Object

RESPONSE OBJECT
{
  config
  data
  headers
  request
  status
  statusText
}

Usually inside of the data property of this object you would see the actual data that the front end is interested. By following the tutorial I was expecting to learn how to add a property to the response object "pageCount", and result in something like this:

RESPONSE OBJECT
{
  config
  data
  headers
  request
  status
  statusText
  pageCount
}

However, the actual result has the same response object, but with a different data property. Inside of the data property, this is what it looks like:

DATA PROPERTY
{
  data
  errors
  message
  pageCount
  succeeded
}

I don't like this approach as the data property of the response object has additional information inside of it that's not the data. I'd instead like to be able to add the page count to response. Ideally the front end would be able to get pages from assigning a variable like 'response' to the response object and doing something like response.pageCount to determine the available pages as well as response.data to get the actual data.

I have been searching for a way to add the information to the response object and haven't found any luck. I did find a solution talking about adding it to headers but that's not where I want to add it. Additionally, I did find some outdated code that no longer works on my version.

Ideally, once I find a solution to send the pageCount back, the whole response and data structure will look like this:

RESPONSE OBJECT
{
  config
  data:
    [Array of Items] (No additional information inside of data)
  headers
  request
  status
  statusText
  pageCount
}

Please let me know if any additional information is needed. Any help is appreciated! Thank you in advance!

EDIT Additional Code & Information:

[HttpGet("[action]")]
public IActionResult GetAll([FromHeader(Name = "itemsPerPage")] int? itemsPerPage, [FromHeader(Name = "sortBy")] string? sortBy, [FromHeader(Name = "page")] int? page) {
    List<Things> things = repo.GetAll(itemsPerPage, sortBy, page);
    return new JsonResult(new PagedResponse<List<Things>>(things, things.Count));

}

If you were to console.log() a regular response from the backend on the front end without any pagination information, the response object would look like this

Snippet of Items

This is what I'm calling the "Response" Object.

As you can see there is a data property on this Response Object:

enter image description here

And as you can see from the picture, it is an array of items. There is no additional information inside of the data property. An example of something extra would be pagination information like "PageCount". I do not want the "Page Count" property inside of the data property. However, when following the guide I linked above, that is the result I get.

Here is what I would like my response object to look like:

Snippet of Ideal Response Object

As you can see the PageCount property is a property of the Response Object, and not inside of the data property.

Now this is what my response object looks like after I what I've attempted through the tutorial:

Snippet of Response after finishing tutorail

As you can see inside of the data property, there is another data property. You can see that the pagesCount is inside of the top level data property. And the additional attributes such as errors and message are additional properties that the tutorial added.

Hopefully that gives you an idea of what I've done and how the result is not what I would've expected.

So my direct question right now is either How can I overwrite the Response Object completely so that I can directly control what it looks like including adding a pageCount property. Or Alternatively, how can I add a single property pageCount to the already existing response object?

Body:
@Andrew Williamson was the one who really answered my question. He pointed out that the response Object I was assuming was coming from the backend was actually not the response. And the information inside of the data property was what was actually being returned by the backend.

I've discovered that the reason I'm seeing that wrapper object is actually because I'm using axios through npm to access responses.

Basically the Axios NPM package describes the Response Schema:
https://www.npmjs.com/package/axios#response-schema

This shows the response object I was looking at.

The solution that I settled on was using response headers to add the page count there.

To add the response headers, I did this code:

public List<Things> GetAll([FromHeader(Name = "itemsPerPage")] int? itemsPerPage, [FromHeader(Name = "sortBy")] string? sortBy, [FromHeader(Name = "page")] int? page) {

    List<Things> things = repo.GetAll(itemsPerPage, sortBy, page);
    Response.Headers.Add("Pages", things.Count.ToString());
    return things;

}

And this is how I accessed the pages header on the front end using AXIOS

useEffect(() => {
  endPointServiceMethod(query).then((response: any) => {
    console.log('Pages Headers');
    console.log(response.headers['pages']);
    console.log('Data');
    console.log(response.data);
    setItems(response);
  });
}, []);

Once again, thank you Andrew Williamson for pointing out the answer!


问:
Function to return current half quarter and previous two quarters based on current date
I would like to create a variable (suffix) that prints current year and quarter in this format: '_21_q2' and (previous_suffix) which is simply suffix - 2 quarters in this case: '_21_q2'

This is what I have tried so far:

```<code>currrent_date = datetime.datetime.now()
current_year = str(x.year)[2:]
current_quarter = str(((x.month-1)//3)+1)
suffix = ('_' + current_year + '_q' + currentquarter)
previous_suffix = ?
</code>```

Desired output

```<code>suffix = '_22_q1'
previous_suffix = '_21_q2'
</code>```

答:
You should consider using strftime instead of calling str on a datetime object.

That said, here is one way leveraging pd.Period (since you have a pandas tag anyway):

```<code>import pandas as pd
from datetime import datetime

def format_quarter(date):
    year = date.strftime('%y')
    quarter = pd.Period(date, freq='q').strftime('%q')

    return f'_{year}_q{quarter}_'

# You're better off choosing a date first and formatting it afterwards
d1 = datetime.now()
d2 = d1 - pd.tseries.offsets.QuarterEnd(3)

suffix = format_quarter(d1)
previous_suffix = format_quarter(d2)
</code>```

Output:

```<code>In [18]: suffix
Out[18]: '_22_q1_'

In [19]: previous_suffix
Out[19]: '_21_q2_'
</code>```

Body:
I would like to create a variable (suffix) that prints current year and quarter in this format: '_21_q2' and (previous_suffix) which is simply suffix - 2 quarters in this case: '_21_q2'

This is what I have tried so far:

currrent_date = datetime.datetime.now()
current_year = str(x.year)[2:]
current_quarter = str(((x.month-1)//3)+1)
suffix = ('_' + current_year + '_q' + currentquarter)
previous_suffix = ?

Desired output

suffix = '_22_q1'
previous_suffix = '_21_q2'

Body:
You should consider using strftime instead of calling str on a datetime object.

That said, here is one way leveraging pd.Period (since you have a pandas tag anyway):

import pandas as pd
from datetime import datetime

def format_quarter(date):
    year = date.strftime('%y')
    quarter = pd.Period(date, freq='q').strftime('%q')

    return f'_{year}_q{quarter}_'

# You're better off choosing a date first and formatting it afterwards
d1 = datetime.now()
d2 = d1 - pd.tseries.offsets.QuarterEnd(3)

suffix = format_quarter(d1)
previous_suffix = format_quarter(d2)

Output:

In [18]: suffix
Out[18]: '_22_q1_'

In [19]: previous_suffix
Out[19]: '_21_q2_'


问:
Export two pages of a spreedsheet
I want export two pages of a same spreedsheet to one single file, how can i do it?</p>
```<code>  var ssID = "ssID"
  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=AAAA";
  var url2 = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=BBBB";
  var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);
</code>```

答:
I believe your goal is as follows.

You want to select 2 of all sheets in a Google Spreadsheet and export it as one XLSX file using Google Apps Script.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  var name = "sample.xlsx"; // Please set the output filename.
  var ssID = "###"; // Please set your Spreadsheet ID.
  var sheetIds = [12345, 67890]; // Please set the sheet IDs.

  // 1. Create new Spreadsheet as a temporal.
  var temp = SpreadsheetApp.create("temp");
  var tempId = temp.getId();

  // 2. Copy the selected sheets to the temp Spreadsheet.
  SpreadsheetApp.openById(ssID).getSheets().filter(s => sheetIds.includes(s.getSheetId())).forEach(s => s.copyTo(temp).setName(s.getSheetName()));
  temp.deleteSheet(temp.getSheets()[0]);

  // 3. Export the temp Spreadsheet as a XLSX file.
  var url = "https://docs.google.com/spreadsheets/d/" + tempId + "/export?format=xlsx";
  var params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);

  // 4. Remove the temp Spreadsheet.
  DriveApp.getFileById(tempId).setTrashed(true);
}
```

References:

filter()

forEach()

copyTo(spreadsheet) of Class Sheet

Title: Export two pages of a spreedsheet

Body:
I want export two pages of a same spreedsheet to one single file, how can i do it?

  var ssID = "ssID"
  var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=AAAA";
  var url2 = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=BBBB";
  var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);

Body:
I believe your goal is as follows.

You want to select 2 of all sheets in a Google Spreadsheet and export it as one XLSX file using Google Apps Script.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  var name = "sample.xlsx"; // Please set the output filename.
  var ssID = "###"; // Please set your Spreadsheet ID.
  var sheetIds = [12345, 67890]; // Please set the sheet IDs.

  // 1. Create new Spreadsheet as a temporal.
  var temp = SpreadsheetApp.create("temp");
  var tempId = temp.getId();

  // 2. Copy the selected sheets to the temp Spreadsheet.
  SpreadsheetApp.openById(ssID).getSheets().filter(s => sheetIds.includes(s.getSheetId())).forEach(s => s.copyTo(temp).setName(s.getSheetName()));
  temp.deleteSheet(temp.getSheets()[0]);

  // 3. Export the temp Spreadsheet as a XLSX file.
  var url = "https://docs.google.com/spreadsheets/d/" + tempId + "/export?format=xlsx";
  var params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);

  // 4. Remove the temp Spreadsheet.
  DriveApp.getFileById(tempId).setTrashed(true);
}

References:

filter()

forEach()

copyTo(spreadsheet) of Class Sheet


问:
Images not showing up in Github
I'm trying to upload my website in GitHub but the images won't show. I've tried a lot of the solutions posted here (changing path, changing png to PNG..) but nothing works?</p>
```<code>

<body>
  <div class="top-container">
    <img class="top-bird" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/seagull.png" alt="bird">
    <h1>I'm Hana</h1>
    <h2>A programmer</h2>
    <img class="bottom-bird" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/seagull.png" alt="bird">
    <img src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/mountain.png" alt="mountain">

  </div>
  <div class="middle-container">
    <div class="profile">
      <img src="Hana profile-modified.PNG" alt="Hana Profile">
      <h2 class="hello2">Hello.</h2>
      <p class="hello">My name is Hana and I'm currently studying to become a Web Developer. I graduated in 2020 from UC Riverside with a Bachelor's in Art. I have always been interested in digital design and tech in general so I'm purusing HTML, CSS
        and
        Javascript at the moment and plan to learn other coding languages like Python and Java. In my free time I enjoy reading, art, and music.</p>
    </div>
    <hr class="hr">
    <div class="skills">
      <h2 class="myskills">My Skills.</h2>

      <div class="skill-row">
        <img class="art" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/art.png">
        <h3>Web Development</h3>
        <p>I love designing and coding websites for users to enjoy and am excited to expand my skill set.</p>
      </div>
      <div class="skill-row">
        <img class="web" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/coding.png" alt="art">
        <h3>Art</h3>
        <p>Whether it is digital design or traditional art, I enjoy it all and am eager to learn more.</p>

</body>

</html>

</code>```

答:
You need to use relative paths, not full paths.

This is because you are asking GitHub to access the full path, which does not exist on their server. So change this:

```<code>C:/Users/Administrator/Documents/Coding/Project/picture.png
</code>```

Changed the path!

To this:

```<code>picture.png
</code>```

Also, as a bonus tip, you should avoid spaces in file and folder names whenever possible. You can replace spaces with _ and/or - by convention.

However, if you can't remove the spaces, you should replace them with %20, which stands simply as a space in URL encoding!

NOTE: This solution is assuming that the images are in the deployed folder. If they are not, then make a new folder (like images), and link it to your HTML by adding a relative path like before (e.g. /images/picture.png).

Title: Images not showing up in Github

Body:
I'm trying to upload my website in GitHub but the images won't show. I've tried a lot of the solutions posted here (changing path, changing png to PNG..) but nothing works?

I'm Hana

A programmer

Hello.

My name is Hana and I'm currently studying to become a Web Developer. I graduated in 2020 from UC Riverside with a Bachelor's in Art. I have always been interested in digital design and tech in general so I'm purusing HTML, CSS
        and
        Javascript at the moment and plan to learn other coding languages like Python and Java. In my free time I enjoy reading, art, and music.

My Skills.

Web Development

I love designing and coding websites for users to enjoy and am excited to expand my skill set.

Art

Whether it is digital design or traditional art, I enjoy it all and am eager to learn more.

Body:
You need to use relative paths, not full paths.

This is because you are asking GitHub to access the full path, which does not exist on their server. So change this:

C:/Users/Administrator/Documents/Coding/Project/picture.png

Changed the path!

To this:

picture.png

Also, as a bonus tip, you should avoid spaces in file and folder names whenever possible. You can replace spaces with _ and/or - by convention.

However, if you can't remove the spaces, you should replace them with %20, which stands simply as a space in URL encoding!

NOTE: This solution is assuming that the images are in the deployed folder. If they are not, then make a new folder (like images), and link it to your HTML by adding a relative path like before (e.g. /images/picture.png).


问:
trying to insert an array but Cannot access offset of type string on string laravel 8
i want to insert an array but it tells me Cannot access offset of type string on string

and i made foreach and when i do $return->request
it looks like

```<code>{
    _token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
    _method: "POST",
    name: "Wanda Rojas",
    phone: [
    "+1 (841) 393-5088",
    "+1 (769) 441-1936"
    ],
    address: "Et est cum delectus"
}
</code>```

and here is my model for clients

and i make phone field as array in protected $casts

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'address',
    ];

    protected $casts = [
        'phone' => 'array'
    ];
}
</code>```

here is my form

```<code><form action="{{route('clients.store')}}" method="POST">
        @csrf
        @method('POST')

        <input type="text" placeholder="add name" name="name"><br>
        @for ($i = 0; $i < 2; $i++) <div class="form-group">
            <label>@lang('site.phone')</label>
            <input type="text" name="phone[]" class="form-control">
            </div>
        @endfor
            <input type="text" placeholder="add address" name="address"><br>
            <button type="submit" class="btn btn-primary">add</button>
</form>
</code>```

and here is my controller at store method

```<code> public function store(Request $request)
{
    //return $request;

    $this->validate($request,[
        'name' => 'required',
        'phone' => 'required|array|min:1',
        'phone.*' => 'required',
        'address' => 'required'
    ]);

    $phone = $request->phone;
    foreach ($phone as $p){
        $add = new Client();
        $add->name = $request->name;
        $add->phone = $p['phone'];
        $add->address = $request->address;
        $add->save();
    };

    return redirect()->route('clients.index');
}
</code>```

答:
Your code when you store client should looks like this

```<code>   public function store(Request $request)
    {
        //return $request;

        $this->validate($request,[
            'name' => 'required',
            'phone' => 'required|array|min:1',
            'phone.*' => 'required',
            'address' => 'required'
        ]);

        $phone = $request->phone;

        $add = new Client();
        $add->name = $request->name;
        $add->phone = $phone; // $phone it's already an array, so you should only set it to property
        $add->address = $request->address;
        $add->save();

        return redirect()->route('clients.index');
    }
</code>```

and in clients.index.blade.php to access phone

```<code>@foreach($client->phone as $phone)
  ...
  {{ $phone }}
  ...
@endforeach
</code>```

Body:
i want to insert an array but it tells me Cannot access offset of type string on string

and i made foreach and when i do $return->request
it looks like

{
    _token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
    _method: "POST",
    name: "Wanda Rojas",
    phone: [
    "+1 (841) 393-5088",
    "+1 (769) 441-1936"
    ],
    address: "Et est cum delectus"
}

and here is my model for clients

and i make phone field as array in protected $casts

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'address',
    ];

    protected $casts = [
        'phone' => 'array'
    ];
}

here is my form

<form action="{{route('clients.store')}}" method="POST">
        @csrf
        @method('POST')

        <input type="text" placeholder="add name" name="name">

        @for ($i = 0; $i < 2; $i++)

            @lang('site.phone')
            <input type="text" name="phone[]" class="form-control">

        @endfor
            <input type="text" placeholder="add address" name="address">

            <button type="submit" class="btn btn-primary">add</button>
</form>

and here is my controller at store method

 public function store(Request $request)
{
    //return $request;

    $this->validate($request,[
        'name' => 'required',
        'phone' => 'required|array|min:1',
        'phone.*' => 'required',
        'address' => 'required'
    ]);

    $phone = $request->phone;
    foreach ($phone as $p){
        $add = new Client();
        $add->name = $request->name;
        $add->phone = $p['phone'];
        $add->address = $request->address;
        $add->save();
    };

    return redirect()->route('clients.index');
}

Body:
Your code when you store client should looks like this

   public function store(Request $request)
    {
        //return $request;

        $this->validate($request,[
            'name' => 'required',
            'phone' => 'required|array|min:1',
            'phone.*' => 'required',
            'address' => 'required'
        ]);

        $phone = $request->phone;

        $add = new Client();
        $add->name = $request->name;
        $add->phone = $phone; // $phone it's already an array, so you should only set it to property
        $add->address = $request->address;
        $add->save();

        return redirect()->route('clients.index');
    }

and in clients.index.blade.php to access phone

@foreach($client->phone as $phone)
  ...
  {{ $phone }}
  ...
@endforeach


问:
Python wakeup word for AI assistant
I have a voice assistant in python and can't add a wake word.
When I execute the code it just keeps listening until I stop talkin then it shuts off I need to make it keep listening for a wake word and when it hears the wake word to listen for I command.</p>
```<code>import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import requests
from bs4 import BeautifulSoup
from selenium import webdriver

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
rn = sr.Recognizer()

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            rn.adjust_for_ambient_noise(source)
            voice = rn.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        print(time)
        talk('Current time is ' + time)
    else:
        talk('Please say the command again.')

while True:
    run_alexa()
</code>```

答:
You can try doing the following:</p>
```<code>wake_word = "your wake word"

while True:
    print("Listening")
    text = take_command()

    if text.count(wake_word) > 0:
        talk("I am ready")
        run_alexa
</code>```

Title: Python wakeup word for AI assistant

Body:
I have a voice assistant in python and can't add a wake word.
When I execute the code it just keeps listening until I stop talkin then it shuts off I need to make it keep listening for a wake word and when it hears the wake word to listen for I command.

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import requests
from bs4 import BeautifulSoup
from selenium import webdriver

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
rn = sr.Recognizer()

def talk(text):
    engine.say(text)
    engine.runAndWait()

def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            rn.adjust_for_ambient_noise(source)
            voice = rn.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        print(time)
        talk('Current time is ' + time)
    else:
        talk('Please say the command again.')

while True:
    run_alexa()

Body:
You can try doing the following:

wake_word = "your wake word"

while True:
    print("Listening")
    text = take_command()

    if text.count(wake_word) > 0:
        talk("I am ready")
        run_alexa


问:
What is the reasoning behind github access tokens?
And are they more secure or less secure than SSH key pairs.

I am using these instead of SSH key pairs, as referenced on github.  And it appears to me that they are just randomized complex passwords.

I authenticate now by putting my username / token in, instead of my username / password.  I don't see how this can provide better security than a password.

I'm not opposed to using them, but they just seem like auto-generated passwords.  It would also appear they are less secure than SSH.

答:
They are first different: a token is to be used with HTTPS URL.

I know I would not be able to push using SSH from my company: any egress SSH is forbidden.

And since I have to use HTTPS, tokens are mandatory (because they can be easily revoked/regenerated, as opposed to a password which, if compromised, give access to your all account)

See more with "Behind GitHub’s new authentication token formats":

Many of our old authentication token formats are hex-encoded 40 character strings that are indistinguishable from other encoded data like SHA hashes. These have several limitations, such as inefficient or even inaccurate detection of compromised tokens for our secret scanning feature.

token prefixes are a clear way to make tokens identifiable. We are including specific 3 letter prefixes to represent each token, starting with a company signifier, gh, and the first letter of the token type.

Additionally, we want to make these prefixes clearly distinguishable within the token to improve readability. Thus, we are adding a separator: _.

An underscore is not a Base64 character which helps ensure that our tokens cannot be accidentally duplicated by randomly generated strings like SHAs.

And:

A checksum virtually eliminates false positives for secret scanning offline. We can check the token input matches the checksum and eliminate fake tokens without having to hit our database.

Our implementation for OAuth access tokens are now 178:


问:
Zend Framework Facebook-like wall plugin
Do you know any plugin for adding a Facebook-like wall to my Zend Framework application?</p>

答:
Here is a jQuery plugin that provides that functionality.  http://www.neosmart.de/social-media/facebook-wall

If you need to do this all server side you should be able to look through the plugin and extract the appropriate FB api calls that they are using to retrieve the data.


问:
How to authenticate gocql to AWS
I have a Go service that needs to connect Keyspaces on AWS. My pod has a role and AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID and AWS_SESSION_TOKEN env vars.

I want to use aws SDK v2. What credential provider should I use? ec2rolecreds or other one (maybe stscreds)?

I tried to implement example from here. But I get an error

```<code>no EC2 IMDS role found, operation error ec2imds: GetMetadata, request canceled, context deadline exceeded
</code>```

Where can I find working example and more explanations?

UPDATE

Now my code looks like this:

awsCfg, err := awsConfig.LoadDefaultConfig(ctx)
if err != nil {
    return nil, fmt.Errorf("failed to load AWS config: %w", err)
}

imdsClient := imds.NewFromConfig(awsCfg)

appCreds := aws.NewCredentialsCache(ec2rolecreds.New(func(options *ec2rolecreds.Options) {
        options.Client = imdsClient
}))
cluster := gocql.NewCluster(cassandraHost)

auth := sigv4.NewAwsAuthenticator()
auth.SessionToken = value.SessionToken
auth.AccessKeyId = value.AccessKeyID
auth.SecretAccessKey = value.SecretAccessKey

cluster.Authenticator = auth

session, err := cluster.CreateSession()
```
<p><code>Retrieve()</code> returns an error</p>
```no EC2 IMDS role found, operation error ec2imds: GetMetadata, exceeded maximum number of attempts, 3, request send failed, Get \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\": dial tcp 169.254.169.254:80: connect: host is down
```
<p><strong>UPDATE 2</strong></p>
<p>In the same environment AWS SDK v1 works ok. So physically AWS endpoint is available.</p>
<pre class="lang-golang prettyprint-override"><code>
session, err := aws_sess.NewSession()
if err != nil {
    return fmt.Errorf("failed to create AWS session: %w", err)
}

creds := credentialsV1.NewChainCredentials(
    []credentialsV1.Provider{
        &credentialsV1.EnvProvider{},
        &ec2rolecredsV1.EC2RoleProvider{
            Client: ec2metadataV1.New(session),
    }})

value, getErr := creds.Get()
</code>```

答:
no EC2 IMDS role found, operation error ec2imds: GetMetadata, exceeded maximum number of attempts, 3, request send failed, Get \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\": dial tcp 169.254.169.254:80: connect: host is down

Your snippet of code is attempting to use the EC2 instance meta-data service to read an IAM role to use. For that to work, you need to be able to communicate with it, and the role must be attached to the instance.

Is your Go service running on an EC2 instance? If not, that would explain your error. If it is, make sure the process or container has appropriate network access (eg: network namespace) to communicate with 169.254.169.254.

Title: How to authenticate gocql to AWS

Body:
I have a Go service that needs to connect Keyspaces on AWS. My pod has a role and AWS_SECRET_ACCESS_KEY, AWS_ACCESS_KEY_ID and AWS_SESSION_TOKEN env vars.

I want to use aws SDK v2. What credential provider should I use? ec2rolecreds or other one (maybe stscreds)?

I tried to implement example from here. But I get an error

no EC2 IMDS role found, operation error ec2imds: GetMetadata, request canceled, context deadline exceeded

Where can I find working example and more explanations?

UPDATE

Now my code looks like this:

awsCfg, err := awsConfig.LoadDefaultConfig(ctx)
if err != nil {
    return nil, fmt.Errorf("failed to load AWS config: %w", err)
}

imdsClient := imds.NewFromConfig(awsCfg)

appCreds := aws.NewCredentialsCache(ec2rolecreds.New(func(options *ec2rolecreds.Options) {
        options.Client = imdsClient
}))
cluster := gocql.NewCluster(cassandraHost)

auth := sigv4.NewAwsAuthenticator()
auth.SessionToken = value.SessionToken
auth.AccessKeyId = value.AccessKeyID
auth.SecretAccessKey = value.SecretAccessKey

cluster.Authenticator = auth

session, err := cluster.CreateSession()

Retrieve() returns an error

no EC2 IMDS role found, operation error ec2imds: GetMetadata, exceeded maximum number of attempts, 3, request send failed, Get \"http://169.254.169.254/latest/meta-data/iam/security-credentials/\": dial tcp 169.254.169.254:80: connect: host is down

UPDATE 2

In the same environment AWS SDK v1 works ok. So physically AWS endpoint is available.

session, err := aws_sess.NewSession()
if err != nil {
    return fmt.Errorf("failed to create AWS session: %w", err)
}

creds := credentialsV1.NewChainCredentials(
    []credentialsV1.Provider{
        &credentialsV1.EnvProvider{},
        &ec2rolecredsV1.EC2RoleProvider{
            Client: ec2metadataV1.New(session),
    }})

value, getErr := creds.Get()


问:
Typescript specify string array or just empty array but not `any[ ]`
Got this basic problem:

```<code>let b:string[] = []
undefined
> b
[]
> b[0].split('')
</code>```

Throws an error because b[0] won't store a string. Also [ ] is different from [null] or [undefined] as far as I understand.

And this isn't good enough b:string[]|[] because that makes it any[] afaik.

How do you specify either string[] or empty array [ ]?

答:
```<code>  const c: [] | string[] = []; // either string array, or empty array
</code>```

Also, in javascript, referring to array elements that are not defined returns undefined - it's the way javascript works.

Writing "safe" code while working with possibly undefined values might look like this

```<code>const c: string[] = [];

console.log((c[5] ?? '').split('.'));

// or

console.log(c[5]?.split('.'));
</code>```

Body:
Got this basic problem:

let b:string[] = []
undefined
> b
[]
> b[0].split('')

Throws an error because b[0] won't store a string. Also [ ] is different from [null] or [undefined] as far as I understand.

And this isn't good enough b:string[]|[] because that makes it any[] afaik.

How do you specify either string[] or empty array [ ]?

Body:
  const c: [] | string[] = []; // either string array, or empty array

Also, in javascript, referring to array elements that are not defined returns undefined - it's the way javascript works.

Writing "safe" code while working with possibly undefined values might look like this

const c: string[] = [];

console.log((c[5] ?? '').split('.'));

// or

console.log(c[5]?.split('.'));


问:
How to define tablelayout dynamically in Android?
How do I create table rows dynamically in this columns should be in horizontal way and each row should be separated by single line or different colours in Android.</p>

答:
Look at the following code.
layout is table Layout;rowColor is the color you can set for the row background</p>

```<code>TableRow tr1=new TableRow(this);
TextView title=new TextView(this);
title.setText(tit);
title.setTextColor(Color.rgb(0,0,0));
tr1.addView(title,150,30);
tr1.setBackgroundColor(rowColor);
layout.addView(tr1);
</code>```

Body:
Look at the following code.
layout is table Layout;rowColor is the color you can set for the row background

TableRow tr1=new TableRow(this);
TextView title=new TextView(this);
title.setText(tit);
title.setTextColor(Color.rgb(0,0,0));
tr1.addView(title,150,30);
tr1.setBackgroundColor(rowColor);
layout.addView(tr1);


问:
Fetching specific fields from an S3 document
I am using AWS Java SDK in my application to talk to one of my S3 buckets which holds objects in JSON format.

A document may look like this:

{
    "a" : dataA,
    "b" : dataB,
    "c" : dataC,
    "d" : dataD,
    "e" : dataE
}
```

Now, for a certain document lets say document1 I need to fetch the values corresponding to field a and b instead of fetching the entire document.

This sounds like something that wouldn't be possible because S3 buckets can have any type of documents in them and not just JSONs.

Is this something that is achievable though?

答:
That's actually doable. You could do selects like you've described, but only for particular formats: JSON, CSV, Parquet.

Imagine having a data.json file in so67315601 bucket in eu-central-1:

{
  "a": "dataA",
  "b": "dataB",
  "c": "dataC",
  "d": "dataD",
  "e": "dataE"
}
```
<p>First, learn how to select the fields via the S3 Console. Use "Object Actions" → "Query with S3 Select":</p>
<p><img src="https://i.stack.imgur.com/4g3hk.png" alt="enter image description here" />
<img src="https://i.stack.imgur.com/qLmNj.png" alt="enter image description here" /></p>
<hr />
<h2>AWS Java SDK 1.x</h2>
<p>Here is the code to do the select with AWS Java SDK 1.x:</p>
<pre class="lang-java prettyprint-override"><code>@ExtendWith(S3.class)
class SelectTest {
    @AWSClient(endpoint = Endpoint.class)
    private AmazonS3 client;

    @Test
    void test() throws IOException {
        // LINES: Each line in the input data contains a single JSON object
        // DOCUMENT: A single JSON object can span multiple lines in the input
        final JSONInput input = new JSONInput();
        input.setType(JSONType.DOCUMENT);

        // Configure input format and compression
        final InputSerialization inputSerialization = new InputSerialization();
        inputSerialization.setJson(input);
        inputSerialization.setCompressionType(CompressionType.NONE);

        // Configure output format
        final OutputSerialization outputSerialization = new OutputSerialization();
        outputSerialization.setJson(new JSONOutput());

        // Build the request
        final SelectObjectContentRequest request = new SelectObjectContentRequest();
        request.setBucketName("so67315601");
        request.setKey("data.json");
        request.setExpression("SELECT s.a, s.b FROM s3object s LIMIT 5");
        request.setExpressionType(ExpressionType.SQL);
        request.setInputSerialization(inputSerialization);
        request.setOutputSerialization(outputSerialization);

        // Run the query
        final SelectObjectContentResult result = client.selectObjectContent(request);

        // Parse the results
        final InputStream stream = result.getPayload().getRecordsInputStream();

        IOUtils.copy(stream, System.out);
    }
}
</code>```

The output is:

{"a":"dataA","b":"dataB"}
```
<hr />
<h2>AWS Java SDK 2.x</h2>
<p>The code for the AWS Java SDK 2.x is more cunning. Refer to this ticket for more information.</p>
<pre class="lang-java prettyprint-override"><code>@ExtendWith(S3.class)
class SelectTest {
    @AWSClient(endpoint = Endpoint.class)
    private S3AsyncClient client;

    @Test
    void test() throws Exception {
        final InputSerialization inputSerialization = InputSerialization
            .builder()
            .json(JSONInput.builder().type(JSONType.DOCUMENT).build())
            .compressionType(CompressionType.NONE)
            .build();

        final OutputSerialization outputSerialization = OutputSerialization.builder()
            .json(JSONOutput.builder().build())
            .build();

        final SelectObjectContentRequest select = SelectObjectContentRequest.builder()
            .bucket("so67315601")
            .key("data.json")
            .expression("SELECT s.a, s.b FROM s3object s LIMIT 5")
            .expressionType(ExpressionType.SQL)
            .inputSerialization(inputSerialization)
            .outputSerialization(outputSerialization)
            .build();
        final TestHandler handler = new TestHandler();

        client.selectObjectContent(select, handler).get();

        RecordsEvent response = (RecordsEvent) handler.receivedEvents.stream()
            .filter(e -> e.sdkEventType() == SelectObjectContentEventStream.EventType.RECORDS)
            .findFirst()
            .orElse(null);

        System.out.println(response.payload().asUtf8String());
    }

    private static class TestHandler implements SelectObjectContentResponseHandler {
        private SelectObjectContentResponse response;
        private List<SelectObjectContentEventStream> receivedEvents = new ArrayList<>();
        private Throwable exception;

        @Override
        public void responseReceived(SelectObjectContentResponse response) {
            this.response = response;
        }

        @Override
        public void onEventStream(SdkPublisher<SelectObjectContentEventStream> publisher) {
            publisher.subscribe(receivedEvents::add);
        }

        @Override
        public void exceptionOccurred(Throwable throwable) {
            exception = throwable;
        }

        @Override
        public void complete() {
        }
    }
}
</code>```

As you see, it's possible to make S3 selects programmatically!

You might be wondering what are those @AWSClient and @ExtendWith( S3.class )?

This is a small library to inject AWS clients in your tests, named aws-junit5. It would greatly simplify your tests. I am the author. The usage is really simple — try it in your next project!

Body:
I am using AWS Java SDK in my application to talk to one of my S3 buckets which holds objects in JSON format.

A document may look like this:

{
    "a" : dataA,
    "b" : dataB,
    "c" : dataC,
    "d" : dataD,
    "e" : dataE
}

Now, for a certain document lets say document1 I need to fetch the values corresponding to field a and b instead of fetching the entire document.

This sounds like something that wouldn't be possible because S3 buckets can have any type of documents in them and not just JSONs.

Is this something that is achievable though?

Body:
That's actually doable. You could do selects like you've described, but only for particular formats: JSON, CSV, Parquet.

Imagine having a data.json file in so67315601 bucket in eu-central-1:

{
  "a": "dataA",
  "b": "dataB",
  "c": "dataC",
  "d": "dataD",
  "e": "dataE"
}

First, learn how to select the fields via the S3 Console. Use "Object Actions" → "Query with S3 Select":

AWS Java SDK 1.x

Here is the code to do the select with AWS Java SDK 1.x:

@ExtendWith(S3.class)
class SelectTest {
    @AWSClient(endpoint = Endpoint.class)
    private AmazonS3 client;

    @Test
    void test() throws IOException {
        // LINES: Each line in the input data contains a single JSON object
        // DOCUMENT: A single JSON object can span multiple lines in the input
        final JSONInput input = new JSONInput();
        input.setType(JSONType.DOCUMENT);

        // Configure input format and compression
        final InputSerialization inputSerialization = new InputSerialization();
        inputSerialization.setJson(input);
        inputSerialization.setCompressionType(CompressionType.NONE);

        // Configure output format
        final OutputSerialization outputSerialization = new OutputSerialization();
        outputSerialization.setJson(new JSONOutput());

        // Build the request
        final SelectObjectContentRequest request = new SelectObjectContentRequest();
        request.setBucketName("so67315601");
        request.setKey("data.json");
        request.setExpression("SELECT s.a, s.b FROM s3object s LIMIT 5");
        request.setExpressionType(ExpressionType.SQL);
        request.setInputSerialization(inputSerialization);
        request.setOutputSerialization(outputSerialization);

        // Run the query
        final SelectObjectContentResult result = client.selectObjectContent(request);

        // Parse the results
        final InputStream stream = result.getPayload().getRecordsInputStream();

        IOUtils.copy(stream, System.out);
    }
}

The output is:

{"a":"dataA","b":"dataB"}

AWS Java SDK 2.x

The code for the AWS Java SDK 2.x is more cunning. Refer to this ticket for more information.

@ExtendWith(S3.class)
class SelectTest {
    @AWSClient(endpoint = Endpoint.class)
    private S3AsyncClient client;

    @Test
    void test() throws Exception {
        final InputSerialization inputSerialization = InputSerialization
            .builder()
            .json(JSONInput.builder().type(JSONType.DOCUMENT).build())
            .compressionType(CompressionType.NONE)
            .build();

        final OutputSerialization outputSerialization = OutputSerialization.builder()
            .json(JSONOutput.builder().build())
            .build();

        final SelectObjectContentRequest select = SelectObjectContentRequest.builder()
            .bucket("so67315601")
            .key("data.json")
            .expression("SELECT s.a, s.b FROM s3object s LIMIT 5")
            .expressionType(ExpressionType.SQL)
            .inputSerialization(inputSerialization)
            .outputSerialization(outputSerialization)
            .build();
        final TestHandler handler = new TestHandler();

        client.selectObjectContent(select, handler).get();

        RecordsEvent response = (RecordsEvent) handler.receivedEvents.stream()
            .filter(e -> e.sdkEventType() == SelectObjectContentEventStream.EventType.RECORDS)
            .findFirst()
            .orElse(null);

        System.out.println(response.payload().asUtf8String());
    }

    private static class TestHandler implements SelectObjectContentResponseHandler {
        private SelectObjectContentResponse response;
        private List<SelectObjectContentEventStream> receivedEvents = new ArrayList<>();
        private Throwable exception;

        @Override
        public void responseReceived(SelectObjectContentResponse response) {
            this.response = response;
        }

        @Override
        public void onEventStream(SdkPublisher<SelectObjectContentEventStream> publisher) {
            publisher.subscribe(receivedEvents::add);
        }

        @Override
        public void exceptionOccurred(Throwable throwable) {
            exception = throwable;
        }

        @Override
        public void complete() {
        }
    }
}

As you see, it's possible to make S3 selects programmatically!

You might be wondering what are those @AWSClient and @ExtendWith( S3.class )?

This is a small library to inject AWS clients in your tests, named aws-junit5. It would greatly simplify your tests. I am the author. The usage is really simple — try it in your next project!


问:
Unity Rigidbody2D stick to Platform which is moving horizontal
I am looking for a solution to the following problem:
I have a player and a level that moves horizontally. If the player lands on a platform, the platform moves, but the player stays on his position and does not move with it.

Do you know a way to get around this and have the player move with the platform?

答: Hayo, the simplest solution would be to make the player a child object of whatever object he is standing on, this way any movement of the platform would also be applied to the player.</p>


问:
Add GitLab CI job to pipeline based on script command result
I have a GitLab CI pipeline with a 'migration' job which I want to be added only if certain files changed between current commit and master branch, but in my current project I'm forced to use GitLab CI pipelines for push event which complicates things.

Docs on rules:changes clearly states that it will glitch and will not work properly without MR (my case of push event), so that's out of question.

Docs on rules:if states that it only works with env variables. But docs on passing CI/CD variables to another job clearly states that

These variables cannot be used as CI/CD variables to configure a
pipeline, but they can be used in job scripts.

So, now I'm stuck. I can just skip running the job in question overriding the script and checking for file changes, but what I want is not adding the job in question to pipeline in first place.

答:
While you can't add a job alone to a pipeline based on the output of a script, you can add a child pipeline dynamically based on the script output. The method of using rules: with dynamic variables won't work because rules: are evaluated at the time the pipeline is created, as you found in the docs.

However, you can achieve the same effect using dynamic child-pipelines feature. The idea is you dynamically create the YAML for the desired pipeline in a job. That YAML created by your job will be used to create a child pipeline, which your pipeline can depend on.


问:
Filter names from Json object/array using jsonpath query
I am trying to extract all name from computerScience and electronics using json path query

my input json is

```<code>{
  "computerscience": [
    {
      "name": "john doe",
      "grade": "B",
      "year": "4"
    },
    {
      "name": "Bjarne Stroustrup",
      "grade": "A",
      "year": "4"
    },
    {
      "name": "Dennis Ritchie",
      "grade": "A",
      "year": "4"
    }
  ],
  "someProp1": "false",
  "someProp2": "dirSync",
  "electronics": [
    {
      "name": "thomas edison",
      "grade": "B",
      "year": "4"
    },
    {
      "name": "nichola tesla",
      "grade": "B",
      "year": "4"
    }
  ]
}
</code>```

I want to figure out json path which give me below result

```<code>["john doe", "Bjarne Stroustrup", "Dennis Ritchie" , "thomas edison", "nichola tesla"]
</code>```

I want to extract names from only computerScience and electronics

I am trying few jsonpaths here but it won't work

答:
This pattern works:

```<code>$.[computerscience,electronics][*].name
</code>```

This simpler pattern works as long as there aren't any other properties that you want to avoid selecting the names from:

```<code>$.*[*].name
</code>```

Or if you really just want to collect all the names in the document, there's:

```<code>$..name
</code>```

Body:
I am trying to extract all name from computerScience and electronics using json path query

my input json is

{
  "computerscience": [
    {
      "name": "john doe",
      "grade": "B",
      "year": "4"
    },
    {
      "name": "Bjarne Stroustrup",
      "grade": "A",
      "year": "4"
    },
    {
      "name": "Dennis Ritchie",
      "grade": "A",
      "year": "4"
    }
  ],
  "someProp1": "false",
  "someProp2": "dirSync",
  "electronics": [
    {
      "name": "thomas edison",
      "grade": "B",
      "year": "4"
    },
    {
      "name": "nichola tesla",
      "grade": "B",
      "year": "4"
    }
  ]
}

I want to figure out json path which give me below result

["john doe", "Bjarne Stroustrup", "Dennis Ritchie" , "thomas edison", "nichola tesla"]

I want to extract names from only computerScience and electronics

I am trying few jsonpaths here but it won't work

Body:
This pattern works:

$.[computerscience,electronics][*].name

This simpler pattern works as long as there aren't any other properties that you want to avoid selecting the names from:

$.*[*].name

Or if you really just want to collect all the names in the document, there's:

$..name


问:
How to filter based on the URL of an image in Google Sheets?
I'm trying to create a filter view in Google Sheets that will only show certain rows of the spreadsheet based on the last few characters of the URL of the images that are inserted in every row. For example, most rows have an image that is simply named "image1.png", "image2.png", "image3.png", etc, but every once in a while there'll be a row where the image is named "image63_s.png", "image176_s.png", "image271_s.png", etc. What I'd like to do is create a filter view that will only show rows where the name of the image in the URL ends with "_s".

EDIT: The images are inserted into the sheet with the formula =IMAGE("https://www.example.com/site/image1.png"), so I don't think regex can work here.

答:
use custom formula:

```<code>=REGEXMATCH(A1, ".*_s.png$")
</code>```

update:

```<code>=REGEXMATCH(FORMULATEXT(A1), ".*_s.png.*")
</code>```

or as suggested have a hidden helper column of urls

Body:
use custom formula:

=REGEXMATCH(A1, ".*_s.png$")

update:

=REGEXMATCH(FORMULATEXT(A1), ".*_s.png.*")

or as suggested have a hidden helper column of urls