问:
Splitting Post Codes from a List
I have a got a list of Post Codes that I would like to return just the first part of it.

postcodes = list(df['postcode'][0:10])
```

<blockquote>
  <p>['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']</p>
</blockquote>

<pre class="lang-py prettyprint-override"><code>for p in postcodes:
    postcodes.append(p.split()[0])
postcodes
</code>```

I was expecting to get something like:

```<code>['EC4V', 'SE1', 'W12', 'E14' ...]
</code>```

but my kernel keeps looping and it doesn't return anything.

答:
Your issue is that you're appending to postcodes while looping through postcodes. So you're never able to loop through everything in postcodes as you keep adding to it each loop. Instead, you can create a new empty list such as modified_postcodes which you can append each modified postcode to:

```<code>modified_postcodes = []
for p in postcodes:
    modified_postcodes.append(p.split()[0])

print(modified_postcodes)
</code>```

Alternatively, you could use pythons map method to map each postcode in postcodes to its first segment by using .split():

```<code>postcodes = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']
res = list(map(lambda p : p.split()[0], postcodes))
print(res)
</code>```

Title: Splitting Post Codes from a List

Body:
I have a got a list of Post Codes that I would like to return just the first part of it.

postcodes = list(df['postcode'][0:10])

['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']

for p in postcodes:
    postcodes.append(p.split()[0])
postcodes

I was expecting to get something like:

['EC4V', 'SE1', 'W12', 'E14' ...]

but my kernel keeps looping and it doesn't return anything.

Body:
Your issue is that you're appending to postcodes while looping through postcodes. So you're never able to loop through everything in postcodes as you keep adding to it each loop. Instead, you can create a new empty list such as modified_postcodes which you can append each modified postcode to:

modified_postcodes = []
for p in postcodes:
    modified_postcodes.append(p.split()[0])

print(modified_postcodes)

Alternatively, you could use pythons map method to map each postcode in postcodes to its first segment by using .split():

postcodes = ['EC4V 3EJ', 'SE1 9DW', 'W12 7EY', 'E14 9GA', 'E17 8ES', 'N10 3LR', 'W2 2RH', 'W3 7ST', 'W2 1PW', 'W4 5RG']
res = list(map(lambda p : p.split()[0], postcodes))
print(res)


来源: stackexchange

问:
How can I get the id of an object through an interface?
I have the following interfaces. In the Cart interface, on the line product I want to collect only the id connected to the product interface.

At the moment I am collecting the entire object Product. What is the best way to retrieve ONLY the id of that object? What's the best syntax?

```<code>export interface Product {
    id: number;
    name: string;
    price: number;
    description: string;
    imageUrl: string;
    year: number;
    added: string;
    productCategory: ProductCategory[];
}

export interface Cart {
    product: Product;
    quantity: number;
}

</code>```

答:
You can use Pick:

```<code>export interface Cart {
    product: Pick<Product, 'id'>;
    quantity: number;
}
</code>```

See docs for more details: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktk

ContentLicense: CC BY-SA 4.0

Body:
I have the following interfaces. In the Cart interface, on the line product I want to collect only the id connected to the product interface.

At the moment I am collecting the entire object Product. What is the best way to retrieve ONLY the id of that object? What's the best syntax?

export interface Product {
    id: number;
    name: string;
    price: number;
    description: string;
    imageUrl: string;
    year: number;
    added: string;
    productCategory: ProductCategory[];
}

export interface Cart {
    product: Product;
    quantity: number;
}

Body:
You can use Pick:

export interface Cart {
    product: Pick<Product, 'id'>;
    quantity: number;
}

See docs for more details: https://www.typescriptlang.org/docs/handbook/utility-types.html#picktk


问:
mail delivery issue in woocommerce website
I am using a GoDaddy server for a Woocommerce website. in this case, if I purchase something the mail notification to customer works perfectly. but the admin didn't get any mail. I checked it with log mail plugin all emails are successfully sent from the website but it didn't reach in the recipient side.

How can I solve the issue or how can I troubleshoot?

答:
If you are using WP forms, You can try with it's add-on "WP Mail SMTP by WPForms"
https://wordpress.org/plugins/wp-mail-smtp/ it will work for sure. </p>


问:
What is the Pythonic way to make an immutable class?
I'm currently working with some data structures in Python, and I would like them to be hashable (so they can be stored in dictionaries and sets). So far I've seen three main ways to do this:

① Make a normal class and give it a __hash__ method.

```<code>class DataStructure:
    def __init__(self, member):
        self.member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member
</code>```

But this is just "trusting" the end user to never mutate member. If they do mutate it while it's stored in a set or dictionary, Bad Things result.

② Use collections.namedtuple.

```<code>DataStructure = collections.namedtuple('DataStructure', ('member',))
</code>```

But a namedtuple can't have member functions, and it would be really nice to have member functions.

③ Use __slots__ and override __setattr__, as shown here.

```<code>class DataStructure:
    __slots__ = ['member']
    def __init__(self, member):
        super(DataStructure, self).__setattr__('member', member)
    def __setattr__(self, key, value):
        raise ValueError('Mutating this object is Not Allowed')
    # also define __hash__ and __eq__ here
</code>```

But this doesn't seem to be intended usage, and also makes inheritance more complicated. Above all it doesn't feel "Pythonic".

So: what is the preferred way of making an immutable class in Python? Wanting a custom data structure to be hashable doesn't seem like such a strange desire—that's why __hash__ exists, after all. And I'd prefer to actually make the class immutable rather than telling users "you're free to assign to these members, but if you do, your sets and dictionaries could crash and burn"—Python generally tries not to let people make those mistakes in the first place (which is why set and frozenset are distinct).

答:
Absolute immutablility is probably impossible to achieve, but you can use properties to make your intent clear:

```<code>class DataStructure:
    def __init__(self, member):
        self._member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member
    @property
    def member(self):
        return self._member
</code>```

This way member is exposed as a "public" attribute, but is not writeable:

```<code>>>> ds = DataStructure(42)
>>> ds.member
42
>>> ds.member = 56
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
</code>```

A determined end user could still mutate self._member, but at this point you would expect that they know they are doing the wrong thing.

Body:
I'm currently working with some data structures in Python, and I would like them to be hashable (so they can be stored in dictionaries and sets). So far I've seen three main ways to do this:

① Make a normal class and give it a __hash__ method.

class DataStructure:
    def __init__(self, member):
        self.member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member

But this is just "trusting" the end user to never mutate member. If they do mutate it while it's stored in a set or dictionary, Bad Things result.

② Use collections.namedtuple.

DataStructure = collections.namedtuple('DataStructure', ('member',))

But a namedtuple can't have member functions, and it would be really nice to have member functions.

③ Use __slots__ and override __setattr__, as shown here.

class DataStructure:
    __slots__ = ['member']
    def __init__(self, member):
        super(DataStructure, self).__setattr__('member', member)
    def __setattr__(self, key, value):
        raise ValueError('Mutating this object is Not Allowed')
    # also define __hash__ and __eq__ here

But this doesn't seem to be intended usage, and also makes inheritance more complicated. Above all it doesn't feel "Pythonic".

So: what is the preferred way of making an immutable class in Python? Wanting a custom data structure to be hashable doesn't seem like such a strange desire—that's why __hash__ exists, after all. And I'd prefer to actually make the class immutable rather than telling users "you're free to assign to these members, but if you do, your sets and dictionaries could crash and burn"—Python generally tries not to let people make those mistakes in the first place (which is why set and frozenset are distinct).

Body:
Absolute immutablility is probably impossible to achieve, but you can use properties to make your intent clear:

class DataStructure:
    def __init__(self, member):
        self._member = member
    def __hash__(self):
        return hash(self.member)
    def __eq__(self, other):
        return isinstance(other, DataStructure) and self.member == other.member
    @property
    def member(self):
        return self._member

This way member is exposed as a "public" attribute, but is not writeable:

>>> ds = DataStructure(42)
>>> ds.member
42
>>> ds.member = 56
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

A determined end user could still mutate self._member, but at this point you would expect that they know they are doing the wrong thing.


问:
GLFW window only displaying Clear Color and nothing else
I have issue in that the window is displaying the clear color i.e. (Orange) I tried all answers on the web but they didn't seem to help me. I'm using GLFW 3.3 precompiled binaries. I'm using GLAD for OpenGL functions.

The code does not give any errors or warnings and also glGetError() returns 0 at all points of the code.

I've already tried changing the order and gDEBugger gives me error (that is, PRIV_INSTRUCTION) and the VAO and VBO tabs are empty.

Here's my code

#define GLFW_DLL

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>

using namespace std;

static const char* vshSrc = "#version 330 core \n layout (location = 0) in vec3 tPos; void main(){gl_Position = tPos.x, tPos.y, tPos.z;} \0";
static const char* fshSrc = "#version 330 core \n layout (location = 0) out vec4 FragOut; void main(){FragOut = vec4(1.0f,0.4f,0.3f,1.0f);} \0";

/** Processes the input.
    *Edit the fuction to add more features. */
void getInput( GLFWwindow *win ){
    if(glfwGetKey(win,GLFW_KEY_ESCAPE) == GLFW_PRESS){
            glfwSetWindowShouldClose(win,true);
    }
}

int main( int argc, char **argv )
{
        //Initialization
        glfwInit();
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
        glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);

        //Make compatible for MacOSX
        #ifdef __APPLE__
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);
        #endif // __APPLE__

        //Window creation

        GLFWwindow* window = glfwCreateWindow(640,480,"Illuminati",NULL,NULL);
        if (window == NULL)
        {
            cout << "Window creation failed" << endl;
            return -1;
        }

        //GLAD

        glfwMakeContextCurrent(window);

        if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
        {
            cout << "GLAD load error." << endl;
            return -1;
        }

        //glViewport( 0, 0, 640, 480);

//==============================================================//

        //Shader programs

        //Vertex Shader
        unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, 1, &vshSrc, NULL);
        glCompileShader(vertexShader);

        //Check for compile errors
        int compilationSuccesful;

        char InfoLog[512];
        glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compilationSuccesful);
        if ( !compilationSuccesful ){
                    glGetShaderInfoLog(vertexShader, 512, NULL, InfoLog);
                    cout << "Vertex Shader compilation Failed. ERROR. \n \n" << InfoLog << endl;
        }

        //Fragment Shader
        unsigned int fragmentShader;
        fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragmentShader, 1, &fshSrc, NULL);
        glCompileShader(fragmentShader);

        //error checking for fragment shader
        glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compilationSuccesful);
        if ( !compilationSuccesful ){
                    glGetShaderInfoLog(fragmentShader, 512, NULL, InfoLog);
                    cout << "Fragment Shader compilation Failed. ERROR. \n \n" << InfoLog << endl;
        }

        //Shader Program

        unsigned int shaderProgram;
        shaderProgram = glCreateProgram();

        //Shader attachments
        glAttachShader(shaderProgram, vertexShader);
        glAttachShader(shaderProgram, fragmentShader);
        glLinkProgram(shaderProgram);

        //Checking for link errors
        glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compilationSuccesful);
        if ( !compilationSuccesful ){
                    glGetProgramInfoLog(shaderProgram, 512, NULL, InfoLog);
                    cout << "The program refused to link. ERROR. \n \n" << InfoLog << endl;
        }

        glDeleteShader(vertexShader);
        glDeleteShader(fragmentShader);

//----------------------------------------------------------------------------------------------------------//

        //Vertex data and elements

        float rect[ ] {

            /* 0 bottom left*/       -0.5f, -0.5f,  0.0f,

            /* 1  top left*/             -0.5,   0.5f,  0.0f,

            /* 2 bottom right*/      0.5f,   -0.5f, 0.0f,

            /* 3 top right*/             0.5f,   0.5f,  0.0f

            };

        unsigned int indices[] {

            0,1,2,  //first triangle
            1,3,2  //second triangle

        };

//==============================================================//

        //Buffers and VAO

        //VAO
        unsigned int VAO;
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);

        //VBO
        unsigned int VBO;
        glGenBuffers(1,&VBO);

        //EBO
        unsigned int EBO;
        glGenBuffers(1, &EBO);

        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, sizeof(rect), rect, GL_STATIC_DRAW);

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

//================================================================//

        //Vertex Attributes

        //glBindVertexArray(0);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float), (void*)0);
        glEnableVertexAttribArray(0);

        //for safety
        //glBindBuffer(GL_ARRAY_BUFFER, 0);

        //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
        //A useless variable
        //unsigned int ui;

//===============================================================//

        //Render Loop

        while ( !glfwWindowShouldClose(window) )
        {

            //Clear the buffer
            glClearColor(0.9f,0.7f,0.2f,1.0f);
            glClear(GL_COLOR_BUFFER_BIT);

            ////////////////////////////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////DRAWING//////////////////////////////////////////

            glBindVertexArray(VAO);
            glUseProgram(shaderProgram);
            //glDrawArrays(GL_TRIANGLES, 0, 4);
            glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT, 0);
            glBindVertexArray(0);
            //////////////////////////////////////////////END/////////////////////////////////////////////

            getInput(window);
            glfwSwapBuffers(window);
            glfwPollEvents();
        }

        //Exit and destructors

            glfwTerminate();
            return 0;
    }

//End

/*
       __
   <( .   )____
    /_______/
~~~~~~~~~
~~~~~~~~~

   */

```

答:
In your shader this expression will try to assign the value of tPos.z and only tPos.z to  gl_Position

```<code>gl_Position = tPos.x, tPos.y, tPos.z;
</code>```

The reason for that is the semantics of the Comma operator, where all expressions delimited by , are evaluated, but only the result of the very last one is used as the whole expression's R-value.

You probably just want to swizzle it, also you must assign .w:

```<code>gl_Position = vec4(tPos.xyz, 1);
</code>```

Body:
In your shader this expression will try to assign the value of tPos.z and only tPos.z to  gl_Position

gl_Position = tPos.x, tPos.y, tPos.z;

The reason for that is the semantics of the Comma operator, where all expressions delimited by , are evaluated, but only the result of the very last one is used as the whole expression's R-value.

You probably just want to swizzle it, also you must assign .w:

gl_Position = vec4(tPos.xyz, 1);


问:
Unexpected closing tag ":svg:use"
I am  new in angularJS and creating app using angular2. I am getting the below error while running the app:

This is my file:

```<code><ul class="social-links">
  <li>
    <a [href]="facebook" target="_blank">
      <svg width="12" height="26">
        <use xlink:href="../../../assets/images/sprite.svg#facebook"></use>
      </svg>
    </a>
  </li>
  <li>
    <a [href]="twitter" target="_blank">
      <svg width="20" height="17">
        <use xlink:href="../../../assets/images/sprite.svg#twitter"></use>
      </svg>
    </a>
  </li>
  <li>
    <a [href]="likedIn" target="_blank">
      <svg width="20" height="20">
        <use xlink:href="../../../assets/images/sprite.svg#linkedin"></use>
      </svg>
    </a>
  </li>
</ul>
</code>```

Unexpected closing tag ":svg:use". It may happen when the tag has
  already been closed by another tag. For more info see
  https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("ebook target=_blank>  [ERROR ->]

答:
This error results from HTML being minimized. In this case you can self-close the <use xlink:href="images/sprite.svg#icon"/> but the compiler would likely pickup on another 'Unexpected closing tag' issue down the line. To resolve set minimize to false. More info here: https://webpack.js.org/loaders/html-loader

module: {
  rules: [{
    test: /\.html$/,
    use: [ {
      loader: 'html-loader',
      options: {
        minimize: false
      }
    }],
  }]
}
```

ContentLicense: CC BY-SA 3.0

Title: Unexpected closing tag ":svg:use"

Body:
I am  new in angularJS and creating app using angular2. I am getting the below error while running the app:

This is my file:

      <svg width="12" height="26">
        <use xlink:href="../../../assets/images/sprite.svg#facebook"></use>
      </svg>

      <svg width="20" height="17">
        <use xlink:href="../../../assets/images/sprite.svg#twitter"></use>
      </svg>

      <svg width="20" height="20">
        <use xlink:href="../../../assets/images/sprite.svg#linkedin"></use>
      </svg>

Unexpected closing tag ":svg:use". It may happen when the tag has
  already been closed by another tag. For more info see
  https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("ebook target=_blank>  [ERROR ->]


问:
How to reserve 2dimention vector with pair
I want to access the two-dimensional vector index directly.

but i dont know how to reserve

```<code>vector<pair<<vector<int>, int>>..
</code>```

what should i do ?

```<code>           vector<pair<vector<int>, int>> c_list;

           vector<int> population;

           population.push_back(1);
           population.push_back(2);
           population.push_back(3);

           c_list[0].first = population;
</code>```

vector out of range

答:
As stated in the comments, reserve only changes the capacity of the vector but not the size. It can improve performance for large vectors because many push_backs could lead to internal resize operations in the vector with multiple allocations and deallocations which may take time.

In your example, simply call c_list.resize(1); before c_list[0].first = population; and you should be fine. resize really changes the size immediately.

Body:
I want to access the two-dimensional vector index directly.

but i dont know how to reserve

vector<pair<<vector<int>, int>>..

what should i do ?

           vector<pair<vector<int>, int>> c_list;

           vector<int> population;

           population.push_back(1);
           population.push_back(2);
           population.push_back(3);

           c_list[0].first = population;

vector out of range


问:
how to connect to rabbitmq using javascript without nodejs
I'm implementing a mobile application using Titanium appcelerator.

In this app, I'll need implementing a chat using RabbitMQ. I saw a lot of examples of how to connect to RabbitMQ server using node js, but in my case it isn't applicable and I could not find any JavaScript standalone client.

I'd like know if there's a way to connect to RabbitMQ without a client, or if there are any JavaScript standalone client?

答: You can use Socket IO in script tag in html, just put a listener into main app.js for listening to rabbit mq consume, and then from there, emit the message to the html script that you want. ( don't forget to put a listener in your html file for listening to what is emitted from app.js )</p>


问:
How can I set the class of a checkbox label with wtforms?
I would like to use Bootstrap 4 forms. This means I need to add the class form-check-label to the label of a checkbox. How can I do that?

Minimal Code Sample

requirements.txt

```<code>Flask==1.0.2
WTForms==2.2.1
Flask-WTF==0.14.2
</code>```

app.py:

```<code>from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, SubmitField

app = Flask(__name__, template_folder="templates")
app.config['SECRET_KEY'] = 'http://flask.pocoo.org/docs/1.0/quickstart/#sessions'

class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    remember_me = BooleanField("Remember Me")
    submit = SubmitField('Submit')

@app.route('/')
def index():
    form = LoginForm()
    return render_template('login.html', form=form)

app.run()
</code>```

templates/login.html:

```<code><form action="" method="post" class="form form-horizontal" role="form">
    {{ form.hidden_tag() }}
    <div class="form-group">
        {{ form.username.label }}<br>
        {{ form.username(size=32, class_="form-control") }}<br>
        {% for error in form.username.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    <div class="form-group">
        {{ form.password.label }}<br>
        {{ form.password(size=32, class_="form-control") }}<br>
        {% for error in form.password.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    <div class="form-check">
        {{ form.remember_me.label }}<br>  # form-check-label
       {{ form.remember_me(value='n', class_="form-check-input") }}
        {% for error in form.remember_me.errors %}
        <span style="color: red;">[{{ error }}]</span>
        {% endfor %}
    </div>
    {{ form.submit(class_="btn btn-primary") }}
</form>
</code>```

答:
The solution turned out to be super simple - I can call .label also as a function identical to the other elements:

```<code>{{ form.remember_me.label(class_="form-check-label") }}
</code>```

Body:
I would like to use Bootstrap 4 forms. This means I need to add the class form-check-label to the label of a checkbox. How can I do that?

Minimal Code Sample

requirements.txt

Flask==1.0.2
WTForms==2.2.1
Flask-WTF==0.14.2

app.py:

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, PasswordField, SubmitField

app = Flask(__name__, template_folder="templates")
app.config['SECRET_KEY'] = 'http://flask.pocoo.org/docs/1.0/quickstart/#sessions'

class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    remember_me = BooleanField("Remember Me")
    submit = SubmitField('Submit')

@app.route('/')
def index():
    form = LoginForm()
    return render_template('login.html', form=form)

app.run()

templates/login.html:

<form action="" method="post" class="form form-horizontal" role="form">
    {{ form.hidden_tag() }}

        {{ form.username.label }}

        {{ form.username(size=32, class_="form-control") }}

        {% for error in form.username.errors %}
        [{{ error }}]
        {% endfor %}

        {{ form.password.label }}

        {{ form.password(size=32, class_="form-control") }}

        {% for error in form.password.errors %}
        [{{ error }}]
        {% endfor %}

        {{ form.remember_me.label }}
  # form-check-label
       {{ form.remember_me(value='n', class_="form-check-input") }}
        {% for error in form.remember_me.errors %}
        [{{ error }}]
        {% endfor %}

    {{ form.submit(class_="btn btn-primary") }}
</form>

Body:
The solution turned out to be super simple - I can call .label also as a function identical to the other elements:

{{ form.remember_me.label(class_="form-check-label") }}


问:
how to display Node Terms in block with tree structure in Drupal?
I just enabled multiple terms for node creation and i just wanna display those mulitple terms
as a tree sturctured in a block i tried with the following code

```<code>if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
$node = node_load(arg(1));
if (module_exists('taxonomy')) {
    $terms = taxonomy_link('taxonomy terms', $node);
    print theme('links', $terms, array('class' => 'node-terms'));
} else {
    print 'No associated categories.';
}
}
</code>```

But no luck its just displaying all terms, But i have to display like below

```<code>- parent term1
   - sub term 1.1
- parent term 2
   - sub term 2.1
       -- sub sub term 2.1.3
</code>```

Based on the user selected will display accordingly as a tree.

Anyone please help,

答:
Check out the Taxonomy Lineage module:

http://drupal.org/project/lineage

ContentLicense: CC BY-SA 2.5

Body:
I just enabled multiple terms for node creation and i just wanna display those mulitple terms
as a tree sturctured in a block i tried with the following code

if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
$node = node_load(arg(1));
if (module_exists('taxonomy')) {
    $terms = taxonomy_link('taxonomy terms', $node);
    print theme('links', $terms, array('class' => 'node-terms'));
} else {
    print 'No associated categories.';
}
}

But no luck its just displaying all terms, But i have to display like below

- parent term1
   - sub term 1.1
- parent term 2
   - sub term 2.1
       -- sub sub term 2.1.3

Based on the user selected will display accordingly as a tree.

Anyone please help,


问:
Is there any way to add an iVar that's not in the header file (not using LLVM 2.0 or later) in Objective-C?
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

```<code>//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end
</code>```

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?

答: The only place to declare instance variables is in the interface or a class extension (which is really an extension of the interface). But you can effectively add instance variables at any time with the modern runtime using the associated object functions.

Body:
I recently learned that you can add ivar in a class extension with LLVM2.0. (gcc can't do this)
This is somehow really private iVar because other users don't it's existence since it's not in the header file.
like:

//SomeClass.h
@interface SomeClass : NSObject {

}
@end

//SomeClass.m
@interface SomeClass ()
{
    NSString *reallyPrivateString;
}
@end

@implementation SomeClass

@end

But this does rely on the compiler. Is there any other way to declare an ivar that's not in the header file?


问:
JavaScript: How to open new window with default features?
The window.open function in JS can be used to open a new tab or window. By default, without the third param, it opens a new tab:

```<code>window.open("http://...","_blank");
</code>```

When specifying the third param, it opens a new window:

```<code>window.open("http://...","_blank","location=yes,...");
</code>```

However, I wish to let user open a new window with default window features just like when the user presses Ctrl+N or "New window" from menu. Possible?

Ps.
And it seems window.open can open a new browser window, but no tabs. However, I want tabs.

答:
Use onkeydown captures keyboard events   and then open a new window

```<code>function document.onkeydown()   {
    if (event.ctrlKey == true && event.keyCode == 78) {//Ctrl+N
        window.open("http://...","_blank","location=yes,...");
    }
}
</code>```

also you can create Menu Button trigger the click event  open a new window

```<code><script>

function doOpenWindow()   {
    window.open("http://...","_blank","location=yes,...");
}
</code>```

```<code><input type="button"  value="Menu" onClick="doOpenWindow()" />
</code>```

Body:
The window.open function in JS can be used to open a new tab or window. By default, without the third param, it opens a new tab:

window.open("http://...","_blank");

When specifying the third param, it opens a new window:

window.open("http://...","_blank","location=yes,...");

However, I wish to let user open a new window with default window features just like when the user presses Ctrl+N or "New window" from menu. Possible?

Ps.
And it seems window.open can open a new browser window, but no tabs. However, I want tabs.

Body:
Use onkeydown captures keyboard events   and then open a new window

function document.onkeydown()   {
    if (event.ctrlKey == true && event.keyCode == 78) {//Ctrl+N
        window.open("http://...","_blank","location=yes,...");
    }
}

also you can create Menu Button trigger the click event  open a new window

<script>

function doOpenWindow()   {
    window.open("http://...","_blank","location=yes,...");
}

<input type="button"  value="Menu" onClick="doOpenWindow()" />


问:
Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p
After downloading minishift, I cant run it due to the following error,

```<code>Starting Minishift VM .... FAIL E0529 13:00:23.325175   82884 start.go:494] Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string. Retrying.
</code>```

The solution provided here does not help

Below is the whole log.

```<code>Isaacs-MacBook-Pro-2:minishift-1.34.0-darwin-amd64 isaack$ minishift start
-- Starting profile 'minishift'
-- Check if deprecated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.11.0' is valid ... SKIP
-- Checking if requested OpenShift version 'v3.11.0' is supported ... OK
-- Checking if requested hypervisor 'xhyve' is supported on this platform ... OK
-- Checking if xhyve driver is installed ...
   Driver is available at /usr/local/bin/docker-machine-driver-xhyve
   Checking for setuid bit ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting the OpenShift cluster using 'xhyve' hypervisor ...
-- Minishift VM will be configured with ...
   Memory:    4 GB
   vCPUs :    2
   Disk size: 10 GB
-- Starting Minishift VM .... FAIL E0529 13:00:23.325175   82884 start.go:494] Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string. Retrying.
Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string
</code>```

答:
Your 1.34.0 version of Minishift is currently tested against docker-machine-driver-xhyve version 0.3.3. and has compatibility issues with the recently deployed docker-machine-driver-xhyve v0.4.0.

The solution for me was to uninstall the docker-machine-driver-xhyve 0.4.0 driver and install the old and tested 0.3.3:

https://github.com/machine-drivers/docker-machine-driver-xhyve/releases/tag/v0.3.3

$ brew uninstall docker-machine-driver-xhyve
$ brew edit docker-machine-driver-xhyve
```

<p>Change the <code>tag:</code> and <code>revision:</code> references to:</p>

<pre class="lang-rb prettyprint-override"><code>class DockerMachineDriverXhyve < Formula
  desc "Docker Machine driver for xhyve"
  homepage "https://github.com/machine-drivers/docker-machine-driver-xhyve"
  url "https://github.com/machine-drivers/docker-machine-driver-xhyve.git",
      :tag      => "v0.3.3",
      :revision => "7d92f74a8b9825e55ee5088b8bfa93b042badc47"
  revision 2
</code>```

brew install as usual:

$ brew install docker-machine-driver-xhyve
```

<pre class="lang-sh prettyprint-override"><code>$ minishift start
-- Starting profile 'minishift'
-- Check if deprecated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.11.0' is valid ... OK
-- Checking if requested OpenShift version 'v3.11.0' is supported ... OK
-- Checking if requested hypervisor 'xhyve' is supported on this platform ... OK
-- Checking if xhyve driver is installed ...
   Driver is available at /usr/local/bin/docker-machine-driver-xhyve
   Checking for setuid bit ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting the OpenShift cluster using 'xhyve' hypervisor ...
-- Minishift VM will be configured with ...
   Memory:    4 GB
   vCPUs :    2
   Disk size: 20 GB
-- Starting Minishift VM ...................... OK
[...]
</code>```

Body:
After downloading minishift, I cant run it due to the following error,

Starting Minishift VM .... FAIL E0529 13:00:23.325175   82884 start.go:494] Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string. Retrying.

The solution provided here does not help

Below is the whole log.

Isaacs-MacBook-Pro-2:minishift-1.34.0-darwin-amd64 isaack$ minishift start
-- Starting profile 'minishift'
-- Check if deprecated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.11.0' is valid ... SKIP
-- Checking if requested OpenShift version 'v3.11.0' is supported ... OK
-- Checking if requested hypervisor 'xhyve' is supported on this platform ... OK
-- Checking if xhyve driver is installed ...
   Driver is available at /usr/local/bin/docker-machine-driver-xhyve
   Checking for setuid bit ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting the OpenShift cluster using 'xhyve' hypervisor ...
-- Minishift VM will be configured with ...
   Memory:    4 GB
   vCPUs :    2
   Disk size: 10 GB
-- Starting Minishift VM .... FAIL E0529 13:00:23.325175   82884 start.go:494] Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string. Retrying.
Error starting the VM: Error creating new host: json: cannot unmarshal bool into Go struct field Driver.Virtio9p of type []string

Body:
Your 1.34.0 version of Minishift is currently tested against docker-machine-driver-xhyve version 0.3.3. and has compatibility issues with the recently deployed docker-machine-driver-xhyve v0.4.0.

The solution for me was to uninstall the docker-machine-driver-xhyve 0.4.0 driver and install the old and tested 0.3.3:

https://github.com/machine-drivers/docker-machine-driver-xhyve/releases/tag/v0.3.3

$ brew uninstall docker-machine-driver-xhyve
$ brew edit docker-machine-driver-xhyve

Change the tag: and revision: references to:

class DockerMachineDriverXhyve < Formula
  desc "Docker Machine driver for xhyve"
  homepage "https://github.com/machine-drivers/docker-machine-driver-xhyve"
  url "https://github.com/machine-drivers/docker-machine-driver-xhyve.git",
      :tag      => "v0.3.3",
      :revision => "7d92f74a8b9825e55ee5088b8bfa93b042badc47"
  revision 2

brew install as usual:

$ brew install docker-machine-driver-xhyve

$ minishift start
-- Starting profile 'minishift'
-- Check if deprecated options are used ... OK
-- Checking if https://github.com is reachable ... OK
-- Checking if requested OpenShift version 'v3.11.0' is valid ... OK
-- Checking if requested OpenShift version 'v3.11.0' is supported ... OK
-- Checking if requested hypervisor 'xhyve' is supported on this platform ... OK
-- Checking if xhyve driver is installed ...
   Driver is available at /usr/local/bin/docker-machine-driver-xhyve
   Checking for setuid bit ... OK
-- Checking the ISO URL ... OK
-- Checking if provided oc flags are supported ... OK
-- Starting the OpenShift cluster using 'xhyve' hypervisor ...
-- Minishift VM will be configured with ...
   Memory:    4 GB
   vCPUs :    2
   Disk size: 20 GB
-- Starting Minishift VM ...................... OK
[...]


问:
Index page of Wordpress is not SSL secured
Runing vHost nginx on ubuntu. After I added a wordpress SEO friendly urls my main page (index) became non secured. However all other pages are

Index non secured.

All other pages are secured.

Can someone point me at the right direction? How do i get index page secured?

```<code>server {

    listen 80;

    listen [::]:80;

    listen 443 ssl;

    listen [::]:443 ssl;

    ssl on;
    ssl_certificate /etc/nginx/ssl-certs/MYSITE.com.crt;
    ssl_trusted_certificate /etc/nginx/ssl-certs/MYSITE.com.crt;
    ssl_certificate_key /etc/nginx/ssl-certs/MYSITE.com.key;
    ssl_prefer_server_ciphers on;

        server_name MYSITE.com www.MYSITE.com;

        root /var/www/MYSITE.com/public_html;
        index index.php index.html;
        autoindex on;
        include /etc/nginx/macros/macro;
        include /etc/nginx/snippets/phpmyadmin.conf;

                ####Please add below lines for SEO Friendly URLs
                location / {
                index index.php;
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
 try_files $uri =404;
 fastcgi_split_path_info ^(.+\.php)(/.+)$;
 fastcgi_pass unix:/var/run/php5-fpm.sock;
 fastcgi_index index.php;
 include fastcgi_params;
 }
}
</code>```

After I added a wordpress SEO friendly urls my main page (index) became non secured. However all other pages are

Tried to clean cookies, tried on different PC, same thing everywhere.

答: Try to use Wordpress plugin "REALLY SIMPLE SSL". Hope it will work. </p>

Body:
Runing vHost nginx on ubuntu. After I added a wordpress SEO friendly urls my main page (index) became non secured. However all other pages are

Index non secured.

All other pages are secured.

Can someone point me at the right direction? How do i get index page secured?

server {

    listen 80;

    listen [::]:80;

    listen 443 ssl;

    listen [::]:443 ssl;

    ssl on;
    ssl_certificate /etc/nginx/ssl-certs/MYSITE.com.crt;
    ssl_trusted_certificate /etc/nginx/ssl-certs/MYSITE.com.crt;
    ssl_certificate_key /etc/nginx/ssl-certs/MYSITE.com.key;
    ssl_prefer_server_ciphers on;

        server_name MYSITE.com www.MYSITE.com;

        root /var/www/MYSITE.com/public_html;
        index index.php index.html;
        autoindex on;
        include /etc/nginx/macros/macro;
        include /etc/nginx/snippets/phpmyadmin.conf;

                ####Please add below lines for SEO Friendly URLs
                location / {
                index index.php;
                try_files $uri $uri/ /index.php?q=$uri&$args;
        }

        location ~ \.php$ {
 try_files $uri =404;
 fastcgi_split_path_info ^(.+\.php)(/.+)$;
 fastcgi_pass unix:/var/run/php5-fpm.sock;
 fastcgi_index index.php;
 include fastcgi_params;
 }
}

After I added a wordpress SEO friendly urls my main page (index) became non secured. However all other pages are

Tried to clean cookies, tried on different PC, same thing everywhere.


问:
How to validate that a string only contain lowercase letters?
I'm trying to verify that my string matches a pattern. That is, the full string can be written as that pattern.
However preg_match returns true, if any substring matches that pattern.
(E.g. preg_match("#[a-z]*#, "333k") returns 1, which I don't want to.
In this example I'd rather verify, the whole string contains only small Latin letters.)

答:
I super-love regex, but not for this task -- it is needless overhead because there is a single, direct, non-regex equivalent.  https://www.php.net/manual/en/function.ctype-lower.php

Code: (Demo)

```<code>$tests = [
    'Test',
    'test',
    'test1',
    '1test',
    'test!'
];
foreach ($tests as $test) {
    echo "$test: " , (ctype_lower($test) ? 'true' : 'false') , "\n";
}
</code>```

Output:

```<code>Test: false
test: true
test1: false
1test: false
test!: false
</code>```

p.s. For the record, an empty string returns false.  I'm not sure of your logical validation requirements for this test unit.

Body:
I super-love regex, but not for this task -- it is needless overhead because there is a single, direct, non-regex equivalent.  https://www.php.net/manual/en/function.ctype-lower.php

Code: (Demo)

$tests = [
    'Test',
    'test',
    'test1',
    '1test',
    'test!'
];
foreach ($tests as $test) {
    echo "$test: " , (ctype_lower($test) ? 'true' : 'false') , "\n";
}

Output:

Test: false
test: true
test1: false
1test: false
test!: false

p.s. For the record, an empty string returns false.  I'm not sure of your logical validation requirements for this test unit.


问:
Replace each occurrence ending with a specific letter from a string separated by blanks
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

```<code>have = "Da 4e 5c 6a 7a"
want = "4e 5c"
</code>```

Any idea?

Thank you in advance,

Anthony

答:
Not the best approach but you could try:</p>

```<code>trimws(gsub("([A-Z]|[0-9])([a])","",have))
[1] "4e 5c"
</code>```

Body:
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

have = "Da 4e 5c 6a 7a"
want = "4e 5c"

Any idea?

Thank you in advance,

Anthony

Body:
Not the best approach but you could try:

trimws(gsub("([A-Z]|[0-9])([a])","",have))
[1] "4e 5c"


问:
How to merge two arrays (song&title) into one multidimensional array?
I have two arrays:

```<code>Array
(
 [0] => Black
 [1] => Five Hours
 [2] => Bvulgari
 [3] => Imaginary
)

Array
(
 [0] => Pearl Jam
 [1] => Deorro
 [2] => Daddy's Groove
 [3] => Brennan Heart
)
</code>```

I want to be able to achieve the following:
I want to have the song title and the Artist into one 'dimension' of the array,
This is how I want it to be:

```<code>Array
(
     [0] => Array
            (
              [0] => Black
              [1] => Pearl Jam
            )
     [1] => Array
            (
              [0] => Five Hours
              [1] => Deorro
            )
     [2] => Array
            (
              [0] => Bvulgari
              [1] => Daddy's Groove

            )
     [3] => Array
            (
              [0] => Imaginary
              [1] => Brennan Heart
            )

)
</code>```

The two arrays that are the input can change depending on the requestor's input.

答:
Another way to do is Array_Combine</p>

```<code>$songs_artists = array_combine($songs,$artists);

Array (
[Black] => Pearl Jam
[Five Hours] => Deorro
[Bvulgari] => Daddy's Groove
[Imaginary] => Brennan Heart
)
</code>```

Body:
I have two arrays:

Array
(
 [0] => Black
 [1] => Five Hours
 [2] => Bvulgari
 [3] => Imaginary
)

Array
(
 [0] => Pearl Jam
 [1] => Deorro
 [2] => Daddy's Groove
 [3] => Brennan Heart
)

I want to be able to achieve the following:
I want to have the song title and the Artist into one 'dimension' of the array,
This is how I want it to be:

Array
(
     [0] => Array
            (
              [0] => Black
              [1] => Pearl Jam
            )
     [1] => Array
            (
              [0] => Five Hours
              [1] => Deorro
            )
     [2] => Array
            (
              [0] => Bvulgari
              [1] => Daddy's Groove

            )
     [3] => Array
            (
              [0] => Imaginary
              [1] => Brennan Heart
            )

)

The two arrays that are the input can change depending on the requestor's input.

Body:
Another way to do is Array_Combine

$songs_artists = array_combine($songs,$artists);

Array (
[Black] => Pearl Jam
[Five Hours] => Deorro
[Bvulgari] => Daddy's Groove
[Imaginary] => Brennan Heart
)


问:
Getting html from site c#
I need to parse some data from this page https://warcraft3.info/replays/18723

Only WebBrowser helps me to get more html part, but I can't get all html text still. But WebBrowser control shows page correctly.

When I save page using browser I get what I need.

Can anybody help me with some advice?

```<code> var d = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.Body.OuterHtml;
</code>```

答: First port of call is to read the following, you can extract pretty much anything that has valid markup. https://jsoup.org/</p>

Title: Getting html from site c#

Body:
I need to parse some data from this page https://warcraft3.info/replays/18723

Only WebBrowser helps me to get more html part, but I can't get all html text still. But WebBrowser control shows page correctly.

When I save page using browser I get what I need.

Can anybody help me with some advice?

 var d = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.Body.OuterHtml;


问:
no resource id found for app:layout_scrollflags from CollapsingToolbarLayout
The title of this question basically says it all. I get the error:
no resource identifier found for app:layout_scrollflags from CollapsingToolbarLayout. I use eclipse and imported the design library jar file. I'm able to use the design support layouts in my classes so that's correct

this is a piece of the code i use:

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/activityBg"
tools:context=".MainActivity"
>

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <include
            layout="@layout/toolbar"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</code>```

examples: http://android-developers.blogspot.in/2015/05/android-design-support-library.html

答:
Androidx soution:

If you are using AndroidX the above solutions won't work.

You will need to implement this:

```<code>implementation 'com.google.android.material:material:1.1.0-alpha06'
</code>```

Notice that Maybe you will need to Invalidate Caches/Restart for this to work for you:

File > Invalidate Caches/Restart

For more info check the Migrating to AndroidX page.

Body:
The title of this question basically says it all. I get the error:
no resource identifier found for app:layout_scrollflags from CollapsingToolbarLayout. I use eclipse and imported the design library jar file. I'm able to use the design support layouts in my classes so that's correct

this is a piece of the code i use:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/activityBg"
tools:context=".MainActivity"
>

<android.support.design.widget.AppBarLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <include
            layout="@layout/toolbar"/>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

examples: http://android-developers.blogspot.in/2015/05/android-design-support-library.html

Body:
Androidx soution:

If you are using AndroidX the above solutions won't work.

You will need to implement this:

implementation 'com.google.android.material:material:1.1.0-alpha06'

Notice that Maybe you will need to Invalidate Caches/Restart for this to work for you:

File > Invalidate Caches/Restart

For more info check the Migrating to AndroidX page.


问:
Modal dialog and __doPostback Infinite loop
I've got a modal dialog created using ModalPopupExtender. There is an UI created in it using Webservices and a JQuery Templates. There is also a hidden ASP.NET button which is called from the javascript using the __doPostback() technique. The javascript hides the modal popup and __doPostback is called on the button (which is inside of the ModalPopupExtender)

I use this technique to pass some parameters are from the javascript. The server-side event handler does some processing and transfers to a page (in some cases, back to itself)

This works fine when the page it transfers to is a different one but if it transfers to the same page, the postback happens over and over again until the stack blows.

How do i stop the postback from re-occurring when I postback to the same page. I guess it doesn't happen the first time around because it posts to a different page and the postback is invalidated.

Code samples are difficult to provide as it's a fairly complicated system and it's difficult to break it apart.

It sounds horrible I know, all I want to do, however, it to call a server side function from javascript with some variables. Is there a better way to do this?

答:
Thanks for the responses. I think i've found the solution.

In the server-side callback I was doing this:

```<code>setupPage();
Server.Transfer("mypage.aspx", true);
</code>```

changing it to this:

```<code>setupPage();
Server.Transfer("mypage.aspx");
</code>```

fixes the problem.

SetupPage() stores all of the data in hidden fields and I assumed that preserving the form state would be necessary so that this resided after the transfer. This doesn't seem to be the case as all of the setup I've done in the page before the transfer seems to still be present.

Odd or perhaps I'm misunderstanding something fundamental about .NET

Edit - Yes, I do misunderstand a lot about .NET. It makes my head hurt sometimes.

Thanks for the help

Body:
Thanks for the responses. I think i've found the solution.

In the server-side callback I was doing this:

setupPage();
Server.Transfer("mypage.aspx", true);

changing it to this:

setupPage();
Server.Transfer("mypage.aspx");

fixes the problem.

SetupPage() stores all of the data in hidden fields and I assumed that preserving the form state would be necessary so that this resided after the transfer. This doesn't seem to be the case as all of the setup I've done in the page before the transfer seems to still be present.

Odd or perhaps I'm misunderstanding something fundamental about .NET

Edit - Yes, I do misunderstand a lot about .NET. It makes my head hurt sometimes.

Thanks for the help


问:
saving the form in django
I want to save a simple form in Django2

But when I send the form data it gave me an error:

```<code> __init__() got an unexpected keyword argument 'name'
</code>```

this is my form

```<code>class Message(forms.Form):
name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
email = forms.EmailField(widget=forms.TextInput(
    attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
messages = forms.CharField(widget=forms.Textarea(
    attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))
</code>```

this is my view

```<code> def index(request):
if request.method == 'POST':
    form = Message(request.POST)
    if form.is_valid():
        new_messages = Message(name=request.POST['name'], email=request.POST['email'],
                               messages=request.POST['messages'])
        new_messages.save()
        return redirect('index')
    else:
        form = Message()
</code>```

and this is my model

```<code>class Message(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
messages = models.TextField()

def __str__(self):
    return self.name
</code>```

I try to change the name to anything you think but it did not work.

how can I fix this?

答:
Model and Form have the same name!!!!!

try this code:

```<code>class MessageForm(forms.Form):
    name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
    messages = forms.CharField(widget=forms.Textarea(
        attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))

def index(request):
     if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            Message.objects.create(**form.cleaned_data)
            return redirect('index')
        else:
            form = MessageForm()
</code>```

Title: saving the form in django

Body:
I want to save a simple form in Django2

But when I send the form data it gave me an error:

 __init__() got an unexpected keyword argument 'name'

this is my form

class Message(forms.Form):
name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
email = forms.EmailField(widget=forms.TextInput(
    attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
messages = forms.CharField(widget=forms.Textarea(
    attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))

this is my view

 def index(request):
if request.method == 'POST':
    form = Message(request.POST)
    if form.is_valid():
        new_messages = Message(name=request.POST['name'], email=request.POST['email'],
                               messages=request.POST['messages'])
        new_messages.save()
        return redirect('index')
    else:
        form = Message()

and this is my model

class Message(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
messages = models.TextField()

def __str__(self):
    return self.name

I try to change the name to anything you think but it did not work.

how can I fix this?

Body:
Model and Form have the same name!!!!!

try this code:

class MessageForm(forms.Form):
    name = forms.CharField(max_length=20,
                       widget=forms.TextInput(
                           attrs={'class': 'form-control',
                                  'placeholder': 'Your Name'
                                  }))
    email = forms.EmailField(widget=forms.TextInput(
        attrs={'class': 'form-control',
           'placeholder': 'Your Email'
           }))
    messages = forms.CharField(widget=forms.Textarea(
        attrs={'rows': '5',
           'class': 'form-control',
           'placeholder': 'Write your message...'
           }))

def index(request):
     if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            Message.objects.create(**form.cleaned_data)
            return redirect('index')
        else:
            form = MessageForm()


问:
Baguettebox doesn't show next/previous stepper
I'm using baguettebox for image  viewer. The problem is, everything works except the "next/previous" buttons. So I can't go to the next image.

```<code> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.10.0/baguetteBox.min.js"></script>

<script>
   baguetteBox.run('.labrador');
</script>
</code>```

and the html:

```<code><div class="labrador">
      <a href="img/portfolio/cabin.png"
       data-at-450="img/portfolio/blog.jpg"
       data-at-800="img/portfolio/cake.png"
       data-at-1366="img/portfolio/circus.png"
       data-at-1920="img/portfolio/blog.jpg">
<button type="button" class="btn btn-primary" href="#">Images</button>
            </a>
          </div>

</code>```

My result:
https://i.gyazo.com/3e9bad7f104794962a31b8ef13ce0891.png

As you can see, there aren't next/prev buttons, only the X which works fine.

答:
Try the below code or visit this link:
https://www.cssscript.com/simple-gallery-lightbox-with-javascript-and-css3-baguettebox-js/

```<code>baguetteBox.run('.labrador', {
  captions: true, // display image captions.
  buttons: 'auto', // arrows navigation
  fullScreen: false,
  noScrollbars: false,
  bodyClass: 'baguetteBox-open',
  titleTag: false,
  async: false,
  preload: 2,
  animation: 'slideIn', // fadeIn or slideIn
  verlayBackgroundColor: 'rgba(0,0,0,.8)'
});
</code>```

Body:
I'm using baguettebox for image  viewer. The problem is, everything works except the "next/previous" buttons. So I can't go to the next image.

and the html:

<button type="button" class="btn btn-primary" href="#">Images</button>

My result:
https://i.gyazo.com/3e9bad7f104794962a31b8ef13ce0891.png

As you can see, there aren't next/prev buttons, only the X which works fine.

Body:
Try the below code or visit this link:
https://www.cssscript.com/simple-gallery-lightbox-with-javascript-and-css3-baguettebox-js/

baguetteBox.run('.labrador', {
  captions: true, // display image captions.
  buttons: 'auto', // arrows navigation
  fullScreen: false,
  noScrollbars: false,
  bodyClass: 'baguetteBox-open',
  titleTag: false,
  async: false,
  preload: 2,
  animation: 'slideIn', // fadeIn or slideIn
  verlayBackgroundColor: 'rgba(0,0,0,.8)'
});


问:
shopify number of transactions discrepancy with google analytics
It might be a very stupid rocky question but I’ve never worked with Shopify before.

We have implemented Google Analytics via default functionality available with Shopify Plus. On top of it, I have added quite simple JS to track Consumer Funnel Steps and activated enhanced ecommerce feature.

One month later I have discovered the discrepancy in both number of transactions reported and the revenue that is nearly 50% which clearly indicates that something went wrong. My investigation has shown no patterns from the point of payment method/checkout process/device category.  Our success manager told us that the process looks ok from their end and the issue is on our end.

Please help me to understand where else shall I look to identify the bug. Thanks!!

答:
This is a common issue for Google Analytics and it happens on all ecommerce platforms and the main reason behind it is ad blockers.

About 20% of users use ad blocking extensions which prevents Google Analytics from firing and capturing any data regarding that visit (this also includes ecommerce data), thus, discrepancies are created between the numbers reported in Shopify backend and Google Analytics.

There are more reasons behind why the discrepancies might happen (some of them are of legit concerns like faulty tracking) but ad blocking extensions are probably responsible for most of the discrepancies. If interested, you can see the full list of transaction discrepancy causes here.


问:
Stop return back to first function
I'd like to stop returning to the first function. Look at my example for better understanding:</p>

```<code>function function1() {
    function2();
    console.log('back after called function'); // shoudn't log if condition is true
}

function function2() {
    if (condition === true) { // if condition is true, stop right here (no callback to function1)
        return false;
    } else {
        // callback is allowed
    }
}
</code>```

答:
Simple Just throw and caught the error

function function1() {
  try{
      function2();
      console.log('back after called function'); // shoudn't log if condition is true
  }catch(e){
   console.log(e.message);
  }

  }

function function2() {
    if (1 === 1) { // if condition is true, stop right here (no callback to function1)
        throw new Error('forced stopped');
    } else {
        // callback is allowed
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body onLoad="function1()">
</body>
</html></code>```

Title: Stop return back to first function

Body:
I'd like to stop returning to the first function. Look at my example for better understanding:

function function1() {
    function2();
    console.log('back after called function'); // shoudn't log if condition is true
}

function function2() {
    if (condition === true) { // if condition is true, stop right here (no callback to function1)
        return false;
    } else {
        // callback is allowed
    }
}

Body:
Simple Just throw and caught the error

function function1() {
  try{
      function2();
      console.log('back after called function'); // shoudn't log if condition is true
  }catch(e){
   console.log(e.message);
  }

  }

function function2() {
    if (1 === 1) { // if condition is true, stop right here (no callback to function1)
        throw new Error('forced stopped');
    } else {
        // callback is allowed
    }
}

<!DOCTYPE html>
<html>
<body onLoad="function1()">
</body>
</html>


问:
How to successfully execute test via phpunit within relationship between two models?
I'm new in Laravel. I have 2 tables Productions and Products. Also, I have 2 factories ProductionFactory and ProductFactory. I want to test them via phpunit. Their connection is via production_id.

Error is ErrorException: Undefined variable: production.

I don't get it.

Thanks in advance.

This is a code.

ProductionFactory.php

```<code>        $factory->define(App\Production::class, function (Faker $faker) {
        return [
                'name' =>$faker->name,
            ];
          });
</code>```

ProductFactory.php

```<code>       $factory->define(App\Product::class, function (Faker $faker) {
        $production_id = App\Production::pluck('id');

       if(!$production_id->isEmpty()){
          $production = $production_id->random();
       }

    return [
             'id' =>$faker->uuid,
             'name' =>$faker->name,
             'price' => $faker->numberBetween($min = 100, $max = 900),
             'description' =>Str::random(10),
             'production_id'=> $production,
          ];
</code>```

ProductionTest.php

```<code>           class ProductionTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function production()
               {
                   factory(Production::class)->make();
                   $this->assertTrue(true);
               }
           }
</code>```

ProductTest.php

```<code>           class ProductTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function product()
               {
                   factory(Product::class)->make();
                   $this->assertTrue(true);
               }
           }
</code>```

答:
Model Production

```<code>      use Illuminate\Database\Eloquent\SoftDeletes;

       class Production extends Model
       {
            use SoftDeletes;
              protected $fillable = [
                 'name',
              ];
             public function products()
               {
              return $this->hasMany('App\Product');

               }
</code>```

Model Product

```<code>      class Product extends Model
          {

              use SoftDeletes;
               protected $fillable = [
              'id','name','price','description','production_id'
               ];
           public function production()
          {
             return $this->belongsTo('App\Production');
            }
</code>```

SQLSTATE[HY000]: General error: 1364 Field 'production_id' doesn't have a default value

Body:
I'm new in Laravel. I have 2 tables Productions and Products. Also, I have 2 factories ProductionFactory and ProductFactory. I want to test them via phpunit. Their connection is via production_id.

Error is ErrorException: Undefined variable: production.

I don't get it.

Thanks in advance.

This is a code.

ProductionFactory.php

        $factory->define(App\Production::class, function (Faker $faker) {
        return [
                'name' =>$faker->name,
            ];
          });

ProductFactory.php

       $factory->define(App\Product::class, function (Faker $faker) {
        $production_id = App\Production::pluck('id');

       if(!$production_id->isEmpty()){
          $production = $production_id->random();
       }

    return [
             'id' =>$faker->uuid,
             'name' =>$faker->name,
             'price' => $faker->numberBetween($min = 100, $max = 900),
             'description' =>Str::random(10),
             'production_id'=> $production,
          ];

ProductionTest.php

           class ProductionTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function production()
               {
                   factory(Production::class)->make();
                   $this->assertTrue(true);
               }
           }

ProductTest.php

           class ProductTest extends TestCase
            {
              use RefreshDatabase;

             /**
             * A basic unit test example.
             * @test
             * @return void
               */
            public function product()
               {
                   factory(Product::class)->make();
                   $this->assertTrue(true);
               }
           }

Body:
Model Production

      use Illuminate\Database\Eloquent\SoftDeletes;

       class Production extends Model
       {
            use SoftDeletes;
              protected $fillable = [
                 'name',
              ];
             public function products()
               {
              return $this->hasMany('App\Product');

               }

Model Product

      class Product extends Model
          {

              use SoftDeletes;
               protected $fillable = [
              'id','name','price','description','production_id'
               ];
           public function production()
          {
             return $this->belongsTo('App\Production');
            }

SQLSTATE[HY000]: General error: 1364 Field 'production_id' doesn't have a default value


问:
How to prevent Travis-CI from executing the script if PR and anything else than master
Is it possible to make Travis-CI build only once a merge has been done on Master? So not the PR itself, but only after it's merged?

As described in the documentation, I've tried

```<code>branches:
  only: ["master"]
</code>```

However, once this was filed in as a PR, Travis still built it.

Is there another method possible to prevent all other branches from building?

答: In addition to your branches only master setting, I believe you should disable the "Build pushed pull requests" switch in the Build Settings menu.

Body:
Is it possible to make Travis-CI build only once a merge has been done on Master? So not the PR itself, but only after it's merged?

As described in the documentation, I've tried

branches:
  only: ["master"]

However, once this was filed in as a PR, Travis still built it.

Is there another method possible to prevent all other branches from building?


问:
How to fix url contains arabic characters
I want to get the url of each file in certain directory

i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.

example:

this is my code output:

String A :

https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3

this code is not working in some android devices

but the next code works with all devices

String B:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

Note: i got String B from internet download manager that converts it automatically when i tried to use string A

my question is:

how to convert String A to String B by php

and is there better way to readdir and get the url of each file

My code is:

```<code>if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){

if($file == "." or $file == ".."){
//...
} else { //create object with two fields

sort($file);
$fileName = pathinfo($file)['filename'];

if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}

</code>```

答:
Try this one, I've used once for a legacy project:

```<code>function encode_fullurl($url) {
$output = '';
$valid  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*\'();:@&=+$,/?#[]%';
$length = strlen($url);
for ($i = 0; $i < $length; $i++) {
    $character = $url[$i];
    $output   .= (strpos($valid, $character) === false ? rawurlencode($character) : $character);
}
return $output;

}

$url ="https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3";
echo encode_fullurl($url);
</code>```

output:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

it is not very performing, but it should do what you need

Body:
I want to get the url of each file in certain directory

i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.

example:

this is my code output:

String A :

https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3

this code is not working in some android devices

but the next code works with all devices

String B:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

Note: i got String B from internet download manager that converts it automatically when i tried to use string A

my question is:

how to convert String A to String B by php

and is there better way to readdir and get the url of each file

My code is:

if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){

if($file == "." or $file == ".."){
//...
} else { //create object with two fields

sort($file);
$fileName = pathinfo($file)['filename'];

if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}

Body:
Try this one, I've used once for a legacy project:

function encode_fullurl($url) {
$output = '';
$valid  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*\'();:@&=+$,/?#[]%';
$length = strlen($url);
for ($i = 0; $i < $length; $i++) {
    $character = $url[$i];
    $output   .= (strpos($valid, $character) === false ? rawurlencode($character) : $character);
}
return $output;

}

$url ="https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3";
echo encode_fullurl($url);

output:

https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3

it is not very performing, but it should do what you need


问:
How to write Hebrew strings to a log file using log4j
How to write a Hebrew string to a log4j file. Right now I see ?????? in the file.

I have searched everywhere online to convert Unicode to string:

```<code>String abc = myStr.replaceAll("\u200F", "");
   abc = abc.replaceAll("\u200E", "");
   byte[] utf8Bytes = abc.getBytes(Charset.forName("UTF-8"));
   String value = new String(utf8Bytes);
   log.debug("value : "+ value );
</code>```

I just need to write out a Hebrew string to a Log4j file in a readable format. Here is my configuration:

```<code>log4j.rootLogger=debug, stdout, R log4j.logger.testlogging=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=C:\\dri\\ums.log log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern= %d{dd MMM yyyy HH:mm:ss,SSS} %5p [%t] (%F:%L) - %m%n log4j.appender.FILE.encoding=UTF-8
</code>```

答:
Based from what I've gathered from the comments and my own experience this is most probably not an issue with Log4j itself. I've posted a comment indicating just that:

What exactly do you mean with Log4j file? Is it a regular text log file that the FileAppender points to? Because I've tried printing Hebrew text right now and all is working out fine. I believe this is not a Log4j issue and might be related to your text reader.

Other comments have confirmed their suspicion that it is your text reader that might be causing this issue. I was able to reproduce your issue by doing the following in Notepad++:

Open a new tab in notepad++.

Copy and paste sample text containing Hebrew letters.

Language -> Convert to ANSI

Text before the conversion:

See also: אלף־בית and אַלף־בית

Text after conversion:

See also: ???????? and ?????????

Based on the code you provided (assuming there is no shenanigans that we don't know for behind the scenes) we can definitively conclude you are either writing to a file  that has it's encoding set to ANSI where all your special characters are being converted to question marks because they cannot be decoded or your characters are being read as UTF-8 but merely displayed as ANSI.

ANSI and UTF-8 are both encoding formats. ANSI is the common one byte format used to encode Latin alphabet; whereas, UTF-8 is a Unicode format of variable length (from 1 to 4 bytes) which can encode all possible characters.

I would recommend following these steps:

Navigate to Settings -> Preferences -> New Document -> Encoding and make sure that the UTF-8 (Apply to opened ANSI files) option is selected.

Close all your files currently opened in Notepad++ and delete the log file. Make sure you are actually closing the files instead of just closing Notepad++. This should clear the file entries from cache and allow you to open them again with a different encoding.

Run your Java application and let Log4j print to the file.

Open the file with Notepad++ and check that you are encoding in UTF-8 by clicking on Encoding tab. If the option is not set to UTF-8, change it.

If none of the above worked, please post further information in the comments.

Unfortunately I am not that well versed in encoding matters and had to look some stuff up in the process of writing this, so I can't help you as much as I would like to. However in addition to providing the steps above I can direct you to the following links which should provide you with further knowledge and (consequently) more insight into your problem:

Encodings And Character Display - Notepad++ Wiki

ANSI to UTF-8 in Notepad++ - SuperUser

Body:
How to write a Hebrew string to a log4j file. Right now I see ?????? in the file.

I have searched everywhere online to convert Unicode to string:

String abc = myStr.replaceAll("\u200F", "");
   abc = abc.replaceAll("\u200E", "");
   byte[] utf8Bytes = abc.getBytes(Charset.forName("UTF-8"));
   String value = new String(utf8Bytes);
   log.debug("value : "+ value );

I just need to write out a Hebrew string to a Log4j file in a readable format. Here is my configuration:

log4j.rootLogger=debug, stdout, R log4j.logger.testlogging=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd} %5p [%t] (%F:%L) - %m%n log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=C:\\dri\\ums.log log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern= %d{dd MMM yyyy HH:mm:ss,SSS} %5p [%t] (%F:%L) - %m%n log4j.appender.FILE.encoding=UTF-8


问:
Avoid URI validation for http call in java
I have http call where query parameter should contain JSON with symbols like { } [ ] not encoded.

Url example:

http://server.com?queryParam={%22address1%22%3A%2277+tehama%22%2C%}

in this case { } should be passed without encoding.

I know that according to URL Encoding Reference this symbols should be encoded but it is third party API and it could not be changed in any way.

So far I've tried to make such call with:

Spring RestTemplate

Spring org.springframework.web.reactive.function.client.WebClient

Java9 java.net.http.HttpClient

All this clients have URI validation and do not allow to make such call.
Spring clients consider {*} as parameter name and fails with exception and java HttpClient fails with java.lang.IllegalArgumentException: Illegal character in query.

Is there a way to disable validation for mentioned clients or some other http client (maybe low level) which will allow such kind of calls?

答:
Found a way to achieve this with java.net.URL

Code sample:

```<code>final URL url = new URL("http://server.com?queryParam={%22address1%22%3A%2277+tehama%22%2C%}");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");

final Response response;
try (InputStream inputStream = connection.getInputStream()) {
   response = objectMapper.readValue(inputStream, Response.class);
} catch (final Exception e) {
   log.error("Error when calling API", e);
}
</code>```

Body:
Found a way to achieve this with java.net.URL

Code sample:

final URL url = new URL("http://server.com?queryParam={%22address1%22%3A%2277+tehama%22%2C%}");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");

final Response response;
try (InputStream inputStream = connection.getInputStream()) {
   response = objectMapper.readValue(inputStream, Response.class);
} catch (final Exception e) {
   log.error("Error when calling API", e);
}


问:
PHP: Auto hit the submit button after limited time
Sorry, I don't know codes much.

I want to make a quiz exam were student will submit his/her answer between a limited time.

I tried to use setTimeout(); unfortunately didn't worked for me. The page was refreshing but I didn't get anything form echo $_POST['name'];

My form-

```<code><form action="result.php" method="POST">
   <input type="text" name="answer" >
   <input type="submit" name="submit" >
</form>
</code>```

If the student can't finish the answer between 10 Sec, the page will stop him to type anyting and will take him to result.php where he can see the answers he gave.

result.php

```<code><?php

echo $_POST['answer'];

?>
</code>```

Hope you will solve it for me.

答:
Blueblazer172's answer was correct. But give your form an id then submit or else js will submit all the forms in the page

html

```<code><form id="anything" action="result.php" method="POST">
   <input type="text" name="answer" >
   <input type="submit" name="submit" >
</form>
</code>```

JS

```<code>setTimeout(function(){
    $('form').submit();
}, 10000);
</code>```

Body:
Sorry, I don't know codes much.

I want to make a quiz exam were student will submit his/her answer between a limited time.

I tried to use setTimeout(); unfortunately didn't worked for me. The page was refreshing but I didn't get anything form echo $_POST['name'];

My form-

<form action="result.php" method="POST">
   <input type="text" name="answer" >
   <input type="submit" name="submit" >
</form>

If the student can't finish the answer between 10 Sec, the page will stop him to type anyting and will take him to result.php where he can see the answers he gave.

result.php

<?php

echo $_POST['answer'];

?>

Hope you will solve it for me.

Body:
Blueblazer172's answer was correct. But give your form an id then submit or else js will submit all the forms in the page

html

<form id="anything" action="result.php" method="POST">
   <input type="text" name="answer" >
   <input type="submit" name="submit" >
</form>

JS

setTimeout(function(){
    $('form').submit();
}, 10000);


问:
Cypress: any difference between cy.get("a").find("b") and cy.get("a b")
It seems like they're identical. Is there ever any difference in output between cy.get("a").find("b") and cy.get("a b")?

(Where a and b are some selectors, e.g. div and span, or .someClass and .someOtherClass.)

答:
As you stated in your question there is not difference between cy.get("a").find("b") and cy.get("a b"). But the most important difference between find and get commands in Cypress is that cy.get() is chained off of cy, it always looks for the selector within the entire document as stated in Cypress documents. But as again stated in Cypress documents find works as follows:

Get the descendent DOM elements of a specific selector.

So the command cy.get("a").find("b") returns all the b elements which are successor of an a element, but cy.get("a").get("b") finds all the a and b elements regardless of they are parent and child.


问:
It's listcomps or genexps when no [] or () obvious exist
When we use list comprehension like [i for i in range(10) we got a list, use generator expression like (i for i in range(10) we got a generator. If there are no [] or () obvious exist, and what we get? a list or generator?

>>> max(i for i in range(10))
9
>>> max((i for i in range(10))
9
>>> max([i for i in range(10)])
9
```

So, I just want to know max(i for i in range(10)) use list or generator when calculate max number?

答: max(x for x in ...) is using a generator. Lists are always enclosed in square brackets: [x for x in ...].

Body:
When we use list comprehension like [i for i in range(10) we got a list, use generator expression like (i for i in range(10) we got a generator. If there are no [] or () obvious exist, and what we get? a list or generator?

>>> max(i for i in range(10))
9
>>> max((i for i in range(10))
9
>>> max([i for i in range(10)])
9

So, I just want to know max(i for i in range(10)) use list or generator when calculate max number?


问:
How to fix "CreateDirectory: Relative paths not supported" when using a variable?
As a newbiew, I am still in the stage of experimenting and building little prototypes. The idea is to build a silent installer that has all settings in multiple sections of a .INI and the users calls the setup with parameter /config={NameOfSection}.
My current situation:

FooBar-install.ini

```<code>[PROD]
FOOHOME=c:\FooBar
</code>```

FooBar.nsi

```<code>!include FileFunc.nsh
!include LogicLib.nsh

!insertmacro GetParameters
!insertmacro GetOptions

var /GLOBAL config
var /GLOBAL cmdLineParams
var /global REGAPPKEY
var /global FOOHOME

!define TheName "FooBar"
!define OutFileSuffix "-Install."
!define IniFile "$EXEDIR\${TheName}${OutFileSuffix}ini"

Name "${TheName} ${PRODUCT_VERSION}"     ; bei 2 Kunden geht's auch kd-spezifisch ;)
OutFile ${TheName}${OutFileSuffix}exe

RequestExecutionLevel admin
Icon "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico"
UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"

Section "-aInstaller Section"

ReadINIStr $FOOHOME ${IniFile} $config "FOOHOME"
MessageBox MB_OK "ini=${IniFile} , config=$config, FOOHOME=$FOOHOME"
CreateDirectory "SFOOHOME"

SectionEnd

function .onInit
UserInfo::GetAccountType
pop $0
${If} $0 != "admin" ;Require admin rights on NT4+
    MessageBox mb_iconstop "Administrator rights required!"
    SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED
${Else}
MessageBox  MB_OK "onInit"
${EndIf}
    ; Get parameters
${GetParameters} $cmdLineParams

    ; /? param (help)
ClearErrors

${GetOptions} $cmdLineParams '/?' $R0

IfErrors +3 0
MessageBox MB_OK "Befehlszeilenparameter /config={{name}} verweist auf einen Abschnitt aus ${TheName}${OutFileSuffix}ini mit div. Parametern zur Steuerung des Setup"
Abort

Call parseParameters
Pop $R0

FunctionEnd

Function parseParameters
    ; /config
${GetOptions} $cmdLineParams '/config=' $R0
${If} ${Errors}
StrCpy $config "errPROD"
${Else}
StrCpy $config $R0
${Endif}
FunctionEnd
</code>```

Problem

If I try to compile this, I get the msg

```<code>CreateDirectory: Relative paths not supported
Usage: CreateDirectory directory_name
</code>```

Questions

I do not understand why this error comes up at compile time. When using a variable (especially in this situation where the variable depends on user-input), it does not seem to make sense to complain about the argument when it is not known.

How can I avoid this probolem?

A little puzzle that messes me up is the syntax to refer to variables.The statement MessageBox MB_OK "ini=${IniFile} , config=$config, FOOHOME=$FOOHOME" shows that. I found that I needed to enclose IniFile in {} in order to display its value (I commented out the CreateDir-line to compile the installer and check my assumptions). When do I have to use {}?

If you see any other "unusual" things in my little script, I'd be happy to know ;)

答:
You have a typo, change CreateDirectory "SFOOHOME"  to CreateDirectory "$FOOHOME"

You might want to read the documentation again to learn the basics; ${define}, $(langstring) and $variable.

Body:
As a newbiew, I am still in the stage of experimenting and building little prototypes. The idea is to build a silent installer that has all settings in multiple sections of a .INI and the users calls the setup with parameter /config={NameOfSection}.
My current situation:

FooBar-install.ini

[PROD]
FOOHOME=c:\FooBar

FooBar.nsi

!include FileFunc.nsh
!include LogicLib.nsh

!insertmacro GetParameters
!insertmacro GetOptions

var /GLOBAL config
var /GLOBAL cmdLineParams
var /global REGAPPKEY
var /global FOOHOME

!define TheName "FooBar"
!define OutFileSuffix "-Install."
!define IniFile "$EXEDIR\${TheName}${OutFileSuffix}ini"

Name "${TheName} ${PRODUCT_VERSION}"     ; bei 2 Kunden geht's auch kd-spezifisch ;)
OutFile ${TheName}${OutFileSuffix}exe

RequestExecutionLevel admin
Icon "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico"
UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"

Section "-aInstaller Section"

ReadINIStr $FOOHOME ${IniFile} $config "FOOHOME"
MessageBox MB_OK "ini=${IniFile} , config=$config, FOOHOME=$FOOHOME"
CreateDirectory "SFOOHOME"

SectionEnd

function .onInit
UserInfo::GetAccountType
pop $0
${If} $0 != "admin" ;Require admin rights on NT4+
    MessageBox mb_iconstop "Administrator rights required!"
    SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED
${Else}
MessageBox  MB_OK "onInit"
${EndIf}
    ; Get parameters
${GetParameters} $cmdLineParams

    ; /? param (help)
ClearErrors

${GetOptions} $cmdLineParams '/?' $R0

IfErrors +3 0
MessageBox MB_OK "Befehlszeilenparameter /config={{name}} verweist auf einen Abschnitt aus ${TheName}${OutFileSuffix}ini mit div. Parametern zur Steuerung des Setup"
Abort

Call parseParameters
Pop $R0

FunctionEnd

Function parseParameters
    ; /config
${GetOptions} $cmdLineParams '/config=' $R0
${If} ${Errors}
StrCpy $config "errPROD"
${Else}
StrCpy $config $R0
${Endif}
FunctionEnd

Problem

If I try to compile this, I get the msg

CreateDirectory: Relative paths not supported
Usage: CreateDirectory directory_name

Questions

I do not understand why this error comes up at compile time. When using a variable (especially in this situation where the variable depends on user-input), it does not seem to make sense to complain about the argument when it is not known.

How can I avoid this probolem?

A little puzzle that messes me up is the syntax to refer to variables.The statement MessageBox MB_OK "ini=${IniFile} , config=$config, FOOHOME=$FOOHOME" shows that. I found that I needed to enclose IniFile in {} in order to display its value (I commented out the CreateDir-line to compile the installer and check my assumptions). When do I have to use {}?

If you see any other "unusual" things in my little script, I'd be happy to know ;)


问:
sending gridview column name value from one page to another page
I have grid view with column names categoryid  and category name.

I want to send the category id value to another page.

I have bit confused for sending this information. I know using "Request.querystring" we can get the

information from any page.

i dont know whether it is applicable to grid view cloumns or not.

would any one pls suggest any idea about this.

Many thanks

答:
Set up the CategoryID column as a TemplateField with a Hyperlink.  See this question for sample code:

loading gridview with hyperlink column

You can then reference CategoryID from the next page using Request.Querystring, just like you would with any other Querystring variable.


问:
Replace each occurrence ending with a specific letter from a string separated by blanks
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

```<code>have = "Da 4e 5c 6a 7a"
want = "4e 5c"
</code>```

Any idea?

Thank you in advance,

Anthony

答:
Using link from @PoGibas </p>

```<code>gsub("\\w+a *", "", have)
# "4e 5c "
</code>```

Body:
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

have = "Da 4e 5c 6a 7a"
want = "4e 5c"

Any idea?

Thank you in advance,

Anthony

Body:
Using link from @PoGibas

gsub("\\w+a *", "", have)
# "4e 5c "


问:
Xamarin UI.Test - How can I Close my App after login and re - open to check Login Session is continued or not?
As i need to check my Login Session is continued or not ?
I am using for Android Application.
Kindly help.</p>

答:
You can send an Android app to the background by using app.Back() repeatedly until you leave it.

Although, how to call it back? I do not know.


问:
Getting data from a range of values in jquery
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

```<code><form id="shoe_size">
    <label for="size">Enter sizes</label>
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>
</code>```

my jquery

```<code>$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});
</code>```

答:
As far I'm understanding you code, you should change the following line

found = 'true';

to

size = 'true'

because you are checking size == 'true' in your code later, and also found is not declared anywhere in your code

Body:
I'm trying to get a range of numbers depending on what the user inputs.
I have customer.js which has the customer name and shoe size and what I would like is to get a range of shoe sizes depending
on what the user puts in.

For example. A user puts in the first textbox 5 and in the second textbox 9 I want the customers that is between 5 and 9,
but also including 5 and 9 to be displayed.

I've only gotten as far as this.

my html

<form id="shoe_size">
    Enter sizes
    <input type="text" name="size1" class="size1">
    <input type="text" name="size2" class="size2">
    <input type="submit" value="Search" class="submit">
</form>

my jquery

$('#shoe_size').on('submit', function(){
    var size1 = $('.size1').val();
    var size2 = $('.size2').val();

    $('.table tr').each(function(){
        var size = 'false';
        $(this).each(function(){
            if(size1 <= size2){
                found = 'true';
            }
        })

        if(size == 'true'){
            $(this).show();
        }else{
            $(this).hide();
        }
    });
});


问:
Jmeter: Http POST request with body data and file upload
I'm trying to test a Rest api which is working on postman but not on Jmeter,
the request takes (2 parameters):

a pdf file

a body data (json containing pdf information)

on Postman : when I put the Content-Type = application/x-www-form-urlencoded, and I upload the json file and the pdf file it works
but on jmeter I'm always getting errors such as "Unsupported Media Type"

答:
You can try to add record the network request in Jmeter via postman. I have came across the below link which will do the trick for you

https://www.youtube.com/watch?v=OQWyLMJbXaw

The solution mentioned in the above link actually uses a proxy server in Postman and use the same proxy server in Jmeter test script recorder so that whenever a request is being executed in postman, it travels through Jmeter via proxy.