问:
App won't run when apk is shared with friend
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Manifest.xml:

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

Any help?

答: Go to build and then click on generate/build apk. The apks generated by clicking on run are for devices with same API level.</p>

Body:
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Manifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Any help?


来源: stackexchange

问:
Suggestions for defining limits of frequencies in Matlab Spectrogram function?
I am new to Matlab and signal processing. I am having an issue with defining the frequency range in which the spectrogram is processed. When I am plotting the spectrogram of .wav audio data, the y axis, frequency, spans from zero to around 23 kHz. The useful data I am looking for is in the range of 200-400 Hz. My code snippet is:

```<code>[samFa, fs] = audioread('samFa.wav'); %convert audio to numerical data
samFa = samFa(:,1); %take only one channel of numerical output
spectrogram(samFA,2205,1200,12800, fs,'yaxis','MinThreshold',-80);
</code>```

I don't want to be some noobie that runs into a problem and instantly gives up and posts a duplicate question to stackoverflow, so I have done as much digging as I can, but am at my wit's end.

I scoured the documentation for parameters or ways to have Matlab only analyze a subset or range of the data, but found nothing. Additionally, in all of the examples the frequency range seems to automatically adapt to the data set.

I know it is possible to just calculate the spectrogram for the entire range of frequencies, and then remove all of the unnecessary data through truncating or manually changing the limits in the plot itself, but changing plotting limits does not help with the numerical data.

I went searching through many similar questions, and found an answer all the way from 2012 here: Can I adjust spectogram frequency axes?
where the suggested answer was to import a vector of specific frequencies for the spectrogram to analyze. I tried passing a vector of integer values between 200 and 400, and a few other test ranges, but got the error:

```<code>Error using welchparse>welch_options (line 297)
The sampling frequency must be a scalar.
</code>```

I've tried passing the parameter in at different places in the function, with no avail, and don't see anything regarding this parameter in the documentation, leading me to believe that this functionality was possibly removed sometime between 2012 and now.

When plotting spectrogram without providing signal frequency, Matlab provides a normalized spectrogram, which only provides a much smaller data window, which I can visually assess to cover the data from 0:5kHz (an artifact of overtones in the audio), so I know that matlab is not finding any data above this range to make the frequency range go to 20kHz

I've been trying to learn some signal processing for this project, so I believe the Nyquist frequency should be the maximum frequency that a Fourier transform is able to analyze, to be half the sampling frequency. My recording frequency is sampling at 44,100 Hz, and the spectrogram is ranging to around 22 or 23 kHz, leading me to believe that it's Matlab is noticing my sampling frequency and assuming that it needs to analyze up to such a high range.

For my work I am doing I am needing to produce thousands of spectrograms to then be processed through much further analysis, so it is very time consuming for Matlab to be processing so much unecessary data, and I would expect there to be some functionality in Matlab somehow to get around this.

Sorry for the very long post, but I wanted to fully explain my problem and show that I have done as much work as I could to solve the problem before turning for help. Thank you very much.

答:
Get the axis handle and set the visual range there:

```<code>spectrogram(samFA,2205,1200,12800, fs,'yaxis','MinThreshold',-80);
ax=gca;
ylim(ax, [0.2,0.4]); %kHz
</code>```

And if you want to calculate specific frequencies range to save time you better use goertzel.

```<code>f = 200:10:400;
freq_indices = round(f/fs*N) + 1;
dft_data = goertzel(data,freq_indices);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Matlab and signal processing. I am having an issue with defining the frequency range in which the spectrogram is processed. When I am plotting the spectrogram of .wav audio data, the y axis, frequency, spans from zero to around 23 kHz. The useful data I am looking for is in the range of 200-400 Hz. My code snippet is:

[samFa, fs] = audioread('samFa.wav'); %convert audio to numerical data
samFa = samFa(:,1); %take only one channel of numerical output
spectrogram(samFA,2205,1200,12800, fs,'yaxis','MinThreshold',-80);

I don't want to be some noobie that runs into a problem and instantly gives up and posts a duplicate question to stackoverflow, so I have done as much digging as I can, but am at my wit's end.

I scoured the documentation for parameters or ways to have Matlab only analyze a subset or range of the data, but found nothing. Additionally, in all of the examples the frequency range seems to automatically adapt to the data set.

I know it is possible to just calculate the spectrogram for the entire range of frequencies, and then remove all of the unnecessary data through truncating or manually changing the limits in the plot itself, but changing plotting limits does not help with the numerical data.

I went searching through many similar questions, and found an answer all the way from 2012 here: Can I adjust spectogram frequency axes?
where the suggested answer was to import a vector of specific frequencies for the spectrogram to analyze. I tried passing a vector of integer values between 200 and 400, and a few other test ranges, but got the error:

Error using welchparse>welch_options (line 297)
The sampling frequency must be a scalar.

I've tried passing the parameter in at different places in the function, with no avail, and don't see anything regarding this parameter in the documentation, leading me to believe that this functionality was possibly removed sometime between 2012 and now.

When plotting spectrogram without providing signal frequency, Matlab provides a normalized spectrogram, which only provides a much smaller data window, which I can visually assess to cover the data from 0:5kHz (an artifact of overtones in the audio), so I know that matlab is not finding any data above this range to make the frequency range go to 20kHz

I've been trying to learn some signal processing for this project, so I believe the Nyquist frequency should be the maximum frequency that a Fourier transform is able to analyze, to be half the sampling frequency. My recording frequency is sampling at 44,100 Hz, and the spectrogram is ranging to around 22 or 23 kHz, leading me to believe that it's Matlab is noticing my sampling frequency and assuming that it needs to analyze up to such a high range.

For my work I am doing I am needing to produce thousands of spectrograms to then be processed through much further analysis, so it is very time consuming for Matlab to be processing so much unecessary data, and I would expect there to be some functionality in Matlab somehow to get around this.

Sorry for the very long post, but I wanted to fully explain my problem and show that I have done as much work as I could to solve the problem before turning for help. Thank you very much.

Body:
Get the axis handle and set the visual range there:

spectrogram(samFA,2205,1200,12800, fs,'yaxis','MinThreshold',-80);
ax=gca;
ylim(ax, [0.2,0.4]); %kHz

And if you want to calculate specific frequencies range to save time you better use goertzel.

f = 200:10:400;
freq_indices = round(f/fs*N) + 1;
dft_data = goertzel(data,freq_indices);


问:
Reading from a file in assembly
I'm trying to learn assembly -- x86 in a Linux environment.  The most useful tutorial I can find is Writing A Useful Program With NASM.  The task I'm setting myself is simple: read a file and write it to stdout.

This is what I have:

```<code>section  .text              ; declaring our .text segment
  global  _start            ; telling where program execution should start

_start:                     ; this is where code starts getting exec'ed

  ; get the filename in ebx
    pop   ebx               ; argc
    pop   ebx               ; argv[0]
    pop   ebx               ; the first real arg, a filename

  ; open the file
    mov   eax,  5           ; open(
    mov   ecx,  0           ;   read-only mode
    int   80h               ; );

  ; read the file
    mov     eax,  3         ; read(
    mov     ebx,  eax       ;   file_descriptor,
    mov     ecx,  buf       ;   *buf,
    mov     edx,  bufsize   ;   *bufsize
    int     80h             ; );

  ; write to STDOUT
    mov     eax,  4         ; write(
    mov     ebx,  1         ;   STDOUT,
  ; mov     ecx,  buf       ;   *buf
    int     80h             ; );

  ; exit
    mov   eax,  1           ; exit(
    mov   ebx,  0           ;   0
    int   80h               ; );
</code>```

A crucial problem here is that the tutorial never mentions how to create a buffer, the bufsize variable, or indeed variables at all.

How do I do this?

(An aside: after at least an hour of searching, I'm vaguely appalled at the low quality of resources for learning assembly.  How on earth does any computer run when the only documentation is the hearsay traded on the 'net?)

答:
you must declare your buffer in bss section and the bufsize in data</p>

```<code>section .data
   bufsize dw      1024

section .bss
   buf     resb    1024
</code>```

ContentLicense: CC BY-SA 2.5

Title: Reading from a file in assembly

Body:
I'm trying to learn assembly -- x86 in a Linux environment.  The most useful tutorial I can find is Writing A Useful Program With NASM.  The task I'm setting myself is simple: read a file and write it to stdout.

This is what I have:

section  .text              ; declaring our .text segment
  global  _start            ; telling where program execution should start

_start:                     ; this is where code starts getting exec'ed

  ; get the filename in ebx
    pop   ebx               ; argc
    pop   ebx               ; argv[0]
    pop   ebx               ; the first real arg, a filename

  ; open the file
    mov   eax,  5           ; open(
    mov   ecx,  0           ;   read-only mode
    int   80h               ; );

  ; read the file
    mov     eax,  3         ; read(
    mov     ebx,  eax       ;   file_descriptor,
    mov     ecx,  buf       ;   *buf,
    mov     edx,  bufsize   ;   *bufsize
    int     80h             ; );

  ; write to STDOUT
    mov     eax,  4         ; write(
    mov     ebx,  1         ;   STDOUT,
  ; mov     ecx,  buf       ;   *buf
    int     80h             ; );

  ; exit
    mov   eax,  1           ; exit(
    mov   ebx,  0           ;   0
    int   80h               ; );

A crucial problem here is that the tutorial never mentions how to create a buffer, the bufsize variable, or indeed variables at all.

How do I do this?

(An aside: after at least an hour of searching, I'm vaguely appalled at the low quality of resources for learning assembly.  How on earth does any computer run when the only documentation is the hearsay traded on the 'net?)

Body:
you must declare your buffer in bss section and the bufsize in data

section .data
   bufsize dw      1024

section .bss
   buf     resb    1024


问:
Better way then sorting dictionary and getting keys only
I have a dictionary of customers and associated data (e.g. MoneySpent) and would like to return the sorted list of customers only.
The only solution I figured out so far is this:

```<code>CustomerData<Customer, int>  //the value here is the money spent
List<KeyValuePair<Customer, int>> sortedListByValue = CustomerData.OrderByDescending(s => s.Value).ToList();
</code>```

Then just going throug the list and obtaining keys. However, I am sure there is an easier way of doing and would be glad for advice.

答:
You can select the Key which will give you the customers.

```<code>var sortedListByValue = CustomerData.OrderByDescending(s => s.Value)
    .Select(x => x.Key).ToList();
</code>```

Body:
I have a dictionary of customers and associated data (e.g. MoneySpent) and would like to return the sorted list of customers only.
The only solution I figured out so far is this:

CustomerData<Customer, int>  //the value here is the money spent
List<KeyValuePair<Customer, int>> sortedListByValue = CustomerData.OrderByDescending(s => s.Value).ToList();

Then just going throug the list and obtaining keys. However, I am sure there is an easier way of doing and would be glad for advice.

Body:
You can select the Key which will give you the customers.

var sortedListByValue = CustomerData.OrderByDescending(s => s.Value)
    .Select(x => x.Key).ToList();


问:
Tensorflow object detection API:Sample program not working as expected
I am running sample program which comes packaged with Tensorflow object detection API(object_detection_tutorial.ipynb).
Program runs fine with no error, but bounding boxes are not diaplayed at all.

My environment is as follows:

Windows 10

Python 3.6.3

What can be the reason?

With regards

Manish

答: Please try updated SSD models in the detection zoo : https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md. This should be fixed.</p>


问:
Is it good practice to use exceptions for control flow in Ruby or Ruby on Rails?
I am reading Agile Web Development with Rails (4th ed.) and I have found the following code

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery

  private

  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end
end
</code>```

Since I am a Java developer, my understanding of that part of code is more or less the following:

```<code>private Cart currentCard(){
  try{
    return CartManager.get_cart_from_session(cartId)
  }catch(RecordNotFoundEx e){
    Cart c = CartManager.create_cart_and_add_to_session(new Cart())
    return c;
  }
}
</code>```

That what strikes me is that the exception handling is used to control normal application flow (lack of Cart is perfectly normal behaviour when user visits Depot application for the first time).

If one takes any Java book, they say that this is a very bad thing to do - and for a good reason: error handling shouldn't be used as a replacement for control statements, it's kind of misleading for those who read code.

Is there any good reason why such a practice is justified in Ruby (Rails)? Is this a common practice in Ruby?

答:
For the specific use case, you can simply do

```<code>def current_cart
  cart = Cart.find_or_create_by_id(session[:cart_id])
  session[:cart_id] = cart.id
  cart
end
</code>```

This may seem like it will set a specific id for a new record it creates, but since id is always a protected attribute, it will not be set for a new record. You will either get the record with the specified id, or if that doesn't exist, a new record with a new id.

Body:
I am reading Agile Web Development with Rails (4th ed.) and I have found the following code

class ApplicationController < ActionController::Base
  protect_from_forgery

  private

  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end
end

Since I am a Java developer, my understanding of that part of code is more or less the following:

private Cart currentCard(){
  try{
    return CartManager.get_cart_from_session(cartId)
  }catch(RecordNotFoundEx e){
    Cart c = CartManager.create_cart_and_add_to_session(new Cart())
    return c;
  }
}

That what strikes me is that the exception handling is used to control normal application flow (lack of Cart is perfectly normal behaviour when user visits Depot application for the first time).

If one takes any Java book, they say that this is a very bad thing to do - and for a good reason: error handling shouldn't be used as a replacement for control statements, it's kind of misleading for those who read code.

Is there any good reason why such a practice is justified in Ruby (Rails)? Is this a common practice in Ruby?

Body:
For the specific use case, you can simply do

def current_cart
  cart = Cart.find_or_create_by_id(session[:cart_id])
  session[:cart_id] = cart.id
  cart
end

This may seem like it will set a specific id for a new record it creates, but since id is always a protected attribute, it will not be set for a new record. You will either get the record with the specified id, or if that doesn't exist, a new record with a new id.


答: I think you have the problem in APK version. check your mobile APK version and your targeted APK version. your App will not run Lower then APK version 25 as you built with 25.0.0</p>

Title: App won't run when apk is shared with friend


问:
How to add a button to go to new activity in android app
I want to add a 'button' that leads to a new activity inside of my main activity of my app. I cannot get this button to respond inside of this main activity. I tried to put the following in my current code:

```<code>public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private ImageView photoImageView;
    private TextView nameTextView;
    private TextView emailTextView;
    private TextView idTextView;

    private GoogleApiClient googleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        photoImageView = (ImageView) findViewById(R.id.photoImageView);
        nameTextView = (TextView) findViewById(R.id.nameTextView);
        emailTextView = (TextView) findViewById(R.id.emailTextView);
        idTextView = (TextView) findViewById(R.id.idTextView);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

// I want something like this - click a textView to go to the new activity

        TextView listViewItem = (TextView) findViewById(R.id.textView11);
        listViewItem.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });

    }
// end

    @Override
    protected void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
        if (opr.isDone()) {
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }
</code>```

How can I get this button to go to my new activity? I am using a text view as a button currently. Is this my problem?

```<code> <LinearLayout
    <TextView
        android:id="@+id/textView11"
        android:text="One"
        tools:layout_editor_absoluteY="70dp" />
</LinearLayout>
</code>```

答:
```<code><TextView
     android:id="@+id/text_view"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="text";
     android:textSize="28sp" />
</code>```

Body:
I want to add a 'button' that leads to a new activity inside of my main activity of my app. I cannot get this button to respond inside of this main activity. I tried to put the following in my current code:

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    private ImageView photoImageView;
    private TextView nameTextView;
    private TextView emailTextView;
    private TextView idTextView;

    private GoogleApiClient googleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        photoImageView = (ImageView) findViewById(R.id.photoImageView);
        nameTextView = (TextView) findViewById(R.id.nameTextView);
        emailTextView = (TextView) findViewById(R.id.emailTextView);
        idTextView = (TextView) findViewById(R.id.idTextView);

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

// I want something like this - click a textView to go to the new activity

        TextView listViewItem = (TextView) findViewById(R.id.textView11);
        listViewItem.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });

    }
// end

    @Override
    protected void onStart() {
        super.onStart();

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
        if (opr.isDone()) {
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

How can I get this button to go to my new activity? I am using a text view as a button currently. Is this my problem?

 <LinearLayout
    <TextView
        android:id="@+id/textView11"
        android:text="One"
        tools:layout_editor_absoluteY="70dp" />
</LinearLayout>


问:
Networking for Xna (C#) and C++?
Me and some friends were thinking about making an online game with XNA game studio. Our games mainly used Winsock for the networking portion, but our most recent project used RakNet where the server was in C++ and the Client used a small RakNet wrapper I wrote. As far as I know XNA can't really use DLLs, so I was wondering what a good networking solution would be.

1) C# already has some networking capabilities, but would it be a bad idea to write a server in C#. I've primarily used C++ for the raw power it has.

2) If it's a bad idea to write server in C#, are their any libraries that will work with C++ and C#? Or maybe I could just use the C# networking for the client, and Winsock for the server (if they are compatible.. I assume C# uses standard TCP layers..)?

Hopefully you guys have some suggestions for networking options.

Thanks in advance!

答:
There is nothing wrong with writing a server in C#.

The open source MMORPG software that simulates a Ultima Online server, RunUO, runs in C# with good results.

Yes, Winsock and C# Sockets are compatible.

Title: Networking for Xna (C#) and C++?


问:
Save method not persisting entity object Spring Data JPA
I am moving my current code from hibernate and mybatis to spring data jpa.I configured spring data with my existing application and tried to perform certain operations.

When I tried to persist an entity using save(T t) it didn't return any exception and returned same entity object as result but didn't persist.

Persistence.xml

```<code><context:annotation-config />

<tx:annotation-driven />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="com.mysql.jdbc.Driver" p:url="${db.url}"
    p:username="${db.username}" p:password="${db.password}" />

<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.moneyhaul.dao.model</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<!--<tx:annotation-driven transaction-manager="transactionManager" />-->
</code>```

```<code><!--
          Configure Spring Data JPA and set the base package of the
          repository interfaces
        -->
<jpa:repositories base-package="com.moneyhaul.repositary"/>

    <!-- Create default configuration for Hibernate -->
    <bean id="hibernateJpaVendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

    <!-- Configure the entity manager factory bean -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <!-- Set JPA properties -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="javax.persistence.schema-generation.database.action">none</prop>
                <prop key="hibernate.ejb.use_class_enhancer">false</prop>
            </props>
        </property>
        <!-- Set base package of your entities -->
        <property name="packagesToScan" value="com.moneyhaul.dao.model"/>
        <!-- Set share cache mode -->
        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
        <!-- Set validation mode -->
        <property name="validationMode" value="NONE"/>

    </bean>

    <!-- Configure the transaction manager bean -->
    <bean id="transactionManagerJpa"
          class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!-- Enable annotation driven transaction management -->
    <tx:annotation-driven transaction-manager="transactionManagerJpa"/>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- Mybatis session factory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
    p:dataSource-ref="dataSource" p:configLocation="WEB-INF/mybatis/sqlmap-config.xml" />

<bean id="caarmoMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.CaarmoMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="paymentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.PaymentMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="reportingMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ReportingMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="reportingTrendsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ReportingTrendsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="customerDBMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.CustomerDBMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="vehicleDBMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.VehicleDBMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="geomaticsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.GeomaticsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="serviceCenterMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ServiceCenterMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="moneyhaulMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.moneyhaul.mapper.MoneyHaulMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="mhGeomaticsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.moneyhaul.mapper.MHGeomaticsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="configurationMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ConfigurationMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />
</code>```

DriverRepositary.java

```<code>@Repository
public interface DriverRepositary extends CrudRepository<Driver,Long>{}
</code>```

Persisting entity

```<code>@Transactional
public void addDriver(Driver driver) {
    driver.setTabletPassword(setDriverPassword(driver.getPhone()));
    driver.setUpdated(new Date());
    driverRepositary.save(driver);

}
</code>```

答:
Can you just check the following :

There are two Transaction Manager Bean which are declared. Are they required?

Why do you need session factory bean declaration ?

Set the hibernate.show_sql to true as part of JPA Properties (for debugging)

Are explicitly setting the primary key OR are you using a sequence?

Also if possible provide all the logs available from server startup till this error point for any further analysis.

Body:
I am moving my current code from hibernate and mybatis to spring data jpa.I configured spring data with my existing application and tried to perform certain operations.

When I tried to persist an entity using save(T t) it didn't return any exception and returned same entity object as result but didn't persist.

Persistence.xml

<context:annotation-config />

<tx:annotation-driven />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="com.mysql.jdbc.Driver" p:url="${db.url}"
    p:username="${db.username}" p:password="${db.password}" />

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.moneyhaul.dao.model</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<jpa:repositories base-package="com.moneyhaul.repositary"/>

    <bean id="hibernateJpaVendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="javax.persistence.schema-generation.database.action">none</prop>
                <prop key="hibernate.ejb.use_class_enhancer">false</prop>
            </props>
        </property>

        <property name="packagesToScan" value="com.moneyhaul.dao.model"/>

        <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>

        <property name="validationMode" value="NONE"/>

    </bean>

    <bean id="transactionManagerJpa"
          class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManagerJpa"/>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
    p:dataSource-ref="dataSource" p:configLocation="WEB-INF/mybatis/sqlmap-config.xml" />

<bean id="caarmoMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.CaarmoMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="paymentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.PaymentMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="reportingMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ReportingMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="reportingTrendsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ReportingTrendsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="customerDBMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.CustomerDBMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="vehicleDBMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.VehicleDBMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="geomaticsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.GeomaticsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="serviceCenterMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ServiceCenterMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="moneyhaulMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.moneyhaul.mapper.MoneyHaulMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="mhGeomaticsMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.moneyhaul.mapper.MHGeomaticsMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

<bean id="configurationMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"
    p:mapperInterface="com.caarmo.mapper.ConfigurationMapper"
    p:sqlSessionFactory-ref="sqlSessionFactory" />

DriverRepositary.java

@Repository
public interface DriverRepositary extends CrudRepository<Driver,Long>{}

Persisting entity

@Transactional
public void addDriver(Driver driver) {
    driver.setTabletPassword(setDriverPassword(driver.getPhone()));
    driver.setUpdated(new Date());
    driverRepositary.save(driver);

}


问:
Oozie Hive Action keeps failing due to parameter assignment?
I'm trying to test out running a simple Hive script using Oozie, but I keep getting an error that I cannot make sense of.

Every time I submit a job, I get an error message that says "Job failed, error message[Parameter expression must contain an assignment: jobRequest]". However, I have this parameter defined and assign it a value when I originally submit the config.

The parameter in question is for an external hive table name that I'm trying to create. In the Oozie workflow, I define the table name parameter that is getting passed to the Hive script here:

```<code><param>${hiveTableName}</param>
</code>```

I then create a job.xml that I submit to oozie, where this parameter is assigned the value like so:

```<code><property>
    <name>hiveTableName</name>
    <value>jobRequest</value>
</property>
</code>```

Has anyone else ran into an issue like this or have any idea of what might be causing it? It seems like the parameter is properly defined and assigned, but the job keeps failing with the above error message. If it helps, the xml namespace that I'm using is:

```<code><hive xmlns="uri:oozie:hive-action:0.2">
</code>```

答:
I get an error message that says "Job failed, error message[Parameter expression must contain an assignment: jobRequest]"

Its complaining that the assignment operator is missing in the param tag. Check the documentation for more details https://oozie.apache.org/docs/3.3.1/DG_HiveActionExtension.html

First solution, using property tag Use like below

```<code><property>
    <name>hiveTableName</name>
    <value>jobRequest</value>
</property>
</code>```

Add param like this :

```<code> <param>hiveTableName=${hiveTableName}</param>
</code>```

Second solution via job.properties :
you want to pass the parameter with <param> tag, define the variable in your job.properties and then pass with the <param> tag.

e.g In job.properties add,

```<code>hiveTableName=jobRequest
</code>```

then put <param>hiveTableName=${hiveTableName}</param> in the oozie workflow hive action

Body:
I'm trying to test out running a simple Hive script using Oozie, but I keep getting an error that I cannot make sense of.

Every time I submit a job, I get an error message that says "Job failed, error message[Parameter expression must contain an assignment: jobRequest]". However, I have this parameter defined and assign it a value when I originally submit the config.

The parameter in question is for an external hive table name that I'm trying to create. In the Oozie workflow, I define the table name parameter that is getting passed to the Hive script here:

<param>${hiveTableName}</param>

I then create a job.xml that I submit to oozie, where this parameter is assigned the value like so:

<property>
    <name>hiveTableName</name>
    <value>jobRequest</value>
</property>

Has anyone else ran into an issue like this or have any idea of what might be causing it? It seems like the parameter is properly defined and assigned, but the job keeps failing with the above error message. If it helps, the xml namespace that I'm using is:

<hive xmlns="uri:oozie:hive-action:0.2">

Body:
I get an error message that says "Job failed, error message[Parameter expression must contain an assignment: jobRequest]"

Its complaining that the assignment operator is missing in the param tag. Check the documentation for more details https://oozie.apache.org/docs/3.3.1/DG_HiveActionExtension.html

First solution, using property tag Use like below

<property>
    <name>hiveTableName</name>
    <value>jobRequest</value>
</property>

Add param like this :

 <param>hiveTableName=${hiveTableName}</param>

Second solution via job.properties :
you want to pass the parameter with <param> tag, define the variable in your job.properties and then pass with the <param> tag.

e.g In job.properties add,

hiveTableName=jobRequest

then put <param>hiveTableName=${hiveTableName}</param> in the oozie workflow hive action


问:
Cocoapods deployment target issue
I am using cocoapods to update Google maps to updated version 2.5.0. Using pod  ‘GoogleMaps’, '~> 2.5.0’ in pod file, but when i install it gives me the mentioned error.

答:
There is a dependency of the google maps library by two of your other libraries. Those are Google Places, Google Maps/Maps. That's why it's not able to update it. Update all libraries related to google maps will solve your problem.

Use pod update to update all libraries

Title: Cocoapods deployment target issue


问:
Dropdown Menu Slow Response and Disappearing on Hover
I'm having issues with my dropdown navigation for just this page. The response times on the navigation are extremely slow, and the dropdown menu will show momentarily on hover, but quickly disappears. I'm unsure if it has to do with the main element below, or not. If you have any insight or help, it would be great. I'm a graphic major, not web, so this isn't my forte.

body{
 background-color: white;
}

#page-wrapper{
 margin-left: auto;
 margin-right: auto;
 width: 960px;
 height: auto;
 background-image: url(Images/brick-wall-2209991.jpg);
 background-repeat: repeat-y;
}

li {
 text-align: center;
 display: inline;
}

a {
    text-decoration: none;
}

.span01,.span02,.span03,.span04,.span05,.span06,.span07,.span08,.span09,.span10,.span11,.span12
{
 display: inline;
 float: left;
 margin-left: 10px;
 margin-right: 10px;
}

.first-child{
 margin-left: 0;
}

.last-child{
 margin-right: 0;
}

.span01 {
 width: 60px;
}

.span02 {
 width: 140px;
}

.span03 {
width: 220px;
}

.span04 {
width: 300px;
}

.span05 {
width: 380px;
}

.span06 {
width: 460px;
}

.span07 {
width: 540px;
}

.span08 {
width: 620px;
}

.span09 {
width: 700px;
}

.span10 {
width: 780px;
}

.span11 {
width: 860px;
}

.span12 {
width: 940px;
}

.reset{
 clear: both;
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0px;
}

.header {height: 115px;
   background-color: #1e241b;
  width: 960px;
}

/********Navigation********/

ul { margin-right: 20px;}

li {text-align: center;
 display: inline;
 font-family: 'Josefin Sans', sans-serif;
 font-size: 14pt;
 text-transform: uppercase;
 font-weight: bold;
 letter-spacing: 1px;
 color: #d98a79;

    }
li a:link {color: #d98a79;}

li a:visited {
    color: #d98a79;
}

li a:hover {
 text-decoration-color: white;
 color: white;

}

li a:active {
    color: white;
}

nav {text-align: center;
 padding-left: 110px;
 margin-top: 30px;
 float: right;
 margin-right: 70px;
 }
nav ul ul {
 display: none;
 position: absolute;
 top: 100%;
}

nav ul ul li {
 float: none;
 position: relative;
 text-align: left;
}

nav ul ul li a {
 padding-top: 15px;
 margin-top: 0px;
 padding-bottom: 15px;
 margin-left: -10px;
 margin-right: 15px;
 text-align: left;

}

nav ul li:hover > ul {
 display: block;
}

nav ul {
 background-color: #1e241b;
 list-style: none;
 position: relative;
 display: inline-table;
}

nav ul:after {
 content: "";
 clear: both;
 display: block;
}

nav ul li {
 float: left;
}

nav ul li a{
 display: block;
 padding: 10px 8px;

}
.bar {height: 190px;
 background-color: rgba(0,0,0,0.75);
 position: relative;
 margin-top: 20px;
}

h1 {
 font-family: 'Josefin Sans', sans-serif;
 text-align: right;
 text-transform: uppercase;
 color: white;
 font-size: 90pt;
 position: relative;
 top:-140px;
 left: -40px;
 margin-bottom: -140px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta charset="UTF-8">
<title>Sous Vide - About</title>
<link href="secondary.css" rel="stylesheet" type="text/css">
<style>
@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');
@import url('https://fonts.googleapis.com/css?family=Barlow+Semi+Condensed');
</style>
</head>

<body>

<div id="page-wrapper">

 <header class="span12 header first-child last-child">

  <nav class="span12">

   <ul>
    <li>Home</li>
    <li>About Us
     <ul>
      <li>About Us</li>
      <li>FAQ</li>
     </ul>
    </li>
    <li>Menus
     <ul>
      <li>Seasonal Menu</li>
      <li>Breakfast Menu</li>
      <li>Lunch Menu</li>
     </ul>
    </li>
    <li>Catering</li>
    <li>Gallery</li>
    <li>Locations</li>
    </ul>

  </nav>
     </header>
<div class="reset"></div>

 <main class="bar span12"></main>
  <h1>About Us</h1>

<div class="reset"></div></code>```

答:
hi try this: it will work

```<code>h1{
clear:both;
}
</code>```

Body:
I'm having issues with my dropdown navigation for just this page. The response times on the navigation are extremely slow, and the dropdown menu will show momentarily on hover, but quickly disappears. I'm unsure if it has to do with the main element below, or not. If you have any insight or help, it would be great. I'm a graphic major, not web, so this isn't my forte.

body{
 background-color: white;
}

#page-wrapper{
 margin-left: auto;
 margin-right: auto;
 width: 960px;
 height: auto;
 background-image: url(Images/brick-wall-2209991.jpg);
 background-repeat: repeat-y;
}

li {
 text-align: center;
 display: inline;
}

a {
    text-decoration: none;
}

.span01,.span02,.span03,.span04,.span05,.span06,.span07,.span08,.span09,.span10,.span11,.span12
{
 display: inline;
 float: left;
 margin-left: 10px;
 margin-right: 10px;
}

.first-child{
 margin-left: 0;
}

.last-child{
 margin-right: 0;
}

.span01 {
 width: 60px;
}

.span02 {
 width: 140px;
}

.span03 {
width: 220px;
}

.span04 {
width: 300px;
}

.span05 {
width: 380px;
}

.span06 {
width: 460px;
}

.span07 {
width: 540px;
}

.span08 {
width: 620px;
}

.span09 {
width: 700px;
}

.span10 {
width: 780px;
}

.span11 {
width: 860px;
}

.span12 {
width: 940px;
}

.reset{
 clear: both;
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0px;
}

.header {height: 115px;
   background-color: #1e241b;
  width: 960px;
}

/********Navigation********/

ul { margin-right: 20px;}

li {text-align: center;
 display: inline;
 font-family: 'Josefin Sans', sans-serif;
 font-size: 14pt;
 text-transform: uppercase;
 font-weight: bold;
 letter-spacing: 1px;
 color: #d98a79;

    }
li a:link {color: #d98a79;}

li a:visited {
    color: #d98a79;
}

li a:hover {
 text-decoration-color: white;
 color: white;

}

li a:active {
    color: white;
}

nav {text-align: center;
 padding-left: 110px;
 margin-top: 30px;
 float: right;
 margin-right: 70px;
 }
nav ul ul {
 display: none;
 position: absolute;
 top: 100%;
}

nav ul ul li {
 float: none;
 position: relative;
 text-align: left;
}

nav ul ul li a {
 padding-top: 15px;
 margin-top: 0px;
 padding-bottom: 15px;
 margin-left: -10px;
 margin-right: 15px;
 text-align: left;

}

nav ul li:hover > ul {
 display: block;
}

nav ul {
 background-color: #1e241b;
 list-style: none;
 position: relative;
 display: inline-table;
}

nav ul:after {
 content: "";
 clear: both;
 display: block;
}

nav ul li {
 float: left;
}

nav ul li a{
 display: block;
 padding: 10px 8px;

}
.bar {height: 190px;
 background-color: rgba(0,0,0,0.75);
 position: relative;
 margin-top: 20px;
}

h1 {
 font-family: 'Josefin Sans', sans-serif;
 text-align: right;
 text-transform: uppercase;
 color: white;
 font-size: 90pt;
 position: relative;
 top:-140px;
 left: -40px;
 margin-bottom: -140px;
}

<meta charset="UTF-8">
<title>Sous Vide - About</title>
<link href="secondary.css" rel="stylesheet" type="text/css">

Home

About Us

About Us

FAQ

Menus

Seasonal Menu

Breakfast Menu

Lunch Menu

Catering

Gallery

Locations

About Us

Body:
hi try this: it will work

h1{
clear:both;
}


问:
R plot function gives out weird answer
I tried to use R plot to get the curve for some functions. Sometimes, I got very weird results. Here is an example

```<code>u=c(2,2,2,2,2)
elas=function(P){
  prob=P/sum(u,P)
  return(prob)
}
plot(elas,0,6)
</code>```

This code gives out the plot like this:

It is obviously not right. The right code should be like this:

I know that if I change the 3rd line of the code to be

```<code>  prob=P/(sum(u)+P)
</code>```

It would work. But I do not understand why my original code does not work. Does it mean that I cannot plot a function which embeds another function?

Title: R plot function gives out weird answer

Body:
I tried to use R plot to get the curve for some functions. Sometimes, I got very weird results. Here is an example

u=c(2,2,2,2,2)
elas=function(P){
  prob=P/sum(u,P)
  return(prob)
}
plot(elas,0,6)

This code gives out the plot like this:

It is obviously not right. The right code should be like this:

I know that if I change the 3rd line of the code to be

  prob=P/(sum(u)+P)

It would work. But I do not understand why my original code does not work. Does it mean that I cannot plot a function which embeds another function?

Body:
sum(u,P) is a single value equal to the sum of all the values in u and P. So in elas, every value of P get's divided by the same number (313 in your example).

sum(u) + P is a vector containing each individual value of P with sum(u) added to it. So in the second version of elas (which I've called elas2 below), P/(sum(u) + P) results in element-by-element division of P by sum(u) + P.

Consider the examples below.

u=c(2,2,2,2,2)
x=seq(0,6,length=101)

sum(u,x)

[1] 313

sum(u) + x

  [1] 10.00 10.06 10.12 10.18 10.24 10.30 10.36 10.42 10.48 10.54 10.60 10.66 10.72 10.78
 [15] 10.84 10.90 10.96 11.02 11.08 11.14 11.20 11.26 11.32 11.38 11.44 11.50 11.56 11.62
 [29] 11.68 11.74 11.80 11.86 11.92 11.98 12.04 12.10 12.16 12.22 12.28 12.34 12.40 12.46
 [43] 12.52 12.58 12.64 12.70 12.76 12.82 12.88 12.94 13.00 13.06 13.12 13.18 13.24 13.30
 [57] 13.36 13.42 13.48 13.54 13.60 13.66 13.72 13.78 13.84 13.90 13.96 14.02 14.08 14.14
 [71] 14.20 14.26 14.32 14.38 14.44 14.50 14.56 14.62 14.68 14.74 14.80 14.86 14.92 14.98
 [85] 15.04 15.10 15.16 15.22 15.28 15.34 15.40 15.46 15.52 15.58 15.64 15.70 15.76 15.82
 [99] 15.88 15.94 16.00

par(mfrow=c(1,3))

elas=function(P) {
   P/sum(u,P)
}

dat = data.frame(x, y=elas(x), y_calc=x/sum(u,x))

plot(dat$x, dat$y, type="l", lwd=2, ylim=c(0,0.020))
plot(elas, 0, 6, lwd=2, ylim=c(0,0.020))
curve(elas, 0, 6, lwd=2, ylim=c(0,0.020))

dat$y - dat$y_calc

[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[43] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[85] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

elas2 = function(P) {
  P/(sum(u) + P)
}

dat$y2 = elas2(x)

plot(dat$x, dat$y2, type="l", lwd=2, ylim=c(0,0.4))
plot(elas2, 0, 6, lwd=2, ylim=c(0,0.4))
curve(elas2, 0, 6, lwd=2, ylim=c(0,0.4))


问:
STL std::remove_copy
```<code> std::remove_copy

 template <class InputIterator, class OutputIterator, class T>
 OutputIterator remove_copy (InputIterator first, InputIterator last,
                               OutputIterator result, const T& val);
</code>```

Copy range removing value, Copies the elements in the range
  [first,last) to the range beginning at result, except those elements
  that compare equal to val. The output container must be large enough
  to hold the result.

q1. Why the size of the output  container must be large enough to hold the result? Wont the container grow by itself?

q2. Why is the previous content in  the output container  overwritten when i perform a remove_copy? i.e When i perform a remove_copy(a.begin(),a.end(),b.begin(),' '); The previous content inside the container b are lost and they are replaced by the new contents why is it so? Why is the result of remove_copy not appended at the beginning of  the output container?

答:
Why the size of the output container must be large enough to hold the
  result? Wont the container grow by itself?

No. How could it? All the algorithm has is iterators, and you can't access a container's member functions (which would be required in order to grow the container) from its iterators. However, there are special purpose iterators which do know how to grow a container. std::front_insert_iterator, std::back_insert_iterator, and std::insert_iterator, which hold references to a container and call push_front, push_back and insert respectively whenever they are dereferenced and assigned to.

Why is the previous content in the output container overwritten when i
  perform a remove_copy?

Because that's just how the algorithm works. That's how all the standard library algorithms work. They don't know anything about containers. Not all iterators come from containers. And not all containers are even growable. If you want to append to the container, then use std::back_insert_iterator, as mentioned above. You can use the std::back_inserter helper function to conveniently create one without having to specify the template parameters. For example:

```<code>std::remove_copy(source.begin(), source.end(), std::back_inserter(dest), value);
</code>```

Title: STL std::remove_copy

Body:
 std::remove_copy

 template <class InputIterator, class OutputIterator, class T>
 OutputIterator remove_copy (InputIterator first, InputIterator last,
                               OutputIterator result, const T& val);

Copy range removing value, Copies the elements in the range
  [first,last) to the range beginning at result, except those elements
  that compare equal to val. The output container must be large enough
  to hold the result.

q1. Why the size of the output  container must be large enough to hold the result? Wont the container grow by itself?

q2. Why is the previous content in  the output container  overwritten when i perform a remove_copy? i.e When i perform a remove_copy(a.begin(),a.end(),b.begin(),' '); The previous content inside the container b are lost and they are replaced by the new contents why is it so? Why is the result of remove_copy not appended at the beginning of  the output container?

Body:
Why the size of the output container must be large enough to hold the
  result? Wont the container grow by itself?

No. How could it? All the algorithm has is iterators, and you can't access a container's member functions (which would be required in order to grow the container) from its iterators. However, there are special purpose iterators which do know how to grow a container. std::front_insert_iterator, std::back_insert_iterator, and std::insert_iterator, which hold references to a container and call push_front, push_back and insert respectively whenever they are dereferenced and assigned to.

Why is the previous content in the output container overwritten when i
  perform a remove_copy?

Because that's just how the algorithm works. That's how all the standard library algorithms work. They don't know anything about containers. Not all iterators come from containers. And not all containers are even growable. If you want to append to the container, then use std::back_insert_iterator, as mentioned above. You can use the std::back_inserter helper function to conveniently create one without having to specify the template parameters. For example:

std::remove_copy(source.begin(), source.end(), std::back_inserter(dest), value);


问:
note++ file is already open bug?
usually I could save and overwrite my file without any problem but now, a message keeps poping up when I try to/this thing</p>

答: Hey try to copy your code, afterwards close all tabs and then open a new tab and paste your code again. Then it should save again had this error a few times this solution fixed it most of the time.</p>

Title: note++ file is already open bug?


问:
Unable to start XAMPP Apache server on MacOS-Sierra
Whenever I'm trying to start my Apache server from XAMPP on my Macbook (MacOS-Sierra) . I'm getting following application log :

```<code>Starting Apache Web Server...
/Applications/XAMPP/xamppfiles/apache2/scripts/ctl.sh : httpd started
</code>```

And status remains Stopped. I re-install XAMPP and restarted my laptop multiple times, but I'm still having same issue. Couldn't find anything help to resolve this issue.

答:
Another related issue, which I faced caused Apache sever failure. And failure logs is :

```<code>[Sun Jul 30 12:43:58.747822 2017] [unique_id:alert] [pid 9188] (EAI 8)nodename nor servname provided, or not known: AH01564:
unable to find IPv4 address of "MacBook-Pro.local" AH00016: Configuration Failed
</code>```

To solve this :

Executed following command

```<code>sudo -e /etc/hosts
</code>```

Then, changed following entries

```<code>127.0.0.1    localhost
::1    localhost
</code>```

to

```<code>127.0.0.1    localhost MacBook-Pro.local
::1    localhost MacBook-Pro.local
</code>```

Body:
Whenever I'm trying to start my Apache server from XAMPP on my Macbook (MacOS-Sierra) . I'm getting following application log :

Starting Apache Web Server...
/Applications/XAMPP/xamppfiles/apache2/scripts/ctl.sh : httpd started

And status remains Stopped. I re-install XAMPP and restarted my laptop multiple times, but I'm still having same issue. Couldn't find anything help to resolve this issue.

Body:
Another related issue, which I faced caused Apache sever failure. And failure logs is :

[Sun Jul 30 12:43:58.747822 2017] [unique_id:alert] [pid 9188] (EAI 8)nodename nor servname provided, or not known: AH01564:
unable to find IPv4 address of "MacBook-Pro.local" AH00016: Configuration Failed

To solve this :

Executed following command

sudo -e /etc/hosts

Then, changed following entries

127.0.0.1    localhost
::1    localhost

to

127.0.0.1    localhost MacBook-Pro.local
::1    localhost MacBook-Pro.local


问:
Kotlin - chaining of safe call operator. unnecessary operator calls
Take the following example which uses safe call operator (?.):

```<code>class Sample {
    class A(
            val sampleB: B? = B()
    )

    class B(
            val sampleC: C = C()
    )

    class C(
            val sampleInt: Int = 1
    )

    fun test() {
        val intInC: Int? = A().sampleB?.sampleC?.sampleInt
    }
}
</code>```

I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC.
If I remove that operator, it does not compile.

Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?

答:
First of all, the safe call operator ?. will not break the chain of safe calls. When you write A().sampleB?.sampleC?.sampleInt, if A().sampleB is null, the chain will not stop at ?.sampleC but it will execute null?.sampleC. The type of A().sampleB?.sampleC will be C? but not C since it depends on the whole expression but not the type of the property. That's why ?. is needed if the previous expression is nullable.

If sampleB is the only nullable expression in the chain, you may consider using .run:

```<code>val intInC: Int? = A().sampleB?.run { sampleC.sampleInt }
</code>```

Body:
Take the following example which uses safe call operator (?.):

class Sample {
    class A(
            val sampleB: B? = B()
    )

    class B(
            val sampleC: C = C()
    )

    class C(
            val sampleInt: Int = 1
    )

    fun test() {
        val intInC: Int? = A().sampleB?.sampleC?.sampleInt
    }
}

I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC.
If I remove that operator, it does not compile.

Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?

Body:
First of all, the safe call operator ?. will not break the chain of safe calls. When you write A().sampleB?.sampleC?.sampleInt, if A().sampleB is null, the chain will not stop at ?.sampleC but it will execute null?.sampleC. The type of A().sampleB?.sampleC will be C? but not C since it depends on the whole expression but not the type of the property. That's why ?. is needed if the previous expression is nullable.

If sampleB is the only nullable expression in the chain, you may consider using .run:

val intInC: Int? = A().sampleB?.run { sampleC.sampleInt }


问:
App won't run when apk is shared with friend
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Manifest.xml:

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

Any help?

答:
I think you are lacking Runtime Permissions on API 23 or Above

Try giving Runtime permissions for Camera, Location and Phone. Here are examples of adding runtime permission.

https://developer.android.com/training/permissions/requesting.html

How to check Grants Permissions at Run-Time?

https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/

To check if lacking runtime permission is the problem Go to Phone Settings -> Apps -> Installed App -> Your App -> Permissions -> Allow Permissions there

Body:
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Manifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Any help?


问:
python - How to input distinct random numbers into a list using loop?
What I aim to do is to input 4 distinct numbers into a list called var. If 2 random numbers give the same number, it is not appended, and the loop iterates to pick a new random number. But my code will give only the list of random numbers that are not equal. For example if random numbers generated are 1,4,4,3 my list('var') will only have 1,4,3. ie, only 3 numbers in total. How to correct the code to append a total of 4 unique random numbers into the list?</p>

```<code>import random
var=[]
end=4
for i in range(0,end,1):
 k=random.randint(0,9)
 print k
 if k not in var:
  var.append(k)
 else:
  end+=1
</code>```

答:
So the requirement here is that you keep on doing that operation until your lenght of array is 4, so you can use while len(arr) < 4. Example coded for you :

```<code>import random
var=[]
end=4
while len(var) < end:
 k=random.randint(0,9)
 print k
 if k not in var:
  var.append(k)
</code>```

A better way to do this would be random.sample

```<code>>>> import random
>>> random.sample(range(0, 9), 4) # xrange is using python 2.7
</code>```

Read here.

Body:
What I aim to do is to input 4 distinct numbers into a list called var. If 2 random numbers give the same number, it is not appended, and the loop iterates to pick a new random number. But my code will give only the list of random numbers that are not equal. For example if random numbers generated are 1,4,4,3 my list('var') will only have 1,4,3. ie, only 3 numbers in total. How to correct the code to append a total of 4 unique random numbers into the list?

import random
var=[]
end=4
for i in range(0,end,1):
 k=random.randint(0,9)
 print k
 if k not in var:
  var.append(k)
 else:
  end+=1

Body:
So the requirement here is that you keep on doing that operation until your lenght of array is 4, so you can use while len(arr) < 4. Example coded for you :

import random
var=[]
end=4
while len(var) < end:
 k=random.randint(0,9)
 print k
 if k not in var:
  var.append(k)

A better way to do this would be random.sample

>>> import random
>>> random.sample(range(0, 9), 4) # xrange is using python 2.7

Read here.


问:
Scaling Geometry Path based on actual height and width with of a usercontrol is very slow
I have an application where I need to perform a fairly expensive calculation based on the actual width and height of a control. I have bound ActualWidth and ActualHeight of this control to properties in my code. I find that Actualheight is being changed in small steps. I assume this is because of the Layout Engine.

A stripped down version of the xAML is

```<code><UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sup="clr-namespace:RowAnimation.Support"
    xmlns:vm="clr-namespace:RowAnimation.ViewModels"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:RowAnimation.Views"
    x:Name="RowerAnimation"
    x:Class="RowAnimation.Views.RowerAnimationControl"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance {x:Type vm:RowerAnimationControlVM}}"
             d:DesignHeight="497" d:DesignWidth="741">
    <Grid>
        <DockPanel >
            <Grid Margin="5" x:Name="canvas1" ClipToBounds="True" VerticalAlignment="Top">
                <sup:DataPiping.DataPipes>
                    <sup:DataPipeCollection>
                        <sup:DataPipe Source="{Binding ActualWidth, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"
                                    Target="{Binding ViewportWidth, Mode=OneWayToSource}"/>
                        <sup:DataPipe Source="{Binding ActualHeight, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"
                                    Target="{Binding ViewportHeight, Mode=OneWayToSource}"/>
                    </sup:DataPipeCollection>
                </sup:DataPiping.DataPipes>
                <Path x:Name="gridLines" Stroke="#FF6083E2" Data="{Binding GridPath, Mode=OneWay}"/>
            </Grid>
        </DockPanel>
    </Grid>
</UserControl>
</code>```

The GridPath is set in my ViewModel when the ViewportHeight or ViewportWidth property in the ViewModel is changed.

When I set a breakpoint in my ViewModel I find that ViewportWidth is changed once but the ViewportHeight is changed multiple times in small increments. When I comment out the method that calculates the GridPath then the VieportHeight break point hits only once. So it looks like the setting of GridPath triggers a new Layout calculation.

In my actual implementation I also have a Grid docked to the bottom of the control, which is why I have the Dockpanel in the XAML.

Since I am using MVVM I use DataPiping from this Stackoverflow link to get the ActualHeight and ActualWidth in my ViewModel.

Does anybody have an idea what is going on and how I might avoid it? As it is the setting of the GridPath (and I actually have more PathGeometries in my actual implementation) can make resizing my window take more than 8 seconds.

In addition:

Hm, It seems that I don't understand Geometries enough. Here is the code that I use to populate the grid:

```<code>private void PopulateGrid()
{
    PathGeometry path = new PathGeometry();
    Rect rect = new Rect(converter.NormalizePoint(xMin, yMin), converter.NormalizePoint(xMax, yMax));
    RectangleGeometry border = new RectangleGeometry(rect);
    path.AddGeometry(border);
    for (double y = 0; y < yMax; y += 30) {
        LineGeometry line = new LineGeometry(converter.NormalizePoint(xMin, y), converter.NormalizePoint(xMax, y));
        path.AddGeometry(line);
    }
    GridPath = path;
}
</code>```

When I comment out the first 4 lines then the ActualHeight is not set and I see no Grid in my user control. The rectangle causes the Layout engine to work but just the LineGeometry doesn't.

Note that xMin, yMin, xMax and xMin are in world coordinates and the NormalizePoint converts them to screen coordinates, based on the current ViewportWidth and ViewportHeight.

答:
I found the issue. In the XAML above I have

```<code><Grid Margin="5" x:Name="canvas1" ClipToBounds="True" VerticalAlignment="Top">
</code>```

With the VerticalAlignment="Top" and the Height (implicitly) set to Auto I tell the system set the grids vertical size by measuring the content. I am not completely sure why this gives exactly the effects I see but it is clearly not what I want. What I want is that the Grid fills the space available in the DockPanel and then tell my ViewModel what that size is.

The solution is simple: Remove the VerticalAlignment="Top" which implicitly sets VerticalAlignment="Stretch" and now it does exactly what I want.

Body:
I have an application where I need to perform a fairly expensive calculation based on the actual width and height of a control. I have bound ActualWidth and ActualHeight of this control to properties in my code. I find that Actualheight is being changed in small steps. I assume this is because of the Layout Engine.

A stripped down version of the xAML is

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sup="clr-namespace:RowAnimation.Support"
    xmlns:vm="clr-namespace:RowAnimation.ViewModels"
    xmlns:System="clr-namespace:System;assembly=mscorlib"
    xmlns:local="clr-namespace:RowAnimation.Views"
    x:Name="RowerAnimation"
    x:Class="RowAnimation.Views.RowerAnimationControl"
             mc:Ignorable="d"
             d:DataContext="{d:DesignInstance {x:Type vm:RowerAnimationControlVM}}"
             d:DesignHeight="497" d:DesignWidth="741">
    <Grid>
        <DockPanel >
            <Grid Margin="5" x:Name="canvas1" ClipToBounds="True" VerticalAlignment="Top">

                <Path x:Name="gridLines" Stroke="#FF6083E2" Data="{Binding GridPath, Mode=OneWay}"/>
            </Grid>
        </DockPanel>
    </Grid>
</UserControl>

The GridPath is set in my ViewModel when the ViewportHeight or ViewportWidth property in the ViewModel is changed.

When I set a breakpoint in my ViewModel I find that ViewportWidth is changed once but the ViewportHeight is changed multiple times in small increments. When I comment out the method that calculates the GridPath then the VieportHeight break point hits only once. So it looks like the setting of GridPath triggers a new Layout calculation.

In my actual implementation I also have a Grid docked to the bottom of the control, which is why I have the Dockpanel in the XAML.

Since I am using MVVM I use DataPiping from this Stackoverflow link to get the ActualHeight and ActualWidth in my ViewModel.

Does anybody have an idea what is going on and how I might avoid it? As it is the setting of the GridPath (and I actually have more PathGeometries in my actual implementation) can make resizing my window take more than 8 seconds.

In addition:

Hm, It seems that I don't understand Geometries enough. Here is the code that I use to populate the grid:

private void PopulateGrid()
{
    PathGeometry path = new PathGeometry();
    Rect rect = new Rect(converter.NormalizePoint(xMin, yMin), converter.NormalizePoint(xMax, yMax));
    RectangleGeometry border = new RectangleGeometry(rect);
    path.AddGeometry(border);
    for (double y = 0; y < yMax; y += 30) {
        LineGeometry line = new LineGeometry(converter.NormalizePoint(xMin, y), converter.NormalizePoint(xMax, y));
        path.AddGeometry(line);
    }
    GridPath = path;
}

When I comment out the first 4 lines then the ActualHeight is not set and I see no Grid in my user control. The rectangle causes the Layout engine to work but just the LineGeometry doesn't.

Note that xMin, yMin, xMax and xMin are in world coordinates and the NormalizePoint converts them to screen coordinates, based on the current ViewportWidth and ViewportHeight.

Body:
I found the issue. In the XAML above I have

<Grid Margin="5" x:Name="canvas1" ClipToBounds="True" VerticalAlignment="Top">

With the VerticalAlignment="Top" and the Height (implicitly) set to Auto I tell the system set the grids vertical size by measuring the content. I am not completely sure why this gives exactly the effects I see but it is clearly not what I want. What I want is that the Grid fills the space available in the DockPanel and then tell my ViewModel what that size is.

The solution is simple: Remove the VerticalAlignment="Top" which implicitly sets VerticalAlignment="Stretch" and now it does exactly what I want.


问:
IndexError: Extract table from a webpage using BeautifulSoup
I am trying to extract a table (with columns - flight, carrier, origin, date, scheduled, estimated, status) containing flight arrival information from an airport website, but I got the error below:

```<code>  IndexError Traceback (most recent call last)
  <ipython-input-39-2f7369a95ba9> in <module>()
        6  for cl in cols:
        7  dv = cl.findAll('div')
  ----> 8  if 'col-xs-12 col-sm-6' in dv[0]['class']:
        9  flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
       10 print(flight, carrier, origin, date, scheduled, estimated, status)
  IndexError: list index out of range
</code>```

I have combed stackoverflow for solution but could not find solution. Here is my code:

```<code>  # import libraries
  import urllib3
  import requests
  from bs4 import BeautifulSoup

  # query the website and return the html to the variable ‘page’
  page = requests.get("https://www.aucklandairport.co.nz/flights").text

  soup = BeautifulSoup(page)
  tbody = soup.findAll('tbody')
  for tb in tbody:
    rows = tb.findAll('tr')
    for tr in rows:
      cols = tr.findAll('td')
        for cl in cols:
          dv = cl.findAll('div')
          if 'col-xs-12 col-sm-6' in dv[0]['class']:
             flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
             print(flight, carrier, origin, date, scheduled, estimated, status)
</code>```

Thanks for your contribution.

答:
You can peel the same apple in different ways. Here is another way you can achieve the same.

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

response = requests.get("https://www.aucklandairport.co.nz/flights")
soup = BeautifulSoup(response.text,"lxml")
table = soup.select(".flights-table")[0]
for items in table.select("tr.flight-toggle"):
    data = ' '.join([' '.join(item.text.split()) for item in items.select("td")])
    print(data.strip())
</code>```

Partial result:

```<code>QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
AA7377 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
BA7421 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
CZ7575 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
</code>```

Body:
I am trying to extract a table (with columns - flight, carrier, origin, date, scheduled, estimated, status) containing flight arrival information from an airport website, but I got the error below:

  IndexError Traceback (most recent call last)
  <ipython-input-39-2f7369a95ba9> in <module>()
        6  for cl in cols:
        7  dv = cl.findAll('div')
  ----> 8  if 'col-xs-12 col-sm-6' in dv[0]['class']:
        9  flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
       10 print(flight, carrier, origin, date, scheduled, estimated, status)
  IndexError: list index out of range

I have combed stackoverflow for solution but could not find solution. Here is my code:

  # import libraries
  import urllib3
  import requests
  from bs4 import BeautifulSoup

  # query the website and return the html to the variable ‘page’
  page = requests.get("https://www.aucklandairport.co.nz/flights").text

  soup = BeautifulSoup(page)
  tbody = soup.findAll('tbody')
  for tb in tbody:
    rows = tb.findAll('tr')
    for tr in rows:
      cols = tr.findAll('td')
        for cl in cols:
          dv = cl.findAll('div')
          if 'col-xs-12 col-sm-6' in dv[0]['class']:
             flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
             print(flight, carrier, origin, date, scheduled, estimated, status)

Thanks for your contribution.

Body:
You can peel the same apple in different ways. Here is another way you can achieve the same.

import requests
from bs4 import BeautifulSoup

response = requests.get("https://www.aucklandairport.co.nz/flights")
soup = BeautifulSoup(response.text,"lxml")
table = soup.select(".flights-table")[0]
for items in table.select("tr.flight-toggle"):
    data = ' '.join([' '.join(item.text.split()) for item in items.select("td")])
    print(data.strip())

Partial result:

QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
AA7377 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
BA7421 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing
CZ7575 QF145 Sydney 18 Nov 05:05pm Est 05:32pm Processing


问:
Group by 2 categories then take the sum

Above output is from:

```<code>df.groupby('croho subonderdeel').sum()
</code>```

I took the sum of total graduates per category, but I want to do it per column as well. For instance, just receive the output for the first column '2011 MAN'.

I tried the following:

```<code>df.groupby('croho subonderdeel','2011 MAN').sum()
</code>```

Then I get the following error:

```<code>ValueError: No axis named 2011 MAN for object type <class 'pandas.core.frame.DataFrame'>
</code>```

Then I thought maybe instead of grouping twice, I need to take the sum of '2011 MAN'. So I tried:

```<code>df.groupby('croho subonderdeel').sum('2011 MAN')
</code>```

Then I receive this error:

```<code>TypeError: f() takes 1 positional argument but 2 were given
</code>```

Can someone explain to me, why both methods which I'm trying are not possible? Maybe I can solve the issue then by myself.

答:
You need specify column in [] like:

```<code>df.groupby('croho subonderdeel')['2011 MAN'].sum()
</code>```

You can also specify multiple columns:

```<code>df.groupby('croho subonderdeel')['2011 MAN', '2012 MAN'].sum()
</code>```

Also if need 2 columns output add parameter as_index=False:

```<code>df.groupby('croho subonderdeel', as_index=False)['2011 MAN'].sum()
</code>```

Or:

```<code>df.groupby('croho subonderdeel')['2011 MAN'].sum().reset_index()
</code>```

But if want group by 2 categories (2 columns) add [] to groupby:

```<code>df.groupby(['croho subonderdeel', 'another col'])['2011 MAN'].sum()
</code>```

Sample:

```<code>df = pd.DataFrame({'another col':list('efefef'),
                   '2011 MAN':[4,5,4,5,5,4],
                   '2011 WROUW':[7,8,9,4,2,3],
                   '2012 MAN':[1,3,5,7,1,0],
                   '2012 WROUW':[5,3,6,9,2,4],
                   'croho subonderdeel':list('aaabbb')})

print (df)
   2011 MAN  2011 WROUW  2012 MAN  2012 WROUW another col croho subonderdeel
0         4           7         1           5           e                  a
1         5           8         3           3           f                  a
2         4           9         5           6           e                  a
3         5           4         7           9           f                  b
4         5           2         1           2           e                  b
5         4           3         0           4           f                  b

print(df.groupby('croho subonderdeel')['2011 MAN'].sum())
croho subonderdeel
a    13
b    14
Name: 2011 MAN, dtype: int64

print(df.groupby('croho subonderdeel', as_index=False)['2011 MAN'].sum())
  croho subonderdeel  2011 MAN
0                  a        13
1                  b        14

print(df.groupby('croho subonderdeel')['2011 MAN'].sum().reset_index())
  croho subonderdeel  2011 MAN
0                  a        13
1                  b        14
</code>```

```<code>print(df.groupby('croho subonderdeel')['2011 MAN', '2012 WROUW'].sum())
                    2011 MAN  2012 WROUW
croho subonderdeel
a                         13          14
b                         14          15

print(df.groupby('croho subonderdeel', as_index=False)['2011 MAN', '2012 WROUW'].sum())
  croho subonderdeel  2011 MAN  2012 WROUW
0                  a        13          14
1                  b        14          15
</code>```

```<code>print (df.groupby(['croho subonderdeel', 'another col'])['2011 MAN'].sum())
croho subonderdeel  another col
a                   e              8
                    f              5
b                   e              5
                    f              9
Name: 2011 MAN, dtype: int64

print (df.groupby(['croho subonderdeel', 'another col'], as_index=False)['2011 MAN'].sum())
  croho subonderdeel another col  2011 MAN
0                  a           e         8
1                  a           f         5
2                  b           e         5
3                  b           f         9
</code>```

```<code>print (df.groupby(['croho subonderdeel', 'another col']).sum())
                                2011 MAN  2011 WROUW  2012 MAN  2012 WROUW
croho subonderdeel another col
a                  e                   8          16         6          11
                   f                   5           8         3           3
b                  e                   5           2         1           2
                   f                   9           7         7          13

print (df.groupby(['croho subonderdeel', 'another col'], as_index=False).sum())
 croho subonderdeel another col  2011 MAN  2011 WROUW  2012 MAN  2012 WROUW
0                  a           e         8          16         6          11
1                  a           f         5           8         3           3
2                  b           e         5           2         1           2
3                  b           f         9           7         7          13
</code>```

Title: Group by 2 categories then take the sum

Body:
Above output is from:

df.groupby('croho subonderdeel').sum()

I took the sum of total graduates per category, but I want to do it per column as well. For instance, just receive the output for the first column '2011 MAN'.

I tried the following:

df.groupby('croho subonderdeel','2011 MAN').sum()

Then I get the following error:

ValueError: No axis named 2011 MAN for object type <class 'pandas.core.frame.DataFrame'>

Then I thought maybe instead of grouping twice, I need to take the sum of '2011 MAN'. So I tried:

df.groupby('croho subonderdeel').sum('2011 MAN')

Then I receive this error:

TypeError: f() takes 1 positional argument but 2 were given

Can someone explain to me, why both methods which I'm trying are not possible? Maybe I can solve the issue then by myself.

Body:
You need specify column in [] like:

df.groupby('croho subonderdeel')['2011 MAN'].sum()

You can also specify multiple columns:

df.groupby('croho subonderdeel')['2011 MAN', '2012 MAN'].sum()

Also if need 2 columns output add parameter as_index=False:

df.groupby('croho subonderdeel', as_index=False)['2011 MAN'].sum()

Or:

df.groupby('croho subonderdeel')['2011 MAN'].sum().reset_index()

But if want group by 2 categories (2 columns) add [] to groupby:

df.groupby(['croho subonderdeel', 'another col'])['2011 MAN'].sum()

Sample:

df = pd.DataFrame({'another col':list('efefef'),
                   '2011 MAN':[4,5,4,5,5,4],
                   '2011 WROUW':[7,8,9,4,2,3],
                   '2012 MAN':[1,3,5,7,1,0],
                   '2012 WROUW':[5,3,6,9,2,4],
                   'croho subonderdeel':list('aaabbb')})

print (df)
   2011 MAN  2011 WROUW  2012 MAN  2012 WROUW another col croho subonderdeel
0         4           7         1           5           e                  a
1         5           8         3           3           f                  a
2         4           9         5           6           e                  a
3         5           4         7           9           f                  b
4         5           2         1           2           e                  b
5         4           3         0           4           f                  b

print(df.groupby('croho subonderdeel')['2011 MAN'].sum())
croho subonderdeel
a    13
b    14
Name: 2011 MAN, dtype: int64

print(df.groupby('croho subonderdeel', as_index=False)['2011 MAN'].sum())
  croho subonderdeel  2011 MAN
0                  a        13
1                  b        14

print(df.groupby('croho subonderdeel')['2011 MAN'].sum().reset_index())
  croho subonderdeel  2011 MAN
0                  a        13
1                  b        14

print(df.groupby('croho subonderdeel')['2011 MAN', '2012 WROUW'].sum())
                    2011 MAN  2012 WROUW
croho subonderdeel
a                         13          14
b                         14          15

print(df.groupby('croho subonderdeel', as_index=False)['2011 MAN', '2012 WROUW'].sum())
  croho subonderdeel  2011 MAN  2012 WROUW
0                  a        13          14
1                  b        14          15

print (df.groupby(['croho subonderdeel', 'another col'])['2011 MAN'].sum())
croho subonderdeel  another col
a                   e              8
                    f              5
b                   e              5
                    f              9
Name: 2011 MAN, dtype: int64

print (df.groupby(['croho subonderdeel', 'another col'], as_index=False)['2011 MAN'].sum())
  croho subonderdeel another col  2011 MAN
0                  a           e         8
1                  a           f         5
2                  b           e         5
3                  b           f         9

print (df.groupby(['croho subonderdeel', 'another col']).sum())
                                2011 MAN  2011 WROUW  2012 MAN  2012 WROUW
croho subonderdeel another col
a                  e                   8          16         6          11
                   f                   5           8         3           3
b                  e                   5           2         1           2
                   f                   9           7         7          13

print (df.groupby(['croho subonderdeel', 'another col'], as_index=False).sum())
 croho subonderdeel another col  2011 MAN  2011 WROUW  2012 MAN  2012 WROUW
0                  a           e         8          16         6          11
1                  a           f         5           8         3           3
2                  b           e         5           2         1           2
3                  b           f         9           7         7          13


问:
Tensorflow object_detection does not create boxes, Scores for classes are so weak
I run tensorflow object_detection api last week correctly on my webcam (in windows). But this week after tensorflow updated to 1.4.0 it compiled correctly but it did not create boxes even for its test images. Since I did not have tensorflow 1.4.0 source files for windows platform, I run it on my ubuntu but the result is the same, boxes do not created.
I saw my variables in spyder IDE, the scores for detected classes are so weak. Why this happened? Am I run it wrong?
Thanks for your helps guys ...</p>

答: This was a bug with tensorflow last update. I mentioned it in github and it solved. this is the link</p>


问:
Call to a member function real_escape_string() on array in
I am struggling with something strange.  I am running a mysqli::real_escape_string on a function to prepare an SQL statement.  I am taking data from one database and developing a query to insert it into a database on a different server.

There error message I get is:

Fatal error: Uncaught Error: Call to a member function real_escape_string() on array in ...

I tried logging a is_array() function right before calling the real_escape_string() and it confirms that it is not an array.  I am getting this whether I pass in a numeric or a string value.   I thought perhaps it was an encoding issue, but I'm not sure how to deal with those.  I tried to convert it before, but that also didn't work:

```<code>$str = $row[$key];                     // Tried on two strings '1' (is_numeric = True), and 'Kevin'
is_array( $str );                      // Returns False
$str = mb_convert_encoding($row[$key], 'UTF-8');    // Consequently, also tried 'latin1' with the same result.
$db->real_escape_string( $str );
</code>```

That also did not work, still is returning the array error.

Any other suggestions on what to try?

Thanks.

答: This error means that it's your $db is array, not the function's parameter</p>

Body:
I am struggling with something strange.  I am running a mysqli::real_escape_string on a function to prepare an SQL statement.  I am taking data from one database and developing a query to insert it into a database on a different server.

There error message I get is:

Fatal error: Uncaught Error: Call to a member function real_escape_string() on array in ...

I tried logging a is_array() function right before calling the real_escape_string() and it confirms that it is not an array.  I am getting this whether I pass in a numeric or a string value.   I thought perhaps it was an encoding issue, but I'm not sure how to deal with those.  I tried to convert it before, but that also didn't work:

$str = $row[$key];                     // Tried on two strings '1' (is_numeric = True), and 'Kevin'
is_array( $str );                      // Returns False
$str = mb_convert_encoding($row[$key], 'UTF-8');    // Consequently, also tried 'latin1' with the same result.
$db->real_escape_string( $str );

That also did not work, still is returning the array error.

Any other suggestions on what to try?

Thanks.


问:
Is caching roles in cookies secure?
Would caching user roles in a cookie be a security problem? Could they decrypt the cookie and change their role to like Admin? Whats a good way around this?

答:
Here is one good read:

How serious is this new ASP.NET security vulnerability and how can I workaround it?

I would personally not store roles in cookies unless there was a really serious performance problem getting them from the database. It's all up to you, security vs. performance wise. If you have a banking or health site, don't cache. If you have an e-commerce store, caching shouldn't be as huge an issue.

Even if you don't cache, the web server should call the database only once per request for automatic role checking. It may call again if you invoke a GetRoles method from any of the System.Web classes.

Title: Is caching roles in cookies secure?