Write image downloaded in the media content

Question: I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.
I do not understand why because I set up the permission in the manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seb.sebastien.reddit">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.
Thanks
Comment: Possible duplicate of [Storage permission error in Marshmallow](https://stackoverflow.com/questions/33162152/storage-permission-error-in-marshmallow)
Comment: is your app crashing if yes then add crash logs to further investiage your problem
Comment: https://stackoverflow.com/questions/33162152/storage-permission-error-in-marshmallow
Comment: https://developer.android.com/training/permissions/requesting.html
Answer: For Android Running on Android 6.0 (API level 23) and above , we need to add runtime permission to work, you can follow this link  Storage permission error in Marshmallow
----Updated ----
Code reference
public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {

            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

Permission result callback:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}

Comment: That's perfect catch!
Comment: Ok ,edited , i will keep this in mind while giving answer to questions :)
Answer: For TargetSDK 23 or higher, you need to give runtime permission As per Android's guideline. Check this link for code snippet and more description.
https://developer.android.com/training/permissions/requesting.html
Answer: Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.
if (!checkPermission()) {
        openActivity();
    } else {
        if (checkPermission()) {
            requestPermissionAndContinue();
        } else {
            openActivity();
        }
    }

Add this method outside onCreate.
private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}

happy Coding.


GCP Https Load Balancer SSL Certificate

Question: I am trying to create a Https load balancer using yaml and Jinja files on GCP deployment manager. But I am not sure how to provide SSL certificate. In the "sslCertificates" of "compute.v1.targetHttpsProxy", it expects the value to be URL to sslCertificates. How do i create an URL for the SSL certificate. Earlier, I was trying to provide the certificate itself in the field but I get an error saying "The URL is malformed".
Please help if anyone knows how to solve this.
Comment: I suspect that answer to this question is the same as the format needed for the API call for setSSLCertificates. Unfortunately I haven't been able to find that information. I'm asking a separate question about that.
Comment: Someone pointed me to the correct answer someplace else, which is that the URL you need for the API, and presumably for Google Deployment Manager, is the one pointed to by "selfLink" in when listing sslCertificates in GCP. It looks like:

[https]://www.googleapis.com/compute/v1/projects//global/sslCertificates/"
Answer: You have to use gcloud to upload the certificate to Google Cloud, like this:
gcloud compute ssl-certificates create [SSL_CERTIFICATE] \
--certificate [CRT_FILE_PATH] --private-key [KEY_FILE_PATH]

You need the certificate to be PEM encoded. After this you can attach [SSL_CERTIFICATE] to your load balancer. Do this for each of the certificates you want to attach to it.
The documentation for this is here.
Edit:
To add to this incomplete answer, in case you in ever have a doubt of what API call to make while within Google Cloud just run the equivalent gcloud command with the flag --log-http and review carefully the results. The gcloud SDK is making the API calls you need and this flag will output all that happens and what endpoints and in which format you need to call to reproduce that.
Comment: This isn't really a good answer to the question. The poster asked how to attach a certificate to a load balancer in GCP Deployment Manager, and you told them how create a certificate with gcloud. You also told them you have to create the certificate with gcloud, which isn't true either; the API works fine. Unfortunately, I don't know the correct answer to the question, because the URL format for a GCP SSL certificate needed for the API call (which I assume is what GCP is looking for here) isn't documented anyplace I can find it.
Comment: Added extended answer. Something about teaching to fish or whatever.

GCP Https Load Balancer SSL Certificate


Parsing value of a field from content to a webform field

Question: I have a content type named apartments. When i view a content of content type apartments i will give a button for requesting a quote. When clicked on that button it takes to a webform and by default a field value should be filled by that contents title. Please let me know the process of parsing a fields value to a webform field.
Answer: Try using the webform node value module

Fill a Webform field with the value of a node field.
Comment: I tried that module but its not working. Please let me know if there's any other solution.


App crashing while implementing current location in android studio

Question:
home.java

package com.example.nitctraveltogether;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import android.location.Location;
import android.os.Bundle;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class home extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    GoogleApiClient googleApiClient;
    Location lastLocation;
    LocationRequest locationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        locationRequest= new LocationRequest();
        locationRequest.setInterval(1000);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);

        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

        lastLocation= location;
        LatLng latLng= new LatLng(location.getLatitude(),location.getLongitude());
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }

    protected synchronized void buildGoogleApiClient(){
        googleApiClient=new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        googleApiClient.connect();
    }
}

manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nitctraveltogether">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".demo"
            android:label="@string/title_activity_demo"></activity>
        <activity
            android:name=".home"
            android:label="@string/title_activity_home">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Splashscreen"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat

2020-03-08 17:19:31.144 28966-28966/com.example.nitctraveltogether E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.nitctraveltogether, PID: 28966
    java.lang.SecurityException: my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
        at com.google.maps.api.android.lib6.impl.bi.c(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (100400-0):26)
        at com.google.android.gms.maps.internal.i.a(:com.google.android.gms.dynamite_mapsdynamite@firstname.lastname@example.com (100400-0):139)
        at ch.onTransact(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (100400-0):4)
        at android.os.Binder.transact(Binder.java:675)
        at com.google.android.gms.internal.maps.zza.zzb(Unknown Source:20)
        at com.google.android.gms.maps.internal.zzg.setMyLocationEnabled(Unknown Source:109)
        at com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(Unknown Source:112)
        at com.example.nitctraveltogether.demo.onMapReady(demo.java:42)
        at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
        at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
        at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
        at android.os.Binder.transact(Binder.java:675)
        at cg.b(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (100400-0):2)
        at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_mapsdynamite@email@example.com (100400-0):2)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

App is getting crashed while accessing this activity, I am trying to access current location through google map api in android studio and using firebase location. Please help me resolve this error, is there any mistake in manifest file or java file. I have written all the required permissions in manifest file but still the app is getting crashed while running. You can also check the logcat for the error.
Answer: You need to request for user's permission to access location.
Read more here:
https://developer.android.com/training/permissions/requesting


Does this variant of Cantor's diagonal argument work?

Question: I fully realize the following is a less-elegant obfuscation of Cantor's argument, so forgive me. I am still curious if it is otherwise conceptually sound.

Make the infinitely-long list alleged to contain every infinitely-long binary sequence, as in the classic argument. Assume each infinite sequence occupies one row.

Arrange the list such that it is duplicated in full by optionally taking each column instead of each row—that is, the sequences consisting of the $k^\text{th}$ bits of every row—since if we're asserting there's only one species of infinity, we should be able to put the list in bijection to itself.

The most straightforward way I see of doing this is to have the first column and the first row be the same sequence, and likewise for the second column and row, and so forth. The choice of ordering for the list is irrelevant, provided that order is identical on each axis. The resulting table would necessarily be symmetrical about the diagonal.

I think there are lots of ways to kill it from here, but here's one:

Notice that one sequence must consist only of infinitely many zeros, and another sequence must consist only of infinitely many ones. Since each sequence appears both horizontally and vertically, it means our zero-sequence must intersect our one-sequence somewhere. Since these two sequences clearly cannot intersect, which requires sharing an element, at least one of them is not on the list, so the list is not complete.

My question is whether this is substantively the same as Cantor's argument, more or less, or if I've introduced any additional suspect assumptions without realizing it which could break the argument.
Comment: In your point $2.\bullet$, it is unclear to me how you would guarantee that $f(n)_m=f(m)_n$ for all $m$ and $n$, while preserving surjectivity of $f$ onto $2^{\Bbb N}$.
Comment: Second step (symmetry between rows and columns) looks impossible.
Comment: If the first row and the first column are all zeros, you haven't made a complete list.
Comment: @Gae.S. Perfect, this is what I wanted pointed out. I'll think on that for a few and fix it, or surrender. But to be clear, the idea of the list being able to be put in bijection with itself makes sense, right? (Assuming there *were* only a countable infinity.) It's just my proposed symmetry arrangement that sounds problematic?
Comment: I don't understand exactly which two sets you want to put in bijection. Let's say that $f:\Bbb N\to\Bbb \{0,1\}^{\Bbb N}$ is a bijection. Then what do you want to put in bijection with what?
Answer: This argument just doesn't work at all.  You have not justified your claim in step 2 that you can arrange both that every sequence appears in a row and that every sequence appears in a column.  There is no reason to expect this to be true.
It is instructive to consider what would happen if you were instead only trying to list all the sequences that have only finitely many $1$s.  In this case, the set of such sequences is countable, so it is possible to do so!  However, it is not possible to do so such that the columns also include every such sequence.  For if you could, then one of the columns (say column $n$) would be all $0$s, but then that would mean every row has a $0$ as its $n$th entry, so your list includes no sequences whose $n$th term is $1$.


Possibility to override DateFormat.getDateTimeInstance()?

Question: I just wonder, is it possible to tell our JVM to use a default DateFormat that is not the one configured for the current locale for exemple?
I know I can provide the Locale but I don't want to.
Actually, I would like to be able to specify the DateFormat to be returned for a specific locale.
Is it possible?
Answer: The only solution that comes to my mind here is to "hijack" the java.text.DateFormat class. To do this, you would need to write your own class of the same package and name, compile it into a jar and place that jar into the JRE's lib\endorsed folder.
Disclaimer:
I haven't tested this, and I'm pretty sure it constitutes a violation of some rule, it may not work, and it may delete the entire contents of your disk.
Other than that: Why would you want to do this? If you want to change the date format for your system's locale, go to the system's control center and change it for every locale you like ;-)


White Screen of Death on Cron, fixed with update.php

Question: One installation of Drupal has been fine for a long time, but has started developing a WSOD on most (maybe all) cron invocations.
Looking through Drupal's log messages, I see a few normal cron messages, and then this:
Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in theme_get_registry() (line 277 of theme.inc).
Warning: array_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc).
Warning: array_fill_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc)
Warning: PHP Shutdown: Argument #1 is not an array in ThemeRegistry->set() (line 457 of theme.inc).

I then see the following repeated many hundreds of times, once for each theme hook, it seems:
Theme <hook name> not found. Warning: array_key_exists() expects
parameter 2 to be array, null given in ThemeRegistry->offsetExists()
(line 421 of theme.inc).

So that is repeated a few hundred times, where <hook name> is every theme hook in the entire Drupal installation.
It has been running a custom theme, but that theme has behaved fine for ages. In fact, I have not made many recent site changes. I've only updated Drupal to 7.52.
Any ideas how to proceed?
Answer: Looks like an issue with either a theme hook implementation, or call to a theme function. In particular seems related to theme_block
While it could be something else, I'd suggest making sure you have the file block.tpl.php in your base and sub-theme directories and then clear cache.
Other possibilities are a file permission issue, make sure the files are readable by the webserver
Comment: When I said that message was repeated for every theme hook, I meant that "hook block" was different in each of the hundreds of messages. It seems to cycle through every single hook in Drupal. There is nothing special about hook block. I will try to clarify that in the post.
Comment: @RichardofEssex in that case, perhaps a file permission issue, if the system can't read the updated files. Make sure the install files are readable by the webserver user.


How can I resolve OutofMemoryError error? (After Bitmap.createScaledBitmap)

Question: I know, there are a lot of similar questions in Stackoverflow. But I could not solve my problem.
I have some kind of jigsaw puzzle. The pictures in the Drawable-nodpi folder are 2500x1250.
I am trying to resize the images with the following code suggested:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

I call it like this:
(I call these codes several times.)
private Bitmap resizeImg (int rsm) {

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);

   return bmp;
}

I need to use Matrix as the scaling of Imageview. But it's not the size I want. It works right without the Matrix.
I'm solving the Matrix problem like this:

Bitmap.createScaledBitmap

private Bitmap resizeImg (int rsm) {

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);

   //  return bmp;

    Bitmap resized = Bitmap.createScaledBitmap(bmp, wdth,hght,true); //I get OutOfMemoryError this line.
    return resized;

}

This insertion really solves my problem. But every day I get lots of OutOfMemoryError errors.
What do I need to do to fix this error? Please help me. Thank you.
Comment: Try getting rid of the first `decodeResource()` call, with the `inJustDecodeBounds = true`. You know the size of the images, as you provided that detail in the question. I don't know how well `inJustDecodeBounds = true` works with resources, and since you already know the size, it would save time anyway.
Answer: 1] Add largeHeap as true in android manifest to your application tag:
          android:largeHeap="true"

2] Recycle your all used bitmaps,
    Example:
         bmp.recycle();
         resized.recycle();

Comment: I'm already using `android:largeHeap="true"`. I will try the other codes and write the result. Thank you.
Comment: but be sure, you are not using Bitmap instance after called recycle(), else your will get exception "trying to use a recycled bitmap" & app will get crash.
Comment: Yes. I arranged the codes by paying attention to this. The application is up to date on the market. There are fewer mistakes than before. But the error still exists. I do not get any errors on my test devices myself.


Prove that for every natural number $n$, there exists a natural number $m$ such that $\frac{1}{m}-\frac{1}{m+1} < \frac{1}{n}$

Question: I am not sure how to proceed with my proof. I can easily explain in words why this is so (just by maximizing the values of the LHS and RHS then noting the left will always decrease faster than the RHS due to denominator getting smaller), but I do not think this is mathematically valid and doesn't necessarily prove anything.
This is how I did it.
$\frac{1}{m} - \frac{1}{m+1} < \frac{1}{n}$
$=\frac{1}{m(m+1)} < \frac{1}{n}$
Now, I am sadly stuck and have no way to proceed. I am thinking to expand this inequality like $\frac{1}{m(m+1)}  < \text{something} < \frac{1}{n}$
or
$\text{something}  < \frac{1}{m(m+1)}  < \frac{1}{n}$, but I am not sure how to go about this or if this is even the right approach.
Comment: Now you can choose (for example) $m=n$.
Comment: Based on the new title, let $m=n$.  Then the inequality holds.
Comment: The partial fraction recombination is appropriate, but there are no limits listed for $n$ so it is always possible to choose $n$ to make the inequality fail.  Are there more conditions than you have listed?
Comment: That inequality does *not* hold for all $m, n$.
Comment: Let $m=n$ then the problem is solved
Comment: Is the problem supposed to be "for every natural number $n$, there is an integer $m$ ..."?
Comment: @abiessu sorry, updated the title.
Comment: @MartinR apologies, updated the title.
Answer: You have $\frac{1}{m(m+1)} < \frac{1}{n}$, which is equivalent to
$m(m+1) > n$. Surely you can find a value of $m$ that will make this true.
Answer: Even more directly, if $m=n$, then $\frac 1m - \frac {1}{m+1} = \frac 1n - \frac{1}{n+1} \lt \frac 1n$ because $\frac {1}{n+1} \gt 0$.


Showing that $\beta \alpha \beta^{-1}$ and $\alpha$ both odd or even

Question:
Question: Let $\alpha$ and $\beta$ belong to $S_{n}$. Prove that $\beta \alpha \beta^{-1}$ and $\alpha$ are both odd or even.

$\alpha \alpha ^{-1} =\varepsilon =\beta^{-1} \beta $
where $\varepsilon$ is an even permutation.
Let $\alpha = \sigma _{1}\cdot \cdot \cdot \sigma_{s}$, $\beta = \theta _{1}\cdot \cdot \cdot \theta_{t}$
Observe:
$\varepsilon =\sigma _{1}\cdot \cdot \cdot \sigma_{s} \theta _{1}\cdot \cdot \cdot \theta_{t}$
Thus, s + t is even implies that both s and t are either odd or even.
$\beta \alpha \beta^{-1}$ has $\left ( 2t + s \right )$ 2-cycles.
A crucial piece of detail could be preventing me from completing this proof.
Any hint is appreciated.
Comment: Perhaps then it would be a good idea to try some small examples. A permutation is a $2$-cycle when it interchanges precisely two elements. If $\tau$ is a $2$-cycle, what elements can the permutation $\beta \tau \beta^{-1}$ change?
Comment: Perhaps http://math.stackexchange.com/questions/529195/if-alpha-is-even-show-that-beta-alpha-beta-1-is-even?rq=1 will help?
Comment: I am unable to understand how it is a product of an even number of two cycles.
Comment: The proof in the link has three sentences. Which one of those specifically do you not understand?
Comment: The second sentence. He asked to note that the composition is a 2-cycle. But I am unable to understand why that composition is a product of an even number of 2 -cycles.
It's much similar to my work above. Except that, I am unable to 'see' why it is an even number of 2 cycles
Answer: Note that if:
$\alpha = \sigma_1\sigma_2\cdots\sigma_k$
that:
$\beta\alpha\beta^{-1} = (\beta\sigma_1\beta^{-1})(\beta\sigma_2\beta^{-1})\cdots(\beta\sigma_k\beta^{-1})$.
Now if each $\sigma_i$ for $i = 1,\dots,k$ is a transposition, we will show each $\beta\sigma_i\beta^{-1}$ is likewise a transposition.
Suppose $\sigma_i = (a\ b)$. Let us denote:
$c = \beta(a)$ and $d = \beta(b)$, so that $\beta^{-1}(c) = a$, and $\beta^{-1}(d) = b$.
If $m \not\in \{c,d\}$, then $\beta^{-1}(m) \not\in \{a,b\}$ (because $\beta,\beta^{-1}$ are bijective), and thus:
$\sigma_i\beta^{-1}(m) = \sigma_i(\beta^{-1}(m)) = \beta^{-1}(m)$, since $\sigma_i$ only affects $a$ and $b$.
Therefore, $\beta\sigma_i\beta^{-1}(m) = \beta(\sigma_i(\beta^{-1}(m))) = \beta(\beta^{-1}(m)) = m$.
If $m = c$, we have: $\beta\sigma_i\beta^{-1}(c) = \beta(\sigma_i(\beta^{-1}(c))) = \beta(\sigma_i(a)) = \beta(b) = d$,
and if $m = d$, we have: $\beta\sigma_i\beta^{-1}(d) = \beta(\sigma_i(\beta^{-1}(d))) = \beta(\sigma_i(b)) = \beta(a) = c$.
So, $\beta\sigma_i\beta^{-1} = (c\ d)$.
Thus if $\alpha$ is a product of $k$ transpositions, $\beta\alpha\beta^{-1}$ is likewise, whether $k$ be even or odd.
Answer: Consider the following homomorphism: $f:S_n \to \{-1,1\}$ given by
$$f(A_n)=1 \, \,, f(S_n\backslash A_n)=-1.$$
One should check that this is indeed a homomorphism, and that it is typically denoted $\mathrm{Sgn}$. If you check that it is a homomorphism, you can see that its kernel is exactly $A_n$, so $A_n$ is a normal subgroup which means that $\sigma A_n \sigma^{-1}=A_n$.
edit: Without explicit use of homomorphisms, you can use the fact that the decomposition into transpositions is not unique, but its parity is. Hence, we can see that if $\sigma:=\sigma_1\dots \sigma_n$, where $\sigma_i$ are transpositions and $\tau:=\tau_1\dots \tau_k$ where $\tau_j$ are transpositions, then $\sigma \tau =(\sigma_1\cdots\sigma_n)(\tau_1 \cdots \tau_k)$, which has some parity independent of its decomposition. You can use this to finish the problem ,and look here for some more in depth discussion.
Comment: Can you do this with only permutation?
Comment: yeah, you can. I think the first way is easiest though.
Comment: How does your edited comment ties in with my current attempt? it isn't as though I haven't tried after having worked on  this for 90 mins while having also looked at the theorem related to your comments.
Comment: I already know $\beta \alpha$ is even
Comment: so what **don't** you know?
Comment: I don't know what $\beta \alpha \beta^{-1}$ is. This stems from the fact that I don't know if $\beta$ is odd or even.
Comment: Why not try the following argument: if $\beta$ is even iff $\beta^{-1}$ is even, so first suppose that $\beta$ is even, and then odd. It will not change your proof at all.  Ultimately it will not matter: $\beta \tau \beta^{-1}$ is *always* odd when $\tau$ is a transposition, for the following intuitive reasons: **(1)** it is itself a transposition or **(2)** $\mathrm{Sgn}(\beta) \mathrm{Sgn}(\beta^{-1})=\mathrm{Sgn}(\beta \beta^{-1})=1$ and $\mathrm{Sgn}(\tau)=-1$ whenever $\tau$ is a transposition.
Answer: Here's the easiest proof. Take the sign function
$$\mbox{sgn}:S_n\to\{-1,1\}$$
$$\mbox{sgn}(a_1\cdots a_n)=(-1)^n\mbox{ for } a_i=\mbox{ transpositions}$$
It can be proved that this is a well defined function and it is a group homomorphism (with integer multiplication on the right side), i.e.
$$\mbox{sgn}(ab)=\mbox{sgn}(a)\mbox{sgn}(b)$$
In particular $\mbox{sgn}(a^{-1})=\mbox{sgn}(a)^{-1}$, the simple property of any group homomorphism.
Therefore
$$\mbox{sgn}(\beta\alpha\beta^{-1})=\mbox{sgn}(\beta)\mbox{sgn}(\alpha)\mbox{sgn}(\beta)^{-1}=\mbox{sgn}(\beta)\mbox{sgn}(\beta)^{-1}\mbox{sgn}(\alpha)=\mbox{sgn}(\alpha)$$
The second equality makes sense, because multiplication in $\{-1,1\}$ is commutative.
Comment: Here's how I solved it.
$\beta\alpha$ is even.
Note: $\beta^{-1}=\alpha$

Observe:
If $\beta$ is even, then $\beta \alpha \beta^{-1}$ is even. $\alpha$ is even.

If  $\beta$ is odd, then $\beta \alpha \beta^{-1}$ is odd. $\alpha$ is odd.
Comment: @Mathematicing $\beta^{-1}=\alpha$? Why would you have that? That's definitely not true. What is true howeve is that $\beta^{-1}$ is even if and only if $\beta$ is even. And then your reasoning is correct.


JavaScript é interpretado ou compilado em tempo de execução?

Question: Nesta outra pergunta eu perguntei a mesma coisa, mas em relação a Java. Agora pergunto sobre o JavaScript.
Pelo que eu saiba, historicamente o JavaScript sempre foi interpretado, mas o Google mudou isso com o V8 no Chromium. Estou certo ou errado? E em relação aos outros browsers, como o Firefox e IE, ainda é interpretado?
Comment: Essa é uma boa pergunta
Answer: Compilado em tempo de execução. Tal como o V8, os demais browsers introduziram Compilação JIT aos seus motores JavaScript para melhorar a performance, alguns quase que paralelamente ao lançamento do V8 (e outros depois):

Internet Explorer: suporta JIT a partir da versão 9, com a engine Chakra;
Firefox: suporta JIT a partir da versão 3.5, com o TraceMonkey. Segundo a Wikipedia, esta foi inclusive a primeira implementação a usar JIT, e não o V8, mas os respectivos artigos não dão datas exatas. A partir de então, outros motores também JIT foram incorporados ao SpiderMonkey;
Opera: usa o V8, a partir da versão 15;
Safari: usa a engine Nitro, também JITada, a partir de 2008 (não há menção à versão).

Esses são os principais browsers. No contexto standalone, temos o Node.js que é baseado no V8, e o Rhino que é um caso especial: originalmente, ele operava em modo compilado de A pra B, i.e. traduzindo todo o código JavaScript para bytecodes Java (um exemplo prático do 3º item na minha resposta à sua outra pergunta). Isso oferecia uma performance de execução ainda melhor que a compilação JIT, mas com a desvantagem do tempo de compilação ser longo. Hoje ele dá suporte aos dois modos: compilado e interpretado, de modo que o programador pode pesar o que é mais importante para ele numa determinada situação - velocidade de execução vs. velocidade de compilação.
Concluindo, todas as implementações modernas mais comuns usam algum tipo de compilação, a maioria do tipo JIT. Podem haver outras que eu não conheço e, de todo modo, vale relembrar o que disse Maniero na mesma pergunta linkada: "Não podemos dizer que existem linguagens interpretadas ou compiladas ou mesmo JITtadas. No máximo podemos dizer que as implementações tem estas características. E elas não são mutuamente exclusivas."
Comment: Isso explica por que o Opera ta sempre apanhando das minhas animações enquanto outros navegadores rodam perfeitamente
Answer: V8 e Rhino são exemplos de compiladores de JavaScript. Respectivamente, para código nativo interno (C++) e para JAVA Bytecode. Existem ainda outros interpretadores que utilizam um compilador JIT.
À risca, JavaScript é tanto interpretado quanto compilado – essa especificação não é obrigatoriamente de responsabilidade da linguagem, mas no cenário JavaScript, você pode delegar qual mecanismo de interpretação ou compilação você vai querer usar.
Se você quiser utilizar o V8, o Google explica como trabalhar em cima do seu motor que, como já dito, é compilado. Aplicações naturalmente web, por sua vez, utilizarão os motores e dispositivos providos pelos navegadores do cliente, que trazem consigo mecanismos interpretadores e que não compilarão o JavaScript em um padrão standard.
Cuidado aqui: precompilação de assets
Um erro recorrente é confundir compilação de assets com compilação de linguagem. Quando usamos Rails, por exemplo, podemos utilizar o Asset Pipeline para precompilar os nossos assets, fazendo com que uma quantidade X de arquivos <code>.js</code> se unifiquem e se comprimam para então formar um só, minificado, resultando em uma sensação (errônea) de "compilação".
Na verdade, houve sim uma compilação, mas ela não é a mesma que você está pensando, como a qual C# ou JAVA fazem.
Comment: Para quem trabalhar com ASP.NET MVC, essa precompilação de assets é também conhecida como bundle e minification - http://msdn.microsoft.com/pt-br/library/dn168847.aspx


Determining elements and subsets of a set

Question: Let A := {1, {1}, {2}}
Which statements are true?
a) {1} is an element of A
b) {1} is a subset of A
c} {{1}} is a subset of A
I think a is true, because {1} is listed in A. c is the one giving me the most trouble, why is there two sets of brackets? What does it mean?
Comment: {{1}} means the set whose only element is {1}.
Comment: So what is {{1}} in correspondence to A?
Comment: A subset, because it is a set that contains  {1} as element, and you have asserted that it is also an element of A.
Comment: Sorry, I have a hard time with this, just to clarify, {1} is an element of A. {{1}} is the set consisting of {1} which is the set consisting of 1. And all 1, {1}, and {{1}} are elements as well in A?
Comment: No, {{1}} is not an element of A, it is a subset of A
Comment: Remember that sets can be elements too.  The outermost braces indicate that what it contains are listing or describing the elements in the set. The set $H=\{a,b,c\}$ contains the element $a$ as well as the element $b$ as well as the element $c$. This is regardless of whether $c$ is itself a primitive or a set itself. Here, $a$ is an element of $H$, $\{a\}$ is a subset of $H$ and $\{b\}$ is a subset of $H$. Now, if you replace $a$ by $1$, and replace $b$ by $\{1\}$ you have your original question.  It so happens that in this specific case $\{1\}$ is both an element and a subset, merely a fluke.
Answer: Consider the following variant of your question:
Let $A=\{1,\heartsuit,\{2\}\}$. Which statements are true? a) $\heartsuit$ is an element of $A$ b) $\{1\}$ is a subset of $A$ c) $\{\heartsuit\}$ is a subset of $A$
I think you'll agree that all three statements are pretty clearly true. Indeed, b) and c) are almost identical questions: $1$ and $\heartsuit$ are different objects, but that difference has no bearing on whether b) and c) are true. (And, for that matter, $\{1,\heartsuit\}$ is also a subset of $A$.)
Now your actual question is exactly the same as this question, except with $\heartsuit$ replaced by $\{1\}$ (so that, in particular, $A=\{1,\{1\},\{2\}\}$). Again, all three statements are true; and again, b) and c) are almost identical: $1$ and $\{1\}$ are different mathematical objects, but that has no bearing on the fact that both $1$ and $\{1\}$ are elements of $A$, and therefore both $\{1\}$ and $\{\{1\}\}$ are subsets of $A$. (And, for that matter, $\{1,\{1\}\}$ is also a subset of $A$.) The fact that there is some relationship between the two objects $1$ and $\{1\}$ is irrelevant to the question!
Clearly the question was designed to be a little confusing (so don't feel bad about that); remember that confusion that makes us understand better after we're done being confused is really helpful to our learning.


How to display 2 phrases in a single line , one center aligned ,the other right aligned in html?

Question: I want to display the following heading line in HTML:
                         Hello World                  HTML Example

"Hello World" is center aligned while "HTML Example" is right aligned.
Which HTML element should I use?
I've tried using span element and the display:inline css style but the two phrases always display in two separate lines.
HTML
 Hello World  HTML Example

Answer: Hopefully it's what you're trying to achieve:

 Hello World  HTML Example

Good luck!
Answer:
 Hello World  HTML Example


RDFa output and Panels

Question: I need to get RDFa working with Panels.  As it currently stands, fields output with panels or panelizer will have their property fields set correctly.  You can see an example of this at http://schema.org/Product when you look at the bottom and view RDFa output.
The part that isn't working is getting all of the properties to be wrapped by their proper type, in this case Drug.  So at some point, all of the output fields need to be contained within a wrapper that has the attribute typeof="Product".
Panels has no support for this, but you can see an example of what it would look like if you looked at some sample node output.  The node container wrapper would look something like this.

That's your typical RDFa output when rendering output with node.tpl.php.  Panels doesn't use this though, so it never gets rendered.
I'm hoping someone out there has dealt with this situation.  Structured data is pretty common to see these days, and so is the use of Drupal with Panels.  Someone has to have tackled this problem before, and I'm just looking for the best solution possible at this time.  Thanks.
TL;DR: What is the best way to get RDFa working with Panels?  Specifically, getting the typeof property added to some wrapper element which contains all of the other properties.
Answer: This is a known issue, and something I'm hoping to tackle at some point in the next couple of months: https://drupal.org/node/1485074 (see in particular comments #5 and #8). Feel free to subscribe to that issue as well.
Comment: I did end up browsing through that thread, forgot to follow though.  Thanks Scor.

RDFa output and Panels


I have a following mistake: PG::UndefinedColumn: ERROR: column students.year_course_id does not exist LINE 1

Question: Change my code! I have a following mistake: PG::UndefinedColumn: ERROR: column students.year_course_id does not exist LINE 1: SELECT COUNT() FROM "students" WHERE "students"."year_cour... ^ : SELECT COUNT() FROM "students" WHERE "students"."year_course_id" = $1
Answer:
PG::UndefinedColumn: ERROR: column students.year_course_id does not
  exist LINE 1: SELECT COUNT() FROM "students" WHERE
  "students"."year_cour... ^ : SELECT COUNT() FROM "students" WHERE
  "students"."year_course_id" = $1

Error clearly states that year_course_id column does not exist in students table.
Create it to resolve the issue.
When you specify
class Student < ActiveRecord::Base
  belongs_to :year_course
end

you would need to add year_course_id field in students table referencing year_courses table.
UPDATE
Here is how you can add year_course_id column in students table by generating a migration:
rails generate migration AddYearCourseRefToStudents year_course:references

After this run rake db:migrate
Comment: `@year_courses.students` would not work unless you have `year_course_id` in `students` table. See my updated answer of how to add it.
Comment: Whether it is possible to solve on another this problem? To replace these lines with others:@student_count = @year_courses ?...
Comment: I have in the table students a field course_id and I corrected it,
Comment: Did it work then? If not, what is the error that you get? Also, share the schema of `students` table from `schema.rb`. Add it in the question.
Comment: <%= f.text_field :stud_count, @student_count %> - How it is correct to write this line.
Comment: What is the error that you get now? Is your actual issue `PG::UndefinedColumn: ERROR: column students.year_course_id does not exist ` gone?
Comment: I solve this problem. I have field course_id in table Students. And I change this field from year_courses to @courses ?
Answer: Kirti's answer is correct in that you definitely need to have an id column in the respective, referencing model, however, if you've already got that in place but still getting the error (like myself), here's how I resolved it:
I found saw that I was trying to delegate a different name to the column association in my model, which was tripping this up for some reason. Namely, I had:
has_many :document_doc_types, as: :doc_types

and Rails was barfing with a similar error to what you posted. After I removed the 'as: doc_types' portion, all was well again. So, this works as expected:
has_many :document_doc_types

Hope this helps.


Trouble storing PHP variables

Question: to start I consider myself in between beginner and intermediate when it comes to PHP.  On my website, I have a textarea that the user can input web code in and when a button is pressed, it sends the code to the page and displays the output.  Here is the link to the page: http://opensourcewebsite.host22.com/editpage.php. Another problem that I am running into is that I want whatever the user enters to stay on the page.
Here is what the code looks like so far:
<?php $source_code = $_POST['source-code'}; ?>
...
<editable_area>
<?php echo $source_code ?>
</editable_area>
...
<form action="" method="post">
input class="result" type="submit" name="submit" value="View Result">
<textarea id="source" class="edit_are" name="source-code"></textarea>

Currently, when a user inputs code containing  an id/class/name/etc. that has quotes in it, it is like when you do:
echo "
"

It will add the \" and thus messing up the code.  I need to find a way to store the code so that it will display correctly.  If you try the web page, you will see my issue first hand.

When the code is submitted, the textarea grabs the source code of the web page through javascript.  I have discovered that if you leave out the "" in the code, it works as expected. The problem is that when it grabs the source code, there is quotes in it so the code will display them in the textare. This means every time you make a change, you need to take out all of the quotes.

Thanks to webbiedave, I fixed the quote problem by using:
<?php echo stripslashes($source_code) ?>

Now I just need to figure out how to permanently store changes.
Comment: Do you have sick thing called `magic_quotes_gpc` turned on?
Comment: http://php.net/manual/en/security.magicquotes.php May need to turn this off.
Comment: wow you are just asking for all kinds of trouble with a page like this.  This kind of page is exactly what spammers want to create XXS injection attacks.  make sure that you at least strip `
Comment: I do not have magic_quotes_gpc turned on.  I realize the concern thenetimp, but this is page is not finished yet.  There will be a log-in system and only that user can change the page.  The textarea does not edit outside of the  tag.
Answer: Check if you have magic quotes turned on and make sure you turn them off. Also, you'll want to use htmlspecialchars to escape the special characters. Otherwise, they can just close your textarea and wreak other havoc.
echo htmlspecialchars($source_code);

Comment: I tried changing the code to what you suggested, but when I put in the following code:

It swrites that exactly on the page.
Answer: <?php echo htmlentities(stripslashes($source_code)) ?>

Comment: This worked to an extent, except that it displays the tags on the page instead of reading them. It still didn't fix the quotes.
Comment: have you tried using stripslashes or addslashes to escape the quotes or unescape them?
Comment: I just tried that and it got rid of the slashes but it still displayed the code and not the correct output.  So, I just put stripslashes() and it worked.  Not sure if this is what you meant but it still worked.
Comment: whatever works :D I can't see the output that's why I recommend trying out `stripslashes` or `addslashes`
Answer: Can you use single quotes instead:
    '
';
Comment: That would normally work but that is not how the variable is stored.
$source_code gets its value by reading what is in the textarea

Trouble storing PHP variables


Style BasedOn suddenly not working

Question: These simple styles just stopped working out of the blue. They worked fine until today.

These both shows errors on the BasedOn property.
The resource "{x:Type TextBlock}" could not be resolved.
The resource "{x:Type TextBox}" could not be resolved.

If I copy and pase one of the styles right next to itself, there is no error on the pasted style.

Comment: It turns out the only difference is the existence of a key `noErrorOnThisStyle`?
Comment: Yes. Simply declaring the Style a few lines above or below makes the error disappear. Also note that for two similar Styles based on a TextBox, one says TextBox could not be resolved and the other doesn't.
Comment: i have the same problem when the type is stackpanel . I am also using vs 2012 update3
Answer: In fact in your case the BasedOn attribute is not needed. Just write

When BasedOn is not set, BasedOn point to the default style of the type specified by the TargetType attribute.
Regards
Claude
Comment: That doesn't answer why it stopped working just now. The code worked fine for YEARS. I installed VS2012 Update 3 recently.
Comment: The default style is not the same as the current style however and afaik `BasedOn="{StaticResource {x:Type TextBlock}}"` uses the current style.
Comment: If I change the default style for TextBlock, then I have to use BasedOn to descend from it. However, if you do not change the default style, BasedOn is not needed.

Style BasedOn suddenly not working


For every two points, that are not equal in $R^n$ it's possible to find neighbourhoods,such that they don't intersect

Question: I want to show, that for every two points, that are not equal in $R^n$ it's possible to find neighbourhoods,such that these neighbourhoods don't intersect
My idea: let distance between points is equal to $d(p,q) = \epsilon$.
Then let's take neighbourhood around points $p$ and $q$ with the radius $\dfrac{\epsilon}{2}$: $U_{\dfrac{\epsilon}{2}}$, $V_{\dfrac{\epsilon}{2}}$.
So it means, that radius of each is equal to $\dfrac{\epsilon}{2}$. And because neighbourhoods are open, hey don't intersect each other:
$d(p,r_1) < \dfrac{\epsilon}{2}$ ;$d(q,r_2) < \dfrac{\epsilon}{2}$
So: $d(p,r_1) + d(q,r_2) < \epsilon$
But it seemse to easy and trivial. Is my proof correct?
Comment: The idea is right - the proof is formally not sufficient. Assume there exists $x\in U\cap V$ and lead this to a contradiction.
Comment: The proof of them not intersecting each other is not clear from what you have written. You should assume that there is a common point, and then come up with a contradiction.
Comment: yes, this idea is correct
Answer: Let $x$ and $y$ be points in $\mathbb{R}^n$, where $\mathbb{R}^n$ has the standard Euclidean metric imposed on it and $x \neq y$.
Suppose $d(x, y) = \epsilon$, put $U =B_{(\mathbb{R}^n, d)}(x, \frac{\epsilon}{4}) $ and$V=B_{(\mathbb{R}^n, d)}(y, \frac{\epsilon}{4}) $.
Now assume $U \cap V \neq \emptyset$. Pick $z \in U \cap V$, then $d(x, z) < \frac{\epsilon}{4}$ and $d(z, y) < \frac{\epsilon}{4}$ and by the triangle inequality we have $d(x, y) = \epsilon \leq \frac{\epsilon}{4} + \frac{\epsilon}{4} = \frac{\epsilon}{2}$ a contradiction. Hence $U \cap V = \emptyset$. $\square$.

Note that this result actually holds for general metric spaces.
Comment: With slightly more work (to keep track of when you have strict inequality) you can adapt this proof to the idea in the question, where we take neighborhoods with radius $\epsilon/2.$ But I recall making a habit of choosing $\epsilon/3$ in such cases in order to avoid the extra effort.


rule to remove "Public files directory Not fully protected" in nginx?

Question: I use D7 with nginx and php5-fpm on Linux and get this security warning:

Public files directory Not fully protected

I see here that one needs to use this snippet in Apache's htaccess to resolve the issue:
# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</files>

Just wondering what should be the nginx equivalent rule?
Update: I already have this in my nginx configs:
root   /path/to/drupal;
}

location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
                return 404;
        }
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
}

Comment: I have this strange suspicion that Drupal may test for specific rules, not for their effect. Of course I;ll be glad to know if I'm wrong.
Answer: The .htaccess file won't have any effect in Nginx. You'll need to add your own rules to prevent PHP execution in the files directory.
e.g:
# Allow access to index.php only
location = /index.php {
  include fastcgi.conf;
  fastcgi_pass    127.0.0.1:9000;
}

# Any other attempt to access PHP files returns a 403.
location ~ \.php$ {
  return 403;
}

However, to fix that error message, you can actually just delete the old .htaccess file and Drupal will recreate a new correct one.
Note: the check is in system_requirements with the line
if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {

It only checks for that line, Drupal doesn't currently validate an actual PHP request to the relevant directory to test the handler.
Comment: @Molot, indeed. It appears the check is in [`system_requirements`](https://api.drupal.org/api/drupal/modules%21system%21system.install/function/system_requirements/7) with the line `if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {` It only checks for that line, Drupal could instead for example, create and request an arbitrary PHP file in the files directory to validate access.
Comment: So, was I right to guess that Drupal tests for the presence of `.htaccess`, not for the safety itself? :(
Comment: @David I have a more complicate rule. Just not sure if that suffice. Please see the updated question.
Comment: Consider adding this to your answer - comment by @Godo shows it's confusing and people may expect that if config is OK, warning will disappear.
Comment: @Molot, I was not confused about role of .htaccess in nginx. I just wanted to make sure that my nginx configs is secure enough with respect to these vulnerabilities.
Comment: You can also use:   `location ~* ^/sites/default/files/(.+\.php)$ { return 403;  }`


How do I recreate the system.site configuration element?

Question: For some reason system.site, system.performance and system.date config values have been deleted from our site.
I have the original configuration files, but when attempting to import those using drush cim, Drush complains about the site UUID mismatch.
The import failed due to the following reasons:
Site UUID in source storage does not match the target storage.

I assume this is because UUID is missing entirely. If I run drush cget system.site, I get the following error:
[error]  Config system.site does not exist

Attempting to set the UUID with drush config-set "system.site" uuid "my site id" also fails with:
[error]  Config system.site does not exist

So now I'm in a bit of conundrum.
Any suggestions on how to restore the system.site configuration?
Answer: I solved it with Drush.
To get around the UUID mismatch I uncommented the UUID field in system.site.yml and ran drush cim. After that I specifically set the UUID by running drush cset "system.site" uuid "my site id".


Child Expanders raising Parent Expander's Expanded and Collapsed Events?

Question: For some reason, child Expanders (placed in a StackPanel inside of another Expander), when collapsed or expanded, cause the parent Expander to raise its Expanded or Collapsed events.
Anyone know why this is or how I can change it? I'm only interested in the parent's events.
Here is some test XAML:
    <Expander Header="Outer" Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
        <StackPanel>
            <Expander Header="Inner1">
                <Canvas Height="100" Width="100" Background="Blue" />
            </Expander>
            <Expander Header="Inner2">
                <Canvas Height="100" Width="100" Background="Red" />
            </Expander>
        </StackPanel>
    </Expander>

and here is the code-behind:
    private void Expander_Expanded(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("expanded");
    }

    private void Expander_Collapsed(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("collapsed");
    }

When you run this, if you expand the parent, you get an "expanded" messagebox, as you'd expect. But when you then expand one of the children, you get the messagebox again.
The documentation for the Expanded event says:

The Expanded event occurs when the IsExpanded property changes from false to true

But clearly the IsExpanded property isn't changing on the parent Expander.
Why is this happening, any ideas?
Answer: Those events are routed and bubble up in the tree, if you want to prevent the parents from handling the event and thus reacting to it, set e.Handled to true in the child expander's event handler.
Edit: Instead of preventing the event from being raised you also could just restrict the code-execution in the handler to the case when the actual expander where the handler is attached raised the event. You can do this by wrapping everything in an if-block which executes if sender == e.OriginalSource.

(Woo, 10k...)
Comment: @ Haris Hasan - make sure you're setting `e.Handled = true` in the child expander's event, not in the parent expander's event.
Comment: Ah ok. I didn't realize that type of event would get Routed that way. Makes sense for mouse/keyboard interaction when it actually does impact the parent as well... but expanded seems an odd choice to be routed that way. Thanks for the response, H.B.
Comment: Indeed, i once programatically created a tree made up of expanders and the children just would not expand as expected due to this.
Comment: Haha. I'm sure that was frustrating (as was this). Congrats on the 10k. I'm trying to work my way there!
Comment: To be clear, just because it's a routed event doesn't mean it bubbles up the visual tree. Bubbling is one of three routing stratagies, which also include Direct (more like CLR events) and Tunnel (routes down the visual tree).
Comment: @H.B. - Oh, and congrats! :-)
Comment: @CodeNaked: Thanks! You are of course right and i am aware of the different strategies, i removed the implied inference `RoutedEvent => Bubbling`, you'd be welcome to directly edit my answers yourself if you see such inaccuracies.
Comment: @Markus Hütter: A *Danke* to you as well :D


How can I get the Operations Link Field back?

Question: I have a custom entity created in code which displays list in collection route. I decided to use a view to show this collection.

I created a new view of type 'Product' (Views shows my custom entity)
I added the fields I need to display
then searched for Operations Links (to add the edit, delete menu)

but it wasn't showing. I can confirm I've used this before in a view of custom entities.
Wat magic do I need to do here?
Answer: I had deleted the "list_builder" handler from my custom entity's annotations - thinking I didn't need a list builder since I was using a Views handler. Well, turns out that was the problem. The "Operations" link in views came back after I reinserted the list builder handler in my custom entity.


Missing "view mode" permission in core

Question: Context

Drupal 8
Switching to Drupal for intranet site in large organization

Background
OtraganixLocker Corporation is switching to Drupal from a custom-made home-grown intranet site. They want to use D8.
The problem is, the old custom-made intranet had the following permissions for
(its equivalent of) D8 nodes:

add content
edit own content
edit any content
delete own content
delete any content
view own content
view any content

Moreover, the granularity of the permissions worked down to the "content-type" level on the old intranet.
Moreover, the granularity of the permissions on the old intranet permitted user-based-assignment as well as role-based-assignment.
Question
Drupal 8 seems to be missing the view own content and view any content permissions that the old intranet system had.
Moreover, there seem to be a lot of ways to handle this, at least in D7.

Is this missing functionality accounted for in D8 core and simply missing from the front-end interface, or is it also absent from D8 core?
If it is not absent from D8 core, which specific function or functions in the D8 API account for this functionality?

See also

Blog post detailing the lack of granularity issue
Blog post addressing lack of granularity issue in D8
Comment: Hi, your 2nd question needs to be asked on drupal.org as we don't engage in that sort of speculation here; as a Q+A site we're looking for questions with objective, definitive answers, rather than the more opinionated/discursive/ephemeral stuff. I'm struggling to understand what you mean by your first question, could you clarify what you're asking for?
Comment: **//I'm struggling to understand what you mean by your first question, could you clarify what you're asking for?//** Sure the question was blocked from modification by someone, so it was impossible to clarify. Now it looks like that block has been wisely revoked, so the question can now be updated.
Comment: @Clive: Hello, the question text has been clarified. If there are any further questions or comments, feel free to leave them here and they will be addressed at the earliest opportunity. Thanks for your participation on StackExchange.
Comment: Nope looks good to me, re-opened. Is there an implied 3rd part to the question too? Along the lines of "if it is absent from D8 core, how can I achieve it?" Or are you fact-finding rather than fixing?
Comment: **//Or are you fact-finding rather than fixing?//** Good point in asking this. The D8 Core API has numerous functions that can be used for this functionality, so much that it would be impossible to enumerate them all. For example, at this point a developer has to decide if she wants to use the Drupal hook_ system, or switch to the Symfony Event Model. The hook_ system is the most pervasive but is also not technically "object oriented" ... so there are trade-offs. You might say it is a question of both fact-finding and fixing, but it depends on numerous factors.
Answer: The node access control methods between Drupal 7 and Drupal 8 are largely the same and described in Node access rights.  There are still the same hooks, just some of the plumbing is different.
So, if you want to implement the Drupal 6 fine grained access in Drupal 8, you can either do hook_node_access() or proper grants.  Remember, node usage can exist in case other than the node pages (eg, lists); the node access system takes care of this.  Work has begun on the ACL module and dependencies which provide some abstractions for these.
Drupal 8 also has a new concept for route access.  It uses classes that implement AccessInterface, and then use YAML configuration for providing the requirements for the route.  Looking at how routing is set up for the code node module (which defines the Node entity), may be the best starting point for delving into this, though it uses the same Access classes as the node acccess system.  I think explaining it here may be too much.
Comment: Someone feel free to either correct or post a better answer in relation to `AccessInterface`; my memory is fuzzy here.
Answer: There is a module doing exactly that https://www.drupal.org/project/node_view_permissions.

Missing "view mode" permission in core


Closed-form formula for inverse of this function

Question: I need to find the inverse of the expected value of the continuous Bernoulli distribution. Here is the formula:
$$
\frac{x}{2x-1}  + \frac{1}{2\tanh^{-1}(1-2x)}
$$
Is there a simple closed-form formula for inverse of this function?
Comment: [I doubt it.](https://www.wolframalpha.com/input/?i=inverse+of+%28x%2F%282x-1%29%2B1%2F%282*tanh%281-2x%29%29)
Comment: @EricTowers, I plotted the function, and seems increasing, and so injective, where I'm doing wrong?
Comment: @enzotib : I see one problem: I fat-fingered the function so was looking at the wrong plot.  Sorry.
Comment: @K.defaoite  You plotted the wrong function. The denominator in the second term is "Arctanh" but you entered  "tanh" instead.
Comment: [Ok.](https://www.wolframalpha.com/input/?i=inverse+of+%28x%2F%282x-1%29%2B1%2F%282*arctanh%281-2x%29%29)
Answer: Your formula is the function term of an elementary function.
This function doesn't have partial inverses that are elementary functions.
$$\text{arctanh}(x)=\frac{1}{2}\,\ln(x+1)-\frac{1}{2}\,\ln(1-x)$$
$$\frac{x}{2\,x-1}-\frac{1}{2\,\text{arctanh}(2\,x-1)}$$
$$\frac{x}{2\,x-1}-\frac{1}{2\,(\frac{1}{2}\,\ln(2\,x)-\frac{1}{2}\,\ln(2-2\,x))}$$
$${\frac{-x\ln(x)+x\ln(1-x)+2\,x-1}{(2\,x-1)(-\ln(x)+\ln(1-x))}}$$
This is the function term of an elementary function of $x$. It's the function term of an algebraic function over the algebraic numbers of $x$, $\ln(x)$ and $\ln(1-x)$. If Schanuel's conjecture is true, the transcendence degree of $\{x,\ln(x),\ln(1-x)\}$ over the algebraic numbers is 3. We cannot simplify the algebraic term of the three indeterminates to one with less than 3 indeterminates therefore. With help of the theorem in [Ritt 1925], that is proved also in [Risch 1979], we can conclude that the mentioned elementary function doesn't have partial inverses that are elementary functions.
$\ $
[Risch 1979] Risch, R. H.: Algebraic Properties of the Elementary Functions of Analysis. Amer. J. Math. 101 (1979) (4) 743-759
[Ritt 1925] Ritt, J. F.: Elementary functions and their inverses. Trans. Amer. Math. Soc. 27 (1925) (1) 68-90


How to translate this PAWN example to LUA?

Question: I have a new question for you all.
I am wondering if you're able to do enumerations within Lua (I am not sure if this is the correct name for it).
The best way I can explain this is if I show you an example using PAWN (if you know a C type language it will make sense).
#define MAX_SPIDERS 1000

new spawnedSpiders;

enum _spiderData {
    spiderX,
    spiderY,
    bool:spiderDead
}

new SpiderData[MAX_SPIDERS][_spiderData];

stock SpawnSpider(x, y)
{
    spawnedSpiders++;
    new thisId = spawnedSpiders;
    SpiderData[thisId][spiderX] = x;
    SpiderData[thisId][spiderY] = y;
    SpiderData[thisId][spiderDead] = false;
    return thisId;
}

So that's what it would look like in PAWN, however I don't know how to do this in Lua... This is what I got so far.
local spawnedSpiders = {x, y, dead}
local spawnCount = 0

function spider.spawn(tilex, tiley)
    spawnCount = spawnCount + 1
    local thisId = spawnCount
    spawnedSpiders[thisId].x = tilex
    spawnedSpiders[thisId].y = tiley
    spawnedSpiders[thisId].dead = false
    return thisId
end

But obviously it gives an error, do any of you know the proper way of doing this? Thanks!
Comment: This conversation doesn't solve the issue given in title "How to do enumerations in LUA?". Could it be modified to: "How to translate the PAW example to LUA?"
Answer: I don't know about PAWN, but I think this is what you mean:
local spawnedSpiders = {}

function spawn(tilex, tiley)
    local spiderData = {x = tilex, y = tiley, dead = false}
    spawnedSpiders[#spawnedSpiders + 1] = spiderData
    return #spawnedSpiders
end

Give it a test:
spawn("first", "hello")
spawn("second", "world")

print(spawnedSpiders[1].x, spawnedSpiders[1].y)

Output: first  hello
Answer: Something like this?
local spawnedSpiders = {}
local spawnCount = 0

function spawn_spider(tilex, tiley)
    spawnCount = spawnCount + 1
    spawnedSpiders[spawnCount] = {
      x = tilex,
      y = tiley,
      dead = false,
    }
    return spawnCount
end

EDIT: Yu Hao was faster than me :)
Comment: `spawnCount` can be replace with `#spawnedSpiders`
Comment: @hjpotter92 For simplicity, yes, like in Yu Hao's answer. If there is a *lot* of spiders it will be slightly less efficient though because the length operator `#` is `O(log n)`. But the real reason I didn't do it is I wanted to stay close to @Bicentric's code (avoid introducing another concept).
Comment: Aha that's okay! It's what I was looking for anyway :3


How to create a preconfigured block/view.

Question: I am looking for a way to create a view/block that is styled with CSS by myself, that can have content uploaded by an administrator, that will automatically use the same styles.
So it is easy for the admin to add content repeatedly that will automatically through my preconfiguration layout with the CSS as I have styled it.
I thought maybe I could create a content type then run it through a view and place that view on the page that I need it. I this case it is an Image/Icon with a link and text description, so the admin can upload the content easily and it will layout as I have styled it without them needing to write any CSS.
Thanks
Ant:-)
Answer: Yes I could work with a specific content type and views.
an alternative way is to create a module with a specific form to change the content block, and to add the content to the block API.
1 _ add your admin path
function my_module_menu() {
 $items['content_block'] = array(
  'menu_name' => 'main-menu',
  'type' => NORMAL_MENU_ITEM,
  'title' => 'My content block',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_form'),
  'access arguments' => array('admin_content_block'),
 );
 return $items;
}

2 _ Set your permission
function my_module_permission() {
 return array(
  'admin_content_block' => array(
      'title' => t('Can change content block'),
  ),

}

3 _ A form dedicated to your admin, allowing to change the content :
function my_module_form($form, &$form_state){

$form['block_content'] = array(
   '#type' => 'textarea',
   '#title' => t('Block Content'),
    '#default_value' => variable_get('my_module_block_content', ''),
);
$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
);

return $form;
}

function my_module_form_submit($form, &$form_state) {
   variable_set('my_module_block_content', $form_state['values']['block_content']);
}

4 _ your block view
function my_module_block_info() {
$blocks['block_content'] = array(
  'info' => t('Block Content'),
);
return $blocks;
}

function my_module_block_view($delta = '') {
if ($delta == 'block_content') {
    $block['subject'] = t('Your block title');
    $block['content'] = variable_get('my_module_block_content', '');

    }
return $block;
 }

Comment: Can you explain a little bit more about doing it through content and views, do you just create the content type with specific fields then channel it through a view and ouutput through the block?
Comment: It works with content type & views and the way you suggest it is correct. But I think that code that I written (see above) is better (lighter).


Alternative proofs of the remainder theorem for polynomials

Question: The theorem I've been tasked with proving is that for any polynomial function $f:\mathbb{R} \to \mathbb{R}$ and any $a \in \mathbb{R}$ there exists some polynomial $g:\mathbb{R} \to \mathbb{R}$ and some $b \in \mathbb{R}$ such that $$f(x)=(x-a)g(x)+b.$$
Using induction on the degree of $f$, I came up with the following proof.

For the case $n = 1$, we have a first degree polynomial, i.e. $f(x) = cx+d$. So if we let $g(x)=c$ and $b=ca+d$, then we have $$(x-a)g(x)+b=c(x-a)+ca+d=cx-ca+ca+d=cx+d=f(x)$$
proving it for the base case. Now we assume that for any polynomial of degree $n$ the theorem is true, so we can represent $f$ in the form $f(x) = (x-a)g(x) + b$. Now, for a polynomial of degree $n+1$ we have
$$\begin{align}
f(x) &= a_{n+1}x^{n+1}+a_nx^n+\cdots+a_0 \\
     &= x^n(a_{n+1}x+a_n)+a_{n-1}x^{n-1}+\cdots+a_0 \\
     &= x^n[(x-a)g_1(x)+b_1]+(x-a)g_2(x)+b_2 \tag{By hypothesis} \\
     &= x^n(x-a)g_1(x)+(x-a)g_2(x)+(b_1x^n+b_2) \\
     &= (x-a)x^ng_1(x)g_2(x)+(x-a)g_3(x)+b_3 \tag{By hypothesis}\\
     &= (x-a)x^ng_1(x)g_2(x)g_3(x)+b_3
\end{align}$$
so we let $g(x) = x^ng_1(x)g_2(x)g_3(x)$ and $b = b_3$, proving that it also holds in the $n+1$ case. $\square$

Does anyone know of any neater/cleaner/more enlightening proofs of this theorem? I'm particularly interested in seeing ones that don't use induction (I've seen one simpler proof  here: Proof of Remainder Theorem for polynomials).
Answer: Note that $x^k-a^k$ is divisible by $x-a$. For we have the familiar identity $$x^k-a^k=(x-a)(x^{k-1}+x^{k-2}a +\cdots +xa^{k-2}+a^{k-1}).$$
It follows that
$$\sum_{k=0}^n b_kx^k -\sum_{k=0}^n b_k a^k$$
is divisible by $x-a$.
Thus $P(x)=(x-a)Q(x)+P(a)$ for some polynomial $Q$.
Answer: Whatever way you turn the proof, your proof will be pointing at the quotient $g$ of Euclidean division of $f$ by $x-a$, whose coefficients depend on those of$~f$ in the usual long-division manner. This means some iteration or induction will be applied at some level anyway. There are different way to hide this though; the answer by André Nicholas explicitly gives the contribution to the quotient for each monomial, which can then be combined by linearity. Another way, essentially the answer referred to in the question, is to put $y=x-a$, expand  $f(x)=f(y+a)$ as a polynomial in$~y$, and let $b$ be its constant term.


Making sure edits work as intended before publishing

Question: I just wanted to pre-empt a situation that is highly likely to occur at some point in the future. I am going to be hosting a small online business using shared hosting. Obviously, once the website (which uses Drupal) is finalized and I take it out of maintenance mode, I want to keep it usable 99.99%. However at some point of time, I'll  probably wish to make some edit, add content or even make some reforms that will need some thorough testing. I know that there is a preview button but for some alterations this may not be enough, but I'd still like to avoid putting the site in maintenance. (Although for fixing bugs and critical updates I obviously would).
I'd appreciate your suggestions on how I could do this please. I assume it must be a common issue among online businesses?
Comment: You should look at creating another instance of the site for major development and after testing you can push the changes to the live site. For content addition I dont think this is needed. In case of contents you can always have to option to make it unpublished. And then when everything looks ok you can publish it.
Comment: @MohammedShameem Sorry for the slow reply and thanks. I think I will do that. If I use to test modules etc., and they work how do you suggest that I update the main site (bearing in mind that I can't use Drush)? And what do you recommend I do about the database for the staging site? Just clone the database of the original site?
Answer: The more or less standard solution is to maintain a so-called staging site (i.e. a mirror of your production site, but in a protected environment), and make all changes to the staging site before committing them to the production site.
The use of a staging site is not only limited to edits, but is also very useful when making more substantial changes, such as updating a module or adding a new module.  The staging site let you run detailed tests to make sure that changes does not "break" anything before committing to the main site.
You can use drush to simplify syncing content and configuration between the staging and production site.
Edit: By "protected environment", I mean some computer that is not available to outsiders on the Internet. It is typically only available for use by yourself (and your team if you're not working alone, but manage a team of developers). The standard way of protecting it is to use a firewall and only allow connections from the IP-addresses belonging to you (and your team members)
Comment: Sorry for the very slow reply and thank you for your answer. A staging site does make sense and sounds simple too so I think that this is what I will do. Unfortunately because I only have shared hosting I can't get access to the SSH so I don't think I can use Drush (if I'm right) so what's the next best solution?
Comment: Also, could you please clarify what you mean by a protected environment. A password protected directory? Thanks again
Comment: Ah I understand, so the staging site isn't actually hosted online. That makes a lot more sense. If I create a local version of the staging site on Ubuntu or something then it would be near impossible to access, and I can use Drush because I'll have root access. Thanks very much!


Why does a DPM protection group configured for Sync work for some databases in simple recovery model but not others?

Question: Using System Center Data Protection Manager 10.22.197.0 to back up SQL Server 2022 CU 10 on Windows Server 2022.   DPM agent is also 10.22.197.0 on these SQL servers.  The SQL Server instance was added to DPM protection.  Some of the databases on this SQL Server are in Simple recovery model, others in Full.  The protection group is set to do periodic Synchronization (every 15 minutes) as well as Express Full (1/day).  I realize that Synchronization should not work for databases in Simple recovery model, but in reality, for 3 of the 4 databases in Simple recovery mode, DPM just doesn't try to do Sync jobs for them; while for the 4th database it does try the Sync and fails with the normal error for that scenario ("Execution of SQL command failed for SQL Server 2022 database  on  with reason: BACKUP LOG is terminating abnormally.  The statement BACKUP LOG is not allowed while the recovery model is SIMPLE...").
Any ideas why DPM is treating these databases differently?  The only difference I've identified in the databases themselves is that the "working" ones are at compatibility level 150 and the "failing" one is at compatibility level 160.
thanks
Martin
Comment: @djdomi I'll try to remember that for next time...
Comment: if it is a Db specific problem I would suggest that you take a look at [dba.se]
Comment: @djdomi - ok, will try, thanks.
Comment: to do so, just flag your own question for movement and a link will be kept inhere and the transition is the easiest and will have no impact on reputation instead of crossposting
Answer: When a database is configured with the Simple recovery model, the only backup option available is a full backup. This is because the Simple recovery model does not support transaction log backups. Without transaction logs, synchronizing backups incrementally is not possible, as these operations rely on log data to capture changes since the last full or differential backup
Comment: That is understood - I said so in the question.  However, the same protection group has a number of databases configured in Simple recovery model, and for three of them there is no problem - DPM for some reason is not attempting the transaction log backups (apparently).  The question is, why is it treating these different databases differently, on the same SQL Server instance, using the same DPM protection group?


Como fazer algo expirar apos certos meses na db?

Question: Eu quero adicionar uma "licença" para uma compra na minha database, mais essa licença que o meu "cliente" irá comprar terá um prazo de expiração, vamos dizer que ele comprou uma licença...
    INSERT INTO compras (userid, pluginid) VALUES ('$userid', '$pluginid');

Agora, eu quero fazer com que esse INSERT que eu fiz se apague daqui a 1 mês, por exemplo, como faço isso??
Answer: dê uma olhada nesta resposta do SO.
now() + INTERVAL 3 DAY

enquanto NOW retorna a atual data e hora, INTERVAL adiciona um intervalo de tempo, veja no manual:
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Answer: Não faça esta deleção , crie uma coluna DATA_DE_VALIDADE , na aplicação teste algo como
select *
from compras
where userid = 'DaviDEV'
and   CURDATE() <= DATA_DE_VALIDADE

A vantagem é não se perde a informação permitindo até "correr atrás" do cliente para um retorno.
Comment: Mais na hora de fazer o INSERT, o que eu preencho no campo DATA_DE_VALIDADE?
Comment: Algo como ADDDATE(CURDATE(), INTERVAL 31 DAY) , ou seja a data de quando "caduca" a compra. No caso 31 dias da data corrente.
Comment: Tipo:
    INSERT INTO compras (userid, pluginid,expiracao) VALUES ('$userid', '$pluginid',ADDDATE(CURDATE(), INTERVAL 31 DAY));
??????
Comment: Sim, mas a coluna precisa existir na tabela , para isto veja ADD COLUMN emhttp://dev.mysql.com/doc/refman/5.7/en/alter-table.html
Comment: eu acho a sugestão do Motta melhor, nunca se deve descartar um histórico de compra de um cliente. até porque, se acontecer de seu sistema fornecer um mesmo numero de licença de um cliente que já a comprou, você pode se complicar
Comment: Não, estou usando so para absorver conhecimento, não tenho loja virtual nem algo do tipo.
Comment: então encare apenas como boas práticas!


Let's get critical: Mar 2014 Site Self-Evaluation

Question: We all love Magento Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
Answer: Final Results

Add Category tree in custom extension

Net Score: 11 (Excellent: 12, Satisfactory: 1, Needs Improvement: 1)

Do Billing Agreements even work with Paypal Payflow Pro?

Net Score: 10 (Excellent: 10, Satisfactory: 3, Needs Improvement: 0)

conditionally change layout template for catalogsearch

Net Score: 9 (Excellent: 10, Satisfactory: 5, Needs Improvement: 1)

Is there a recommended way to temporarily suspend ordering?

Net Score: 7 (Excellent: 7, Satisfactory: 8, Needs Improvement: 0)

Redirect to same product URL after error from Add To Cart

Net Score: 5 (Excellent: 7, Satisfactory: 4, Needs Improvement: 2)

how to add shipping method options

Net Score: 5 (Excellent: 6, Satisfactory: 7, Needs Improvement: 1)

How to change Magento's default date in calendar?

Net Score: 5 (Excellent: 6, Satisfactory: 6, Needs Improvement: 1)

flow of method call in payment method

Net Score: 1 (Excellent: 5, Satisfactory: 5, Needs Improvement: 4)

How to access custom table/attributes using the ORM?

Net Score: -1 (Excellent: 4, Satisfactory: 2, Needs Improvement: 5)

how to make dynamic two-column layout for custom options

Net Score: -3 (Excellent: 3, Satisfactory: 3, Needs Improvement: 6)


Limitations in Correlation Analysis

Question: Suppose I have the following dataset that shows the faculty composition of different colleges and the total number of drop outs that happened in an academic year.
Here is some R code for this problem:
set.seed(123)
n <- 100
college_id <- paste0("college_", 1:n)
percent_engineering <- runif(n, 0, 100)
percent_science <- runif(n, 0, 100 - percent_engineering)
percent_liberal_arts <- runif(n, 0, 100 - percent_engineering - percent_science)
percent_other <- 100 - percent_engineering - percent_science - percent_liberal_arts
number_of_dropouts <- sample(0:100, n, replace = TRUE)
number_of_students <- sample(200:1000, n, replace = TRUE)

df <- data.frame(college_id,
                 percent_engineering,
                 percent_science,
                 percent_liberal_arts,
                 percent_other,
                 number_of_dropouts, number_of_students)

df$drop_out_rate <- (df$number_of_dropouts/df$number_of_students)*100

I could be interested in trying to answer the following question: Is it possible that when colleges tend to be more engineering based are more correlated with larger dropout rates in general? (e.g. lets say I don't have access to the number of drop outs per faculty per college)
A very basic way to explore this question could be to calculate correlations between faculty compositions and drop out rates:
library(ggplot2)
plot_list <- list()
percent_cols <- c("percent_engineering", "percent_science", "percent_liberal_arts", "percent_other")

for (col in percent_cols) {
    # Calculate the Pearson and Spearman correlation coefficients
    pearson_cor <- cor(df[[col]], df$drop_out_rate, method = "pearson")
    spearman_cor <- cor(df[[col]], df$drop_out_rate, method = "spearman")

    # Create the scatter plot with a line of best fit
    p <- ggplot(df, aes_string(x = col, y = "drop_out_rate")) +
        geom_point() +
        geom_smooth(method = "lm") +
        labs(
            x = col,
            y = "Dropout Rate",
            title = paste("Relationship between", col, "and Dropout Rate"),
            subtitle = paste(
                "Pearson correlation =", round(pearson_cor, 2),
                "| Spearman correlation =", round(spearman_cor, 2)
            )
        )

    # Add the plot to the list
    plot_list[[col]] <- p
}

# Assign the plots to individual variables
g1 <- plot_list[["percent_engineering"]]
g2 <- plot_list[["percent_science"]]
g3 <- plot_list[["percent_liberal_arts"]]
g4 <- plot_list[["percent_other"]]

library(gridExtra)
grid.arrange(g1, g2, g3,g4 ,ncol = 2)

At first glance, this approach might be suitable to study correlations between total drop out rates and the composition of different faculties (e.g. engineering) - however, I think there might be some problems with this approach.
One of the first problems that comes to mind is that this approach is not taking into account the effect of other variables when calculating correlations. As a humorous example, perhaps Science Students and Engineering Students hate each other - and when a college has more than x% Science Students and y% Engineering Students, this results in fights and these fights result in drop outs. Thus, the patterns and trends that would be observed during this analysis between pairs of variables might not necessarily be only attributable to those pairs.
As such, I think it would be a better idea to fit a Regression Model to this data and then be able to find out the "average effect of each increase in faculty percent on drop out rate (adjusted over the other variables".
But as such, what are the limitations of performing and making conclusions from this type of correlation analysis?
Thanks!
Comment: Well, it still will be a correlational analysis. So, usual limitations still apply. Besides percent variables are functions of each other, and they add up to 100 (i.e., compositional data). So, you might have high collinearity for some them. In fact, if you include all percent variables, one would be dropped due to collinearity.
Answer: I think you've identified the most likely culprit of misleading conclusions from looking at bivariate correlations: confounding
However, performing a regression would only adjust for known and measured confounders in the data.  If a variable is omitted and that variable is correlated with drop out and faculty, then the analysis remains biased.

Limitations in Correlation Analysis


gluUnProject was working, then stopped working

Question: This function was working when i was using glut that i downloaded from the opengl nvidia examples
void gl_select(int x, int y)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)x;
    winY = (float)viewport[3] - (float)y;
    glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    printf("%f %f %f\n", posX, posZ, posY);

    glutPostRedisplay();
}

but then i switched to free glut and now it's not working, can someone tell me why?
Comment: GLUT =/= GLUT =/= OpenGL. I think you got a few things mixed up in your mental model of the code.
Answer: Okay, I think I can guess your problem: You're probably calling gl_select from an input event handler. Now here's the thing: When you read pixels from the main framebuffer, you may actually never get any sensible value. Why? Because the operating system may decide "uh, that part is not visible anyway, so why bother processing it" (this is called the pixel ownership test). Furthermore the contents of the main framebuffer can become lost anytime (damage event).
Well, and then glReadPixels reads from the framebuffer selected for reading. If that is the back buffer and you access it after a buffer swap, the contents are undefined as well (for colours). The depth component of the framebuffer also get corrupted by a swap.
So, if glReadPixels is so unreliable, you may think, how to use it? Well it's not glReadPixels that unreliable, it's just the window framebuffer that's volatile. So you should not use that. Instead, if you want to do pixel space depth selection, you should render first to an FBO, and then copy that to the main window framebuffer. The contents of FBOs are asserted to not get lost. So you can read from an FBO at any time, being sure you get what you asked for.
Furthermore you should not rely on what's in the matrix stack when you call gl_select. Instead you should make snapshot copies of the projection and the modelview matrix in the display code, in the state that represents the transformations as which they apply for the selection.


Two line of text and overflow is dotted

Question: Is there any way to display text in two line and overflow is dotted?
I can use
white-space: nowrap;
text-overflow: ellipsis;

But it show the text in one line. I need to show my text in two line and if overflow text then it should show dotted end.
Comment: This may help: https://stackoverflow.com/questions/15909489/text-overflow-ellipsis-on-two-lines?rq=1
Answer: Working CSS solution for Chrome, Safari and Opera is:
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;

You can change 2 to any number. It will show X number of text and dots at the end
line-clamp is not supported by all browsers. https://caniuse.com/#search=line-clamp
Comment: Is there any solution for firefox??
Comment: As I know there is no elegant and pure CSS solution for FF. It can be something like this https://codepen.io/romanrudenko/pen/ymHFh
Comment: @VictorLeontyev You must have  also included the browser support for line-clamp.
Answer: At css set width of element, white-space to pre

div  {
  font-size: 1em;
  display: inline-block;
  width: 2em;
  white-space: pre;
  text-overflow: ellipsis;
  overflow: hidden;
}

lines of
breaks

Answer: Remove White-space Property and use a height of the element

Two line of text and overflow is dotted


Prove $\sum_{0}^{n}(-1)^i\binom{n}{i} = 0$

Question: I have to prove that $\sum_{0}^{n}(-1)^i\binom{n}{i} = 0$,
I know i have to use the binomial theorem,But i dont know how.
Thanks.
Comment: Use the binomial theorem to expand $(1-1)^n$.
Comment: thanks, i solved it successfully using your help.
Comment: Have you tried induction?
Comment: I have to prove it with binomial theorem.
Comment: @user296113 What do you mean ?
Comment: Apply the binomial theorem $(a+b)^n$ for $a=1$ and $b=-1$.
Comment: Possible duplicate of [Alternating sum of binomial coefficients](http://math.stackexchange.com/questions/176622/alternating-sum-of-binomial-coefficients)
Comment: Possible duplicate of [Proving $\sum\limits_{k=0}^{n} (-1)^{k} \binom{n}{k} = 0$](http://math.stackexchange.com/questions/94514/proving-sum-limits-k-0n-1k-binomnk-0)
Answer: $$ 0 = \bigl((1+ (-1)\bigr)^n = \sum_{i=0}^n \binom ni 1^{n-i}(-1)^i = \sum_{i=0}^n \binom ni (-1)^i $$
Answer:
The Binomial Theorem: $$(x+y)^n = \sum\limits_{i=0}^n \binom{n}{i}x^{n-i}y^i$$

For example $(x+y)^4 = x^4+4x^3y+6x^2y^2+4xy^3+y^4$
Using the above, notice what happens when $x=1$ and $y=-1$
$0=(1-1)=(1+(-1))^n=\sum\limits_{i=0}^n\binom{n}{i}1^{n-i}(-1)^i=\sum\limits_{i=0}^n\binom{n}{i}(-1)^i$
In general, with other sums like this, one can throw in additional factors of $1$ to an arbitrary power to notice the pattern.
For example, $\sum\limits_{i=0}^n\binom{n}{i} = \sum\limits_{i=0}^n\binom{n}{i}(1)^i(1)^{n-i} = (1+1)^n = 2^n$


Want to capture grep counts for a command output

Question: I would like to count the occurrence of word ERROR by using command:-

mysql -B -u root -pxxxx -h abc -e show databases | grep -c "ERROR"

However my understanding says it should return 1 however it is returning it as O
Why ?
Also please let me know the significance of mysql -B and -e
Thanks,
Ruchir
Comment: To understanding the significance of `-B` and `-e`, try `man mysql` or `mysql --help`.
Comment: Can you provide an example of grep's input?
Answer: Errors go to the standard error (stderr) by default, so you need to redirect it to standard output (via 2>&1). In which case grep can process them:
mysql -B -u root -pxxxx -h abc -e show databases 2>&1 | grep -c "ERROR"

Comment: Only be careful that multiple `ERROR` on a single line are counted as one.
Comment: Or you can use  `|&` as a shortcut for ` 2>&1 |` (Bash 4.0)
Comment: Yes, it is better `grep -o "ERROR" | wc -l`.


É possível um "Group by" por conteúdo da coluna?

Question: Estava a pensar, se era possível usar GROUP BY baseado na data de uma coluna, neste caso da coluna ANALYSIS que cria grupos sempre que encontra 0, invés da coluna.
<code>       DIA        MES       YEAR      TODAY   TOMORROW   ANALYSIS      LIMIT
---------- ---------- ---------- ---------- ---------- ---------- ----------
        19          9       2016        111        988          0        150
        20          9       2016        988        853        853        150
        21          9       2016        853        895        895        150
        22          9       2016        895        776        776        150
        23          9       2016        776        954          0        150
        26          9       2016        954        968        968        150
        27          9       2016        968        810        810        150
        28          9       2016        810        937        937        150
        29          9       2016        937        769        769        150
        30          9       2016        769       1020          0        150
         3         10       2016       1020        923        923        150
         4         10       2016        923         32         32        150
</code>
O que pretendia era o seguinte, com base neste exemplo:

Group 1 (Analysis): 0
Group 2(Analysis): 853, 895,776,0
Group 3(Analysis): 968,810,937,169,0
...
Comment: Por favor, traduza sua pergunta para o português.
Comment: ups, pensei que tava na english version, erro meu xd
Comment: É MySQL ou SQL Server? Se for SQL Server, qual é a versão?
Comment: oracle version 184.108.40.206(por isso digo possivelmente sql server) contudo o que interessa é o raciocinio
Comment: "4.0.3" provavelmente se refere ao Oracle SQL Developer, que não é o gerenciador de banco de dados mas sim IDE (integrated development environment) da Oracle.
Comment: Se não me engano Sql Developer usa Sql server, contudo nao sei a versão
Comment: Creio que nem com "analytic functions" pois a "quebra" é complicada. Como seria usada a saída ? Relatório ?
Comment: A forma mais simples de implementar o que solicita é através do uso de cursor. // Outra opção é adaptar o algoritmo _gaps and islands_: sequenciar as linhas usando ANO/MES/DIA como critério de ordenação  (de modo que não haja intervalo), retirar então as linhas com ANALYSIS = 0 e após procurar pelos intervalos.
Comment: Gaps and islands parece promissor
Comment: Ou tentar combinar lad and lead com listagg https://oracle-base.com/articles/misc/analytic-functions tentar obter o último zero.
Answer: Usando o metodo "start-of-group" é possivel fazer uma espécie de iterador.
<code>select
from   ( select tbl.*,
                count(case when analysis = 0 then 1 end)
                           over (order by year, mes, dia) as cnt
         from   tbl
       )
where  ...
GROUP BY cnt;
</code>
Este código não foi feito por mim. por isso um grande obrigado a Mathguy.