问:
Replace bookmarks content without removing the bookmark
I want to replace the text content of bookmarks without loosing the bookmark.

```<code>foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}
</code>```

I tried to set the new Range of the bookmark before the Text setting but I still have the same problem.

I also tried to re-add the bookmark with document.Bookmarks.Add(name, range); but I can't create an instance of range.

答:
With the above approach, you still lose the bookmark before it is added back in. If you really need to preserve the bookmark, I find that you can create an inner bookmark that wraps around the text (a bookmark within bookmark). After having the inner bookmark, you simply need to do:

```<code>innerBookmark.Range.Text = newText;
</code>```

After the text replacing, the inner bookmark is gone and the outer bookmark is preserved.  No need to set range.End.

You can create the inner bookmark manually or programmatically depending on your situation.

Body:
I want to replace the text content of bookmarks without loosing the bookmark.

foreach(Bookmark b in document.Bookmarks)
{
    b.Range.Text = "newtext";  // text is set in document but bookmark is gone
}

I tried to set the new Range of the bookmark before the Text setting but I still have the same problem.

I also tried to re-add the bookmark with document.Bookmarks.Add(name, range); but I can't create an instance of range.

Body:
With the above approach, you still lose the bookmark before it is added back in. If you really need to preserve the bookmark, I find that you can create an inner bookmark that wraps around the text (a bookmark within bookmark). After having the inner bookmark, you simply need to do:

innerBookmark.Range.Text = newText;

After the text replacing, the inner bookmark is gone and the outer bookmark is preserved.  No need to set range.End.

You can create the inner bookmark manually or programmatically depending on your situation.


来源: stackexchange

问:
How to merge two data frames together with no common ID?
I am trying to run the sample code from here:

https://www.dataquest.io/blog/k-nearest-neighbors-in-python/

The sample data is available here:

https://www.dropbox.com/s/b3nv38jjo5dxcl6/nba_2013.csv?dl=0

I'm getting an error here:

lebron_normalized = nba_normalized[nba["player"] == "LeBron James"]

Error: KeyError: 'player'

When I look at the data set, I see that nba_normalized doesn't have a field named player because nba_normalized is only numeric. How can I find the normalized vector for Lebron James, and based on that, find euclidean_distances?

答:
I ran the code, and it worked for me (had to change sort to sort_values because newer version of Pandas).

The following statement is not true, and if so, then you did something wrong.

nba_normalized is only numeric

When you do:

```<code>nba_normalized = (nba_numeric - nba_numeric.mean()) / nba_numeric.std()
</code>```

nba_numeric is a pandas dataframe. When we do operations on dataframes, we will be subtracting and dividing the scalars for ALL columns of the data.

ContentLicense: CC BY-SA 4.0

Body:
I ran the code, and it worked for me (had to change sort to sort_values because newer version of Pandas).

The following statement is not true, and if so, then you did something wrong.

nba_normalized is only numeric

When you do:

nba_normalized = (nba_numeric - nba_numeric.mean()) / nba_numeric.std()

nba_numeric is a pandas dataframe. When we do operations on dataframes, we will be subtracting and dividing the scalars for ALL columns of the data.


问:
React Native: Module AppRegistry is not a registered callable module (calling runApplication)
I am trying to boot up a React Native 0.53.3 app with React 16.2.0 using simulator from Xcode 10.1 on High Sierra.

I previously had some issues that I have since resolved just to get the build to succeed:
npm-shrinkwrap.json: Could not install from "node_modules/react-navigation/react-native-tab-view@github:react-navigation/react-native-tab-view

React Native: ":CFBundleIdentifier", Does Not Exist

Now all build succeed even though I continue to get the cfbundleridentifier error:

```<code>Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/NFIBEngage.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist
</code>```

Even in Metro Bundler it succeeds:

```<code>Metro Bundler ready.

Loading dependency graph, done.
 BUNDLE  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.

 BUNDLE  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1/1), done.

 DELTA  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.

 MAP  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.
</code>```

So I was wondering why my app when launched in simulator would stay stuck in the splashscreen, that usually only happens when an index.ios.js has failed. So I looked at http://localhost:8081/debugger-ui/ and sure enough I saw the following errors:

```<code>Module AppRegistry is not a registered callable module (calling runApplication)

Unhandled JS Exception: Cannot read property 'invocationEventNone' of undefined

Unhandled JS Exception: Module AppRegistry is not a registered callable module (calling runApplication)
</code>```

I don't know where its getting invocationEventNone from, its not anything written in the codebase, I checked.

```<code>As far as the `AppRegistry` module, it appears to look fine:

import {AppRegistry} from 'react-native';
import KeyboardManager from 'react-native-keyboard-manager';
import NFIBEngage from './App';

KeyboardManager.setToolbarPreviousNextButtonEnable(true);

AppRegistry.registerComponent('NFIBEngage', () => NFIBEngage);
</code>```

Has anyone experienced something like this running versions similar to what I am running? What should I be investigating? How to resolve this?

I followed every solution in here:
Module AppRegistry is not registered callable module (calling runApplication)

There was nothing in here that could help:
React Native Module AppRegistry is not a registered callable module

This was not relevant:
React Native(iOS) Module AppRegistry is not a registered callable module (calling runApplication)

Not relevant:
React native AppRegistry is not a callable module

I then tried following the solution offered by iDevAmit here:
React-Native: Module AppRegistry is not a registered callable module

but it appears my iOS which is what I am interested in running right now, is already linked according to this output:

```<code>rnpm-install info Platform 'ios' module appcenter is already linked
rnpm-install info Linking appcenter android dependency
rnpm-install info Platform 'android' module appcenter has been successfully linked
iOS App Secret is '00000000-0000-0000-0000-000000000000' set in ios/NFIBEngage/AppCenter-Config.plist
Added code to initialize iOS AppCenter SDK in ios/NFIBEngage/AppDelegate.m

            Could not install dependencies using CocoaPods.
            Please refer to the documentation to install dependencies manually.

            Error Reason - Could not find "pod" command. Is CocoaPods installed?

Configuring AppCenter Analytics
rnpm-install info Platform 'ios' module appcenter-analytics is already linked
? For the Android app, should user tracking be enabled automatical
ly? (Use arrow keys)
❯ Enable Automatically
  Enable in JavaScript iOS App Secret is '00000000-0000-0000-0000-000000000000' set in ios/NFIBEngage/AppCenter-Config.plist
? For the iOS app, should user tracking be enabled automatically?
(Use arrow keys)
❯ Enable Automatically
  Enable in JavaScript
</code>```

I did a Ctrl + C to get out and I do not know if the CocoaPods message is related as I have never used it. One time I tried a pod install and zsh could not find pod as a command.

Omar's solution does not work as it gave me Duplicate declaration "appName"

None of the other recommendations were applicable and upgrading React Native is not an option for this project.

In my Xcode 10.1 I have the current configuration inside of Project Settings -> Advanced button:

In this post:
React Native IOS Build CFBundleIdentifier Does not Exist

I already have what SUMIT and priyanga recommended.

答:
What resolved this error was by removing the Instabug library and code from App.js file:

```<code>export default class appName extends PureComponent {
  constructor() {
    super();
    this._startSentry();
    // if (Platform.OS === "ios") {
    //   const key = base === "prod" ? env.instabug.prod : env.instabug.beta;
    //   Instabug.startWithToken(key, Instabug.invocationEvent.twoFingersSwipe);
    // }
    // Instabug.setIntroMessageEnabled(false);
    // appcenter.trackAppOpened();
  }
</code>```

as I was also getting invocationEvent undefined along with that AppRegistry error.

Body:
I am trying to boot up a React Native 0.53.3 app with React 16.2.0 using simulator from Xcode 10.1 on High Sierra.

I previously had some issues that I have since resolved just to get the build to succeed:
npm-shrinkwrap.json: Could not install from "node_modules/react-navigation/react-native-tab-view@github:react-navigation/react-native-tab-view

React Native: ":CFBundleIdentifier", Does Not Exist

Now all build succeed even though I continue to get the cfbundleridentifier error:

Check dependencies

** BUILD SUCCEEDED **

Installing build/Build/Products/Debug-iphonesimulator/NFIBEngage.app
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier build/Build/Products/Debug-iphonesimulator/NFIBEngage.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

Even in Metro Bundler it succeeds:

Metro Bundler ready.

Loading dependency graph, done.
 BUNDLE  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.

 BUNDLE  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1/1), done.

 DELTA  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.

 MAP  [ios, dev] ./index.ios.js ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 100.0% (1667/1667), done.

So I was wondering why my app when launched in simulator would stay stuck in the splashscreen, that usually only happens when an index.ios.js has failed. So I looked at http://localhost:8081/debugger-ui/ and sure enough I saw the following errors:

Module AppRegistry is not a registered callable module (calling runApplication)

Unhandled JS Exception: Cannot read property 'invocationEventNone' of undefined

Unhandled JS Exception: Module AppRegistry is not a registered callable module (calling runApplication)

I don't know where its getting invocationEventNone from, its not anything written in the codebase, I checked.

As far as the `AppRegistry` module, it appears to look fine:

import {AppRegistry} from 'react-native';
import KeyboardManager from 'react-native-keyboard-manager';
import NFIBEngage from './App';

KeyboardManager.setToolbarPreviousNextButtonEnable(true);

AppRegistry.registerComponent('NFIBEngage', () => NFIBEngage);

Has anyone experienced something like this running versions similar to what I am running? What should I be investigating? How to resolve this?

I followed every solution in here:
Module AppRegistry is not registered callable module (calling runApplication)

There was nothing in here that could help:
React Native Module AppRegistry is not a registered callable module

This was not relevant:
React Native(iOS) Module AppRegistry is not a registered callable module (calling runApplication)

Not relevant:
React native AppRegistry is not a callable module

I then tried following the solution offered by iDevAmit here:
React-Native: Module AppRegistry is not a registered callable module

but it appears my iOS which is what I am interested in running right now, is already linked according to this output:

rnpm-install info Platform 'ios' module appcenter is already linked
rnpm-install info Linking appcenter android dependency
rnpm-install info Platform 'android' module appcenter has been successfully linked
iOS App Secret is '00000000-0000-0000-0000-000000000000' set in ios/NFIBEngage/AppCenter-Config.plist
Added code to initialize iOS AppCenter SDK in ios/NFIBEngage/AppDelegate.m

            Could not install dependencies using CocoaPods.
            Please refer to the documentation to install dependencies manually.

            Error Reason - Could not find "pod" command. Is CocoaPods installed?

Configuring AppCenter Analytics
rnpm-install info Platform 'ios' module appcenter-analytics is already linked
? For the Android app, should user tracking be enabled automatical
ly? (Use arrow keys)
❯ Enable Automatically
  Enable in JavaScript iOS App Secret is '00000000-0000-0000-0000-000000000000' set in ios/NFIBEngage/AppCenter-Config.plist
? For the iOS app, should user tracking be enabled automatically?
(Use arrow keys)
❯ Enable Automatically
  Enable in JavaScript

I did a Ctrl + C to get out and I do not know if the CocoaPods message is related as I have never used it. One time I tried a pod install and zsh could not find pod as a command.

Omar's solution does not work as it gave me Duplicate declaration "appName"

None of the other recommendations were applicable and upgrading React Native is not an option for this project.

In my Xcode 10.1 I have the current configuration inside of Project Settings -> Advanced button:

In this post:
React Native IOS Build CFBundleIdentifier Does not Exist

I already have what SUMIT and priyanga recommended.

Body:
What resolved this error was by removing the Instabug library and code from App.js file:

export default class appName extends PureComponent {
  constructor() {
    super();
    this._startSentry();
    // if (Platform.OS === "ios") {
    //   const key = base === "prod" ? env.instabug.prod : env.instabug.beta;
    //   Instabug.startWithToken(key, Instabug.invocationEvent.twoFingersSwipe);
    // }
    // Instabug.setIntroMessageEnabled(false);
    // appcenter.trackAppOpened();
  }

as I was also getting invocationEvent undefined along with that AppRegistry error.


问:
error: groovy.lang.MissingPropertyException No such property: sql for class: Script9
I need to compare two values in data format

```<code>import groovy.sql.*
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( "oracle.jdbc.driver.OracleDriver" )

def messageId1 = context.expand( '${#Project#Id1}' )
def messageId2 = context.expand( '${#Project#Id2}' )

def first = sql.firstRow("select timestamp from table where Messageid = '"+messageId1+"'")
def second = sql.firstRow("select timestamp from table where Messageid = '"+messageId2+"'")

assert first <  second, 'OK'
</code>```

I get following error:

error: groovy.lang.MissingPropertyException No such property: sql for class: Script9

答:
I had the same issue and the mistake that I made is, I didn't create a SQL Instance...So  this would help you</p>

```<code>def DBurl = '<Your database URL>'
def DBuser = '<Database user name>'
def DBpassword = '<Database Password>'
def DBdriver = '< Your database driver>'
def sql = Sql.newInstance(DBurl, DBuser, DBpassword, DBdriver)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to compare two values in data format

import groovy.sql.*
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( "oracle.jdbc.driver.OracleDriver" )

def messageId1 = context.expand( '${#Project#Id1}' )
def messageId2 = context.expand( '${#Project#Id2}' )

def first = sql.firstRow("select timestamp from table where Messageid = '"+messageId1+"'")
def second = sql.firstRow("select timestamp from table where Messageid = '"+messageId2+"'")

assert first <  second, 'OK'

I get following error:

error: groovy.lang.MissingPropertyException No such property: sql for class: Script9

Body:
I had the same issue and the mistake that I made is, I didn't create a SQL Instance...So  this would help you

def DBurl = '<Your database URL>'
def DBuser = '<Database user name>'
def DBpassword = '<Database Password>'
def DBdriver = '< Your database driver>'
def sql = Sql.newInstance(DBurl, DBuser, DBpassword, DBdriver)


问:
How to fix for-loop output in python
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

```<code>    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)
</code>```

My expected result is:

```<code>{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

however I am getting this output:

```<code>{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

答:
```<code>for ips in multi_ip_addr:
    pass
</code>```

As this loop executes, ips takes on the value of each item in multi_ip_addr.  When the loop ends, ips retains the value of the last item.

In the next loop, you never change the value of ips, so it has the same value every time.

Title: How to fix for-loop output in python

Body:
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)

My expected result is:

{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}

however I am getting this output:

{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}

Body:
for ips in multi_ip_addr:
    pass

As this loop executes, ips takes on the value of each item in multi_ip_addr.  When the loop ends, ips retains the value of the last item.

In the next loop, you never change the value of ips, so it has the same value every time.


问:
Is declare new property in class extension a bad practice in Objective-C?
One strong advantage of class extension is that with class extension you can declare a readonly property in the header file and override this property in class extension as readwrite property. Like below :

```<code>//SomeClass.h

@interface SomeClass : NSObject
{
    NSInteger someInt;   //with modern runtime you can omit this line
}
@property (readonly) NSInteger someInt;
@end

//SomeClass.m
@interface SomeClass ()
@property (readwrite) NSInteger someInt;
@end

@implementation SomeClass
@synthesize someInt;
@end
</code>```

But if you use a modern runtime ,you can also declare a totally new property in the class extension (which also generate an iVar for that property if there isn't).

```<code>//SomeClass.h

@interface SomeClass : NSObject
{
}
@end

//SomeClass.m
@interface SomeClass ()
@property (readwrite) NSInteger someInt;
@end

@implementation SomeClass
@synthesize someInt;
@end
</code>```

Here's my question : I think declare a totally new property in class extention is somehow has some side effects. Because class extension my not be in the header file and someone else who subclass the class may not know about that "secret property". And if he declare a property with the same name of that "secret property". And this new property's getter and setter method will override the super class's. Isn't this a problem?And why would modern runtime allow such thing happen?

EDIT I posted another question about this topic , please check it out:
The risk of declare new propery in class extension (Ojbective-C) , how to solve it?

答:
I don't think it's bad practice to declare a new property in a class extension. I do this with some frequency. The only reason to include the readonly property in the header in the first place is to allow other classes to get the value, while only you are allowed to modify it. Quite often, that ivar should be of no concern to other classes, and is an implementation detail only. As such, it has no place in the header file.

Implementing this ivar as a private property (a new property only declared in the Class Extension) is still useful, because of the convenient memory management boilerplate code it can abstract for you. Unfortunately, name collisions are just a fact of life in Objective C. Apple lays out some pretty clear naming conventions for you to follow (or not follow) to prevent collisions with their method names. If you're worried about collisions with the getters and setters you've invisibly created with that private property, just adopt and obsessively follow some naming convention for those private property names that you only ever use when implementing a private property. That's the best you're going to do with Objective C, but I personally think the benefits outweigh the risks.

Body:
One strong advantage of class extension is that with class extension you can declare a readonly property in the header file and override this property in class extension as readwrite property. Like below :

//SomeClass.h

@interface SomeClass : NSObject
{
    NSInteger someInt;   //with modern runtime you can omit this line
}
@property (readonly) NSInteger someInt;
@end

//SomeClass.m
@interface SomeClass ()
@property (readwrite) NSInteger someInt;
@end

@implementation SomeClass
@synthesize someInt;
@end

But if you use a modern runtime ,you can also declare a totally new property in the class extension (which also generate an iVar for that property if there isn't).

//SomeClass.h

@interface SomeClass : NSObject
{
}
@end

//SomeClass.m
@interface SomeClass ()
@property (readwrite) NSInteger someInt;
@end

@implementation SomeClass
@synthesize someInt;
@end

Here's my question : I think declare a totally new property in class extention is somehow has some side effects. Because class extension my not be in the header file and someone else who subclass the class may not know about that "secret property". And if he declare a property with the same name of that "secret property". And this new property's getter and setter method will override the super class's. Isn't this a problem?And why would modern runtime allow such thing happen?

EDIT I posted another question about this topic , please check it out:
The risk of declare new propery in class extension (Ojbective-C) , how to solve it?


问:
Why are grid items overflowing the grid container?
I want my grid container to auto-adjust to the content it has. It's parent also has a height of auto. At this time, the grid is being overflowed by its content.
It has this behavior:

```
xxxxxxxxxxcontainerxxxxxxxxxx   _
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |---------Grid items
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |
|xxxxxxxxx|xxxxxxxx|xxxxxxxx|    |
|         |        |        |    |
|_________|________|________|   _|
```

I've tried to use the grid-template-columns, but it was only affecting the first row, so tried using grid-auto-columns and it resizes all the rows, but still overflowing.

I expect that if I add another row, the grid container will be resized to its content.

#allyes {
  position: relative;
  width: 100%;
  height: auto;
  background-image: url('../img/fondo-laptop.webp');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
}

#allyes #allyesLogos {
  height: auto;
  margin-left: auto;
  width: 60%;
  padding: 2% 3%;
  background: rgba(255, 255, 255, 0.6);
}

#allyes #allyesTitle {
  font-size: var(--bigTitleSize);
  font-family: var(--titleFamily);
  color: white;
  text-transform: uppercase;
  margin-bottom: 5vh;
  text-shadow: 2px 2px rgba(0, 0, 0, 0.6);
}

#allyesLogos .logosTable {
  width: 100%;
  height: auto;
  display: grid;
  margin-bottom: 5vh;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  grid-auto-rows: 70px;
  align-items: center;
  justify-items: center;
  grid-gap: 2% 3%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="allyes">
  <div id="allyesLogos">
    <h1 id="allyesTitle">alianzas comericales</h1>
    <div class="logosTable">
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/4yousee.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/benq.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/bright-sign.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/dell.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/dynascan.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/elo.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/fortinet.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/glassapps.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/hisense.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/iadea.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/lenovo.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/LG.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/nec.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/panasonic.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/samsung.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/screengoo.webp'?>" alt="ally"></div>
      <div class='allyLogo'><img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/sharp.webp'?>" alt="ally"></div>
    </div>
  </div>
</section></code>```

答:
This is the source of the problem:

```<code>grid-gap: 2% 3%
</code>```

It appears that the percentage grid gaps are being factored into the layout after the rendering engine has set the dimensions of the container.

It may also be an issue with what the percentages are being based on (container height? row height? something else?).

Either way, percentage values for grid gaps are causing grid items to overflow the grid container.

Try using a different unit of length, such as vh, px or em. They seem to work fine.

In the demo below, I used grid-gap: 2vh 3vh.

#allyes {
  position: relative;
  width: 100%;
  height: auto;
  background-image: url('../img/fondo-laptop.webp');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
}

#allyes #allyesLogos {
  height: auto;
  margin-left: auto;
  width: 60%;
  padding: 2% 3%;
  background: rgba(255, 255, 255, 0.6);
}

#allyes #allyesTitle {
  font-size: var(--bigTitleSize);
  font-family: var(--titleFamily);
  color: white;
  text-transform: uppercase;
  margin-bottom: 5vh;
  text-shadow: 2px 2px rgba(0, 0, 0, 0.6);
}

#allyesLogos .logosTable {
  width: 100%;
  height: auto;
  display: grid;
  margin-bottom: 5vh;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  grid-auto-rows: 70px;
  align-items: center;
  justify-items: center;
  /* grid-gap: 2% 3%; */
    grid-gap: 2vh 3vh; /* adjustment */
  border: 1px solid red; /* demo */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="allyes">
  <div id="allyesLogos">
    <h1 id="allyesTitle">alianzas comericales</h1>
    <div class="logosTable">
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
    </div>
  </div>
</section></code>```

Also note: The problem described in the question exists in Chrome and Firefox, but not in Edge. The grid container in Edge expands naturally to accommodate grid items along with percentage grid gaps.

Body:
I want my grid container to auto-adjust to the content it has. It's parent also has a height of auto. At this time, the grid is being overflowed by its content.
It has this behavior:

xxxxxxxxxxcontainerxxxxxxxxxx   _
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |---------Grid items
|         |        |        |    |
|         |        |        |    |
|_________|________|________|    |
|xxxxxxxxx|xxxxxxxx|xxxxxxxx|    |
|         |        |        |    |
|_________|________|________|   _|

I've tried to use the grid-template-columns, but it was only affecting the first row, so tried using grid-auto-columns and it resizes all the rows, but still overflowing.

I expect that if I add another row, the grid container will be resized to its content.

#allyes {
  position: relative;
  width: 100%;
  height: auto;
  background-image: url('../img/fondo-laptop.webp');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
}

#allyes #allyesLogos {
  height: auto;
  margin-left: auto;
  width: 60%;
  padding: 2% 3%;
  background: rgba(255, 255, 255, 0.6);
}

#allyes #allyesTitle {
  font-size: var(--bigTitleSize);
  font-family: var(--titleFamily);
  color: white;
  text-transform: uppercase;
  margin-bottom: 5vh;
  text-shadow: 2px 2px rgba(0, 0, 0, 0.6);
}

#allyesLogos .logosTable {
  width: 100%;
  height: auto;
  display: grid;
  margin-bottom: 5vh;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  grid-auto-rows: 70px;
  align-items: center;
  justify-items: center;
  grid-gap: 2% 3%;
}

alianzas comericales

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/4yousee.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/benq.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/bright-sign.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/dell.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/dynascan.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/elo.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/fortinet.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/glassapps.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/hisense.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/iadea.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/lenovo.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/LG.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/nec.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/panasonic.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/samsung.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/screengoo.webp'?>" alt="ally">

<img src="<?php echo $httpProtocol.$host.$url.'img/logos-alianzas/sharp.webp'?>" alt="ally">

Body:
This is the source of the problem:

grid-gap: 2% 3%

It appears that the percentage grid gaps are being factored into the layout after the rendering engine has set the dimensions of the container.

It may also be an issue with what the percentages are being based on (container height? row height? something else?).

Either way, percentage values for grid gaps are causing grid items to overflow the grid container.

Try using a different unit of length, such as vh, px or em. They seem to work fine.

In the demo below, I used grid-gap: 2vh 3vh.

#allyes {
  position: relative;
  width: 100%;
  height: auto;
  background-image: url('../img/fondo-laptop.webp');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
}

#allyes #allyesLogos {
  height: auto;
  margin-left: auto;
  width: 60%;
  padding: 2% 3%;
  background: rgba(255, 255, 255, 0.6);
}

#allyes #allyesTitle {
  font-size: var(--bigTitleSize);
  font-family: var(--titleFamily);
  color: white;
  text-transform: uppercase;
  margin-bottom: 5vh;
  text-shadow: 2px 2px rgba(0, 0, 0, 0.6);
}

#allyesLogos .logosTable {
  width: 100%;
  height: auto;
  display: grid;
  margin-bottom: 5vh;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  grid-auto-rows: 70px;
  align-items: center;
  justify-items: center;
  /* grid-gap: 2% 3%; */
    grid-gap: 2vh 3vh; /* adjustment */
  border: 1px solid red; /* demo */
}

<section id="allyes">
  <div id="allyesLogos">
    <h1 id="allyesTitle">alianzas comericales</h1>
    <div class="logosTable">
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
      <div class='allyLogo'><img src="http://i.imgur.com/60PVLis.png" width="50" height="50" alt=""></div>
    </div>
  </div>
</section>

Also note: The problem described in the question exists in Chrome and Firefox, but not in Edge. The grid container in Edge expands naturally to accommodate grid items along with percentage grid gaps.


问:
Add target hours onto the next working day if job is logged after a certain time
Bit of a specific request / query but hope that I can explain it correctly, and that it makes sense.

The working day is 8am-5pm Monday-Friday

Each job has a target response time eg 1 hour, 2 hours, 4 hours

Some jobs it shows the target response time as outside of the working day eg a 4 hour job logged at 4:15pm will show a target response time of 8:15pm.

What I would like to do (and not even sure if it is possible) is:

If the priority_code is GC04 (1 hour job) and the time logged is after 4pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 1 hour job logged at 4:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (45 minutes used on Monday and 15 minutes carried over to Tuesday).

If the priority_code is GC05 (2 hour job) and the time logged is after 3pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 2 hour job logged at 3:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (1 hour 45 minutes used on Monday and 15 minutes carried over to Tuesday).

If the priority_code is GC06 (4 hour job) and the time logged is after 1pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 4 hour job logged at 1:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (3 hours 45 minutes used on Monday and 15 minutes carried over to Tuesday).

THANK YOU TO ALEX POOLE I'VE NOW GOT IT WORKING
Coding is below

```<code>select job_number, priority_code, job_entry_date, clock_start,
target_comp_date,
case
   when to_char(target_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
   and floor((target_time - trunc(target_time)) * 24) >= 17
   then target_time + 2 + 63/24
           when floor((target_time - trunc(target_time)) * 24) >= 17
           then target_time + 15/24
                  else target_time
end as target_time

from (
select job_number, priority_code, job_entry_date, clock_start,
TARGET_COMP_DATE,
CASE
WHEN PRIORITY_CODE IN ('GC01','GC02','GC03','GC04','GC05','GC06','GC07')
THEN
clock_start
+ case priority_code
when 'GC01' then 1
when 'GC02' then 2
when 'GC03' then 0.5
when 'GC04' then 1
when 'GC05' then 2
when 'GC06' then 4
when 'GC07' then 24

end
/ 24

ELSE
TARGET_COMP_DATE END as target_time

from              (
 select job_number, priority_code, job_entry_date, target_comp_date,
 case
 when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
 and floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
 then trunc(job_entry_date) + 80/24
     when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Sat'
      then trunc(job_entry_date) + 56/24
          when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') =
 'Sun'
          or floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
          then trunc(job_entry_date) + 32/24
               when floor((job_entry_date - trunc(job_entry_date)) * 24) < 8
               then trunc(job_entry_date) + 8/24
                    else job_entry_date
  end as clock_start
  from job
                )
     )
</code>```

答:
A slightly convoluted approach, which assumes your logged_time column is a timestamp (easy to adapt if it's a date), and that it can't be out-of-hours:

```<code>select id, priority_code, logged_time,
  logged_time
    +
    -- response time
    (
      interval '1' hour
        * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
    )
    +
    -- actual time adjustment
    (
      -- possible time adjustment...
      (
        -- gap between 17:00 and 08:00
        interval '15' hour
        +
        -- weekend days, only if Friday
        (
            interval '2' day
              * case when to_char(logged_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
                     then 1 else 0 end
        )
      )
      *
      -- ... but only if target exceeds 17:00
      case when extract
      (
        hour from logged_time
        +
        -- response time
        (
          interval '1' hour
            * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
        )
      ) > 16 then 1 else 0 end
    )
    as target_time
from your_table;
</code>```

which with some sample data like yours and just before your cut-offs, both on a Friday and Monday, gives:

```<code>        ID PRIO LOGGED_TIME           TARGET_TIME
---------- ---- --------------------- ---------------------
         1 GC06 2019-05-26 12:59:59.0 2019-05-26 16:59:59.0
         2 GC06 2019-05-26 13:15:00.0 2019-05-27 08:15:00.0
         3 GC05 2019-05-26 14:59:59.0 2019-05-26 16:59:59.0
         4 GC05 2019-05-26 15:15:00.0 2019-05-27 08:15:00.0
         5 GC04 2019-05-26 15:59:59.0 2019-05-26 16:59:59.0
         6 GC04 2019-05-26 16:15:00.0 2019-05-27 08:15:00.0
         7 GC06 2019-05-31 12:59:59.0 2019-05-31 16:59:59.0
         8 GC06 2019-05-31 13:15:00.0 2019-06-03 08:15:00.0
         9 GC05 2019-05-31 14:59:59.0 2019-05-31 16:59:59.0
        10 GC05 2019-05-31 15:15:00.0 2019-06-03 08:15:00.0
        11 GC04 2019-05-31 15:59:59.0 2019-05-31 16:59:59.0
        12 GC04 2019-05-31 16:15:00.0 2019-06-03 08:15:00.0
</code>```

You can reduce some of the duplication with a CTE or inline view:

```<code>select id, priority_code, logged_time,
  raw_target_time
    +
    -- actual time adjustment
    (
      -- possible time adjustment...
      (
        -- gap between 17:00 and 08:00
        interval '15' hour
        +
        -- weekend days, only if Friday
        (
            interval '2' day
              * case when to_char(logged_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
                     then 1 else 0 end
        )
      )
      *
      -- ... but only if target exceeds 17:00
      case when extract (hour from raw_target_time) > 16 then 1 else 0 end
    )
    as target_time
from (
  select id, priority_code, logged_time,
    logged_time
    +
    -- response time
    (
      interval '1' hour
        * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
    )
    as raw_target_time
  from your_table
);
</code>```

and of course it doesn't need to be laid out like that, I was just trying to make the logic a bit clearer.

Body:
Bit of a specific request / query but hope that I can explain it correctly, and that it makes sense.

The working day is 8am-5pm Monday-Friday

Each job has a target response time eg 1 hour, 2 hours, 4 hours

Some jobs it shows the target response time as outside of the working day eg a 4 hour job logged at 4:15pm will show a target response time of 8:15pm.

What I would like to do (and not even sure if it is possible) is:

If the priority_code is GC04 (1 hour job) and the time logged is after 4pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 1 hour job logged at 4:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (45 minutes used on Monday and 15 minutes carried over to Tuesday).

If the priority_code is GC05 (2 hour job) and the time logged is after 3pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 2 hour job logged at 3:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (1 hour 45 minutes used on Monday and 15 minutes carried over to Tuesday).

If the priority_code is GC06 (4 hour job) and the time logged is after 1pm on a Monday-Fri take whatever time is before 5pm and add the remainder on to the next working day from 8am.
So an example would be 4 hour job logged at 1:15pm on Monday would show a target response time of 8:15am on Tuesday morning. (3 hours 45 minutes used on Monday and 15 minutes carried over to Tuesday).

THANK YOU TO ALEX POOLE I'VE NOW GOT IT WORKING
Coding is below

select job_number, priority_code, job_entry_date, clock_start,
target_comp_date,
case
   when to_char(target_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
   and floor((target_time - trunc(target_time)) * 24) >= 17
   then target_time + 2 + 63/24
           when floor((target_time - trunc(target_time)) * 24) >= 17
           then target_time + 15/24
                  else target_time
end as target_time

from (
select job_number, priority_code, job_entry_date, clock_start,
TARGET_COMP_DATE,
CASE
WHEN PRIORITY_CODE IN ('GC01','GC02','GC03','GC04','GC05','GC06','GC07')
THEN
clock_start
+ case priority_code
when 'GC01' then 1
when 'GC02' then 2
when 'GC03' then 0.5
when 'GC04' then 1
when 'GC05' then 2
when 'GC06' then 4
when 'GC07' then 24

end
/ 24

ELSE
TARGET_COMP_DATE END as target_time

from              (
 select job_number, priority_code, job_entry_date, target_comp_date,
 case
 when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
 and floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
 then trunc(job_entry_date) + 80/24
     when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Sat'
      then trunc(job_entry_date) + 56/24
          when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') =
 'Sun'
          or floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
          then trunc(job_entry_date) + 32/24
               when floor((job_entry_date - trunc(job_entry_date)) * 24) < 8
               then trunc(job_entry_date) + 8/24
                    else job_entry_date
  end as clock_start
  from job
                )
     )

Body:
A slightly convoluted approach, which assumes your logged_time column is a timestamp (easy to adapt if it's a date), and that it can't be out-of-hours:

select id, priority_code, logged_time,
  logged_time
    +
    -- response time
    (
      interval '1' hour
        * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
    )
    +
    -- actual time adjustment
    (
      -- possible time adjustment...
      (
        -- gap between 17:00 and 08:00
        interval '15' hour
        +
        -- weekend days, only if Friday
        (
            interval '2' day
              * case when to_char(logged_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
                     then 1 else 0 end
        )
      )
      *
      -- ... but only if target exceeds 17:00
      case when extract
      (
        hour from logged_time
        +
        -- response time
        (
          interval '1' hour
            * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
        )
      ) > 16 then 1 else 0 end
    )
    as target_time
from your_table;

which with some sample data like yours and just before your cut-offs, both on a Friday and Monday, gives:

        ID PRIO LOGGED_TIME           TARGET_TIME
---------- ---- --------------------- ---------------------
         1 GC06 2019-05-26 12:59:59.0 2019-05-26 16:59:59.0
         2 GC06 2019-05-26 13:15:00.0 2019-05-27 08:15:00.0
         3 GC05 2019-05-26 14:59:59.0 2019-05-26 16:59:59.0
         4 GC05 2019-05-26 15:15:00.0 2019-05-27 08:15:00.0
         5 GC04 2019-05-26 15:59:59.0 2019-05-26 16:59:59.0
         6 GC04 2019-05-26 16:15:00.0 2019-05-27 08:15:00.0
         7 GC06 2019-05-31 12:59:59.0 2019-05-31 16:59:59.0
         8 GC06 2019-05-31 13:15:00.0 2019-06-03 08:15:00.0
         9 GC05 2019-05-31 14:59:59.0 2019-05-31 16:59:59.0
        10 GC05 2019-05-31 15:15:00.0 2019-06-03 08:15:00.0
        11 GC04 2019-05-31 15:59:59.0 2019-05-31 16:59:59.0
        12 GC04 2019-05-31 16:15:00.0 2019-06-03 08:15:00.0

You can reduce some of the duplication with a CTE or inline view:

select id, priority_code, logged_time,
  raw_target_time
    +
    -- actual time adjustment
    (
      -- possible time adjustment...
      (
        -- gap between 17:00 and 08:00
        interval '15' hour
        +
        -- weekend days, only if Friday
        (
            interval '2' day
              * case when to_char(logged_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
                     then 1 else 0 end
        )
      )
      *
      -- ... but only if target exceeds 17:00
      case when extract (hour from raw_target_time) > 16 then 1 else 0 end
    )
    as target_time
from (
  select id, priority_code, logged_time,
    logged_time
    +
    -- response time
    (
      interval '1' hour
        * case priority_code when 'GC04' then 1 when 'GC05' then 2 when 'GC06' then 4 end
    )
    as raw_target_time
  from your_table
);

and of course it doesn't need to be laid out like that, I was just trying to make the logic a bit clearer.


答:
You need to get the item out of the list of IPs. Use the for loop for that, not a range:

```<code>for ip in multi_ip_addr:
    device = {
        'ip': ip,
        'username': 'admin',
        'password': 'password'
    }
    print(device)
</code>```

The first for loop will overwrite the value of ips on each loop, so really by the end of the loop, ips equals the last value of multi_ip_addr.

Title: How to fix for-loop output in python

Body:
You need to get the item out of the list of IPs. Use the for loop for that, not a range:

for ip in multi_ip_addr:
    device = {
        'ip': ip,
        'username': 'admin',
        'password': 'password'
    }
    print(device)

The first for loop will overwrite the value of ips on each loop, so really by the end of the loop, ips equals the last value of multi_ip_addr.


问:
How to get json_encode() to work with ISO-8859-1 (åäö)
json_encode() wont work for me when I'm using åäö. Why? And how can I get it to work?

The php:

```<code>echo json_encode($arr);
</code>```

The javascript:

```<code>var theResponse = JSON.parse(xmlHttp.responseText);
</code>```

When I alert() the response, and the response contains å, ä or ö, the response is = NULL

Please, help me out...

答:
As of PHP 5.4.0:

Convert your strings in your array to into utf-8 using utf8_encode($str) function.

Then json_encode with JSON_UNESCAPED_UNICODE option:

$arr = json_encode($array, JSON_UNESCAPED_UNICODE);

ContentLicense: CC BY-SA 2.5

Body:
json_encode() wont work for me when I'm using åäö. Why? And how can I get it to work?

The php:

echo json_encode($arr);

The javascript:

var theResponse = JSON.parse(xmlHttp.responseText);

When I alert() the response, and the response contains å, ä or ö, the response is = NULL

Please, help me out...


问:
What does float *a[]; declare in c?
Suppose float *a[]; is declared in the main method n c. I'm trying to learn about pointers and understand what the above means.

I'm guessing it declares a pointer to the first element of that array a[].
But a[] doesn't have any elements..
I am really confused.

Thanks anyone who helps.

答:
When declaring a variable, it's not valid code without an array size.

```<code>a.c: In function ‘main’:
a.c:2:11: error: array size missing in ‘a’
    float *a[];
</code>```

With an array size, it creates an array of pointers.

Test:

```<code>#include <stdio.h>

int main() {
   printf("float:           %zu\n", sizeof(float));
   printf("pointer:         %zu\n", sizeof(void*));

   float *a[100];
   printf("float *a[100]:   %zu\n", sizeof(a));

   float (*b)[100];
   printf("float (*b)[100]: %zu\n", sizeof(b));
   printf("*b:              %zu\n", sizeof(*b));

   return 0;
}
</code>```

Output:

```<code>float:           4
pointer:         8
float* a[100]:   800       // a is an array of 100 float pointers.
float (*b)[100]: 8         // b is a pointer to an array of 100 floats.
*b:              400
</code>```

Note that there's a special case in C where a [] does not declare an array, but a pointer. When declaring a function parameter:

```<code>void f(float *a[], size_t n) {
   // ...
}
</code>```

The [] is treated as a pointer declaration, so it's equivalent to:

```<code>void f(float **a, size_t n) { // ...
</code>```

Since an array decays to a pointer to its first element when passing it as an argument to a function, the function can accept arrays:

```<code>int main() {
   int n = 100;
   float *a[n];
   // ... Initialize the array here ...
   f(a, n);
   return 0;
}
</code>```

This is a quirk of the C language.

Title: What does float *a[]; declare in c?

Body:
When declaring a variable, it's not valid code without an array size.

a.c: In function ‘main’:
a.c:2:11: error: array size missing in ‘a’
    float *a[];

With an array size, it creates an array of pointers.

Test:

#include <stdio.h>

int main() {
   printf("float:           %zu\n", sizeof(float));
   printf("pointer:         %zu\n", sizeof(void*));

   float *a[100];
   printf("float *a[100]:   %zu\n", sizeof(a));

   float (*b)[100];
   printf("float (*b)[100]: %zu\n", sizeof(b));
   printf("*b:              %zu\n", sizeof(*b));

   return 0;
}

Output:

float:           4
pointer:         8
float* a[100]:   800       // a is an array of 100 float pointers.
float (*b)[100]: 8         // b is a pointer to an array of 100 floats.
*b:              400

Note that there's a special case in C where a [] does not declare an array, but a pointer. When declaring a function parameter:

void f(float *a[], size_t n) {
   // ...
}

The [] is treated as a pointer declaration, so it's equivalent to:

void f(float **a, size_t n) { // ...

Since an array decays to a pointer to its first element when passing it as an argument to a function, the function can accept arrays:

int main() {
   int n = 100;
   float *a[n];
   // ... Initialize the array here ...
   f(a, n);
   return 0;
}

This is a quirk of the C language.


问:
How do I fix "No pubspec.yaml file found" in flutter?
I am using Windows 10 with VS Code, although I also tested it on PowerShell, and both produced the same result:

After creating a new flutter program, before editing anything, I tried to run it on my phone, as the Tutorial Says, but I get an error saying "No pubspec.yaml file found". I thought that the issue must be that the default new app setup having an issue, so I used the "flutter_gallery" example. However, this had the exact same issue. I have reinstalled flutter, installed dart 2 on its own, deleted .pub-cache, but nothing works. I tried Googling the issue, but I couldn't find anything.

EDIT: I am running the commands from the root directory of the flutter project, where the pubspec.yaml file is, but I still get an error. The full error message is:

```<code>Error: No pubspec.yaml file found.
This command should be run from the root of your Flutter project.
Do not run this command from the root of your git clone of Flutter.
</code>```

here is the result of running dir from the root of the project:

```<code>Mode                LastWriteTime         Length Name
----                -------------         ------ ----
da---l       2018-04-11   3:45 PM                .idea
da---l       2018-04-11   3:45 PM                android
da---l       2018-04-11   3:45 PM                ios
da---l       2018-04-11   4:19 PM                lib
da---l       2018-04-11   3:45 PM                test
-a---l       2018-04-11   3:45 PM            120 .gitignore
-a---l       2018-04-11   3:45 PM            292 .metadata
-a---l       2018-04-11   3:45 PM           5425 .packages
-a---l       2018-04-11   3:45 PM            851 hello_world.iml
-a---l       2018-04-11   3:45 PM           1412 hello_world_android.iml
-a---l       2018-04-11   3:59 PM           8882 pubspec.lock
-a---l       2018-04-11   3:59 PM            358 pubspec.yaml
-a---l       2018-04-11   3:45 PM            160 README.md
</code>```

UPDATE: I still don't know what caused the problem, but when I reinstalled flutter for Beta 3, it finally worked.

答:
This error gets thrown when you try to run flutter build apk command (at least, it was in my case) while not being in the project directory. Usually, a flutter app's project directory path (let's say it is in F drive, and inside a folder named apps, is as:
F:\Apps\app_name

I had the same issue, and the culprit in my case was this path: F:\Apps\app_name\android which is without a doubt, NOT a project directory. So, all I had to do was type this command in terminal: cd .. which takes to the parent directory.

So, before running the command, make sure to check out the directory being shown in terminal.

Body:
I am using Windows 10 with VS Code, although I also tested it on PowerShell, and both produced the same result:

After creating a new flutter program, before editing anything, I tried to run it on my phone, as the Tutorial Says, but I get an error saying "No pubspec.yaml file found". I thought that the issue must be that the default new app setup having an issue, so I used the "flutter_gallery" example. However, this had the exact same issue. I have reinstalled flutter, installed dart 2 on its own, deleted .pub-cache, but nothing works. I tried Googling the issue, but I couldn't find anything.

EDIT: I am running the commands from the root directory of the flutter project, where the pubspec.yaml file is, but I still get an error. The full error message is:

Error: No pubspec.yaml file found.
This command should be run from the root of your Flutter project.
Do not run this command from the root of your git clone of Flutter.

here is the result of running dir from the root of the project:

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
da---l       2018-04-11   3:45 PM                .idea
da---l       2018-04-11   3:45 PM                android
da---l       2018-04-11   3:45 PM                ios
da---l       2018-04-11   4:19 PM                lib
da---l       2018-04-11   3:45 PM                test
-a---l       2018-04-11   3:45 PM            120 .gitignore
-a---l       2018-04-11   3:45 PM            292 .metadata
-a---l       2018-04-11   3:45 PM           5425 .packages
-a---l       2018-04-11   3:45 PM            851 hello_world.iml
-a---l       2018-04-11   3:45 PM           1412 hello_world_android.iml
-a---l       2018-04-11   3:59 PM           8882 pubspec.lock
-a---l       2018-04-11   3:59 PM            358 pubspec.yaml
-a---l       2018-04-11   3:45 PM            160 README.md

UPDATE: I still don't know what caused the problem, but when I reinstalled flutter for Beta 3, it finally worked.


问:
Stubbing out method with ArrayList/List param fails when using any() or anyList()
I have a java class.

```<code>class Blah{
        public Blah(){

        }
        public String testMe(List<String> s){
            return new String("hello "+s.get(0));
        }

        public String testMeString(String s){
            return new String("hello "+s);
        }

    }
</code>```

I am unable trying to stub and test the testMe method successfully. Note that I am just trying to understand mocking in java. For example I have tried:

```<code>    @Test
    public void testTestMe(){
        Blah blah = spy(new Blah());
        ArrayList<String> l = new ArrayList<String>();
        l.add("oopsie");
        when(blah.testMe(Matchers.any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMe(l));
</code>```

This returns a NullPointerException. I have also tried any(List.class), any(ArrayList.class). I have also tried using anyList() but this gives me an IndexOutOfBounds error. What am I doing wrong?
Interestingly, my testMeString works fine. If I do

```<code>@Test
    public void testTestMeString(){
        Blah blah = spy(new Blah());
        when(blah.testMeString(any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMeString("lala"));
}
</code>```

the tests pass with any() and any(String.class).

答:
Your NullPointerException is being thrown during your stubbing, not during your test.

This is because Matchers.any() actually returns null, so if you use it when you're calling a real method, you pass null as the argument. testMeString happens to work because null + s doesn't cause a NullPointerException (the string "null" is used instead).

Instead of:

```<code>when(blah.testMe(any())).thenReturn("intercepted");
</code>```

You need to use

```<code>doReturn("intercepted").when(blah).testMe(any());
</code>```

This is documented (although admittedly not super clearly) as the Important gotcha on spying real objects! in the Mockito documentation.

Body:
I have a java class.

class Blah{
        public Blah(){

        }
        public String testMe(List<String> s){
            return new String("hello "+s.get(0));
        }

        public String testMeString(String s){
            return new String("hello "+s);
        }

    }

I am unable trying to stub and test the testMe method successfully. Note that I am just trying to understand mocking in java. For example I have tried:

    @Test
    public void testTestMe(){
        Blah blah = spy(new Blah());
        ArrayList<String> l = new ArrayList<String>();
        l.add("oopsie");
        when(blah.testMe(Matchers.any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMe(l));

This returns a NullPointerException. I have also tried any(List.class), any(ArrayList.class). I have also tried using anyList() but this gives me an IndexOutOfBounds error. What am I doing wrong?
Interestingly, my testMeString works fine. If I do

@Test
    public void testTestMeString(){
        Blah blah = spy(new Blah());
        when(blah.testMeString(any())).thenReturn("intercepted");
        assertEquals("intercepted",blah.testMeString("lala"));
}

the tests pass with any() and any(String.class).

Body:
Your NullPointerException is being thrown during your stubbing, not during your test.

This is because Matchers.any() actually returns null, so if you use it when you're calling a real method, you pass null as the argument. testMeString happens to work because null + s doesn't cause a NullPointerException (the string "null" is used instead).

Instead of:

when(blah.testMe(any())).thenReturn("intercepted");

You need to use

doReturn("intercepted").when(blah).testMe(any());

This is documented (although admittedly not super clearly) as the Important gotcha on spying real objects! in the Mockito documentation.


问:
UNIX sockets: How to check if TCP stream is closed for reading or EOF?
I am writing a simple client which reads binary data through a TCP stream.
Since the file is sent part-by-part I have a loop similar to this one:

```<code>while (1 /* Maybe a check for EOF or if the socket is closed here ? */) {
  ssize_t bytes_red = recv(
  if (bytes_read <= 0) // not working properly ?
    break;
  ...
}
</code>```

The reading is done via recv() method, which returns the number of bytes received.
The idea is obviously to read data as long the TCP stream is opened, but it seems the above approach does not work for me.

Any other ideas? What is a clean way to read from socket until the stream is closed or EOF is encountered?

EDIT: The above approach works fine, I had a bug elsewhere.

答:
recv() returns 0 if the socket was properly closed, -1 if there was an error. So, you read until recv() returns <=0. Your posted code snippet looks correct - why do you think it's not working for you? What happens, what did you expect?

If your socket is non-blocking, you will also have to handle the case where recv() returns -1 and errno is set to EAGAIN or EWOULDBLOCK. This means that the socket is still alive and well, but there's no more data right now.

Body:
I am writing a simple client which reads binary data through a TCP stream.
Since the file is sent part-by-part I have a loop similar to this one:

while (1 /* Maybe a check for EOF or if the socket is closed here ? */) {
  ssize_t bytes_red = recv(
  if (bytes_read <= 0) // not working properly ?
    break;
  ...
}

The reading is done via recv() method, which returns the number of bytes received.
The idea is obviously to read data as long the TCP stream is opened, but it seems the above approach does not work for me.

Any other ideas? What is a clean way to read from socket until the stream is closed or EOF is encountered?

EDIT: The above approach works fine, I had a bug elsewhere.


问:
is there any way to extract password protected zip file in cpanel?
I am upload 100 GB zip file in my file server and zip file is password protected .

Is there any way to extract password protected zip file in my Cpanel ?

答:
The answer is NO.

CPanel doesnt provide any feature to extract password protected archives

Visit this for more info https://forums.cpanel.net/threads/how-to-extract-zip-passworded-file.139473/


问:
Bot v4 web chat channel, sending the message very slowly
I am using the latest v4 web chat react lib. In the emulator things works fine and quick. But when i deploy it on azure and use the webchat channel, and type a message and send, the "Sending" label appears and stay a little and then says "Just now". The problem is that its very slow and the sending label actually stay for like 2 seconds. What could be the possible cause here ?

The same issue has been raised in github https://github.com/MicrosoftDocs/bot-docs/issues/1172

答:
It's indicative of how fast your user message is hitting the bot endpoint. The emulator is local, and thus, a bit faster (2 seconds in this case).

"Sending" means the user has sent off the message, and the "Just now" message means the bot has read the user's message. It's apparently taking 2 seconds for your bot to hit your azure endpoint. In order to turn from "sending" to "sent", the Direct Line channel need to explicitly tell Web Chat that the bot has read it. Technically, it means Direct Line channel will send the copy of the user's message back to Web Chat again.

For example, for this story.

User say "My name is John"

Bot say "Hello, John"

If you look at the network traffic from Direct Line channel in the browser, you should see a few packets send or receive in this particular order:

HTTP POST "My name is John", returns 200 OK

HTTP GET 200 OK for "Hello, John" (or as Web Socket packet)

HTTP GET 200 OK for "My name is John" (or as Web Socket packet)

If the 3rd packet is not received, Web Chat will not consider the message is successfully sent.

If you are using our Direct Line channel (not custom bot adapter), Direct Line channel will make up the 3rd packet for you automatically, as long as the bot respond "positively and timely" for the HTTP request "My name is John" from Direct Line channel. In other words, if the bot is error-ed out or taking too long time while processing the user's message, Web Chat will not change to "Just Now" status because it's a negative response. (For timeout, I believe the hard deadline is 120s.)

If you have Application Insights added to your bot, you can look at the dashboard to review the network traffic:


问:
Simple find primes implementation
i have idea "find primes between 1 and n".
    Algorithms based on residual division.
    i use 2 array pr and nt.
    [pr is saved primes. nt is saved counter number.]
    ex.
    begin with 3
    3 is primes => pr0 = 3 and nt0 = 2.
    primes >3 is odd.
    when i = 5 nt0 = nt0-1 = 1  => 5 is prime.
    And pr1 = 5, nt1 =pr1 -1 = 4.
    when i = 7 :
    nt0 = nt0 -1 = 0, => 7 is prime.
    and pr2 = 7, nt2 = 6.
    when i = 9
    nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5.
    ....

```<code>    using System;
    namespace primes
    { // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1; // n is number of primes.
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else
                    {
                        ct[l] = pr[l] - 1  ;
                     //  Console.Write("{0} ", ct[l]);
                        for (int a = l + 1; a < n; a++)
                        {
                            ct[a]--;
                         //   Console.Write("{0} ", ct[a]);
                        }
                    //    Console.WriteLine();
                        goto resume; // when ct <0 jump to resume
                    }
                }
           //     Console.WriteLine();
                pr[n] = i;
                ct[n] = i ;
            //    Console.Write("{0} ", ct[n]);
                n++;
            resume : ;
            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
    }
</code>```

i want to print primes 3,5,7,11, 13...
but i when i run:  3 5 7 9 13 15 17 23 29 37 39 63 65 71 89.
i dont understand.
Can you help me?

答:
thanks all.
i finished my program.
This is my code :</p>

```<code>using System;

namespace primes
{ // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1;
            int v = 0;
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] == 0)
                    {
                        ct[l] = pr[l] - 1;
                        v++;
                    }
                    else
                    {
                        ct[l]--;
                    }
                }
                if(v != 0)
                { v = 0;
                }
               else  {
                pr[n] = i;
                ct[n] = i-1 ;
                n++;
            }

            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
}
</code>```

Title: Simple find primes implementation

Body:
i have idea "find primes between 1 and n".
    Algorithms based on residual division.
    i use 2 array pr and nt.
    [pr is saved primes. nt is saved counter number.]
    ex.
    begin with 3
    3 is primes => pr0 = 3 and nt0 = 2.
    primes >3 is odd.
    when i = 5 nt0 = nt0-1 = 1  => 5 is prime.
    And pr1 = 5, nt1 =pr1 -1 = 4.
    when i = 7 :
    nt0 = nt0 -1 = 0, => 7 is prime.
    and pr2 = 7, nt2 = 6.
    when i = 9
    nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5.
    ....

    using System;
    namespace primes
    { // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1; // n is number of primes.
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] >= 0)
                    {
                       ct[l]--  ;
                        //Console.Write("{0} ", ct[l]);
                    }
                  else
                    {
                        ct[l] = pr[l] - 1  ;
                     //  Console.Write("{0} ", ct[l]);
                        for (int a = l + 1; a < n; a++)
                        {
                            ct[a]--;
                         //   Console.Write("{0} ", ct[a]);
                        }
                    //    Console.WriteLine();
                        goto resume; // when ct <0 jump to resume
                    }
                }
           //     Console.WriteLine();
                pr[n] = i;
                ct[n] = i ;
            //    Console.Write("{0} ", ct[n]);
                n++;
            resume : ;
            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
    }

i want to print primes 3,5,7,11, 13...
but i when i run:  3 5 7 9 13 15 17 23 29 37 39 63 65 71 89.
i dont understand.
Can you help me?

Body:
thanks all.
i finished my program.
This is my code :

using System;

namespace primes
{ // program for find primes between 1 and n.
    class Program
    {    public  static void Main()
        {
            int[] pr = new int[100], ct = new int[100];
            ct[0] = 2;
            pr[0] = 3;// 3 is primes => n[0] is 3 .
            int n = 1;
            int v = 0;
            for (int i = 5; i < 111; i += 2)
            {
                for (int l = 0; l < n; l++)
                { if (ct[l] == 0)
                    {
                        ct[l] = pr[l] - 1;
                        v++;
                    }
                    else
                    {
                        ct[l]--;
                    }
                }
                if(v != 0)
                { v = 0;
                }
               else  {
                pr[n] = i;
                ct[n] = i-1 ;
                n++;
            }

            }
            for (int m = 0; m < n; m++)
            {
                Console.Write(" {0}", pr[m]);
            }
            Console.ReadKey();
        }
    }
}


问:
Using a wildcard to get all nodes
I'm trying to pull data from a json file using a wildcard.

The data I'm trying to pull are the game stats for every player from this json file.  They are under

http://statsapi-default-elb-prod-876255662.us-east-1.elb.amazonaws.com/api/v1/game/565711/boxscore

I've tested the jsonpath using this website

```<code>http://jsonpath.herokuapp.com/
</code>```

If I enter this json path

teams..players..person.fullName

I get a list of all the players

```<code>"Shane Bieber",
"Jon Edwards",
"Max Moroff",
"Jake Bauers",
"Tyler Olson",
"Nick Wittgren",
"Carlos Carrasco",
"Leonys Martin",
"Neil Ramirez",
"Greg Allen",
"Kevin Plawecki",
"Brad Miller",
"Jordan Luplow".
etc...
</code>```

However when I put that code into r I get an error

```<code>Error: unexpected '*' in "  repos$teams$*"
</code>```

I've tried the following codes

```<code>repos$teams$*$players$*$person$fullName
repos$teams$[*]$players$[*]$person$fullName
repos$teams$[[*]]$players$[[*]]$person$fullName
</code>```

The end goal is to get all the games stats for each player in to a dataframe

Can someone please point me in the right direction?  I'm new to json with R, thought I was doing pretty good, then this hit me between the eyes!  ha!

Thanks!

答:
You might try using the rjsonpath package. It's not on CRAN yet, but is useful here.

Once installed, you could do:

```<code>json_path(repos,  "$teams..players..person.fullName")
</code>```

or maybe just

```<code>json_path(repos,  "$..fullName")
</code>```

Title: Using a wildcard to get all nodes

Body:
I'm trying to pull data from a json file using a wildcard.

The data I'm trying to pull are the game stats for every player from this json file.  They are under

http://statsapi-default-elb-prod-876255662.us-east-1.elb.amazonaws.com/api/v1/game/565711/boxscore

I've tested the jsonpath using this website

http://jsonpath.herokuapp.com/

If I enter this json path

teams..players..person.fullName

I get a list of all the players

"Shane Bieber",
"Jon Edwards",
"Max Moroff",
"Jake Bauers",
"Tyler Olson",
"Nick Wittgren",
"Carlos Carrasco",
"Leonys Martin",
"Neil Ramirez",
"Greg Allen",
"Kevin Plawecki",
"Brad Miller",
"Jordan Luplow".
etc...

However when I put that code into r I get an error

Error: unexpected '*' in "  repos$teams$*"

I've tried the following codes

repos$teams$*$players$*$person$fullName
repos$teams$[*]$players$[*]$person$fullName
repos$teams$[[*]]$players$[[*]]$person$fullName

The end goal is to get all the games stats for each player in to a dataframe

Can someone please point me in the right direction?  I'm new to json with R, thought I was doing pretty good, then this hit me between the eyes!  ha!

Thanks!

Body:
You might try using the rjsonpath package. It's not on CRAN yet, but is useful here.

Once installed, you could do:

json_path(repos,  "$teams..players..person.fullName")

or maybe just

json_path(repos,  "$..fullName")


问:
nested attributes ids arrays syntax problem
So, there is a working part of code in rails 5. I'm making huge form with nested attributes on many levels. I've got an strong params list:

```<code>params.require(:lexeme).permit(
    :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
    variants_attributes: [ :word, :id, :_destroy, proofs_attributes: [ :word, :language_id, :meaning, :id, :_destroy, language_mode_ids: [] ] ]
  )
</code>```

And when I tried to change order a little bit...

```<code>params.require(:lexeme).permit(
    :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
    variants_attributes: [ :word, :id, :_destroy, proofs_attributes: [ :word, :language_id, :meaning, :id, language_mode_ids: [], :_destroy ] ]
  )
</code>```

I'm getting:

```<code>syntax error, unexpected ']', expecting =>
...guage_mode_ids: [], :_destroy ] ]
...                              ^):
</code>```

So, rails masters, what is wrong with this simple syntax here, has always array parameters need to be placed as last? What if I have more arrays in params?

答:
The problem is that the last :_destroy should be a key => value according to the syntax sugar lexical parsing.

If you want to retain the new order you need to make language_mode_ids: [] a literal Hash like so:

```<code>params.require(:lexeme).permit(
  :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
  variants_attributes: [ :word, :id, :_destroy,
    proofs_attributes: [
      :word, :language_id, :meaning, :id, {language_mode_ids: []}, :_destroy
    ]
  ]
)
</code>```

Ruby is trying to help you by allowing you to specify language_mode_ids: [] but it will require all the arguments on the right hand side of that to also represent a key value pair.

Since :_destroy is just a symbol the interpreter does not know what to do with this. That is why your first order worked and the new order does not.

Body:
So, there is a working part of code in rails 5. I'm making huge form with nested attributes on many levels. I've got an strong params list:

params.require(:lexeme).permit(
    :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
    variants_attributes: [ :word, :id, :_destroy, proofs_attributes: [ :word, :language_id, :meaning, :id, :_destroy, language_mode_ids: [] ] ]
  )

And when I tried to change order a little bit...

params.require(:lexeme).permit(
    :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
    variants_attributes: [ :word, :id, :_destroy, proofs_attributes: [ :word, :language_id, :meaning, :id, language_mode_ids: [], :_destroy ] ]
  )

I'm getting:

syntax error, unexpected ']', expecting =>
...guage_mode_ids: [], :_destroy ] ]
...                              ^):

So, rails masters, what is wrong with this simple syntax here, has always array parameters need to be placed as last? What if I have more arrays in params?

Body:
The problem is that the last :_destroy should be a key => value according to the syntax sugar lexical parsing.

If you want to retain the new order you need to make language_mode_ids: [] a literal Hash like so:

params.require(:lexeme).permit(
  :word, :homonym_number, :see_other_lexeme_id, :semantic_description, :afterword,
  variants_attributes: [ :word, :id, :_destroy,
    proofs_attributes: [
      :word, :language_id, :meaning, :id, {language_mode_ids: []}, :_destroy
    ]
  ]
)

Ruby is trying to help you by allowing you to specify language_mode_ids: [] but it will require all the arguments on the right hand side of that to also represent a key value pair.

Since :_destroy is just a symbol the interpreter does not know what to do with this. That is why your first order worked and the new order does not.


问:
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

答:
Here is an example of fetching those properties you are looking for:

```<code>Get-WKSWorkspace | foreach {
    $connectionStatus = Get-WKSWorkspacesConnectionStatus -WorkspaceId $_.WorkspaceId;
    echo "";
    echo "==> About $($_.WorkspaceId)";
    echo "Last State Check: $($connectionStatus.ConnectionStateCheckTimestamp)";
    echo "User Last Active: $($connectionStatus.LastKnownUserConnectionTimestamp)";
    echo "Directory: $($_.DirectoryId)";
    echo "Compute: $($_.WorkspaceProperties.ComputeTypeName)";
    echo "Running mode $($_.WorkspaceProperties.RunningMode)";
    echo "State $($_.State)"
}
</code>```

I don't see a 'Creation Time' on workspace on the console either.

[edit]
I believe you are looking for a way to export these info, may be below code will help:

```<code>[System.Collections.ArrayList]$output=@()
Get-WKSWorkspace | foreach {
    $connectionStatus = Get-WKSWorkspacesConnectionStatus -WorkspaceId $_.WorkspaceId;
    $bunch = [pscustomobject]@{
        WorkspaceId = $_.WorkspaceId
        LastStateCheck=$connectionStatus.ConnectionStateCheckTimestamp
        UserLastActive=$connectionStatus.LastKnownUserConnectionTimestamp
        Directory= $_.DirectoryId
        Compute=$_.WorkspaceProperties.ComputeTypeName
        Runningmode= $_.WorkspaceProperties.RunningMode
        State= $_.State
    }
    $output.Add($bunch)|Out-Null
}

$output | Export-Csv -NoType c:\dd.csv
</code>```

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

Body:
Here is an example of fetching those properties you are looking for:

Get-WKSWorkspace | foreach {
    $connectionStatus = Get-WKSWorkspacesConnectionStatus -WorkspaceId $_.WorkspaceId;
    echo "";
    echo "==> About $($_.WorkspaceId)";
    echo "Last State Check: $($connectionStatus.ConnectionStateCheckTimestamp)";
    echo "User Last Active: $($connectionStatus.LastKnownUserConnectionTimestamp)";
    echo "Directory: $($_.DirectoryId)";
    echo "Compute: $($_.WorkspaceProperties.ComputeTypeName)";
    echo "Running mode $($_.WorkspaceProperties.RunningMode)";
    echo "State $($_.State)"
}

I don't see a 'Creation Time' on workspace on the console either.

[edit]
I believe you are looking for a way to export these info, may be below code will help:

[System.Collections.ArrayList]$output=@()
Get-WKSWorkspace | foreach {
    $connectionStatus = Get-WKSWorkspacesConnectionStatus -WorkspaceId $_.WorkspaceId;
    $bunch = [pscustomobject]@{
        WorkspaceId = $_.WorkspaceId
        LastStateCheck=$connectionStatus.ConnectionStateCheckTimestamp
        UserLastActive=$connectionStatus.LastKnownUserConnectionTimestamp
        Directory= $_.DirectoryId
        Compute=$_.WorkspaceProperties.ComputeTypeName
        Runningmode= $_.WorkspaceProperties.RunningMode
        State= $_.State
    }
    $output.Add($bunch)|Out-Null
}

$output | Export-Csv -NoType c:\dd.csv


问:
Supervisor gets a SIGTERM for some reason, quits and stops all its processes
I use supervisor on an Ubuntu 12.04 machine (installed with pip) to run gunicorn and Django.

I start supervisord and everything is fine. I can reach my Django app through the nginx server which proxies gunicorn. The problem is, that after a few hours or even a day, supervisor stops. The supervisor log shows WARN received SIGTERM indicating exit request and the lines following are the shutting down of the 'supervised' processes.

I'm not really sure what is going on and what sends the SIGTERM. I searched Google and found someone who had a similar problem and opened an issue in GitHub, but he closed it, and his solution was not related to my setup: https://github.com/Supervisor/supervisor/issues/321

I read a bit further about an our-of-memory issue sending a SIGTERM, but my server does not run high on resources and has plenty of free memory.

What can I do to debug this issue better?

答:
The comment under the question is definitely a good answer:

Check /var/log/apt/history.log (ubuntu). I found out there was unattended-upgrade of supervisor.

In my case, I checked the timestamps of the SIGTERM in /var/log/supervisor/supervisord.log and Start-Date in /var/log/apt/history.log.  They were indeed the same time, which all but confirms the fact that auto updates were the problem here.

To turn those off, like in this tutorial, you can modify /etc/apt/apt.conf.d/10periodic to have the value:

```<code>APT::Periodic::Update-Package-Lists "0";
</code>```

Body:
The comment under the question is definitely a good answer:

Check /var/log/apt/history.log (ubuntu). I found out there was unattended-upgrade of supervisor.

In my case, I checked the timestamps of the SIGTERM in /var/log/supervisor/supervisord.log and Start-Date in /var/log/apt/history.log.  They were indeed the same time, which all but confirms the fact that auto updates were the problem here.

To turn those off, like in this tutorial, you can modify /etc/apt/apt.conf.d/10periodic to have the value:

APT::Periodic::Update-Package-Lists "0";


答:
With this statement blah.testMe() includes in the when(), it invokes the real method :

```<code>when(blah.testMe(Matchers.any())).thenReturn("intercepted");
</code>```

To avoid that, you should use the doReturn(...).when(...).methodToInvoke() pattern.

```<code>doReturn("intercepted").when(blah).testMe(Matchers.any()));
</code>```

You notice that with this syntax : the blah.testMe() statement is specified nowhere. So that is not called.

Beyond this question I think you don't need any spy to test this method.

Spying is a very particular tool in mocking that you use only when you don't have any choice : you need to mock the object under test which is a bad practice and you cannot refactor the actual code.

But here you can just do :

```<code>@Test
public void testTestMe(){
    Blah blah = new Blah();
    ArrayList<String> l = new ArrayList<String>();
    l.add("oopsie");
    assertEquals("hello oopsie",blah.testMe(l));
 }
</code>```

Title: Stubbing out method with ArrayList/List param fails when using any() or anyList()

Body:
With this statement blah.testMe() includes in the when(), it invokes the real method :

when(blah.testMe(Matchers.any())).thenReturn("intercepted");

To avoid that, you should use the doReturn(...).when(...).methodToInvoke() pattern.

doReturn("intercepted").when(blah).testMe(Matchers.any()));

You notice that with this syntax : the blah.testMe() statement is specified nowhere. So that is not called.

Beyond this question I think you don't need any spy to test this method.

Spying is a very particular tool in mocking that you use only when you don't have any choice : you need to mock the object under test which is a bad practice and you cannot refactor the actual code.

But here you can just do :

@Test
public void testTestMe(){
    Blah blah = new Blah();
    ArrayList<String> l = new ArrayList<String>();
    l.add("oopsie");
    assertEquals("hello oopsie",blah.testMe(l));
 }