问:
How can I retrieve all data from a given AWS Powershell cmdlets/alias?
When running a cmdlet like Get-WKSWorkspaces, it will return a set of properties about your workspaces (e.g. WorkspaceID, Username, SubnetID, BundleID, etc.), but not everything you see in the AWS GUI. I am specifically trying to pull things like Running Mode, Compute Type, and Creation Time as well, but can't seem to find where to pull it.

In my research, I got up to the point where I was using $AWSHistory to try and dig deeper into the data returned from my previous cmdlets, but have definitely hit a wall and can't seem to get around it.

I do have a partial command that is giving me most of the output I need:

```<code>$region = Get-DefaultAWSRegion
$lastuserconnect = Get-WKSWorkspacesConnectionStatus | Select LastKnownUserConnectionTimestamp

Get-WKSWorkspace -ProfileName ITSLayer1-053082227562-Profile | Select WorkspaceID, UserName, BundleID, DirectoryID,
@{Name="Region"; Expression={$region.Region}},
@{Name="LastKnownUserConnect"; Expression=
{$lastuserconnect.LastKnownUserConnectionTimestamp}}
</code>```

Update for posterity: Actually got something decent to come out here. It's slow, but it renders in a table format pretty well and includes a bit at the start to select your AWS region.

Suggestions for improvement include:

Automatically switching the Region select to get all workspaces from
the main Regions we use

Cleaning the lines up so it's easier to
read

Getting the region to automatically append the filename so it
doesn't overwrite your file every time (it's in there but broken at
the moment...still pops out a file with 'workspace_properties.csv'
as the name)

Optimizing the script because it's pretty slow

$lastuserconnect = Get-WKSWorkspacesConnectionStatus -ProfileName $profile
$defaultregion = Get-DefaultAWSRegion
$showallregions = Get-AWSRegion
$exportpath = "" + $env:USERPROFILE + "\workspace_properties" +
$defaultregion.Region + ".csv"

$showallregions | Format-Table

$setregion = Read-Host -Prompt 'AWS Region'

Clear-DefaultAWSRegion
Set-DefaultAWSRegion $setregion

Get-WKSWorkspace -ProfileName $profile | Select WorkspaceID, UserName, BundleID, DirectoryID, @{Name="ComputeType"; Expression={$.WorkspaceProperties.ComputeTypeName}}, @{Name="RunningMode"; Expression={$.WorkspaceProperties.RunningMode}}, @{Name="Region"; Expression={$defaultregion.Region}}, @{Name="LastKnownUserConnect"; Expression={$_ | foreach {$lastuserconnect = Get-WKSWorkspacesConnectionStatus -ProfileName $profile -WorkspaceId $_.WorkspaceId; echo $lastuserconnect.LastKnownUserConnectionTimestamp}}} | Export-Csv $exportpath

答:
From looking at the docs it appears what you are looking for in the property WorkspaceProperties which contains an Amazon.WorkSpaces.Model.WorkspaceProperties object with the following properties:

ComputeTypeName   Amazon.WorkSpaces.Compute

  RootVolumeSizeGib System.Int32

  RunningMode   Amazon.WorkSpaces.RunningMode

  RunningModeAutoStopTimeoutInMinutes   System.Int32

  UserVolumeSizeGib  System.Int32

Not sure about the CreationTime though...

Body:
When running a cmdlet like Get-WKSWorkspaces, it will return a set of properties about your workspaces (e.g. WorkspaceID, Username, SubnetID, BundleID, etc.), but not everything you see in the AWS GUI. I am specifically trying to pull things like Running Mode, Compute Type, and Creation Time as well, but can't seem to find where to pull it.

In my research, I got up to the point where I was using $AWSHistory to try and dig deeper into the data returned from my previous cmdlets, but have definitely hit a wall and can't seem to get around it.

I do have a partial command that is giving me most of the output I need:

$region = Get-DefaultAWSRegion
$lastuserconnect = Get-WKSWorkspacesConnectionStatus | Select LastKnownUserConnectionTimestamp

Get-WKSWorkspace -ProfileName ITSLayer1-053082227562-Profile | Select WorkspaceID, UserName, BundleID, DirectoryID,
@{Name="Region"; Expression={$region.Region}},
@{Name="LastKnownUserConnect"; Expression=
{$lastuserconnect.LastKnownUserConnectionTimestamp}}

Update for posterity: Actually got something decent to come out here. It's slow, but it renders in a table format pretty well and includes a bit at the start to select your AWS region.

Suggestions for improvement include:

Automatically switching the Region select to get all workspaces from
the main Regions we use

Cleaning the lines up so it's easier to
read

Getting the region to automatically append the filename so it
doesn't overwrite your file every time (it's in there but broken at
the moment...still pops out a file with 'workspace_properties.csv'
as the name)

Optimizing the script because it's pretty slow

$lastuserconnect = Get-WKSWorkspacesConnectionStatus -ProfileName $profile
$defaultregion = Get-DefaultAWSRegion
$showallregions = Get-AWSRegion
$exportpath = "" + $env:USERPROFILE + "\workspace_properties" +
$defaultregion.Region + ".csv"

$showallregions | Format-Table

$setregion = Read-Host -Prompt 'AWS Region'

Clear-DefaultAWSRegion
Set-DefaultAWSRegion $setregion

Get-WKSWorkspace -ProfileName $profile | Select WorkspaceID, UserName, BundleID, DirectoryID, @{Name="ComputeType"; Expression={$.WorkspaceProperties.ComputeTypeName}}, @{Name="RunningMode"; Expression={$.WorkspaceProperties.RunningMode}}, @{Name="Region"; Expression={$defaultregion.Region}}, @{Name="LastKnownUserConnect"; Expression={$_ | foreach {$lastuserconnect = Get-WKSWorkspacesConnectionStatus -ProfileName $profile -WorkspaceId $_.WorkspaceId; echo $lastuserconnect.LastKnownUserConnectionTimestamp}}} | Export-Csv $exportpath


来源: stackexchange

问:
How to catch exception when creating MongoClient instance
I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.

```<code>try {
            new MongoClient("localhost", 1111);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

If the hostname or port number is not correct, I will get below exceptions. I wander how I can catch that exceptions. MongoDB connecting is happening in an internal thread which can't be catched by client code. I want to know whether the MongoClient has connected correctly or not. How can I get that information?

```<code>INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more
</code>```

EDIT1

The exceptions shown above is not catch by my code. It may be catch by Mongo code. So I don't know whether the instance is created correctly or not.

答:
For anyone who stumbles upon this now. I had the same issue and tried using Macario's answer, but didn't come out with much luck. Then realized that the thread monitoring the connection is not sending it to System.err, but instead was sending it to System.out so instead of using System.err, use System.out like so: </p>

```<code>PrintStream out = System.out;  // Save the original out stream to reset later

// Set out to a buffer
ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setOut(new PrintStream(file));

mongoClient = new MongoClient(new MongoClientURI("<connection_string>")));

// Found this to be important as we need to wait for the thread to dump to out
// 1000 millis was too fast for me but 2000 did the trick
Thread.sleep(2000);

// Convert buffer to a string
String texto=new String(file.toByteArray());

System.setOut(out); // Reset out

// Check if saved out contins the error (I was looking for MongoSocketException)
if(texto.contains("MongoSocketException")){
    // Do Stuff
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.

try {
            new MongoClient("localhost", 1111);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

If the hostname or port number is not correct, I will get below exceptions. I wander how I can catch that exceptions. MongoDB connecting is happening in an internal thread which can't be catched by client code. I want to know whether the MongoClient has connected correctly or not. How can I get that information?

INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
    ... 3 more

EDIT1

The exceptions shown above is not catch by my code. It may be catch by Mongo code. So I don't know whether the instance is created correctly or not.

Body:
For anyone who stumbles upon this now. I had the same issue and tried using Macario's answer, but didn't come out with much luck. Then realized that the thread monitoring the connection is not sending it to System.err, but instead was sending it to System.out so instead of using System.err, use System.out like so:

PrintStream out = System.out;  // Save the original out stream to reset later

// Set out to a buffer
ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setOut(new PrintStream(file));

mongoClient = new MongoClient(new MongoClientURI("<connection_string>")));

// Found this to be important as we need to wait for the thread to dump to out
// 1000 millis was too fast for me but 2000 did the trick
Thread.sleep(2000);

// Convert buffer to a string
String texto=new String(file.toByteArray());

System.setOut(out); // Reset out

// Check if saved out contins the error (I was looking for MongoSocketException)
if(texto.contains("MongoSocketException")){
    // Do Stuff
}

ContentLicense: CC BY-SA 4.0


问:
Fluent nHibernate, ToManyBase, Generic usage
I have discovered the method T Generic() in the abstract class ToManyBase<T, TChild, TRelationshipAttributes> but I cannot find any documentation or examples of how this is used, or what it does. Can anyone enlighten me a bit?

答:
Nothing of significance.

It's the equivalent of the NHibernate generic= attribute, which is simply away of explicitly specifying that a collection is a generic one. A holdover from NHibernate's pre-generic days.


问:
How to use the result of std::regex_search?
I'm simply calling

```<code>std::smatch m;
if (std::regex_search
  (std::string (strT.GetString ()),
  m,
  std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
  ...
}
</code>```

I can't for the life of me figure out how to extract the matched values from m.

EVERY SINGLE page on the subject writes it to cout which is worthless to me. I just want to get what's been captured in a string, but no matter what I try it crashes with a "string iterators incompatible" error message.

OK so I tried a few more things and got annoyed at a lot more, most notably about how the same code worked in online testers but not on my computer. I've come down to this

```<code>std::string s (strT.GetString ()) ;
std::smatch m;
if (std::regex_search (
    s,
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}
</code>```

working, but this

```<code>std::smatch m;
if (std::regex_search (
    std::string (strT.GetString ()),
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}
</code>```

Not Working For Some Reason (with the incompatible string iterator error thingy).
There's surely some trick to it. I'll let someone who knows explain it.

答:
You are correct that you can just assign the match to a std::string; you don't have to use the stream insertion feature.

However, your third example crashes because std::smatch holds references/handles to positions in the original source data … which in your crashy case is the temporary strT.GetString() that went out of scope as soon as the regex was done (read here).

Your second example is correct.

I concede that the C++ regex implementation is not entirely intuitive at first glance.

Body:
I'm simply calling

std::smatch m;
if (std::regex_search
  (std::string (strT.GetString ()),
  m,
  std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
  ...
}

I can't for the life of me figure out how to extract the matched values from m.

EVERY SINGLE page on the subject writes it to cout which is worthless to me. I just want to get what's been captured in a string, but no matter what I try it crashes with a "string iterators incompatible" error message.

OK so I tried a few more things and got annoyed at a lot more, most notably about how the same code worked in online testers but not on my computer. I've come down to this

std::string s (strT.GetString ()) ;
std::smatch m;
if (std::regex_search (
    s,
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}

working, but this

std::smatch m;
if (std::regex_search (
    std::string (strT.GetString ()),
    m,
    std::regex ("((\\d[\\s_\\-.]*){10,13})")))
{
    std::string v = m[ 0 ] ;
}

Not Working For Some Reason (with the incompatible string iterator error thingy).
There's surely some trick to it. I'll let someone who knows explain it.


问:
Maximum update depth exceeded. Infinity loop when using TimePickerInput onChange event React.js
I have TimePickerInput component like this

```<code>  class TimePickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func.isRequired,
    disabled: PropTypes.bool
  };

  static defaultProps = {
    onChange: function() {}
  };
  componentDidMount() {
    this._$input
      .timepicker({
        autoclose: true,
        minuteStep: 5,
        showSeconds: false,
        showMeridian: false
      })
      .on("changeTime.timepicker", e => {
        this.props.onChange(e.time.value);
      });
    this._$input.timepicker("setTime", this.props.value);
  }
  componentWillReceiveProps(nextProps) {
    this._$input.timepicker("setTime", nextProps.value);
  }
  render() {
    const { disabled } = this.props;
    return (
      <Wrapper>
        <IconWrapper>
          <Icon className="fa fa-clock-o" />
        </IconWrapper>
        <Input
          innerRef={ref => (this._$input = $(ref))}
          type="text"
          size="16"
          className="form-control"
          readOnly
          disabled={disabled}
        />
      </Wrapper>
    );
  }
}
export default TimePickerInput;
</code>```

When I using it in my another component like this

```<code><TimePickerInput  value={notificationConfig.timeToSendAuditReminder} onChange={e => this.onChangeTimeField(e, 'timeToSendAuditReminder')}/>
</code>```

and have onChangeTimeField like this

```<code>onChangeTimeField = (value, fieldName) => {
    this.props.dispatch(notificationConfigActions.requestUpdateTimeField(value, fieldName))
  }
</code>```

I always get an error like this

```<code>Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
</code>```

I cannot find solution how to fix this error. I think it happened when there are a lot of onChange event call between  on("changeTime.timepicker") and when requestUpdateTimeField(value, fieldName) done

答: This might be because you're using componentWillReceivePropsuncondtionally. See this see this. You should use one of these instead of componentWillReceivePropsas it is considered legacy now.

Body:
I have TimePickerInput component like this

  class TimePickerInput extends React.Component {
  static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func.isRequired,
    disabled: PropTypes.bool
  };

  static defaultProps = {
    onChange: function() {}
  };
  componentDidMount() {
    this._$input
      .timepicker({
        autoclose: true,
        minuteStep: 5,
        showSeconds: false,
        showMeridian: false
      })
      .on("changeTime.timepicker", e => {
        this.props.onChange(e.time.value);
      });
    this._$input.timepicker("setTime", this.props.value);
  }
  componentWillReceiveProps(nextProps) {
    this._$input.timepicker("setTime", nextProps.value);
  }
  render() {
    const { disabled } = this.props;
    return (
      <Wrapper>
        <IconWrapper>
          <Icon className="fa fa-clock-o" />
        </IconWrapper>
        <Input
          innerRef={ref => (this._$input = $(ref))}
          type="text"
          size="16"
          className="form-control"
          readOnly
          disabled={disabled}
        />
      </Wrapper>
    );
  }
}
export default TimePickerInput;

When I using it in my another component like this

<TimePickerInput  value={notificationConfig.timeToSendAuditReminder} onChange={e => this.onChangeTimeField(e, 'timeToSendAuditReminder')}/>

and have onChangeTimeField like this

onChangeTimeField = (value, fieldName) => {
    this.props.dispatch(notificationConfigActions.requestUpdateTimeField(value, fieldName))
  }

I always get an error like this

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

I cannot find solution how to fix this error. I think it happened when there are a lot of onChange event call between  on("changeTime.timepicker") and when requestUpdateTimeField(value, fieldName) done


问:
Python NumPy adding [] after operator such as where
I'm super new to python. I'm trying to understand some code. The code uses the NumPy library to analyze a data stream. </p>

```<code>in0 = input_items[0]
mask = np.where(in0 > 0.9)[0]
(start, stop) = (mask[0], mask[-1])
blank = int(50e-6*sample_rate) # Skip first 50 us.
start = start+blank
foo = in1[start:stop] > 0.5
preamble_location = np.where(foo)[0][0]
</code>```

<p>In the second line np.where returns where the elements of in0 are greater than 0.9. What I don't understand is what the [0] in that line does. Similar to the last line I'm not sure what [0][0] does as well. </p>

答:
It's a function of Numpy : https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

[0] is the first element of the return.

Like :

```<code>list = [3,2,5]
print(list[0])
</code>```

The return will be :

```<code>3
</code>```

Body:
I'm super new to python. I'm trying to understand some code. The code uses the NumPy library to analyze a data stream.

in0 = input_items[0]
mask = np.where(in0 > 0.9)[0]
(start, stop) = (mask[0], mask[-1])
blank = int(50e-6*sample_rate) # Skip first 50 us.
start = start+blank
foo = in1[start:stop] > 0.5
preamble_location = np.where(foo)[0][0]

In the second line np.where returns where the elements of in0 are greater than 0.9. What I don't understand is what the [0] in that line does. Similar to the last line I'm not sure what [0][0] does as well.

Body:
It's a function of Numpy : https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

[0] is the first element of the return.

Like :

list = [3,2,5]
print(list[0])

The return will be :

3


问:
How to unzip large size zip files between blob containers without using physical filepaths
We have one requirement to extract large size .zip files (around 3 - 4 GB size) in Blob Container to other Blob Container and the extracted files are Jason files (around 35 -50GB size).

For implementation been referred code from this link: https://msdevzone.wordpress.com/2017/07/07/extract-a-zip-file-stored-in-azure-blob/ and able to extract files lesser sizes  40MB  unzipping to 400MB in few minutes but getting stuck more than an hour with 2 GB  file sizes extracting to 30GB  JSON files.

Could anyone suggest whether any better solution they come across this scenario not using file operations?

Please below code reference we worked on:

```<code>CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
BlobRequestOptions options = new BlobRequestOptions();
options.ServerTimeout = new TimeSpan(0, 20, 0);

// Save blob(zip file) contents to a Memory Stream.
using (MemoryStream zipBlobFileStream = new MemoryStream())
{
    //blockBlob.Properties.LeaseDuration
    blockBlob.DownloadToStream(zipBlobFileStream, null, options);
    zipBlobFileStream.Flush();
    zipBlobFileStream.Position = 0;
    //use ZipArchive from System.IO.Compression to extract all the files from zip file
    using (ZipArchive zip = new ZipArchive(zipBlobFileStream, ZipArchiveMode.Read, true))
    {
        //Each entry here represents an individual file or a folder
        foreach (var entry in zip.Entries)
        {
            //creating an empty file (blobkBlob) for the actual file with the same name of file
            var blob = extractcontainer.GetBlockBlobReference(entry.FullName);
            using (var stream = entry.Open())
            {
                //check for file or folder and update the above blob reference with actual content from stream
                if (entry.Length > 0)
                    blob.UploadFromStream(stream);
            }
        }
    }
}
</code>```

答:
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. Maybe you can adapt to BlockBlobs. I hope it helps!</p>

```<code>var zipFiles = _directory.ListFilesAndDirectories()
    .OfType<CloudFile>()
    .Where(x => x.Name.ToLower().Contains(".zip"))
    .ToList();

foreach (var zipFile in zipFiles)
{
    using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
    {
        foreach (var entry in zipArchive.Entries)
        {
            if (entry.Length > 0)
            {
                CloudFile extractedFile = _directory.GetFileReference(entry.Name);

                using (var entryStream = entry.Open())
                {
                    byte[] buffer = new byte[16 * 1024];
                    using (var ms = extractedFile.OpenWrite(entry.Length))
                    {
                        int read;
                        while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    }
}
</code>```

Body:
We have one requirement to extract large size .zip files (around 3 - 4 GB size) in Blob Container to other Blob Container and the extracted files are Jason files (around 35 -50GB size).

For implementation been referred code from this link: https://msdevzone.wordpress.com/2017/07/07/extract-a-zip-file-stored-in-azure-blob/ and able to extract files lesser sizes  40MB  unzipping to 400MB in few minutes but getting stuck more than an hour with 2 GB  file sizes extracting to 30GB  JSON files.

Could anyone suggest whether any better solution they come across this scenario not using file operations?

Please below code reference we worked on:

CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
BlobRequestOptions options = new BlobRequestOptions();
options.ServerTimeout = new TimeSpan(0, 20, 0);

// Save blob(zip file) contents to a Memory Stream.
using (MemoryStream zipBlobFileStream = new MemoryStream())
{
    //blockBlob.Properties.LeaseDuration
    blockBlob.DownloadToStream(zipBlobFileStream, null, options);
    zipBlobFileStream.Flush();
    zipBlobFileStream.Position = 0;
    //use ZipArchive from System.IO.Compression to extract all the files from zip file
    using (ZipArchive zip = new ZipArchive(zipBlobFileStream, ZipArchiveMode.Read, true))
    {
        //Each entry here represents an individual file or a folder
        foreach (var entry in zip.Entries)
        {
            //creating an empty file (blobkBlob) for the actual file with the same name of file
            var blob = extractcontainer.GetBlockBlobReference(entry.FullName);
            using (var stream = entry.Open())
            {
                //check for file or folder and update the above blob reference with actual content from stream
                if (entry.Length > 0)
                    blob.UploadFromStream(stream);
            }
        }
    }
}

Body:
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. Maybe you can adapt to BlockBlobs. I hope it helps!

var zipFiles = _directory.ListFilesAndDirectories()
    .OfType<CloudFile>()
    .Where(x => x.Name.ToLower().Contains(".zip"))
    .ToList();

foreach (var zipFile in zipFiles)
{
    using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
    {
        foreach (var entry in zipArchive.Entries)
        {
            if (entry.Length > 0)
            {
                CloudFile extractedFile = _directory.GetFileReference(entry.Name);

                using (var entryStream = entry.Open())
                {
                    byte[] buffer = new byte[16 * 1024];
                    using (var ms = extractedFile.OpenWrite(entry.Length))
                    {
                        int read;
                        while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                    }
                }
            }
        }
    }
}


问:
URL Rewriting based on form input
I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:

```<code>site.com/go/?id=whateverIType
</code>```

and I want to change it to

```<code>site.com/go/whateverIType
</code>```

I was thinking on Mod Rewrite, but if the user put something in the URL, like:

```<code>site.com/go/?dontwant=this&id=whateverIType&somemore=trash
</code>```

I want to ignore the other variables but "id", and rewrite the rule.

What's the better way of get this done? Thanks in advance!

PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".

答:
Mod_rewrite supports conditions and rules with RegEx, so you could have a rule that matched the ?id=XXXX, that would extract it from the URL (keeping the other parameters), and rewrote the URL accordingly.

However... I don't think you want to do this, because if you rewrite the URL to be /go/Some+Search+Query, you won't be able to pick it up with say, PHP, without parsing the URL out manually.

It's really tough to have custom, SEO-friendly URLs with user input, but it is technically possible. You're better off leaving in the ?id=XXX part, and instead, using mod_rewrite in the opposite approach... take all URLs that match the pattern /go/My+Search+Terms and translate that back into something like ?id=My+Search+Terms, that way you'll be able to easily parse out the value using the URL's GET parameters. This isn't an uncommon practice - Google actually still uses URL parameters for user input (example URL: http://www.google.com/search?q=test).

Just keep in mind that mod_rewrite rewrites the URL before anything else (even PHP), so anything you do to the URL you need to handle. Think of mod_rewrite as a regular expression-based, global "Find and Replace" for URLs, every time a page is called on the server. For example, if you remove the query string, you need to make sure your website/application/whatever accounts for that.

Title: URL Rewriting based on form input

Body:
I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:

site.com/go/?id=whateverIType

and I want to change it to

site.com/go/whateverIType

I was thinking on Mod Rewrite, but if the user put something in the URL, like:

site.com/go/?dontwant=this&id=whateverIType&somemore=trash

I want to ignore the other variables but "id", and rewrite the rule.

What's the better way of get this done? Thanks in advance!

PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".


问:
Does pimpl design pattern prevent you from compilation?
According to this article, it's trying to explain the problem which pimpl solve but i see that there is no problem in example he showed.

It says that:
"there is an issue with below design (that could be serious or not, depending on how many clients Fridge has). Since Fridge.h #includes Engine.h, any client of the Fridge class will indirectly #include the Engine class. So when the Engine class is modified, all the clients of Fridge have to recompile, even if they don’t use Engine directly."

```<code>#include "Engine.h"

class Fridge
{
public:
   void coolDown();
private:
   Engine engine_;
};
</code>```

```<code>#include "Fridge.h"

void Fridge::coolDown()
{
   /* ... */
}
</code>```

But, i see that if Engine is modified, Fridge should modify according. And since Fridge will modify, the Client which uses Fridge will also get modified.

In other words, If Engine get modified, then Fridge should be recompiled and according to that, Client also will be recompiled. In this case Client modified because Fridge is modified NOT because Engine is modified.

So, there is no indirection problem in this situation.

Am i right? if yes, So, what's the actual problem does pimpl solve? if no, can you give me an indirection example which explain this problem?

答:
In other words, If Engine get modified, then Fridge should be recompiled.

This is correct, but to be more accurate: The functions that depend on Engine need to be recompiled.

and according to that, Client also will be recompiled.

No. Just because translation unit that implements Fridges member functions is recompiled, doesn't mean that Fridges clients would need to be recompiled. Only if Fridge.h is modified, do translation units including that header need to be recompiled.

But, i see that if Engine is modified, Fridge should modify according. And since Fridge will modify, the Client which uses Fridge will also get modified.

That is the problem that the shown implementation has. If Engine was instead hidden using PIMPL, then a modification to Engine wouldn't imply a modification to the Fridge class. It only implies modification to the implementation of member functions of Fridge, which depend on Engine and those implementations are hidden by the PIMPL.

If you take a look at the PIMPL version of Fridge.h, you'll notice that it doesn't use Engine class directly, and consequently doesn't include Engine.h. A change to Engine.h therefore doesn't cause changes in Fridge.h and therefore doesn't cause changes in translation units that include Fridge.h:

```<code>class Fridge
{
public:
   Fridge();
   ~Fridge();

   void coolDown();
private:
   class FridgeImpl;
   FridgeImpl* impl_;
};
</code>```

Can you give me example how NOT recompiling Client translation unit after modifying Engine.h will cause issue?

If one translation unit uses a different definition of Engine than another translation unit, then the program violates the one definition rule, and the behaviour will be undefined.

With PIMPL, translation units that include Fridge.h do not ODR-use Engine class at all, so there is no possibility of ODR violation.

Body:
According to this article, it's trying to explain the problem which pimpl solve but i see that there is no problem in example he showed.

It says that:
"there is an issue with below design (that could be serious or not, depending on how many clients Fridge has). Since Fridge.h #includes Engine.h, any client of the Fridge class will indirectly #include the Engine class. So when the Engine class is modified, all the clients of Fridge have to recompile, even if they don’t use Engine directly."

#include "Engine.h"

class Fridge
{
public:
   void coolDown();
private:
   Engine engine_;
};

#include "Fridge.h"

void Fridge::coolDown()
{
   /* ... */
}

But, i see that if Engine is modified, Fridge should modify according. And since Fridge will modify, the Client which uses Fridge will also get modified.

In other words, If Engine get modified, then Fridge should be recompiled and according to that, Client also will be recompiled. In this case Client modified because Fridge is modified NOT because Engine is modified.

So, there is no indirection problem in this situation.

Am i right? if yes, So, what's the actual problem does pimpl solve? if no, can you give me an indirection example which explain this problem?

Body:
In other words, If Engine get modified, then Fridge should be recompiled.

This is correct, but to be more accurate: The functions that depend on Engine need to be recompiled.

and according to that, Client also will be recompiled.

No. Just because translation unit that implements Fridges member functions is recompiled, doesn't mean that Fridges clients would need to be recompiled. Only if Fridge.h is modified, do translation units including that header need to be recompiled.

But, i see that if Engine is modified, Fridge should modify according. And since Fridge will modify, the Client which uses Fridge will also get modified.

That is the problem that the shown implementation has. If Engine was instead hidden using PIMPL, then a modification to Engine wouldn't imply a modification to the Fridge class. It only implies modification to the implementation of member functions of Fridge, which depend on Engine and those implementations are hidden by the PIMPL.

If you take a look at the PIMPL version of Fridge.h, you'll notice that it doesn't use Engine class directly, and consequently doesn't include Engine.h. A change to Engine.h therefore doesn't cause changes in Fridge.h and therefore doesn't cause changes in translation units that include Fridge.h:

class Fridge
{
public:
   Fridge();
   ~Fridge();

   void coolDown();
private:
   class FridgeImpl;
   FridgeImpl* impl_;
};

Can you give me example how NOT recompiling Client translation unit after modifying Engine.h will cause issue?

If one translation unit uses a different definition of Engine than another translation unit, then the program violates the one definition rule, and the behaviour will be undefined.

With PIMPL, translation units that include Fridge.h do not ODR-use Engine class at all, so there is no possibility of ODR violation.


问:
How to read and write DDR memory in FPGA?
I am not good at English. sorry.

I don't know if the content of the question is too abstract.

I'm going to build a Neural Network Hardware Accelerator with Artix 7 FPGA.
However, block memory is out of capacity.
So I'm going to use DDR3 memory, which is included on the arty a7 board.

I want to write the value in the block memory to DDR memory or read the value in DDR memory.

Is there a good way to read and write DDR memory on the FPGA?

答:
I had a quick look at the Artix-7 product summary. They mention DD3 memory support and the datasheet mentions DDR memory controllers.

You have to find Xilinx' information about the Artix DDR controller and read through it.  Probably it has an AXI interface as Xilinx is very much into AXI these days. If so you have to write an AXI master interface to read from or write to the DDR. Or maybe Xilinx have some IP which does most of the work.

None of the above is easy! Start with installing the latest Vivado design suit (it is free) which gives you also Xilinx' docnav. You will need it as the documentation of Xilinx is reasonably good but there is a lot and a lot and a lot of it.

I'll be honest: this is not something I would recommended a begginner with HDL to do unless you are prepared to put a lot of time it (and also learn a lot).


问:
Sql stored procedure Count equity turnover for brooker
I'm trying to count a brookers qty turnover, total buy sum, total sell sum.
The problem is when the buyer is also the seller in which case the brooker has turnover the equities once on the buy side and once on the sell side. So if a brooker sells 150 equities to itself the turnover for that trade should be 300.

Table:

```<code> | InstrumentId | Price | Qty | Buyer | Seller | Date
-----------------------------------------------------
 |    265       |  22   | 100 |   A   |   B    | ----
-------------------------------------------------------
 |    265       |  23   | 150 |   A   |   A    | ----
-------------------------------------------------------
 |    265       |  21   | 75  |   C   |   A    | ----
----------------------------------------------------

Expected result: turnover 475.
Buy total: 250.
Sell total: 225.
</code>```

答:
One method is:</p>

```<code>select broker, sum(qty)
from ((select buyer as broker, qty from sales) union all
      (select seller, qty from sales)
     ) b
group by broker;
</code>```

Body:
I'm trying to count a brookers qty turnover, total buy sum, total sell sum.
The problem is when the buyer is also the seller in which case the brooker has turnover the equities once on the buy side and once on the sell side. So if a brooker sells 150 equities to itself the turnover for that trade should be 300.

Table:

 | InstrumentId | Price | Qty | Buyer | Seller | Date
-----------------------------------------------------
 |    265       |  22   | 100 |   A   |   B    | ----
-------------------------------------------------------
 |    265       |  23   | 150 |   A   |   A    | ----
-------------------------------------------------------
 |    265       |  21   | 75  |   C   |   A    | ----
----------------------------------------------------

Expected result: turnover 475.
Buy total: 250.
Sell total: 225.

Body:
One method is:

select broker, sum(qty)
from ((select buyer as broker, qty from sales) union all
      (select seller, qty from sales)
     ) b
group by broker;


问:
Why are my .NET strings so large in memory?
If I run

```<code>string myString = "*.txt";
Print("sizeof(char): " + sizeof(char) + " bytes");
Print("myString.Length * sizeof(char): " + (myString.Length * sizeof(char)) + " bytes");
</code>```

It will print

sizeof(char): 2 bytes

myString.Length * sizeof(char): 10 bytes

But, if I run the code from the first answer to this question:

```<code>myString = "*.txt"
long size = 0;
using (Stream s = new MemoryStream())
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, myString);
    size = s.Length;
}
Print("myString Serialized Size: " + size + " bytes");
</code>```

I get

myString Serialized Size: 29 bytes

Which of these is a more accurate representation of how much space my string is taking up in memory?

答:
Asking about the size (bytes) of a string is complex;

internally, it will be UTF-16, so: twice as many characters (assuming it wasn't created over-sized, which is possible)

but the string object itself has the string length and the object overhead to consider, then there's "padding" etc

if you're talking about size in vanilla binary encodings, then you need to know what Encoding you're discussing; ASCII, UTF-8, UTF-16, etc - plus you need to know whether or not you're including a BOM

the one thing you would not do is run it through BinaryFormatter; BinaryFormatter is a general purpose serializer that includes type metadata, field names, etc; in general, you should almost never use BinaryFormatter ... for anything :)

So: the reason you're getting an unexpected answer is that you're asking the wrong question. For the "in memory" discussion, you're really after the first bullet. It isn't easy to give an exact answer because the size of the object overhead depends on your target platform.

Body:
If I run

string myString = "*.txt";
Print("sizeof(char): " + sizeof(char) + " bytes");
Print("myString.Length * sizeof(char): " + (myString.Length * sizeof(char)) + " bytes");

It will print

sizeof(char): 2 bytes

myString.Length * sizeof(char): 10 bytes

But, if I run the code from the first answer to this question:

myString = "*.txt"
long size = 0;
using (Stream s = new MemoryStream())
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, myString);
    size = s.Length;
}
Print("myString Serialized Size: " + size + " bytes");

I get

myString Serialized Size: 29 bytes

Which of these is a more accurate representation of how much space my string is taking up in memory?


问:
Get the difference of two array of objects with multiple constraints
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */```

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?

答:
Maybe just go through both arrays and add to the result when the element is not found in the result.

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = [];
dbArr.map(cv => {if(res.find(e => e.name === cv.name))return cv; res.push(cv)});
diffArr.map(cv => {if(res.find(e => e.name === cv.name))return cv; res.push(cv)});
```

Body:
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?


问:
Remove portion of XML declarations, encoding="UTF-8" standalone="yes" JAXB
I'm splitting an incoming xml file using JAXB.
I know this seems like a duplicate thread, However

Expected,

<?xml version="1.0"?>

Actual,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I tried using JAXB_FRAGMENT which completely removes the first line

```<code>jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
</code>```

And

```<code>jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
</code>```

with and without Marshaller.JAXB_FRAGMENT

FYI, I'm using StringWriter

```<code>        JAXBContext jaxbContext = JAXBContext.newInstance(ExportDocument.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);//

        //jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        //jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");

        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(employee, sw);
        String xmlContent = sw.toString();

        System.out.println(xmlContent);
</code>```

答:
I was actually looking for the exact same thing and this is what I found
Altering the XML header produced by the JAXB marshaller</p>

Body:
I'm splitting an incoming xml file using JAXB.
I know this seems like a duplicate thread, However

Expected,

<?xml version="1.0"?>

Actual,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I tried using JAXB_FRAGMENT which completely removes the first line

jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

And

jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");

with and without Marshaller.JAXB_FRAGMENT

FYI, I'm using StringWriter

        JAXBContext jaxbContext = JAXBContext.newInstance(ExportDocument.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);//

        //jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        //jaxbMarshaller.setProperty("com.sun.xml.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");

        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(employee, sw);
        String xmlContent = sw.toString();

        System.out.println(xmlContent);


问:
Resize the width of the div in mobile phone
I have two divs. One is 15%, and the other is 76%. I want to hide the 16% div on mobile phones. That is being achieved using this.

```<code>class="navbar hidden-xs"
</code>```

And the code is as follows

```<code>#right {
  top: -1px;
  position: fixed;
  background: blue;
  width: 15%;
}
</code>```

However, when I change the screen size, the box is getting hidden but the space remains there. I want to make the width of the content to 100% in mobile-only. How can I achieve this? My code for the content is as follows:

```<code>#content {
      float: right;
      width: 76%;
}
</code>```

答:
```<code>@media (max-width: 767px) {
  #right {
    display: none;
  }
  #content {
    width: 100%;
    float: none
  }
}
</code>```

Body:
I have two divs. One is 15%, and the other is 76%. I want to hide the 16% div on mobile phones. That is being achieved using this.

class="navbar hidden-xs"

And the code is as follows

#right {
  top: -1px;
  position: fixed;
  background: blue;
  width: 15%;
}

However, when I change the screen size, the box is getting hidden but the space remains there. I want to make the width of the content to 100% in mobile-only. How can I achieve this? My code for the content is as follows:

#content {
      float: right;
      width: 76%;
}


问:
Is there a way to get the .txt file I am creating and writing to with this code to be named after the text in the top left cell of the selected area?
I am very new to VBA and am trying to write a module that creates and writes a .txt file containing the information in the active cells as part of a bigger project to automate reports. The module will loop through, activating specific cells until its finished (but this will be part of a different module). I need the file to be named after the top left cell in the selected range but cannot figure out how to integrate this.

```<code>Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j  As Integer
myFile = Application.DefaultFilePath & "\(Cells(B, 7).Value).txt"
Set rng = Selection

Open myFile For Output As #1
For i = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count

cellValue = rng.Cells(i, j).Value

If j = rng.Columns.Count Then
Print #1, cellValue
Else
    Print #1, cellValue,
End If

    Next j
Next i
Close #1
End Sub
</code>```

I expected Application.DefaultFilePath & "\(Cells(i, j).Value).txt" to name the file after the first cell but instead it names my file (Cells(i, j).Value).txt

答:
Everything in quotes will be treated literally so you need to remove that bit from inside, viz

```<code>myFile = Application.DefaultFilePath & "\" & Cells(7,"B").Value & ".txt"
</code>```

To base on the top left of selection

```<code>myFile = Application.DefaultFilePath & "\" & Selection(1).Value & ".txt"
</code>```

Body:
I am very new to VBA and am trying to write a module that creates and writes a .txt file containing the information in the active cells as part of a bigger project to automate reports. The module will loop through, activating specific cells until its finished (but this will be part of a different module). I need the file to be named after the top left cell in the selected range but cannot figure out how to integrate this.

Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j  As Integer
myFile = Application.DefaultFilePath & "\(Cells(B, 7).Value).txt"
Set rng = Selection

Open myFile For Output As #1
For i = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count

cellValue = rng.Cells(i, j).Value

If j = rng.Columns.Count Then
Print #1, cellValue
Else
    Print #1, cellValue,
End If

    Next j
Next i
Close #1
End Sub

I expected Application.DefaultFilePath & "\(Cells(i, j).Value).txt" to name the file after the first cell but instead it names my file (Cells(i, j).Value).txt

Body:
Everything in quotes will be treated literally so you need to remove that bit from inside, viz

myFile = Application.DefaultFilePath & "\" & Cells(7,"B").Value & ".txt"

To base on the top left of selection

myFile = Application.DefaultFilePath & "\" & Selection(1).Value & ".txt"


问:
Insert if not exists, if exists update
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

```<code> db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });
</code>```

答:
```<code>db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>
   }
)
</code>```

The updateMany() method takes the following parameters:

Filter

The selection criteria for the update. The same query selectors as in the find() method are available.

Specify an empty document { } to update all documents in the collection.

Update

The modifications to apply.

Use Update Operators such as $set, $unset, or $rename.

Upsert

Optional. When true, updateMany() either:

Creates a new document if no documents match the filter. For more details see upsert behavior.
Updates documents that match the filter.
To avoid multiple upserts, ensure that the filter fields are uniquely indexed.

Defaults to false.

```<code>db.users.updateMany(
       {},
       {$set: users},
       {
         upsert: true
       }
    )
</code>```

Title: Insert if not exists, if exists update

Body:
I'm getting usersfrom this API.

https://redmine-mock-api.herokuapp.com/api/v1/users

There are 100 in total (100 different ids). I added them to my mongodb database using mongoose but the problem is that it's always adding (i already have 5000 users (50 times repeated 100 users)

I want to add if the id does not exist or update if it exists.

What am I doing wrong? users is the array of users from the API

 db.collection("users").insertMany(users, function (error, response) {
                        if (error) throw error;
                        console.log("Number of users inserted: " + response.insertedCount);
                        db.close();
                    });

Body:
db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>
   }
)

The updateMany() method takes the following parameters:

Filter

The selection criteria for the update. The same query selectors as in the find() method are available.

Specify an empty document { } to update all documents in the collection.

Update

The modifications to apply.

Use Update Operators such as $set, $unset, or $rename.

Upsert

Optional. When true, updateMany() either:

Creates a new document if no documents match the filter. For more details see upsert behavior.
Updates documents that match the filter.
To avoid multiple upserts, ensure that the filter fields are uniquely indexed.

Defaults to false.

db.users.updateMany(
       {},
       {$set: users},
       {
         upsert: true
       }
    )


问:
Center align li with equal height and fixed width
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

JS Fiddle Link

答:
if you want to keep using the table-layout, you will need to get the container centered itself, the row is always entirely filled.

width is to be set directly to the cell(.boxes) so that you have 1 or 5, it will be the size set and the table(.box-outer) will center itself.

This means you cannot set the table(.box-outer) to width:100% and benefit from the table-layout:fixed; algorythm.
The cells(.boxes) will grow if the content is wider than the width set (this is the table-layout behavior).

the only benefit you get here, is that every boxes will be the same height and most of the time the same width.

Also, table-cell do not accept margin, you need to set border-spacing on the table parent displayed instead.

some fix of your code, keeping the display: table / table-cell , rules could be :

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;/* useless if no width set */
  background-color: #333;
  margin: auto;/* update */
  border-spacing: 0.5vw 0;/* update */
}

.boxes {
  vertical-align: middle;
  /* removed:
  width: 10% !important; ?? this allows 10 boxes ?
  margin-right: 1% !important; :( doesn't work on a cell .
  */
  width: 20vw;/* update  whatever value, it is equal to min-width in this table-layout */
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
</div>
<hr>Your 5 boxes: it breaks on small screen
<hr>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

On the other side, every body tells you about flex, which can be more flexible and also different.

flex can be inbricated to let you have .boxes of same height but also  allow vertical and horizontal centering of their content.(maybe, at this point, you'll be thinking about dropping the display:table method)

here is an example:

.box-outer {
  text-align: center;
  display: flex;
  background-color: #333;
  justify-content:center;
  /* flex-wrap:wrap; *//* to allow boxes to wrap to next line(s) */
}

.boxes {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex: 0 1 16.5%;/* 5 boxes + margins tune this to your needs  */
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  margin: 1% 0.5%;/*tune to your needs, Note: vertical margin/padding in % is calculated from width */
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>5 boxes on small screen breaks too with flex, you may want to allow wrapping ? Less than 5 boxes is to be seen below </p>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div>
<hr>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor </span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
</div></code>```

Usefull tutorial or reminder about the flex model : https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Body:
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

83

    Lorem ipsum dolor sit amet, consectetur adipiscing elit,

7,800
mod tempor incididunt ut labor

65k
ut aliquip

37k
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

£250m
veniam, quis nostrud exercitation ullamco

JS Fiddle Link

Body:
if you want to keep using the table-layout, you will need to get the container centered itself, the row is always entirely filled.

width is to be set directly to the cell(.boxes) so that you have 1 or 5, it will be the size set and the table(.box-outer) will center itself.

This means you cannot set the table(.box-outer) to width:100% and benefit from the table-layout:fixed; algorythm.
The cells(.boxes) will grow if the content is wider than the width set (this is the table-layout behavior).

the only benefit you get here, is that every boxes will be the same height and most of the time the same width.

Also, table-cell do not accept margin, you need to set border-spacing on the table parent displayed instead.

some fix of your code, keeping the display: table / table-cell , rules could be :

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;/* useless if no width set */
  background-color: #333;
  margin: auto;/* update */
  border-spacing: 0.5vw 0;/* update */
}

.boxes {
  vertical-align: middle;
  /* removed:
  width: 10% !important; ?? this allows 10 boxes ?
  margin-right: 1% !important; :( doesn't work on a cell .
  */
  width: 20vw;/* update  whatever value, it is equal to min-width in this table-layout */
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
</div>
<hr>Your 5 boxes: it breaks on small screen
<hr>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">&#163;250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div>

On the other side, every body tells you about flex, which can be more flexible and also different.

flex can be inbricated to let you have .boxes of same height but also  allow vertical and horizontal centering of their content.(maybe, at this point, you'll be thinking about dropping the display:table method)

here is an example:

.box-outer {
  text-align: center;
  display: flex;
  background-color: #333;
  justify-content:center;
  /* flex-wrap:wrap; *//* to allow boxes to wrap to next line(s) */
}

.boxes {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex: 0 1 16.5%;/* 5 boxes + margins tune this to your needs  */
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  margin: 1% 0.5%;/*tune to your needs, Note: vertical margin/padding in % is calculated from width */
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

<p>5 boxes on small screen breaks too with flex, you may want to allow wrapping ? Less than 5 boxes is to be seen below </p>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">&#163;250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div>
<hr>
<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor </span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
</div>

Usefull tutorial or reminder about the flex model : https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
Material-UI drop-down menu causing error in IE11
Unfortunately we have to support IE11.

The following is a snippet of Angular from our app:

```<code><nav class="navbar-menu" fxFill>
    <span class="fill-it"></span>
    <span class="nav-user-wrap" fxFlexAlign="right">
        <button class="nav-user" mat-button [matMenuTriggerFor]="usrmenu">{{ userManager.currentDealer?.name }} <mat-icon class="icon-avatar">person</mat-icon><mat-icon class="icon-arrwdwn">keyboard_arrow_down</mat-icon></button>
        <mat-menu #usrmenu="matMenu" class="userdd mmdd" xPosition="after" yPosition="below" [overlapTrigger]="false">
            <span mat-menu-item [disabled]="true" [disableRipple]="true">{{ userManager.firstName }} {{ userManager.lastName }}</span>
            <mat-divider style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>

            <span mat-menu-item *ngIf="!userManager.isDealerGroupUser" (click)="openSelectDealerGroupDialog()">{{ userManager.dealerGroup?.name }}</span>
            <mat-divider *ngIf="!userManager.isDealerGroupUser" style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>

            <button *ngFor="let dealer of userManager.dealers" (click)="userManager.setCurrentDealer(dealer.id)" mat-menu-item>{{ dealer.name }} <span *ngIf="dealer.id === userManager.defaultDealer?.id">(Default)</span></button>

            <mat-divider style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>
            <!-- <button mat-menu-item>My Account</button>
            <button mat-menu-item>Settings</button> -->
            <button mat-menu-item (click)="logOut()">Logout</button>
        </mat-menu>
    </span>
</nav>
</code>```

Pretty standard drop-down menu, but in IE11 clicking the button gives the following exception:

```<code>Unable to get property 'opacity' of undefined or null reference
</code>```

I'm pulling my hair out trying to work out why.
Does IE11 do some kind of pseudo-script thing in the background to set the CSS or something? No idea.

All help appreciated!

答: Angular docs say that you only need the 'web-animations-js' polyfill for IE if you use the AnimationBuilder, but my project doesn't use AnimationBuilder and I get this error message.  There's a possibility one of the libraries I'm using does. But I only started getting this error after I upgraded to Angular 8.</p>

Body:
Unfortunately we have to support IE11.

The following is a snippet of Angular from our app:

        <button class="nav-user" mat-button [matMenuTriggerFor]="usrmenu">{{ userManager.currentDealer?.name }} <mat-icon class="icon-avatar">person</mat-icon><mat-icon class="icon-arrwdwn">keyboard_arrow_down</mat-icon></button>
        <mat-menu #usrmenu="matMenu" class="userdd mmdd" xPosition="after" yPosition="below" [overlapTrigger]="false">
            {{ userManager.firstName }} {{ userManager.lastName }}
            <mat-divider style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>

            {{ userManager.dealerGroup?.name }}
            <mat-divider *ngIf="!userManager.isDealerGroupUser" style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>

            <button *ngFor="let dealer of userManager.dealers" (click)="userManager.setCurrentDealer(dealer.id)" mat-menu-item>{{ dealer.name }} (Default)</button>

            <mat-divider style="border-color: rgba(255,255,255,0.8); margin: 0 16px;"></mat-divider>

            <button mat-menu-item (click)="logOut()">Logout</button>
        </mat-menu>

Pretty standard drop-down menu, but in IE11 clicking the button gives the following exception:

Unable to get property 'opacity' of undefined or null reference

I'm pulling my hair out trying to work out why.
Does IE11 do some kind of pseudo-script thing in the background to set the CSS or something? No idea.

All help appreciated!


问:
How do I create hover text that copies when you select the base text?
Right now i'm currently using a simple bootstrap tooltip when I create my tables with jQuery, but i wanted a specific functionality that the bootstrap tooltip doesn't offer.

I want to be able to copy the base text and get something like "base text - hover text"; because i need both values when i paste it into excel, simply creating two columns for this data makes the table slightly too big, so i'm looking for another solution.

base text
```

```$(document).ready(function(){
   $("#query").click(function() {

    $.ajax({
            method: "GET",
            url: $('#dns').val()
        })
        .done(function(data) {
            if (data.Success == true) {
//this is where my table with the tooltips are created
                parseResults(data.Results);
            } else {
                $('.dnsError').show();
            }

            $('[data-toggle="tooltip"]').on('copy', function(event) {
                event.preventDefault();
                console.log(this.title);
                copyToClipboard(this.innerText + " - " + this.getAttribute('data-original-title'));
              }).tooltip();
        })
        });
});

function copyToClipboard(text) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val(text).select();
      document.execCommand("copy");
      $temp.remove();
    }
```

答:
I used a slightly modified version of this to copy the text to the clipboard.

You have to get the data-original-title instead of the title since Bootstrap changes that.

function copyToClipboard(text) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();
}

$(document).ready(function() {
  $('[data-toggle="tooltip"]').on('copy', function(event) {
    event.preventDefault();
    console.log(this.title);
    copyToClipboard(this.innerText + " - " + this.getAttribute('data-original-title'));
  }).tooltip();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/popper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

base text</code>```

Body:
Right now i'm currently using a simple bootstrap tooltip when I create my tables with jQuery, but i wanted a specific functionality that the bootstrap tooltip doesn't offer.

I want to be able to copy the base text and get something like "base text - hover text"; because i need both values when i paste it into excel, simply creating two columns for this data makes the table slightly too big, so i'm looking for another solution.

base text

$(document).ready(function(){
   $("#query").click(function() {

    $.ajax({
            method: "GET",
            url: $('#dns').val()
        })
        .done(function(data) {
            if (data.Success == true) {
//this is where my table with the tooltips are created
                parseResults(data.Results);
            } else {
                $('.dnsError').show();
            }

            $('[data-toggle="tooltip"]').on('copy', function(event) {
                event.preventDefault();
                console.log(this.title);
                copyToClipboard(this.innerText + " - " + this.getAttribute('data-original-title'));
              }).tooltip();
        })
        });
});

function copyToClipboard(text) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val(text).select();
      document.execCommand("copy");
      $temp.remove();
    }

Body:
I used a slightly modified version of this to copy the text to the clipboard.

You have to get the data-original-title instead of the title since Bootstrap changes that.

function copyToClipboard(text) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(text).select();
  document.execCommand("copy");
  $temp.remove();
}

$(document).ready(function() {
  $('[data-toggle="tooltip"]').on('copy', function(event) {
    event.preventDefault();
    console.log(this.title);
    copyToClipboard(this.innerText + " - " + this.getAttribute('data-original-title'));
  }).tooltip();
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/popper.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

<a href="#" data-toggle="tooltip" title="hover text">base text</a>


问:
Changing current user timezone based on server UTC offset and user UTC offset
im writing a twitter web service in php. When a user signs in, i receive this node:

```<code><utc_offset>-18000</utc_offset>
</code>```

I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.

So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset

BTW, this is how i'm getting the server UTC offset value:

```<code>$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
</code>```

Any ideas? Thanks!

答:
The date_default_timezone... functions expect a string giving something like "Africa/Luanda" or whatever.

I suggest programmatically searching through the timezone database for a matching offset.  If I recall correctly, those are in minutes from UTC, so you should divide the offset you are given by 60.

Body:
im writing a twitter web service in php. When a user signs in, i receive this node:

<utc_offset>-18000</utc_offset>

I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.

So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset

BTW, this is how i'm getting the server UTC offset value:

$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);

Any ideas? Thanks!


问:
SQL Query to Laravel Eloquent
I have this query below and i want to convert it to Laravel Eloquent. I have tried with no success.

```<code>select A.client_id, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By max(A.purchase_date) desc
</code>```

I tried this but i get the oldest record from each user.

```<code>$this->data['expiringSubscriptions'] = Gym::select('first_name', 'last_name', 'gym_client_purchases.*')
->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
->groupBy('client_id')
->orderBy('gym_client_purchases.purchase_date', 'desc')
->get();
</code>```

Could anyone guide me to convert my queries?

Thank you.

答:
You didn't mention any models, so here it is using the query builder.

```<code>$results = DB::table('gym_client_purchases gcp')
    ->selectRaw('gcp.client_id, MAX(gcp.purchase_date) AS max_purchase_date')
    ->leftJoin('gym_clients gc', 'gc.id', '=', 'gcp.client_id')
    ->groupBy('gcp.client_id')
    ->orderBy('max_purchase_date', 'desc');
</code>```

Haven't run it - but that should be basically it.

Title: SQL Query to Laravel Eloquent

Body:
I have this query below and i want to convert it to Laravel Eloquent. I have tried with no success.

select A.client_id, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By max(A.purchase_date) desc

I tried this but i get the oldest record from each user.

$this->data['expiringSubscriptions'] = Gym::select('first_name', 'last_name', 'gym_client_purchases.*')
->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
->groupBy('client_id')
->orderBy('gym_client_purchases.purchase_date', 'desc')
->get();

Could anyone guide me to convert my queries?

Thank you.

Body:
You didn't mention any models, so here it is using the query builder.

$results = DB::table('gym_client_purchases gcp')
    ->selectRaw('gcp.client_id, MAX(gcp.purchase_date) AS max_purchase_date')
    ->leftJoin('gym_clients gc', 'gc.id', '=', 'gcp.client_id')
    ->groupBy('gcp.client_id')
    ->orderBy('max_purchase_date', 'desc');

Haven't run it - but that should be basically it.


问:
Persist dropzone files in Session storage
I am trying to temporary persist some form data in the session storage and can't find a way to properly store enqueued (not uploaded) dropzone.js files.

Accoring to documentation, I already tried the following:

storing:

```<code>dropzone.getQueuedFiles().forEach(function(file, index) {
      sessionStorage.setItem("picture_" + index, file.dataURL);
      sessionStorage.setItem("picture_" + index + "_name", file.name);
      sessionStorage.setItem("picture_" + index + "_type", file.type);
    })
</code>```

retrieving after DOM rendered:

```<code>let restoredFiles = 0;
  for(let i =0; i < dropzone.options.maxFiles; i++) {
    restoredFiles++;
    if(sessionStorage.getItem('picture_' + i) !== null){
      let data_url = sessionStorage.getItem('picture_' + i);
      let name = sessionStorage.getItem('picture_' + i + '_name');
      let type = sessionStorage.getItem('picture_' + i + '_type');
      let mockFile = {dataURL: data_url, name: name, type: type};

      dropzone.emit("addedfile", mockFile);
      dropzone.emit("thumbnail", mockFile);
      dropzone.createThumbnailFromUrl(mockFile);
      dropzone.emit("complete", mockFile);
    }
  }
dropzone.options.maxFiles = dropzone.options.maxFiles - restoredFiles;
</code>```

This works fine for adding the file to Dropzone, but there is no way to show a thumbnail. Neither one of the two thumbnail commands acutally produces a thumbnail, and without an actual URL, I can't really use dropzone.createThumbnailFromUrl.

Is there a better way?

答:
It took a good while, but in the end, i solved it like this:

storing:

```<code>var images = [];
dropzone.getQueuedFiles().forEach(function (file) {
  let image = {
    dataURL: file.dataURL,
    name: file.name,
    type: file.type,
    size: file.size,
  };
  images.push(image);
});
sessionStorage.setItem("images", JSON.stringify(pictures));
</code>```

retrieving:

```<code>var images = JSON.parse(sessionStorage.getItem('images'));
images.forEach(function(image) {
  dropzone.files.push(image);
  dropzone.emit("addedfile", image);
  dropzone.emit("thumbnail", image, image.dataURL);
  dropzone.emit("complete", image);
});
dropzone.options.maxFiles = dropzone.options.maxFiles - images.length;
</code>```

Body:
I am trying to temporary persist some form data in the session storage and can't find a way to properly store enqueued (not uploaded) dropzone.js files.

Accoring to documentation, I already tried the following:

storing:

dropzone.getQueuedFiles().forEach(function(file, index) {
      sessionStorage.setItem("picture_" + index, file.dataURL);
      sessionStorage.setItem("picture_" + index + "_name", file.name);
      sessionStorage.setItem("picture_" + index + "_type", file.type);
    })

retrieving after DOM rendered:

let restoredFiles = 0;
  for(let i =0; i < dropzone.options.maxFiles; i++) {
    restoredFiles++;
    if(sessionStorage.getItem('picture_' + i) !== null){
      let data_url = sessionStorage.getItem('picture_' + i);
      let name = sessionStorage.getItem('picture_' + i + '_name');
      let type = sessionStorage.getItem('picture_' + i + '_type');
      let mockFile = {dataURL: data_url, name: name, type: type};

      dropzone.emit("addedfile", mockFile);
      dropzone.emit("thumbnail", mockFile);
      dropzone.createThumbnailFromUrl(mockFile);
      dropzone.emit("complete", mockFile);
    }
  }
dropzone.options.maxFiles = dropzone.options.maxFiles - restoredFiles;

This works fine for adding the file to Dropzone, but there is no way to show a thumbnail. Neither one of the two thumbnail commands acutally produces a thumbnail, and without an actual URL, I can't really use dropzone.createThumbnailFromUrl.

Is there a better way?

Body:
It took a good while, but in the end, i solved it like this:

storing:

var images = [];
dropzone.getQueuedFiles().forEach(function (file) {
  let image = {
    dataURL: file.dataURL,
    name: file.name,
    type: file.type,
    size: file.size,
  };
  images.push(image);
});
sessionStorage.setItem("images", JSON.stringify(pictures));

retrieving:

var images = JSON.parse(sessionStorage.getItem('images'));
images.forEach(function(image) {
  dropzone.files.push(image);
  dropzone.emit("addedfile", image);
  dropzone.emit("thumbnail", image, image.dataURL);
  dropzone.emit("complete", image);
});
dropzone.options.maxFiles = dropzone.options.maxFiles - images.length;


问:
Check all checkboxes at all pages of jQuery DataTable (server side processing)
I'm using jQuery DataTables with server side processing enabled and i'm facing the issue with checking all checkboxes at all pages. Below is my code, so help me with solution.
This worked only for current page.

```<code>$(document).on("ifClicked","#selecAllRec",function(event){
    if(event.currentTarget.checked){
        proCustomerListTbl.api().column(0).nodes().to$().each(function(index){
            $(this).find('.proCustChk').iCheck("uncheck");
        });
    } else {
        proCustomerListTbl.api().column(0).nodes().to$().each(function(index){
            $(this).find('.proCustChk').iCheck("check");
        });
    }
});
</code>```

答:
You may have global variable that will store whether all entries should be considered checked or not:

```<code>var allChecked = false;
</code>```

That value can be switched by your major checkbox (I have used plain JS addEventListener() instead of jQuery .on() for certain extended options):

```<code>document.getElementById('example').addEventListener('click', event => {
  if($(event.target).is('thead [type="checkbox"]')){
    allChecked = $(event.target).prop('checked');
    $('table').DataTable().draw(false);
    event.stopPropagation();
  }
}, true);
</code>```

And you may render your rows checkboxes according to allChecked current value:

```<code>  drawCallback: function(){
    $(this.api().column(0).header()).html('<input type="checkbox"></input>');
    [...$('#example [type="checkbox"]')].forEach(checkbox => $(checkbox).prop('checked', allChecked));
  }
</code>```

That will not allow you, by any means, to mark  current data rows with respect to current ordering/filtering, but you may use allChecked variable to restore that selection server side.

Following snippet demonstrates that approach:

//mimic source data
const srcData = [
  {name: 'apple', cat: 'fruit'},
  {name: 'pear', cat: 'fruit'},
  {name: 'carrot', cat: 'vegie'},
  {name: 'cabbage', cat: 'vegie'},
  {name: 'potato', cat: 'vegie'}
];
//initialize global 'allChecked' variable
var allChecked = false;

//initialize datatables
$('table').DataTable({
  dom: 'tp',
  data: srcData,
  pageLength: 3,
  columns: [null, 'name', 'cat'].map(header => ({title: (header || ''), data: header})),
  columnDefs: [{
    targets: 0,
    render: () => `<input type="checkbox"></input>`
  }],
  drawCallback: function(){
    $(this.api().column(0).header()).html('<input type="checkbox"></input>');
    [...$('#example [type="checkbox"]')].forEach(checkbox => $(checkbox).prop('checked', allChecked));
  }
});

//header checkbox click handler
document.getElementById('example').addEventListener('click', event => {
  if($(event.target).is('thead [type="checkbox"]')){
    //assign global variable to current state
    allChecked = $(event.target).prop('checked');
    //trigger table re-draw
    $('table').DataTable().draw(false);
    //prevent click from propagation and swapping column ordering
    event.stopPropagation();
  }
}, true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="example"></table>
</body>
</html></code>```

Body:
I'm using jQuery DataTables with server side processing enabled and i'm facing the issue with checking all checkboxes at all pages. Below is my code, so help me with solution.
This worked only for current page.

$(document).on("ifClicked","#selecAllRec",function(event){
    if(event.currentTarget.checked){
        proCustomerListTbl.api().column(0).nodes().to$().each(function(index){
            $(this).find('.proCustChk').iCheck("uncheck");
        });
    } else {
        proCustomerListTbl.api().column(0).nodes().to$().each(function(index){
            $(this).find('.proCustChk').iCheck("check");
        });
    }
});

Body:
You may have global variable that will store whether all entries should be considered checked or not:

var allChecked = false;

That value can be switched by your major checkbox (I have used plain JS addEventListener() instead of jQuery .on() for certain extended options):

document.getElementById('example').addEventListener('click', event => {
  if($(event.target).is('thead [type="checkbox"]')){
    allChecked = $(event.target).prop('checked');
    $('table').DataTable().draw(false);
    event.stopPropagation();
  }
}, true);

And you may render your rows checkboxes according to allChecked current value:

  drawCallback: function(){
    $(this.api().column(0).header()).html('<input type="checkbox"></input>');
    [...$('#example [type="checkbox"]')].forEach(checkbox => $(checkbox).prop('checked', allChecked));
  }

That will not allow you, by any means, to mark  current data rows with respect to current ordering/filtering, but you may use allChecked variable to restore that selection server side.

Following snippet demonstrates that approach:

//mimic source data
const srcData = [
  {name: 'apple', cat: 'fruit'},
  {name: 'pear', cat: 'fruit'},
  {name: 'carrot', cat: 'vegie'},
  {name: 'cabbage', cat: 'vegie'},
  {name: 'potato', cat: 'vegie'}
];
//initialize global 'allChecked' variable
var allChecked = false;

//initialize datatables
$('table').DataTable({
  dom: 'tp',
  data: srcData,
  pageLength: 3,
  columns: [null, 'name', 'cat'].map(header => ({title: (header || ''), data: header})),
  columnDefs: [{
    targets: 0,
    render: () => `<input type="checkbox"></input>`
  }],
  drawCallback: function(){
    $(this.api().column(0).header()).html('<input type="checkbox"></input>');
    [...$('#example [type="checkbox"]')].forEach(checkbox => $(checkbox).prop('checked', allChecked));
  }
});

//header checkbox click handler
document.getElementById('example').addEventListener('click', event => {
  if($(event.target).is('thead [type="checkbox"]')){
    //assign global variable to current state
    allChecked = $(event.target).prop('checked');
    //trigger table re-draw
    $('table').DataTable().draw(false);
    //prevent click from propagation and swapping column ordering
    event.stopPropagation();
  }
}, true);

<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="example"></table>
</body>
</html>


问:
Return all node values with their parents in PHP multidimensional array
I have a simple multidimensional array like this:
`

```<code>$array= [
    'A' => [
        'B' => ['D', 'E', 'F'],
    'C' => 'G',
    ],
];
</code>```

I need to return all node values with their parents. So I need an output like:

```<code>P[A] = 0;
P[B] = A;
P[D] = B;
P[E] = B;
P[F] = B;
P[C] = A;
P[G] = C;
</code>```

I've tried some functions like array_search(), array_walk_recursive and so on, but I couldn't apply these functions to my situation.
Thanks very much for any help!

答:
```<code>function recursive($arr, $parentKey, &$flattened) {
    foreach ($arr as $key => $item) {
        if (is_array($item)) {
            recursive($item, $key, $flattened);
            $flattened[$key] = $parentKey;
        } else {
            if (is_numeric($key)) {
                $flattened[$item] = $parentKey;
            } else {
                $flattened[$item] = $key;
                $flattened[$key] = $parentKey;
            }
        }
    }
}

$inputArray= [
    'A' => [
        'B' => ['D', 'E', 'F'],
        'C' => 'G'
    ]
];

$result = [];
recursive($inputArray, 0, $result);
var_dump($result); // array(7) { ["D"]=> string(1) "B" ["E"]=> string(1) "B" ["F"]=> string(1) "B" ["B"]=> string(1) "A" ["G"]=> string(1) "C" ["C"]=> string(1) "A" ["A"]=> int(0) }
</code>```

Body:
I have a simple multidimensional array like this:
`

$array= [
    'A' => [
        'B' => ['D', 'E', 'F'],
    'C' => 'G',
    ],
];

I need to return all node values with their parents. So I need an output like:

P[A] = 0;
P[B] = A;
P[D] = B;
P[E] = B;
P[F] = B;
P[C] = A;
P[G] = C;

I've tried some functions like array_search(), array_walk_recursive and so on, but I couldn't apply these functions to my situation.
Thanks very much for any help!


问:
Is it possible to register the rest endpoints in MarkLogic Query console
Is it possible to register the rest endpoints in MarkLogic Query Console using XQuery?</p>

答: I'm not sure what you mean by "register". Are you talking about creating a new REST API extension? If so, yes, you can, using the xdmp:http-* functions, as @ehennum noted. However, taking that approach will lead to one-off solutions and I wouldn't recommend it. You'd be much better off using ml-gradle, a tool specifically for deploying MarkLogic code and configuration. </p>