问:
Is there an Instruments API?
Is it possible to setup an Instruments run programmatically from my code? For instance, I'd like to structure my code something like this where startTrace might setup a specific probe for the current thread and start recording while stopTrace would stop recording. I would be writing the content of those routines using the Instruments API that is the subject of this question.

```<code>-(void)myInterestingMethod
{
    [self startTrace];

    // do something interesting and performance critical

    [self stopTrace];
}
</code>```

If the above isn't available, is setting up my own DTrace probe a viable alternative?

答:
Doesn't look like there's anything straight-forward, but there is an instruments command-line tool. Here's some quick+dirty code that will invoke it and sample CPU usage for the calling process

```<code>static void sampleMe() {
    // instruments -t '/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate' -p 26838 -l 5000

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/instruments"];
    [task setArguments:[NSArray arrayWithObjects:
                        @"-t",
                        @"/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate",
                        @"-p",
                        [NSString stringWithFormat:@"%ld", getpid()],
                        @"-l",
                        @"5000",
                        nil]];
    [task setCurrentDirectoryPath:NSHomeDirectory()];
    [task setStandardInput:[NSPipe pipe]];
    [task setStandardOutput:[NSPipe pipe]];
    [task setStandardError:[NSPipe pipe]];
    [task launch];
    // purposely leak everything since I can't be bothered to figure out lifetimes
}
</code>```

After invocation a file named instrumentscli0.trace will be in your home directory.

Update: Instruments 4.0 offers DTSendSignalFlag in the DTPerformanceSession for iOS apps.

Title: Is there an Instruments API?

Body:
Is it possible to setup an Instruments run programmatically from my code? For instance, I'd like to structure my code something like this where startTrace might setup a specific probe for the current thread and start recording while stopTrace would stop recording. I would be writing the content of those routines using the Instruments API that is the subject of this question.

-(void)myInterestingMethod
{
    [self startTrace];

    // do something interesting and performance critical

    [self stopTrace];
}

If the above isn't available, is setting up my own DTrace probe a viable alternative?

Body:
Doesn't look like there's anything straight-forward, but there is an instruments command-line tool. Here's some quick+dirty code that will invoke it and sample CPU usage for the calling process

static void sampleMe() {
    // instruments -t '/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate' -p 26838 -l 5000

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/usr/bin/instruments"];
    [task setArguments:[NSArray arrayWithObjects:
                        @"-t",
                        @"/Developer/Applications/Instruments.app/Contents/Resources/templates/CPU Sampler.tracetemplate",
                        @"-p",
                        [NSString stringWithFormat:@"%ld", getpid()],
                        @"-l",
                        @"5000",
                        nil]];
    [task setCurrentDirectoryPath:NSHomeDirectory()];
    [task setStandardInput:[NSPipe pipe]];
    [task setStandardOutput:[NSPipe pipe]];
    [task setStandardError:[NSPipe pipe]];
    [task launch];
    // purposely leak everything since I can't be bothered to figure out lifetimes
}

After invocation a file named instrumentscli0.trace will be in your home directory.

Update: Instruments 4.0 offers DTSendSignalFlag in the DTPerformanceSession for iOS apps.


来源: stackexchange

问:
Continue after failed assertion
Once an assertion fails( typically API response ), the remaining test steps in a test case do not get executed. How do I get SoapUI to continue on and complete the rest of the test steps?

I am also looking for a way to retry that step again with the same set of data. If not possible, skip that and proceed to next set of items. Any idea on this ?

答:
In Ready Api (Soapui pro) right click on Test Case and click on Option.

Abort test if an error occurs (Disable)

ContentLicense: CC BY-SA 3.0

Title: Continue after failed assertion


问:
Converting a calculated decimal number into 8 bit binary
I am currently making a python program that is byte adder related, it will prompt the user to enter 2 integers, add them together and if it's within the range of the actual size of a byte (0 to 255) display that number and also give the corresponding value in its 8 bit binary form, for example, the calculation is equal to 1, show the binary number which python declares as the correct one.

This is the task that I am doing ~

"The program must check the input data for the data type permitted and the data value limitations (the value of the integer must not exceed the actual size of byte-coded integers, i.e. min 00000000 and max 11111111 in Base 2 or min 0 and max 255 in Base 10 for positive integers" Input in both binary and decimal format with conversion to binary

```<code>def add():
    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))

    calculatedanswer = Num1+Num2

    if calculatedanswer >= 0 and calculatedanswer <=255:
        print("The answer in decimal is" ,calculatedanswer,)

        **bin(calculatedanswer)**

    elif calculatedanswer < 0 and calculatedanswer >255:
        print("Please ensure the added numbers are above 0 and below 255")
        add()
</code>```

This is my code so far, I have no trouble getting it to display the standard decimal number, but I really can't get the bin(calculatedanswer) to show the binary equivalent of it. I tried using this method that I found on YouTube.

I think my main problem here is my lack of understanding of how "bin" works on python as this is really the first time I am using it.

I have put asterisks around the line that I am having trouble with.

答:
You do have to print the value:

```<code>>>> print(bin(160))  # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b'))  # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}')  # Python 3.6+ new f-string format.
10100000
</code>```

Body:
I am currently making a python program that is byte adder related, it will prompt the user to enter 2 integers, add them together and if it's within the range of the actual size of a byte (0 to 255) display that number and also give the corresponding value in its 8 bit binary form, for example, the calculation is equal to 1, show the binary number which python declares as the correct one.

This is the task that I am doing ~

"The program must check the input data for the data type permitted and the data value limitations (the value of the integer must not exceed the actual size of byte-coded integers, i.e. min 00000000 and max 11111111 in Base 2 or min 0 and max 255 in Base 10 for positive integers" Input in both binary and decimal format with conversion to binary

def add():
    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))

    calculatedanswer = Num1+Num2

    if calculatedanswer >= 0 and calculatedanswer <=255:
        print("The answer in decimal is" ,calculatedanswer,)

        **bin(calculatedanswer)**

    elif calculatedanswer < 0 and calculatedanswer >255:
        print("Please ensure the added numbers are above 0 and below 255")
        add()

This is my code so far, I have no trouble getting it to display the standard decimal number, but I really can't get the bin(calculatedanswer) to show the binary equivalent of it. I tried using this method that I found on YouTube.

I think my main problem here is my lack of understanding of how "bin" works on python as this is really the first time I am using it.

I have put asterisks around the line that I am having trouble with.

Body:
You do have to print the value:

>>> print(bin(160))  # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b'))  # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}')  # Python 3.6+ new f-string format.
10100000


问:
Is it advisable to use meta keywords (2017)?
Is it still advisable to use meta keywords in website design? Googling around seems to suggest that they have fallen out of favor with search engines. </p>

答:
Google doesn't use meta keywords since 2009, and they declared there is not any reason to use them.

you can have a look here to find out the reason.

Q: Why doesn't Google use the keywords meta tag?

A: About a decade ago, search engines judged pages only on the content of web pages, not any so-called "off-page" factors such as the links pointing to a web page. In those days, keyword meta tags quickly became an area where someone could stuff often-irrelevant keywords without typical visitors ever seeing those keywords. Because the keywords meta tag was so often abused, many years ago Google began disregarding the keywords meta tag.


问:
Pedometer in fragment
I am trying to use the pedometer sensor in a fragment to count the number of steps that has been taken since the device last rebooted.

I can get the pedometer working in an Activity but cannot seem to get it working in the fragment. I am new to using fragments so it's probably very simple what I am doing wrong.

My class is below:

```<code>import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import static com.example.application.placepicker.R.id.count;

public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);
    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    count = (TextView) getActivity().findViewById(count);  **error

    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);     **error

}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show();                            **error
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));         **error
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}
</code>```

My XML file to accompany this is:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>
</code>```

答:
You have no member variable for count

```<code>private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;
</code>```

are examples of member variables in your fragment class

```<code>count = (TextView) getActivity().findViewById(count);
</code>```

is setting a TextView to an unknown reference, please initialise count properly i.e.

```<code>TextView count = (TextView) getActivity().findViewById(count);
</code>```

as a function member or:

```<code>private TextView count;
</code>```

with the other class member variables

you will then need to call

```<code>sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE)
</code>```

as a fragment has no reference to the getSystemService method by itself, so it needs to go through it's holding activity

Title: Pedometer in fragment

Body:
I am trying to use the pedometer sensor in a fragment to count the number of steps that has been taken since the device last rebooted.

I can get the pedometer working in an Activity but cannot seem to get it working in the fragment. I am new to using fragments so it's probably very simple what I am doing wrong.

My class is below:

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import static com.example.application.placepicker.R.id.count;

public class Tab3 extends Fragment implements SensorEventListener {

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);
    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    count = (TextView) getActivity().findViewById(count);  **error

    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);     **error

}

@Override
public void onResume() {
    super.onResume();
    activityRunning = true;
    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    if (countSensor != null) {
        sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
    } else {
        Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show();                            **error
    }

}

@Override
public void onPause() {
    super.onPause();
    activityRunning = false;
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (activityRunning) {
        count.setText(String.valueOf(event.values[0]));         **error
    }

}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

My XML file to accompany this is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="114dp"
    android:gravity="center"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Step counter"
        android:textSize="40sp"
        android:textColor="@color/colorAccent"
        android:fontFamily="sans-serif"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="33dp"
        android:layout_gravity="center_horizontal"
        android:textSize="26dp"
        android:text="Steps walked so far today:"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="50dp"
        android:text="---"
        android:textColor="@color/colorAccent"
        android:textSize="36dp" />

</LinearLayout>

Body:
You have no member variable for count

private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;

are examples of member variables in your fragment class

count = (TextView) getActivity().findViewById(count);

is setting a TextView to an unknown reference, please initialise count properly i.e.

TextView count = (TextView) getActivity().findViewById(count);

as a function member or:

private TextView count;

with the other class member variables

you will then need to call

sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE)

as a fragment has no reference to the getSystemService method by itself, so it needs to go through it's holding activity


问:
Ruby rails add field to form with JavaScript
I am using ruby on rails and JavaScript. I want to create a form in which one field can have more than one "object". In my example an employee can add multiple formations.

Just to let you know, I don't know much in JavaScript and I am not an expert in Web languages. So please explain to me what are my problems in the following code.

This is the code in my employe _form.html.erb

```<code><div id="formationSet" class="form-group row">
</div>
<a href="javascript:" id="addNewFormation">Add Formations</a>
</code>```

this is my code in employeFormation.js

```<code>$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"><input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>    </div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});
</code>```

and this is my code in application.js

```<code>//= require employeFormation
</code>```

what I actually want is that when I click on addFormation its add a field below the other and I can remove it and is added to my object when I create the new employee

Thanks you for your answer.

Edit: corrected some typo in the code (thanks to KKK). But its still not working

答:
The problem in your code was that you refer a wrong id in javascript. In your HTML the id is FormationSet and in javascript you try to append form into formationSet div. Change the id in HTML and it works fine.

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
<input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formationSet" class="form-group row">
</div>
Add Formations</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using ruby on rails and JavaScript. I want to create a form in which one field can have more than one "object". In my example an employee can add multiple formations.

Just to let you know, I don't know much in JavaScript and I am not an expert in Web languages. So please explain to me what are my problems in the following code.

This is the code in my employe _form.html.erb

Add Formations

this is my code in employeFormation.js

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
<input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

and this is my code in application.js

//= require employeFormation

what I actually want is that when I click on addFormation its add a field below the other and I can remove it and is added to my object when I create the new employee

Thanks you for your answer.

Edit: corrected some typo in the code (thanks to KKK). But its still not working

Body:
The problem in your code was that you refer a wrong id in javascript. In your HTML the id is FormationSet and in javascript you try to append form into formationSet div. Change the id in HTML and it works fine.

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"><input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>    </div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formationSet" class="form-group row">
</div>
<a href="javascript:" id="addNewFormation">Add Formations</a>


答:
One option for printing it would be to slice off the 0b portion of the result, which I assume is what you mean when you say you are having problems with the bin function.

Try this:

print(bin(calculatedanswer)[2:]))

Title: Converting a calculated decimal number into 8 bit binary


问:
Javascript: indexOf slow on high index despite sparse array?
While running some tests on my site, I ended up with an array that has only 10 String in it, but one with a very high index (600 000 000).

Running indexOf on this array is very slow, making the whole tab freeze for several seconds for each call.

When I tried looking for information about this, most seemed to be saying that modern Javascript implementations use sparse array and that it shouldn't be a problem. I'm using the latest Chrome 62.

The issue is actually reproducible just in the Developer Tools' console. If you try running the following code :

```<code>test = [];
test[600000000] = "test";
test.indexOf("test");
</code>```

You'll see that the console takes several seconds to return the index, indicating that Javascript is looping through every index from 0 to 600000000 rather than skipping directly to the one element. Is this normal behavior?

答:
I'm not sure if this is "normal" behaviour, but an easy replacement would be:</p>

```<code>function sparseIndexOf(arr, value) {
    return Object.keys(arr).find(function(k) {
        return arr[k] === value;
    })
}

test = [];
test[600000000] = "test";
sparseIndexOf(test, "test")
</code>```

Body:
While running some tests on my site, I ended up with an array that has only 10 String in it, but one with a very high index (600 000 000).

Running indexOf on this array is very slow, making the whole tab freeze for several seconds for each call.

When I tried looking for information about this, most seemed to be saying that modern Javascript implementations use sparse array and that it shouldn't be a problem. I'm using the latest Chrome 62.

The issue is actually reproducible just in the Developer Tools' console. If you try running the following code :

test = [];
test[600000000] = "test";
test.indexOf("test");

You'll see that the console takes several seconds to return the index, indicating that Javascript is looping through every index from 0 to 600000000 rather than skipping directly to the one element. Is this normal behavior?

Body:
I'm not sure if this is "normal" behaviour, but an easy replacement would be:

function sparseIndexOf(arr, value) {
    return Object.keys(arr).find(function(k) {
        return arr[k] === value;
    })
}

test = [];
test[600000000] = "test";
sparseIndexOf(test, "test")


问:
Hibernate @Where annotation not working with inheritance
I am using Hibernate 5.1.2

I have run into an unexpected problem that I can't seem to work around. Here's the summary of my data model:

dfip_project_version is my superclass table, and dfip_appln_proj_version is my subclass table. dfip_application contains a list of dfip_appln_proj_versions.

I have mapped this as follows:

```<code>@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion {
    @Id @GeneratedValue
    @Column(name = "PROJECT_VERSION_OID")
    Long oid;

    @Column(name = "PROJ_VSN_EFF_FROM_DTM")
    Timestamp effFromDtm;

    @Column(name = "PROJ_VSN_EFF_TO_DTM")
    Timestamp effToDtm;

    @Column(name = "PROJECT_VERSION_TYPE")
    @Type(type = "project_version_type")
    ProjectVersionType projectVersionType;
}

@Table(name = "DFIP_APPLN_PROJ_VERSION")
@Entity
class ApplicationProjectVersion extends AbstractProjectVersion {

    @OneToOne
    @JoinColumn(name = "APPLICATION_OID", nullable = false)
    Application application;

    public ApplicationProjectVersion() {
        projectVersionType = ProjectVersionType.APPLICATION;
    }
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
    List<ApplicationProjectVersion> applicationVersions = [];
}
</code>```

I am using the @Where annotation so that only the current ApplicationProjectVersion is retrieved with the Application.

The problem with this is that Hibernate assumes that the column I am referencing is in the dfip_appl_proj_version table, when it's actually on the super-class table (dfip_project_version).

Here's what I tried so far to work around this limitation:

Attempt 1

I tried putting the @Where annotation onto the AbstractProjectVersion super-class, like so:

```<code>@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}
</code>```

This did nothing, as the WHERE clause does not seem to be noticed when retrieving the Application.

Attempt 2

I made the applicationVersions list on Application LAZY, and tried to map latestVersion manually like this:

```<code>@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinColumnsOrFormulas([
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")),
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = APPLICATION_OID and pv.PROJ_VSN_EFF_TO_DTM is null)", referencedColumnName="PROJECT_VERSION_OID")),
    ])
    ApplicationProjectVersion latestVersion;
}
</code>```

This caused Hibernate to generate the following SQL (snippet):

```<code>from DFIP_APPLICATION this_
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and
       (select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv
        where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = this_.APPLICATION_OID
        and pv.PROJ_VSN_EFF_TO_DTM is null)=applicatio2_.PROJECT_VERSION_OID
</code>```

which resulted in ORA-01799: a column may not be outer-joined to a subquery.

If I can't specify a sub-query in my join formula, then I cannot join to the super-class manually...

Attempt 3

I noticed that usage of @JoinFormula makes Hibernate notice my @Where annotation on the super-class. So I tried the following:

```<code>@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")
    ApplicationProjectVersion latestVersion;
}
</code>```

This generated the following SQL (snippet):

```<code>from DFIP_APPLICATION this_
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and ( applicatio2_1_.PROJ_VSN_EFF_TO_DTM is null)
left outer join DFIP_PROJECT_VERSION applicatio2_1_ on applicatio2_.PROJECT_VERSION_OID=applicatio2_1_.PROJECT_VERSION_OID
</code>```

This is almost correct! Unfortunately it is not valid SQL, since applicatio2_1_ is used before it is declared on the next line :(.

Now I am out of ideas, so any help would be appreciated. Is there a way to  specify a WHERE clause that will bring in only the current ProjectVersion, without getting rid of my inheritance structure?

Related Hibernate issue ticket

答:
I have a solution to this problem. I must admit, it ended up being a little more cumbersome than what I hoped for, but it does work quite well. I waited a couple of months before posting, to make sure that there are no issues and so far, I have not experienced any problems.

My entities are still mapped exactly as described in the question, but instead of using the problematic @Where annotation, I had to use @Filter annotation instead:

```<code>public class Application {

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Cascade([SAVE_UPDATE, DELETE, MERGE])
    @Fetch(FetchMode.SELECT)

    // Normally we'd just use the @Where(clause = "PROJ_VSN_EFF_TO_DTM is null"), but that doesn't work with collections of
    // entities that use inheritance, as we have here.
    //
    // Hibernate thinks that PROJ_VSN_EFF_TO_DTM is a column on DFIP_APPLN_PROJ_VERSION table, but it is actually on the "superclass"
    // table (DFIP_PROJECT_VERSION).
    //
    // B/c of this, we have to do the same thing with a Filter, which is defined on AbstractProjectVersion.
    // NOTE: This filter must be explicitly enabled, which is currently achieved by HibernateForceFiltersAspect
    //
    @Filter(name="currentProjectVersionOnly",
        condition = "{pvAlias}.PROJ_VSN_EFF_TO_DTM is null",
        deduceAliasInjectionPoints=false,
        aliases=[ @SqlFragmentAlias(alias = "pvAlias", table = "DFIP_PROJECT_VERSION") ]
    )
    List<ApplicationProjectVersion> projectVersions = [];

}
</code>```

Since we are using a Filter, we must also define it:

```<code>// NOTE: This filter needs to be explicitly turned on with session.enableFilter("currentProjectVersionOnly");
// This is currently achieved with HibernateForceFiltersAspect
@FilterDef(name="currentProjectVersionOnly")

@Table(name = "DFIP_PROJECT_VERSION")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion  {

}
</code>```

And of course, we must enable it, since Hibernate does not have a setting to automatically turn on all filters.

To do this I created a system-wide Aspect, whose job is to enable specified filters before every call to any DAO:

```<code>/**
 * Enables provided Hibernate filters every time a Hibernate session is openned.
 *
 * Must be enabled and configured explicitly from Spring XML config (i.e. no auto-scan here)
 *
 * @author Val Blant
 */
@Aspect
public class HibernateForceFiltersAspect {

    List<String> filtersToEnable = [];

    @PostConstruct
    public void checkConfig() throws Exception {
        if ( filtersToEnable.isEmpty() ) {
            throw new IllegalArgumentException("Missing required property 'filtersToEnable'");
        }
    }

    /**
     * This advice gets executed before all method calls into DAOs that extend from <code>HibernateDao</code>
     *
     * @param jp
     */
    @Before("@target(org.springframework.stereotype.Repository) && execution(* ca.gc.agr.common.dao.hibernate.HibernateDao+.*(..))")
    public void enableAllFilters(JoinPoint jp) {
        Session session = ((HibernateDao)jp?.getTarget())?.getSession();

        if ( session != null ) {
            filtersToEnable.each { session.enableFilter(it) } // Enable all specified Hibernate filters
        }
    }

}
</code>```

And the corresponding Spring configuration:

```<code><!-- This aspect is used to force-enable specified Hibernate filters for all method calls on DAOs that extend HibernateDao -->
<bean class="ca.gc.agr.common.dao.hibernate.HibernateForceFiltersAspect">
    <property name="filtersToEnable">
        <list>
            <value>currentProjectVersionOnly</value>            <!-- Defined in AbstractProjectVersion -->
        </list>
    </property>
</bean>
</code>```

And there you have it - polymorphic @Where clause :).

Body:
I am using Hibernate 5.1.2

I have run into an unexpected problem that I can't seem to work around. Here's the summary of my data model:

dfip_project_version is my superclass table, and dfip_appln_proj_version is my subclass table. dfip_application contains a list of dfip_appln_proj_versions.

I have mapped this as follows:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion {
    @Id @GeneratedValue
    @Column(name = "PROJECT_VERSION_OID")
    Long oid;

    @Column(name = "PROJ_VSN_EFF_FROM_DTM")
    Timestamp effFromDtm;

    @Column(name = "PROJ_VSN_EFF_TO_DTM")
    Timestamp effToDtm;

    @Column(name = "PROJECT_VERSION_TYPE")
    @Type(type = "project_version_type")
    ProjectVersionType projectVersionType;
}

@Table(name = "DFIP_APPLN_PROJ_VERSION")
@Entity
class ApplicationProjectVersion extends AbstractProjectVersion {

    @OneToOne
    @JoinColumn(name = "APPLICATION_OID", nullable = false)
    Application application;

    public ApplicationProjectVersion() {
        projectVersionType = ProjectVersionType.APPLICATION;
    }
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
    List<ApplicationProjectVersion> applicationVersions = [];
}

I am using the @Where annotation so that only the current ApplicationProjectVersion is retrieved with the Application.

The problem with this is that Hibernate assumes that the column I am referencing is in the dfip_appl_proj_version table, when it's actually on the super-class table (dfip_project_version).

Here's what I tried so far to work around this limitation:

Attempt 1

I tried putting the @Where annotation onto the AbstractProjectVersion super-class, like so:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}

This did nothing, as the WHERE clause does not seem to be noticed when retrieving the Application.

Attempt 2

I made the applicationVersions list on Application LAZY, and tried to map latestVersion manually like this:

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinColumnsOrFormulas([
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")),
        @JoinColumnOrFormula(formula = @JoinFormula(value = "(select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = APPLICATION_OID and pv.PROJ_VSN_EFF_TO_DTM is null)", referencedColumnName="PROJECT_VERSION_OID")),
    ])
    ApplicationProjectVersion latestVersion;
}

This caused Hibernate to generate the following SQL (snippet):

from DFIP_APPLICATION this_
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and
       (select apv.PROJECT_VERSION_OID from DFIP_PROJECT_VERSION pv, DFIP_APPLN_PROJ_VERSION apv
        where apv.PROJECT_VERSION_OID = pv.PROJECT_VERSION_OID and apv.APPLICATION_OID = this_.APPLICATION_OID
        and pv.PROJ_VSN_EFF_TO_DTM is null)=applicatio2_.PROJECT_VERSION_OID

which resulted in ORA-01799: a column may not be outer-joined to a subquery.

If I can't specify a sub-query in my join formula, then I cannot join to the super-class manually...

Attempt 3

I noticed that usage of @JoinFormula makes Hibernate notice my @Where annotation on the super-class. So I tried the following:

@Table(name = "DFIP_PROJECT_VERSION")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Where(clause = "PROJ_VSN_EFF_TO_DTM is null")
public abstract class AbstractProjectVersion {
    ...etc...
}

@Table(name = "DFIP_APPLICATION")
@Entity
class Application {

    @Id @GeneratedValue
    @Column(name = "APPLICATION_OID")
    Long oid;

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.LAZY)
    @Fetch(FetchMode.SELECT)
    List<ApplicationProjectVersion> applicationVersions = [];

    @ManyToOne
    @JoinFormula(value = "(APPLICATION_OID)", referencedColumnName="APPLICATION_OID")
    ApplicationProjectVersion latestVersion;
}

This generated the following SQL (snippet):

from DFIP_APPLICATION this_
left outer join DFIP_APPLN_PROJ_VERSION applicatio2_
    on (this_.APPLICATION_OID)=applicatio2_.APPLICATION_OID and ( applicatio2_1_.PROJ_VSN_EFF_TO_DTM is null)
left outer join DFIP_PROJECT_VERSION applicatio2_1_ on applicatio2_.PROJECT_VERSION_OID=applicatio2_1_.PROJECT_VERSION_OID

This is almost correct! Unfortunately it is not valid SQL, since applicatio2_1_ is used before it is declared on the next line :(.

Now I am out of ideas, so any help would be appreciated. Is there a way to  specify a WHERE clause that will bring in only the current ProjectVersion, without getting rid of my inheritance structure?

Related Hibernate issue ticket

Body:
I have a solution to this problem. I must admit, it ended up being a little more cumbersome than what I hoped for, but it does work quite well. I waited a couple of months before posting, to make sure that there are no issues and so far, I have not experienced any problems.

My entities are still mapped exactly as described in the question, but instead of using the problematic @Where annotation, I had to use @Filter annotation instead:

public class Application {

    @OneToMany(mappedBy="application", orphanRemoval = true, fetch = FetchType.EAGER)
    @Cascade([SAVE_UPDATE, DELETE, MERGE])
    @Fetch(FetchMode.SELECT)

    // Normally we'd just use the @Where(clause = "PROJ_VSN_EFF_TO_DTM is null"), but that doesn't work with collections of
    // entities that use inheritance, as we have here.
    //
    // Hibernate thinks that PROJ_VSN_EFF_TO_DTM is a column on DFIP_APPLN_PROJ_VERSION table, but it is actually on the "superclass"
    // table (DFIP_PROJECT_VERSION).
    //
    // B/c of this, we have to do the same thing with a Filter, which is defined on AbstractProjectVersion.
    // NOTE: This filter must be explicitly enabled, which is currently achieved by HibernateForceFiltersAspect
    //
    @Filter(name="currentProjectVersionOnly",
        condition = "{pvAlias}.PROJ_VSN_EFF_TO_DTM is null",
        deduceAliasInjectionPoints=false,
        aliases=[ @SqlFragmentAlias(alias = "pvAlias", table = "DFIP_PROJECT_VERSION") ]
    )
    List<ApplicationProjectVersion> projectVersions = [];

}

Since we are using a Filter, we must also define it:

// NOTE: This filter needs to be explicitly turned on with session.enableFilter("currentProjectVersionOnly");
// This is currently achieved with HibernateForceFiltersAspect
@FilterDef(name="currentProjectVersionOnly")

@Table(name = "DFIP_PROJECT_VERSION")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class AbstractProjectVersion  {

}

And of course, we must enable it, since Hibernate does not have a setting to automatically turn on all filters.

To do this I created a system-wide Aspect, whose job is to enable specified filters before every call to any DAO:

/**
 * Enables provided Hibernate filters every time a Hibernate session is openned.
 *
 * Must be enabled and configured explicitly from Spring XML config (i.e. no auto-scan here)
 *
 * @author Val Blant
 */
@Aspect
public class HibernateForceFiltersAspect {

    List<String> filtersToEnable = [];

    @PostConstruct
    public void checkConfig() throws Exception {
        if ( filtersToEnable.isEmpty() ) {
            throw new IllegalArgumentException("Missing required property 'filtersToEnable'");
        }
    }

    /**
     * This advice gets executed before all method calls into DAOs that extend from <code>HibernateDao</code>
     *
     * @param jp
     */
    @Before("@target(org.springframework.stereotype.Repository) && execution(* ca.gc.agr.common.dao.hibernate.HibernateDao+.*(..))")
    public void enableAllFilters(JoinPoint jp) {
        Session session = ((HibernateDao)jp?.getTarget())?.getSession();

        if ( session != null ) {
            filtersToEnable.each { session.enableFilter(it) } // Enable all specified Hibernate filters
        }
    }

}

And the corresponding Spring configuration:

<!-- This aspect is used to force-enable specified Hibernate filters for all method calls on DAOs that extend HibernateDao -->
<bean class="ca.gc.agr.common.dao.hibernate.HibernateForceFiltersAspect">
    <property name="filtersToEnable">
        <list>
            <value>currentProjectVersionOnly</value>            <!-- Defined in AbstractProjectVersion -->
        </list>
    </property>
</bean>

And there you have it - polymorphic @Where clause :).


问:
Form Submit - Open New Tab at same time
I have a contact form on my website. I'm using a free bootstrap template that I've been editing and configuring because I don't know much about coding.

I want a new tab to open and go to a specific website when the user hits the submit button (so both submit the form, and take them to a new web page). How can I do that?

```<code><form name="sentMessage" id="contactForm" target="blank" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <br><br>
                        <div class="col-lg-12 text-center">
                            <div id="success"></div>
                            <button type="submit" class="btn btn-xl">Send Message</button>
                        </div>
                    </div>
                </form>
</code>```

答:
Please use the javascript like this.
then will open new tab as you said

function func1(){
  window.open('https://google.com', '_blank');

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="sentMessage" id="contactForm" onsubmit="func1()" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <br><br>
                        <div class="col-lg-12 text-center">
                            <div id="success"></div>
                            <button type="submit" class="btn btn-xl">Send Message</button>
                        </div>
                    </div>
                </form></code>```

And also you can add action property to form tag.
then if you click the button then will open the new tab as your request, and then will send request to file you specified in action property.
if your purpose is only to open new tab, and don't need to submit form, then please add

```<code>return false
</code>```

at the end of func1 function in my code

Title: Form Submit - Open New Tab at same time

Body:
I have a contact form on my website. I'm using a free bootstrap template that I've been editing and configuring because I don't know much about coding.

I want a new tab to open and go to a specific website when the user hits the submit button (so both submit the form, and take them to a new web page). How can I do that?

<form name="sentMessage" id="contactForm" target="blank" novalidate>

                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                            <button type="submit" class="btn btn-xl">Send Message</button>

                </form>

Body:
Please use the javascript like this.
then will open new tab as you said

function func1(){
  window.open('https://google.com', '_blank');

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form name="sentMessage" id="contactForm" onsubmit="func1()" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <br><br>
                        <div class="col-lg-12 text-center">
                            <div id="success"></div>
                            <button type="submit" class="btn btn-xl">Send Message</button>
                        </div>
                    </div>
                </form>

And also you can add action property to form tag.
then if you click the button then will open the new tab as your request, and then will send request to file you specified in action property.
if your purpose is only to open new tab, and don't need to submit form, then please add

return false

at the end of func1 function in my code


问:
awk: take entries from file and add values in between
I have the following file:

```<code>2    some
5    some
8    some
10   thing
15   thing
19   thing
</code>```

Now I want to end up with entries, where for "some" 2,5,8 correspond to rows where there is a 1, everything else is 0. It doesn't matter how many rows there are. This means for "some":

```<code>0
1
0
0
1
0
0
1
0
0
</code>```

and for "thing"

```<code>0
0
0
0
0
0
0
0
0
1
0
0
0
0
1
0
0
0
1
0
</code>```

Is this possible in a quick way with awk? I mean with something like:

```<code>awk '{for(i=1;i<=10;i++) entries[$i]=0 for(f=0;<=NF;f++) entries[$f]=1' testfile.txt
</code>```

答:
another awk, output terminates with the last index

```<code>awk -v key='thing' '$2==key{while(++c<$1) print 0; print 1}' file
</code>```

to add some extra 0's after the last 1; add END{while(i++<3) print 0}

Body:
I have the following file:

2    some
5    some
8    some
10   thing
15   thing
19   thing

Now I want to end up with entries, where for "some" 2,5,8 correspond to rows where there is a 1, everything else is 0. It doesn't matter how many rows there are. This means for "some":

0
1
0
0
1
0
0
1
0
0

and for "thing"

0
0
0
0
0
0
0
0
0
1
0
0
0
0
1
0
0
0
1
0

Is this possible in a quick way with awk? I mean with something like:

awk '{for(i=1;i<=10;i++) entries[$i]=0 for(f=0;<=NF;f++) entries[$f]=1' testfile.txt

Body:
another awk, output terminates with the last index

awk -v key='thing' '$2==key{while(++c<$1) print 0; print 1}' file

to add some extra 0's after the last 1; add END{while(i++<3) print 0}


问:
Typecasting a superview in Swift
I have subclassed a UIView, and I am trying to access it's superview, but it is returned as a UIView instead of the type of my subclass.

Here is a Swift 4 Playground showing an oversimplification of the problem.

```<code>import UIKit

class SubUIView: UIView {}

var parent:SubUIView = SubUIView()
var child:SubUIView = SubUIView()
parent.addSubview(child)
var other:SubUIView = child.superview
</code>```

How can I typecast child.superview into a SubUIView?

Currently, it throws this error:

Cannot convert value of type 'UIView?' to specified type 'SubUIView'

Previous Stakeoverflow answers on this topic were not clear to me, but the answer provided here was.

答:
superview is a property on UIView that your view subclass inherits. If you want to cast the view returned from the call to superview you have mainly two options:

Force casting, where other's type will be SubUIView. If this operation fails – i.e. the super view isn't actually of type SubUIView, the application will crash. This is done with:

```<code>var other = child.superview as! SubUIView
</code>```

You can also use as? instead of as!. This way the type for other will be SubUIView?, and if the casting fails, the value will be nil.

If you add type annotation to other, it'll have to match the result of the casting operation. As in:

```<code>var other: SubUIView = child.superview as! SubUIView
var other: SubUIView? = child.superview as? SubUIView
</code>```

The type annotations are not needed though.

Title: Typecasting a superview in Swift

Body:
I have subclassed a UIView, and I am trying to access it's superview, but it is returned as a UIView instead of the type of my subclass.

Here is a Swift 4 Playground showing an oversimplification of the problem.

import UIKit

class SubUIView: UIView {}

var parent:SubUIView = SubUIView()
var child:SubUIView = SubUIView()
parent.addSubview(child)
var other:SubUIView = child.superview

How can I typecast child.superview into a SubUIView?

Currently, it throws this error:

Cannot convert value of type 'UIView?' to specified type 'SubUIView'

Previous Stakeoverflow answers on this topic were not clear to me, but the answer provided here was.

Body:
superview is a property on UIView that your view subclass inherits. If you want to cast the view returned from the call to superview you have mainly two options:

Force casting, where other's type will be SubUIView. If this operation fails – i.e. the super view isn't actually of type SubUIView, the application will crash. This is done with:

var other = child.superview as! SubUIView

You can also use as? instead of as!. This way the type for other will be SubUIView?, and if the casting fails, the value will be nil.

If you add type annotation to other, it'll have to match the result of the casting operation. As in:

var other: SubUIView = child.superview as! SubUIView
var other: SubUIView? = child.superview as? SubUIView

The type annotations are not needed though.


答:
The answer is yes and no. Using meta tags is a good idea just in case someone is using an older browser that still uses them sometimes but most browsers are up to date. The only really important tag now would be the description tag as you can have that description published for your website when you search on google, safari, etc..

Also i believe online citation generators frequently look at meta tags so on my sites with information I prefer to add an author tag and a date tag.

EDIT
I just realized you were specifically asking about the keywords tag. The keywords tag is no longer used by the common search engines like google, bing, and safari.

Title: Is it advisable to use meta keywords (2017)?

Body: Is it still advisable to use meta keywords in website design? Googling around seems to suggest that they have fallen out of favor with search engines.


问:
manipulate Windows explorer context menu
I am currently writing application with WPF in framework 3.5 SP1, and I need to extend my functionality to Windows Explorer context menu, like how Winzip or Winrar or anyone else did when user right click on a file or folder.

I did a lot of study, some said use Registry, which after I tried, is quite inflexible. Because I need sub menu in my context menu, and also icons.

Another approach I found, is the shell programming, which is even more nasty, but have much much more potential than the registry method.

Shell programming require COM programming knowledge, which need time to learn.

For all the articles I found about modifying windows explorer context menu, they are mostly published in year 2003, 2005 etc, it's 5 years ago, I mean, after 5 years of development, is there any new technology that can make this possible in current .net framework like 3.5 SP1 or 4.0 using c#?

Thanks.

答:
Adding an Application to the Right Click on Every Folder

Here is how to add any application to the Context Menu when you right click on any Folder. This way you do not have to always go to the Start Menu. When you right click on any folder, you can have access to that application, the same as using Sent To.

Open RegEdit

Go to HKEY_CLASSES_ROOT\Folder\shell

Add a new Key to the "Shell" Key and name it anything you like.

Give it a default value that will appear when you right click a folder,
  i.e. NewKey (use an "&" without the
  quotes, in front of any character and
  it will allow you to use the keyboard)

Click on the Key HKEY_CLASSES_ROOT\Folder\shell\NewKey

Add a New Key named Command

Set the (Default) value of the application you want to run

For example: c:\program files\internet explorer\iexplore.exe
  (Include the full path and parameters
  if you need them)

Writing code for you....

Edit:

code in C# (for folders)

```<code> private void button1_Click(object sender, EventArgs e)
    {
        Microsoft.Win32.RegistryKey contextMenuKey = Registry.ClassesRoot.CreateSubKey(@"Folder\shell\MyName\command");
        //MyName is name to display
        contextMenuKey.SetValue(null, @"c:\program files\internet explorer\iexplore.exe");
        //null or "" to set value in (Default), full path of your application
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Adding an Application to the Right Click on Every Folder

Here is how to add any application to the Context Menu when you right click on any Folder. This way you do not have to always go to the Start Menu. When you right click on any folder, you can have access to that application, the same as using Sent To.

Open RegEdit

Go to HKEY_CLASSES_ROOT\Folder\shell

Add a new Key to the "Shell" Key and name it anything you like.

Give it a default value that will appear when you right click a folder,
  i.e. NewKey (use an "&" without the
  quotes, in front of any character and
  it will allow you to use the keyboard)

Click on the Key HKEY_CLASSES_ROOT\Folder\shell\NewKey

Add a New Key named Command

Set the (Default) value of the application you want to run

For example: c:\program files\internet explorer\iexplore.exe
  (Include the full path and parameters
  if you need them)

Writing code for you....

Edit:

code in C# (for folders)

 private void button1_Click(object sender, EventArgs e)
    {
        Microsoft.Win32.RegistryKey contextMenuKey = Registry.ClassesRoot.CreateSubKey(@"Folder\shell\MyName\command");
        //MyName is name to display
        contextMenuKey.SetValue(null, @"c:\program files\internet explorer\iexplore.exe");
        //null or "" to set value in (Default), full path of your application
    }


问:
String cannot be converted to double aaaaa
so i'm trying to read a row in a txt file (which i got working) but
when i try to find the total it gives me an error saying "total can't be
converted to double" although i've seen examples that should work in this
format

EDIT: i added the Double.parseDouble(input) but now i get "Exception in thread "main" java.lang.NumberFormatException:"

```<code>import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class AAAAA {
   public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
 //1)
    Scanner sc = new Scanner(new File(fileName));

    String input;
    double total = 0;
    double num = 0;
    double count = 0;
    double average = 0;

//2) process rows
          while (sc.hasNext()) {
             input = sc.nextLine();
            System.out.println(input);

   //format 2 decimal points
            DecimalFormat form = new DecimalFormat("#0.##");

   //find total
            total += Double.parseDouble(input);  //compile error on using input
            count++;

            System.out.println(count); //test delete later
   //find average (decimal 2 points)
            System.out.println("hi");
            average = (double)total / count;
            System.out.println("Average = " + average);

//3) class statistics

         }
         System.out.println("Program created by MYNAME");
     }
}
</code>```

答:
The line

```<code>total += input;
</code>```

is essentially the same as

```<code>total = String.valueOf(total) + input;
</code>```

You cannot set total, a double, to the resultant string. Replace that line with

```<code>total += Double.parseDouble(input);
</code>```

Body:
so i'm trying to read a row in a txt file (which i got working) but
when i try to find the total it gives me an error saying "total can't be
converted to double" although i've seen examples that should work in this
format

EDIT: i added the Double.parseDouble(input) but now i get "Exception in thread "main" java.lang.NumberFormatException:"

import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class AAAAA {
   public static void main (String[] args)throws IOException {

    final String fileName = "classQuizzes.txt";
 //1)
    Scanner sc = new Scanner(new File(fileName));

    String input;
    double total = 0;
    double num = 0;
    double count = 0;
    double average = 0;

//2) process rows
          while (sc.hasNext()) {
             input = sc.nextLine();
            System.out.println(input);

   //format 2 decimal points
            DecimalFormat form = new DecimalFormat("#0.##");

   //find total
            total += Double.parseDouble(input);  //compile error on using input
            count++;

            System.out.println(count); //test delete later
   //find average (decimal 2 points)
            System.out.println("hi");
            average = (double)total / count;
            System.out.println("Average = " + average);

//3) class statistics

         }
         System.out.println("Program created by MYNAME");
     }
}

Body:
The line

total += input;

is essentially the same as

total = String.valueOf(total) + input;

You cannot set total, a double, to the resultant string. Replace that line with

total += Double.parseDouble(input);


问:
Rails 3 full-text search options (gems, plugins, etc)
I was wondering if there were any suggestions for how to best roll with full text searching in your Rails 3 apps? Thinking Sphinx and acts_as_ferret aren't updated for Rails 3 yet, and even basic activerecord search helpers like Searchlogic also aren't there yet.

Any thoughts? Are you using any forked versions of the above gems that have been updated to Rails 3?

答:
update complete change

I would go for Elasticsearch via Tire

super fast

scalable

configurable

super powerful

This is a good resource to start learning: http://exploringelasticsearch.com/book/searching-data/the-query-dsl-and-the-search-api.html


问:
Java: playing audio from a youtube video
I'm thinking about coding a Java applet that would take in the top 100 or so songs, find their samples (music that appears within the songs) off WhoSampled.com and then playing those samples off of YouTube.

My problem is the playing part, let's say I have the URL. What's the best way to deal with that in Java, do you think ripping the audio off and playing the audio from there would be best, or should I try to control a sentient YouTube player.

I'm leaning towards extracting the audio, and this: thread mentions a way to extract that audio, however the code:

```<code>  wget http://www.youtube.com/get_video.php?video_id=...
  ffmpeg -i - audio.mp3
</code>```

Is not written in Java. How do I, if possible convert this to run in a Java program? Or does anyone know a good way in Java

Thank you for your suggestions.

答:
You can use an FFMPEG Java wrapper like this one https://github.com/bramp/ffmpeg-cli-wrapper/

An example can be found in Readme. Converting MP4 to mp3 should be like this:

```<code>FFmpeg ffmpeg = new FFmpeg("/path/to/ffmpeg");
FFprobe ffprobe = new FFprobe("/path/to/ffprobe");

FFmpegBuilder builder = new FFmpegBuilder()

  .setInput("input.mp4")     // Filename, or a FFmpegProbeResult
  .overrideOutputFiles(true) // Override the output if it exists

  .addOutput("output.mp3")   // Filename for the destination
    .setFormat("mp3")        // Format is inferred from filename, or can be set
    .setAudioCodec("aac")        // using the aac codec
    .setAudioSampleRate(48_000)  // at 48KHz
    .setAudioBitRate(32768)      // at 32 kbit/s

    .done();

FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);

// Run a one-pass encode
executor.createJob(builder).run();
</code>```

Body:
I'm thinking about coding a Java applet that would take in the top 100 or so songs, find their samples (music that appears within the songs) off WhoSampled.com and then playing those samples off of YouTube.

My problem is the playing part, let's say I have the URL. What's the best way to deal with that in Java, do you think ripping the audio off and playing the audio from there would be best, or should I try to control a sentient YouTube player.

I'm leaning towards extracting the audio, and this: thread mentions a way to extract that audio, however the code:

  wget http://www.youtube.com/get_video.php?video_id=...
  ffmpeg -i - audio.mp3

Is not written in Java. How do I, if possible convert this to run in a Java program? Or does anyone know a good way in Java

Thank you for your suggestions.

Body:
You can use an FFMPEG Java wrapper like this one https://github.com/bramp/ffmpeg-cli-wrapper/

An example can be found in Readme. Converting MP4 to mp3 should be like this:

FFmpeg ffmpeg = new FFmpeg("/path/to/ffmpeg");
FFprobe ffprobe = new FFprobe("/path/to/ffprobe");

FFmpegBuilder builder = new FFmpegBuilder()

  .setInput("input.mp4")     // Filename, or a FFmpegProbeResult
  .overrideOutputFiles(true) // Override the output if it exists

  .addOutput("output.mp3")   // Filename for the destination
    .setFormat("mp3")        // Format is inferred from filename, or can be set
    .setAudioCodec("aac")        // using the aac codec
    .setAudioSampleRate(48_000)  // at 48KHz
    .setAudioBitRate(32768)      // at 32 kbit/s

    .done();

FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);

// Run a one-pass encode
executor.createJob(builder).run();


问:
Async function not returning value, but console.log() does: how to do?
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

```<code>class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}
</code>```

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

```<code>let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console
</code>```

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

```<code>let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}
</code>```

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !

答:
NOTE: Wherever you use await it has to be inside an async function.

Check out the UPDATED FIDDLE

You need to use await myFunc() to get the value you expect from getPostById because an async function always returns a promise.

This sometimes is very frustrating as the whole chain needs to be converted into async functions but that's the price you pay for converting it to a synchronous code, I guess. I am not sure if that can be avoided but am interested in hearing from people who have more experience on this.

Try out the below code in your console by copying over the functions and then accessing final and await final.

NOTE:

An async function CAN contain an await expression.
  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

There is no rule that is must have await in order to even declare an async function.
The example below uses an async function without await just to show that an async function always returns a promise.

const sample = async () => {
  return 100;
}

// sample() WILL RETURN A PROMISE AND NOT 100
// await sample() WILL RETURN 100

const init = async (num) => {
  return new Promise((resolve, reject) => {
    resolve(num);
  });
}

const myFunc = async (num) => {
  const k = await init(num);
  return k;
}

// const final = myFunc();
// final; This returns a promise
// await final; This returns the number you provided to myFunc```

Body:
I have an es6 class, with an init() method responsible for fetching data, transforming it, then update the class's property this.data with newly transformed data.
So far so good.
The class itself has another getPostById() method, to just do what it sounds like. Here is the code for the class:

class Posts {
  constructor(url) {
    this.ready = false
    this.data = {}
    this.url = url
  }
  async init() {
      try {
        let res = await fetch( this.url )
        if (res.ok) {
            let data = await res.json()

          // Do bunch of transformation stuff here

          this.data = data
          this.ready = true
            return data
        }
      }
      catch (e) {
         console.log(e)
      }
  }
  getPostById(id){
     return this.data.find( p => p.id === id )
  }
}

Straightforward, except I have an async/await mechanism in the init() method.
Now, this code will work correctly:

let allPosts = new Posts('https://jsonplaceholder.typicode.com/posts')

allPosts.init()
        .then( d => console.log(allPosts.getPostById(4)) )
// resulting Object correctly logged in console

but it only gets printed into the console:
How could I use allPosts.getPostById(4) as a return of a function ?

Like:

let myFunc = async () => {
   const postId = 4
   await allPosts.init()  // I need to wait for this to finish before returning

   // This is logging correct value
   console.log( 'logging: ' + JSON.stringify(allPosts.getPostById( postId ), null, 4) )

   // How can I return the RESULT of allPosts.getPostById( postId ) ???
   return allPosts.getPostById( postId )
}

myFunc() returns a Promise but not the final value. I have read several related posts on the subject but they all give example of logging, never returning.

Here is a fiddle that includes two ways of handling init(): using Promise and using async/await. No matter what I try, I can't manage to USE the FINAL VALUE of getPostById(id).

The question of this post is: how can I create a function that will RETURN the VALUE of getPostById(id) ?

EDIT:

A lot of good answers trying to explain what Promises are in regards to the main execution loop.
After a lot of videos and other good reads, here is what I understand now:

my function init() correctly returns. However, within the main event loop: it returns a Promise, then it is my job to catch the result of this Promise from within a kinda parallel loop (not a new real thread). In order to catch the result from the parallel loop there are two ways:

use .then( value => doSomethingWithMy(value) )

use let value = await myAsyncFn(). Now here is the foolish hiccup:

await can only be used within an async function :p

thus itself returning a Promise, usable with await which should be embed in an async function, which will be usable with await etc...

This means we cannot really WAIT for a Promise: instead we should catch parallel loop indefinitely: using .then() or async/await.

Thanks for the help !


问:
Reduce ticks & format axis labels in Matplotlib - scaling
I have an array of subplots, but whenever I try to reduce the tick density or even change the format, the values seem to change.

Is there a distinction here between the 'tick' and its value? How would I match the correct value to the tick if so?

Here's a stand-alone plot that's right: France

Here's the (EDITED) code I'm trying:

```<code>import matplotlib as mpl
from matplotlib.ticker import FormatStrFormatter

f, axarr = plt.subplots(5,6,figsize=(30,30))
for i in range(0,6):
    for j in range(0,5):
        # there are only 26 entries in ser
        if (4*i+j) < 26:
            x = pp_gdp.loc[pp_gdp.index == ser.index[4*i+j],:].round(1)
            y = ser.loc[ser.index == ser.index[4*i+j],:].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[4*i+j])
             xt = axarr[j,i].get_xticks()
        #axarr[j,i].set_xscale('linear')
        axarr[j,i].set_xticks([axarr[j,i].get_xticks()[0],int(len(axarr[j,i].get_xticks())/2), axarr[j,i].get_xticks()[-1]])
        axarr[j,i].set_xticklabels([x.values.min(),sorted(x.values)[0][int(len(xt)/2)],x.values.max()])
        yt = axarr[j,i].get_yticks()
        #axarr[j,i].set_yscale('linear')
        axarr[j,i].set_yticks([axarr[j,i].get_yticks()[0],int(len(axarr[j,i].get_yticks())/2), axarr[j,i].get_yticks()[-1]])
        axarr[j,i].set_yticklabels([y.values.min(),sorted(y.values)[0][int(len(yt)/2)],y.values.max()]);
</code>```

Here's what I get if I comment out all the tick code, i.e. the default subplots:
Default plot

As you can see, it's far too dense to read.

Here's what happens when I try nbins:

```<code>axarr[j,i].locator_params(tight=True, axis='y', nbins=10)
axarr[j,i].locator_params(tight=True, axis='x', nbins=5)
</code>```

France nbins wrong

Again, the values are wrong on both axes.

Using the get_xticks and set_xticks as in the big code sample sort of works, but ruins the intuition of the plot. Also the scale is all wrong because of the way it keeps the 0.

Very linear plots stay linear, but the slope is exaggerated. Plots a little more complicated lose their shape altogether, as in:
China now wrong

The chart on the rightis much harder to understand, just because the scale isn't playing nicely.

With my new

Thanks,
Roy

答: Based on bgamari's answer to this question, I'd suggest playing around with mpl.pyplot.locator_params(axis='x', nticks=4).

Body:
I have an array of subplots, but whenever I try to reduce the tick density or even change the format, the values seem to change.

Is there a distinction here between the 'tick' and its value? How would I match the correct value to the tick if so?

Here's a stand-alone plot that's right: France

Here's the (EDITED) code I'm trying:

import matplotlib as mpl
from matplotlib.ticker import FormatStrFormatter

f, axarr = plt.subplots(5,6,figsize=(30,30))
for i in range(0,6):
    for j in range(0,5):
        # there are only 26 entries in ser
        if (4*i+j) < 26:
            x = pp_gdp.loc[pp_gdp.index == ser.index[4*i+j],:].round(1)
            y = ser.loc[ser.index == ser.index[4*i+j],:].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[4*i+j])
             xt = axarr[j,i].get_xticks()
        #axarr[j,i].set_xscale('linear')
        axarr[j,i].set_xticks([axarr[j,i].get_xticks()[0],int(len(axarr[j,i].get_xticks())/2), axarr[j,i].get_xticks()[-1]])
        axarr[j,i].set_xticklabels([x.values.min(),sorted(x.values)[0][int(len(xt)/2)],x.values.max()])
        yt = axarr[j,i].get_yticks()
        #axarr[j,i].set_yscale('linear')
        axarr[j,i].set_yticks([axarr[j,i].get_yticks()[0],int(len(axarr[j,i].get_yticks())/2), axarr[j,i].get_yticks()[-1]])
        axarr[j,i].set_yticklabels([y.values.min(),sorted(y.values)[0][int(len(yt)/2)],y.values.max()]);

Here's what I get if I comment out all the tick code, i.e. the default subplots:
Default plot

As you can see, it's far too dense to read.

Here's what happens when I try nbins:

axarr[j,i].locator_params(tight=True, axis='y', nbins=10)
axarr[j,i].locator_params(tight=True, axis='x', nbins=5)

France nbins wrong

Again, the values are wrong on both axes.

Using the get_xticks and set_xticks as in the big code sample sort of works, but ruins the intuition of the plot. Also the scale is all wrong because of the way it keeps the 0.

Very linear plots stay linear, but the slope is exaggerated. Plots a little more complicated lose their shape altogether, as in:
China now wrong

The chart on the rightis much harder to understand, just because the scale isn't playing nicely.

With my new

Thanks,
Roy


问:
Node.js, express, and object instantiation inside/outside route endpoints
I have a question regarding object instantiation.  Right now I have a fairly large application set up, with RESTful endpoints implemented on the back-end.

I was wondering what is the "best" way of object instantiation, and how the garbage collector is affected by what I do.

Take for example the following:

```<code>const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    const myClass = new MyClass();
    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});
</code>```

Here, an object is instantiated INSIDE the route path implementation.

Now, takes this for example:

```<code>const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

const myClass = new MyClass();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});
</code>```

Here, the object is instantiated OUTSIDE the route path implementation.  Seems to me as though this would persist indefinitely for the life of the application, whereas the first example, the variable myClass would get cleaned up.

So really I'm wondering:

Am I thinking about this the right way?

Is there a reason why I should do one method vs the other?  It seems as though if I chose option 2, I might as well just make static methods on the class itself...

What are some general pros/cons of each approach?

I feel like in my head I'm fighting the battle that things aren't being correctly cleaned up, one way is better than the other in terms of how much traffic there is, race condition avoidance, etc!

答:
It's all fairly simple really.

If you only ever need one object for the duration of your entire application and you can use that one object for any request that happens to need to use it, then it's an "application cycle" type of object.  Create one at initialization time, store its instance (probably as a module level variable) and use it from then on.  As an example, if you had a some sort of cache object designed to be used by lots of request handlers, that would be something that you'd want to create once and then retain it and use the same object every time by all the request handlers that use it.  As another example, some applications create one connection to their main database upon startup and then all other requests can use that one connection.

If you need a fresh object for every single request that might use it, then create it inside the request handler and let normal garbage collection take care of cleaning it up when the request is done.  For example if you need to create a Date() object in order to measure some time duration during a request, the simplest implementation will create a new Date() object within the request handler, use it for what you need to use it for and then let GC take care of it when the request is done.

If you need an independent object for each request such that when multiple request handlers are "in-flight" at the same time, you need to make sure that each request handler has its own object and none are being shared or conflicting.

There are also hybrid models (which are generally done this way as performance optimizations) where you might create a pool of objects and then each request that needs one can "check one out", use it for awhile and then return it to the pool when its done.  This often saves time rebuilding objects from scratch when a small pool of objects can generally serve the needs of the server.  Some databases use this "pool" model for database connections.  Rather than create a new connection to the database for every single request that wants to do a query, the request might just obtain a database connection from the pool, make its query, then return the connection to the pool.

Internally in node.js, it uses a thread pool for some parts of the disk I/O implementation.  Similar concept.

I was wondering what is the "best" way of object instantiation, and how the garbage collector is affected by what I do.

The best way is to pick the instantiation model that matches the usage.  In option 1 above, the object will likely be stored for the entire application cycle and not GCed at all.  In options 2 and 3, the objects will be created and GCed for each request.  You shouldn't worry about creating and object for use and then letting it GC.  That's how the language is designed to work for things that don't have durable lasting state and should be kept around longer.

Is there a reason why I should do one method vs the other? It seems as though if I chose option 2, I might as well just make static methods on the class itself...

If you have no request-specific state in the object and the state of the object itself does not get into trouble if there are multiple request handlers attempting to use the object at the same time, then you really just have a global service that any request handler who wants to use it can use it.  It's up to you if you implement that as an object you create, store the instance of and then call traditional methods on that instance or implement it as more of a singleton that instantiates itself and you just call functions or static methods on it.  That's just a coding style difference, not a functional difference.

What are some general pros/cons of each approach?

In general, you want as much encapsulation and local state as possible.  No need to go putting things that are request-specific stuff into shared globals.  Things being calculated or figured out for a specific request belong internal to the request-handler logic.  So, just follow the four questions above to determine whether the object belongs local to a request handler or shared at a higher scope.  If you can meet your goals by keeping things local, that's generally cleaner, safer and more flexible.

I feel like in my head I'm fighting the battle that things aren't being correctly cleaned up, one way is better than the other in terms of how much traffic there is, race condition avoidance, etc!

GC takes care of cleanup for you.  You can rely on that.  As long as you don't persistently store a reference to an object in a variable that has lasting scope, garbage collection will clean things up for you nicely.  This is how the language is designed to be used.  You should not be afraid of it.  If, perhaps you came from a non-GC language like C or C++, you may be over thinking this.  GC is there to be your friend.  Very, very, very occasionally you may need to do some performance tuning that becomes more aware of how much you're asking the GC to do, but that should pretty much never be something you worry about until you've actually found you have something that needs special optimization in that way.

The simplest way to avoid race conditions between request handlers is to not share any state between request handlers.  If everything you need to handle a given request is created and used locally and never made available to any other request handler, then you will absolutely avoid any race or sharing conditions between multiple request handlers.  In general, start there because that's the simplest and safest.  Then, if you find there is something you need to do a performance optimization of, then you may explore some sharing or caching of certain types of objects and you will have to do that carefully in order to not introduce sharing problems.  But, you'd rarely start your design trying to do that because most of the time that extra complexity is not needed.

Body:
I have a question regarding object instantiation.  Right now I have a fairly large application set up, with RESTful endpoints implemented on the back-end.

I was wondering what is the "best" way of object instantiation, and how the garbage collector is affected by what I do.

Take for example the following:

const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    const myClass = new MyClass();
    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});

Here, an object is instantiated INSIDE the route path implementation.

Now, takes this for example:

const MyClass = require('../controllers/myClassController');
const router = require('express').Router();

const myClass = new MyClass();

router.get('/', (req, res) => {
    console.log('GET request at api/someEndPoint');

    myClass.doSomePromise()
        .then(() => {
            res.end();
        })
        .catch((err) => {
            res.status(500).end();
        });
});

Here, the object is instantiated OUTSIDE the route path implementation.  Seems to me as though this would persist indefinitely for the life of the application, whereas the first example, the variable myClass would get cleaned up.

So really I'm wondering:

Am I thinking about this the right way?

Is there a reason why I should do one method vs the other?  It seems as though if I chose option 2, I might as well just make static methods on the class itself...

What are some general pros/cons of each approach?

I feel like in my head I'm fighting the battle that things aren't being correctly cleaned up, one way is better than the other in terms of how much traffic there is, race condition avoidance, etc!


问:
Python Web Scraper + Cleanup
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

```<code>"<div class=""js-tweet-text-container"">
<p class=""TweetTextSize js-tweet-text tweet-text"" data-aria-label-
part=""0"" lang=""en"">*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (<strong>NYSE:BAC</strong>) <a class=""twitter-
timeline-link u-hidden"" data-expanded-url=""https://good-
stockinvest.com/2017/11/29/bank-of-america-growth-is-back-bank-of-
america-corporation-nysebac/"" dir=""ltr""
href="" rel=""nofollow noopener""
target=""_blank"" title=""https://good-stockinvest.com/2017/11/29/bank-
of-america-growth-is-back-bank-of-america-corporation-nysebac/""><span
class=""tco-ellipsis""></span><span class=""invisible"">https://</span>
<span class=""js-display-url"">good-
stockinvest.com/2017/11/29/ban</span><span class=""invisible"">k-of-
america-growth-is-back-bank-of-america-corporation-nysebac/</span><span
class=""tco-ellipsis""><span class=""invisible""> </span>…</span></a>
</p>
</div>"
</code>```

Below is my code:

```<code>from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()
</code>```

答:
First you have a couple of errors, you used a for to iterate over the tweets but you are writing the tweets instead of tweet,

Also if you want it to be line by line instead of comma separated values you could change from using csv to use

with open(fine_name,'w') as file_output:
       for tweet in tweets:
            file_output.write(tweet)

that way it will be one line per tweet,
also you could use
file_output = open(file_name,'w')
 for tweet in tweets:
     file_output.write()
 file_output.close()

its up to you

Title: Python Web Scraper + Cleanup

Body:
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

"

*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (NYSE:BAC) https://
good-
stockinvest.com/2017/11/29/bank-of-
america-growth-is-back-bank-of-america-corporation-nysebac/ …

"

Below is my code:

from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()