问:
unable to retrieve link params when opening branch link inside app
Our android app is a chat app. Users can paste a branch link in a chat message. When another user taps on it, we want to retrieve the link parameters to take the user to another screen.

Unfortunately, we are unable to retrieve the link parameters when we tap on such link inside the app (note that we are not using a webview), we are getting the error "Warning. Session initialisation already happened.

To force a new session, set intent extra, branch_force_new_session, to true in the onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) method.

How can we solve this? It's not obvious to me how I could pass a new intent param in that use case.

Notes:

Our launcher activity is singleTask
We are on branch.io sdk 4.3.2
onNewIntent() does not seem to be called (in the code below), maybe that is the root cause for our issue.

sample code:

```<code>private Branch.BranchReferralInitListener branchReferralInitListener =
            new Branch.BranchReferralInitListener() {

                @Override
                public void onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) {
                    ...
}

@Override
    protected void onStart() {
        super.onStart();
        Branch.getInstance().initSession(branchReferralInitListener, getIntent() != null ?
                getIntent().getData() : null, this);
    }
@Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        // activity will skip onStart, handle this case with reInitSession
        Branch.getInstance().reInitSession(this, branchReferralInitListener);
    }
</code>```

答:
Initialized, you branch IO in application class so that it will initialize once and will not be require again

```<code>// Branch logging for debugging
        Branch.enableLogging();
        //Disable Device ID #2966
        Branch.disableDeviceIDFetch(true);
        // Initialize the Branch object
        BranchIOManager.setupBranchInstance(this);
        // It tells the Branch initialization to wait for the Google Play Referrer before proceeding.
        Branch.enablePlayStoreReferrer(1000L);
</code>```

Then inside initSession() branch method use. Pass them as JSON Object to method where you can retrieve the value based on key names.

```<code>if (branch != null && uri != null) {
                branch.initSession(new Branch.BranchUniversalReferralInitListener() {
                    @Override
                    public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
                        // Log.d("onInitFinished", error + "");
                        if (error == null && branchUniversalObject != null) {
                            JSONObject jBranch = branchUniversalObject.getContentMetadata().convertToJson();
                            if (!branchJSONString.equals(jBranch.toString())) {
                                //This check is applied as if we launch another mLandingScreenPhoneActivity from Branch link then app will become in loop
                                branchJSONString = jBranch.toString();
                                loadScreenFromBranchIODynamicLink(jBranch, 0);
                            }
                        }

                        if (error != null) {
                            //  //Toast.makeText(LandingScreenPhoneActivity.this, error + "", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, uri, this);
            }
</code>```

Here you can get screen values

```<code>String screenName = referringParams.optString("screen_key");
            //Screen in app where needs to navigate
int screenIndex = referringParams.optInt("screen_index");
</code>```

Body:
Our android app is a chat app. Users can paste a branch link in a chat message. When another user taps on it, we want to retrieve the link parameters to take the user to another screen.

Unfortunately, we are unable to retrieve the link parameters when we tap on such link inside the app (note that we are not using a webview), we are getting the error "Warning. Session initialisation already happened.

To force a new session, set intent extra, branch_force_new_session, to true in the onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) method.

How can we solve this? It's not obvious to me how I could pass a new intent param in that use case.

Notes:

Our launcher activity is singleTask
We are on branch.io sdk 4.3.2
onNewIntent() does not seem to be called (in the code below), maybe that is the root cause for our issue.

sample code:

private Branch.BranchReferralInitListener branchReferralInitListener =
            new Branch.BranchReferralInitListener() {

                @Override
                public void onInitFinished(@Nullable JSONObject referringParams, @Nullable BranchError error) {
                    ...
}

@Override
    protected void onStart() {
        super.onStart();
        Branch.getInstance().initSession(branchReferralInitListener, getIntent() != null ?
                getIntent().getData() : null, this);
    }
@Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        // activity will skip onStart, handle this case with reInitSession
        Branch.getInstance().reInitSession(this, branchReferralInitListener);
    }

Body:
Initialized, you branch IO in application class so that it will initialize once and will not be require again

// Branch logging for debugging
        Branch.enableLogging();
        //Disable Device ID #2966
        Branch.disableDeviceIDFetch(true);
        // Initialize the Branch object
        BranchIOManager.setupBranchInstance(this);
        // It tells the Branch initialization to wait for the Google Play Referrer before proceeding.
        Branch.enablePlayStoreReferrer(1000L);

Then inside initSession() branch method use. Pass them as JSON Object to method where you can retrieve the value based on key names.

if (branch != null && uri != null) {
                branch.initSession(new Branch.BranchUniversalReferralInitListener() {
                    @Override
                    public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
                        // Log.d("onInitFinished", error + "");
                        if (error == null && branchUniversalObject != null) {
                            JSONObject jBranch = branchUniversalObject.getContentMetadata().convertToJson();
                            if (!branchJSONString.equals(jBranch.toString())) {
                                //This check is applied as if we launch another mLandingScreenPhoneActivity from Branch link then app will become in loop
                                branchJSONString = jBranch.toString();
                                loadScreenFromBranchIODynamicLink(jBranch, 0);
                            }
                        }

                        if (error != null) {
                            //  //Toast.makeText(LandingScreenPhoneActivity.this, error + "", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, uri, this);
            }

Here you can get screen values

String screenName = referringParams.optString("screen_key");
            //Screen in app where needs to navigate
int screenIndex = referringParams.optInt("screen_index");


来源: stackexchange

问:
list is not updating after first call from get API
get API link using retrofit and live data call the first time after some time not updating itself

Call the function on resume in fragment
LiveDataReport used in call retrofit and set the value mutable live
data

Model Fragment used in RecyclerView and adapter

I want get change on anything or updating in get API

immediate change updating RecyclerView list

here my code

Java

```<code>    public class LiveDataReport {
        private static LiveDataReport liveDataReport;
        private MutableLiveData<ArrayList<Model>> modelLiveData = new MutableLiveData<>();
        private ApiService apiService;

        private LiveDataReport() {
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuth("user", "pass")).build();
            Retrofit retrofit = new Retrofit.Builder()
                                            .client(client)
                                            .baseUrl("http://someipaddress")
                                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                                            .addConverterFactory(GsonConverterFactory.create()).build();
            apiService = retrofit.create(ApiService.class);
            getModelLiveData();
    }
        public synchronized static LiveDataReport getInstance() {
            if (liveDataReport == null)
                liveDataReport = new LiveDataReport();
            return liveDataReport;
        }

        public LiveData<ArrayList<Model>> getModelLiveData() {
            Call<ArrayList<Model>> arrayListCall = apiService.getLiveDataJson();
            arrayListCall.enqueue(new Callback<ArrayList<Model>>() {
                @Override
                public void onResponse(@NotNull Call<ArrayList<Model>> call, @NotNullResponse<ArrayList<Model>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    System.out.println("//report change success Model");
                    modelLiveData.postValue(response.body());
                }
            }

            @Override
            public void onFailure(@NotNull Call<ArrayList<Model>> call, @NotNull Throwable t) {
                System.out.println("//report change failure " + t.toString());
            }
        });
        return modelLiveData;
    }
}

public class MainViewModel extends AndroidViewModel {

    private LiveData<ArrayList<Model>> liveData ;

        public MainViewModel(@NonNull Application application) {
            super(application);
            liveData=LiveDataReport.getInstance().getModelLiveData();

        }

        public LiveData<ArrayList<Model>> getLiveData() {
            System.out.println("//report call last update : getModelLiveData");
            liveData=LiveDataReport.getInstance().getModelLiveData();
            return liveData;
        }
    }

public class ModelFragment extends Fragment implements LifecycleOwner {

    private MainViewModel mainViewModel;
    private RecyclerView recyclerView;
    private FragmentBinding binding;
    private LiveDataAdapter adapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment, container, false);
        mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        recyclerView = binding.myRecycleView;
        adapter = new LiveDataAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.setHasFixedSize(false);
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (Utils.isNetWorkConnected(requireContext())) {
            mainViewModel.getLiveData().observe(getViewLifecycleOwner(),new Observer<ArrayList<Model>>() {
                @Override
                public void onChanged(ArrayList<Model> models) {
                    recyclerView.setAdapter(adapter);
                    adapter.setModel(models,requireContext());
                }
            });
        } else
            Utils.alertCheckNetwork(requireContext());

    }
}

public class LiveDataAdapter extends AdapterSkeleton<Model, LiveDataAdapter.CustomViewHolder> {

    public LiveDataAdapter(Context context, ArrayList<Model> model, RecyclerView recyclerView, IsCanSetAdapterListener canSetAdapterListener){
        this.context=context;
        this.items=model;
        this.isCanSetAdapterListener=canSetAdapterListener;

        measureHeightRecyclerViewAndItem(recyclerView,R.layout.list_model);
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ListModelBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.list_model, parent, false);
        return new CustomViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        if(skeletonConfig.isSkeletonIsOn()){
            return;
        }
        else{
            holder.binding.appSkeleton.setShowSkeleton(false);
            holder.binding.appSkeleton.finishAnimation();
        }
        Model model = items.get(position);
        holder.binding.setModel(reportStatus);

        setAnimation(holder.itemView, position);
    }

    private void setAnimation(View viewToAnimate, int position) {
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.item_animation_fall_down);
        viewToAnimate.startAnimation(animation);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        ListModelBinding binding;

        public CustomViewHolder(@NonNull ListModelBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }
}
</code>```

答:
updating list does not means it will shown into RecyclerView immediately . you have to manually update RecyclerView as well .

to implement this concept , create a method into your RecyclerView Adapter something like this one below

```<code>void updateList(List<POJO> newList) {
    oldList = newList;
    notifyDataChange();
}
</code>```

so you will see that your RecyclerView will update , i know that we use livedata to do it automatically but in order to update recyclerView you have to approach this concept .

ContentLicense: CC BY-SA 4.0

Body:
get API link using retrofit and live data call the first time after some time not updating itself

Call the function on resume in fragment
LiveDataReport used in call retrofit and set the value mutable live
data

Model Fragment used in RecyclerView and adapter

I want get change on anything or updating in get API

immediate change updating RecyclerView list

here my code

Java

    public class LiveDataReport {
        private static LiveDataReport liveDataReport;
        private MutableLiveData<ArrayList<Model>> modelLiveData = new MutableLiveData<>();
        private ApiService apiService;

        private LiveDataReport() {
            OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuth("user", "pass")).build();
            Retrofit retrofit = new Retrofit.Builder()
                                            .client(client)
                                            .baseUrl("http://someipaddress")
                                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                                            .addConverterFactory(GsonConverterFactory.create()).build();
            apiService = retrofit.create(ApiService.class);
            getModelLiveData();
    }
        public synchronized static LiveDataReport getInstance() {
            if (liveDataReport == null)
                liveDataReport = new LiveDataReport();
            return liveDataReport;
        }

        public LiveData<ArrayList<Model>> getModelLiveData() {
            Call<ArrayList<Model>> arrayListCall = apiService.getLiveDataJson();
            arrayListCall.enqueue(new Callback<ArrayList<Model>>() {
                @Override
                public void onResponse(@NotNull Call<ArrayList<Model>> call, @NotNullResponse<ArrayList<Model>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    System.out.println("//report change success Model");
                    modelLiveData.postValue(response.body());
                }
            }

            @Override
            public void onFailure(@NotNull Call<ArrayList<Model>> call, @NotNull Throwable t) {
                System.out.println("//report change failure " + t.toString());
            }
        });
        return modelLiveData;
    }
}

public class MainViewModel extends AndroidViewModel {

    private LiveData<ArrayList<Model>> liveData ;

        public MainViewModel(@NonNull Application application) {
            super(application);
            liveData=LiveDataReport.getInstance().getModelLiveData();

        }

        public LiveData<ArrayList<Model>> getLiveData() {
            System.out.println("//report call last update : getModelLiveData");
            liveData=LiveDataReport.getInstance().getModelLiveData();
            return liveData;
        }
    }

public class ModelFragment extends Fragment implements LifecycleOwner {

    private MainViewModel mainViewModel;
    private RecyclerView recyclerView;
    private FragmentBinding binding;
    private LiveDataAdapter adapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment, container, false);
        mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        recyclerView = binding.myRecycleView;
        adapter = new LiveDataAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerView.setHasFixedSize(false);
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (Utils.isNetWorkConnected(requireContext())) {
            mainViewModel.getLiveData().observe(getViewLifecycleOwner(),new Observer<ArrayList<Model>>() {
                @Override
                public void onChanged(ArrayList<Model> models) {
                    recyclerView.setAdapter(adapter);
                    adapter.setModel(models,requireContext());
                }
            });
        } else
            Utils.alertCheckNetwork(requireContext());

    }
}

public class LiveDataAdapter extends AdapterSkeleton<Model, LiveDataAdapter.CustomViewHolder> {

    public LiveDataAdapter(Context context, ArrayList<Model> model, RecyclerView recyclerView, IsCanSetAdapterListener canSetAdapterListener){
        this.context=context;
        this.items=model;
        this.isCanSetAdapterListener=canSetAdapterListener;

        measureHeightRecyclerViewAndItem(recyclerView,R.layout.list_model);
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ListModelBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.list_model, parent, false);
        return new CustomViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        if(skeletonConfig.isSkeletonIsOn()){
            return;
        }
        else{
            holder.binding.appSkeleton.setShowSkeleton(false);
            holder.binding.appSkeleton.finishAnimation();
        }
        Model model = items.get(position);
        holder.binding.setModel(reportStatus);

        setAnimation(holder.itemView, position);
    }

    private void setAnimation(View viewToAnimate, int position) {
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.item_animation_fall_down);
        viewToAnimate.startAnimation(animation);
    }

    class CustomViewHolder extends RecyclerView.ViewHolder {
        ListModelBinding binding;

        public CustomViewHolder(@NonNull ListModelBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }
    }
}

Body:
updating list does not means it will shown into RecyclerView immediately . you have to manually update RecyclerView as well .

to implement this concept , create a method into your RecyclerView Adapter something like this one below

void updateList(List<POJO> newList) {
    oldList = newList;
    notifyDataChange();
}

so you will see that your RecyclerView will update , i know that we use livedata to do it automatically but in order to update recyclerView you have to approach this concept .


问:
Why this includes() case return false?

var product_id = "14728";
console.log(product_id.includes("14782,12434,3143")); // this return false```

Example.

I just want to check that my product_id is within those other articles ids string

答:
Two reasons:

You have it backwards. You are asking if "14728" includes "14782,12434,3143" (which it doesn't, the latter is too long to be included in the former for a start), not the other way around

"14782,12434,3143" doesn't include "14728" anyway

Your approach is also broken. "14782,12434,3143" includes "314". Presumably you want to only match complete numbers in the comma-separated list. You need to use Array.prototype.includes, not String.prototype.includes.

const myData = ["14782", "12434", "3143"];

const mySearch = "14728";      // Not in the array
const myOtherSearch = "12434"; // In the array

console.log(myData.includes(mySearch));
console.log(myData.includes(myOtherSearch));```

Title: Why this includes() case return false?

Body:
var product_id = "14728";
console.log(product_id.includes("14782,12434,3143")); // this return false

Example.

I just want to check that my product_id is within those other articles ids string


问:
Node MODULE_NOT_FOUND
I just upgraded to node version 9.0.0 and am now getting this error in the command line when trying to use npm install

```<code>npm ERR! code MODULE_NOT_FOUND
npm ERR! Cannot find module 'internal/util/types'
</code>```

I'm using:

OSX 10.10.5

Node version 9.0.0

NPM version 5.5.1

Extra information: I am also trying to do this with a Laravel 5.5 project. This is how I update my version of node: How do I update Node.js?

答: If you are using libraries make sure to install everything with npm or yarn before starting. And in cases of you files if you are going to use them make sure to do the export.module thing everytime.</p>

ContentLicense: CC BY-SA 3.0

Title: Node MODULE_NOT_FOUND

Body:
I just upgraded to node version 9.0.0 and am now getting this error in the command line when trying to use npm install

npm ERR! code MODULE_NOT_FOUND
npm ERR! Cannot find module 'internal/util/types'

I'm using:

OSX 10.10.5

Node version 9.0.0

NPM version 5.5.1

Extra information: I am also trying to do this with a Laravel 5.5 project. This is how I update my version of node: How do I update Node.js?


问:
React 16 setState callback causes Maximum update depth exceeded
In my app I used React setState's callback for setting new state after render.
When I upgraded React to 16.4.2, Maximum update depth exceeded appeared because of the setState.

React 16 CHANGELOG:

setState callback (second argument) now fires immediately after
  componentDidMount / componentDidUpdate instead of after all components
  have rendered.

Use:

```<code>someHandler() {
    this.setState({prop1: true}, () => {
        this.setState({prop1: false});
    });
},
</code>```

How can I replace that use in a valid React 16 api, for setting state after render called?

答:
This occurs due to an infinite loop. you must be calling someHandler from somewhere inside render. Somehandler setstates which triggers a re-render and while re-rendering somehandler is called again. Thus, infinite loop.
Try calling somehandler from somewhere inside the Lifecycle hooks like ComponentDidMount (or in case of functional/stateless components - useEffect(()=>{body},[]))

Body:
In my app I used React setState's callback for setting new state after render.
When I upgraded React to 16.4.2, Maximum update depth exceeded appeared because of the setState.

React 16 CHANGELOG:

setState callback (second argument) now fires immediately after
  componentDidMount / componentDidUpdate instead of after all components
  have rendered.

Use:

someHandler() {
    this.setState({prop1: true}, () => {
        this.setState({prop1: false});
    });
},

How can I replace that use in a valid React 16 api, for setting state after render called?


问:
Remember the time left when browser refresh using jquery
This code below pops up with an interval of 5 seconds, 10 seconds & 15 seconds and inside this box is a contact form 7 form

So when I refresh the page it goes back to 5 seconds all the time.

```<code>var iteration = 0;
var times = [5,10,15]
var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
        Cookies.set('popup_box', time);
    }, time)

}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < 3) {
      showPopUp(times[iteration])
    }
});
</code>```

How can I make it so that when I refresh the page will will remember what it has left

and also make it all stop when contact form 7 is successfully submitted (popup will not show anymore maybe until browser exit)

Thank in advance for the help

答: Nice try! but your code still have problems, i think var times is not realiza</p>

Body:
This code below pops up with an interval of 5 seconds, 10 seconds & 15 seconds and inside this box is a contact form 7 form

So when I refresh the page it goes back to 5 seconds all the time.

var iteration = 0;
var times = [5,10,15]
var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
        Cookies.set('popup_box', time);
    }, time)

}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < 3) {
      showPopUp(times[iteration])
    }
});

How can I make it so that when I refresh the page will will remember what it has left

and also make it all stop when contact form 7 is successfully submitted (popup will not show anymore maybe until browser exit)

Thank in advance for the help


问:
Pycurl is not compiled against Openssl, when I trie to use wfuzz how to solve this problem?
I was testing the tool wfuzz on kali linux, and I'm getting this warning.

Warning: Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.

I'm trying to brute force the password in the DVWA  'Vulnerable Web Application'.
I was following this steps: https://ogma-sec.fr/dvwa-brute-force-command-execution-solutions-protections/
unfortunately it didn't work.

So my question is: it is because of the warning?

if Yes how can I compile pycURL against openssl?

by the way: I did flow this steps in the link bellow => https://github.com/xmendez/wfuzz/blob/master/docs/user/installation.rst
and I'm stuck in the  step 10.

答:
```<code>
mkdir ~/python-pycurl-openssl
cd ~/python-pycurl-openssl
sudo apt-get source python-pycurl
sudo apt-get build-dep python-pycurl
sudo apt-get install libcurl4-openssl-dev
sudo dpkg-source -x pycurl_7.43.0.1-0.2.dsc
cd pycurl-7.43.0.1/debian/control
sudo sed -i ‘s/libcurl4-gnutls-dev/libcurl4-openssl-dev/g’ control
sudo dpkg-buildpackage -rfakeroot -b
sudo dpkg -i python-pycurl_7.43.0.1-0.2_amd64.deb
```</code></p>


问:
Evaluate string expression and convert to bool?
I want to evaluate the string expression and convert the result to bool.

For example

string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;

the above expression has to evaluate and return true.

Can anyone suggest how to evaluate the expression and return bool value?

答:
You can use the NCalc package. The code below produces "False"

```<code>using System;
using NCalc;

public class Program
{
    public static void Main()
    {
        Expression e = new Expression("!((71 > 70) && (80 > 71)) || 72 < 71");
        bool v = (bool)e.Evaluate();
        Console.WriteLine(v.ToString());
    }
}
</code>```

.Net Fiddle: https://dotnetfiddle.net/02c5ww

Body:
You can use the NCalc package. The code below produces "False"

using System;
using NCalc;

public class Program
{
    public static void Main()
    {
        Expression e = new Expression("!((71 > 70) && (80 > 71)) || 72 < 71");
        bool v = (bool)e.Evaluate();
        Console.WriteLine(v.ToString());
    }
}

.Net Fiddle: https://dotnetfiddle.net/02c5ww


问:
How to get this into Kotlin?
I am a newbie at Kotlin and have been praticing Android for months now . I am stuck at converting this code from Java to Kotlin . The declaration syntax of args is out of my understanding.How can I convert below piece of code to Kotlin?

```<code> public static boolean validate(EditText... editTexts){
        EditText nameTxt = editTexts[0];
        EditText descriptionTxt = editTexts[1];
        EditText galaxyTxt = editTexts[2];
        return true;
}
</code>```

Thank-You in advance

答:
instead of

```<code>validate(EditText... editTexts)
</code>```

you must use this in kotlin (vararg)

```<code>validate(vararg editTexts: EditText)
</code>```

So full code in kotlin is

```<code>   fun validate(vararg editTexts: EditText): Boolean {
        val nameTxt = editTexts[0]
        val descriptionTxt = editTexts[1]
        val galaxyTxt = editTexts[2]
        return true
    }
</code>```

Source variable-number-of-arguments-varargs

Title: How to get this into Kotlin?

Body:
I am a newbie at Kotlin and have been praticing Android for months now . I am stuck at converting this code from Java to Kotlin . The declaration syntax of args is out of my understanding.How can I convert below piece of code to Kotlin?

 public static boolean validate(EditText... editTexts){
        EditText nameTxt = editTexts[0];
        EditText descriptionTxt = editTexts[1];
        EditText galaxyTxt = editTexts[2];
        return true;
}

Thank-You in advance

Body:
instead of

validate(EditText... editTexts)

you must use this in kotlin (vararg)

validate(vararg editTexts: EditText)

So full code in kotlin is

   fun validate(vararg editTexts: EditText): Boolean {
        val nameTxt = editTexts[0]
        val descriptionTxt = editTexts[1]
        val galaxyTxt = editTexts[2]
        return true
    }

Source variable-number-of-arguments-varargs


问:
pyspark: Converting string to struct
I have data as follows -

```<code>{
    "Id": "01d3050e",
    "Properties": "{\"choices\":null,\"object\":\"demo\",\"database\":\"pg\",\"timestamp\":\"1581534117303\"}",
    "LastUpdated": 1581530000000,
    "LastUpdatedBy": "System"
}
</code>```

Using aws glue, I want to relationalize the "Properties" column  but since the datatype is string it can't be done. Converting it to struct, might do it based on reading this blog -

https://aws.amazon.com/blogs/big-data/simplify-querying-nested-json-with-the-aws-glue-relationalize-transform/

```<code>>>> df.show
<bound method DataFrame.show of DataFrame[Id: string, LastUpdated: bigint, LastUpdatedBy: string, Properties: string]>
>>> df.show()
+--------+-------------+-------------+--------------------+
|      Id|  LastUpdated|LastUpdatedBy|          Properties|
+--------+-------------+-------------+--------------------+
|01d3050e|1581530000000|       System|{"choices":null,"...|
+--------+-------------+-------------+--------------------+

</code>```

How can I un-nested the "properties" column to break it into "choices", "object", "database" and "timestamp" columns, using relationalize transformer or any UDF in pyspark.

Title: pyspark: Converting string to struct

Body:
I have data as follows -

{
    "Id": "01d3050e",
    "Properties": "{\"choices\":null,\"object\":\"demo\",\"database\":\"pg\",\"timestamp\":\"1581534117303\"}",
    "LastUpdated": 1581530000000,
    "LastUpdatedBy": "System"
}

Using aws glue, I want to relationalize the "Properties" column  but since the datatype is string it can't be done. Converting it to struct, might do it based on reading this blog -

https://aws.amazon.com/blogs/big-data/simplify-querying-nested-json-with-the-aws-glue-relationalize-transform/

>>> df.show
<bound method DataFrame.show of DataFrame[Id: string, LastUpdated: bigint, LastUpdatedBy: string, Properties: string]>
>>> df.show()
+--------+-------------+-------------+--------------------+
|      Id|  LastUpdated|LastUpdatedBy|          Properties|
+--------+-------------+-------------+--------------------+
|01d3050e|1581530000000|       System|{"choices":null,"...|
+--------+-------------+-------------+--------------------+

How can I un-nested the "properties" column to break it into "choices", "object", "database" and "timestamp" columns, using relationalize transformer or any UDF in pyspark.

Body:
Creating your dataframe:

from pyspark.sql import functions as F
list=[["01d3050e","{\"choices\":null,\"object\":\"demo\",\"database\":\"pg\",\"timestamp\":\"1581534117303\"}",1581530000000,"System"]]
df=spark.createDataFrame(list, ['Id','Properties','LastUpdated','LastUpdatedBy'])
df.show(truncate=False)

+--------+----------------------------------------------------------------------------+-------------+-------------+
|Id      |Properties                                                                  |LastUpdated  |LastUpdatedBy|
+--------+----------------------------------------------------------------------------+-------------+-------------+
|01d3050e|{"choices":null,"object":"demo","database":"pg","timestamp":"1581534117303"}|1581530000000|System       |
+--------+----------------------------------------------------------------------------+-------------+-------------+

Use inbuilt regex, split, and element_at:

No need to use UDF, inbuilt functions are adequate and very much optimized for big data tasks.

df.withColumn("Properties", F.split(F.regexp_replace(F.regexp_replace((F.regexp_replace("Properties",'\{|}',"")),'\:',','),'\"|"',"").cast("string"),','))\
.withColumn("choices", F.element_at("Properties",2))\
.withColumn("object", F.element_at("Properties",4))\
.withColumn("database",F.element_at("Properties",6))\
.withColumn("timestamp",F.element_at("Properties",8).cast('long')).drop("Properties").show()

+--------+-------------+-------------+-------+------+--------+-------------+
|      Id|  LastUpdated|LastUpdatedBy|choices|object|database|    timestamp|
+--------+-------------+-------------+-------+------+--------+-------------+
|01d3050e|1581530000000|       System|   null|  demo|      pg|1581534117303|
+--------+-------------+-------------+-------+------+--------+-------------+

root
 |-- Id: string (nullable = true)
 |-- LastUpdated: long (nullable = true)
 |-- LastUpdatedBy: string (nullable = true)
 |-- choices: string (nullable = true)
 |-- object: string (nullable = true)
 |-- database: string (nullable = true)
 |-- timestamp: long (nullable = true)


问:
Firebase Cloud Storage Function Trigger -- Determine User's ID Token for Newly Created File
[SUMMARY]

For a newly uploaded file to Firebase Cloud Storage I want to determine who uploaded the file (the User's ID token) from within a triggered Firebase Function.

[DETAILS]

I'm allowing the Firebase authenticated mobile user to upload a file to Cloud storage.  I've attached a Firebase Cloud Storage trigger via Firebase Function with onFinalize.  When a new file is added to Cloud Storage it triggers the function.

From within the function is it possible to determine the mobile user's ID token so that i may use Firebase Cloud Messaging to send a message back?  Or do i have to upload the file as before then after upload is complete make a reference to the uploaded file then apply metadata to it (eg. add the User's ID Token which belongs to the mobile user)?  I would then have to have a Firebase Function trigger on metadata changes -- when a change occurs i can then read out the ID token for whom the newly uploaded file belongs to.

Mobile: Java Android

Firebase Cloud Functions: Node.js

答:
The most reliable way to do this is:

Associate the device token with the user's UID before the upload.  There might be multiple active device tokens per user depending on how many devices the user is using. This is normal.

When the file is uplaoded, also attach metadata to the file with the user's UID.  You can ensure this is correct using security rules.

In the triggered function, match the secured UID with the previously saved tokens, and send each token the message about the upload.


问:
My form always tells users there's a problem
I'm a total PHP idiot so I'm re-using some PHP code that works in another site of mine to get an email when visitors use an HTML form. Although all the HTML and PHP code looks properly matched to me, submitting a form always triggers the errorurl.
I suspect the recaptcha could be the problem, as the recaptcha dashboard tells me there's been no usage. Can someone help this journalist-turned-unwilling-developer? Thank you in advance.

Claudio

Here's the HTML form:

```<code><form action="contactus.php" method="post" name="contact_form" target="_self" >
        <div class="row">
            <div class="col-sm"><label for="yourname">Your first name<strong>*</strong></label>
            <input autofocus required type="text" id="yourname" class="form-control" accesskey="n" tabindex="1" placeholder="please enter your given name"></div>

            <div class="col-sm"><label for="yoursurname">Your family name<strong>*</strong></label>
            <input autofocus required type="text" id="yoursurname" class="form-control" accesskey="s" tabindex="2" placeholder="please enter your family name"></div>

            <div class="col-sm"><label for="yourmobile">Your mobile<strong>*</strong></label><input required maxlength="10" type="tel" id="yourmobile" class="form-control" accesskey="m" tabindex="3" placeholder="enter your mobile, no spaces or prefix"></div>
          </div>
      <div class="row">
            <div class="col-sm"><label for="youremail">Your email<strong>*</strong></label>
            <input required type="email" id="youremail" class="form-control" accesskey="e" tabindex="4" placeholder="please enter your email"></div>
            <div class="col-sm">
            <label for="yourcompany">Your Company</label>
          <input type="text" class="form-control" id="yourcompany" accesskey="c" tabindex="5" placeholder="Your Company">
          <small id="emailHelp1" class="form-text text-muted">We'll never share your details with anyone else.</small> </div></div>
        <div class="form-group">
          <label for="healthfund">Your comments<strong>*</strong></label>
          <textarea class="form-control" id="healthfund" rows="5" tabindex="6" placeholder="Write away, no tight limits!"></textarea>
        </div>
          <div class="form-group"><label for>Please reassure us that you are human... </label><br>
<div class="g-recaptcha" id="recaptcha" data-sitekey="6LfKAcwUAAAAAAzIKAGlduOulkTw5PU7cuFzdUst"></div>
            <input class="btn btn-success btn-lg float-right ml-4" name="submit" type="submit" id="submit" tabindex="7" value="OK" /><input class="btn bg-danger btn-lg float-right" name="cancel" type="button" tabindex="8" value="Cancel" onClick="javascript:history.go(-1)"/></div>

      </form>
</code>```

and this is the PHP file:

```<code><?php
$mailto = 'claudioparoli@gmail.com' ;
$subject = "contact" ;
$formurl = "contactus.html" ;
$errorurl = "contacterror.html" ;
$thankyouurl = "contactthankyou.html" ;

$yourname_is_required = 1;
$yoursurname_is_required = 1;
$yourmobile_is_required = 1;
$youremail_is_required = 1;
$yourcompany_is_required = 0;
$comments_is_required = 1;
$uself = 1;
$use_envsender = 0;
$use_sendmailfrom = 0;
$use_webmaster_email_for_from = 0;
$use_utf8 = 1;
$my_recaptcha_private_key = '' ;

// -------------------- END OF CONFIGURABLE SECTION ---------------

$headersep = (!isset( $uself ) || ($uself == 0)) ? "\r\n" : "\n" ;
$content_type = (!isset( $use_utf8 ) || ($use_utf8 == 0)) ? 'Content-Type: text/plain; charset="iso-8859-1"' : 'Content-Type: text/plain; charset="utf-8"' ;
if (!isset( $use_envsender )) { $use_envsender = 0 ; }
if (isset( $use_sendmailfrom ) && $use_sendmailfrom) {
    ini_set( 'sendmail_from', $mailto );
}
$envsender = "-f$mailto" ;
$yourname = (isset($_POST['yourname']))? $_POST['yourname'] : $_POST['yourname'] ;
$yoursurname = $_POST['yoursurname'];
$yourmobile = $_POST['yourmobile'] ;
$youremail = $_POST['youremail'] ;
$yourcompany = $_POST['yourcompany'] ;
$comments = $_POST['comments'];
$http_referrer = getenv( "HTTP_REFERER" );

if (!isset($_POST['youremail'])) {
    header( "Location: $formurl" );
    exit ;
}
if (($youremail_is_required && (empty($youremail) || !preg_match('/@/', $youremail))) || ($yourname_is_required && empty($yourname)) || ($yoursurname_is_required && empty($yoursurname)) || ($yourmobile_is_required && empty($yourmobile)) || ($yourcompany_is_required && empty($yourcompany)) || ($comments_is_required && empty($comments))) {
header( "Location: $errorurl" );
exit ;
}
if ( preg_match( "/[\r\n]/", $yourname ) || preg_match( "/[\r\n]/", $youremail ) ) {
header( "Location: $errorurl" );
exit ;
}

if (strlen( $my_recaptcha_private_key )) {
    require_once( '../../edge/recaptchalib.php' );
   $resp = recaptcha_check_answer ( $my_recaptcha_private_key, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] );
    if (!$resp->is_valid) {
        header( "Location: $errorurl" );
        exit ;
    }
}
if (empty($youremail)) {
    $youremail = $mailto ;
}
$fromemail = (!isset( $use_webmaster_email_for_from ) || ($use_webmaster_email_for_from == 0)) ? $email : $mailto ;

if (function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc()) {
    $details = stripslashes( $details );
}

$messageproper =
    "This message was sent from:\n" .
    "$http_referrer\n" .

"-------------------THE SENDER-----------------------\n\n" .

    "name of sender: $yourname\n" .
    "surname of sender: $yoursurname\n" .
    "mobile of sender: $yourmobile\n" .
    "email of sender: $youremail\n" .
    "company of sender: $yourcompany\n" .
    "comments by sender: $comments\n\n" .

    "\n\n------------------------------------------\n" ;

$headers =
    "From: \"$yourname\" <$youremail>" . $headersep . "Reply-To: \"$yourname\" <$youremail>" . $headersep . "X-Mailer: chfeedback.php 2.15.0" .
    $headersep . 'MIME-Version: 1.0' . $headersep . $content_type ;

if ($use_envsender) {
    mail($mailto, $subject, $messageproper, $headers, $envsender );
}
else {
    mail($mailto, $subject, $messageproper, $headers );
}
header( "Location: $thankyouurl" );

?>
</code>```

答:
I would use a debugger and step through the code to see which of your validations is redirecting to the error page.
If you don't have a debugger installed, then use error_log before each redirect with some text to tell you which validation was hit. Look in the log for your messages.

Something like

```<code>if (($youremail_is_required && (empty($youremail) || !preg_match('/@/', $youremail))) || ($yourname_is_required && empty($yourname)) || ($yoursurname_is_required && empty($yoursurname)) || ($yourmobile_is_required && empty($yourmobile)) || ($yourcompany_is_required && empty($yourcompany)) || ($comments_is_required && empty($comments))) {
error_log("email is required. youremail_is_required: $youremail_is_required youremail: $youremail your_username_is_required: $your_username_is_required yourusername: $yourusername");
header( "Location: $errorurl" );
exit ;
}
</code>```

Body:
I'm a total PHP idiot so I'm re-using some PHP code that works in another site of mine to get an email when visitors use an HTML form. Although all the HTML and PHP code looks properly matched to me, submitting a form always triggers the errorurl.
I suspect the recaptcha could be the problem, as the recaptcha dashboard tells me there's been no usage. Can someone help this journalist-turned-unwilling-developer? Thank you in advance.

Claudio

Here's the HTML form:

<form action="contactus.php" method="post" name="contact_form" target="_self" >

Your first name*
            <input autofocus required type="text" id="yourname" class="form-control" accesskey="n" tabindex="1" placeholder="please enter your given name">

Your family name*
            <input autofocus required type="text" id="yoursurname" class="form-control" accesskey="s" tabindex="2" placeholder="please enter your family name">

Your mobile*<input required maxlength="10" type="tel" id="yourmobile" class="form-control" accesskey="m" tabindex="3" placeholder="enter your mobile, no spaces or prefix">

Your email*
            <input required type="email" id="youremail" class="form-control" accesskey="e" tabindex="4" placeholder="please enter your email">

            Your Company
          <input type="text" class="form-control" id="yourcompany" accesskey="c" tabindex="5" placeholder="Your Company">
          We'll never share your details with anyone else.

          Your comments*
          <textarea class="form-control" id="healthfund" rows="5" tabindex="6" placeholder="Write away, no tight limits!"></textarea>

Please reassure us that you are human...

            <input class="btn btn-success btn-lg float-right ml-4" name="submit" type="submit" id="submit" tabindex="7" value="OK" /><input class="btn bg-danger btn-lg float-right" name="cancel" type="button" tabindex="8" value="Cancel" onClick="javascript:history.go(-1)"/>

      </form>

and this is the PHP file:

<?php
$mailto = 'claudioparoli@gmail.com' ;
$subject = "contact" ;
$formurl = "contactus.html" ;
$errorurl = "contacterror.html" ;
$thankyouurl = "contactthankyou.html" ;

$yourname_is_required = 1;
$yoursurname_is_required = 1;
$yourmobile_is_required = 1;
$youremail_is_required = 1;
$yourcompany_is_required = 0;
$comments_is_required = 1;
$uself = 1;
$use_envsender = 0;
$use_sendmailfrom = 0;
$use_webmaster_email_for_from = 0;
$use_utf8 = 1;
$my_recaptcha_private_key = '' ;

// -------------------- END OF CONFIGURABLE SECTION ---------------

$headersep = (!isset( $uself ) || ($uself == 0)) ? "\r\n" : "\n" ;
$content_type = (!isset( $use_utf8 ) || ($use_utf8 == 0)) ? 'Content-Type: text/plain; charset="iso-8859-1"' : 'Content-Type: text/plain; charset="utf-8"' ;
if (!isset( $use_envsender )) { $use_envsender = 0 ; }
if (isset( $use_sendmailfrom ) && $use_sendmailfrom) {
    ini_set( 'sendmail_from', $mailto );
}
$envsender = "-f$mailto" ;
$yourname = (isset($_POST['yourname']))? $_POST['yourname'] : $_POST['yourname'] ;
$yoursurname = $_POST['yoursurname'];
$yourmobile = $_POST['yourmobile'] ;
$youremail = $_POST['youremail'] ;
$yourcompany = $_POST['yourcompany'] ;
$comments = $_POST['comments'];
$http_referrer = getenv( "HTTP_REFERER" );

if (!isset($_POST['youremail'])) {
    header( "Location: $formurl" );
    exit ;
}
if (($youremail_is_required && (empty($youremail) || !preg_match('/@/', $youremail))) || ($yourname_is_required && empty($yourname)) || ($yoursurname_is_required && empty($yoursurname)) || ($yourmobile_is_required && empty($yourmobile)) || ($yourcompany_is_required && empty($yourcompany)) || ($comments_is_required && empty($comments))) {
header( "Location: $errorurl" );
exit ;
}
if ( preg_match( "/[\r\n]/", $yourname ) || preg_match( "/[\r\n]/", $youremail ) ) {
header( "Location: $errorurl" );
exit ;
}

if (strlen( $my_recaptcha_private_key )) {
    require_once( '../../edge/recaptchalib.php' );
   $resp = recaptcha_check_answer ( $my_recaptcha_private_key, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] );
    if (!$resp->is_valid) {
        header( "Location: $errorurl" );
        exit ;
    }
}
if (empty($youremail)) {
    $youremail = $mailto ;
}
$fromemail = (!isset( $use_webmaster_email_for_from ) || ($use_webmaster_email_for_from == 0)) ? $email : $mailto ;

if (function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc()) {
    $details = stripslashes( $details );
}

$messageproper =
    "This message was sent from:\n" .
    "$http_referrer\n" .

"-------------------THE SENDER-----------------------\n\n" .

    "name of sender: $yourname\n" .
    "surname of sender: $yoursurname\n" .
    "mobile of sender: $yourmobile\n" .
    "email of sender: $youremail\n" .
    "company of sender: $yourcompany\n" .
    "comments by sender: $comments\n\n" .

    "\n\n------------------------------------------\n" ;

$headers =
    "From: \"$yourname\" <$youremail>" . $headersep . "Reply-To: \"$yourname\" <$youremail>" . $headersep . "X-Mailer: chfeedback.php 2.15.0" .
    $headersep . 'MIME-Version: 1.0' . $headersep . $content_type ;

if ($use_envsender) {
    mail($mailto, $subject, $messageproper, $headers, $envsender );
}
else {
    mail($mailto, $subject, $messageproper, $headers );
}
header( "Location: $thankyouurl" );

?>

Body:
I would use a debugger and step through the code to see which of your validations is redirecting to the error page.
If you don't have a debugger installed, then use error_log before each redirect with some text to tell you which validation was hit. Look in the log for your messages.

Something like

if (($youremail_is_required && (empty($youremail) || !preg_match('/@/', $youremail))) || ($yourname_is_required && empty($yourname)) || ($yoursurname_is_required && empty($yoursurname)) || ($yourmobile_is_required && empty($yourmobile)) || ($yourcompany_is_required && empty($yourcompany)) || ($comments_is_required && empty($comments))) {
error_log("email is required. youremail_is_required: $youremail_is_required youremail: $youremail your_username_is_required: $your_username_is_required yourusername: $yourusername");
header( "Location: $errorurl" );
exit ;
}


问:
EntityException: The underlying provider failed on Open. Can one server closing a db connection, make another server fail on opening?
I am experiencing database connection errors with an ASP.NET application written in VB, running on three IIS servers. The underlying database is MS Access, which is on a shared network device. It uses Entity Framework, code first implementation and JetEntityFrameworkProvider.

The application is running stable. But, approximately 1 out of 1000 attempts to open the database connection fails with either one of the following two errors:

```<code>06:33:50   DbContext  "Failed to open connection at 2/12/2020 6:33:50 AM +00:00 with error:
Cannot open database ''.  It may not be a database that your application recognizes, or the file may be corrupt.
</code>```

Or

```<code>14:04:39   DbContext  "Failed to open connection at 2/13/2020 2:04:39 PM +00:00 with error:
Could not use ''; file already in use.
</code>```

One second later, with refreshing (F5), the error is gone and it works again.

Details about the environment and used code.

Connection String

```<code><add name="DbContext" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=x:\thedatabase.mdb;Jet OLEDB:Database Password=xx;OLE DB Services=-4;" providerName="JetEntityFrameworkProvider" />
</code>```

DbContext management

The application uses public property to access DbContext. DbContext is kept in the HttpContext.Current.Items collection for the lifetime of the request, and is disposed at it’s end.

```<code>Public Shared ReadOnly Property Instance() As DbContext
    Get
        SyncLock obj
            If Not HttpContext.Current.Items.Contains("DbContext") Then
                HttpContext.Current.Items.Item("DbContext") = New DbContext()
            End If

            Return HttpContext.Current.Items.Item("DbContext")
        End SyncLock
    End Get
End Property
</code>```

BasePage inits and disposes the DbContext.

```<code>Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    DbContext = Data.DbContext.Instance
    ...
End Sub

Protected Overrides Sub OnUnload(e As EventArgs)
    MyBase.OnUnload(e)
    If DbContext IsNot Nothing Then DbContext.Dispose()
End Sub
</code>```

What I have tried

Many of the questions on SO which address above error messages, deal with generally not being able to establish a connection to the database – they can’t connect at all. That’s  different with this case. Connection works 99,99% of the time.

Besides that, I have checked:

Permissions: Full access is granted for share where .mdb (database) and .ldb (locking file) resides.

Network connection: there are no connection issues to the shared device; it’s a Gigabit LAN connection

Maximum number of 255 concurrent connections is not reached

Maximum size of database not exceeded (db has only 5 MB)

Changed the compile option from “Any CPU” to “x86” as suggested in this MS Dev-Net post

Quote: I was getting the same "Cannot open database ''" error, but completely randomly (it seemed). The MDB file was less than 1Mb, so no issue with a 2Gb limit as mentioned a lot with this error.
  It worked 100% on 32 bit versions of windows, but I discovered that the issues were on 64 bit installations.
  The app was being compiled as "Any CPU".
  I changed the compile option from "Any CPU" to "x86" and the problem has disappeared.

Nothing helped so far.

To gather more information, I attached an Nlog logger to the DbContext which writes all database actions and queries to a log file.

```<code>Shared Log As Logger = LogManager.GetLogger("DbContext")
Me.Database.Log = Sub(s) Log.Debug(s)
</code>```

Investigating the logs I figured out that when one of the above errors occured on one server, another one of the servers (3 in total) has closed the db connection at exactly the same time.
Here two examples which correspond to the above errors:

```<code>06:33:50   DbContext  "Closed connection at 2/12/2020 6:33:50 AM +00:00
14:04:39   DbContext  "Closed connection at 2/13/2020 2:04:39 PM +00:00
</code>```

Assumption

When all connections of a DbContext have been closed, the according record is removed from the .ldb lock file. When a connection to the db is being opened, a record will be added to the lock file. When these two events occur at the exact same time, from two different servers, there is a write conflict to the .ldb lock file, which results in on of the errors from above.

Question

Can anyone confirm or prove this wrong? Has anyone experienced this behaviour? Maybe I am missing something else. I’d appreciate your input and experience on this.

If my assumption is true, a solution could be to use a helper class for accessing db, which catches and handles this error, waiting for a minimal time period and trying again.

But this feels kind of wrong. So I am also open to suggestions for a “proper” solution.

EDIT: The "proper" solution would be using a DBMS Server (as stated in the comments below). I'm aware of this. For now, I have to deal with this design mistake without being responsible for it. Also, I can't change it in the short run.

答:
I write this as an aswer because of space but this is not really an answer.

It's for sure an OleDb provider issue.

I think that is a sharing issue.
You could do some tries:

use a newer OleDb provider instead of Microsoft.Jet.OLEDB.4.0. (if you have try 64 bits you could already have try another provider because Jet.OLEDB.4.0 is 32 bits only)

Implement a retry mechanism on the new DbContext()

Reading your tests this is probaly not your case. I THINK that Dispose does not always work properly on Jet.OLEDB.4.0 connections. I noted it on tests and I solved it using a different testing engine. Before giving up I used this piece of code

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();

GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

As you can understand reading this code, they are tries and the latest solution was changing the testing engine.

If your app is not too busy you could try to lock the db using a different mechanism (for example using a lock file). This is not really different from new DbContext() retries.

In late '90s I remember I had an issue related to disk sharing OS (I were using Novel Netware). Actually I have not experience in using mdb files on a network share. You could try to move the mdb on a folder shared with Windows

Actually I use Access databases only for tests. If you really need to use a single file database you could try other solutions: SQL Lite (you need a library, also this written by me, to apply code first https://www.nuget.org/packages/System.Data.SQLite.EF6.Migrations/ ) or SQL Server CE

Use a DBMS Server. This is for sure the best solution. As the writer of JetEntityFrameworkProvider I think that single file databases are great for single user apps (for this apps I suggest SQL Lite), for tests (I think that for tests JetEntityFrameworkProvider is great), for transfering data or, also, for readonly applications. In other cases use a DBMS Server. As you know, with EF, you can change from JetEntityFrameworkProvider to SQL Server or to MySql without effort.

Body:
I am experiencing database connection errors with an ASP.NET application written in VB, running on three IIS servers. The underlying database is MS Access, which is on a shared network device. It uses Entity Framework, code first implementation and JetEntityFrameworkProvider.

The application is running stable. But, approximately 1 out of 1000 attempts to open the database connection fails with either one of the following two errors:

06:33:50   DbContext  "Failed to open connection at 2/12/2020 6:33:50 AM +00:00 with error:
Cannot open database ''.  It may not be a database that your application recognizes, or the file may be corrupt.

Or

14:04:39   DbContext  "Failed to open connection at 2/13/2020 2:04:39 PM +00:00 with error:
Could not use ''; file already in use.

One second later, with refreshing (F5), the error is gone and it works again.

Details about the environment and used code.

Connection String

<add name="DbContext" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=x:\thedatabase.mdb;Jet OLEDB:Database Password=xx;OLE DB Services=-4;" providerName="JetEntityFrameworkProvider" />

DbContext management

The application uses public property to access DbContext. DbContext is kept in the HttpContext.Current.Items collection for the lifetime of the request, and is disposed at it’s end.

Public Shared ReadOnly Property Instance() As DbContext
    Get
        SyncLock obj
            If Not HttpContext.Current.Items.Contains("DbContext") Then
                HttpContext.Current.Items.Item("DbContext") = New DbContext()
            End If

            Return HttpContext.Current.Items.Item("DbContext")
        End SyncLock
    End Get
End Property

BasePage inits and disposes the DbContext.

Protected Overrides Sub OnInit(e As EventArgs)
    MyBase.OnInit(e)
    DbContext = Data.DbContext.Instance
    ...
End Sub

Protected Overrides Sub OnUnload(e As EventArgs)
    MyBase.OnUnload(e)
    If DbContext IsNot Nothing Then DbContext.Dispose()
End Sub

What I have tried

Many of the questions on SO which address above error messages, deal with generally not being able to establish a connection to the database – they can’t connect at all. That’s  different with this case. Connection works 99,99% of the time.

Besides that, I have checked:

Permissions: Full access is granted for share where .mdb (database) and .ldb (locking file) resides.

Network connection: there are no connection issues to the shared device; it’s a Gigabit LAN connection

Maximum number of 255 concurrent connections is not reached

Maximum size of database not exceeded (db has only 5 MB)

Changed the compile option from “Any CPU” to “x86” as suggested in this MS Dev-Net post

Quote: I was getting the same "Cannot open database ''" error, but completely randomly (it seemed). The MDB file was less than 1Mb, so no issue with a 2Gb limit as mentioned a lot with this error.
  It worked 100% on 32 bit versions of windows, but I discovered that the issues were on 64 bit installations.
  The app was being compiled as "Any CPU".
  I changed the compile option from "Any CPU" to "x86" and the problem has disappeared.

Nothing helped so far.

To gather more information, I attached an Nlog logger to the DbContext which writes all database actions and queries to a log file.

Shared Log As Logger = LogManager.GetLogger("DbContext")
Me.Database.Log = Sub(s) Log.Debug(s)

Investigating the logs I figured out that when one of the above errors occured on one server, another one of the servers (3 in total) has closed the db connection at exactly the same time.
Here two examples which correspond to the above errors:

06:33:50   DbContext  "Closed connection at 2/12/2020 6:33:50 AM +00:00
14:04:39   DbContext  "Closed connection at 2/13/2020 2:04:39 PM +00:00

Assumption

When all connections of a DbContext have been closed, the according record is removed from the .ldb lock file. When a connection to the db is being opened, a record will be added to the lock file. When these two events occur at the exact same time, from two different servers, there is a write conflict to the .ldb lock file, which results in on of the errors from above.

Question

Can anyone confirm or prove this wrong? Has anyone experienced this behaviour? Maybe I am missing something else. I’d appreciate your input and experience on this.

If my assumption is true, a solution could be to use a helper class for accessing db, which catches and handles this error, waiting for a minimal time period and trying again.

But this feels kind of wrong. So I am also open to suggestions for a “proper” solution.

EDIT: The "proper" solution would be using a DBMS Server (as stated in the comments below). I'm aware of this. For now, I have to deal with this design mistake without being responsible for it. Also, I can't change it in the short run.


问:
Flask webservice https call results in ssl error
I have Flask based webservice providing REST interfaces.

We have written webservice class inherited from flask.Flask and can't provide entire the code here but webservice app call looks like,
app.run(host=host, port=port, ssl_context='adhoc)

With this when I try to run GET request then I am getting SSL error,

```<code>  File "/opt/debesys/build/x86-64/debug/python/tt/pyrate/test/test_juno_sim.py", line 1077, in test_main_page
    resp = requests.get(self.url, headers=self.headers, verify=False)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/adapters.py", line 382, in send
    raise SSLError(e, request=request)
SSLError: [Errno 1] _ssl.c:507: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code>```

I have also tried starting app like,
app.run(host=host, port=port, ssl_context=('cert.pem', 'key.pem'))
Also used urllib2 module for get request instead of requests module.

But getting same error. If I try starting app without ssl_context and use http then getting response successfully.

Here I am using headers = {'Content-Type': 'application/json'} and url = "https://127.0.0.1:{}".format(port)

```<code>[shrishinde@localhost debesys]$ wget https://127.0.0.1:47855/
--2020-02-19 13:03:25--  https://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
[shrishinde@localhost debesys]$ wget http://127.0.0.1:47855/
--2020-02-19 13:03:28--  http://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31 [text/html]
Saving to: “index.html”

100%[=====================================================================================================================================================================>] 31          --.-K/s   in 0s

2020-02-19 13:03:28 (6.25 MB/s) - “index.html” saved [31/31]

[shrishinde@localhost debesys]$
</code>```

Update

Found solution:
After inheriting Flask, we have overridden Flask run method and in that WSGIServer is used so instead of ssl_context I should use ssl_args.

With hope that above steps will help user diagnose similar issues so keeping the question.

答:
I might know what's happening, even though you should provide part of the code alongside the stack trace to better understanding of the problem.

SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

This error is produced when OpenSSL receives a wrong parameter in the Handshake from the server. It might happen if the server is answering with plain HTTP (withouth TLS). It might happen for other various reasons, your client might not understand the TLS version (library only supports SSL) or something like that.

Try to run the request with wgetor Postman to the url (http://your.url:422). If you get a response, SSL is not enabled.

Fixed

Ok i've managed to replicate your problem, you aren't running the server in ssl mode. Run this.

pip install pyopenssl

python -m flask run --cert=adhoc

And ensure that the message is running ont https://127.0.0.1:5000/ and then quit it and run it with

python -m flask run --cert=adhoc -p [your port]

To run int in your desired port

Body:
I have Flask based webservice providing REST interfaces.

We have written webservice class inherited from flask.Flask and can't provide entire the code here but webservice app call looks like,
app.run(host=host, port=port, ssl_context='adhoc)

With this when I try to run GET request then I am getting SSL error,

  File "/opt/debesys/build/x86-64/debug/python/tt/pyrate/test/test_juno_sim.py", line 1077, in test_main_page
    resp = requests.get(self.url, headers=self.headers, verify=False)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/adapters.py", line 382, in send
    raise SSLError(e, request=request)
SSLError: [Errno 1] _ssl.c:507: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

I have also tried starting app like,
app.run(host=host, port=port, ssl_context=('cert.pem', 'key.pem'))
Also used urllib2 module for get request instead of requests module.

But getting same error. If I try starting app without ssl_context and use http then getting response successfully.

Here I am using headers = {'Content-Type': 'application/json'} and url = "https://127.0.0.1:{}".format(port)

[shrishinde@localhost debesys]$ wget https://127.0.0.1:47855/
--2020-02-19 13:03:25--  https://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
[shrishinde@localhost debesys]$ wget http://127.0.0.1:47855/
--2020-02-19 13:03:28--  http://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31 [text/html]
Saving to: “index.html”

100%[=====================================================================================================================================================================>] 31          --.-K/s   in 0s

2020-02-19 13:03:28 (6.25 MB/s) - “index.html” saved [31/31]

[shrishinde@localhost debesys]$

Update

Found solution:
After inheriting Flask, we have overridden Flask run method and in that WSGIServer is used so instead of ssl_context I should use ssl_args.

With hope that above steps will help user diagnose similar issues so keeping the question.


问:
Can I import html of other sites using jquery.load()?
```<code>Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I got ...

Can I import html of other sites using jquery.load into div?

答:
The error you are getting is because the webpage you are trying to load is from a different domain than your own.

See CORS

You should use Iframes instead, to load the pages from different domains.
Otherwise as target domain to allow your domain in their CORS Policies.

Body:
Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I got ...

Can I import html of other sites using jquery.load into div?


问:
Adding function parameters using a single variable in jQuery
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

```<code>function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);
</code>```

Problem demo

Thanks in advance

答:
Is this what you're after?

```<code>function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';

$('button').click(function() {
    Func.apply(this, Parameters.split(","));
});
</code>```

Demo: http://jsfiddle.net/6nJx7/14/

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply

Body:
I was thinking the is it possible to pass a variable to function which is to be executed on clicking the button and the function is given by a variable.

Also the parameters of the functions could be more than one and so I separated them by ,.

So is there a way that I can put the parameters into function using any jQuery plugin or a function. Please help me out, cause I'm confuse big time! Here is my current jQuery Code:

function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';
var Function = Func;

$('button').click(Function);

Problem demo

Thanks in advance

Body:
Is this what you're after?

function Func (a,b){
 alert(a+' | '+b);
}
var Parameters = 'cool,123';

$('button').click(function() {
    Func.apply(this, Parameters.split(","));
});

Demo: http://jsfiddle.net/6nJx7/14/

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply


问:
Why does php allow invalid return type declerations it knows it can't allow?
As far as I can tell php has the ability to prevent a return type from being declared where it knows it's problematic.

```<code>class Foo {
    public function __clone(): Baz {
        return new Baz;
    }
}

class Baz {

}

$foo = new Foo;
$newFoo = clone $foo;
</code>```

This results in a Fatal error: Clone method Foo::__clone() cannot declare a return type, which is perfectly sensible.

But then why would php allow things like this:

```<code>class Foo {
    public function __toString(): float {
        return "WAT!?!";
    }
}

echo new Foo;
</code>```

This results in

Fatal error: Uncaught TypeError: Return value of Foo::__toString() must be of the type float, string returned

Which doesn't make sense, because were you to try and return a float:

Fatal error: Uncaught Error: Method Foo::__toString() must return a string value

Wouldn't it make more sense for php to prevent the declared return type of these types of methods rather than give those dubious errors? If not, what is the underlying reason behind this internally? Is there some mechanical barricade that prevents php from doing this where it can do it in cases like clone?

答:
TL;DR: Supporting type inferences on magic methods breaks backwards compatibility.

Example: what does this code output?

```<code>$foo = new Foo;
$bar = $foo->__construct();
echo get_class($bar);
</code>```

If you said Foo, you are incorrect: it's Bar.

PHP has a long, complicated evolution of its return type handling.

Before PHP 7.0, return type hints were a parse error.

In PHP 7.0, we got return type declarations with very simple rules (RFC), and after perhaps the most contentious internal debate ever, we got strict types (RFC).

PHP limped along with some oddities in co- and contra-variance until PHP 7.4, where we got many of these sorted (RFC).

The behavior of today reflects this organic growth, warts and all.

You indicate that the __clone() behavior is sensible, then compare that to the apparently non-sensical __toString() behavior. I challenge that neither of them are sensible, under any rational expectation of type inference.

Here's the __clone engine code:

```<code>6642     if (ce->clone) {
6643         if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) {
6644             zend_error_noreturn(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static",
6645                 ZSTR_VAL(ce->name), ZSTR_VAL(ce->clone->common.function_name));
6646         } else if (ce->clone->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
6647             zend_error_noreturn(E_COMPILE_ERROR,
6648                 "Clone method %s::%s() cannot declare a return type",
6649                 ZSTR_VAL(ce->name), ZSTR_VAL(ce->clone->common.function_name));
6650         }
6651     }
</code>```

Pay careful attention to that wording (emphasis mine):

Clone method ... cannot declare a return type

__clone() gave you an error not because the types were different, but because you gave a type at all! This also is a compile error:

```<code>class Foo {
    public function __clone(): Foo {
        return new Foo;
    }
}
</code>```

"Why?!", you scream.

I believe there are two reasons:

Internals is beholden to a high-bar of backwards compatibility maintenance.

Incremental improvement comes slowly, each improvement building on earlier ones.

Let's talk about #1. Consider this code, which is valid all the way back to PHP 4.0:

```<code><?php
class Amount {
    var $amount;
}
class TaxedAmount extends Amount {
    var $rate;
    function __toString() {
        return $this->amount * $this->rate;
    }
}
$item = new TaxedAmount;
$item->amount = 242.0;
$item->rate = 1.13;
echo "You owe me $" . $item->__toString() . " for this answer.";
</code>```

Some poor soul used __toString as their own method, in a perfectly reasonable way. Now preserving its behavior is a top priority, so we can't make changes to the engine that break this code. That's the motivation for strict_types declaration: allowing opt-in changes to parser behavior so as to keep old behavior going while still adding new behavior.

You might ask: why don't we just fix this when declare(strict_types=1) is on? Well, because this code is perfectly valid in strict types mode, too! It even makes sense:

```<code><?php declare(strict_types=1);

class Amount {
    var $amount;
}
class TaxedAmount extends Amount {
    var $rate;
    function __toString(): float {
        return $this->amount * $this->rate;
    }
}
$item = new TaxedAmount;
$item->amount = 242.0;
$item->rate = 1.13;
echo "You owe me $" . $item->__toString() . " for this answer.";
</code>```

Nothing about this code smells. It's valid PHP code. If the method were called getTotalAmount instead of __toString, no one would bat an eye. The only odd part: the method name is "reserved".

So the engine can neither (a) enforce __toString returns a string type nor (b) prevent you from setting your own return type. Because to do either would violate backwards compatibility.

What we could do, however, is implement a new affirmative opt-in that says these methods aren't directly callable. Once we do that, then we can add type inference to them. Hypothetically:

```<code><?php declare(strict_magic=1);

class Person {
    function __construct(): Person {
    }
    function __toString(): string {
    }
    // ... other magic
}

(new Person)->__construct(); // Fatal Error: cannot call magic method on strict_magic object
</code>```

And this is point #2: once we have a way to protect backwards compatibility, we can add a way to enforce types on magic methods.

In summary, __construct, __destruct, __clone, __toString, etc. are both (a) functions the engine calls in certain circumstances for which it can reasonably infer types and (b) functions that - historically - can be called directly in ways that violate the reasonable type inference from (1).

This is the reason PR 4117 to fix Bug #69718 is blocked.

The only way to break this stale-mate: the developer opts in to a promise that these methods cannot be called directly. Doing that frees the engine to enforce strict type inference rules.

Body:
As far as I can tell php has the ability to prevent a return type from being declared where it knows it's problematic.

class Foo {
    public function __clone(): Baz {
        return new Baz;
    }
}

class Baz {

}

$foo = new Foo;
$newFoo = clone $foo;

This results in a Fatal error: Clone method Foo::__clone() cannot declare a return type, which is perfectly sensible.

But then why would php allow things like this:

class Foo {
    public function __toString(): float {
        return "WAT!?!";
    }
}

echo new Foo;

This results in

Fatal error: Uncaught TypeError: Return value of Foo::__toString() must be of the type float, string returned

Which doesn't make sense, because were you to try and return a float:

Fatal error: Uncaught Error: Method Foo::__toString() must return a string value

Wouldn't it make more sense for php to prevent the declared return type of these types of methods rather than give those dubious errors? If not, what is the underlying reason behind this internally? Is there some mechanical barricade that prevents php from doing this where it can do it in cases like clone?

Body:
TL;DR: Supporting type inferences on magic methods breaks backwards compatibility.

Example: what does this code output?

$foo = new Foo;
$bar = $foo->__construct();
echo get_class($bar);

If you said Foo, you are incorrect: it's Bar.

PHP has a long, complicated evolution of its return type handling.

Before PHP 7.0, return type hints were a parse error.

In PHP 7.0, we got return type declarations with very simple rules (RFC), and after perhaps the most contentious internal debate ever, we got strict types (RFC).

PHP limped along with some oddities in co- and contra-variance until PHP 7.4, where we got many of these sorted (RFC).

The behavior of today reflects this organic growth, warts and all.

You indicate that the __clone() behavior is sensible, then compare that to the apparently non-sensical __toString() behavior. I challenge that neither of them are sensible, under any rational expectation of type inference.

Here's the __clone engine code:

6642     if (ce->clone) {
6643         if (ce->clone->common.fn_flags & ZEND_ACC_STATIC) {
6644             zend_error_noreturn(E_COMPILE_ERROR, "Clone method %s::%s() cannot be static",
6645                 ZSTR_VAL(ce->name), ZSTR_VAL(ce->clone->common.function_name));
6646         } else if (ce->clone->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
6647             zend_error_noreturn(E_COMPILE_ERROR,
6648                 "Clone method %s::%s() cannot declare a return type",
6649                 ZSTR_VAL(ce->name), ZSTR_VAL(ce->clone->common.function_name));
6650         }
6651     }

Pay careful attention to that wording (emphasis mine):

Clone method ... cannot declare a return type

__clone() gave you an error not because the types were different, but because you gave a type at all! This also is a compile error:

class Foo {
    public function __clone(): Foo {
        return new Foo;
    }
}

"Why?!", you scream.

I believe there are two reasons:

Internals is beholden to a high-bar of backwards compatibility maintenance.

Incremental improvement comes slowly, each improvement building on earlier ones.

Let's talk about #1. Consider this code, which is valid all the way back to PHP 4.0:

<?php
class Amount {
    var $amount;
}
class TaxedAmount extends Amount {
    var $rate;
    function __toString() {
        return $this->amount * $this->rate;
    }
}
$item = new TaxedAmount;
$item->amount = 242.0;
$item->rate = 1.13;
echo "You owe me $" . $item->__toString() . " for this answer.";

Some poor soul used __toString as their own method, in a perfectly reasonable way. Now preserving its behavior is a top priority, so we can't make changes to the engine that break this code. That's the motivation for strict_types declaration: allowing opt-in changes to parser behavior so as to keep old behavior going while still adding new behavior.

You might ask: why don't we just fix this when declare(strict_types=1) is on? Well, because this code is perfectly valid in strict types mode, too! It even makes sense:

<?php declare(strict_types=1);

class Amount {
    var $amount;
}
class TaxedAmount extends Amount {
    var $rate;
    function __toString(): float {
        return $this->amount * $this->rate;
    }
}
$item = new TaxedAmount;
$item->amount = 242.0;
$item->rate = 1.13;
echo "You owe me $" . $item->__toString() . " for this answer.";

Nothing about this code smells. It's valid PHP code. If the method were called getTotalAmount instead of __toString, no one would bat an eye. The only odd part: the method name is "reserved".

So the engine can neither (a) enforce __toString returns a string type nor (b) prevent you from setting your own return type. Because to do either would violate backwards compatibility.

What we could do, however, is implement a new affirmative opt-in that says these methods aren't directly callable. Once we do that, then we can add type inference to them. Hypothetically:

<?php declare(strict_magic=1);

class Person {
    function __construct(): Person {
    }
    function __toString(): string {
    }
    // ... other magic
}

(new Person)->__construct(); // Fatal Error: cannot call magic method on strict_magic object

And this is point #2: once we have a way to protect backwards compatibility, we can add a way to enforce types on magic methods.

In summary, __construct, __destruct, __clone, __toString, etc. are both (a) functions the engine calls in certain circumstances for which it can reasonably infer types and (b) functions that - historically - can be called directly in ways that violate the reasonable type inference from (1).

This is the reason PR 4117 to fix Bug #69718 is blocked.

The only way to break this stale-mate: the developer opts in to a promise that these methods cannot be called directly. Doing that frees the engine to enforce strict type inference rules.


问:
How can I use tsvector on a string with numbers?
I would like to use a postgres tsquery on a column that has strings that all contain numbers, like this:

```<code>FRUIT-239476234
</code>```

If I try to make a tsquery out of this:

```<code>select to_tsquery('FRUIT-239476234');
</code>```

What I get is:

```<code>'fruit' & '-239476234'
</code>```

I want to be able to search by just the numeric portion of this value like so:

```<code>239476234
</code>```

It seems that it is unable to match this because it is interpreting my hyphen as a "negative sign" and doesn't think 239476234 matches -239476234.  How can I tell postgres to treat all of my characters as text and not try to be smart about numbers and hyphens?

答:
This is done by the text search parser, which is not configurable (short of writing your own parser in C, which is supported).

The simplest solution is to pre-process all search strings by replacing - with a space.

Body:
I would like to use a postgres tsquery on a column that has strings that all contain numbers, like this:

FRUIT-239476234

If I try to make a tsquery out of this:

select to_tsquery('FRUIT-239476234');

What I get is:

'fruit' & '-239476234'

I want to be able to search by just the numeric portion of this value like so:

239476234

It seems that it is unable to match this because it is interpreting my hyphen as a "negative sign" and doesn't think 239476234 matches -239476234.  How can I tell postgres to treat all of my characters as text and not try to be smart about numbers and hyphens?


问:
Insert on conflict with query parameters
How could i use psycopg2 query parameters with on conflict?
for example, i have this data:

```<code>#This is the data for the insert query
q_values = {'customer_app_id': '35', 'email': 'my@email.com', 'access_counter': 1, 'company_name': 'twitter', 'status': 'start'}

#This is the data for the on conflict query part
conflict_values = {'access_counter': +1, 'status': 'check', 'status_info': 'already exist'}
</code>```

This is the query:

```<code>insert into access (customer_app_id,email,access_counter,company_name,status)
values (%s,%s,%s,%s,%s) ON CONFLICT (customer_app_id,email)  DO UPDATE SET
%s,%s,%s RETURNING *
</code>```

Then i run this line:

```<code>q_values = q_values.update(conflict_values)
cursor.execute(query, q_values)
</code>```

First, how at all to run on conflict with query parameters ?

Second, the update i am doing with the dict is not good since if it will be duplicate keys it will merge them, and then number of parameters wont be equal to number of values.

and access_counter +1 - on conflict i'm trying to increase the access _counter by 1

please can you help ?
Thank you!

答:
To run on conflict with query parameter:
The %s has to be replaced by %(key value that you want to access)s. This has to be done since you are using a dictionary. So in this case the query would look as follows-

insert into access (customer_app_id,email,access_counter,company_name,status)
values (%(customer_app_id)s,%(email)s,%(access_counter)s,%(company_name)s,%(status)s) ON CONFLICT

To update the access counter:
A separate dictionary need not be used. Rather ON CONFLICT you can directly make changes in the database. So in this case the final query would look as follows-

insert into access (customer_app_id,email,access_counter,company_name,status)
values (%(customer_app_id)s,%(email)s,%(access_counter)s,%(company_name)s,%(status)s) ON CONFLICT (customer_app_id,email) DO UPDATE SET access_counter = access.access_counter + 1

In case you want to update one of your column values to a new value sent in the INSERT query then you will have to use EXCLUDED keyword.

Example(this example is not related to the question):

INSERT INTO user_details (user_id, username,email,last_login)
                            VALUES (%s, %s, %s,%s)
                            ON CONFLICT (user_id) DO UPDATE
                            SET  last_login = EXCLUDED.last_login

Body:
How could i use psycopg2 query parameters with on conflict?
for example, i have this data:

#This is the data for the insert query
q_values = {'customer_app_id': '35', 'email': 'my@email.com', 'access_counter': 1, 'company_name': 'twitter', 'status': 'start'}

#This is the data for the on conflict query part
conflict_values = {'access_counter': +1, 'status': 'check', 'status_info': 'already exist'}

This is the query:

insert into access (customer_app_id,email,access_counter,company_name,status)
values (%s,%s,%s,%s,%s) ON CONFLICT (customer_app_id,email)  DO UPDATE SET
%s,%s,%s RETURNING *

Then i run this line:

q_values = q_values.update(conflict_values)
cursor.execute(query, q_values)

First, how at all to run on conflict with query parameters ?

Second, the update i am doing with the dict is not good since if it will be duplicate keys it will merge them, and then number of parameters wont be equal to number of values.

and access_counter +1 - on conflict i'm trying to increase the access _counter by 1

please can you help ?
Thank you!


问:
Xamarin.Forms vs Xamarin Mvvmcross
We are planning to go with Xamarin for our next big project.
Seems like Xamarin.Forms is mature enough to use with production projects.
But I still want to take input from you experts - should we go with Xamarin.Forms or Xamarin with MvvmCross architecture?

The project is big and critical for our customer.

答: Xamarin.Forms is a bit of a different technology than MvvmCross. Everything depends on the size of project, how complicated the UI is. I recommend reading this article - it should give you some ideas.</p>

Title: Xamarin.Forms vs Xamarin Mvvmcross


问:
Docker-compose runs with successful build but one container missing
I have a basic docker-compose.yml:

```<code>version: '2'
services:
  hvac_backend:
    build: ./HVAC_backend
    ports:
      - 8000:5000
  hvac_frontend:
    build: ./HVAC_frontend
    ports:
      - 80:80
</code>```

and the two following Dockerfiles being HVAC_frontend:

```<code>FROM nginx:1.17.8

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
</code>```

and HVAC_backend:

```<code>FROM balenalib/beaglebone-black-alpine-python:3-3.11

MAINTAINER Muller

WORKDIR /usr/src/app

COPY . ./

RUN pip install -r requirements.txt

ENTRYPOINT ["python"]

CMD ["app.py"]

</code>```

When I run a normal docker build and docker run on the the HVAC_frontend nginx runs fine on localhost:80. When I do a docker-compose up -d I get a output of:

```<code>Creating hvac_balenaos_hvac_backend_1  ... done
Creating hvac_balenaos_hvac_frontend_1 ... done
</code>```

but after a docker ps only the HVAC_backend is running

```<code>CONTAINER ID        IMAGE                        COMMAND             CREATED             STATUS              PORTS                    NAMES
249be0be515a        hvac_balenaos_hvac_backend   "python app.py"     10 seconds ago      Up 9 seconds        0.0.0.0:8000->5000/tcp   hvac_balenaos_hvac_backend_1
</code>```

Any clues? Feels like I'm just missing something small. What happened to HVAC_frontend?

答:
Probably your backend container starts properly but stops because of some exception.

run this command:

```<code>docker ps -a
</code>```

to list all containers even this which are stopped.

Body:
I have a basic docker-compose.yml:

version: '2'
services:
  hvac_backend:
    build: ./HVAC_backend
    ports:
      - 8000:5000
  hvac_frontend:
    build: ./HVAC_frontend
    ports:
      - 80:80

and the two following Dockerfiles being HVAC_frontend:

FROM nginx:1.17.8

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

and HVAC_backend:

FROM balenalib/beaglebone-black-alpine-python:3-3.11

MAINTAINER Muller

WORKDIR /usr/src/app

COPY . ./

RUN pip install -r requirements.txt

ENTRYPOINT ["python"]

CMD ["app.py"]

When I run a normal docker build and docker run on the the HVAC_frontend nginx runs fine on localhost:80. When I do a docker-compose up -d I get a output of:

Creating hvac_balenaos_hvac_backend_1  ... done
Creating hvac_balenaos_hvac_frontend_1 ... done

but after a docker ps only the HVAC_backend is running

CONTAINER ID        IMAGE                        COMMAND             CREATED             STATUS              PORTS                    NAMES
249be0be515a        hvac_balenaos_hvac_backend   "python app.py"     10 seconds ago      Up 9 seconds        0.0.0.0:8000->5000/tcp   hvac_balenaos_hvac_backend_1

Any clues? Feels like I'm just missing something small. What happened to HVAC_frontend?

Body:
Probably your backend container starts properly but stops because of some exception.

run this command:

docker ps -a

to list all containers even this which are stopped.


问:
Hide Div permanently when CF7 form is submitted successfuly until cache or cookies is cleared
I have this script which popup a div on 5, 10 15 seconds interval when you click the close button

```<code>var iteration = 0;
var times = [5,10,15]

var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
    }, time)
}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < <?=$interval_array_count?>) {
      showPopUp(times[iteration])
    }
});
</code>```

Inside the div is a contact form 7, and the code below hides the div when the form is submitted

```<code>document.addEventListener( 'wpcf7mailsent', function( event ) {
    if(event.detail.contactFormId == '10917') {
    jQuery('.pop_timer_box').hide();
    }
}, false );
</code>```

My question is how to make it so that when I submit a form and its successful the popup form won't appear anymore unless cache or cookie or localstorage is cleared

答:
function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
 }

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
function showNewsletterPopUp(){
 $(window).scroll(function() {
    if($(window).scrollTop() > 100) {
     $('.popup').fadeIn(300);
    }

 });
 jQuery(function($) {
     $('.parallax').on('scroll', function() {
      if($(".parallax").scrollTop() > 100) {
       $('.popup').fadeIn(300);
   }
     })
 });
 $('.pop_close').click(function(){
     $('.popup').addClass('hide_this');
    });
}
function checkCookie() {

 //console.log('hgghhggh');
  var user = getCookie("popup-attribute");

  if(typeof user === "undefined" || user == null || user == ''){
   console.log('HERE');
      showNewsletterPopUp();
      setCookie("popup-attribute", 'enable', 7);
  }
}
checkCookie();```

Body:
I have this script which popup a div on 5, 10 15 seconds interval when you click the close button

var iteration = 0;
var times = [5,10,15]

var showPopUp = function(time) {
    setTimeout(function() {
        jQuery('.pop_timer_box').css('display','flex');
    }, time)
}

showPopUp(times[iteration]);

jQuery('body').on('click', '.cclose_pop', function() {
    jQuery('.pop_timer_box').hide();
    iteration +=1;
    if (iteration < <?=$interval_array_count?>) {
      showPopUp(times[iteration])
    }
});

Inside the div is a contact form 7, and the code below hides the div when the form is submitted

document.addEventListener( 'wpcf7mailsent', function( event ) {
    if(event.detail.contactFormId == '10917') {
    jQuery('.pop_timer_box').hide();
    }
}, false );

My question is how to make it so that when I submit a form and its successful the popup form won't appear anymore unless cache or cookie or localstorage is cleared


问:
How to parse specific field from GMAIL body to google SHEETS
I have a gmail body that starts with this:

```<code>Name: Full Report
Store: River North (Wells St)
Date Tripped: 18 Feb 2020 8:40 PM
Business Date: 18 Feb 2020 (Closed)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 5 minutes.
</code>```

I'm trying to parse the Date Tripped: field and the Business Date: field but don't believe i'm getting the regex correct.

```<code>    // Implement Parsing rules using regular expressions
    if (content) {

      tmp = content.match(/Date Tripped: \s*([A-Za-z0-9.\s ]+)(\r?\n)/);
      var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

      tmp = content.match(/Business Date: \[0-9][()]/);
      var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
</code>```

答:
For the Date Tripped, minor change needed:

```<code>Date Tripped:\s*([:A-Za-z0-9\s]+)\r?\n
</code>```

Your main error: you forgot to put : inside the class brackets.
Tip: get rid of the ( and ) around \r?\n. You don't want to catch those.

You could make this even a bit shorter:

```<code>Date Tripped:\s*([:\w\s]+)\r?\n
</code>```

See regex101

For the business date, this one will do:

```<code>Business Date:\s([\w\s]+\([a-zA-Z]+\))
</code>```

Or even shorter:

```<code>Business Date:\s([\w\s]+\(\w+\))
</code>```

Your (main) error: you escape \[ which is not correct here. Next: [()] matches ( and ), but not (Closed).
See regex101

Body:
I have a gmail body that starts with this:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 18 Feb 2020 8:40 PM
Business Date: 18 Feb 2020 (Closed)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 5 minutes.

I'm trying to parse the Date Tripped: field and the Business Date: field but don't believe i'm getting the regex correct.

    // Implement Parsing rules using regular expressions
    if (content) {

      tmp = content.match(/Date Tripped: \s*([A-Za-z0-9.\s ]+)(\r?\n)/);
      var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

      tmp = content.match(/Business Date: \[0-9][()]/);
      var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

Body:
For the Date Tripped, minor change needed:

Date Tripped:\s*([:A-Za-z0-9\s]+)\r?\n

Your main error: you forgot to put : inside the class brackets.
Tip: get rid of the ( and ) around \r?\n. You don't want to catch those.

You could make this even a bit shorter:

Date Tripped:\s*([:\w\s]+)\r?\n

See regex101

For the business date, this one will do:

Business Date:\s([\w\s]+\([a-zA-Z]+\))

Or even shorter:

Business Date:\s([\w\s]+\(\w+\))

Your (main) error: you escape \[ which is not correct here. Next: [()] matches ( and ), but not (Closed).
See regex101