问:
audio validation issues laravel 5.4
I am trying to validate my form request. What I'm doing is I am to upload audio, that is, mp3,wav etc, the issue I'm having is that it keeps throwing an error message back at me saying 'the file type must be mp3', I tried uploading an image and it said the file type must be mp3, I also tried uploading mp3 and it says the same thing, below is my audio controller.

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class UploadController extends Controller
{
public function uploadsingle(Request $request)
{
    $validator = Validator::make($request->all(), [
        'song' => 'required|mimes:image/png',
    ]);

    if($validator->fails()){
        return redirect()->back()->withErrors($validator)->withInput();
    }

    ///save audio, etc
    echo 'validation passed';
}
}
</code>```

this is my html code

```<code><title>Upload page</title>
@include('layouts.page-life')
@include('layouts.navbar')

<h1>Upload Page</h1>
<br>
<form action="{{ route('doupload') }}" method="POST">
{{ csrf_field() }}
@if (count($errors) > 0)
        <div class="alert alert-danger alert-dismissible" role="alert">
            <ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
        @endif

<input name="song" type="file"/>
<br>
<button class="btn">Submit</button>
</form>
</code>```

答:
Most of the answers above are correct. My case was that I forgot to add enctype="multipart/form-data" to my form tag as follows:</p>

```<code><form action="some url" method="some method" enctype="multipart/form-data">
   stuff
</form>
</code>```

Title: audio validation issues laravel 5.4

Body:
I am trying to validate my form request. What I'm doing is I am to upload audio, that is, mp3,wav etc, the issue I'm having is that it keeps throwing an error message back at me saying 'the file type must be mp3', I tried uploading an image and it said the file type must be mp3, I also tried uploading mp3 and it says the same thing, below is my audio controller.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;

class UploadController extends Controller
{
public function uploadsingle(Request $request)
{
    $validator = Validator::make($request->all(), [
        'song' => 'required|mimes:image/png',
    ]);

    if($validator->fails()){
        return redirect()->back()->withErrors($validator)->withInput();
    }

    ///save audio, etc
    echo 'validation passed';
}
}

this is my html code

<title>Upload page</title>
@include('layouts.page-life')
@include('layouts.navbar')

Upload Page

<form action="{{ route('doupload') }}" method="POST">
{{ csrf_field() }}
@if (count($errors) > 0)

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                @foreach ($errors->all() as $error)

{{ $error }}

                @endforeach

        @endif

<input name="song" type="file"/>

<button class="btn">Submit</button>
</form>

Body:
Most of the answers above are correct. My case was that I forgot to add enctype="multipart/form-data" to my form tag as follows:

<form action="some url" method="some method" enctype="multipart/form-data">
   stuff
</form>


来源: stackexchange

问:
N/A error while using the correct VLookup formula to get value from other sheet
In excel, I was trying to get fund value of a particular mutual fund by using VLookup to search another sheet. In the process, I am getting N/A error even if the VLookup formula seems correct.

The below screenshot is of the sheet with the VLookup excel formula:

Is there any issues with the vlookup formula that I am using here.
=VLOOKUP(D4,Sheet1!$A$5072:$E$5075,5,FALSE)
I have tried many version of the vlookup but to no avail. Could anyone please help? Thanks!

答:
Agree with Chris Neilsen that this is most likely a case of different formatting between the lookup item vs lookup array.  The left alignment implies that both are formatted as text.  Given this, just double check that both indeed are formatted as text vs. someone left-aligning a column of numbers.

Let us know if that doesn't solve the problem and we can walk you through replacing this formula with an Index+Match formula.

ContentLicense: CC BY-SA 4.0


问:
Android studio firebase Authentication doesn't sign up
I have created a user sign up and login method. However when i sign up it is not showing me any signed up user data in firebase.
Here is my MainActivity.

```<code>package com.mike.mikeproject;

import android.content.Intent;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
 import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

private DatabaseReference lDatabase;

private EditText email;
private EditText password;
private Button signup;
private Button login;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    lDatabase = FirebaseDatabase.getInstance().getReference();

    email = (EditText) findViewById(R.id.user_email);
    password = (EditText) findViewById(R.id.user_password);
    signup = (Button) findViewById(R.id.signup_btn);
    login = (Button) findViewById(R.id.login_btn);

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user == null){

            }else {

                startActivity(new Intent(MainActivity.this, WelcomeActivity.class));

            }

        }
    };

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String emailtodb = email.getText().toString().trim();

            String passwordtodb = password.getText().toString().trim();

            //Toast.makeText(MainActivity.this,"Sign up button clickeddd"+emailtodb+passwordtodb, Toast.LENGTH_LONG).show();

            if(!TextUtils.isEmpty(emailtodb) && !TextUtils.isEmpty(passwordtodb)){

                mAuth.createUserWithEmailAndPassword(emailtodb,passwordtodb).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if(task.isSuccessful()){

                            startActivity(new Intent(MainActivity.this,WelcomeActivity.class));

                        } else {

                            Toast.makeText(MainActivity.this,"Sign up failed", Toast.LENGTH_LONG).show();

                        }

                    }
                });

            } else {

                Toast.makeText(MainActivity.this,"email and password required", Toast.LENGTH_LONG).show();

            }

        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            startActivity(new Intent(MainActivity.this,LoginActivity.class));

        }
    });

}

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

    mAuth.addAuthStateListener(mAuthListener);

}

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

    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }

  }
}
</code>```

What is wrong with my code? why is it not signing up. Thanks in advance.

firebase user record:

答: Make your password greater than 6 characters.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a user sign up and login method. However when i sign up it is not showing me any signed up user data in firebase.
Here is my MainActivity.

package com.mike.mikeproject;

import android.content.Intent;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
 import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

private DatabaseReference lDatabase;

private EditText email;
private EditText password;
private Button signup;
private Button login;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;

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

    lDatabase = FirebaseDatabase.getInstance().getReference();

    email = (EditText) findViewById(R.id.user_email);
    password = (EditText) findViewById(R.id.user_password);
    signup = (Button) findViewById(R.id.signup_btn);
    login = (Button) findViewById(R.id.login_btn);

    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user == null){

            }else {

                startActivity(new Intent(MainActivity.this, WelcomeActivity.class));

            }

        }
    };

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String emailtodb = email.getText().toString().trim();

            String passwordtodb = password.getText().toString().trim();

            //Toast.makeText(MainActivity.this,"Sign up button clickeddd"+emailtodb+passwordtodb, Toast.LENGTH_LONG).show();

            if(!TextUtils.isEmpty(emailtodb) && !TextUtils.isEmpty(passwordtodb)){

                mAuth.createUserWithEmailAndPassword(emailtodb,passwordtodb).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if(task.isSuccessful()){

                            startActivity(new Intent(MainActivity.this,WelcomeActivity.class));

                        } else {

                            Toast.makeText(MainActivity.this,"Sign up failed", Toast.LENGTH_LONG).show();

                        }

                    }
                });

            } else {

                Toast.makeText(MainActivity.this,"email and password required", Toast.LENGTH_LONG).show();

            }

        }
    });

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            startActivity(new Intent(MainActivity.this,LoginActivity.class));

        }
    });

}

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

    mAuth.addAuthStateListener(mAuthListener);

}

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

    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }

  }
}

What is wrong with my code? why is it not signing up. Thanks in advance.

firebase user record:


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答:
When you have the choice, change your file format.

You can serialize your object by using xstream. Then you only have to store the complete Java object without checking if some value is existing.

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

OwnerDisplayName: Markus Lausberg


问:
help with a PHP regex to extract text around a string
I am trying to use a regular expression and it's just breaking my brain.  I'll think I have it and the the script just breaks. I need to try to give people a way to report their location via SMS. I ask them to text me a string that looks like this:

I give up, stopping for the night.
  Find me at Main Street and Pine,
  Atlanta, GA.

And I want to break it at Find me at. I need to capture everything to the right of that (essentially their street corner) and I need to be able to detect if they didn't use proper capitalization for Find.

Any suggestions?

答: Give this a shot: /find me at (.*)$/i

Body: Give this a shot: /find me at (.*)$/i


问:
Firebase Functions How To Handle Errors Properly

NOTE: this question is mainly about error handling, and if this is an ok approach, not about nesting promises, please read before closing

Since there are currently no error codes for services like firestore and firebase database, i'm using a system to know where the function failed and to handle error accordingly, simplified version below:

```<code>exports.doStuff = functions.https.onCall((data, context) => {

    return [promise doing stuff goes here].catch(error => { throw new Error('ERROR0') })
        .then(result => {
            return [promise doing stuff goes here, needs result of previous promise]
                .catch(error => { throw new Error('ERROR1') })
        })
        .then(result => {
            return [promise doing stuff goes here, needs result of previous promise]
                .catch(error => { throw new Error('ERROR2') })
        })
        .then(result => {
            //inform client function successful
            return {
                success: true
            }
        })
        .catch(error => {
            if (error !== null) {
                switch (error.message) {
                    case 'ERROR0':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR0');
                    case 'ERROR1':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR1');
                    case 'ERROR2':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR2');
                    default:
                        console.error('uncaught error: ', error);
                        throw error;
                }
            }
        });
});
</code>```

the thing is, for each .catch() inside each returned promise, i'm getting the following warning: warning  Avoid nesting promises

so my question is, is there a better way to handle errors?

答:
Ultimately it's a style recommendation to prevent bizarre and hard to recognise errors. Most of the time a rewrite can eliminate the warning. As an example, you could rewrite your code as the following whilst retaining the same functionality.

```<code>exports.doStuff = functions.https.onCall(async (data, context) => {

    const result1 = await [promise doing stuff goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR0', { message: error.message } )
      });

    const result2 = await [promise based on result1 goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR1', { message: error.message } )
      });

    const result3 = await [promise based on result1/result2 goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR2', { message: error.message } )
      });

    return {
      success: true
    };
});
</code>```

Lastly, rather than using unknown everywhere, you could use one of several possible values for the first argument whilst passing in whatever supporting information you need as the third argument (as shown above where I pass through the original error message).

Body:
NOTE: this question is mainly about error handling, and if this is an ok approach, not about nesting promises, please read before closing

Since there are currently no error codes for services like firestore and firebase database, i'm using a system to know where the function failed and to handle error accordingly, simplified version below:

exports.doStuff = functions.https.onCall((data, context) => {

    return [promise doing stuff goes here].catch(error => { throw new Error('ERROR0') })
        .then(result => {
            return [promise doing stuff goes here, needs result of previous promise]
                .catch(error => { throw new Error('ERROR1') })
        })
        .then(result => {
            return [promise doing stuff goes here, needs result of previous promise]
                .catch(error => { throw new Error('ERROR2') })
        })
        .then(result => {
            //inform client function successful
            return {
                success: true
            }
        })
        .catch(error => {
            if (error !== null) {
                switch (error.message) {
                    case 'ERROR0':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR0');
                    case 'ERROR1':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR1');
                    case 'ERROR2':
                        //do stuff
                        throw new functions.https.HttpsError('unknown', 'ERROR2');
                    default:
                        console.error('uncaught error: ', error);
                        throw error;
                }
            }
        });
});

the thing is, for each .catch() inside each returned promise, i'm getting the following warning: warning  Avoid nesting promises

so my question is, is there a better way to handle errors?

Body:
Ultimately it's a style recommendation to prevent bizarre and hard to recognise errors. Most of the time a rewrite can eliminate the warning. As an example, you could rewrite your code as the following whilst retaining the same functionality.

exports.doStuff = functions.https.onCall(async (data, context) => {

    const result1 = await [promise doing stuff goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR0', { message: error.message } )
      });

    const result2 = await [promise based on result1 goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR1', { message: error.message } )
      });

    const result3 = await [promise based on result1/result2 goes here]
      .catch(error => {
          throw new functions.https.HttpsError('unknown', 'ERROR2', { message: error.message } )
      });

    return {
      success: true
    };
});

Lastly, rather than using unknown everywhere, you could use one of several possible values for the first argument whilst passing in whatever supporting information you need as the third argument (as shown above where I pass through the original error message).


问:
Why doesn't this trigger work the way I want it to?
I have two tables in my mysql database:
Advisor: id
Student: advisorID | major

I want to update Student where the deleted ID in Advisor is equal to advisorID and use a set of if statements to change that student's advisorID value based on that student's major. This is what I have thus far:

```<code>    delimiter //
    create trigger advisor_delete after delete
    on advisor
        UPDATE Student
            IF Student.major = 'major1' THEN SET Student.advisorID = 1;
            ELSEIF Student.major = 'major2' THEN SET Student.advisorID = 2;
            ELSEIF Student.major = 'major3' THEN SET Student.advisorID = 3;
            ELSE SET Student.advisorID = 4;
            ENDIF;
        WHERE Student.advisorID = OLD.id;
    end//
</code>```

Any help is welcome. Thanks.

答:
I don't know this UPDATE/IF ELSEIF syntax, but CASE statement will work for you:

```<code>delimiter //
create trigger advisor_delete after delete
on advisor
    UPDATE Student
        SET Student.advisorID =
            CASE Student.major WHEN 'major1' THEN 1
                               WHEN 'major2' THEN 2
                               WHEN 'major3' THEN 3
                               ELSE 4
            END
    WHERE Student.advisorID = OLD.id;
end//
</code>```

Body:
I have two tables in my mysql database:
Advisor: id
Student: advisorID | major

I want to update Student where the deleted ID in Advisor is equal to advisorID and use a set of if statements to change that student's advisorID value based on that student's major. This is what I have thus far:

    delimiter //
    create trigger advisor_delete after delete
    on advisor
        UPDATE Student
            IF Student.major = 'major1' THEN SET Student.advisorID = 1;
            ELSEIF Student.major = 'major2' THEN SET Student.advisorID = 2;
            ELSEIF Student.major = 'major3' THEN SET Student.advisorID = 3;
            ELSE SET Student.advisorID = 4;
            ENDIF;
        WHERE Student.advisorID = OLD.id;
    end//

Any help is welcome. Thanks.

Body:
I don't know this UPDATE/IF ELSEIF syntax, but CASE statement will work for you:

delimiter //
create trigger advisor_delete after delete
on advisor
    UPDATE Student
        SET Student.advisorID =
            CASE Student.major WHEN 'major1' THEN 1
                               WHEN 'major2' THEN 2
                               WHEN 'major3' THEN 3
                               ELSE 4
            END
    WHERE Student.advisorID = OLD.id;
end//


问:
Python, Selenium Webdriver: How can I find the value of this attribute?
I'm working on a python script to get some data from a website using selenium Chrome webdriver. Finding the elements needed worked fine for me - until now. Now I'm trying to get an advertisement-ID (value of "data-ad-link".

```<code><div class="header w-brk" style="overflow-wrap: break-word;">
        <a href="/iad/immobilien/d/eigentumswohnung/wien/wien-1010-innere-stadt/am-werdertor-etages-de-luxe-344939582/" class="" data-ad-link="344939582">
            <span itemprop="name">
                AM WERDERTOR - ÉTAGES DE LUXE
            </span>
        </a>
    </div>
</code>```

From this HTML segment I'd need the value of data-ad-link. I tried solving this problem using

```<code>elem = driver.find_elements_by_xpath("//*[@class='']")
for i in range(count):
    #uniqueid = elem[i].get_attribute('data-ad-link')
    #uniqueid = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', elem[i])
    print(uniqueid)
</code>```

In my debugger I'm seeing that creating the list works well - but getting the value doesn't. So I already tried element.get_attribute which returned None (also for href!). I tried driver.execute_script which I found here: Selenium webdriver: How do I find ALL of an element's attributes? which just gives me class, href and rel.

Does anyone know how I could get this value? It would help me so much!

I'm using Selenium (v 3.141.0) on Python

答:
To extract the value of the attribute data-ad-link i.e. 344939582 you have to induce WebDriverWait for the desired visibility_of_element_located() and you can use the following Locator Strategy:

Using XPATH:

```<code>print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='header w-brk']/a[starts-with(@href, '/iad/immobilien/d/eigentumswohnung/wien/wien-')]/span[@itemprop='name' and normalize-space()='AM WERDERTOR - ÉTAGES DE LUXE']/.."))).get_attribute("data-ad-link"))
</code>```

Body:
I'm working on a python script to get some data from a website using selenium Chrome webdriver. Finding the elements needed worked fine for me - until now. Now I'm trying to get an advertisement-ID (value of "data-ad-link".

                AM WERDERTOR - ÉTAGES DE LUXE

From this HTML segment I'd need the value of data-ad-link. I tried solving this problem using

elem = driver.find_elements_by_xpath("//*[@class='']")
for i in range(count):
    #uniqueid = elem[i].get_attribute('data-ad-link')
    #uniqueid = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', elem[i])
    print(uniqueid)

In my debugger I'm seeing that creating the list works well - but getting the value doesn't. So I already tried element.get_attribute which returned None (also for href!). I tried driver.execute_script which I found here: Selenium webdriver: How do I find ALL of an element's attributes? which just gives me class, href and rel.

Does anyone know how I could get this value? It would help me so much!

I'm using Selenium (v 3.141.0) on Python

Body:
To extract the value of the attribute data-ad-link i.e. 344939582 you have to induce WebDriverWait for the desired visibility_of_element_located() and you can use the following Locator Strategy:

Using XPATH:

print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='header w-brk']/a[starts-with(@href, '/iad/immobilien/d/eigentumswohnung/wien/wien-')]/span[@itemprop='name' and normalize-space()='AM WERDERTOR - ÉTAGES DE LUXE']/.."))).get_attribute("data-ad-link"))


问:
__NSCFType _referenceView exception
My xcdoe application throws the following exception:
[__NSCFType _referenceView]: unrecognized selector sent to instance 0x174183b50
And sometimes it throws
-[NSISEngine _referenceView]: unrecognized selector sent to instance 0x170186660'

I reviewed my code and tried to add exception breakpoint
but i haven't got any detailed information about the exception.
i tried backtrace too but with no use.
I googled the error but it seems a rare exception.

so please any help would be much appreciated.

答:
This tells you that somewhere in your code you've got something like [someVariable _referenceView] and whatever is stored in someVariable is not a reference to an object that supports _referenceView. The existence of the call implies the programmer thought someVariable did contain an appropriate reference, work back from them.

To find the particular call:

Add a symbolic breakpoint for doesNotRecognizeSelector:.

Run

When this breakpoint is hit look up the stack and you'll find the specific call to _referenceView and what it is being called on.

Investigate

HTH, happy hunting!

Title: __NSCFType _referenceView exception


问:
cvc-elt.1: Cannot find the declaration of element 'MyElement'
I'm trying to validate a really simple xml using xsd, but for some reason I get this error.
I'll really appreciate if someone can explain me why.

XML File

```<code><?xml version="1.0" encoding="utf-8"?>
<MyElement>A</MyElement>
</code>```

XSD File

```<code><?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.example.org/Test"
        xmlns:tns="http://www.example.org/Test"
        elementFormDefault="qualified">

    <simpleType name="MyType">
        <restriction base="string"></restriction>
    </simpleType>

    <element name="MyElement" type="tns:MyType"></element>
</schema>
</code>```

答:
I got this same error working in Eclipse with Maven with the additional information

```<code>schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
</code>```

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.

Body:
I'm trying to validate a really simple xml using xsd, but for some reason I get this error.
I'll really appreciate if someone can explain me why.

XML File

<?xml version="1.0" encoding="utf-8"?>
<MyElement>A</MyElement>

XSD File

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        targetNamespace="http://www.example.org/Test"
        xmlns:tns="http://www.example.org/Test"
        elementFormDefault="qualified">

    <simpleType name="MyType">
        <restriction base="string"></restriction>
    </simpleType>

    <element name="MyElement" type="tns:MyType"></element>
</schema>

Body:
I got this same error working in Eclipse with Maven with the additional information

schema_reference.4: Failed to read schema document 'https://maven.apache.org/xsd/maven-4.0.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This was after copying in a new controller and it's interface from a Thymeleaf example. Honestly, no matter how careful I am I still am at a loss to understand how one is expected to figure this out. On a (lucky) guess I right clicked the project, clicked Maven and Update Project which cleared up the issue.


问:
Collection View Items can't Bind on FileInfo type. [Xamarin Forms]
I'am trying to bind my collection view on a list of FileInfo

For example :

```<code>List<FileInfo> files = FileHelper.GetFiles();
collectionViewList.ItemsSource = files;
</code>```

But I have an error : "Specified cast is invalid"

If am trying to do this on a simple list view it work.

Maybe collection view doesn't accept somes type of objects ?

Code Used when the exeption is raise :

```<code> private async void StartProcessButton(object sender, EventArgs e)
    {

        if (MyListView.SelectedItem == null)
        {
            return;
        }

        switch (this.selectedItemId)
        {
            case 0:
                await Navigation.PushAsync(new ConcatePdfPage(fileInfo));
                break;
            default:
                break;
        }

    }
</code>```

I tried debuging and when my app is loading my concate page the exeption is raise at this line of code :

```<code>await Navigation.PushAsync(new ConcatePdfPage(fileInfo));
</code>```

My constructor class :

```<code>public ConcatePdfPage(FileInfo fileInfo)
        {
            InitializeComponent();
            this.fileInfo1 = fileInfo;

            IPdfPickerAndroid pdfPickerAndroid = DependencyService.Get<IPdfPickerAndroid>();

            FilesList.ItemsSource = pdfPickerAndroid.GetPdfFilesInDocuments();
        }
</code>```

To be more precise the errors is raise when my collection view is loading, binding to the *List of FileInfo *

https://learn.microsoft.com/fr-fr/dotnet/api/system.io.fileinfo?view=netframework-4.8

But I tried to bind my collection view on a list of string.

And it work, no exeption is raise.

I also tried to bind my list of FileInfo on a list view instead of a collection view and no exeption was raise.

答:
Problem solved :

I deleted the viewcell attributes in my xaml code on the page where the exeption is raise.

```<code><CollectionView x:Name="FilesList" SelectionMode="Single">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <StackLayout Orientation="Vertical">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding CreationTime.Date, StringFormat='{}{0:dd/MM/yyyy}'}"/>
                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</code>```

New code :

```<code><CollectionView x:Name="FilesList" SelectionMode="Single">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout Orientation="Horizontal">
                        <StackLayout Orientation="Vertical">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding CreationTime.Date, StringFormat='{}{0:dd/MM/yyyy}'}"/>
                        </StackLayout>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</code>```

https://medium.com/a-developer-in-making/how-to-work-with-collectionview-in-xamarin-forms-5dc65c50b419

Body:
I'am trying to bind my collection view on a list of FileInfo

For example :

List<FileInfo> files = FileHelper.GetFiles();
collectionViewList.ItemsSource = files;

But I have an error : "Specified cast is invalid"

If am trying to do this on a simple list view it work.

Maybe collection view doesn't accept somes type of objects ?

Code Used when the exeption is raise :

 private async void StartProcessButton(object sender, EventArgs e)
    {

        if (MyListView.SelectedItem == null)
        {
            return;
        }

        switch (this.selectedItemId)
        {
            case 0:
                await Navigation.PushAsync(new ConcatePdfPage(fileInfo));
                break;
            default:
                break;
        }

    }

I tried debuging and when my app is loading my concate page the exeption is raise at this line of code :

await Navigation.PushAsync(new ConcatePdfPage(fileInfo));

My constructor class :

public ConcatePdfPage(FileInfo fileInfo)
        {
            InitializeComponent();
            this.fileInfo1 = fileInfo;

            IPdfPickerAndroid pdfPickerAndroid = DependencyService.Get<IPdfPickerAndroid>();

            FilesList.ItemsSource = pdfPickerAndroid.GetPdfFilesInDocuments();
        }

To be more precise the errors is raise when my collection view is loading, binding to the *List of FileInfo *

https://learn.microsoft.com/fr-fr/dotnet/api/system.io.fileinfo?view=netframework-4.8

But I tried to bind my collection view on a list of string.

And it work, no exeption is raise.

I also tried to bind my list of FileInfo on a list view instead of a collection view and no exeption was raise.

Body:
Problem solved :

I deleted the viewcell attributes in my xaml code on the page where the exeption is raise.

<CollectionView x:Name="FilesList" SelectionMode="Single">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <StackLayout Orientation="Vertical">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding CreationTime.Date, StringFormat='{}{0:dd/MM/yyyy}'}"/>
                        </StackLayout>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

New code :

<CollectionView x:Name="FilesList" SelectionMode="Single">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout Orientation="Horizontal">
                        <StackLayout Orientation="Vertical">
                            <Label Text="{Binding Name}"/>
                            <Label Text="{Binding CreationTime.Date, StringFormat='{}{0:dd/MM/yyyy}'}"/>
                        </StackLayout>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

https://medium.com/a-developer-in-making/how-to-work-with-collectionview-in-xamarin-forms-5dc65c50b419


问:
Why can't I declare a variable or function more than once with different types?
Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:

```<code>int fkc();
void fkc();
</code>```

enter image description here

I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?

答:
Because you cannot overload the method just by changing return type . It is not allowed. The compiler distinguishes function invocations based on signature.and the signature of function includes only function name and arugments like

func(int x....) which does not include return type

Body:
Okay I know "One Definition Rule", but when I try to declare a variable with different types subsequently in source code, I run into some mistake like following:

int fkc();
void fkc();

enter image description here

I mean these two statements are just two declarations, not definitions. Alright, Does every declaration have to have only one unique definition?


问:
When running a project without a .env file, bootstrap.php throws a fatal error when the DotEnv component attempts to read it
I have tried to deploy a Symfony application by using the following tutorial: https://medium.com/@runawaycoin/deploying-symfony-4-application-to-shared-hosting-with-just-ftp-access-e65d2c5e0e3d

When trying to load the site I got a 500 internal server error. As per the tutorial I looked into my hosting error logs and saw a lot of stuff about DotEnv. Here's the first part of the output:

PHP Fatal error:  Uncaught
  Symfony\Component\Dotenv\Exception\PathException: Unable to read the
  "/var/www/vhosts/137/332002/webspace/httpdocs/symfony_temp/.env"
  environment file. in
  /var/www/vhosts/137/332002/webspace/httpdocs/symfony_temp/vendor/symfony/dotenv/Dotenv.php:484

The tutorial tells me to store my env variables in other places like index.php for example. But looking at the code I see that bootstrap.php immediately calls DotEnv and tries to get data from there, which results in an error eventually I think.

How can I disable DotEnv, so that Symfony doesn't use it, and I can simply get my env variables from somewhere else? It is hosted in a hosting environment belonging to a customer where I think .htaccess doesn't allow access to DotEnv and I can't change that in this case as I have no authorization to edit that .htaccess file or even open it.

答:
bootstrap.php belongs to you. If you do not like its behaviour, just change it.

If you do not want to use DotEnv, just remove it and remove whatever references to it in your code (e.g. the aforementioned bootstrap.php).

Mind you, hardcoding configuration variables in code like index.php sounds like a bad idea. Even if you are not using environment variables, DotEnv will help you centralize your configuration data in a single file not related to your application logic.

For best performance, configure your environment variables for production settings while on dev and use composer dump-env prod as mentioned here. This will generate a .env.local.php that you can upload to production, and for the default bootstrap.php will prevent the use of DotEnv.


问:
how to do if check between Carbon now and column expired_at
hello i need to do check after 24 hours from user created check if the user pay many or not if the user not payment set status = 0 ...  but  i cant make Comparison between time in column expired_at  and time now after 24 hours how can i do this?

```<code>public function handle()
{
    $update_row = booking_ravs::all();

    foreach ($update_row as $item) {

        if (Carbon::now() > $item->expired_at) {
            DB::table('booking_ravs')->update(['stauts' => 0]);
        }
    }
}
</code>```

I try multiple if  but it doesn't work what the selection

答:
Since the created_at and updated_at fields are Carbon instances you can simply add the time to them:

```<code>(now() > $item->expired_at->addHours(24))
</code>```

alternatively

```<code>(now() > $item->expired_at->addDay())
</code>```

For more information please have a look at the Carbon Documentation

Body:
hello i need to do check after 24 hours from user created check if the user pay many or not if the user not payment set status = 0 ...  but  i cant make Comparison between time in column expired_at  and time now after 24 hours how can i do this?

public function handle()
{
    $update_row = booking_ravs::all();

    foreach ($update_row as $item) {

        if (Carbon::now() > $item->expired_at) {
            DB::table('booking_ravs')->update(['stauts' => 0]);
        }
    }
}

I try multiple if  but it doesn't work what the selection

Body:
Since the created_at and updated_at fields are Carbon instances you can simply add the time to them:

(now() > $item->expired_at->addHours(24))

alternatively

(now() > $item->expired_at->addDay())

For more information please have a look at the Carbon Documentation


问:
How to find the number of times that 2 follows 3 in a list
If I have a number 13245. What I need is to return how many times 2 follows behind number 3.

```<code>def thirtyTwos(n):
  lst=(map(int,str(n)))
  count=0
  i=0
  j=1
  while i<len(lst):
    while j<len(lst):
        if lst[i]==3>lst[j]==2:

                count+=1
        j+=1
    j=i+1
    i+=1
return count
</code>```

But it turns wrong on some numbers. What should I do now?

答:
An approach using regex:</p>

```<code>import re

def count_32(number):
    if not isinstance(number, str):
        number = str(number)
    return len(re.findall('32', number))
</code>```

Body:
If I have a number 13245. What I need is to return how many times 2 follows behind number 3.

def thirtyTwos(n):
  lst=(map(int,str(n)))
  count=0
  i=0
  j=1
  while i<len(lst):
    while j<len(lst):
        if lst[i]==3>lst[j]==2:

                count+=1
        j+=1
    j=i+1
    i+=1
return count

But it turns wrong on some numbers. What should I do now?

Body:
An approach using regex:

import re

def count_32(number):
    if not isinstance(number, str):
        number = str(number)
    return len(re.findall('32', number))


问:
Finding min and max elements of every column and row in a matrix C++
I was trying to  do the following:
Have a matrix, print the entire thing out, print at end of every row the biggest element of said row and print at the bottom of every column the smallest element of said column.
I'm pretty much a beginner at C++.

So here's what I've done so far:

```<code> #include <iostream>
    #include <iomanip>
    #define M 50
    #define N 50
    using namespace std;
    int main()
    {
        int m,n;
        int a[M][N];
        int b[M],c[N];

        do {
        cout<<"m=";
        cin>>m;
        cout<<endl<<"n=";
        cin>>n;
        cout<<endl;
        }
        while(m!=n);

        for(int i=0;i<m; i++) {
            for(int j=0; j<n; j++){
            cout<<"a["<<i<<"]["<<j<<"]=";
            cin>>a[i][j];
            }
        }
        int max_row;
        max_row=0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (a[i][j] > max_row) {
                    max_row = a[i][j];
                    b[i] = max_row;
                }
            }
        }

        for (int i=0; i<m; i++)
        { for(int j=0; j<n; j++){
            cout<<setw(3)<<a[i][j]<<"\t";
        }
        cout<<"|"<<b[i];
        cout<<endl;
        }
        for(int i=0; i<m; i++){
        cout<<setw(3)<<"-";}

        cout<<endl;

        for(int j=0; j<n; j++)
        {cout<<c[j]<<"\t";
        }

        system("pause");
    }
</code>```

Most of the time the max_row are the correct ones such as this case:

```<code>  3       2       1     |3
  4       6       5     |6
  7       8       9     |9
</code>```

Other times they get messed up and it goes like this:

```<code>  1       2       3     |3
  4      33       6     |33
  7       8       9     |-858993460
</code>```

I really have no idea what causes it and since there are no error messages I got really confused. Also I have no idea how to make the min column ones. Any help would be appreciated.

答:
The problem with these loops

```<code>    max_row=0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j] > max_row) {
                max_row = a[i][j];
                b[i] = max_row;
            }
        }
    }
</code>```

is that the value of max_row should be initialized with each iteration of the outer loop. Otherwise all rows after the first row deal with the maximum value of the previous row and in general can not have en element that is greater than the current value of max_row. So the corresponding element of the array b will not be initialized.

Also the user can enter for the matrix negative values in this case your program will output zeroes instead of maximum values.

To find maximum elements in rows and minimum elements in columns it is enough to have one pair of nested loops/

Here is a demonstrative program/

```<code>#include <iostream>
#include <iomanip>

int main()
{
    const size_t N = 3;
    int a[N][N] =
    {
        { 1,  2, 3 },
        { 4, 33, 6 },
        { 7,  8, 9 }
    };

    int b[N], c[N];

    for ( size_t i = 0; i < N; i++ )
    {
        b[i] = a[i][0];
        c[i] = a[0][i];
        for ( size_t j = 1; j < N; j++ )
        {
            if ( b[i] < a[i][j] ) b[i] = a[i][j];
            if ( a[j][i] < c[i] ) c[i] = a[j][i];
        }
    }

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            std::cout << std::setw( 3 ) << a[i][j] << '\t';
        }
        std::cout << '|' << b[i] << '\n';
    }

    for ( size_t i = 0; i < N; i++ )
    {
        std::cout << std::setw( 3 ) << '-' << '\t';
    }
    std::cout << '\n';

    for ( size_t i = 0; i < N; i++ )
    {
        std::cout << std::setw( 3 ) << c[i] << '\t';
    }
    std::cout << '\n';

    return 0;
}
</code>```

Its output is

```<code>  1   2   3 |3
  4  33   6 |33
  7   8   9 |9
  -   -   -
  1   2   3
</code>```

Body:
I was trying to  do the following:
Have a matrix, print the entire thing out, print at end of every row the biggest element of said row and print at the bottom of every column the smallest element of said column.
I'm pretty much a beginner at C++.

So here's what I've done so far:

 #include <iostream>
    #include <iomanip>
    #define M 50
    #define N 50
    using namespace std;
    int main()
    {
        int m,n;
        int a[M][N];
        int b[M],c[N];

        do {
        cout<<"m=";
        cin>>m;
        cout<<endl<<"n=";
        cin>>n;
        cout<<endl;
        }
        while(m!=n);

        for(int i=0;i<m; i++) {
            for(int j=0; j<n; j++){
            cout<<"a["<<i<<"]["<<j<<"]=";
            cin>>a[i][j];
            }
        }
        int max_row;
        max_row=0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (a[i][j] > max_row) {
                    max_row = a[i][j];
                    b[i] = max_row;
                }
            }
        }

        for (int i=0; i<m; i++)
        { for(int j=0; j<n; j++){
            cout<<setw(3)<<a[i][j]<<"\t";
        }
        cout<<"|"<<b[i];
        cout<<endl;
        }
        for(int i=0; i<m; i++){
        cout<<setw(3)<<"-";}

        cout<<endl;

        for(int j=0; j<n; j++)
        {cout<<c[j]<<"\t";
        }

        system("pause");
    }

Most of the time the max_row are the correct ones such as this case:

  3       2       1     |3
  4       6       5     |6
  7       8       9     |9

Other times they get messed up and it goes like this:

  1       2       3     |3
  4      33       6     |33
  7       8       9     |-858993460

I really have no idea what causes it and since there are no error messages I got really confused. Also I have no idea how to make the min column ones. Any help would be appreciated.

Body:
The problem with these loops

    max_row=0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (a[i][j] > max_row) {
                max_row = a[i][j];
                b[i] = max_row;
            }
        }
    }

is that the value of max_row should be initialized with each iteration of the outer loop. Otherwise all rows after the first row deal with the maximum value of the previous row and in general can not have en element that is greater than the current value of max_row. So the corresponding element of the array b will not be initialized.

Also the user can enter for the matrix negative values in this case your program will output zeroes instead of maximum values.

To find maximum elements in rows and minimum elements in columns it is enough to have one pair of nested loops/

Here is a demonstrative program/

#include <iostream>
#include <iomanip>

int main()
{
    const size_t N = 3;
    int a[N][N] =
    {
        { 1,  2, 3 },
        { 4, 33, 6 },
        { 7,  8, 9 }
    };

    int b[N], c[N];

    for ( size_t i = 0; i < N; i++ )
    {
        b[i] = a[i][0];
        c[i] = a[0][i];
        for ( size_t j = 1; j < N; j++ )
        {
            if ( b[i] < a[i][j] ) b[i] = a[i][j];
            if ( a[j][i] < c[i] ) c[i] = a[j][i];
        }
    }

    for ( size_t i = 0; i < N; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            std::cout << std::setw( 3 ) << a[i][j] << '\t';
        }
        std::cout << '|' << b[i] << '\n';
    }

    for ( size_t i = 0; i < N; i++ )
    {
        std::cout << std::setw( 3 ) << '-' << '\t';
    }
    std::cout << '\n';

    for ( size_t i = 0; i < N; i++ )
    {
        std::cout << std::setw( 3 ) << c[i] << '\t';
    }
    std::cout << '\n';

    return 0;
}

Its output is

  1   2   3 |3
  4  33   6 |33
  7   8   9 |9
  -   -   -
  1   2   3


问:
Measure does not work for Month Threshold
I build this Dax measure

```<code>_Access_Daily = CALCULATE(
    DISTINCTCOUNTNOBLANK(ApplicationAccessLog[ApplicationUserID]),
FILTER('Date','Date'[DateId]=SELECTEDVALUE('DateSelector'[DateId],MAX('DateSelector'[DateId]))))+0

_Access__PreviousDay = CALCULATE(
DISTINCTCOUNTNOBLANK(ApplicationAccessLog[ApplicationUserID]),  FILTER('Date','Date'[DateId]=SELECTEDVALUE('DateSelector'[DateId],MAX('DateSelector'[DateId]))-1 ))+0
</code>```

The Date Selector table is a disconnected table containing dates from the 20th Jan to now. Dateid is a whole number like 20200131.
The Date table is a standard date table with all the dates between 1970 and 2038. Date id is a whole number like 20200131.
However it does not seems to work for the month threshold between Jan and Feb ? So if selected date is 01/02/2020 then it does not return correctly for the 31/01/2020.

答:
As mentioned in the comments, the root problem here is that the whole numbers you use are not dates. As a result, when you subtract 1 and cross month (or year) boundaries, there is no calendar intelligence that can adjust the numbers properly.

Your solution (using 'Date'[DayDateNext]) might work, and if for some additional considerations this design is a must, go with it. However, I'd suggest to revisit the overall approach and use real dates instead of "DateId". You will then be able to use built-in DAX time intelligence, and your code will be more elegant and faster.

For example, if your "Date" and "DateSelector" tables have regular date fields, your code can be re-written as follows:

```<code>_Access_Daily =
VAR Selected_Date = SELECTEDVALUE ( 'DateSelector'[Date], MAX ( 'DateSelector'[Date] ) )
VAR Result =
    CALCULATE (
        DISTINCTCOUNTNOBLANK ( ApplicationAccessLog[ApplicationUserID] ),
        'Date'[Date] = Selected_Date
    )
RETURN
    Result + 0
</code>```

and:

```<code>_Access_PreviousDay =
CALCULATE ( [_Access_Daily], PREVIOUSDAY ( 'Date'[Date] ) )
</code>```

Body:
I build this Dax measure

_Access_Daily = CALCULATE(
    DISTINCTCOUNTNOBLANK(ApplicationAccessLog[ApplicationUserID]),
FILTER('Date','Date'[DateId]=SELECTEDVALUE('DateSelector'[DateId],MAX('DateSelector'[DateId]))))+0

_Access__PreviousDay = CALCULATE(
DISTINCTCOUNTNOBLANK(ApplicationAccessLog[ApplicationUserID]),  FILTER('Date','Date'[DateId]=SELECTEDVALUE('DateSelector'[DateId],MAX('DateSelector'[DateId]))-1 ))+0

The Date Selector table is a disconnected table containing dates from the 20th Jan to now. Dateid is a whole number like 20200131.
The Date table is a standard date table with all the dates between 1970 and 2038. Date id is a whole number like 20200131.
However it does not seems to work for the month threshold between Jan and Feb ? So if selected date is 01/02/2020 then it does not return correctly for the 31/01/2020.

Body:
As mentioned in the comments, the root problem here is that the whole numbers you use are not dates. As a result, when you subtract 1 and cross month (or year) boundaries, there is no calendar intelligence that can adjust the numbers properly.

Your solution (using 'Date'[DayDateNext]) might work, and if for some additional considerations this design is a must, go with it. However, I'd suggest to revisit the overall approach and use real dates instead of "DateId". You will then be able to use built-in DAX time intelligence, and your code will be more elegant and faster.

For example, if your "Date" and "DateSelector" tables have regular date fields, your code can be re-written as follows:

_Access_Daily =
VAR Selected_Date = SELECTEDVALUE ( 'DateSelector'[Date], MAX ( 'DateSelector'[Date] ) )
VAR Result =
    CALCULATE (
        DISTINCTCOUNTNOBLANK ( ApplicationAccessLog[ApplicationUserID] ),
        'Date'[Date] = Selected_Date
    )
RETURN
    Result + 0

and:

_Access_PreviousDay =
CALCULATE ( [_Access_Daily], PREVIOUSDAY ( 'Date'[Date] ) )


问:
Get parent/children where parent numbers don't always match
I'm having an issue getting all related items to roll up into one result set.

In this instance, we have a master ParentPart (901359) with components that are related. We can also have components that are a parent part (340804, 340801, 340850)

The below data is what I'm dealing with

```<code>ParentPart  Component
---------------------
901359      340804
340804      340801
340801      340850
340850      333000
</code>```

What I'm looking to get is this result, or to get all of the related components to roll-up

```<code>ParentPart  Component
----------------------
901359      340804
901359      340801
901359      340850
901359      333000
</code>```

Below is code for testing.

```<code>CREATE TABLE #Hierarchy
(
    ParentPart VARCHAR(15),
    Component VARCHAR(15)
)

INSERT INTO #Hierarchy (ParentPart, Component)
VALUES
  ('901359','340804'),
  ('340804','340801'),
  ('340801','340850'),
  ('340850','333000')

 SELECT *
 FROM #Hierarchy

 DROP TABLE #Hierarchy
</code>```

I've tried a recursive CTE, but it doesn't give me the result I'm looking for since the parent parts are not all the same.

Any pointers?

答:
Following recursive CTE will do the work:</p>

```<code>with hier as (
select ParentPart as MainPart, ParentPart, Component from #Heirarchy
union all
select hier.MainPart, p.ParentPart, p.Component
from hier
join #Heirarchy as p
on p.ParentPart = hier.Component
)
select MainPart, Component from hier where MainPart = '901359';
</code>```

Body:
I'm having an issue getting all related items to roll up into one result set.

In this instance, we have a master ParentPart (901359) with components that are related. We can also have components that are a parent part (340804, 340801, 340850)

The below data is what I'm dealing with

ParentPart  Component
---------------------
901359      340804
340804      340801
340801      340850
340850      333000

What I'm looking to get is this result, or to get all of the related components to roll-up

ParentPart  Component
----------------------
901359      340804
901359      340801
901359      340850
901359      333000

Below is code for testing.

CREATE TABLE #Hierarchy
(
    ParentPart VARCHAR(15),
    Component VARCHAR(15)
)

INSERT INTO #Hierarchy (ParentPart, Component)
VALUES
  ('901359','340804'),
  ('340804','340801'),
  ('340801','340850'),
  ('340850','333000')

 SELECT *
 FROM #Hierarchy

 DROP TABLE #Hierarchy

I've tried a recursive CTE, but it doesn't give me the result I'm looking for since the parent parts are not all the same.

Any pointers?

Body:
Following recursive CTE will do the work:

with hier as (
select ParentPart as MainPart, ParentPart, Component from #Heirarchy
union all
select hier.MainPart, p.ParentPart, p.Component
from hier
join #Heirarchy as p
on p.ParentPart = hier.Component
)
select MainPart, Component from hier where MainPart = '901359';


答:
That's a typical recursive query. In this case, you can walk the tree from the top to the bottom:

```<code>with cte as (
    select parentpart, component, 1 lvl  from #Hierarchy
    union all
    select c.parentpart, h.component, lvl + 1
    from cte c
    inner join #Hierarchy h on h.parentpart = c.component
)
select parentpart, component
from cte c
where c.lvl = (select max(c1.lvl) from cte c1 where c1.component = c.component)
</code>```

The recursive common table expression generates the tree paths, while keeping track of the level of each node; then the outer query filters on the top parent per node.

Demo on DB Fiddle:

```
parentpart | component
:--------- | :--------
901359     | 340804
901359     | 340801
901359     | 340850
901359     | 333000
```

Title: Get parent/children where parent numbers don't always match

Body:
That's a typical recursive query. In this case, you can walk the tree from the top to the bottom:

with cte as (
    select parentpart, component, 1 lvl  from #Hierarchy
    union all
    select c.parentpart, h.component, lvl + 1
    from cte c
    inner join #Hierarchy h on h.parentpart = c.component
)
select parentpart, component
from cte c
where c.lvl = (select max(c1.lvl) from cte c1 where c1.component = c.component)

The recursive common table expression generates the tree paths, while keeping track of the level of each node; then the outer query filters on the top parent per node.

Demo on DB Fiddle:

parentpart | component
:--------- | :--------
901359     | 340804
901359     | 340801
901359     | 340850
901359     | 333000


问:
Guice + Tomcat potential memory leak
I have just started using Google Guice with my Tomcat webapp, and have noticed the following in the catalina.out file whenever the WAR file is undeployed:

May 16, 2011 5:37:24 PM org.apache.catalina.startup.HostConfig checkResources
INFO: Undeploying context [/app]

May 16, 2011 5:37:24 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: A web application appears to have started a thread named [com.google.inject.internal.util.$Finalizer] but has failed to stop it. This is very likely to create a memory leak.

May 16, 2011 5:37:24 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: A web application created a ThreadLocal with key of type [null] (value [com.google.inject.internal.InjectorImpl$1@10ace8d]) and a value of type [java.lang.Object[]] (value [[Ljava.lang.Object;@7e9bed]) but failed to remove it when the web application was stopped. To prevent a memory leak, the ThreadLocal has been forcibly removed.

Does anyone know what causes this, or how I can stop it from happening?

I have only followed the instructions from here
http://code.google.com/docreader/#p=google-guice&s=google-guice&t=ServletModule

... and haven't done anything fancy with it yet. I just have 2 servlets and a filter.

Thanks!

答:
If you are getting this when you shutdown the webapp, I wouldn't worry too much. This type of resource leak on app. shutdown is common. They do become a problem when you frequently do hot deploys (i.e. un-deploy many times without killing the JVM), but they won't be problematic when a cold deploy is done (un-deploy/deploy is done while killing the JVM before re-deploy).

A common tactic is that you do hot-deploys during development (as they are typically faster than cold-deploys), and only do a cold deploy when the resource leak starts to affect your performance. Then, in production you do a cold deploy on every deploy. Given the number of code/libraries that has this type of leak, trying to eliminate them would be hard IMO.

Title: Guice + Tomcat potential memory leak


问:
os.walk() is not throwing any error nor the result in python
I am trying to print the file names which are in a predefined paths where the paths are stored in paths.txt. But when I execute the below code, I'm not getting any error nor the files names printed.

```<code>import os
with open('D:\paths.txt', 'r') as file:
    data = file.read()
    path = data.split(";")
    print(path)
    for line in path:
        for root, dirs, files in os.walk(line):
            for name in files:
                print(name)
</code>```

答:
You need to remove the double-quotes from the file (""). Here is why; When the file gets read by Python, after it does the .split(), the double-quote characters are part of the Python string. So instead of passing into os.walk() the path D:\bp1, you were actually passing in "D:\bp1", and there was no path that starts with a " that's why nothing was happening.

You would only need to provide the double quotes if you're writing the name in a terminal/command prompt and don't want to escape the double quotes, or if you're trying to define the string inside Python using the double quote literal, for example path = "D:\\bp1" (notice that in that case you also have to escape the \ with another one.

Body:
I am trying to print the file names which are in a predefined paths where the paths are stored in paths.txt. But when I execute the below code, I'm not getting any error nor the files names printed.

import os
with open('D:\paths.txt', 'r') as file:
    data = file.read()
    path = data.split(";")
    print(path)
    for line in path:
        for root, dirs, files in os.walk(line):
            for name in files:
                print(name)


问:
Pass parameter to nested procedure or create temp table and check if table exists
I have the following structure of stored procedures:

```<code>exec A -> exec B -> exec C -> exec D
</code>```

where stored procedure A calls stored procedure B, B calls C and C calls D.

I need a special behavior to happen in stored procedure D based on a condition that is determined in stored procedure A. Of course one option is to pass param from A to B, then from B to C, then from C to D, but I was wondering if I can simply just create a temp table prior to executing A, then when I am in stored procedure D I can just check if temp table exists and perform my logic based on that.Finally in the line right after exec A, I will drop the temp table

EDIT: I am aware that if proc D is called from a different procedure the condition will be treated as not exists. Also I am aware of temp table name can clash with another temp table with the same name. Other than that...

Is there any unwanted side effects to doing the later solution?

答:
The temp tables or (#tables) should have the lifespan of the session. In the case you describe you should be able to create the #table in PROC A and reference it on PROC D without any special considerations.

Please note that if you take this approach you are creating a direct dependency between PROC D and PROC A, since now you have to call PROC A to create the Temp table you are using on PROC D. If you are OK with this then go ahead.

Body:
I have the following structure of stored procedures:

exec A -> exec B -> exec C -> exec D

where stored procedure A calls stored procedure B, B calls C and C calls D.

I need a special behavior to happen in stored procedure D based on a condition that is determined in stored procedure A. Of course one option is to pass param from A to B, then from B to C, then from C to D, but I was wondering if I can simply just create a temp table prior to executing A, then when I am in stored procedure D I can just check if temp table exists and perform my logic based on that.Finally in the line right after exec A, I will drop the temp table

EDIT: I am aware that if proc D is called from a different procedure the condition will be treated as not exists. Also I am aware of temp table name can clash with another temp table with the same name. Other than that...

Is there any unwanted side effects to doing the later solution?


问:
Using v-for with nested object in Vue
I have data in this form:

```<code>itemlist : {
  "dates": [
    "2019-03-15",
    "2019-04-01",
    "2019-05-15"
  ],
  "id": [
    "arn21",
    "3sa4a",
    "wqa99"
  ],
  "price": [
    22,
    10,
    31
  ]
}
</code>```

I want to use v-for in my created component that loops through this object treating every index in those 3 nested arrays as one observation. So dates[0], id[0] and price[0]correspond to same item, dates[1] id[1] price[1] is second and so on.

So In other words I think I need to transform this into, but not sure:

```<code>0 : {
dates: "2019-03-15",
id: "arn21",
price: 22,}
1:{
dates: "2019-04-01",
id: "3sa4a",
price: 10}
}
2:...
</code>```

Thats how I pass the data to the component:

```<code><tempc v-for="i in itemlist" :key="i.id" :price="i.price" :dates="i.dates"></temp>
</code>```

But this does not work for the original data

答:
You can create a computed property for this:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      itemlist: {
        "dates": [
          "2019-03-15",
          "2019-04-01",
          "2019-05-15"
        ],
        "id": [
          "arn21",
          "3sa4a",
          "wqa99"
        ],
        "price": [
          22,
          10,
          31
        ]
      }
    };
  },
  computed: {
    // Note: here I assume these arrays will always have the same length
    mergedList() {
      return this.itemlist.dates.map((dates, i) => {
        return {
          dates,
          id: this.itemlist.id[i],
          price: this.itemlist.price[i]
        };
      });
    }
  }
});

var vm = new Vue({
  el: '#app'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <ul>
    <li v-for="i in mergedList" :key="i.id" :price="i.price" :dates="i.dates">
      {{i.id}} - ${{i.price}} ({{i.dates}})
    </li>
  </ul>
</template></code>```

Title: Using v-for with nested object in Vue

Body:
I have data in this form:

itemlist : {
  "dates": [
    "2019-03-15",
    "2019-04-01",
    "2019-05-15"
  ],
  "id": [
    "arn21",
    "3sa4a",
    "wqa99"
  ],
  "price": [
    22,
    10,
    31
  ]
}

I want to use v-for in my created component that loops through this object treating every index in those 3 nested arrays as one observation. So dates[0], id[0] and price[0]correspond to same item, dates[1] id[1] price[1] is second and so on.

So In other words I think I need to transform this into, but not sure:

0 : {
dates: "2019-03-15",
id: "arn21",
price: 22,}
1:{
dates: "2019-04-01",
id: "3sa4a",
price: 10}
}
2:...

Thats how I pass the data to the component:

<tempc v-for="i in itemlist" :key="i.id" :price="i.price" :dates="i.dates"></temp>

But this does not work for the original data

Body:
You can create a computed property for this:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      itemlist: {
        "dates": [
          "2019-03-15",
          "2019-04-01",
          "2019-05-15"
        ],
        "id": [
          "arn21",
          "3sa4a",
          "wqa99"
        ],
        "price": [
          22,
          10,
          31
        ]
      }
    };
  },
  computed: {
    // Note: here I assume these arrays will always have the same length
    mergedList() {
      return this.itemlist.dates.map((dates, i) => {
        return {
          dates,
          id: this.itemlist.id[i],
          price: this.itemlist.price[i]
        };
      });
    }
  }
});

var vm = new Vue({
  el: '#app'
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <ul>
    <li v-for="i in mergedList" :key="i.id" :price="i.price" :dates="i.dates">
      {{i.id}} - ${{i.price}} ({{i.dates}})
    </li>
  </ul>
</template>


问:
Detect swipe gestures and touch events on a view
Android Studio, Java

Is there a way to detect touch down, touch release, and swipe gestures, on a single view? I have a button and I need to be able to listen to all of these on it.

I'm looking for a solution where the listeners/detectors end up calling these methods so I easily can work with them:

```<code>public void buttonPressedDown() {

}

public void buttonReleased() {

}

public void swipeUp() {

}

public void swipeRight() {

}

public void swipeDown() {

}

public void swipeLeft() {

}
</code>```

This is easy to accomplish in xcode when developing ios apps, but I can't seem to find a way to do it for android.

Extra info:
This is what I've tried:

```<code>    timerButton.setOnTouchListener(new View.OnTouchListener() { //Detecting a press down
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            timerDown();

            return false;
        }
    });

    timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {//Detecting swipes

        public void onSwipeTop() {

            showStats();

        }

        public void onSwipeBottom() {

            showType();

        }

        public void onSwipeRight() {

            showMenu();

        }

        public void onSwipeLeft() {

            showTimes();

        }

    });

    .
    .
    .

    public void timerButtonPressed(View view) {//Detecting press releases
        timerUp();
    }
</code>```

This seemed like what I was looking for, except it didn't work. When setting two onTouchListeners on the same view, only one of the listeners were being called. Either only the swipe detections worked, or only the press detections, when I tested it.

Help!?

Edit:
I've tried this:

OnSwipeTouchListener.java

```<code>public class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context context) {
        gestureDetector = new GestureDetector(context, new GestureListener());
    }

    public void onSwipeLeft() {
    }

    public void onSwipeRight() {
    }

    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_DISTANCE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float distanceX = e2.getX() - e1.getX();
            float distanceY = e2.getY() - e1.getY();
            if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceX > 0)
                    onSwipeRight();
                else
                    onSwipeLeft();
                return true;
            }
            return false;
        }
    }
}
</code>```

And in my activity:

```<code>timerButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(timerActivity.this);
            boolean result = onSwipeTouchListener.onTouch(v, event);
            // check if swipe was detected:
            if (result) return true;

            // Otherwise, detect other types of motion event
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // touch down

                    timerDown();

                    break;
                case MotionEvent.ACTION_UP:
                    // touch released

                    timerUp();

                    break;
            }

            return false;
        }
    });
</code>```

But how would I detect the swipes from here? Also when I run the application it doesn't even detect touches anymore.

I also tried this in my activity:

```<code>timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {

        public void onSwipeLeft() {
            Log.i("LEFT", "LEFT");
        }

        public void onSwipeRight() {
            Log.i("RIGHT", "RIGHT");
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // touch down

                    timerDown();

                    break;
                case MotionEvent.ACTION_UP:
                    // touch released

                    timerUp();

                    break;
            }

            return false;
        }
    });
</code>```

Now it detects touches but won't detect swipes. If I remove the @override onTouch method above, but still have the onSwipe methods, then the swipes are detected. How is this so complicated? Why won't it detect both swipes and touches, and how do I solve it?

答:
I found a solution.

In OnSwipeTouchListener.java:

```<code>public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public void onSwipeBottom() {
}

public void onSwipeTop() {
}

public void onDownTouch() {

}

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        onDownTouch();
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                    result = true;
                }
            }
            else if (Math.abs(diffY) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    onSwipeBottom();
                } else {
                    onSwipeTop();
                }
                result = true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}
</code>```

}

And in activity:

To detect button release press: (on click)

```<code>public void timerButtonPressed(View view) {

}
</code>```

To detect swipes and down press:

```<code>timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {

        public void onSwipeLeft() {

        }

        public void onSwipeRight() {

        }

        public void onSwipeBottom() {

        }

        public void onSwipeTop() {

        }

        public void onDownTouch() {

        }
    });
</code>```

Body:
Android Studio, Java

Is there a way to detect touch down, touch release, and swipe gestures, on a single view? I have a button and I need to be able to listen to all of these on it.

I'm looking for a solution where the listeners/detectors end up calling these methods so I easily can work with them:

public void buttonPressedDown() {

}

public void buttonReleased() {

}

public void swipeUp() {

}

public void swipeRight() {

}

public void swipeDown() {

}

public void swipeLeft() {

}

This is easy to accomplish in xcode when developing ios apps, but I can't seem to find a way to do it for android.

Extra info:
This is what I've tried:

    timerButton.setOnTouchListener(new View.OnTouchListener() { //Detecting a press down
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            timerDown();

            return false;
        }
    });

    timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {//Detecting swipes

        public void onSwipeTop() {

            showStats();

        }

        public void onSwipeBottom() {

            showType();

        }

        public void onSwipeRight() {

            showMenu();

        }

        public void onSwipeLeft() {

            showTimes();

        }

    });

    .
    .
    .

    public void timerButtonPressed(View view) {//Detecting press releases
        timerUp();
    }

This seemed like what I was looking for, except it didn't work. When setting two onTouchListeners on the same view, only one of the listeners were being called. Either only the swipe detections worked, or only the press detections, when I tested it.

Help!?

Edit:
I've tried this:

OnSwipeTouchListener.java

public class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context context) {
        gestureDetector = new GestureDetector(context, new GestureListener());
    }

    public void onSwipeLeft() {
    }

    public void onSwipeRight() {
    }

    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_DISTANCE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float distanceX = e2.getX() - e1.getX();
            float distanceY = e2.getY() - e1.getY();
            if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (distanceX > 0)
                    onSwipeRight();
                else
                    onSwipeLeft();
                return true;
            }
            return false;
        }
    }
}

And in my activity:

timerButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(timerActivity.this);
            boolean result = onSwipeTouchListener.onTouch(v, event);
            // check if swipe was detected:
            if (result) return true;

            // Otherwise, detect other types of motion event
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // touch down

                    timerDown();

                    break;
                case MotionEvent.ACTION_UP:
                    // touch released

                    timerUp();

                    break;
            }

            return false;
        }
    });

But how would I detect the swipes from here? Also when I run the application it doesn't even detect touches anymore.

I also tried this in my activity:

timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {

        public void onSwipeLeft() {
            Log.i("LEFT", "LEFT");
        }

        public void onSwipeRight() {
            Log.i("RIGHT", "RIGHT");
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // touch down

                    timerDown();

                    break;
                case MotionEvent.ACTION_UP:
                    // touch released

                    timerUp();

                    break;
            }

            return false;
        }
    });

Now it detects touches but won't detect swipes. If I remove the @override onTouch method above, but still have the onSwipe methods, then the swipes are detected. How is this so complicated? Why won't it detect both swipes and touches, and how do I solve it?

Body:
I found a solution.

In OnSwipeTouchListener.java:

public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public void onSwipeBottom() {
}

public void onSwipeTop() {
}

public void onDownTouch() {

}

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;

    @Override
    public boolean onDown(MotionEvent e) {
        onDownTouch();
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        boolean result = false;
        try {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffX > 0) {
                        onSwipeRight();
                    } else {
                        onSwipeLeft();
                    }
                    result = true;
                }
            }
            else if (Math.abs(diffY) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    onSwipeBottom();
                } else {
                    onSwipeTop();
                }
                result = true;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

}

And in activity:

To detect button release press: (on click)

public void timerButtonPressed(View view) {

}

To detect swipes and down press:

timerButton.setOnTouchListener(new OnSwipeTouchListener(timerActivity.this) {

        public void onSwipeLeft() {

        }

        public void onSwipeRight() {

        }

        public void onSwipeBottom() {

        }

        public void onSwipeTop() {

        }

        public void onDownTouch() {

        }
    });


问:
NOT NULL constraint failed: community_comment.posts_id?
how can I fix this issue?

the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question?

- also, I need anyone to give me the best way to make a relationship between post and comment

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

class Publication(models.Model):
    title = models.CharField(max_length=30)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

class Article(models.Model):
    publications = models.ManyToManyField(Publication)
    headline = models.CharField(max_length=100)

    class Meta:
        ordering = ['headline']

    def __str__(self):
        return self.headline

class Post(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    question = models.TextField(max_length=500)

    def __str__(self):
        return self.title

class Comment(models.Model):
    posts = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500)

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

views.py

```<code>from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm

def index(request):
    # All questions
    posts = Post.objects.all()
    return render(request, 'community/index.html', {'posts': posts})

def post_view(request):
    post_form = PostForm
    context = {'posted': post_form}

    # Create post
    if request.method == 'GET':
        post_form = PostForm(request.GET)
        if post_form.is_valid():
            user_post = post_form.save(commit=False)
            user_post.title = post_form.cleaned_data['title']
            user_post.question = post_form.cleaned_data['question']
            post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
            post.save()
            return redirect('community:index')

    return render(request, 'community/post.html', context)

def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.comment = comment_form.cleaned_data['comment']
            user_comment.save()

    return render(request, 'community/answers.html', context)
</code>```

urls.py

```<code>from django.urls import path
from . import views

app_name = 'community'

urlpatterns = [
    path('', views.index, name='index'),
    path('post/', views.post_view, name='post'),
    path('answers/<int:post_id>', views.answers, name='answers'),
]
</code>```

forms.py

```<code>from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = '__all__'
        exclude = ['users']

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = '__all__'
        exclude = ['users', 'posts']
</code>```

答:
You forgot to assign the post, or the post_id of the comment you created:

```<code>def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            <b>comment_form.instance.post_id = post_id</b>
            user_comment = comment_form.save()
    # …</code>```

That being said, the above view does not really respect the HTTP assumptions. A view that makes a GET request is not supposed to change entities, so if you want to create a comment, you need to do that through a POST request. Furthemore in order to implement the Post/Redirect/Get pattern [wiki] a successful POST request should return a redirect response.

Body:
how can I fix this issue?

the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question?

- also, I need anyone to give me the best way to make a relationship between post and comment

models.py

from django.db import models
from django.contrib.auth.models import User

class Publication(models.Model):
    title = models.CharField(max_length=30)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

class Article(models.Model):
    publications = models.ManyToManyField(Publication)
    headline = models.CharField(max_length=100)

    class Meta:
        ordering = ['headline']

    def __str__(self):
        return self.headline

class Post(models.Model):
    users = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    question = models.TextField(max_length=500)

    def __str__(self):
        return self.title

class Comment(models.Model):
    posts = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment = models.TextField(max_length=500)

    def __str__(self):
        return self.comment

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm

def index(request):
    # All questions
    posts = Post.objects.all()
    return render(request, 'community/index.html', {'posts': posts})

def post_view(request):
    post_form = PostForm
    context = {'posted': post_form}

    # Create post
    if request.method == 'GET':
        post_form = PostForm(request.GET)
        if post_form.is_valid():
            user_post = post_form.save(commit=False)
            user_post.title = post_form.cleaned_data['title']
            user_post.question = post_form.cleaned_data['question']
            post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
            post.save()
            return redirect('community:index')

    return render(request, 'community/post.html', context)

def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            user_comment = comment_form.save(commit=False)
            user_comment.comment = comment_form.cleaned_data['comment']
            user_comment.save()

    return render(request, 'community/answers.html', context)

urls.py

from django.urls import path
from . import views

app_name = 'community'

urlpatterns = [
    path('', views.index, name='index'),
    path('post/', views.post_view, name='post'),
    path('answers/<int:post_id>', views.answers, name='answers'),
]

forms.py

from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = '__all__'
        exclude = ['users']

class CommentForm(forms.ModelForm):

    class Meta:
        model = Comment
        fields = '__all__'
        exclude = ['users', 'posts']

Body:
You forgot to assign the post, or the post_id of the comment you created:

def answers(request, post_id):
    # Specific post
    posts = Post.objects.get(id=post_id)
    # Create comment
    comment_form = CommentForm
    context = {'posts': posts, 'comment_form': comment_form}
    if request.method == 'GET':
        comment_form = CommentForm(request.GET)
        if comment_form.is_valid():
            comment_form.instance.post_id = post_id
            user_comment = comment_form.save()
    # …

That being said, the above view does not really respect the HTTP assumptions. A view that makes a GET request is not supposed to change entities, so if you want to create a comment, you need to do that through a POST request. Furthemore in order to implement the Post/Redirect/Get pattern [wiki] a successful POST request should return a redirect response.


问:
In Android Studio, how can I get the Layout Inspector to display more complex views?
I'm writing automated UI tests for an Android app. However, sometimes the Layout Inspector fails to show the view hierarchy and instead displays an error:

Error obtaining view hierarchy: There was a timeout error capturing the layout data from the device. The device may be too slow, the captured view may be too complex, or the view may contain animations.

Please retry with a simplified view and ensure the device is responsive.

I've tried the solutions from this question, but none have worked for me. I'm using Android Studio 3.5.2 and am running the app on a physical device.

Is there a way to get the Layout Inspector to display more complex views? Or is it possible to increase the timeout?

答: I found an unorthodox solution: Layout Inspector sometimes works when the app is sent to the background. The views will be shown as inactive, but it will still be possible to see their properties.


问:
PHP getallheaders alternative
I am trying to switch from apache to nginx on my server. The only problem here is the getallheaders() function I used in my PHP scripts which does not work with Nginx. I have tried the user contributed notes on php site on getallheaders finction but that does not return all request headers.

Please tell me how to solve this problem. I would really like to switch to Nginx.

答: A request header of Owner-ID will be passed to php as $_SERVER['HTTP_OWNER_ID'] by nginx.  All request headers are passed in a similar manner.</p>

Title: PHP getallheaders alternative