问:
I am unable to install my project packages
I was getting error installing expressJs to my packages. I have had to do an npm cache clean --force no sucess, then I deleted my node_modules and package-lock.json, I try to reinstall packages using npm i I still got an error.

Now I deleted node.js from my pc windows 10 and downloaded and installed the latest node and tried to reinstall the project packages again. Now the error I get is this

```<code>$ npm i
npm ERR! Unexpected end of JSON input while parsing near '...ncies":{"autoprefixer'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Chioma Onyepere\AppData\Roaming\npm-cache\_logs\2019-05-28T20_26_29_676Z-debug.log
</code>```

My app is built on nextJs

Here's the package.json

```<code>{
  "name": "ratethis",
  "version": "1.0.2",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "now-build": "next build",
    "start": "next start -p %PORT%"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/infinity-web-development/ratethis"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/infinity-web-development/ratethis/issues"
  },
  "homepage": "https://github.com/infinity-web-development/ratethis#readme",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.15.1",
    "faker": "^4.1.0",
    "next": "^8.0.3",
    "next-images": "^1.1.1",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "now": "^15.0.6",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-polls": "^1.2.0",
    "react-redux": "^7.0.1",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.2",
    "shallow-equal": "^1.1.0",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-inline-import": "^3.0.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-react": "^7.11.1",
    "eslint-plugin-standard": "^4.0.0",
    "next-antd-aza-less": "^1.0.2"
  }
}
</code>```

Apparently error is from my pc cause it works just fine on another pc.

答:
I don't know much about npm, but I'd suggesting trying to have it verify the installs it's already done and somehow rewrite the package.json file from the existing installs.

https://docs.npmjs.com/cli/cache.html

Even though the install failed and the package.json doesn't show any traces of the install, there could be some artifact that only npm knows about that's getting in the way.

Body:
I was getting error installing expressJs to my packages. I have had to do an npm cache clean --force no sucess, then I deleted my node_modules and package-lock.json, I try to reinstall packages using npm i I still got an error.

Now I deleted node.js from my pc windows 10 and downloaded and installed the latest node and tried to reinstall the project packages again. Now the error I get is this

$ npm i
npm ERR! Unexpected end of JSON input while parsing near '...ncies":{"autoprefixer'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Chioma Onyepere\AppData\Roaming\npm-cache\_logs\2019-05-28T20_26_29_676Z-debug.log

My app is built on nextJs

Here's the package.json

{
  "name": "ratethis",
  "version": "1.0.2",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "now-build": "next build",
    "start": "next start -p %PORT%"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/infinity-web-development/ratethis"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/infinity-web-development/ratethis/issues"
  },
  "homepage": "https://github.com/infinity-web-development/ratethis#readme",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.15.1",
    "faker": "^4.1.0",
    "next": "^8.0.3",
    "next-images": "^1.1.1",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "now": "^15.0.6",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-polls": "^1.2.0",
    "react-redux": "^7.0.1",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.2",
    "shallow-equal": "^1.1.0",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-inline-import": "^3.0.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-react": "^7.11.1",
    "eslint-plugin-standard": "^4.0.0",
    "next-antd-aza-less": "^1.0.2"
  }
}

Apparently error is from my pc cause it works just fine on another pc.


来源: stackexchange

问:
Error when calling function from another function
I am having some trouble calling one function from inside another

Here is the code I have:

```<code>supported_timeframes = ['1m', '5m', '1h', '1d']
supported_indicators = ['SMA', ... ]
supported_sources = ['open', 'close']

indicator_values = {}

class Indicator:

    def __init__(self):
        self.indictor = ''      # indicator
        self.timeframe = ''     # timeframe
        self.period = 0         # look-back period
        self.source = ''        # open / close

    def error(self, indicator, timeframe, period, source):
        if timeframe not in supported_timeframes:
            return 'timeframe not supported --', 'supported
            timeframes:', supported_indicators
        if indicator not in supported_indicators:
            return 'indicator not found --', 'supported indicators:',
            supported_indicators
        if source not in supported_sources:
            return 'source is not -- open -- or -- close'
    else:
        pass

    def SMA(self, indicator, timeframe, period, source):
        error()

        # TODO get candle data from timeframe
        # TODO calc requested indicator from candle data and append to
        # indicator_values dict

        # return indicator
        for indicator in indicator_values:
            return indicator
</code>```

I have the function error first to check if wrong values have been entered into the parameters.

Then I want to call that function in def SMA(...) function because I am going to have many more functions that each calculate an indicator similar to the SMA one, so to keep things concise I am trying to call error() in each of them instead of copy and pasting the code within every time.

However when doing this, I get an error message within def SMA(...) that says error() is undefined.

Thank you so much in advance if you can help me out!

答:
Unless I'm missing something, you just need to add self where you are calling error()</p>

```<code>def SMA(self, indicator, timeframe, period, source):
        self.error()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having some trouble calling one function from inside another

Here is the code I have:

supported_timeframes = ['1m', '5m', '1h', '1d']
supported_indicators = ['SMA', ... ]
supported_sources = ['open', 'close']

indicator_values = {}

class Indicator:

    def __init__(self):
        self.indictor = ''      # indicator
        self.timeframe = ''     # timeframe
        self.period = 0         # look-back period
        self.source = ''        # open / close

    def error(self, indicator, timeframe, period, source):
        if timeframe not in supported_timeframes:
            return 'timeframe not supported --', 'supported
            timeframes:', supported_indicators
        if indicator not in supported_indicators:
            return 'indicator not found --', 'supported indicators:',
            supported_indicators
        if source not in supported_sources:
            return 'source is not -- open -- or -- close'
    else:
        pass

    def SMA(self, indicator, timeframe, period, source):
        error()

        # TODO get candle data from timeframe
        # TODO calc requested indicator from candle data and append to
        # indicator_values dict

        # return indicator
        for indicator in indicator_values:
            return indicator

I have the function error first to check if wrong values have been entered into the parameters.

Then I want to call that function in def SMA(...) function because I am going to have many more functions that each calculate an indicator similar to the SMA one, so to keep things concise I am trying to call error() in each of them instead of copy and pasting the code within every time.

However when doing this, I get an error message within def SMA(...) that says error() is undefined.

Thank you so much in advance if you can help me out!

Body:
Unless I'm missing something, you just need to add self where you are calling error()

def SMA(self, indicator, timeframe, period, source):
        self.error()


问:
UIAction with two delete buttons
I have an ActionSheets with 2 delete buttons, "delete all" and "delete selected item".

Since delete is an destructive behavior, should i definitely keep them as "destructive buttons" or can i keep them as normal buttons without any destructive button at all?

Advice would greatly help me.

Thanks

答:
If I were you I would make "delete all" the destructive button.

My anger level falls down quick after I have accidentally deleted one item. But if my whole dataset is gone you better stay away from me.

And there is no need to use the destructive button at all.

You can even start the destruction of the whole world with a normal button.

It might confuse your users, but it's okay to do so. Sometimes "delete all" isn't destructive enough to show the red button. It's up to you.

ContentLicense: CC BY-SA 3.0

Title: UIAction with two delete buttons


问:
What's the difference between PROC EXPORT, LIBNAME and ODS in exporting file?
Basically, I understood I can export files and data from SAS in three ways (PROC EXPORT, LIBNAME statement and ODS statement), but I really can't see the differences between them.

From what I understood, the PROC EXPORT let me export only data sets created using a DATA step, but not the results of the procedures.
Differently, LIBNAME and ODS statements allow this, but it seems there isn't a significant difference between them.

Is this correct? And if it's so, what's the main difference between the two statements?

答:
ODS redirects output from the procs directly to a different output format, such as PDF, Excel, Word or PowerPoint. This is more for generating automated reports that have styles and formatting which differentiates it from PROC EXPORT or LIBNAME.

PROC EXPORT exports raw data - no formatting or commenting - best used for data transfers.
LIBNAME is closer to export - you get more raw data extracted but not formatting in the data. I don't think there's a significant difference between PROC EXPORT and LIBNAME methods.


问:
Order files numerically in specific folder
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

```<code>        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();
</code>```

Windows Explore

Console Output

答:
This pads the first number section with zeroes for sorting purposes:</p>

```<code>string folder = @"C:\Testing";
var txtFiles = Directory.GetFiles(folder, "*.txt")
                        .Select(Path.GetFileName)
                        .OrderBy(f => f.Split('_')[0].PadLeft(5, '0'));

foreach (var f in txtFiles)
{
    Console.WriteLine(f);
}
</code>```

Body:
I have a folder which contains only .txt files. I want my output to have a certain order.

The first 2 digit of every filename is its unique ID. I want to order the files numerically in that order

I've researched multiple questions that seem similar to this like
Getting all file names from a folder using C#

but none has helped me accomplish this goal. What is the easiest way for me to get my desired output?

        string folder = @"C:\Testing\";
        var txtFiles = Directory.GetFiles(folder, "*.txt")
                                 .Select(Path.GetFileName)
                                 .ToList();
        foreach(var f in txtFiles)
        {
            Console.WriteLine(f);
        }
        Console.ReadKey();

Windows Explore

Console Output

Body:
This pads the first number section with zeroes for sorting purposes:

string folder = @"C:\Testing";
var txtFiles = Directory.GetFiles(folder, "*.txt")
                        .Select(Path.GetFileName)
                        .OrderBy(f => f.Split('_')[0].PadLeft(5, '0'));

foreach (var f in txtFiles)
{
    Console.WriteLine(f);
}


问:
Specifying trust store information in spring boot application.properties
I am using springBootVersion 1.2.0.RELEASE.
I'm trying to have my keystore and truststore configured through application.properties.

When I add the following settings, I can get the keystore to work, but not the truststore.

```<code>server.ssl.key-store=classpath:foo.jks
server.ssl.key-store-password=password
server.ssl.key-password=password
server.ssl.trust-store=classpath:foo.jks
server.ssl.trust-store-password=password
</code>```

However, if I add the truststore through gradle:

```<code>bootRun {
    jvmArgs = [ "-Djavax.net.ssl.trustStore=c://foo.jks", "-Djavax.net.ssl.trustStorePassword=password"]
}
</code>```

it works just fine.

Has anyone used the application.properties for trust stores?

答:
If you are in Spring, try just add properties for it (use needed properties), and it should work for total JVM</p>

```<code>javax:
  net:
    ssl:
      key-store-password: ${KEYSTORE_SECRET}
      key-store-type: PKCS12
      trust-store-password: ${TRUSTSTORE_SECRET}
      trust-store-type: PKCS12
</code>```

Body:
I am using springBootVersion 1.2.0.RELEASE.
I'm trying to have my keystore and truststore configured through application.properties.

When I add the following settings, I can get the keystore to work, but not the truststore.

server.ssl.key-store=classpath:foo.jks
server.ssl.key-store-password=password
server.ssl.key-password=password
server.ssl.trust-store=classpath:foo.jks
server.ssl.trust-store-password=password

However, if I add the truststore through gradle:

bootRun {
    jvmArgs = [ "-Djavax.net.ssl.trustStore=c://foo.jks", "-Djavax.net.ssl.trustStorePassword=password"]
}

it works just fine.

Has anyone used the application.properties for trust stores?

Body:
If you are in Spring, try just add properties for it (use needed properties), and it should work for total JVM

javax:
  net:
    ssl:
      key-store-password: ${KEYSTORE_SECRET}
      key-store-type: PKCS12
      trust-store-password: ${TRUSTSTORE_SECRET}
      trust-store-type: PKCS12


问:
Exception Unhanded - This was Nullpointer C++
I have two classes Display and Snake.
With the Display class I hols some functionality that involves creating buffer and etc.
I'm trying to do something that seem logical to me but apparently not to the compiler

cSnake.h

```<code>class Snake
{
public:
    Snake();
    void printSnake();
    ~Snake();

private:
    Display* display;

};
</code>```

cSnake.cpp

```<code>Snake::Snake()  {}

void Snake::printSnake() {
    display->PrintCharecter(40, 15, L"    Hello World   ");
}

Snake::~Snake() {}
</code>```

This is the Display class

```<code>Class Display{
public:
void CreateScreenBuffer();
void DisplayFrame();
void PrintCharecter(int x, int y LPCWSTR text);
private:
int nScreenWidth;
int nScreenHeight;
wchar_t *screen;
}
</code>```

```<code>// The function that I try to call
void Display::PrintCharecter(int x, int y, LPCWSTR text) {
    wsprintf(&screen[y* nScreenWidth + x], text); // exception is thrown here
}
</code>```

Calling it in the main

```<code>Snake snake
snake.printSnake();
</code>```

Then it throws unhanded exception that.
Being NULL pointer. I bit confused here, which one the NULL pointer is it the function call or the array screen?

答:
The error is that the Display pointer points to nothing, which is an uninitialized pointer. A pointer only stores the address of the memory, not the actual memory. Therefore you have only created a pointer, but not the memory it points to on the heap. This means that in your constructor, you should create a new display object on the heap and assign that to your pointer.

```<code>Snake::Snake()
{
    display = new Display;
}
</code>```

This will give you your expected behaviour.
It's also important to note that you must delete the memory the pointer points to otherwise it will just float there until the program ends. Therefore your Snake destructor should delete display:

```<code>Snake::~Snake()
{
    delete display;
}
</code>```

Body:
I have two classes Display and Snake.
With the Display class I hols some functionality that involves creating buffer and etc.
I'm trying to do something that seem logical to me but apparently not to the compiler

cSnake.h

class Snake
{
public:
    Snake();
    void printSnake();
    ~Snake();

private:
    Display* display;

};

cSnake.cpp

Snake::Snake()  {}

void Snake::printSnake() {
    display->PrintCharecter(40, 15, L"    Hello World   ");
}

Snake::~Snake() {}

This is the Display class

Class Display{
public:
void CreateScreenBuffer();
void DisplayFrame();
void PrintCharecter(int x, int y LPCWSTR text);
private:
int nScreenWidth;
int nScreenHeight;
wchar_t *screen;
}

// The function that I try to call
void Display::PrintCharecter(int x, int y, LPCWSTR text) {
    wsprintf(&screen[y* nScreenWidth + x], text); // exception is thrown here
}

Calling it in the main

Snake snake
snake.printSnake();

Then it throws unhanded exception that.
Being NULL pointer. I bit confused here, which one the NULL pointer is it the function call or the array screen?

Body:
The error is that the Display pointer points to nothing, which is an uninitialized pointer. A pointer only stores the address of the memory, not the actual memory. Therefore you have only created a pointer, but not the memory it points to on the heap. This means that in your constructor, you should create a new display object on the heap and assign that to your pointer.

Snake::Snake()
{
    display = new Display;
}

This will give you your expected behaviour.
It's also important to note that you must delete the memory the pointer points to otherwise it will just float there until the program ends. Therefore your Snake destructor should delete display:

Snake::~Snake()
{
    delete display;
}


问:
Error parsing JSON with escaped quotes inside single quotes
I have a variable var jsonData = '{"Key":"query","Value":"dept=\"Human Resources*\"","ValueType":"Edm.String"}';

I'm trying to parse the variable with JSON.parse(jsonData), however, I'm getting an error "Unexpected token H in JSON at position 30." I can't change how the variable is returned, so here's what I think I understand about the problem:

The JSON.parse(jsonData) errors out because it's not recognizing the escaped double quotes as escaped since it is fully enclosed in single quotes

jsonData.replace(/\\"/g, "\\\\"") or other combinations that I've tried aren't finding the \" because javascript treats \" as just "

QUESTION How can I parse this properly, by either replacing the escaped quotes with something JSON.parse() can handle or using something else to parse this correctly? I'd like to stick with JSON.parse() on account of it's simplicity, but open to other options.

EDIT: Unfortunately I can't change the variable at this stage, it is just a small example of a larger JSON response. This is a temporary solution until the app is granted access to the API, but I needed the solution in the interim until that happens (IT dept can be slow). What I'm doing now its getting a large JSON response back by hitting the API address directly and the browser uses the cookies from the user OAuth for authentication. I then copy and paste the JSON response into my application so I can work with the data. The response is riddled with the escaped quotes and manually editing the text would be laborious and I'm trying to avoid copying into text processor before copying into the variable.

答:
I think you can also dispense with the initial String to represent the JSON object:

Use a standard JSON object.

Make whatever changes you need on that object.

Call JSON.stringify(YOUR_OBJECT) for a String representation.

Then, JSON.parse(…) when you need an object again.

That should be able to satisfy your initial request, question, keep your current (escaped) String values, and give you some room to make a lot of changes.

To escape your current String value:

obj["Value"] = 'dept=\"Human Resources*\"'

Alternatively, you can nest attributes:

obj["Value"]["dept"] = "Human Resources*"

Which may be helpful for other reasons.

I've found that I've rarely worked with JSON in an enterprise or production environment where the above sequence wasn't used (I've never used a purely string representation in a production environment) simply due to the ease of modifying attributes, generating dynamic data/modifying the JSON object, and actually using the JSON programmatically.

Using string representations for what are really attribute key-value pairings often causes headaches later on (for example, when you want to read the Human Resources* value programmatically and use it).

I hope you find that approach helpful!


问:
Array not returning an answer in For loop
I have an array that takes in values from a single row of a spreadsheet (1 row, 185 columns). I then want to loop through the array, looking for a match between the values in the array, and values in a particular cell.

However, every time I run the code, it says it finds a match, but does not return a value to the cell.

The relevant lines of the code are:

```<code>
Dim qCountry()

Worksheets("Data").Activate

    qCountry = Range("A1:GC1").Value
</code>```

```<code>    For i = 1 To 185
          If Cells(aRow, bCol) <> vbNullString Then
              Exit For
          ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
              Cells(aRow, bCol) = qCountry(i)
          End If
    Next i
</code>```

A screenshot of my array:

答:
Values can be accessed as shown in the screenshot :</p>

```<code>Cells(aRow, bCol) = qCountry(1, i)
</code>```

Body:
I have an array that takes in values from a single row of a spreadsheet (1 row, 185 columns). I then want to loop through the array, looking for a match between the values in the array, and values in a particular cell.

However, every time I run the code, it says it finds a match, but does not return a value to the cell.

The relevant lines of the code are:

Dim qCountry()

Worksheets("Data").Activate

    qCountry = Range("A1:GC1").Value

    For i = 1 To 185
          If Cells(aRow, bCol) <> vbNullString Then
              Exit For
          ElseIf InStr(1, Cells(aRow, 4), "*" & qCountry(i) & "*") = 1 Then
              Cells(aRow, bCol) = qCountry(i)
          End If
    Next i

A screenshot of my array:

Body:
Values can be accessed as shown in the screenshot :

Cells(aRow, bCol) = qCountry(1, i)


问:
How to get a callback when every observer of a hot like ConnectableObservable complete?
I am searching for a doOn... callback for a ConnectableObservable that is invoked when every observer terminates

```<code>       val gatewayItems = viewModel.getGatewayItems(gateways!!)
                .observeOn(Schedulers.io())
                .take(1)
                .publish()
                .autoConnect(2)

            gatewayItems.subscribe { sharedGateways -> sharedGatewaysAdapter.submitList(sharedGateways) }

            gatewayItems.subscribe { sharedGateways -> privateGatewaysAdapter.submitList(privateGateways) }
</code>```

I would like to get a callback to my multicasted hot observable when both of my observers signal a terminal event

I have tried to put doOnTerminate and doOnComplete operators on my parent multicasted observable but, it seems that these callbacks are invoked 2 times (one for each observer)

答:
```<code>   val gatewayItems = viewModel.getGatewayItems(gateways!!)
            .observeOn(Schedulers.io())
            .take(1)
            .doOnComplete { ... }
            .doOnTerminate { ... }
            .publish()
            .autoConnect(2)
</code>```

Both .doOnComplete and .doOnTerminate work for me.

Edit: the chances are you might be attaching the do... operators in incorrect order. For example, neither of these doOnComplete will work:

```<code>   val gatewayItems = viewModel.getGatewayItems(gateways!!)
            .observeOn(Schedulers.io())
            .doOnComplete { ... }
            .take(1)
            .publish()
            .autoConnect(2)
            .doOnComplete { ... }
</code>```

Body:
I am searching for a doOn... callback for a ConnectableObservable that is invoked when every observer terminates

       val gatewayItems = viewModel.getGatewayItems(gateways!!)
                .observeOn(Schedulers.io())
                .take(1)
                .publish()
                .autoConnect(2)

            gatewayItems.subscribe { sharedGateways -> sharedGatewaysAdapter.submitList(sharedGateways) }

            gatewayItems.subscribe { sharedGateways -> privateGatewaysAdapter.submitList(privateGateways) }

I would like to get a callback to my multicasted hot observable when both of my observers signal a terminal event

I have tried to put doOnTerminate and doOnComplete operators on my parent multicasted observable but, it seems that these callbacks are invoked 2 times (one for each observer)

Body:
   val gatewayItems = viewModel.getGatewayItems(gateways!!)
            .observeOn(Schedulers.io())
            .take(1)
            .doOnComplete { ... }
            .doOnTerminate { ... }
            .publish()
            .autoConnect(2)

Both .doOnComplete and .doOnTerminate work for me.

Edit: the chances are you might be attaching the do... operators in incorrect order. For example, neither of these doOnComplete will work:

   val gatewayItems = viewModel.getGatewayItems(gateways!!)
            .observeOn(Schedulers.io())
            .doOnComplete { ... }
            .take(1)
            .publish()
            .autoConnect(2)
            .doOnComplete { ... }


问:
How do I make a right aligned text move to new line when switched to mobile view
I have a div which has two spans which are left and right aligned respectively. On switching to mobile view, the right aligned text should move to next line.

```<code><div align="left">
    <span style="float: left;">Receipt No:</span>
    <span style="float: right";>#1111</spa>
</div>
</code>```

when switched to mobile view, #1111 should be under Receipt No: text.

答:
Something like this, where 480px is mobile view. You can tweak this to your liking.

.number {
  display: inline-block;
  float: right;
}

@media only screen and (max-width: 480px) {
  .number {
    display: block;
    float: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div align="left">
    <span>Receipt No:</span>
    <span class="number">#1111</spa>
</div></code>```

Body:
I have a div which has two spans which are left and right aligned respectively. On switching to mobile view, the right aligned text should move to next line.

    Receipt No:
    #1111</spa>

when switched to mobile view, #1111 should be under Receipt No: text.

Body:
Something like this, where 480px is mobile view. You can tweak this to your liking.

.number {
  display: inline-block;
  float: right;
}

@media only screen and (max-width: 480px) {
  .number {
    display: block;
    float: none;
  }
}

<div align="left">
    <span>Receipt No:</span>
    <span class="number">#1111</spa>
</div>


答:
This is happening because your span is not display: block.

I assume when that line breaks to the next line, you'll want it left aligned and beneath, not beneath and still right aligned.

I suggest using media queries. I do not suggest trying to use media queries inline, so you'll want to move your CSS into your

```<code><html>
<head>
<meta name='viewport' content="width=device-width, initial-scale=1" />
<style>
.alignleft {align: left;}
.floatleft {float: left;}
.floatright {float: right;}
@media only screen and (min-resolution: 117dpi) and (max-resolution: 119dpi), only screen and (min-resolution: 131dpi) and (max-resolution: 133dpi), only screen and (min-resolution: 145dpi) and (max-resolution: 154dpi), only screen and (min-resolution: 162dpi) and (max-resolution: 164dpi), only screen and (min-resolution: 169dpi) {
    .mobilebreak {display: block; float: left;}
}
</style>
</head>
<body>
<div class="alignleft">
<span class="floatleft">Receipt No:</span>
<span class="floatright mobilebreak">#1111</span>
</div>
</body>
</html>
</code>```

Title: How do I make a right aligned text move to new line when switched to mobile view

Body:
This is happening because your span is not display: block.

I assume when that line breaks to the next line, you'll want it left aligned and beneath, not beneath and still right aligned.

I suggest using media queries. I do not suggest trying to use media queries inline, so you'll want to move your CSS into your <head>

<html>
<head>
<meta name='viewport' content="width=device-width, initial-scale=1" />
<style>
.alignleft {align: left;}
.floatleft {float: left;}
.floatright {float: right;}
@media only screen and (min-resolution: 117dpi) and (max-resolution: 119dpi), only screen and (min-resolution: 131dpi) and (max-resolution: 133dpi), only screen and (min-resolution: 145dpi) and (max-resolution: 154dpi), only screen and (min-resolution: 162dpi) and (max-resolution: 164dpi), only screen and (min-resolution: 169dpi) {
    .mobilebreak {display: block; float: left;}
}
</style>
</head>
<body>
<div class="alignleft">
<span class="floatleft">Receipt No:</span>
<span class="floatright mobilebreak">#1111</span>
</div>
</body>
</html>


问:
how to access the struct?
```<code>struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  result->number // undefined symbol
}
</code>```

how to access the struct result inside the function findLongestSeq?

thanks

答:
```<code>struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  struct result result;
  result.number = 0;
  result.length = 42;
  return result;
}
</code>```

If you are dealing with struct result foo then you access its members via foo.number.
If however you are dealing with a pointer to foo (struct result *foo) then you access its members via foo->number.

If you were to manually allocate your result struct via

```<code>struct result *result = (struct result *)malloc(sizeof (struct result));
</code>```

Then you'd have to access its members via result->number (and would be responsible for freeing it once not used anymore).

Further more I'd rather use this for the sake of better readability:

```<code>typedef struct {
  int number;
  int length;
} ResultStruct;
</code>```

This way you can then use ResultStruct result; instead of redundant and verbose struct result result;.

Title: how to access the struct?

Body:
struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  result->number // undefined symbol
}

how to access the struct result inside the function findLongestSeq?

thanks

Body:
struct result {
  int number;
  int length;
};

struct result findLongestSeq(int intarray[], int size) {
  struct result result;
  result.number = 0;
  result.length = 42;
  return result;
}

If you are dealing with struct result foo then you access its members via foo.number.
If however you are dealing with a pointer to foo (struct result *foo) then you access its members via foo->number.

If you were to manually allocate your result struct via

struct result *result = (struct result *)malloc(sizeof (struct result));

Then you'd have to access its members via result->number (and would be responsible for freeing it once not used anymore).

Further more I'd rather use this for the sake of better readability:

typedef struct {
  int number;
  int length;
} ResultStruct;

This way you can then use ResultStruct result; instead of redundant and verbose struct result result;.


问:
Is there a way to generate PDF in landscape orientation while accesing reports through URL?
I am accessing report using URL like this

```<code>< reportServerAddress >/ReportServer?%2f< reportName >&< parameter >=< value >&rs:Command=Render&rc:Parameters=false&rc:Toolbar=false&rs:Format=pdf
</code>```

While in standard HTML form report is displayed properly,
in PDF format it defaults to portrait orientation (page setting are 297mm width and 210mm height).

I wasn't able to find a way to pass orientation by some parameter to the server.

Is there a way to generate report in landscape mode pdf using URLs?

I would rather not use SOAP API but will using it allow me to do so?

答: The orientation is defined by the report properties. It can not be set dynamically. So you'll need to change the Page Size, swap the Height and Width. If you want to be able to use both orientations, you'll need two separate copies of the report.

Body:
I am accessing report using URL like this

< reportServerAddress >/ReportServer?%2f< reportName >&< parameter >=< value >&rs:Command=Render&rc:Parameters=false&rc:Toolbar=false&rs:Format=pdf

While in standard HTML form report is displayed properly,
in PDF format it defaults to portrait orientation (page setting are 297mm width and 210mm height).

I wasn't able to find a way to pass orientation by some parameter to the server.

Is there a way to generate report in landscape mode pdf using URLs?

I would rather not use SOAP API but will using it allow me to do so?


问:
Count total number of matches in directory with ag
I'm attempting to find the number of matches for a given string across a large project. Currently, to do this with ag I am using the following command:

```<code>$ echo 0$(ag -c searchterm | sed -e "s/^.*:/+/") | bc
</code>```

which is obviously a bit lengthy and not very intuitive. Is there any better way to get the total number of matches in a directory from ag? I've dug through the documentation and couldn't find anything helpful there.

Edit: Thanks to a recent commit to ag, the filenames can be stripped with ag instead of sed, so this also works:

```<code>$ echo `ag test -c --nofilename | sed "s/$/+/"`0 | bc
</code>```

Note: I realize I could do this with ack -hcl searchterm (Well, almost. In my specific case I'd need an --ignore-dir building in there as well), but as this is already a large project (and will be growing considerably), the speed boost offered by ag makes it preferable (ack takes about 3 seconds for my searches vs ag's nearly instantaneous result), so I would like to stick with it.

答:
ag -o --nofilename --nobreak 'searchstring' | wc -l

-o prints each match individually

--nofilename removes filenames from output

--nobreak removes newlines between matches in different files

Body:
I'm attempting to find the number of matches for a given string across a large project. Currently, to do this with ag I am using the following command:

$ echo 0$(ag -c searchterm | sed -e "s/^.*:/+/") | bc

which is obviously a bit lengthy and not very intuitive. Is there any better way to get the total number of matches in a directory from ag? I've dug through the documentation and couldn't find anything helpful there.

Edit: Thanks to a recent commit to ag, the filenames can be stripped with ag instead of sed, so this also works:

$ echo `ag test -c --nofilename | sed "s/$/+/"`0 | bc

Note: I realize I could do this with ack -hcl searchterm (Well, almost. In my specific case I'd need an --ignore-dir building in there as well), but as this is already a large project (and will be growing considerably), the speed boost offered by ag makes it preferable (ack takes about 3 seconds for my searches vs ag's nearly instantaneous result), so I would like to stick with it.


问:
how do you style (big) short-circuit assignment in javascripts?
imagine that you have this line:

var result = content['aPossbileValue'] || $el.data('root-path') + content.type +  '/something/' + content.slug;
```

<p>The line length is too long, so i wonder how can i improve this? </p>

<p>Possible options:</p>

<pre class="lang-js prettyprint-override"><code>var result = content['aPossbileValue']
  || $el.data('root-path') + content.type + '/something/' + content.slug;
</code>```

var result = content['aPossbileValue'] ||
             $el.data('root-path') + content.type + '/something/' + content.slug;
```

<pre class="lang-js prettyprint-override"><code>var result = content['aPossbileValue']
             || $el.data('root-path') + content.type + '/something/' + content.slug
</code>```

Or maybe it's considered a bad practice!

let me know your opinion ^^!

答:
Using variables with descriptive name are more readable than long and complex lines. In your case, this would be better:</p>

```<code>var customPath = $el.data('root-path') + type + '/something/' + slug;
var result = content['aPossibleValue'] || customPath;
</code>```

Body:
imagine that you have this line:

var result = content['aPossbileValue'] || $el.data('root-path') + content.type +  '/something/' + content.slug;

The line length is too long, so i wonder how can i improve this?

Possible options:

var result = content['aPossbileValue']
  || $el.data('root-path') + content.type + '/something/' + content.slug;

var result = content['aPossbileValue'] ||
             $el.data('root-path') + content.type + '/something/' + content.slug;

var result = content['aPossbileValue']
             || $el.data('root-path') + content.type + '/something/' + content.slug

Or maybe it's considered a bad practice!

let me know your opinion ^^!

Body:
Using variables with descriptive name are more readable than long and complex lines. In your case, this would be better:

var customPath = $el.data('root-path') + type + '/something/' + slug;
var result = content['aPossibleValue'] || customPath;


问:
Formatting PSCustomObject for conversion to JSON
I'm attempting to create a PSCustomObject that will later be piped through ConvertTo-JSON, but I can't seem to get the formatting of the PSCustomObject quite right. The issue seems to be that the way I want my resultant JSON to be formatted includes a jagged array, but the proper Powershell syntax eludes me.

Here's what I have

```<code>$RetrievalParamsBodyObj = [PSCustomObject]@{
    things = @(@{
                field="date_created"
                operator="within"
                value="7"
            })
    }
</code>```

When I pass that through ConvertTo-JSON, it looks like this:

```<code>$RetrievalParamsBodyObj | ConvertTo-JSON
{
    "things": [
        {
             "field":  "date_created",
             "operator":  "within",
             "value":  "7"
         }
     ]
}

</code>```

But I want it to look like this:

```<code>{
    "things": [
        [{
            "field": "date_created",
            "operator": "within last",
            "value": "7"
        }]
    ]
}
</code>```

I've tried wrapping an additional array around the hash table, but that didn't seem to have any effect.

答:
Two tricks: 1) preface the internal array with a comma so Powershell knows it's a nested array instead of a concatenated one, and 2) make sure to set the Depth: </p>

```<code>[PSCustomObject]@{
    things = @(,@(@{
                field="date_created"
                operator="within"
                value="7"
            }))
    } | ConvertTo-Json -Depth 5
</code>```

<p>Output: </p>

```<code>{
    "things":  [
                   [
                       {
                           "field":  "date_created",
                           "operator":  "within",
                           "value":  "7"
                       }
                   ]
               ]
}
</code>```

<p>... which is syntactically identical to your desired output. To get it formatted differently you would need to create a custom JSON serializer. </p>

Body:
I'm attempting to create a PSCustomObject that will later be piped through ConvertTo-JSON, but I can't seem to get the formatting of the PSCustomObject quite right. The issue seems to be that the way I want my resultant JSON to be formatted includes a jagged array, but the proper Powershell syntax eludes me.

Here's what I have

$RetrievalParamsBodyObj = [PSCustomObject]@{
    things = @(@{
                field="date_created"
                operator="within"
                value="7"
            })
    }

When I pass that through ConvertTo-JSON, it looks like this:

$RetrievalParamsBodyObj | ConvertTo-JSON
{
    "things": [
        {
             "field":  "date_created",
             "operator":  "within",
             "value":  "7"
         }
     ]
}

But I want it to look like this:

{
    "things": [
        [{
            "field": "date_created",
            "operator": "within last",
            "value": "7"
        }]
    ]
}

I've tried wrapping an additional array around the hash table, but that didn't seem to have any effect.

Body:
Two tricks: 1) preface the internal array with a comma so Powershell knows it's a nested array instead of a concatenated one, and 2) make sure to set the Depth:

[PSCustomObject]@{
    things = @(,@(@{
                field="date_created"
                operator="within"
                value="7"
            }))
    } | ConvertTo-Json -Depth 5

Output:

{
    "things":  [
                   [
                       {
                           "field":  "date_created",
                           "operator":  "within",
                           "value":  "7"
                       }
                   ]
               ]
}

... which is syntactically identical to your desired output. To get it formatted differently you would need to create a custom JSON serializer.


问:
Python 3.x/json package cannot convert this json string to list
I have this string which I wanted to convert to a list:

```<code>"{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"
</code>```

I tried json.loads() and it is giving me this error:

```<code>JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</code>```

It is coming from another program and I cannot control the quoting... single or double quote

Environment: Python 3.x with import json

My code:

```<code>mystr =  "{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"
mylist = json.loads(mystr)
</code>```

I expected it to be a valid list

答:
Your string is not a valid JSON.

The following should do the trick:

```<code>import json

mystr =  "{'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}"
mydict = json.loads(mystr.replace("'", "\""))
print(mydict)

>>> {'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}
</code>```

Body:
I have this string which I wanted to convert to a list:

"{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"

I tried json.loads() and it is giving me this error:

JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

It is coming from another program and I cannot control the quoting... single or double quote

Environment: Python 3.x with import json

My code:

mystr =  "{'Attributes': {'a', 'b', 'h'}, 'Group3': {'c'}, 'Group2': {'s', 'm', 'r', 'ac'}}"
mylist = json.loads(mystr)

I expected it to be a valid list

Body:
Your string is not a valid JSON.

The following should do the trick:

import json

mystr =  "{'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}"
mydict = json.loads(mystr.replace("'", "\""))
print(mydict)

>>> {'Attributes': ['a', 'b', 'h'], 'Group3': ['c'], 'Group2': ['s', 'm', 'r', 'ac']}


问:
GCP: What is the best option to setup a periodic Data pipeline from Spanner to Big Query
Task: We have to setup a periodic sync of records from Spanner to Big Query. Our Spanner database has a relational table hierarchy.

Option Considered I was thinking of using Dataflow templates to setup this data pipeline.

Option1: Setup a job with Dataflow template 'Cloud Spanner to Cloud Storage Text' and then another with Dataflow template 'Cloud Storage
Text to BigQuery'. Con: The first template works only on a single table and we have many tables to export.

Option2: Use 'Cloud Spanner to Cloud Storage Avro' template which exports the entire database. Con: I only need to export selected tables within a database and I don't see a template to import Avro into Big Query.

Questions: Please suggest what is the best option for setting up this pipeline

答:
There is currently no off-the-shelf parameterized direct export from Cloud Spanner to BigQuery.

To meet your requirements, a custom dataflow job (spanner dataflow connector, dataflow templates) scheduled periodically (1, 2) would be the best bet.  Incremental exports would require implementing change tracking in you database which can be done with commit timestamps.

For a no-code solution, you would have to relax your requirements and bulk export all tables periodically to Cloud Storage and bulk import them periodically into BigQuery. You could use a combination of a periodic trigger of an export from Cloud Spanner to Cloud Storage and schedule a periodic import from Cloud Storage to BigQuery.


问:
How to handle a fluent interface where each step can be a terminal operation?
I am building a fluent API that roughly works like this (assuming a class Person with a getter getId exists that returns a Long):

```<code>String result = context.map(Person::getId)
     .pipe(Object::toString)
     .pipe(String::toUpperCase)
     .end(Function.identity())
</code>```

As you can see only the .end-function acts a terminal operator. This clutters the overall usage of said API as I often have to end in a .end(Function.identity())-call even though the preceding .pipe-call already has the right type.

Is there any way to make a fluent-API that enables a part of it to be both a terminal operator and a 'bridge-operator'? I just dont want to clutter the API with specialized  pipe-variants like pipeTo (a pipe that only accepts a Function<CurrentType, ExpectedType> and internally calls .end)that emulate said behaviour as it forces the user to think about a very specific part of the API that seems unnecessary to me.

EDIT:
A simplified context-implementation as requested:

```<code>class Context<InType, CurrentType, TargetType> {
    private final Function<InType, CurrentType> getter;

    public Context(Function<InType, CurrentType> getter) {
        this.getter = getter;
    }

    public <IntermediateType> Context<InType, IntermediateType, TargetType>
    pipe(Function<CurrentType, IntermediateType> mapper) {

        return new Context<>(getter.andThen(mapper));
    }

    public Function<InType, TargetType> end(Function<CurrentType, TargetType> mapper) {
        return getter.andThen(mapper);
    }
}

//usage
Function<Person, String> mapper = new Context<Person, Long, String>(Person::getId)
    .pipe(Object::toString)
    .pipe(String::toUpperCase)
    .end(Function.identity());

mapper.apply(new Person(...))
</code>```

答:
The main problem I had was that any pipe step could be a terminal operation. As outlined in the discussions below each answer and the main post: using a function with the same name twice and one being a terminal operation just is not possible in java.

I banged my head against this problem and tried multiple approaches each of which did not work. Thats when I realized what I am doing is essentially the same as Javas Stream-API: you have an origin (source), do some fancy stuff (pipe) and then end (collect). If we apply the same scheme to my question there is no need for pipe to be a terminal operation, we just need another operation (e.g. end) which serves as the end point. As I had some extended requirements on when end is possible (the current type must match another type) I implemented end by only allowing a context specific funtion for which there is only one sane implementation available (hard to explain). Here is an example of the current implementation (pipe has since been renamed to map and end to to):

```<code>Mapper<Person, PersonDTO> mapper = Datus.forTypes(Person.class, PersonDTO.class).immutable(PersonDTO::new)
    .from(Person::getFirstName).to(ConstructorParameter::bind)
    .from(Person::getLastName)
        .given(Objects::nonNull, ln -> ln.toUpperCase()).orElse("fallback")
        .to(ConstructorParameter::bind)
    .build();
</code>```

As you can see .to acts as the terminal operator and ConstructorParameter::bind would complain about a type mismatch if the current type would not match the expected type.

See here for the to part, here for an implementation of ConstructorParameter and here how it is defined.

Body:
I am building a fluent API that roughly works like this (assuming a class Person with a getter getId exists that returns a Long):

String result = context.map(Person::getId)
     .pipe(Object::toString)
     .pipe(String::toUpperCase)
     .end(Function.identity())

As you can see only the .end-function acts a terminal operator. This clutters the overall usage of said API as I often have to end in a .end(Function.identity())-call even though the preceding .pipe-call already has the right type.

Is there any way to make a fluent-API that enables a part of it to be both a terminal operator and a 'bridge-operator'? I just dont want to clutter the API with specialized  pipe-variants like pipeTo (a pipe that only accepts a Function<CurrentType, ExpectedType> and internally calls .end)that emulate said behaviour as it forces the user to think about a very specific part of the API that seems unnecessary to me.

EDIT:
A simplified context-implementation as requested:

class Context<InType, CurrentType, TargetType> {
    private final Function<InType, CurrentType> getter;

    public Context(Function<InType, CurrentType> getter) {
        this.getter = getter;
    }

    public <IntermediateType> Context<InType, IntermediateType, TargetType>
    pipe(Function<CurrentType, IntermediateType> mapper) {

        return new Context<>(getter.andThen(mapper));
    }

    public Function<InType, TargetType> end(Function<CurrentType, TargetType> mapper) {
        return getter.andThen(mapper);
    }
}

//usage
Function<Person, String> mapper = new Context<Person, Long, String>(Person::getId)
    .pipe(Object::toString)
    .pipe(String::toUpperCase)
    .end(Function.identity());

mapper.apply(new Person(...))

Body:
The main problem I had was that any pipe step could be a terminal operation. As outlined in the discussions below each answer and the main post: using a function with the same name twice and one being a terminal operation just is not possible in java.

I banged my head against this problem and tried multiple approaches each of which did not work. Thats when I realized what I am doing is essentially the same as Javas Stream-API: you have an origin (source), do some fancy stuff (pipe) and then end (collect). If we apply the same scheme to my question there is no need for pipe to be a terminal operation, we just need another operation (e.g. end) which serves as the end point. As I had some extended requirements on when end is possible (the current type must match another type) I implemented end by only allowing a context specific funtion for which there is only one sane implementation available (hard to explain). Here is an example of the current implementation (pipe has since been renamed to map and end to to):

Mapper<Person, PersonDTO> mapper = Datus.forTypes(Person.class, PersonDTO.class).immutable(PersonDTO::new)
    .from(Person::getFirstName).to(ConstructorParameter::bind)
    .from(Person::getLastName)
        .given(Objects::nonNull, ln -> ln.toUpperCase()).orElse("fallback")
        .to(ConstructorParameter::bind)
    .build();

As you can see .to acts as the terminal operator and ConstructorParameter::bind would complain about a type mismatch if the current type would not match the expected type.

See here for the to part, here for an implementation of ConstructorParameter and here how it is defined.


问:
Why does the media query which works in devtools "toggle device toolbar" mode doesn't work in Chrome browser?
There is no problem when examining the part of my code related to media query in devtools "toggle device toolbar" mode. But after closing the preview, I found that the code didn't work  in browser. Why is this happening? I think it's related to Chrome browser. Because my code is working properly in Firefox.

```<code>// Main CSS

div#top-header {
    grid-area: theader;
    background-color: #FA6938;
    display: flex;
    padding: 0 5px;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: flex-start;
    justify-content: flex-start;
}

// This is still working

@media screen and (min-width: 600px) { div#top-header { padding: 0 15px; } }

// This code is running in "toggle device toolbar" mode but not running when I close the preview

@media screen and (min-width: 1120px) { div#top-header { padding: 0 14%; } }
</code>```

答:
Do you have

```<code><meta name="viewport" content="width=device-width">
</code>```

In the 'head' of your html ?

Body:
There is no problem when examining the part of my code related to media query in devtools "toggle device toolbar" mode. But after closing the preview, I found that the code didn't work  in browser. Why is this happening? I think it's related to Chrome browser. Because my code is working properly in Firefox.

// Main CSS

div#top-header {
    grid-area: theader;
    background-color: #FA6938;
    display: flex;
    padding: 0 5px;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: flex-start;
    justify-content: flex-start;
}

// This is still working

@media screen and (min-width: 600px) { div#top-header { padding: 0 15px; } }

// This code is running in "toggle device toolbar" mode but not running when I close the preview

@media screen and (min-width: 1120px) { div#top-header { padding: 0 14%; } }

Body:
Do you have

<meta name="viewport" content="width=device-width">

In the 'head' of your html ?


问:
Doctrine query using findBy and update entity
I am fairly new to Doctrine2 and I am trying to learn how to query entities and updating them.

The method I am using to query is the findBy method on a specific attribute to search for a list of records in the database, "my query returns a list of objects". Now I want to update a few of the attributes in the entity which I can not get working. Here is what I have:

```<code>  /** Set the search attributes for hls**/
    $id = array("itemNbr" => $itemNbr);
    $hls = $this->emInstance->getRepository('entity\\Hls')->findBy($id);

    // on update hls
    foreach($hls as $h){

        $h->setAllRd($Rd);
        $h->setRdy($Rdy);
        $h->setNo($no);
        var_dump($h);
    }
    $this->emInstance->flush();
    var_dump($statHdr);
</code>```

It gets to the first var dump in the loop which returns a list of objects
but does not get to the second var dump because of using flush. if I perform without the flush method the attributes show the updated info in var_dump but just will not actually commit the updates since flush is not working. What am I doing wrong.

Also, the id's for the entity is id, and itemCnt

答:
The solution is as follows: </p>

```<code>$crack = $em->getRepository('CrackBundle:Crack')->findBy(array('id' => 1 ));
 foreach ($crack as $c) {
 $c->setName('Nilton');
 $em->persist($c);
 $em->flush();
 }
</code>```

Body:
I am fairly new to Doctrine2 and I am trying to learn how to query entities and updating them.

The method I am using to query is the findBy method on a specific attribute to search for a list of records in the database, "my query returns a list of objects". Now I want to update a few of the attributes in the entity which I can not get working. Here is what I have:

  /** Set the search attributes for hls**/
    $id = array("itemNbr" => $itemNbr);
    $hls = $this->emInstance->getRepository('entity\\Hls')->findBy($id);

    // on update hls
    foreach($hls as $h){

        $h->setAllRd($Rd);
        $h->setRdy($Rdy);
        $h->setNo($no);
        var_dump($h);
    }
    $this->emInstance->flush();
    var_dump($statHdr);

It gets to the first var dump in the loop which returns a list of objects
but does not get to the second var dump because of using flush. if I perform without the flush method the attributes show the updated info in var_dump but just will not actually commit the updates since flush is not working. What am I doing wrong.

Also, the id's for the entity is id, and itemCnt

Body:
The solution is as follows:

$crack = $em->getRepository('CrackBundle:Crack')->findBy(array('id' => 1 ));
 foreach ($crack as $c) {
 $c->setName('Nilton');
 $em->persist($c);
 $em->flush();
 }


问:
java: convert a string to a string that contains the hex number of each character
I have a string that actually each byte in it is a representation of a hexadecimal number.

I want to create a new string that contains the actual hexadecimal numbers of each character.

I know that i can do String.getBytes() to get the bytes of each character, i know iterate through it with i=0;i<=String.getBytes().length. what i don't understand is how to create a new string that each character is the hexacdecimal number (0-F).

thanks!

答:
There are a few misconceptions - or at least problematic descriptions - in your post:

Strings consist of characters, not bytes

Numbers aren't hexadecimal or decimal etc; their representations are hex etc

You're then calling String.getBytes(), but it's not clear what encoding you want to use. As stated before, a String is a sequence of characters. To convert that into bytes, you need to apply an encoding. Unfortunately, String.getBytes() uses the "platform default encoding" which is almost never a good choice. You should always specify which encoding you want to use.

When you have converted the String into bytes (if you definitely want to do that) it's easy to convert that to hex:

```<code>for (byte b : test.getBytes("UTF-8"))
{
    int x = b & 0xff; // I suspect you don't want negative numbers
    System.out.println(Integer.toHexString(b));
}
</code>```

Alternatively you might want to convert each Unicode character to its hex representation:

```<code>for (char c : test.toCharArray())
{
    System.out.println(Integer.toHexString(c));
}
</code>```

Note that Integer.toHexString doesn't pad its output to a particular number of characters.

If you could give more information about your input and expected output, that would really help.

Body:
There are a few misconceptions - or at least problematic descriptions - in your post:

Strings consist of characters, not bytes

Numbers aren't hexadecimal or decimal etc; their representations are hex etc

You're then calling String.getBytes(), but it's not clear what encoding you want to use. As stated before, a String is a sequence of characters. To convert that into bytes, you need to apply an encoding. Unfortunately, String.getBytes() uses the "platform default encoding" which is almost never a good choice. You should always specify which encoding you want to use.

When you have converted the String into bytes (if you definitely want to do that) it's easy to convert that to hex:

for (byte b : test.getBytes("UTF-8"))
{
    int x = b & 0xff; // I suspect you don't want negative numbers
    System.out.println(Integer.toHexString(b));
}

Alternatively you might want to convert each Unicode character to its hex representation:

for (char c : test.toCharArray())
{
    System.out.println(Integer.toHexString(c));
}

Note that Integer.toHexString doesn't pad its output to a particular number of characters.

If you could give more information about your input and expected output, that would really help.


问:
How do I store contents of a parsed JSON message into string variables based on keywords?
I need help storing text from a parsed JSON message into variables based on keywords. What I mean by this is, I have a JSON message that I have parsed once, and within that message, it returns things like:

```<code>Name: Kobe Bryant<br/>
Company: Lakers<br/>
Email: kobe@lakers.com<br/>
etc.
</code>```

I want to be able to look at this block of test, see that it says "Name: Kobe Bryant," and store Kobe Bryant into a string variable called "name" and so on. How can I handle this?

```<code>public class ParseTest {
    public static void main(String[] args) throws Exception {

        String name;
        String company;
        String email;
        String phoneNumber;
        String projectType;
        String contactBy;
        String timeFrame;
        String message;

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

        MainParser mp = mapper.readValue(new File("/Users/kane/VersionControl/LambdaTest/src/InfoBox.txt"), MainParser.class);

        if ("blah".equals(mp.getTopicArn())) {
            //Send to proposal table
            System.out.println(mp.getSubject());
            System.out.println(mp.getMessage());
        } else if ("blah blah".equals(mp.getTopicArn())) {
            //Send to infoBox table
            System.out.println(mp.getMessage());
        }
    }
}
</code>```

The JSON that I'm parsing is:

```<code>{
 "Subject" : "Proposal Request (sent Wed May 22 2019 14:47:49 GMT-0400 (Eastern Daylight Time))",
 "Message" : "Name: Kobe Bryant\nCompany: Lakers\nEmail: kobe@lakers.com"
}
</code>```

Here's the POJO class:

```<code>private String Subject;
private String Message;

public String getSubject() {
    return Subject;
}

public void setSubject(String subject) {
    Subject = subject;
}

public String getMessage() {
    return Message;
}

public void setMessage(String message) {
    Message = message;
}
</code>```

答:
You have a JSON payload where one of values contains data in key:value pairs split by new line \n. We need to create two POJO classes: Message for root JSON and Person - internal person data. These two classes could look like this:

```<code>class Message {

    private String subject;
    private String message;

    // getters, setters, toString
}

class Person {

    private String name;
    private String company;
    private String email;

    // ... more properties

    // getters, setters, toString
}
</code>```

We can parse your JSON payload as below:

```<code>import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.io.File;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);

        Message message = mapper.readValue(jsonFile, Message.class);
        String[] lines = message.getMessage().split("\n");

        Map<String, String> properties = Stream.of(lines)
                .map(i -> i.split(":"))
                .filter(i -> i.length == 2)
                .collect(Collectors.toMap(i -> i[0].trim(), i -> i[1].trim()));

        Person person = mapper.convertValue(properties, Person.class);
        System.out.println(person);
    }
}
</code>```

Above example prints for your JSON payload:

```<code>Person{name='Kobe Bryant', company='Lakers', email='kobe@lakers.com'}
</code>```

As you can see, we created Map from internal data and used convertValue method to convert Map to Person class.

See also:

Java 8 – Convert List to Map

How to deserialize a Map into POJO?

How to serialize to java.util.List and java.util.Map with Jackson

Body:
I need help storing text from a parsed JSON message into variables based on keywords. What I mean by this is, I have a JSON message that I have parsed once, and within that message, it returns things like:

Name: Kobe Bryant

Company: Lakers

Email: kobe@lakers.com

etc.

I want to be able to look at this block of test, see that it says "Name: Kobe Bryant," and store Kobe Bryant into a string variable called "name" and so on. How can I handle this?

public class ParseTest {
    public static void main(String[] args) throws Exception {

        String name;
        String company;
        String email;
        String phoneNumber;
        String projectType;
        String contactBy;
        String timeFrame;
        String message;

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

        MainParser mp = mapper.readValue(new File("/Users/kane/VersionControl/LambdaTest/src/InfoBox.txt"), MainParser.class);

        if ("blah".equals(mp.getTopicArn())) {
            //Send to proposal table
            System.out.println(mp.getSubject());
            System.out.println(mp.getMessage());
        } else if ("blah blah".equals(mp.getTopicArn())) {
            //Send to infoBox table
            System.out.println(mp.getMessage());
        }
    }
}

The JSON that I'm parsing is:

{
 "Subject" : "Proposal Request (sent Wed May 22 2019 14:47:49 GMT-0400 (Eastern Daylight Time))",
 "Message" : "Name: Kobe Bryant\nCompany: Lakers\nEmail: kobe@lakers.com"
}

Here's the POJO class:

private String Subject;
private String Message;

public String getSubject() {
    return Subject;
}

public void setSubject(String subject) {
    Subject = subject;
}

public String getMessage() {
    return Message;
}

public void setMessage(String message) {
    Message = message;
}

Body:
You have a JSON payload where one of values contains data in key:value pairs split by new line \n. We need to create two POJO classes: Message for root JSON and Person - internal person data. These two classes could look like this:

class Message {

    private String subject;
    private String message;

    // getters, setters, toString
}

class Person {

    private String name;
    private String company;
    private String email;

    // ... more properties

    // getters, setters, toString
}

We can parse your JSON payload as below:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import java.io.File;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);

        Message message = mapper.readValue(jsonFile, Message.class);
        String[] lines = message.getMessage().split("\n");

        Map<String, String> properties = Stream.of(lines)
                .map(i -> i.split(":"))
                .filter(i -> i.length == 2)
                .collect(Collectors.toMap(i -> i[0].trim(), i -> i[1].trim()));

        Person person = mapper.convertValue(properties, Person.class);
        System.out.println(person);
    }
}

Above example prints for your JSON payload:

Person{name='Kobe Bryant', company='Lakers', email='kobe@lakers.com'}

As you can see, we created Map from internal data and used convertValue method to convert Map to Person class.

See also:

Java 8 – Convert List to Map

How to deserialize a Map into POJO?

How to serialize to java.util.List and java.util.Map with Jackson


问:
Open Google sheet with script
I would like to open each file in a folder via script.  Below is what I have tried.  This is my first shot at any script in sheets.

This code runs but does not open file, I could be a mile off on this but I can't figure out how to make it open the files.  Thanks for your help

```<code>function myFunction() {
  var dApp = DriveApp;
  var folder = dApp.getFoldersByName("test").next();
  var filesIter = folder.getFiles();

  while(filesIter.hasNext()) {
    var files = filesIter.next();
    var ss = SpreadsheetApp.open(files);
  }
}
</code>```

I simply want it to open all the files in a folder in this case "test".  there are currently two google sheets in the folder.

答:
Google Apps Script server-side code can't do actions on the client side like opening a spreadsheet on the user web browser but you could use HTML Service to use client side code to achieve your goal.

Related

Open a URL in a new tab (and not a new window) using JavaScript

Open URL in same window and in same tab

Title: Open Google sheet with script

Body:
I would like to open each file in a folder via script.  Below is what I have tried.  This is my first shot at any script in sheets.

This code runs but does not open file, I could be a mile off on this but I can't figure out how to make it open the files.  Thanks for your help

function myFunction() {
  var dApp = DriveApp;
  var folder = dApp.getFoldersByName("test").next();
  var filesIter = folder.getFiles();

  while(filesIter.hasNext()) {
    var files = filesIter.next();
    var ss = SpreadsheetApp.open(files);
  }
}

I simply want it to open all the files in a folder in this case "test".  there are currently two google sheets in the folder.


问:
How do I host multiple Meteor apps on the same domain and same port?
I am looking to host a series of self-contained Meteor apps on a single server on our local network. Ideally the URLs would look like:

http://servername/app1

http://servername/app2

etc...

I've tried using mup (meteor up) but that somehow doesn't work (I'm not entirely sure if that's a problem with the way I've set up the VM I'm trying this on or with mup itself)

I'm now trying Passenger, and after going through the tutorial for setting up nginx for Meteor apps, it turns out that frustratingly, the chapter(s) of multi-tenancy on Passenger have not yet been created!

I'm not a node expert, so I'm kind of diving in at the deep end.

Ideally, I'd not have to worry about running the node apps myself, as it looks like Passenger should be able to handle that itself. Is there a good piece of documentation on how to set up Passenger for these kind of scenarios?

答:
You can host multiple meteor apps on a single server, using mup.
The mup.js file for should all point to the same server, but each should specify a unique domain.

Using the following 2 mup.js files you would have apps hosted at:

http://app1.servername.com

http://app2.servername.com

```<code>// app1/mup.js

module.exports = {
  servers: {
    one: {
      host: '45.76.111.111',
      username: 'root',
      password: 'password'
    }
  },

  app: {
    name: 'App1',
    env: {
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://app1.servername.com',
    },
  },

  // Use the proxy to setup ssl and to route requests to the correct
  // app when there are several apps
  proxy: {
    domains: 'app1.servername.com',
  }
};

</code>```

```<code>// app2/mup.js

module.exports = {
  servers: {
    one: {
      host: '45.76.111.111',
      username: 'root',
      password: 'password'
    }
  },

  app: {
    name: 'App2',
    env: {
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://app2.servername.com',
    },
  },

  // Use the proxy to setup ssl and to route requests to the correct
  // app when there are several apps
  proxy: {
    domains: 'app2.servername.com',
  }
};

</code>```

Body:
You can host multiple meteor apps on a single server, using mup.
The mup.js file for should all point to the same server, but each should specify a unique domain.

Using the following 2 mup.js files you would have apps hosted at:

http://app1.servername.com

http://app2.servername.com

// app1/mup.js

module.exports = {
  servers: {
    one: {
      host: '45.76.111.111',
      username: 'root',
      password: 'password'
    }
  },

  app: {
    name: 'App1',
    env: {
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://app1.servername.com',
    },
  },

  // Use the proxy to setup ssl and to route requests to the correct
  // app when there are several apps
  proxy: {
    domains: 'app1.servername.com',
  }
};

// app2/mup.js

module.exports = {
  servers: {
    one: {
      host: '45.76.111.111',
      username: 'root',
      password: 'password'
    }
  },

  app: {
    name: 'App2',
    env: {
      // If you are using ssl, it needs to start with https://
      ROOT_URL: 'http://app2.servername.com',
    },
  },

  // Use the proxy to setup ssl and to route requests to the correct
  // app when there are several apps
  proxy: {
    domains: 'app2.servername.com',
  }
};


问:
Timer-triggered Azure Function not triggered on scheduled time and failed with Azure storage timeout exception
I have a V-1 time triggered Azure Function created from VS used to get data back from a service with estimated time 9 mins via HTTPCLIENT, it runs well locally, and using storage emulator.  But when I published to Azure portal with App Service Plan, two problems arise: 1> Monitor tab not showing all executions, as there are more failed executions I can find if I go to Application Insights, plus the triggered time in Application Insights are not the scheduled time frequency(every 6 hrs I set)   2> Most of them failed with below snapshot.
System.TimeoutException

Any help would be really appreciated!

答:
There is a suggestion in one of the Github issues, and the solution was to disable dashboard logging in the code using the following snippet:

```<code> var config = new JobHostConfiguration();
        config.DashboardConnectionString = null;
</code>```

The full post can be viewed here

Body:
There is a suggestion in one of the Github issues, and the solution was to disable dashboard logging in the code using the following snippet:

 var config = new JobHostConfiguration();
        config.DashboardConnectionString = null;

The full post can be viewed here


问:
Django 1.8 raises error "module X has no attribute 'run'" after upgrading to Python 3.5
I have a Django project running under Django 1.8.4 that I'm trying to upgrade to latest version of Django.  Since I was still using Python 2.7 on a Debian 8 server, I first upgraded my server to Debian 9 and then I upgraded my Django project's virtual environment to Python 3.5.3 (the default version of Python 3 on Debian 9).

After I rebuilt the virtual environment to use Python 3, I ran the command 2to3 -w . in my project's root folder.  2to3 found and fixed 62 problems without any difficulties.  I also have 216 unit tests and only two of them failed under Python 3.5.

I then went to my Django website and the site appeared to be working except that the forms that contain pull-down elements show "SomeThingobject" instead of the values from the SomeThing table.  I ran a few SQL queries directly against the database and confirmed that my SomeThing lookup table is populated.

Now I want to run a Django queryset command in the Python shell like the following to see why my pulldowns are not showing my column values:

```<code>    queryset=SomeThing.objects.all()
</code>```

However, if I activate my virtual environment and try to run the command ./manage.py shell, I get the following error:

```<code>Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 69, in handle
    self.run_shell(shell=options['interface'])
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 58, in run_shell
    return getattr(self, shell)()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 41, in ipython
    ip()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 34, in _ipython
    from IPython import start_ipython
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/__init__.py", line 48, in <module>
    from .terminal.embed import embed
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/terminal/embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/terminal/ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/core/magics/__init__.py", line 22, in <module>
    from .execution import ExecutionMagics
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/core/magics/execution.py", line 21, in <module>
    import cProfile as profile
  File "/usr/lib/python3.5/cProfile.py", line 22, in <module>
    run.__doc__ = _pyprofile.run.__doc__
AttributeError: module 'profile' has no attribute 'run'
</code>```

Now I do have an application named 'profile' in my INSTALLED_APPS.  If I try to open the Python shell on my production server which is still using Python 2.7, the shell executes without a problem.  It's only having this problem with Python 3.5.  What's interesting is that my Django 1.8/Python 2.7 project contains .pyc files but now under Python 3, they're replaced with __pycache__/<filename>.cpython-35.pyc files.

I read the Django document Porting to Python 3 but it doesn't seem to allude to this problem.  What do I have to do to make this Django project operate properly under Python 3.5?  Is there perhaps something new in Python 3.5 that is having a conflict with my profile application or is it something else?

答:
After much digging around in the Python code I surmised that the problem was being caused by the fact that one of my applications inside the Django project was called "profile" and this was conflicting with a profile module in the newer version of cPython in Python 3.5.  After I changed the name of the application to "userprofile" I could start the shell without any problems.  These two articles help me change the app's name:

Stackoverflow: How to change the name of a Django app?

How to Change Name of Django Application

Body:
I have a Django project running under Django 1.8.4 that I'm trying to upgrade to latest version of Django.  Since I was still using Python 2.7 on a Debian 8 server, I first upgraded my server to Debian 9 and then I upgraded my Django project's virtual environment to Python 3.5.3 (the default version of Python 3 on Debian 9).

After I rebuilt the virtual environment to use Python 3, I ran the command 2to3 -w . in my project's root folder.  2to3 found and fixed 62 problems without any difficulties.  I also have 216 unit tests and only two of them failed under Python 3.5.

I then went to my Django website and the site appeared to be working except that the forms that contain pull-down elements show "SomeThingobject" instead of the values from the SomeThing table.  I ran a few SQL queries directly against the database and confirmed that my SomeThing lookup table is populated.

Now I want to run a Django queryset command in the Python shell like the following to see why my pulldowns are not showing my column values:

    queryset=SomeThing.objects.all()

However, if I activate my virtual environment and try to run the command ./manage.py shell, I get the following error:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 69, in handle
    self.run_shell(shell=options['interface'])
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 58, in run_shell
    return getattr(self, shell)()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 41, in ipython
    ip()
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 34, in _ipython
    from IPython import start_ipython
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/__init__.py", line 48, in <module>
    from .terminal.embed import embed
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/terminal/embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/terminal/ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/core/magics/__init__.py", line 22, in <module>
    from .execution import ExecutionMagics
  File "/srv/https/my_project.com/venvs/0bc664fa2a7b562d0b7e42a7acb3f095fe5df3cf/lib/python3.5/site-packages/IPython/core/magics/execution.py", line 21, in <module>
    import cProfile as profile
  File "/usr/lib/python3.5/cProfile.py", line 22, in <module>
    run.__doc__ = _pyprofile.run.__doc__
AttributeError: module 'profile' has no attribute 'run'

Now I do have an application named 'profile' in my INSTALLED_APPS.  If I try to open the Python shell on my production server which is still using Python 2.7, the shell executes without a problem.  It's only having this problem with Python 3.5.  What's interesting is that my Django 1.8/Python 2.7 project contains .pyc files but now under Python 3, they're replaced with __pycache__/<filename>.cpython-35.pyc files.

I read the Django document Porting to Python 3 but it doesn't seem to allude to this problem.  What do I have to do to make this Django project operate properly under Python 3.5?  Is there perhaps something new in Python 3.5 that is having a conflict with my profile application or is it something else?


问:
php echo returns fail to jQuery
Below is jQuery code to pass form data to a php file.  I'm using a very simple file just to test this.  The jQuery code returns success and failure messages, but the failure message is the one that fires.  It looks like the problem is in the php file, or in the data encoding.

This is the php file echo_test.php:

```<code><?php
  $str = "Hello world!";
  echo $str;
?>
</code>```

This is the jQuery code that sends html form data to the php file:

```<code><form>
  <!-- form fields omitted for brevity -->
  <div class="btn_div">
    <button href="google.com" class="btn_joinnow" id="btn_submit"   style="color:rgb(255,255,255)">Click to submit data</button>
  </div>
</form>
</code>```

$("#btn_submit").on("click", function(event) {
  event.preventDefault();
  var datastring = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  });
  console.log("Okay, I'm starting");

  return $.ajax({
    type: "POST",
    url: "echo_test.php",
    data: { post: datastring },
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log("Okay, I failed" + error);
    }
  });
});
```

(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)

The dev console reports:  Okay, I failed[object Object] so it didn't work.

The dev console also says:

XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:

Is the problem with jQuery or PHP?

Thanks for any ideas.

答: You need an HTTP server that processes PHP code and answers with responses to HTTP requests. Your ajax request does not get the response correctly for some reason. That reason is url: "echo_test.php" which is the file probably with wring url. You will have to put the file in accessible URL (maybe your local machine) and request it. There are quick solutions like XAMPP for Windows, Linux or Mac that quickly installs HTTP server with PHP module for ready-to-use environment along with database management system as well.

Title: php echo returns fail to jQuery

Body:
Below is jQuery code to pass form data to a php file.  I'm using a very simple file just to test this.  The jQuery code returns success and failure messages, but the failure message is the one that fires.  It looks like the problem is in the php file, or in the data encoding.

This is the php file echo_test.php:

<?php
  $str = "Hello world!";
  echo $str;
?>

This is the jQuery code that sends html form data to the php file:

<form>

    <button href="google.com" class="btn_joinnow" id="btn_submit"   style="color:rgb(255,255,255)">Click to submit data</button>

</form>

$("#btn_submit").on("click", function(event) {
  event.preventDefault();
  var datastring = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  });
  console.log("Okay, I'm starting");

  return $.ajax({
    type: "POST",
    url: "echo_test.php",
    data: { post: datastring },
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log("Okay, I failed" + error);
    }
  });
});

(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)

The dev console reports:  Okay, I failed[object Object] so it didn't work.

The dev console also says:

XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:

Is the problem with jQuery or PHP?

Thanks for any ideas.


问:
Generic Sorting an XML-Document (parsed by simplexml_load_file) by using usort
I have the following XML-Document:

```<code><?xml version="1.0" encoding="utf-8"?>
<entries>
  <entry>
    <name>Test</name>
    <ext>2</ext>
  </entry>
  <entry>
    <name>Test 2</name>
    <ext>1</ext>
  </entry>
</entries>
</code>```

I parse it with

```<code>$xml_data = simplexml_load_file("doc.xml");
</code>```

Then I want to sort the entries (entry-Elements) of the data structure:

```<code>function sort($key, $dir, $type)
{
    $srt = create_function('$e1,$e2', '
                          $type = "' . $type . '";
                          $dir  = "' . $dir . '";
                  $key  = "' . $key . '";

                                  if($type == "text")
                           return strcmp($e1->$key, $e2->$key);
                  else if($type == "int")
                  {
                       if((int) $e1->$key == (int) $e2->$key)
                               return 0;
                           else
                               return ((int) $e1->$key < (int) $e2->$key) ? -1 : 1;
                  }
                  else
                  {
                      error_log("Unknown sort type!", 0);
                      return 0;
                                  }
    ');

    usort($xml_data->entry, $srt);
}
</code>```

An example call looks like:

```<code>sort('name', 'ASC', 'text'); // sort order not implemented yet
</code>```

but it doesnt work because the array seems to be the first entry and not the entry-Array.
So I looked what printr says:

```<code>printr($xml_data);
</code>```

says:

```<code>SimpleXMLElement Object
(
    [entry] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [name] => Test
                    [ext] => 2
                )

            [1] => SimpleXMLElement Object
                (
                    [name] => Test 2
                    [ext] => 1
                )
        )
)
</code>```

The problem is: How do I have to call usort.

```<code>usort($xml_data->entry, $srt);
</code>```

seems to be wrong but was my interpretation of the printr-Result.

Can anyone give me a hint or a solution for my problem?

Thank you!

答: You cannot sort simplexml elements in an existing instance. You could, however, remove all of them and add them in order afterwards.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have the following XML-Document:

<?xml version="1.0" encoding="utf-8"?>
<entries>
  <entry>
    <name>Test</name>
    <ext>2</ext>
  </entry>
  <entry>
    <name>Test 2</name>
    <ext>1</ext>
  </entry>
</entries>

I parse it with

$xml_data = simplexml_load_file("doc.xml");

Then I want to sort the entries (entry-Elements) of the data structure:

function sort($key, $dir, $type)
{
    $srt = create_function('$e1,$e2', '
                          $type = "' . $type . '";
                          $dir  = "' . $dir . '";
                  $key  = "' . $key . '";

                                  if($type == "text")
                           return strcmp($e1->$key, $e2->$key);
                  else if($type == "int")
                  {
                       if((int) $e1->$key == (int) $e2->$key)
                               return 0;
                           else
                               return ((int) $e1->$key < (int) $e2->$key) ? -1 : 1;
                  }
                  else
                  {
                      error_log("Unknown sort type!", 0);
                      return 0;
                                  }
    ');

    usort($xml_data->entry, $srt);
}

An example call looks like:

sort('name', 'ASC', 'text'); // sort order not implemented yet

but it doesnt work because the array seems to be the first entry and not the entry-Array.
So I looked what printr says:

printr($xml_data);

says:

SimpleXMLElement Object
(
    [entry] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [name] => Test
                    [ext] => 2
                )

            [1] => SimpleXMLElement Object
                (
                    [name] => Test 2
                    [ext] => 1
                )
        )
)

The problem is: How do I have to call usort.

usort($xml_data->entry, $srt);

seems to be wrong but was my interpretation of the printr-Result.

Can anyone give me a hint or a solution for my problem?

Thank you!