text:
Q: Android Dropbox, file created but not uploaded recently i try to play around with Dropbox android application integration
this application obtain user current location and automatically upload it to dropbox
The problem is that, i failed to upload the file.
Toast shows "there seems to be an error"
here's the main activity
  @Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("Location_Filename", Location_Filename);
    super.onSaveInstanceState(outState);
}

@Override
protected void onResume() {
    super.onResume();
    AndroidAuthSession session = mApi.getSession();

    // The next part must be inserted in the onResume() method of the
    // activity from which session.startAuthentication() was called, so
    // that Dropbox authentication completes properly.
    if (session.authenticationSuccessful()) {
        try {
            // Mandatory call to complete the auth
            session.finishAuthentication();

            // Store it locally in our app for later use
            storeAuth(session);
            setLoggedIn(true);
        } catch (IllegalStateException e) {
            showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
            Log.i(TAG, "Error authenticating", e);
        }
    }
}

// This is what gets called on finishing a media piece to import
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == NEW_LOCATION) {
        // return from file upload
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = null;
            if (data != null) {
                uri = data.getData();
            }
            if (uri == null && Location_Filename != null) {
                uri = Uri.fromFile(new File(Location_Filename));
            }
            File file = new File(Location_Filename);

            if (uri != null) {
                UploadLocation upload = new UploadLocation(this, mApi, LOCATION_DIR, file);
                upload.execute();
            }
        } else {
            Log.w(TAG, "Unknown Activity Result from locationImport: "
                    + resultCode);
        }
        }
    }

/**
 * Convenience function to change UI state based on being logged in
 */
private void setLoggedIn(boolean loggedIn) {
    mLoggedIn = loggedIn;
    if (loggedIn) {

        mDisplay.setVisibility(View.VISIBLE);
    } else {

        mDisplay.setVisibility(View.GONE);

    }
}

private void checkAppKeySetup() {
    // Check to make sure that we have a valid app key
    if (APP_KEY.startsWith("CHANGE") ||
            APP_SECRET.startsWith("CHANGE")) {
        showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
        finish();
        return;
    }

    // Check if the app has set up its manifest properly.
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    String scheme = "db-" + APP_KEY;
    String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
    testIntent.setData(Uri.parse(uri));
    PackageManager pm = getPackageManager();
    if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
        showToast("URL scheme in your app's " +
                "manifest is not set up correctly. You should have a " +
                "com.dropbox.client2.android.AuthActivity with the " +
                "scheme: " + scheme);
        finish();
    }
}

private void showToast(String msg) {
    Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
    error.show();
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a local
 * store, rather than storing user name & password, and re-authenticating each
 * time (which is not to be done, ever).
 */
private void loadAuth(AndroidAuthSession session) {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    String key = prefs.getString(ACCESS_KEY_NAME, null);
    String secret = prefs.getString(ACCESS_SECRET_NAME, null);
    if (key == null || secret == null || key.length() == 0 || secret.length() == 0) return;

    if (key.equals("oauth2:")) {
        // If the key is set to "oauth2:", then we can assume the token is for OAuth 2.
        session.setOAuth2AccessToken(secret);
    } else {
        // Still support using old OAuth 1 tokens.
        session.setAccessTokenPair(new AccessTokenPair(key, secret));
    }
}

/**
 * Shows keeping the access keys returned from Trusted Authenticator in a local
 * store, rather than storing user name & password, and re-authenticating each
 * time (which is not to be done, ever).
 */
private void storeAuth(AndroidAuthSession session) {
    // Store the OAuth 2 access token, if there is one.
    String oauth2AccessToken = session.getOAuth2AccessToken();
    if (oauth2AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        SharedPreferences.Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, "oauth2:");
        edit.putString(ACCESS_SECRET_NAME, oauth2AccessToken);
        edit.commit();
        return;
    }
    // Store the OAuth 1 access token, if there is one.  This is only necessary if
    // you're still using OAuth 1.
    AccessTokenPair oauth1AccessToken = session.getAccessTokenPair();
    if (oauth1AccessToken != null) {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        SharedPreferences.Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, oauth1AccessToken.key);
        edit.putString(ACCESS_SECRET_NAME, oauth1AccessToken.secret);
        edit.commit();
        return;
    }
}

private void clearKeys() {
    SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
    SharedPreferences.Editor edit = prefs.edit();
    edit.clear();
    edit.commit();
}

private AndroidAuthSession buildSession() {
    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);

    AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
    loadAuth(session);
    return session;
}

}
here is the Upload location class
public class UploadLocation extends AsyncTask<Void, Long, Boolean> {

    private DropboxAPI<?> mApi;
    private String mPath;
    private File mFile;

    private long mFileLen;
    private UploadRequest mRequest;
    private Context mContext;
    private final ProgressDialog mDialog;

    private String mErrorMsg;

    public UploadLocation(Context context, DropboxAPI<?> api, String dropboxPath,
                          File file) {
        // We set the context this way so we don't accidentally leak activities
        mContext = context.getApplicationContext();

        mFileLen = file.length();
        mApi = api;
        mPath = dropboxPath;
        mFile = file;

        mDialog = new ProgressDialog(context);
        mDialog.setMax(100);
        mDialog.setMessage("Uploading " + file.getName());
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);
        mDialog.setButton(ProgressDialog.BUTTON_POSITIVE, "Cancel", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // This will cancel the putFile operation
                mRequest.abort();
            }
        });
        mDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            // By creating a request, we get a handle to the putFile operation,
            // so we can cancel it later if we want to
            FileInputStream fis = new FileInputStream(mFile);
            String path = mPath + mFile.getName();
            mRequest = mApi.putFileOverwriteRequest(path, fis, mFile.length(),
                    new ProgressListener() {
                @Override
                public long progressInterval() {
                    // Update the progress bar every half-second or so
                    return 500;
                }

                @Override
                public void onProgress(long bytes, long total) {
                    publishProgress(bytes);
                }
            });

            if (mRequest != null) {
                mRequest.upload();
                return true;
            }

        } catch (DropboxUnlinkedException e) {
            // This session wasn't authenticated properly or user unlinked
            mErrorMsg = "This app wasn't authenticated properly.";
        } catch (DropboxFileSizeException e) {
            // File size too big to upload via the API
            mErrorMsg = "This file is too big to upload";
        } catch (DropboxPartialFileException e) {
            // We canceled the operation
            mErrorMsg = "Upload canceled";
        } catch (DropboxServerException e) {
            // Server-side exception.  These are examples of what could happen,
            // but we don't do anything special with them here.
            if (e.error == DropboxServerException._401_UNAUTHORIZED) {
                // Unauthorized, so we should unlink them.  You may want to
                // automatically log the user out in this case.
            } else if (e.error == DropboxServerException._403_FORBIDDEN) {
                // Not allowed to access this
            } else if (e.error == DropboxServerException._404_NOT_FOUND) {
                // path not found (or if it was the thumbnail, can't be
                // thumbnailed)
            } else if (e.error == DropboxServerException._507_INSUFFICIENT_STORAGE) {
                // user is over quota
            } else {
                // Something else
            }
            // This gets the Dropbox error, translated into the user's language
            mErrorMsg = e.body.userError;
            if (mErrorMsg == null) {
                mErrorMsg = e.body.error;
            }
        } catch (DropboxIOException e) {
            // Happens all the time, probably want to retry automatically.
            mErrorMsg = "Network error.  Try again.";
        } catch (DropboxParseException e) {
            // Probably due to Dropbox server restarting, should retry
            mErrorMsg = "Dropbox error.  Try again.";
        } catch (DropboxException e) {
            // Unknown error
            mErrorMsg = "Unknown error.  Try again.";
        } catch (FileNotFoundException e) {
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Long... progress) {
        int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
        mDialog.setProgress(percent);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        mDialog.dismiss();
        if (result) {
            showToast("Image successfully uploaded");
        } else {
            showToast(mErrorMsg);
        }
    }

    private void showToast(String msg) {
        Toast error = Toast.makeText(mContext, msg, Toast.LENGTH_LONG);
        error.show();
    }
}

Logcat

04-09 00:03:47.053: I/Main Activity(2010): Importing Location: /storage/sdcard/BEB.txt
04-09 00:03:47.053: I/ActivityManager(1230): START u0 {(has extras)} from uid 10056 on display 0
04-09 00:03:47.080: W/Main Activity(2010): Unknown Activity Result from mediaImport: 0
04-09 00:03:47.138: W/EGL_emulation(2010): eglSurfaceAttrib not implemented
04-09 00:03:47.138: W/OpenGLRenderer(2010): Failed to set EGL_SWAP_BEHAVIOR on surface 0xa51571a0, error=EGL_SUCCESS

Hope someone can help, its really bothering me
Much appreciated, thank you


text:
Q: Django template return all files in section Here my problem, The user can add Sections, in the section he can add documents, what I would like to do it's to return all documents added in section I can't figure it out which way is the best to filter by section:
Here my model for the Documents :
class Document(models.Model):
    """
    Staff of the hospital center services
    """

    # ATTRIBUTES
    label = models.CharField(
        max_length=255,
        verbose_name='Intitulé'
    )
    description = models.TextField(
        verbose_name='Description',
        blank=True,
        null=True
    )
    document = models.FileField(
        verbose_name='Document'
    )
    section = models.ForeignKey(
        'espace_documentaire.EspaceDocumentaire',
        verbose_name="Espace Documentaire",
        related_name="documents",
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )
    dedicated_page = models.ForeignKey(
        "pages.Pages",
        verbose_name="Page",
        related_name="documents",
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )
    division = models.ForeignKey(
        "services.Division",
        verbose_name="Pôle",
        related_name="documents",
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )
    order = models.IntegerField(
        verbose_name="Ordre d'affichage",
        default=0
    )

    # TRACE
    date_created = models.DateTimeField(
        verbose_name="date de création",
        auto_now=True
    )
    date_updated = models.DateTimeField(
        verbose_name="date de modification",
        auto_now=True
    )

    def __str__(self):
        return self.section

Here my Model for the Sections :
class EspaceDocumentaire(models.Model):

    # ATTRIBUTES
    section = models.CharField(
        max_length=255,
        verbose_name='Nom de la section'
    )
    colorsection = models.CharField(
        max_length=255,
        verbose_name='Couleur de la section'
    )
    order = models.IntegerField(
        verbose_name="Ordre d'affichage",
        default=0
    )
    document = models.ForeignKey(
        'documents.Document',
        verbose_name="Document",
        related_name="documents",
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )

    def __str__(self):
        return self.section

Here my template :
{% for ed in espace_documentaire %}

{{ed.section}}

            {% for document in documents %}
                {% if document.section == ed.section %}

{{ document.label }}

                {% endif %}
            {% endfor %}

{% endfor %}

Thanks

A: Here is how you would filter a single section documents in a view:
def section_documents(request, pk):
    section = EspaceDocumentaire.objects.get(pk=pk)
    documents = section.documents.all() # using related name you set in your model
    return render(request, 'section_documents.html', {'section': section, 'documents': documents})

Then in your template:
{% for document in documents %}
    {{ document }}
{% endfor %}

OR you could also just use the related name in the template like this:
def sections_and_documents(request):
    sections = EspaceDocumentaire.objects.all()
    return render(request, 'sections_and_documents.html', {'sections': sections)

and in the template:
{% for section in sections %}
    {{ section }}
    {% for document in section.documents.all %}
        {{ document }}
    {% endfor %}
{% endfor %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Recursion Overhead I have written a python program that solves Sudoku and want to make it faster. The core operation is a depth first search function which I implement as recursion. I thought I could eliminate the recursion overhead by re-writing the depth first search procedure as a loop which manages a data stack (simply a list); but it turns out that performance is not significantly different. I am pretty sure that the loop version is procedurally equivalent to the recursive version.
Is it because the data stack I use is not fast in pushing/popping? Or python interpreter really makes very good use of hardware? Can someone help me figure out what can be done?
Profiling is attached.
search_naked is the recursive function.
                      2446265 function calls (1813295 primitive calls) in 4.576 seconds

   Ordered by: internal time, cumulative time
   List reduced from 31 to 20 due to restriction <20>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
709255/79779    2.136    0.000    2.136    0.000 sdkx.py:251(search_naked)
     3514    1.539    0.000    3.994    0.001 sdkx.py:106(propagate)
  3514/20    0.239    0.000    4.389    0.219 sdkx.py:234(dfs)
       20    0.135    0.007    4.528    0.226 sdkx.py:468(solvestring)
     3901    0.098    0.000    0.113    0.000 sdkx.py:82(Assume)
   467283    0.071    0.000    0.071    0.000 {method 'add' of 'set' objects}
     3514    0.050    0.000    0.050    0.000 {method 'copy' of 'dict' objects}
   378200    0.048    0.000    0.048    0.000 {method 'discard' of 'set' objects}
        1    0.047    0.047    4.576    4.576 sdkx.py:487(solvefile)

And here is the loop counterpart - search_naked3
         2825303 function calls (2821809 primitive calls) in 4.367 seconds

   Ordered by: internal time, cumulative time
   List reduced from 32 to 20 due to restriction <20>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   144657    1.967    0.000    2.154    0.000 sdkx.py:148(search_naked3)
     3514    1.285    0.000    3.760    0.001 sdkx.py:106(propagate)
  3514/20    0.240    0.000    4.156    0.208 sdkx.py:221(dfs)
   443513    0.114    0.000    0.114    0.000 {method 'pop' of 'list' objects}
       20    0.109    0.005    4.269    0.213 sdkx.py:455(solvestring)
        1    0.097    0.097    4.367    4.367 sdkx.py:474(solvefile)
     3901    0.096    0.000    0.112    0.000 sdkx.py:82(Assume)
   467283    0.072    0.000    0.072    0.000 {method 'add' of 'set' objects}

[Edit]
Here attached the two functions.
def search_naked(Ls, LsL, Tmask, D, NLID,N, locs, masks):  #Find the smallest naked subgroup.
    #global naked, naked_mask, M_size
    LsL1, K  = LsL+1, LsL+N
    for nextLID in xrange(NLID, N):
        Tmask1 =  Tmask|masks[nextLID]
        D1=d_counter[Tmask1]
        if LsL1==D1:
            if D1 <N:
                return Ls+locs[nextLID], Tmask1, D1
            return 0,0,0
        if LsL1>D1:
            return False
        if D1+nextLID > K:# or D1>=M_size:
            continue
        result = search_naked(Ls+locs[nextLID], LsL1, Tmask1, D1, nextLID+1,N, locs, masks)
        if result!=(0,0,0):
            return result

    return 0,0,0

def search_naked3(locs, masks, N):  #Find a subgroup in a deep first manner without recussion. counter is the stack for DFS purpose.

    counter, i, Len, bm,K = [],0, 1,0,N-1
    #i: the current index of a cell to be augmentally considered and checked with for subgroup.
    #bm: base mask is the ORed value of previously selected masks, this is used with the current cell to generate a new mask for checking purpose
    #counter: the stack structure storing (i,bm) pairs, which are used when returning from DFS
    #Len: this is a derived value, as len(counter)+1, Len is maintained to avoid calling len() function.
    #At each stage, there are len(counter)+1 cells are being combined consdered/checked as a subgroup, including len(counter) previous cells and
    #the current cell indicated by i;
    #K=N-1 does not change over the while loop; so save same redundant computation.
    while True:
        TM = bm|masks[i]       #TM (total mask): the mask to check
        D=d_counter[TM]         #D the number of ones in TM.

        if D == Len:        #That is if a subgroup is formed if D==Len<N; or we are checking the entire group (D==Len==N)

            return (0,0,0) if D==N else (locs[i]+sum([locs[c] for (c,m) in counter]), TM, D)   #return a subgroup, else, return the flag that no subgroup is found
        #From now on, D is assumed > Len. Situation of D<Len is impossible due to the treatment before the loop.
        if  D ==N or D - Len > K-i: #Current combination of cells is "blown": either N digits have be provided by less than N locations; or
                                    #there is not enought number (K-i) of unconsidered cells that could possiblly accommodate D-Len digits.
                                    #If blown, we need to check the next cell, unless cell i is already the last of the N cells.
            if i<N-1:               #If there is a next cell, simple increase i, and continue with while loop. Len, bm should not change,
                i+=1
                continue
            else:                   #Now threat the sitation where i is already pointing at the last of N cells.
                if Len-1:           #If there is still something in the stack (indicated by Len-1),
                    i,bm =counter.pop()    #pop from the stack to go back to one level higher, using the older base mask
                    i+=1                    #and try the next cell at that higher level.
                    Len-=1                  #Of course, the we are considering 1 less cells.
                    continue                #continue with the while loop
                break               #If there is nothing left in the stack -> all combinations have been checked. The only exit of the while loop.
        #From now on: Len cells contributed D digits, Len<D and not blown. Prepare to go one level deeper, unless the current cell is already the last of N cells.
        if i< N-1:      #this is the situation in which, the current cell indicated by i is not the last of N cells,
            counter.append((i,bm))  # push to stack
            bm=TM                   #base mask is updated as the current total mask
            i+=1                    #The firt cell to consider in the deeper level is the one just next to the current cell of this level.
            Len+=1                  #of course, we are considering a more cell.
            continue                #continue with the while loop.
        #Now, we treat the situation in which the current combination of cells already include the last of N cells, ie, i==N-1.
        #We cannot go deeper, therefore we return to a higher level.
        i,bm =counter.pop()         # Pop the stack, returning to the higher level, recovering base mask
        i+=1                        # and the next cell to consider in the higher level.
        Len-=1                      #Of course, we are considering 1 less cells in the combination.
    return 0,0,0                    #The loop must be bronken! That means all combinations have been considered without finding a subgroup. Return the flag


text:
Q: Setting different font colors for characters in a cell based on character position I am trying to set three different colors for first 3, second 3 and last 3 characters of contents of all the cells in a range. The below code is changing the entire cell content to green, not only the first 3 characters.
Please guide me how to do this. I am very new to VB.
Sub LoopAndChangeColor()

  Dim i As Integer
  Dim targetRange As Range
  'Set targetRange = Range("A1:A10")

  'For Each cell In targetRange
  For i = 1 To 10
    Cells(i, 1).Characters(1, 3).Font.Color = vbGreen
    Cells(i, 1).Characters(4, 3).Font.Color = vbBlue
    Cells(i, 1).Characters(7, 3).Font.Color = vbRed
  Next

End Sub

A: This info may be too late, but the macro to do what you need is ready to use. Visit: http://excelfindandformat.herobo.com and the related 34 youtube videos.


text:
Q: MySql OR and AND Operation my table schema as follows:
                      +------+-------+-------+
                      | id   | name1 | name2 |
                      +------+-------+-------+
                      |    1 | A     | B     |
                      |    2 | A     | C     |
                      |    3 | B     | A     |
                      |    4 | C     | D     |
                      +------+-------+-------+

and i am using the query as follows:
          select * from t where name1='A' or name1='B' and name2='C';

and the result as follows
                       +------+-------+-------+
                       | id   | name1 | name2 |
                       +------+-------+-------+
                       |    1 | A     | B     |
                       |    2 | A     | C     |
                       +------+-------+-------+

How this result came and
I want the query which returns the row that in which the name1 will be A or B and name2 to be 'B'

the query result should be like this
                       +------+-------+-------+
                       | id   | name1 | name2 |
                       +------+-------+-------+
                       |    1 | A     | B     |
                       +------+-------+-------+

I want the result from the query using only "AND" and "OR" operation...

A: I suggest you read up about boolean logic. This is a very simple operation, so if you were familiar with B.L.,  you'd have been able to do this yourself.
That being said, these two states will accomplish what you want:
SELECT ... WHERE (name1 IN ('A', 'B')) AND (name2 = 'B')
SELECT ... WHERE ((name1 = 'A') or (name1 = 'B')) AND (name2 = 'B')

A: group your condition by adding parenthesis
select * from t where (name1='A' or name1='B') and name2='B';

OR use IN
select * from t where name1 IN ('A','B') and name2='B';

A: You should use parentheses
select * from t where name1='A' or name1='B' and name2='C';

should be
select * from t where (name1='A' or name1='B') and name2='B';

A:    select * from t where (name1='A' or name1='B') and name2='B';

A: It's a precedence issue. The B and C clauses are binding together meaning you're getting:
select * from t where name1='A' or (name1='B' and name2='B');

So what you need to do is explicitly bind the clauses yourself:
select * from t where (name1='A' or name1='B') and name2='B';

(assuming your use of C in your stated query was a typo, since it didn't match the rest of your question).


text:
Q: mate-terminal - start in new PID I often like to kill a set of terminal instances by process id but mate-terminal (which I believe to be a fork of gnome-terminal) will run a number of windows under the same PID. This is not always true and I haven't noticed what determines it,but the outcome is that if I kill a PID I will kill some windows that I don't want to kill.
As a fix, I'd like to tell terminal to start with a new process, but I don't see that option in the terminal man page. Have I missed something? Or perhaps there is a bash command that can force this.

A: The option you're looking for is --disable-factory.


text:
Q: I'm trying to understand how to work with 2D arrays I have a CSV file with almost 65,000 rows divided into 3 values (longitude, latitude, and altitude). What I have to do is to create an array[][] that is longitude by latitude. Longitude and latitude are Doubles and they can't be used for indexing but don't know how to map them to indices. So I imagine it would be something like this:
array[0][0] = altitude_value[0];
array[0][1] = altitude_value[1];
            ·
            ·
            ·
array[i][j] = altitude_value[z];

The values are as such:
-179.75,-89.75,-1965
-179.75,-89.5,-2011
-179.75,-89.25,-2140
-179.75,-89,-2162

What I'm trying to achieve to get the altitude based on longitude and latitude parameters given to the following method:
public double getAltitude(double longitude, double latitude) {
    return array[array.indexOf(longitude)][array.indexOf(latitude)] = altitude_value;
}

A: If you insist on using a 2D array, you could map your values like this:
array[0][0] = longitude[0];
array[0][1] = latitude[0];
array[0][2] = altitude[0];
array[1][0] = longitude[1];
array[1][1] = latitude[1];
array[1][2] = altitude[1];
...
array[n][0] = longitude[n];
array[n][1] = latitude[n];
array[n][2] = altitude[n];

A better solution would be to create a Position class to hold one longitude, latitude, and altitude.  Then you can have a 1D array of Position instances.
Edited to add:
Here's a simple example.  I used your four position lines as input.
-179.75,-89.75,-1965
-179.75,-89.5,-2011
-179.75,-89.25,-2140
-179.75,-89,-2162

I received the following output for longitude -179.75, latitude -89.5.
-2011

I used a simple linear search through the 1D array I created.  For 4 values, it's quick enough.  For 65 thousand values, you can run my code and see how long it takes.  As I said, if you sort the array by longitude, latitude and use a binary search, you'll get the correct result in about 32 tests.
Here's the complete runnable code I used.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PositionApp {

    public static void main(String[] args) {
        new PositionApp().run();
    }

    private Position[] positions;

    public void run() {
        try {
            int count = readCSVFile();
            this.positions = new Position[count];
            processCSVFile();
            int altitude = getAltitude(-179.75, -89.5);
            System.out.println(altitude);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int readCSVFile() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                getClass().getResourceAsStream("/sample.csv")));
        int count = 0;
        String line = reader.readLine();
        while (line != null) {
            count++;
            line = reader.readLine();
        }
        reader.close();
        return count;
    }

    public void processCSVFile() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                getClass().getResourceAsStream("/sample.csv")));
        int count = 0;
        String line = reader.readLine();
        while (line != null) {
            String[] parts = line.split(",");
            double longitude = Double.valueOf(parts[0]);
            double latitude = Double.valueOf(parts[1]);
            int altitude = Integer.valueOf(parts[2]);
            positions[count++] = new Position(longitude, latitude, altitude);
            line = reader.readLine();
        }
        reader.close();
    }

    public int getAltitude(double longitude, double latitude) {
        for (int index = 0; index < positions.length; index++) {
            if ((positions[index].getLongitude() == longitude) &&
                (positions[index].getLatitude() == latitude)) {
                return positions[index].getAltitude();
            }
        }
        return Integer.MIN_VALUE;
    }

    public class Position {

        private final int altitude;

        private final double longitude;
        private final double latitude;

        public Position(double longitude, double latitude, int altitude) {
            this.longitude = longitude;
            this.latitude = latitude;
            this.altitude = altitude;
        }

        public int getAltitude() {
            return altitude;
        }

        public double getLongitude() {
            return longitude;
        }

        public double getLatitude() {
            return latitude;
        }

    }

}

A: Let's say for simplicity you had longitudes and latitudes from 0-1 in increments of 0.25 (n = 5 increments). Then your mapping would look something like this:
0, 0 -> a0
0, 0.25 -> a1
...
0.25, 0 -> a5
...

Then you could access the altitude with the indices [x][y] determined by [longitude * 4][latitude * 4] for any longitude and latitude values.
Obviously for your actual example you would need to offset your longitude and latitude values to zero when querying the array, but that shouldn't be too much extra work.

A: Java primitive arrays do not have an "indexOf" method such as the one shown in your provided getAltitude method.  You would need to cast it to a List or use a helper class such as java.util.Array to get that functionality.
Looking at how are trying to use the array index you might be better off with another datatype, such as a Map of Maps.  The basic functionality of these other datatypes work the same as a 2D array conceptually, but allows for greater variety of index datatype than primitive arrays.
A basic implementation using a Map of Maps:

    Map<Double, Map<Double,Double> longitudeMap; //Read your CSV file into this data structure

    public double getAltitude(double longitude, double latitude) {

        Map<Double> latitudeMap = longitudeMap.get(longitude);
        double altitude = latitudeMap.get(latitude);

        return altitude;
    }

This could be simplified into fewer lines using chained gets.  It also needs some NULL protection, but should convey the jist of a Map based solution rather than primitive array solution.
If you have to use a longitude and latitude indexed primitive array you are basically building a mapping yourself by hand (what value maps to what index in the data array) and would need to store that indexing in a separate object, which could be an array, but is better off as a List.  Your "indexOf" in getAltitude would be into your indexing object, not not the data array.


text:
Q: Error finding module controller in zf2 I'm running into an issue where when I link to my module the controller throws an error:
Fatal error: Class 'Rooms\Controller\RoomController' not found in C:\wamp\www\smtest\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170
Now I'm still new to ZF2 but I'm under the understanding that this means that my module has an error in name spaces or in the autoloader, that being said heres that information:
module.config controller routes
'controllers' => array(
    'invokables' => array(
        'Rooms\Controller\Room' => 'Rooms\Controller\RoomController',
    ),
),

module.php
namespace Rooms;

class Module
{
public function getConfig()
{
    return include __DIR__ . '/config/module.config.php';
}

public function getAutoloaderConfig()
{
    return array(
        'Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
            ),
        ),
    );
}
}

RoomController.php
namespace Rooms\Controller;

class RoomsController extends AbstractActionController
{
private $usersTable;

//retrieve
public function indexAction()
{
    return new ViewModel();
}

link to module from homepage
$this->url('room/default', array('controller' => 'room', 'action' => 'index'))

Every similar question here on stack overflow or elsewhere has not resolved this issue, I've spent hours trying to fix this one issue, I coppied the module directly from another one in another part of my app that work, stripped it down then modified it so i didnt have to change as much and run into these issues.

A: Your definition of the invokables controller RoomController
'controllers' => array(
    'invokables' => array(
        'Rooms\Controller\Room' => 'Rooms\Controller\RoomController',
    ),
),

does not match the class name of your controller RoomsController
namespace Rooms\Controller;

class RoomsController extends AbstractActionController
{

changing the latter to class RoomController should fix the error


text:
Q: How can I do Realtime Google Maps Geolocation Tracking with Angular js I need's to develop Real-time Geo location tracking in showed in google maps. I followed this tutorial : https://www.pubnub.com/blog/2017-02-02-realtime-google-maps-tracking-and-live-geolocation-with-javascript/  I tried to implement in Angular js because for mobile app.
The Code is :

<!DOCTYPE html>

Full Name: {{firstName + " " + lastName}}

Error is :

angularpra.html:41 Entered into HelloCtrl
angularpra.html:66 Uncaught TypeError: Cannot read property 'setCenter' of undefined
    at Object.redraw [as message] (file:///C:/Users/suresh/Desktop/angularpra.html:66:7)
    at https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:1974:41
    at Array.forEach (native)
    at _class.announceMessage (https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:1973:24)
    at https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:1883:36
    at Array.forEach (native)
    at _class._processSubscribeResponse (https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:1817:17)
    at onResponse (https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:2321:8)
    at https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:4500:13
    at Request.callback (https://cdn.pubnub.com/sdk/javascript/pubnub.4.8.0.js:5209:4)


text:
Q: Meaning of 'others' and 'group' in Unix system file I wanna know what's the real meaning of 'others' in Unix System File.
Okay I understand stuff like 755, and tips for remember things like 5 refers to Read Permission(4) + Execute Permission(1) etc...
But what does 'others' and 'group' really mean please ? Is it about for example a person who connect through SSH ?
If I use tools like Yeoman(yo), or NPM, did 'others' refers to theses tools that often create folders and files OR their actions depends of my permissions ?

A: In Unix Users belong to Groups. So a permission for a Group means: for all the other users of the group(s) to which the user belong to, while Others means a permission for all the other users (that is users different from the current user and not belonging to one of its groups).


text:
Q: Insertion Sort algorithm What would be the worst case time complexity of insertion sort if its input are restricted to permutations of $1$ to $n$ with atmost $n$ inversions?
In worst case i.e with $n(n-1)/2$ inversions, time complexity is $O(n^2)$. But when the inversions are limited to $n$ then complexity is $O(n)$. How to prove it?

A: The number of steps taken by insertion sort is $O(n+k)$ where $k$ is the number of inversions. The proof follows by just observing that insertion sort can be implemented using only swaps without changing the time complexity, and that for each of the $n$ passes, every element accessed and compared is followed by a swap except the last, and every swap fixes exactly one inversion. Can you get it now?


text:
Q: chaining multiples context providers working on the same realm in react native I'm trying to chain multiple ContextProviders divided by distinct purposes to work on the same realm in react native.
<FirstRealmProvider>
   <SecondRealmProvider>
     <FunctionalComonentUsingHooksFromFristAndSecond>
   </SecondRealmProvider>
</FirstRealmProvider>

I'm initialising (opening) the realm in the first component (it's also responsible for closing etc.) and save the ref to it via realmRef = useRef<Realm>(null); with the help of a useEffect hook. Using exported context functions and collections from the first component within the second and the third one seams to work fine unless I implement another useEffect in the SecondRealmProvider (with or without accessing the realm directly or its exported ref).
If I do that realm complains about realmRef.current being null (which is set in the useEffect of FirstRealmProvider and should not be null unless the useEffect get called after the inner useEffect of SecondRealmProvider has been called first. In this case it seams not to be possible to chain and share the logic by concerns and the FirstRealmProvider would become a multipurpose over cluttered component.
Please help me to pinpoint what am I missing here.
Thanks.

A: Since react initialises (calls useEffect) first on the inner components those can not use functionality from the outer ones if this relies on initialisation as well. To make it work anyway I added a is"Particular"ProviderInitialized like this:
const [nlpIsInitialized, setInitialized] = useState<boolean>(false);

and each provider ignores useEffect until the outer provider reported to be initialised as well. The useEffect also depends on the initialised value of the outer Provider, and everything works now like it should.


text:
Q: Can I Used wamp server as a db for my web api C#? I am creating my first webapi on visual studio. I used wamp server as a database and my problem is, I dont know how to connect wamp on my webapi. Is it posible to use wamp instead of microsoft sql server? plss help me guys

A: use this c# code
 string connstring ="Server=localhost;Database=testDB;Uid=UserName;Pwd=yourPassword;";
    MySqlConnection connection = new MySqlConnection(connstring);
    connection.Open();
Console.WriteLine("Connected");
connection.close();


text:
Q: How to add a USB printer using lpadmin I'm trying to use this old technology called USB ;) I call it old because all the tutorial that I find on-line deal with wireless printers or IP ones.
The man for lpadmin is very unclear how to go about adding a USB printer, and so I come here for some help.
When I print dmesg I can see my printer being detected over USB
usb 1-1.3: new high-speed USB device number 7 using dwc_otg
usb 1-1.3: New USB device found, idVendor=03f0, idProduct=2b17
usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
usb 1-1.3: Product: HP LaserJet 1020
usb 1-1.3: Manufacturer: Hewlett-Packard
usb 1-1.3: SerialNumber: FN0JW5E
usblp 1-1.3:1.0: usblp0: USB Bidirectional printer dev 7 if 0 alt 0 proto 2 vid 0x03F0 pid 0x2B17

My question is
How can I add it, because it seams this command is adding the printer but there is no communication, and I'm not sure if I have malformed the USB part:
lpadmin -p HP1020 -E -v "usb://Hewlett-Packard/HP%20LaserJet%201020?serial=FN0JW5E" -m lsb/usr/hplip/HP/hp-laserjet_1020-hpijs.ppd
Also, what would be the simplest command to check if I can communicate with the printer. I don't need to print anything, just to be able to see there is communication. This will help me debug the drivers.

A: I found this on
http://www.openprinting.org/download/kpfeifle/LinuxKongress2002/Tutorial/VI.CUPS-Connections/VI.tutorial-handout-cups-connections.html
Local printers: Parallel, USB, serial, FireWire, SCSI
The important part here is the "device-URI". This way you tell CUPS which backend it shall use with the printer "printername". The backends for most types of local printers are already part of the CUPS package. CUPS 1.1.x contains backends for parallel, serial, and USB printers, CUPS 1.2.x will also support FireWire (IEEE 1394) and SCSI printers.
The backends do not only send data to the appropriate devices. They are also called when CUPS is started. They auto-detect which printer models are connected to which ports. So you should set up your BIOS for the parallel ports to allow bi-directional communication. Then your printer(s) can answer to the auto-detection requests.
To see which devices the CUPS backends auto-detect currently, execute them without command line options:

/usr/lib/cups/backend/usb
DEBUG: list_devices
DEBUG: libusb_get_device_list=13
DEBUG2: Printer found with device ID: MFG:Samsung;CMD:GDI;MDL:ML-2510 Series;CLS:PRINTER;STATUS:BUSY; Device URI: usb://Samsung/ML-2510%20Series?serial=3V61BKAQ411232V.
direct usb://Samsung/ML-2510%20Series?serial=3V61BKAQ411232V. "Samsung ML-2510 Series" "Samsung ML-2510 Series" "MFG:Samsung;CMD:GDI;MDL:ML-2510 Series;CLS:PRINTER;STATUS:BUSY;" ""

In the example above my USB URI is usb://Samsung/ML-2510%20Series?serial=3V61BKAQ411232V.
You can also use the wizard GUI in Gnoime on  CENTOS 7 with command
/usr/bin/python /usr/share/system-config-printer/system-config-printer.py
Link with instructions: https://www.maketecheasier.com/set-up-a-printer-in-linux/


text:
Q: # getting month and day from date # I have a table in which there is a column, ci_birthday. The column is declared as nvarchar(50), the format is mm-dd-yyyy. The data in the table is like this:
CI_BIRTHDAY
-----------

07/14/1956
NULL
NULL
11/01/1969
08/15/1955
07/08/1965
NULL
NULL
09/20/1936
NULL
NULL
NULL
NULL
0/0/0
NULL
NULL
NULL
NULL
NULL
0/0/0
NULL
NULL
1/29/1940
NULL
0/0/0
NULL
NULL
NULL
NULL
08/11/1949

I want the output from that column is only month and day, like
09/20
0/0
1/29
08/11
0/0

A: I accept my solution is a very bad way of solving this but if the date is not stored in a date format (in this case its a string), then you can do something like this:
DECLARE @Date varchar(15) = '11/01/1969'
SELECT SUBSTRING(@Date, 1,LEN(@Date) - PATINDEX('%/%',REVERSE(@Date)))

A: Just to show how to cast this very messy data into dates after checking it's safe to do so:
SET DATEFORMAT mdy;

WITH    Dates
          AS ( SELECT   '07/14/1956' AS DateStr
               UNION
               SELECT   '11/01/1969'
               UNION
               SELECT   '08/15/1955'
               UNION
               SELECT   '07/08/1965'
               UNION
               SELECT   '09/20/1936'
               UNION
               SELECT   '0/0/0'
               UNION
               SELECT   NULL
               UNION
               SELECT   '1/29/1940'
             )
    SELECT  CASE WHEN ISDATE(DateStr) = 1 THEN CONVERT(VARCHAR(5), CONVERT(DATE, DateStr, 101), 101)
                 ELSE '00/00'
            END AS [DD/MM]
    FROM    Dates


text:
Q: How to handle a detached entity graph that has duplicate entities with the same PK in Entity Framework 6 For example I'm creating an invoice graph..
The graph is constructed client side with AnuglarJS and then sent as JSON to the backend. In the backend I recieve a seemingly perfect object created by some model binding magic in Web Api 2.
Next I load an Administration entity from the DbContext and add the detached invoice to it's collection navigation property:
Administration.Lines.Add(invoice);

When DetectChanges is triggered each entity in the graph gets an entry with state EntityState.Added.
From the graph I only want to add the entities Invoice and InvoiceLines because the rest of the graph is unchanged. To make this work I've adopted the approach to track the state locally e.g. with a BaseModel interface that implements a State property (as suggested in Programming Entity Framework: DbContext, Chapter 4).
This all works very nicely... until for example, when I add 2 lines with the same item. For illustration purposes, I believe the model binder creates the object from JSON somewhat like:
var invoice = new Invoice
{
    State = State.Added,
    Number = "SALE-001",
    Lines =
    {
        new InvoiceLine
        {
            State = State.Added,
            Price = 10,
            Quantity = 1,
            Item = new Item { Id = 1, Description = "Product" }
        },
        new InvoiceLine
        {
            State = State.Added,
            Price = 10,
            Quantity = 1,
            DiscountPercentage = 50,
            Item = new Item { Id = 1, Description = "Product" }
        },
    }
};

As you can see the items share the same PK but actually are different objects. So when DetectChanges is triggered I have 2 entries of the entity Item with the same PK and this all blows up when I try to convert the state Added to Unchanged with an InvalidOperationException:

Saving or accepting changes failed because more than one entity of type 'AutomapperWithEF.Data.Domain.Item' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.

Should EF not somehow prevent this from occurring? By means of equality comparison for the same type and PK?
EDIT:
The DbContext where ChangeTracker.Entries is the trigger:
public class AppContext : DbContext
{
    public DbSet<Administration> Administrations { get; set; }
    public DbSet<Invoice> Invoices { get; set; }
    public DbSet<InvoiceLine> InvoiceLines { get; set; }
    public DbSet<Item> Items { get; set; }

    public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries<BaseModel>())
        {
            BaseModel baseModel = entry.Entity;
            entry.State = ConvertState(baseModel.State);
        }

        return base.SaveChanges();
    }

    public static EntityState ConvertState(State state)
    {
        switch (state)
        {
            case State.Added:
                return EntityState.Added;
            case State.Modified:
                return EntityState.Modified;
            case State.Deleted:
                return EntityState.Detached;
            default:
                return EntityState.Unchanged;
        }
    }
}

An example to show what I mean: https://github.com/svieillard/SampleEF

A: The reason you are having this problem is that you are creating two different Item objects, giving them both the same key, and trying to add both of them to the context.
Item = new Item { Id = 1, Description = "Product" }

/// and later

Item = new Item { Id = 1, Description = "Product" }

The exception happens when you call .Add(), because you can't have two different objects of the same type with the same key in the EF context.
When I look at the code in your github repo, it looks like you've already solved this.  All I have to do is comment out how you create the Items currently and uncomment your other code, resulting in this:
var item = new Item { Id = 1, Description = "Product" };

// Invoice is added
var invoice = new Invoice
{
    State = State.Added,
    Number = "SALE-001",
    Lines =
    {
        new InvoiceLine
        {
            State = State.Added,
            Price = 10,
            Quantity = 1,
            // Item = new Item { Id = 1, Description = "Product" }
            Item = item
        },
        new InvoiceLine
        {
            State = State.Added,
            Price = 10,
            Quantity = 1,
            DiscountPercentage = 50,
            // Item = new Item { Id = 1, Description = "Product" }
            Item = item
        },
    }
};

This way, only 1 Item ends up getting added to the context, so EF is happy.
When I run the code like that, it works without any exceptions being thrown.

A: You are deserializing some JSON into an Invoice which has two Item objects with the same ID.  You then Add() that Invoice to the context then call SaveChanges().
When you do this, EF sees that you have the Item in there twice and throws an exception.
And even if you only had 1 item in there, EF would try to update the item based on the data in the JSON.  You probably don't want that.
So we're going to remove the Items from the context.
Solution #1:  Remove the items from the objects in memory and use just the ItemId instead
foreach (var line in invoice.Lines)
{
    if (line != null && line.Item != null)
    {
        line.ItemId = line.Item.Id;
        db.Entry(line.Item).State = System.Data.Entity.EntityState.Detached;
    }
}

Solution #2 - Change your JSON line items to have the ItemId instead of the Item, like this
{'state': 2, 'price': 10, 'quantity': 1, 'itemId': 1}


text:
Q: How to determine which Go version was used to compile a binary When I run the command
go build

I end up with an application that's larger than needed, doesn't run and with lots of errors. I'm using the same source as everybody else and I understand the different OS make a difference, but should it affect the actual program and how it works?
How do I find out what version of Go was used and which compiler was used on a already-compiled application? It's just a app file.

A: By doing go build you are creating a binary for the go program in that current folder.
Update
Once a binary file is created you cannot determine what version      of Go was used to create the binary.
To Find the version of GO used for compiling use a debugger like gdb or others. Here is an awesome blog about the same.
And you can inspect the file with
file mybinary

to get info like the type of binary and like which OS it is supposed to run on.
eg : ELF files run on Linux
Mach-O files run on Mac etc...
However you can cross compile your Go code with
GOOS=linux go build

so this creates a binary for linux (ELF file) even though i run Go on Mac / Windows


text:
Q: Search function works on localhost but not on server I am trying to add a search function to my website.  Right now it's very rudimentary, and the search is simply pulling results from MySQL using select.  The problem is, the search works great when I test it on localhost but doesn't work at all when I put it on the server.  When it is used it simply selects the entire database.  I believe the problem is that the variable isn't getting passed to the search results page, but I don't know.
Here's the code for the search box.  It is in a referenced file called "header.php":

Search:
<form style="display:inline" name="search" action="search.php" method="get"><?php echo"         <input type='text' name='query' />";?>
   </form>

home

post an idea

about us

contact us

log in

And here's the code from search.php:
<?php
$search=$_GET['query'];
$search=mysql_real_escape_string($search);
?>

<?php
echo "<title>Search: $search</title>";
?>
<link rel="stylesheet" type="text/css" href="mainstyle.css" />

Search:
<form style="display:inline" name="search" action="search.php" method="get"><?php echo"    <input type='text' name='query' value='$search'/>";?>
</form>

home

post an idea

about us

contact us

log in

<?php

mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("date_ideas") or die(mysql_error());

$result=mysql_query("SELECT * FROM ideas WHERE title LIKE '%".$search."%' ORDER BY    post_date DESC");
echo "SELECT * FROM ideas WHERE title LIKE '%".$search."%' ORDER BY post_date DESC";

echo "";
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
echo "
" . $row['title'] . "
";
echo "";
$date=$row['post_date'];
$time=time();

if (($time-$date)<120)
{
echo "Posted 1 minute ago";
}

else if (($time-$date)>120&&($time-$date)<3600)
{
$minutes=($time-$date)/60;
echo ("Posted " . round($minutes) . " minutes ago");
}
else if (($time-$date)>3600&&($time-$date)<7200)
{
echo "Posted 1 hour ago";
}
else if (($time-$date)<86400&&($time-$date)>7200)
{
$hours=($time-$date)/3600;
echo ("Posted " . round($hours) . " hours ago");
}
else if (($time-$date)<172800&&($time-$date)>86400)
{
echo "Posted 1 day ago";
}
else
{
echo ("Posted on " . date("m-d-y",$date));
}
echo "
";
}
echo "";
?>

Lastly, here's the code for the javascript used to submit the form:
var valid=true;

function validate(field, helptext, type, min, max, field1)
{
var x=field.value;
var text=document.getElementById(helptext);
if (x==null || x=="")
{
if (text!=null)
    {
    text.innerHTML="Please input "+field.id;
    }
valid=false;
}
else if (type=="length")
{
valLength(min,max,field,helptext);
}
else if (type=="email")
{
valEmail(field,helptext);
}
else if (type=="pass")
{
valPass(field, field1, helptext);
}
else
{
if (text!=null)
    {
    text.innerHTML="";
    }
valid=true;
}
}

function searchSubmit()
{
validate(search.query);
if (valid==true)
{
search.submit();
}
else
{
alert("Please enter a search term");
}
}

As I said, when I use it on my localhost on my computer, it works perfectly, returning only the rows where title matches the search.  When I put it on the server, however, it returns all the rows in the table.

A: try to printout the query to see if it injects $search value correctly (if search is not null)
echo "SELECT * FROM ideas WHERE title LIKE '%".$search."%' ORDER BY post_date DESC";

A: I can't see anything in the code given that would cause this. I think your analysis is correct; I'd imagine $_GET['query'] is empty for some reason.
You could make your code a little more robust by doing an explicit check for this: you want that to be an error case, not "return everything" case. But besides confirming your theory, this won't solve the problem outright.
The only thing I can think of is to make sure that $_GET exists on your server; it was introduced in PHP 4.1.0, which is now a very long time ago. Still, it's possible that the PHP on your remote server is ancient.
Good luck!

Update
You're using mysql_real_escape_string, which requires a connection, before you make the connection. If there isn't one, one is attempted using default parameters which is working on your local machine, but not on your [presumably more secure] production server.
This is causing the escaping to fail, and FALSE to be written into $query.
Just use mysql_escape_string which doesn't require a connection.


text:
Q: Java code works well in step by step debug mode not in default run mode I worked on an Andriod App. I read some strings from DB and output them in ListView. My problem is the return string from DB worked well if I in step by step mode. If I in run mode or even if I put the breakpoint after the line which I receive the result in. The string variable will be empty.
 BackgroundWorker backgroundWorker = new BackgroundWorker( this);
 backgroundWorker.execute("Names");
 res = backgroundWorker.FinalRes;
 res = res.replace("[","");
 res = res.replace("]","");
 res = res.replace("\"","");
 ParsedStringsResult = PasrString(res);
 ArrayList<ListNames> NameSs= new ArrayList<ListNames>();
 int size = ParsedStringsResult.length;
 for ( int i=0; i<size;i++ )
 NameSs.add(new ListNames(ParsedStringsResult[i]));

If I put the breakpoint in      res=backgroundWorker.FinalRes;
It works well and shows the value
If I put it after this line or even in the default run mode, res will be empty!
Why this happens and how can I solve it?
my Background class
public class BackgroundWorker extends AsyncTask<String , Void, String> {

Context context;

public String FinalRes="";
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];

    if (type == "Names") {
        String url_login = "http://192.168.1.2/MyApp/getNames.php";

        try {
            URL url = new URL(url_login);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);

          /*  OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");// +"&"+ w nkml tany
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();*/

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = "";
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            FinalRes = result;
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    else
        return null;
}

@Override
protected void onPreExecute(){
   // alertDialog = new AlertDialog.Builder(context).create();
 //   alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result){
    //alertDialog.setMessage(result);
    //alertDialog.show();
    //FinalRes = result;
}

}

A: You have a race condition between starting the background worker, and it setting its final result.
By setting the break point, you are simply waiting long enough for the process to complete.
You just need to wait for FinalRes to be set, by some means. Without seeing the code of your BackgroundWorker class, it is impossible to say how best to do that.

A: Try like that :
BackgroundWorker backgroundWorker = new BackgroundWorker( this);
backgroundWorker.execute("Names");
while(backgroundWorker.getStatus() != AsyncTask.Status.FINISHED) // While the status is different from "FINISHED" you wait for the task to finished
    Thread.sleep(100)
res = backgroundWorker.FinalRes;

Also shown here :
Android, AsyncTask, check status?


text:
Q: ListView Expanding Cells Animation Dosen't collapse Hi i found this video on devBytes a nice expanding listView animation you can download the code.
This code works perfectly but when i try to add anything in the expanding layout like a button or a text my list view expands and shows the new elements but can never collapse.
There was no errors or exception shown in the logcat and since i'am new in android i can't realy figure out where the problem is.
After debugging my code i noticed that the expanded listview  item dosen't enter the click listner method.
This is the list_view_item.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@drawable/border"
 android:orientation="vertical">

 <LinearLayout
    android:id="@+id/item_linear_layout"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image_view"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:gravity="center_vertical"
        android:layout_weight="1"
        android:scaleType="center"/>

    <TextView
        android:id="@+id/title_view"
        android:layout_height="fill_parent"
        android:layout_width="0dp"
        android:gravity="center"
        android:layout_weight="2"
        android:textStyle="bold"
        android:textSize="22sp"
        android:textColor="#ffffff"/>

  </LinearLayout>

  <com.example.android.expandingcells.ExpandingLayout
        android:id="@+id/expanding_layout"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:visibility="gone">

        <LinearLayout
            android:id="@+id/item_expanding_linear_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/text_view"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center_horizontal"
                android:paddingBottom="20dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:textColor="#ffffff"
                android:textSize="22sp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="bottom"
                android:text="Button" />

        </LinearLayout>

  </com.example.android.expandingcells.ExpandingLayout>

  </LinearLayout>


text:
Q: UnicodeEncodeError: 'ascii' codec can't encode characters in position 18-23: ordinal not in range(128) I tried to fit the model but got one weird error
So, I have Win10(64), Python 3.7
This is my code:
clf = LogisticRegression(solver='saga')
param_grid = {
    'C': np.arange(1, 5),
    'penalty': ['l1', 'l2'],
}
search = GridSearchCV(clf, param_grid, n_jobs=-1, cv=5, refit=True, scoring='accuracy')
search.fit(feature_matrix, labels)

And this is traceback:
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-13-93a1aa3c1ec2> in <module>
     12
     13
---> 14 search.fit(feature_matrix, labels)
     15

C:\Anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     71                           FutureWarning)
     72         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 73         return f(**kwargs)
     74     return inner_f
     75

C:\Anaconda3\lib\site-packages\sklearn\model_selection\_search.py in fit(self, X, y, groups, **fit_params)
    693                                     verbose=self.verbose)
    694         results = {}
--> 695         with parallel:
    696             all_candidate_params = []
    697             all_out = []

C:\Anaconda3\lib\site-packages\joblib\parallel.py in __enter__(self)
    709     def __enter__(self):
    710         self._managed_backend = True
--> 711         self._initialize_backend()
    712         return self
    713

C:\Anaconda3\lib\site-packages\joblib\parallel.py in _initialize_backend(self)
    720         try:
    721             n_jobs = self._backend.configure(n_jobs=self.n_jobs, parallel=self,
--> 722                                              **self._backend_args)
    723             if self.timeout is not None and not self._backend.supports_timeout:
    724                 warnings.warn(

C:\Anaconda3\lib\site-packages\joblib\_parallel_backends.py in configure(self, n_jobs, parallel, prefer, require, idle_worker_timeout, **memmappingexecutor_args)
    495             n_jobs, timeout=idle_worker_timeout,
    496             env=self._prepare_worker_env(n_jobs=n_jobs),
--> 497             context_id=parallel._id, **memmappingexecutor_args)
    498         self.parallel = parallel
    499         return n_jobs

C:\Anaconda3\lib\site-packages\joblib\executor.py in get_memmapping_executor(n_jobs, **kwargs)
     18
     19 def get_memmapping_executor(n_jobs, **kwargs):
---> 20     return MemmappingExecutor.get_memmapping_executor(n_jobs, **kwargs)
     21
     22

C:\Anaconda3\lib\site-packages\joblib\executor.py in get_memmapping_executor(cls, n_jobs, timeout, initializer, initargs, env, temp_folder, context_id, **backend_args)
     40         _executor_args = executor_args
     41
---> 42         manager = TemporaryResourcesManager(temp_folder)
     43
     44         # reducers access the temporary folder in which to store temporary

C:\Anaconda3\lib\site-packages\joblib\_memmapping_reducer.py in __init__(self, temp_folder_root, context_id)
    529             # exposes exposes too many low-level details.
    530         context_id = uuid4().hex
--> 531         self.set_current_context(context_id)
    532
    533     def set_current_context(self, context_id):

C:\Anaconda3\lib\site-packages\joblib\_memmapping_reducer.py in set_current_context(self, context_id)
    533     def set_current_context(self, context_id):
    534         self._current_context_id = context_id
--> 535         self.register_new_context(context_id)
    536
    537     def register_new_context(self, context_id):

C:\Anaconda3\lib\site-packages\joblib\_memmapping_reducer.py in register_new_context(self, context_id)
    558                 new_folder_name, self._temp_folder_root
    559             )
--> 560             self.register_folder_finalizer(new_folder_path, context_id)
    561             self._cached_temp_folders[context_id] = new_folder_path
    562

C:\Anaconda3\lib\site-packages\joblib\_memmapping_reducer.py in register_folder_finalizer(self, pool_subfolder, context_id)
    588         # semaphores and pipes
    589         pool_module_name = whichmodule(delete_folder, 'delete_folder')
--> 590         resource_tracker.register(pool_subfolder, "folder")
    591
    592         def _cleanup():

C:\Anaconda3\lib\site-packages\joblib\externals\loky\backend\resource_tracker.py in register(self, name, rtype)
    189         '''Register a named resource, and increment its refcount.'''
    190         self.ensure_running()
--> 191         self._send('REGISTER', name, rtype)
    192
    193     def unregister(self, name, rtype):

C:\Anaconda3\lib\site-packages\joblib\externals\loky\backend\resource_tracker.py in _send(self, cmd, name, rtype)
    202
    203     def _send(self, cmd, name, rtype):
--> 204         msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('ascii')
    205         if len(name) > 512:
    206             # posix guarantees that writes to a pipe of less than PIPE_BUF

UnicodeEncodeError: 'ascii' codec can't encode characters in position 18-23: ordinal not in range(128)

I tried to fix the _send by cutting .encode('ascii'), but it didn't help me. It generates another error (a bytes-like object is required, not 'str') with variable msg from the traceback above
I'm looking for advice about this. Thanks a lot.

A: Try encoding using utf-8.
msg = '{0}:{1}:{2}\n'.format(cmd, name, rtype).encode('utf-8')

These messages usually means that you're trying to either mix Unicode strings with 8-bit strings, or is trying to write Unicode strings to an output file or device that only handles ASCII.
When you do this, Python will usually assume that the 8-bit string contains ASCII data only, and will raise an error if this is not the case.
The best way to avoid this on input is to convert all incoming strings to Unicode, do the processing in Unicode, and then convert back to encoded byte strings on the way out.


text:
Q: Make graph of edges in networkx How can I convert a network into a network of edges where each edge from the original network becomes a node and adjacent edges (sharing a node) are connected in the target network?
I was hoping there would be a function in networkx since conversion into an edge network is mathematically quite common. I have a very large network so I was looking for a more efficient function already part of some python package for network analysis.

A: You can use networkx.generators.line.line_graph to do that:
import networkx as nx

# Your old graph
G = nx.star_graph(3)

# Your new graph (a node for every edge)
L = nx.line_graph(G)


text:
Q: Selenium can't find element by name or id (Python) Consider:
from selenium import webdriver
import os
from selenium.webdriver import chrome

driver = webdriver.Chrome()
driver.get("http://nmcunited.me.showenter.com/%D7%9C%D7%94-%D7%9C%D7%94-%D7%9C%D7%A0%D7%93.html")
driver.implicitly_wait(15)
christmasTag = driver.find_element_by_id('f_2561406_1')
christsmasTag.click()
driver.close()

I used the Python code above in order to practice on some basic Selenium operations.
I couldn't find any element, neither by name nor by id. No matter what I tried, I always got the same error, which stated that the element I'm looking for doesn't exist (the idea was to press one of the buttons, if it matters...).
This is a part of the HTML code of the website:

  <form id="form2" name="form2" method="post" action="/site/form/sendForm.asp" OnSubmit="return CheckSubmit();" enctype="multipart/form-data">

    באיזה חג מפוטר ראין גוסלינג?

    <input type="radio" name="f_2561406" id="f_2561406_0" value="1. חג הפסחא" class="rachbox" checked>
    1. חג הפסחא

    <input type="radio" name="f_2561406" id="f_2561406_1" value="2. חג המולד" class="rachbox">
    2. חג המולד

    <input type="radio" name="f_2561406" id="f_2561406_2" value="3. סליבסטר" class="rachbox">
    3. סליבסטר

    <input type="radio" name="f_2561406" id="f_2561406_3" value="4. חג ראש השנה" class="rachbox">
    4. חג ראש השנה

This is the said website (broken link)
By the way, this is the first program that uses Selenium I'm trying to run. Is there a possibility that I need to change some settings or that I need to install something else?

A: The items you are trying to find are inside of an iframe. You need to switch the context of the webdriver to the frame first.
from selenium import webdriver
import os
from selenium.webdriver import chrome

driver = webdriver.Chrome()
driver.get("http://nmcunited.me.showenter.com/%D7%9C%D7%94-%D7%9C%D7%94-%D7%9C%D7%A0%D7%93.html")
driver.implicitly_wait(15)
frame = driver.find_element_by_css_selector('div.tool_forms iframe')
driver.switch_to.frame(frame)
christmasTag = driver.find_element_by_id('f_2561406_1')
christmasTag.click()
driver.close()

A: Verify whether the "id" is getting changed and generated dynamically by refreshing the page. If it is the case then use the below XPath expression to find the element:
"//input[@value='2. חג המולד']"


text:
Q: Can't keep buttons from disappearing after hovering out of an adjacent element I feel like I'm missing something obvious but I can't seem to find the best way to make it so the buttons below an image don't disappear once you hover off said image. What is meant to happen is you hover over the image to show the buttons, allowing you to click on them. On hovering out of the buttons, only then should they disappear.
I've tried using mouseenter and mouseleave as well as what is shown below (which I found from an example online). I also tried adding more padding below the images to increase the hover area with no luck.
I feel so dumb but this has had me stumped all day.
Codepen:https://codepen.io/gojiHime/pen/eKKroR?editors=0111
jQuery:
$(document).ready(function() {
  $(".thumb").each(function() {
    $(this).hover(
      function() {
        $learn = $(this)
          .parent()
          .prev();
        $cta = $(this).next();
        $learn.stop(true, true).fadeIn();
        $cta.stop(true, true).fadeIn();
      },
      function() {
        $learn = $(this)
          .parent()
          .prev();
        $cta = $(this).next();
        $learn.stop(true, true).fadeOut();
        $cta.stop(true, true).fadeOut();
      }
    );
  });
});

A: You are using display:none; on your buttons. You are hiding them from the page where there is no possible way to 'hover' over them. Instead use, opacity, to hide the button's while keeping them accessible to your cursor.
You also don't have to loop through the selector elements since jQuery already does it for you. So, you can reduce your jQuery code.
css
.learn-more {
  opacity: 1;
  /* your other css */
}

js
$(document).ready(function() {
  $('.inner').hover(function() {
    $(this).find('.learn-more').css({'opacity':'1'})
  }, function(){
    $(this).find('.learn-more').css({'opacity':'0'})
  });
});


text:
Q: ¿Cómo hacer un CRUD en un solo archivo ASP Clasico? Estoy realizando un CRUD, pero fue creado en partes, es decir tengo un archivo ASP llamado leer datos, este archivo tiene la consulta de leer todos los datos de una table, así mismo tengo otro archivo ASP para dar de alta, pero lo que quiero es poner este código en un mismo archivo, no he llegado al objetivo ya que al momento de juntar los dos códigos, me manda en la pantalla index.asp que 192.168.1.75 te redireccionó demasiadas veces.
este es mi código junto, por podrían orientas como lo podría hacer por favor.
<!-- #include file="connection.asp" -->

<%
    strSQL = "SELECT * FROM pacientes"
    set ObjRst = Con.execute(strSQL)

%>

<%
    id_paciente = request.form("id_paciente")
    nombre = request.form("nombre")
    apellido = request.form("apellido")
    correo = request.form("correo")
    motivo = request.form("motivo")

    if (trim(id_paciente) = "") or (isnull(id_paciente)) then id_paciente = 0 end if

if cint(id_paciente) = 0 then

    strSQL = "insert into pacientes (nombre, apellido, correo, motivo) values('"&nombre&"', '"&apellido&"', '"&correo&"', '"&motivo&"');"
    Con.execute(strSQL)
    response.redirect("index.asp")

else
    strSQL = "UPDATE pacientes SET nombre = '"&nombre&"', apellido = '"&apellido&"',  correo = '"&correo&"',  motivo = '"&motivo&"' WHERE id_paciente = " & id_paciente
    Con.execute(strSQL)
    response.redirect("index.asp")
    response.End
end if
%>


text:
Q: Correlate Java field type and generic parameter Consider the following classes:
class A {
    B<Integer> b;
}

class B<T> {
    T t;
}

I need to write the follwing method:
Object create(Class clazz) {
    // todo
}

such that when create(A.class) is called, the returned value is an instance of A which contains an Integer in b.t. Naturally the method must not have any knowledge about A besides its class.
It is well known how to find out that the type of b in A is B<Integer>.
I am looking for a way to find out that the field t in B is intended to have the type of the first type parameter of B.

A: The type of a field that is a type parameter is assignable to java.lang.reflect.TypeVariable. In other words, field.getGenericType() returns an instance of TypeVariable when called for the field B.t.
The following complete example works for the toy case given in the question. The general case is more complicated because you must keep track of multiple levels of type parameters.
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

class Main {
    static class A {
        B<Integer> b;
    }

    static class B<T> {
        T t;
    }

    public static void main(String[] args) throws Exception {
        A a = (A)create(A.class);
        System.out.println(a.b.t.getClass());
        // prints java.lang.Integer
    }

    static Object create(Class<?> clazz) throws Exception {
        return create(clazz, new Type[0]);
    }

    static Object create(Class<?> clazz, Type[] typeArguments) throws Exception {
        Object object;
        if (clazz == Integer.class || clazz == int.class) {
            return 0;
        } else {
            object = clazz.newInstance();
        }
        for (Field field : object.getClass().getDeclaredFields()) {
            Type[] fieldTypeArguments = { };
            Type fieldType = field.getGenericType();
            if (fieldType instanceof TypeVariable) {
                TypeVariable<?> typeVariable = (TypeVariable<?>) fieldType;
                TypeVariable<?>[] typeParameters = typeVariable.getGenericDeclaration().getTypeParameters();
                for (int i = 0; i < typeParameters.length; i++) {
                    if (typeParameters[i] == typeVariable) {
                        fieldType = typeArguments[i];
                    }
                }
            } else if (fieldType instanceof ParameterizedType) {
                fieldTypeArguments = ((ParameterizedType) fieldType).getActualTypeArguments();
            }
            Class<?> fieldClass = null;
            if (fieldType instanceof Class) {
                fieldClass = (Class<?>) fieldType;
            } else if (fieldType instanceof ParameterizedType) {
                fieldClass = (Class<?>) ((ParameterizedType) fieldType).getRawType();
            }
            field.set(object, create(fieldClass, fieldTypeArguments));
        }
        return object;
    }
}


text:
Q: Code-splitting separate exports from a package to different bundles I have a Gatsby site that consumes a number of packages. One of those packages is published from our monorepo: @example/forms. That package contains a number of named exports, one for each form component that we use on our site. There are quite a large number of forms and some are relatively complex multistep forms of a non-trivial size.
Currently, Gatsby/Webpack does a good job of treeshaking, and does produce a large number of bundles, some common bundles and one for each page of the site, containing any local assets or components that are only used on that page. However, all the components from @example/forms are being added to the commons bundle, despite the fact that most are used on only a single page. This is causing unnecessary bloat of the commons bundle which is loaded on every page.
If feels like it should be possible for the individual components within @example/forms to be split out into the page-specific bundles, but I'm not sure if I'm hoping for too much. For example, if Form A is only used on page 4, I'd like Form A to only be added to the bundle for page 4.
Is this something that is supported, and if so, what could be preventing this from happening.
@example/forms is transpiled with ES6 exports left intact, and sideEffects is set to false in its package.json.
Its main file is index.js which (re)exports all the form components from their own files as separate named exports:
export {default as FormA} from './forms/formA'
export {default as FormB} from './forms/formB'
...

Another thing that might be relevant is that all the exports from @example/forms are used within the Gatsby site, just on separate pages. It appears that perhaps tree-shaking cannot be used across bundles, i.e. tree shaking is performed first, then what is left is split into bundles. Using that logic, @example/forms would have been used on multiple pages and would be moved to commons. However this is definitely not optimal, and hopefully isn't what is happening.

A: Tree-shaking process is part of the minification step which is really at  late stage, since that it is not possible to reverse the order, first tree-shake then chunk split.
But you can split your forms lib before hand using some heuristics

*

*The basic one is to use splitChunks in order to split this @example/forms module into a separate chunk as whole, this will decrease the commons bloat & on the first form usage all forms will be loaded.

// webpack.config.js

module.exports = {
  ...
  optimization: {
    splitChunks: {
      cacheGroups: {
        formComponents: {
          chunks: 'all',
          enforce: true,
          minChunks: 1,
          name: 'form-components',
          priority: 10,
          test: /[\\\/]node_modules[\\\/]@example[\\\/]forms[\\\/]/,
        },
      },
    },
  },
  ...
};

*Make a chunk for each form inside the @example/forms module based on some heuristics, in my example I'm "grouping" all items based on the form path.

// webpack.config.js

module.exports = {
  ...
  optimization: {
    splitChunks: {
      cacheGroups: {
        formComponents: {
          chunks: 'all',
          minChunks: 1,
          name(module) {
            const libPath = path.resolve(path.join('node_modules/@example/forms'))
            const folderBasedChunk = path.relative(libPath, module.context);
            const hash = crypto.createHash('sha1');
            hash.update(folderBasedChunk)
            return hash.digest('hex').substring(0, 8)
          },
          priority: 10,
          reuseExistingChunk: true,
          enforce: true,
          test: /[\\\/]node_modules[\\\/]@example[\\\/]forms[\\\/]src[\\\/]forms[\\\/]/,
        },
      },
    },
  ...
};

You can checkout a small example that I've created that mimics the scenario.
https://github.com/felixmosh/webpack-module-split-example
Hope this helps


text:
Q: Converting XML Datetime to SQL Datetime I have an XML datatype and want to convert an element into a sql DateTime variable. How?
e.g.
Declare @Xml Xml
Set @Xml = '<Root><DateFrom>2008-10-31T00:00:00</DateFrom></Root>'

Declare @DateFrom DateTime
Set @DateFrom = ?????

How can I set @DateFrom with the date from the xml above?

A: Declare @Xml Xml
Set @Xml = '<Root><DateFrom>8/10/2008</DateFrom></Root>'

Declare @DateFrom DateTime
Select @DateFrom= t.b.value('DateFrom[1]', 'datetime')
from @xml.nodes('//Root') t(b)

I highly recommend you look at the .nodes functionality of the XML data type. The above code pulls out the value of the DateFrom element and converts it to Date Time format.


text:
Q: Scala unapply in traits How can I use unapply in traits?
import play.api.libs.json.Json

trait Json[T] {

  implicit val jsonFormat = Json.format[T]

}

Gives compile error:
No unapply function found

Can i somehow force the compiler to bound T to case class so I can make use of unapply?

A: This is the requirement for which Scala's extractors exist. An extractor is a method called unapply that is usually defined in an object (typically a companion of the type in question). It is used to destructure a value into its constituents.
Here's an example (quite contrived):
object Extractor1 {
  def unapply(a: Any): Option[(String, Int)] =
    Some(a.toString, a.toString.length)
}

object ExtractorUse {
  import Extractor1._
  def use {
    "23 skeedo!" match {
      case Extractor1(str, length) => printf("str=\"%s\"; length=%d%n", str, length)
    }
  }
}

In use:
scala> ExtractorUse.use
str="23 skeedo!"; length=10

If the extractor returns None, the match attempting it will fail. Likewise if the arity of result is not consistent with the pattern varibles supplied in the case clause.
There is also a counterpart for extracting sequences, unapplySeq. See the Programming in Scala link for details


text:
Q: Post JSON Data from Java to Wordpress WP API v2 I'm a bit stuck here and I don't know why. It's probably very simple. I want to post changes to a Wordpress site from a Java app.
The following curl example does as it should:
curl -X POST -H "Content-Type: application/json" -d '{"title":"hello123"}' -u user:pass http://myurl.com/wp-json/wp/v2/posts/219 -v

The following code example not:
 try {
        URL url = new URL("http://myurl.com/wp-json/wp/v2/posts/219");
        String encoding = Base64.encodeBase64String((txtUserName.getText() + ":" + txtPassword.getText()).getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");
        connection.connect();

        ObjectMapper post = new ObjectMapper();
        ObjectNode node = post.createObjectNode();
        node.put("title", "test1234");

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(os, "UTF-8");
        outputStreamWriter.write(post.toString());
        outputStreamWriter.flush();
        outputStreamWriter.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

So I'm grateful for any help.
Thank you very much


text:
Q: Google App Engine Barrier Synchronization I have n parallel tasks running. When all these tasks are done, I want to create another task. What is the best way to do this ? Since a datastore operation is slower, I used memcache. I keep incrementing the counter by 1 when each task is finished. I keep checking the counter for n. Since memcache is not reliable, the counter value is lost sometimes. Any other solutions?

A: Since you can't afford to lose your counter, you need to use the datastore to ensure that your counter isn't lost (e.g., due to an unexpected memcache eviction).  However, you could also store the value in memcache - that way you can still get fast reads of the counter from memcache (and go to the datastore to get the count if the memcache entry has expired).
If you have so many tasks running in parallel that incrementing the datastore counter is too slow, then consider using a sharded counter to relieve this bottleneck.

A: I would recommend use the appengine-pipeline
Intenally it implements a barrier with models.


text:
Q: Validate types in PactNet I am testing micro services and I'm using PactNet to create and validate pacts. I am finding that the tests are too brittle, as the verifier is checking for exact values and not verifying the types.
For example, I am testing against the GitHub API and the test works. If a new Repo is added, the public_repos value increases by one and the test fails.
Is anyone using this to check the types instead of the concrete values?
Here is the verification code:
[Test]
public void VerifyPact()
{

    // Arrange.
    var pactVerifier = new PactVerifier(() => { }, () => { });
    pactVerifier.ProviderState("There is call with the name 'karlgjertsen'");

    // Act.
    using (var client = new HttpClient { BaseAddress = new Uri("https://api.github.com/users/karlgjertsen") })
    {

        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");

        // Assert.
        pactVerifier
            .ServiceProvider("GitHub API", client)
            .HonoursPactWith("Pact Test")
            .PactUri(@"C:\Pact\pacts\pact_test-git_api.json")
            .Verify();

    }

}

And here's the PACT file.
{
  "provider": {
    "name": "GitHub API"
  },
  "consumer": {
    "name": "PACT Test"
  },
  "interactions": [
    {
      "description": "A GET request for user deatils for 'karlgjertsen'",
      "provider_state": "There is call with the name 'karlgjertsen'",
      "request": {
        "method": "get",
        "path": "/users/karlgjertsen",
        "headers": {
          "Accept": "application/json"
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json; charset=utf-8"
        },
        "body": {
          "login": "karlgjertsen",
          "id": 4457667,
          "avatar_url": "https://avatars.githubusercontent.com/u/4457667?v=3",
          "gravatar_id": "",
          "url": "https://api.github.com/users/karlgjertsen",
          "html_url": "https://github.com/karlgjertsen",
          "followers_url": "https://api.github.com/users/karlgjertsen/followers",
          "following_url": "https://api.github.com/users/karlgjertsen/following{/other_user}",
          "gists_url": "https://api.github.com/users/karlgjertsen/gists{/gist_id}",
          "starred_url": "https://api.github.com/users/karlgjertsen/starred{/owner}{/repo}",
          "subscriptions_url": "https://api.github.com/users/karlgjertsen/subscriptions",
          "organizations_url": "https://api.github.com/users/karlgjertsen/orgs",
          "repos_url": "https://api.github.com/users/karlgjertsen/repos",
          "events_url": "https://api.github.com/users/karlgjertsen/events{/privacy}",
          "received_events_url": "https://api.github.com/users/karlgjertsen/received_events",
          "type": "User",
          "site_admin": false,
          "name": "Karl Gjertsen",
          "company": "infiniforms.io",
          "blog": "http://www.karlgjertsen.com",
          "location": "UK",
          "email": null,
          "hireable": null,
          "bio": null,
          "public_repos": 1,
          "public_gists": 0,
          "followers": 0,
          "following": 0,
          "created_at": "2013-05-17T14:05:30Z",
          "updated_at": "2016-03-07T19:39:58Z"
        }
      }
    }
  ],
  "metadata": {
    "pactSpecificationVersion": "1.1.0"
  }
}

A: PactNet v2 already supports type and regex matching:
Type matching for whole body:
// IMockProviderService
.WillRespondWith(new ProviderServiceResponse
{
    Body = Match.Type(new { Id = 123, FirstName = "John" })
});

or for a property:
.WillRespondWith(new ProviderServiceResponse
{
    Body = new { Id = 123, FirstName = Match.Type("John") }
});

Regex matching:
.WillRespondWith(new ProviderServiceResponse
{
    Body = new { FirstName = Match.Regex("Jan", @"\A\w+\z") }
});

There's also Match.MinType for arrays.

A: It seems that v1 of Pact is all about testing providers where you can control the state and put the system in a deterministic state.
v2 is aiming to work with the scenarios you mention.
At this time PactNet does not support v2 of the Pact specification.
Update 26/02/2020 - V2.0 is now supported for PactNet (https://github.com/pact-foundation/pact-net)


text:
Q: Access to the windows registry using ADO .Net Exist any ADO.NET Provider for access to the windows registry?  Or rather you can use ADO to connect to the windows registry?
Thanks in advance.

A: I'm not aware of a provider to the registry, but if you're looking to search the registry you could write a recursive function that enumerates the registry keys and applies your search criteria through string comparisons.


text:
Q: Different between access key and Shared Access Signature Could you please provide the difference between SAS and Access Key and when to use them?
Thank you for your help.

A: Say you have a website that allows users to upload files. You could create an api that takes the file and put in on a storage account or you can allow the client to upload the file directly to the storage account. In order to do that the api generates and returns a SAS token that allows write access for a short period of time to the storage account. This way the api doesn't need bandwith to cater for large file uploads and the access to the storage account is based on the principle of least privilege
Another scenario is to facilitate the download of a file for a limited amount of time. For example, an expense report is generated and available for download. The api generates a url to the storage account including a SAS token that gives read permission to a certain blob for a short period of time.
The use of Access Keys should be avoided, use managed identities so there is no need for access keys that have to be put in the configuration somehow and needs to be protected.

By using managed identities for Azure resources together with Azure AD authentication, you can avoid storing credentials with your applications that run in the cloud.

Now, if you have an api or azure function or whatever backend process that needs access to a storage account you can use a managed identity and assign that identity permissions based on the principle of least privilege.


text:
Q: WCF Callback between two services I am trying to make a connection between two services. Service1 will send event notifications to service2.
I want to use callbacks, between these two services. service1 will send event to service2 and service2 will pass the event to a client.
Is it possible to use callbacks between two services?
I have already looked into the samples of wcf callbacks, but cant find anything between service to service communication.
Any help is appreaciated. see below the code of 1 of the services.
my question: how is the code of the other service is going to look like with the callback in it?
Or is it in this case one of the services acting like a client? And how should that be looking like?
Service1 code:(Interface class)
public interface IMyEvents
{
    [OperationContract(IsOneWay = true)]
    void Event1();
}

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMyEvents))]
public interface SampleInterface
{
    [OperationContract]
    void DoSomethingAndFireEvent();

    [OperationContract]
    void SubscribeEvent();
}

This is the service class
public class SampleHandlerSimulator : SampleInterface
{
    static Action m_Event1 = delegate { Console.WriteLine("Catch");};

    public void SubscribeEvent()
    {
        IMyEvents subscriber = OperationContext.Current.GetCallbackChannel<IMyEvents>();
        m_Event1 += subscriber.Event1;
    }

    public static void FireEvent()
    {
        m_Event1();
    }

    public void DoSomethingAndFireEvent()
    {
        CCStateHandlerSimulator.FireEvent();
    }

A: Configure your services by adding a service reference to one of them (refering to the other service). To do this make sure the service to be referenced is up and running, then right click on the child service project and select add service reference. Now you can make calls to the methods exposed by the parent service.
You will need an endpoint configured with duplex binding for call backs. See here for information on duplex binding. Update your service reference when you add new endpoint configurations to the parent service. You will need to host your services.
A similar question was raised here.
Your enpoint will look like:
 <endpoint address="http://localhost:61775/DUPLEXFUN/" binding="wsDualHttpBinding"
      bindingConfiguration="" name="DUPEND" contract="IDuplexCallback" />

Note the wsDualHttpBinding is the important bit to note.
Your service contract will look like:
    [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IDuplexCallback))]
public interface IDuplexService
{

    [OperationContract(IsOneWay = true)]
    void FormatString(string institution);
}

and the service implementation will be like:
   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class DuplexService : IDuplexService
{
    IDuplexCallback _callback;
    string _requestString = String.Empty;

    public DuplexService()
    {
        _callback = OperationContext.Current.GetCallbackChannel<IDuplexCallback>();
    }

    public void FormatString(string text)
    {
        //Make the thread to sleep for 10 seconds
        Thread.Sleep(4000);
        //Format the input data
        _requestString = string.Format("Welcome to {0}", text);
        //Pass the string to the client through the call back function
        _callback.DuplexCallbackFunction(_requestString);
    }
}

and finally IDuplexCallback is declared as:
 public interface IDuplexCallback
    {
        [OperationContract(IsOneWay = true)]
        void DuplexCallbackFunction(string requestString);
    }


text:
Q: how to store data crawled from website I want to crawl a website and store the content on my computer for later analysis. However my OS file system has a limit on the number of sub directories, meaning storing the original folder structure is not going to work.
Suggestions?
Map the URL to some filename so can store flatly? Or just shove it in a database like sqlite to avoid file system limitations?

A: It all depends on the effective amount of text and/or web pages you intent to crawl.  A generic solution is probably to

*

*use an RDBMS (SQL server of sorts) to store the meta-data associated with the pages.
Such info would be stored in a simple table (maybe with a very few support/related tables) containing fields such as Url, FileName (where you'll be saving it), Offset in File where stored (the idea is to keep several pages in the same file) date of crawl, size, and a few other fields.

*use a flat file storage for the text proper.
The file name and path matters little (i.e. the path may be shallow and the name cryptic/automatically generated).  This name /  path is stored in the meta-data.  Several crawled pages are stored in the same flat file, to optimize the overhead in the OS to manage too many files.   The text itself may be compressed (ZIP etc.) on a per-page basis (there's little extra compression gain to be had by compressing bigger chunks.), allowing a per-file handling (no need to decompress all the text before it!).  The decision to use compression depends on various factors; the compression/decompression overhead is typically relatively minimal, CPU-wise, and offers a nice saving on HD Space and generally disk I/O performance.

The advantage of this approach is that the DBMS remains small, but is available for SQL-driven queries (of an ad-hoc or programmed nature) to search on various criteria.  There is typically little gain (and a lot of headache) associated with storing many/big files within the SQL server itself.  Furthermore as each page gets processed / analyzed, additional meta-data (such as say title, language, most repeated 5 words, whatever) can be added to the database.

A: Having it in a database will help search through the content and page matadata. You can also try in-memory databases or "memcached" like storage to speed in up.

A: Depending on the processing power of the PC which will do the data mining, you could add the scraped data to a compressible archive like a 7zip, zip, or tarball.  You'll be able to keep the directory structure intact and may end up saving a great deal of disk space - if that happens to be a concern.
On the other hand, a RDBMS like SqLite will balloon out really fast but wont mind ridiculously long directory hierarchies.