_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d11701
train
Because remove is a method that changes the mutable list object it's called on, and returns None. l= MyWords.upper().split() l.remove(SpamWords[SpamCheckRange]) # l is ['YES'] Perhaps you want: >>> [word for word in MyWords.split() if word.upper() not in SpamWords] ['yes'] A: remove is a method of list (str.split returns a list), not str. It mutates the original list (removing what you pass) and returns None, not a modified list.
unknown
d11702
train
I found a good example which works well with twitter4j 3.0.3 on android. Others do not work. http://hintdesk.com/how-to-tweet-in-twitter-within-android-client/ A: This is the working example from my code , i am using twitter4j and also you don't need to set any intent in manifest since i use webview instead of browser. Place your consumer and secret key and you should be good to go package com.example.mysituationtwittertest; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { // Constants /** * Register your here app https://dev.twitter.com/apps/new and get your * consumer key and secret * */ static String TWITTER_CONSUMER_KEY = "XXXXXXXXXXXXXXXXXXX"; // place your // cosumer // key here static String TWITTER_CONSUMER_SECRET = "XXXXXXXXXXXXXXXX"; // place // your // consumer // secret // here // Preference Constants static String PREFERENCE_NAME = "twitter_oauth"; static final String PREF_KEY_OAUTH_TOKEN = "oauth_token"; static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret"; static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn"; static final String TWITTER_CALLBACK_URL = "oauth://youdare"; // Twitter oauth urls static final String URL_TWITTER_AUTH = "auth_url"; static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier"; static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token"; // Login button Button btnShareTwitter; WebView myWebView; // Twitter private static Twitter twitter; private static RequestToken requestToken; private AccessToken accessToken; // Shared Preferences private static SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // All UI elements btnShareTwitter = (Button) findViewById(R.id.btnShareTwitter); myWebView = (WebView) findViewById(R.id.webView1); myWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url != null && url.startsWith(TWITTER_CALLBACK_URL)) new AfterLoginTask().execute(url); else webView.loadUrl(url); return true; } }); // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences( "MyPref", 0); /** * Twitter login button click event will call loginToTwitter() function * */ btnShareTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call login twitter function new LoginTask().execute(); } }); } /** * Function to login twitter * */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter .getOAuthRequestToken(TWITTER_CALLBACK_URL); } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // user already logged into twitter Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show(); } } /** * Check user already logged in your application using twitter Login flag is * fetched from Shared Preferences * */ private boolean isTwitterLoggedInAlready() { // return twitter login status from Shared Preferences return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); } public void handleTwitterCallback(String url) { Uri uri = Uri.parse(url); // oAuth verifier final String verifier = uri .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { // Get the access token MainActivity.this.accessToken = twitter.getOAuthAccessToken( requestToken, verifier); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString( PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString( PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); Twitter twitter = new TwitterFactory(builder.build()) .getInstance(accessToken); // Update status twitter4j.Status response = twitter .updateStatus("XXXXXXXXXXXXXXXXX"); } catch (Exception e) { e.printStackTrace(); } } class LoginTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { // TODO Auto-generated method stub loginToTwitter(); return true; } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub myWebView.loadUrl(requestToken.getAuthenticationURL()); myWebView.setVisibility(View.VISIBLE); myWebView.requestFocus(View.FOCUS_DOWN); } } class AfterLoginTask extends AsyncTask<String, Void, Boolean> { @Override protected void onPreExecute() { // TODO Auto-generated method stub myWebView.clearHistory(); } @Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub handleTwitterCallback(params[0]); return true; } @Override protected void onPostExecute(Boolean result) { // TODO Auto-generated method stub myWebView.setVisibility(View.GONE); Toast.makeText(MainActivity.this, "Tweet Successful", Toast.LENGTH_SHORT).show(); } } @Override public void onBackPressed() { if (myWebView.getVisibility() == View.VISIBLE) { if (myWebView.canGoBack()) { myWebView.goBack(); return; } else { myWebView.setVisibility(View.GONE); return; } } super.onBackPressed(); } } A: To illustrate my comment above, here is my final working MainActivity class. Pretty similar to the code above, the differences are : * *the internal class OAuthAccessTokenTask, that includes the retrieval of the Oauth token and the user information *its callback onRequestTokenRetrieved(Exception) Also, note that to get this to work you must declare a callback url on your twitter app settings, even a phony one. It took me a few hours to figure out the way it works. When you check the twitter4j documentation, the first pieces of code refer to a PIN code you have to get from an authorisation webpage. That's what happens when no callback url is set in your app. It's called PIN based authentication and you don't want to use it on a mobile :) public class MainActivity extends Activity { // Constants /** * Register your here app https://dev.twitter.com/apps/new and get your * consumer key and secret * */ static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere"; // place your cosumer key here static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here // Preference Constants static String PREFERENCE_NAME = "twitter_oauth"; static final String PREF_KEY_OAUTH_TOKEN = "oauth_token"; static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret"; static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn"; static final String TWITTER_CALLBACK_URL = "oauth://t4jsample"; // Twitter oauth urls static final String URL_TWITTER_AUTH = "auth_url"; static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier"; static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token"; // Login button Button btnLoginTwitter; // Update status button Button btnUpdateStatus; // Logout button Button btnLogoutTwitter; // EditText for update EditText txtUpdate; // lbl update TextView lblUpdate; TextView lblUserName; // Progress dialog ProgressDialog pDialog; // Twitter private static Twitter twitter; private static RequestToken requestToken; private AccessToken accessToken; private User user; // Shared Preferences private static SharedPreferences mSharedPreferences; // Internet Connection detector private ConnectionDetector cd; // Alert Dialog Manager AlertDialogManager alert = new AlertDialogManager(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){ // Internet Connection is not present alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // All UI elements btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus); btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter); txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus); lblUpdate = (TextView) findViewById(R.id.lblUpdate); lblUserName = (TextView) findViewById(R.id.lblUserName); // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0); /** * Twitter login button click event will call loginToTwitter() function * */ btnLoginTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call login twitter function loginToTwitter(); } }); /** * Button click event to Update Status, will call updateTwitterStatus() * function * */ btnUpdateStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Call update status function // Get the status from EditText String status = txtUpdate.getText().toString(); // Check for blank text if (status.trim().length() > 0) { // update status new updateTwitterStatus().execute(status); } else { // EditText is empty Toast.makeText( getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT ).show(); } } }); /** * Button click event for logout from twitter * */ btnLogoutTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function logoutFromTwitter(); } }); /** This if conditions is tested once is * redirected from twitter page. Parse the uri to get oAuth * Verifier * */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); new OAuthAccessTokenTask().execute(verifier); } } } private class OAuthAccessTokenTask extends AsyncTask<String, Void, Exception> { @Override protected Exception doInBackground(String... params) { Exception toReturn = null; try { accessToken = twitter.getOAuthAccessToken(requestToken, params[0]); user = twitter.showUser(accessToken.getUserId()); } catch(TwitterException e) { Log.e(MainActivity.class.getName(), "TwitterError: " + e.getErrorMessage()); toReturn = e; } catch(Exception e) { Log.e(MainActivity.class.getName(), "Error: " + e.getMessage()); toReturn = e; } return toReturn; } @Override protected void onPostExecute(Exception exception) { onRequestTokenRetrieved(exception); } } private void onRequestTokenRetrieved(Exception result) { if (result != null) { Toast.makeText( this, result.getMessage(), Toast.LENGTH_LONG ).show(); } else { try { // Shared Preferences Editor editor = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); editor.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true); editor.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Hide login button btnLoginTwitter.setVisibility(View.GONE); // Show Update Twitter lblUpdate.setVisibility(View.VISIBLE); txtUpdate.setVisibility(View.VISIBLE); btnUpdateStatus.setVisibility(View.VISIBLE); btnLogoutTwitter.setVisibility(View.VISIBLE); // Getting user details from twitter String username = user.getName(); // Displaying in xml ui lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>")); } catch (Exception ex) { // Check log for login errors Log.e("Twitter Login Error", "> " + ex.getMessage()); ex.printStackTrace(); } } } /** * Function to login twitter * */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); Thread thread = new Thread(new Runnable(){ @Override public void run() { try { requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show(); } } }); thread.start(); } else { // user already logged into twitter Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show(); } } /** * Function to update status * */ class updateTwitterStatus extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Updating to twitter..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting Places JSON * */ protected String doInBackground(String... args) { Log.d("Tweet Text", "> " + args[0]); String status = args[0]; try { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken); // Update status twitter4j.Status response = twitter.updateStatus(status); Log.d("Status", "> " + response.getText()); } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog and show * the data in UI Always use runOnUiThread(new Runnable()) to update UI * from background thread, otherwise you will get error * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT) .show(); // Clearing EditText field txtUpdate.setText(""); } }); } } /** * Function to logout from twitter * It will just clear the application shared preferences * */ private void logoutFromTwitter() { // Clear the shared preferences Editor e = mSharedPreferences.edit(); e.remove(PREF_KEY_OAUTH_TOKEN); e.remove(PREF_KEY_OAUTH_SECRET); e.remove(PREF_KEY_TWITTER_LOGIN); e.commit(); // After this take the appropriate action // I am showing the hiding/showing buttons again // You might not needed this code btnLogoutTwitter.setVisibility(View.GONE); btnUpdateStatus.setVisibility(View.GONE); txtUpdate.setVisibility(View.GONE); lblUpdate.setVisibility(View.GONE); lblUserName.setText(""); lblUserName.setVisibility(View.GONE); btnLoginTwitter.setVisibility(View.VISIBLE); } /** * Check user already logged in your application using twitter Login flag is * fetched from Shared Preferences * */ private boolean isTwitterLoggedInAlready() { // return twitter login status from Shared Preferences return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); } protected void onResume() { super.onResume(); } } A: I solved the problem. I made changes to the code I found in a tutorial to make it work. Copying the whole code here. Just replace with your ConsumerKey and ConsumerSecret. You need to add twitter4j library to your project's libs folder. AndroidManifest.xml : <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidhive.twitterconnect" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" /> <!-- Permission - Internet Connect --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Network State Permissions --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="t4jsample" android:scheme="oauth" /> </intent-filter> </activity> </application> </manifest> MainActivity.java : package com.androidhive.twitterconnect; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationBuilder; import com.androidhive.twitterconnect.R; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { // Constants /** * Register your here app https://dev.twitter.com/apps/new and get your * consumer key and secret * */ static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere"; // place your cosumer key here static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here // Preference Constants static String PREFERENCE_NAME = "twitter_oauth"; static final String PREF_KEY_OAUTH_TOKEN = "oauth_token"; static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret"; static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn"; static final String TWITTER_CALLBACK_URL = "oauth://t4jsample"; // Twitter oauth urls static final String URL_TWITTER_AUTH = "auth_url"; static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier"; static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token"; // Login button Button btnLoginTwitter; // Update status button Button btnUpdateStatus; // Logout button Button btnLogoutTwitter; // EditText for update EditText txtUpdate; // lbl update TextView lblUpdate; TextView lblUserName; // Progress dialog ProgressDialog pDialog; // Twitter private static Twitter twitter; private static RequestToken requestToken; private AccessToken accessToken; // Shared Preferences private static SharedPreferences mSharedPreferences; // Internet Connection detector private ConnectionDetector cd; // Alert Dialog Manager AlertDialogManager alert = new AlertDialogManager(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); cd = new ConnectionDetector(getApplicationContext()); // Check if Internet present if (!cd.isConnectingToInternet()) { // Internet Connection is not present alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } // Check if twitter keys are set if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){ // Internet Connection is not present alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false); // stop executing code by return return; } // All UI elements btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter); btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus); btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter); txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus); lblUpdate = (TextView) findViewById(R.id.lblUpdate); lblUserName = (TextView) findViewById(R.id.lblUserName); // Shared Preferences mSharedPreferences = getApplicationContext().getSharedPreferences( "MyPref", 0); /** * Twitter login button click event will call loginToTwitter() function * */ btnLoginTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call login twitter function loginToTwitter(); } }); /** * Button click event to Update Status, will call updateTwitterStatus() * function * */ btnUpdateStatus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Call update status function // Get the status from EditText String status = txtUpdate.getText().toString(); // Check for blank text if (status.trim().length() > 0) { // update status new updateTwitterStatus().execute(status); } else { // EditText is empty Toast.makeText(getApplicationContext(), "Please enter status message", Toast.LENGTH_SHORT) .show(); } } }); /** * Button click event for logout from twitter * */ btnLogoutTwitter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Call logout twitter function logoutFromTwitter(); } }); /** This if conditions is tested once is * redirected from twitter page. Parse the uri to get oAuth * Verifier * */ if (!isTwitterLoggedInAlready()) { Uri uri = getIntent().getData(); if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) { // oAuth verifier final String verifier = uri .getQueryParameter(URL_TWITTER_OAUTH_VERIFIER); try { Thread thread = new Thread(new Runnable(){ @Override public void run() { try { // Get the access token MainActivity.this.accessToken = twitter.getOAuthAccessToken( requestToken, verifier); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); // Shared Preferences Editor e = mSharedPreferences.edit(); // After getting access token, access token secret // store them in application preferences e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken()); e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret()); // Store login status - true e.putBoolean(PREF_KEY_TWITTER_LOGIN, true); e.commit(); // save changes Log.e("Twitter OAuth Token", "> " + accessToken.getToken()); // Hide login button btnLoginTwitter.setVisibility(View.GONE); // Show Update Twitter lblUpdate.setVisibility(View.VISIBLE); txtUpdate.setVisibility(View.VISIBLE); btnUpdateStatus.setVisibility(View.VISIBLE); btnLogoutTwitter.setVisibility(View.VISIBLE); // Getting user details from twitter // For now i am getting his name only long userID = accessToken.getUserId(); User user = twitter.showUser(userID); String username = user.getName(); // Displaying in xml ui lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>")); } catch (Exception e) { // Check log for login errors Log.e("Twitter Login Error", "> " + e.getMessage()); e.printStackTrace(); } } } } /** * Function to login twitter * */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); Thread thread = new Thread(new Runnable(){ @Override public void run() { try { requestToken = twitter .getOAuthRequestToken(TWITTER_CALLBACK_URL); MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri .parse(requestToken.getAuthenticationURL()))); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } else { // user already logged into twitter Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show(); } } /** * Function to update status * */ class updateTwitterStatus extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Updating to twitter..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting Places JSON * */ protected String doInBackground(String... args) { Log.d("Tweet Text", "> " + args[0]); String status = args[0]; try { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken); // Update status twitter4j.Status response = twitter.updateStatus(status); Log.d("Status", "> " + response.getText()); } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog and show * the data in UI Always use runOnUiThread(new Runnable()) to update UI * from background thread, otherwise you will get error * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products pDialog.dismiss(); // updating UI from Background Thread runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT) .show(); // Clearing EditText field txtUpdate.setText(""); } }); } } /** * Function to logout from twitter * It will just clear the application shared preferences * */ private void logoutFromTwitter() { // Clear the shared preferences Editor e = mSharedPreferences.edit(); e.remove(PREF_KEY_OAUTH_TOKEN); e.remove(PREF_KEY_OAUTH_SECRET); e.remove(PREF_KEY_TWITTER_LOGIN); e.commit(); // After this take the appropriate action // I am showing the hiding/showing buttons again // You might not needed this code btnLogoutTwitter.setVisibility(View.GONE); btnUpdateStatus.setVisibility(View.GONE); txtUpdate.setVisibility(View.GONE); lblUpdate.setVisibility(View.GONE); lblUserName.setText(""); lblUserName.setVisibility(View.GONE); btnLoginTwitter.setVisibility(View.VISIBLE); } /** * Check user already logged in your application using twitter Login flag is * fetched from Shared Preferences * */ private boolean isTwitterLoggedInAlready() { // return twitter login status from Shared Preferences return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false); } protected void onResume() { super.onResume(); } } AlertDialogManager.java : package com.androidhive.twitterconnect; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class AlertDialogManager { /** * Function to display simple Alert Dialog * @param context - application context * @param title - alert dialog title * @param message - alert message * @param status - success/failure (used to set icon) * - pass null if you don't want icon * */ public void showAlertDialog(Context context, String title, String message, Boolean status) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); if(status != null) // Setting alert dialog icon alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // Showing Alert Message alertDialog.show(); } } ConnectionDetector.java : package com.androidhive.twitterconnect; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context){ this._context = context; } /** * Checking for all possible internet providers * **/ public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } } This is original code by Ravi Tamada. The changes I made are in MainActivity.java and AndroidManifest.xml files only. A: Have you seen the sign-in-with-twitter github project, it is based on twitter4j and implements Twitter sign in for Android.
unknown
d11703
train
The error you were seeing is because you had accidentally included an extra ? inside of your @() block, and it should have been a : Overall, it was close you just need to make sure that you break out of the string concatenation and get back to the razor (server) scope for the rowId. <img src='../../Images/Edit.png' alt='Click to Edit' onclick="@( Model.AdminPermissions ? "javascript:EditDetails('#" + rowId + "');" : "" )" disabled="@(Model.AdminPermissions ? "" : "disabled") />
unknown
d11704
train
bar = 5 is not an expression. The multiple assignment is a separate statement from the assignment statement; the expression is everything to the right of the right-most =. A good way to think about it is that the right-most = is the major separator; everything to the right of it happens from left to right, and everything to the left of it happens from left to right as well. A: All credit goes to @MarkDickinson, who answered this in a comment: Notice the + in (target_list "=")+, which means one or more copies. In foo = bar = 5, there are two (target_list "=") productions, and the expression_list part is just 5 All target_list productions (i.e. things that look like foo =) in an assignment statement get assigned, from left to right, to the expression_list on the right end of the statement, after the expression_list gets evaluated. And of course the usual 'tuple-unpacking' assignment syntax works within this syntax, letting you do things like >>> foo, boo, moo = boo[0], moo[0], foo[0] = moo[0], foo[0], boo[0] = [0], [0], [0] >>> foo [[[[...]]]] >>> foo[0] is boo True >>> foo[0][0] is moo True >>> foo[0][0][0] is foo True A: Mark Dickinson explained the syntax of what is happening, but the weird examples involving foo show that the semantics can be counter-intuitive. In C, = is a right-associative operator which returns as a value the RHS of the assignment so when you write x = y = 5, y=5 is first evaluated (assigning 5 to y in the process) and this value (5) is then assigned to x. Before I read this question, I naively assumed that roughly the same thing happens in Python. But, in Python = isn't an expression (for example, 2 + (x = 5) is a syntax error). So Python must achieve multiple assignments in another way. We can disassemble rather than guess: >>> import dis >>> dis.dis('x = y = 5') 1 0 LOAD_CONST 0 (5) 3 DUP_TOP 4 STORE_NAME 0 (x) 7 STORE_NAME 1 (y) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE See this for a description of the byte code instructions. The first instruction pushes 5 onto the stack. The second instruction duplicates it -- so now the top of the stack has two 5s STORE_NAME(name) "Implements name = TOS" according to the byte code documentation Thus STORE_Name(x) implements x = 5 (the 5 on top of the stack), popping that 5 off the stack as it goes, after which STORE_Name(y) implements y = 5 with the other 5 on the stack. The rest of the bytecode isn't directly relevant here. In the case of foo = foo[0] = [0] the byte-code is more complicated because of the lists but has a fundamentally similar structure. The key observation is that once the list [0] is created and placed on the stack then the instruction DUP_TOP doesn't place another copy of [0] on the stack, instead it places another reference to the list. In other words, at that stage the top two elements of the stack are aliases for the same list. This can be seen most clearly in the somewhat simpler case: >>> x = y = [0] >>> x[0] = 5 >>> y[0] 5 When foo = foo[0] = [0] is executed, the list [0] is first assigned to foo and then an alias of the same list is assigned to foo[0]. This is why it results in foo being a circular reference. A: https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assignment_stmt An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. A: The assignment order is that right most value is assigned to the first variable from left to right. Please note below: >>> foo[0] = foo = [1,2,3] # line 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foo' is not defined >>> foo = foo[0] = [1,2,3] # line 2 >>> foo [[...], 2, 3] The assignment at line 1 fails because it is trying assign a value to foo[0] but foo is never initialized or defined so it fails. The assignment at line 2 works because foo is first initialized to be [1,2,3] and then foo[0] is assigned [1,2,3]
unknown
d11705
train
In a class definition, Python transforms __x into _classname__x. This is called name mangling. Its purpose is to support class local references so that subclasses don't unintentionally break the internal logic of the parent class. A: Cause This is due to Python's name mangling of class attribute names that start with __ and are suffixed with at most a single _. This suggests a stricter privacy for these attributes. Note: This is still a heuristic and shouldn't be counted on for access prevention. From the docs: Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. class A: def __foo_(self): pass print(vars(A)) outputs {'__module__': '__main__', '_A__foo_': <function A.__foo_ at 0x1118c2488>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} Notice that __foo_ has been mangled into _A__foo_. Uses Why might this be useful? Well the example from the docs is pretty compelling: Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. For example: class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) tldr Read the docs on name mangling.
unknown
d11706
train
Generally speaking you can't add something to an existing type. (you can however create a subtype at runtime and add things to that) In your case though I suggest just using a regular variable that you capture when you create the shim, you can then return that variable as part of your shim and read it later at your descresion var thelist = new List<Transport>(); //fill out whatever test data you want here, in the case of TransportsGet using (ShimsContext.Create()) { var shimLinq = new ShimTable<Transport>() { InsertOnSubmitT0 = (transport) => { Transport t = (Transport)transport; thelist = t.Transports; // assign your outer variable, or do the asserts directly } }; } // do assertions on thelist here In the comments you mentioned shimming TransportsGet, you can do this the same way and just return thelist in that shim. Then you can do asserts on thelist variable at the end of the test. However if you want to test a .Where statement, that wont show up on the actual list directly, you have to test it some other way. You could have a thelist with invalid banks and assert that the code doesn't return anything for example
unknown
d11707
train
Multiple formulas can be assigned at the same time, and the relative (without $) row/column references will be auto adjusted : Sub CalcualteSFA() Dim r As Range Set r = [H87:S92] r.Formula = "=Sumproduct([KNA_Amt]*--([KNA_Dt]=h$25)*--([KNA_Cat]=$b47)*--([KNA_Prgm]=$D$8))" r.Value = r.Value ' optional to convert the formulas to values End Sub
unknown
d11708
train
I dont think you can get other user's follower list/following list anymore. You can only get the list for the logged in user. Here is documentation: https://www.instagram.com/developer/endpoints/relationships/ https://api.instagram.com/v1/users/self/followed-by?access_token=ACCESS-TOKEN you can only get list for self, not any id A: List of users who your user follow : https://api.instagram.com/v1/users/self/follows?access_token=ACCESS-TOKEN List of users who your user is being followed by : https://api.instagram.com/v1/users/self/followed-by?access_token=ACCESS-TOKEN List of recent media from your user : https://api.instagram.com/v1/users/self/media/recent?access_token=ACCESS-TOKEN List of recent media from other users : https://api.instagram.com/v1/users/{user-Id}/media/recent?access_token=ACCESS-TOKEN More information at Instagram Endpoint Reference in left pane (below Endpints button) you will see a list of media types, each one corresponding to a page that explains all related api Interfaces.
unknown
d11709
train
Here the basic route descriptions you can know more from https://laravel.com/docs/5.7/routing ┌────────┬─────────┬──────────────────────────────────┬────────────────────────┐ │ HTTP │ CRUD │ ENTIRE COLLECTION (e.g /USERS) │ SPECIFIC ITEM │ │ METHOD │ │ │ (e.g. /USERS/123) │ ├────────┼─────────┼──────────────────────────────────┼────────────────────────┤ │ POST │ Create │ 201 (Created), 'Location' │ Avoid using POST │ │ │ │ with header link to /users/{id} │ on single resource │ │ │ │ containing new ID. │ │ ├────────┼─────────┼──────────────────────────────────┼────────────────────────┤ │ GET │ Read │ 200 (OK), list of users. Use │ 200 (OK), single user │ │ │ │ pagination, sorting and │ 404 (Not Found), If ID │ │ │ │ filtering to navigate big lists. │ not found or invalid. │ ├────────┼─────────┼──────────────────────────────────┼────────────────────────┤ │ PUT │ Update/ │ 404 (Not Found), unless you want │ 200 (OK), or 204 (No │ │ │ Replace │ to update every resource in the │ Content). Use 404 (Not │ │ │ │ entire collection of resource. │ Found). If ID not │ │ │ │ │ found or invalid. │ ├────────┼─────────┼──────────────────────────────────┼────────────────────────┤ │ PATCH │ Partial │ 404 (Not Found), unless you want │ 200 (OK), or 204 (No │ │ │ Update/ │ to modify the collection itself. │ Content). Use 404 (Not │ │ │ Modify │ │ Found). If ID not │ │ │ │ │ found or invalid. │ ├────────┼─────────┼──────────────────────────────────┼────────────────────────┤ │ DELETE │ Delete │ 404 (Not Found), unless you want │ 200 (OK), 404 (Not │ │ │ │ to delete the whole collection - │ Fpund). If ID not │ │ │ │ use with caution. │ found or invalid │ └────────┴─────────┴──────────────────────────────────┴────────────────────────┘ A: Here are the basic rules to use http method, GET : When you need to fetch or retrive information POST : When You need to create or insert information PUT : When you need to update existing record For more information you can use this link. https://restfulapi.net/http-methods/ A: Adding to the answer by Lokesh in reference to Laravel. "index" method uses GET REQUEST as it retrieves records from the database. "store" method uses POST REQUEST as it stores records in the database. "update" method uses PUT REQUEST as it updates record in the database. "show" method uses GET REQUEST as it retrieves single record from the database. "delete" method uses DELETE REQUEST as it retrieves single record from the database. Therefore you would want to use POST/PUT REQUEST if you want to change the record in the database. While toggling the status, the standard option is to use PUT, as your are updating a record.
unknown
d11710
train
The setTimeout method of javascript can be used to run code you specify after a set delay in miliseconds. Try this: var timeout; $("#date_1").hover( function () { $(this).addClass("door"); timeout = setTimeout(function() { $(this).addClass("doorstatic"); }, 2000); }, function () { clearTimeout(timeout); $(this).removeClass("door doorstatic"); } ); A: Actually you can just append a call to jQuery's delay to you addClass call. Something like $(this).addClass("door").delay(2000).addClass("doorstatic", "slow"); should do the trick. A: $("#date_1").hover( function () { var $this = $(this); $this.addClass("door"); setTimeout(function() { $this.addClass("doorstatic"); }, 2000); // 2000 is in mil sec eq to 2 sec. }, function () { $(this).removeClass("door doorstatic"); } ); You can group your classes like removeClass("door doorstatic") The problem here is that if you mouseover and before two seconds mouse out you will still have the class doorstatic on you element. The fix: $("#date_1").hover( function () { var $this = $(this), timer = $this.data("timer") || 0; clearTimeout(timer); $this.addClass("door"); timer = setTimeout(function() { $this.addClass("doorstatic"); }, 2000); // 2000 is in mil sec eq to 2 sec. $this.data("timer", timer); }, function () { var $this = $(this), timer = $this.data("timer") || 0; clearTimeout(timer); $this.removeClass("door doorstatic"); } ); Created a live example of the solution at jsFiddle.
unknown
d11711
train
Try this : df['Book'] = df['Exposure'].replace(0, 100)
unknown
d11712
train
Updated to return current year plus previous 5 years. Should be very fast as this is a small recordset. SELECT YEAR(GETDATE()) as YearNum UNION SELECT YEAR(GETDATE()) - 1 as YearNum UNION SELECT YEAR(GETDATE()) - 2 as YearNum UNION SELECT YEAR(GETDATE()) - 3 as YearNum UNION SELECT YEAR(GETDATE()) - 4 as YearNum UNION SELECT YEAR(GETDATE()) - 5 as YearNum ORDER BY YearNum DESC A: This gets all years from 2004 to the present, using a recursive CTE: with yearlist as ( select 2004 as year union all select yl.year + 1 as year from yearlist yl where yl.year + 1 <= YEAR(GetDate()) ) select year from yearlist order by year desc; A: Using ROW_NUMBER on any column from any large enough (stable) table would be one way to do it. SELECT * FROM ( SELECT TOP 100 2003 + ROW_NUMBER() OVER (ORDER BY <AnyColumn>) AS Yr FROM dbo.<AnyTable> ) Years WHERE Yr <= YEAR(GETDATE()) Note that <AnyTable> should contain at least the amount of rows equal to the amount of years you require. Edit (Cudo's to Joshua) * *Preferably, you'd select a table wich you know will not get truncated and/or deleted. A large enough system table should come to mind. *At present, being a lot older and wiser (older at least), I would implement this requirement using a CTE like mentioned in the answer given by Joshua. The CTE technique is far superior and less error prone than current given ROW_NUMBER solution. A: DECLARE @YEARS TABLE (Y INT) DECLARE @I INT, @NY INT SELECT @I = 2004, @NY = YEAR(GETDATE()) WHILE @I <= @NY BEGIN INSERT @YEARS SELECT @I SET @I = @I + 1 END SELECT Y FROM @YEARS ORDER BY Y DESC A: Try this: declare @lowyear int set @lowyear = 2004 declare @thisyear int set @thisyear = year(getdate()) while @thisyear >= @lowyear begin print @thisyear set @thisyear = (@thisyear - 1) end Returns 2009 2008 2007 2006 2005 2004 When you hit Jan 1, 2010. The same code will return: 2010 2009 2008 2007 2006 2005 2004 A: WITH n(n) AS ( SELECT 0 UNION ALL SELECT n+1 FROM n WHERE n < 10 ) SELECT year(DATEADD( YY, -n, GetDate())) FROM n ORDER BY n A: My two cents: The CTE is the best answer but I like @Lieven Keersmaekers answer as it doesn’t rely on recursion/loops or creating additional objects such as functions/date-tables. The key variation is mine simply uses the Top clause with an expression, instead of the top 100 (basically the whole table) I ask for N number of unordered rows first. This is quicker, if your base table happens to be quite large. Tested on SQL Server 2016 DECLARE @startYear smallint; SET @startYear = 2004; DECLARE @endYear smallint; SET @endYear = YEAR(GETDATE()); -- Top uses expression to bring in N number of rows. The (@startYear - 1) is to retain the start year SELECT [Yr] FROM ( SELECT TOP (@endYear - (@startYear - 1)) COUNT([object_id]) OVER (ORDER BY [object_id] DESC) + (@startYear - 1) AS [Yr] -- Add initial start year to Count FROM sys.all_objects ) AS T1 ORDER BY [Yr] DESC The comments above are valid, but Since OP’s requirements is literally a small set of values from 2004, the sys.all_objects will suffice, as SQL Server install comes with a ton of system objects. Hope that's a different take. A: I think you need to create a dates table, then just select your range from it. It can also come in useful when you need to select a date range with X data attached and not have any missed days. A: SET NOCOUNT ON DECLARE @max int set @max = DATEPART(year, getdate()) CREATE TABLE #temp (val int) while @max >= 2004 BEGIN insert #temp(val) values(@max) set @max = @max - 1 END SELECT * from #temp A: This is a simple query, check this (SELECT REPLACE((TO_CHAR(SYSDATE,'YYYY')-Rownum)+1,' ',NULL) yr FROM dual CONNECT BY LEVEL < 32) year A: Recursive CTE with no variables is a simpler way to go... WITH Years AS ( SELECT DATEPART(YEAR, GETDATE()) AS Year UNION ALL Select Year - 1 FROM Years WHERE Year > 2004 ) SELECT Year FROM Years ORDER BY Year DESC
unknown
d11713
train
/// <summary> /// Static method to detemine the WPF end point of the arc. /// </summary> /// <param name="arc">The DXF ArcEntity object to evaluate</param> /// <returns>Point with values of the arc end point.</returns> public static Point calcEndPoint(Arc arc) { double x = (Math.Cos(arc.endAngle * (Math.PI / 180)) * arc.radius) + arc.center.X; double y = arc.center.Y - (Math.Sin(arc.endAngle * (Math.PI / 180)) * arc.radius); return new Point(x, y); } /// <summary> /// Static method to detemine the WPF start point of the arc. /// </summary> /// <param name="arc">The DXF ArcEntity object to evaluate</param> /// <returns>Point with values of the arc start point.</returns> public static Point calcStartPoint(Arc arc) { double x = (Math.Cos(arc.startAngle * (Math.PI / 180)) * arc.radius) + arc.center.X; double y = arc.center.Y - (Math.Sin(arc.startAngle * (Math.PI / 180)) * arc.radius); return new Point(x, y); } public static bool checkArcSize(Arc arc) { double angleDiff = arc.endAngle - arc.startAngle; return !((angleDiff > 0 && angleDiff <= 180) || angleDiff <= -180); } Using System.Windows.Media.Path, PathFigure, ArcSegment: PathFigure figure = new PathFigure(); figure.StartPoint = calcStartPoint([your arc struct]); ArcSegment arc = new ArcSegment(); arc.Point = calcEndPoints([your arc struct]); arc.RotationAngle = Math.Abs(endAngle - startAngle); arc.Size = new Size(radius, radius); arc.IsLargeArc = checkArcSize([your arc struct]); figure.Segments.Add(arc); You will need to adjust each of the helper functions to use your struct as well as any C++ vs C# differences in syntax. I believe that these helper functions will bridge the gap between what the DXF spec gives you and what is required to draw the Arc in WPF.
unknown
d11714
train
I was able to achieve that with IIS successfully! I know the post is old but hopefully, it will save time for solution seekers :) First (just a reminder) ensure that you have .NET Core Hosting Bundle installed on IIS machine (link could be found here). Bear in mind that it will require at least WinSrvr2012R2 to run. Now copy published .net core API solution folder to the server. The same for Angular - next reminder here: execute ng build --prod then copy dist folder to the server. Then configure IIS - create a new web site that points to the Angular app folder. Your Angular app should run at this point (but obviously there is no API yet). Go to application pools - you will see the pool created for your application. Open basic settings and change CLR version to 'No managed code'. And finally, click on your Web Site and 'Add application' under it. Point to dotnet core API folder and name it using some short alias. Now you should have a website structure with the application included. If your angular app URL is: https://myiissrvr/ your API is under: https://myiissrvr/[ALIAS]/ DONE Final remarks: Usually, web API using URL structure like https://myiissrvr/api/[controller]/[action] So after bundling it together, it will look like: https://myiissrvr/[ALIAS]/api/[controller]/[action] With that approach, you should be able to attach multiple web API services under statically served Angular website - each one under its own alias. Potentially it might be useful in many scenarios. A: I've encountered the same problem, then I've found this post on medium, hope this works for you. Edit: Actually the solution that I've used is from that article. The idea is that you can't "publish" the API and the Angular app on the same port, but you can use a proxy to connect from the Angular app to the API on the other port. Update: sorry for not answering this long time ago. To deal with the cors issue (in this case) you can use a proxy with the ng serve command. For example, in my case I have used a proxy.conf.json file like this: { "/api/*": { "target": "http://localhost:3000", "secure": false, "pathRewrite": {"^/api" : ""} } } This code rewrite the url on every request to /api/* to the http://localhost:3000 where your api is listening. So, to illustrate, if in angular you make a request like http://localhost:4200/api/users it will be redirected/rewrited to http://localhost:3000/api/users solving the cors issue. Now, the way you have to run your angular application is different. ng serve --proxy-config proxy.conf.json
unknown
d11715
train
Try this. RewriteEngine on RewriteRule "/foo/bar$" "/some/folder/file.xml" [PT] you can even specify mime-type. RewriteRule "/foo/bar$" "/some/folder/file.xml" [PT,H=application/xml] You need internal remapping.
unknown
d11716
train
Compiling for another architecture is called cross compiling, but of course you would have read that on the Busybox FAQ. Not to mention the link provided there to cross-compilers for all architectures you could ask for. You could try find a pre-built MIPS binary, the best would be to ask the Busybox list directly if in doubt :)
unknown
d11717
train
According to the HashMultiMap Javadoc, you chose the right MultiMap for that purpose: The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an existing key-value pair has no effect. Now, you only have to make sure that equals() (and hashCode()) is implemented correctly on your values. I don't think you should worry about a faster way to do this. The HashMultiMap should be implemented pretty efficiently. A: If you want this behavior why not use a structure like: Map<Key,Set<Values>> myMap = new HashMap<Key,Set<Values>>(); EDIT: If you want to use the HashMultiMap i would recommend the one bellow Implementation of the MultiMap interface that uses a HashMap for the map and HashSets for automatically created sets. http://people.csail.mit.edu/milch/blog/apidocs/common/HashMultiMap.html
unknown
d11718
train
Using nltk.tag.stanford.POSTagger.tag_sents() for tagging multiple sentences. The tag_sents has replaced the old batch_tag function, see https://github.com/nltk/nltk/blob/develop/nltk/tag/stanford.py#L61 DEPRECATED: Tag the sentences using batch_tag instead of tag, see http://www.nltk.org/_modules/nltk/tag/stanford.html#StanfordTagger.batch_tag A: Found the solution. It is possible to run the POS Tagger in servlet mode and then connect to it via HTTP. Perfect. http://nlp.stanford.edu/software/pos-tagger-faq.shtml#d example start server in background nohup java -mx1000m -cp /var/stanford-postagger-full-2014-01-04/stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTaggerServer -model /var/stanford-postagger-full-2014-01-04/models/german-dewac.tagger -port 2020 >& /dev/null & adjust firewall to limit access to port 2020 from localhost only iptables -A INPUT -p tcp -s localhost --dport 2020 -j ACCEPT iptables -A INPUT -p tcp --dport 2020 -j DROP test it with wget wget http://localhost:2020/?die welt ist schön shutdown server pkill -f stanford restore iptable settings iptables -D INPUT -p tcp -s localhost --dport 2020 -j ACCEPT iptables -D INPUT -p tcp --dport 2020 -j DROP
unknown
d11719
train
Swift 3: // in case, that you have defined `attributedText` of label var attributes = attributedText.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, attributedText.length)) ... A: Swift 4: If you want to get the attributes for NSTextAttachment (just change the attribute value if you want font) commentTextView.attributedText.enumerateAttribute(NSAttachmentAttributeName, in:NSMakeRange(0, commentTextView.attributedText.length), options:.longestEffectiveRangeNotRequired) { value, range, stop in if let attachment = value as? NSTextAttachment { print("GOT AN ATTACHMENT! for comment at \(indexPath.row)") } } A: Apple expects you to use enumerateAttributesInRange:options:usingBlock:. The block you supply will receive ranges and the attributes applicable for that range. I've used that in my code to create invisible buttons that are placed behind text so that it acts as a hyperlink. You could also use enumerateAttribute:inRange:options:usingBlock: if there's only one you're interested in, but no halfway house is provided where you might be interested in, say, two attributes but not every attribute. A: Apple's Docs have a number of methods to access attributes: To retrieve attribute values from either type of attributed string, use any of these methods: attributesAtIndex:effectiveRange: attributesAtIndex:longestEffectiveRange:inRange: attribute:atIndex:effectiveRange: attribute:atIndex:longestEffectiveRange:inRange: fontAttributesInRange: rulerAttributesInRange: A: If you need all of the attributes from the string in the entire range, use this code: NSDictionary *attributesFromString = [stringWithAttributes attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, stringWithAttributes.length)]; A: Swift 5 – 4 let attributedText = NSAttributedString(string: "Hello, playground", attributes: [ .foregroundColor: UIColor.red, .backgroundColor: UIColor.green, .ligature: 1, .strikethroughStyle: 1 ]) // retrieve attributes let attributes = attributedText.attributes(at: 0, effectiveRange: nil) // iterate each attribute for attr in attributes { print(attr.key, attr.value) } In case, that you have defined attributedText of label. Swift 3 var attributes = attributedText.attributes( at: 0, longestEffectiveRange: nil, in: NSRange(location: 0, length: attributedText.length) ) Swift 2.2 var attributes = attributedText.attributesAtIndex(0, longestEffectiveRange: nil, inRange: NSMakeRange(0, attributedText.length) ) A: I have modified one of the answers with suggested fixes to prevent infinite recursion and application crashes. @IBDesignable extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor { return color } return nil } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[.foregroundColor: newValue!]) } } }
unknown
d11720
train
Filebeat is trying to resolve "logstash", but you don't have a service with that name. You have "logstash-logstash". Try to change filebeat config (line 49 and 116 in filebeat values.yaml) or change the name of your logstash service accordingly.
unknown
d11721
train
The left side of the bar is connected to the xAxis, which makes the left border less visible. There are some possible solutions to this issue. * *You can set the minimum value of the xAxis to -0.1 and set startOnTick property to false. Then the left border is visible (it's not directly connected to the axis). Demo: https://jsfiddle.net/BlackLabel/pqy84hvs/ API references: https://api.highcharts.com/highcharts/xAxis.startOnTick https://api.highcharts.com/highcharts/xAxis.min yAxis: { min: -0.1, visible: false, startOnTick: false } *You can set the borderWidth property to 3. Then the border is visible. Demo: https://jsfiddle.net/BlackLabel/01m6p47f/ API references: https://api.highcharts.com/highcharts/series.bar.borderWidth { name: 'Joe', borderWidth: 3, borderColor: 'red', data: [{ y: 33, }] } *You can also use SVG Renderer and render the border yourself. Docs: https://api.highcharts.com/class-reference/Highcharts.SVGRenderer Example demo of using SVG Renderer: https://jsfiddle.net/BlackLabel/2koczuq0/
unknown
d11722
train
You're getting inexact results because you're rounding down to two decimal places after every calculation. Your calculator isn't doing that. With no rounding. >>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5) Decimal('-0.2920353982300884955752212389') With rounding: >>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5) Decimal('-0.28') It only gets worse after that.
unknown
d11723
train
Try the following code: elements = soup.findAll('img', attrs={'class':'profile_photo_img'}) for element in elements: print element['data-src'] print element['alt'] Also make sure that the soup is right parsed from the html by printing it before you are searching for elements
unknown
d11724
train
Use plt.bar import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.bar(x, y, width=0.08,edgecolor='None',color='k',align='center') plt.show()
unknown
d11725
train
Isn't Firebase stores all its data in MongoDB? Update May 2016 Apparently a page where Firebase was mentioned in MongoDB's site was removed (http://www.mongodb.org/about/production-deployments/) After some search on their site I've found another page in their blog https://www.mongodb.com/post/45270275688/mongodbs-growing-ecosystem (mirror) where they say: it’s great to see so many companies building on MongoDB. Here are just a few: * *Modulus. A Node.js platform as a service (PaaS) offering, Modulus includes MongoDB as its default data store. This follows related offerings from Meteor and Firebase. An alternative to MongoDB would be RethinkDB and recently the team behind RethinkDB released Horizon, an open-source backend platform on NodeJS and that is kind of a locally hosted Firebase. Here's a nice talk about Horizon. A: Given that both MongoDB and Firebase are non-relational in nature, most of your data should map to Firebase cleanly. The Firebase REST endpoints support regular JSON, so getting your data in (and, back out if you choose) should also be easy. The main areas you need to keep watch for are: * *The Firebase API is realtime/asynchronous in nature; specifically, when clients are reading data. Migrating your backend request/response code to the client and using this approach will probably be the biggest area with regard to level of effort. *There will also be a disparity in the feature set that MongoDB and Firebase provide; notable areas include Mongo's support for doing things like MapReduce, Cursors, and free-text queries (Firebase doesn't currently support these areas). The other thing to keep in mind is that Firebase isn't an all-or-nothing type of undertaking. Apps can definitely take advantage of the realtime, scaling, and platform features piecemeal. A: Not specifically answering the question, but if you find Firebase lacking a few features which you you are used to with Mongo - I found a node package which will allow you to run both with Firebase as the master DB. Firebase * *Security/Authentication *Sockets MongoDB * *querying *indexing *aggregation https://www.npmjs.org/package/mongofb
unknown
d11726
train
You can try something like import random p = 0.5 arr = np.array([0, 0, 1, 1, 2, 2]) # number of similar elements required num_sim_element = round(len(arr)*p) # creating indeices of similar element hp = {} for i,e in enumerate(arr): if(e in hp): hp[e].append(i) else: hp[e] = [i] #print(hp) out_map = [] k = list(hp.keys()) v = list(hp.values()) index = 0 while(len(out_map) != num_sim_element): if(len(v[index]) > 0): k_ = k[index] random.shuffle(v[index]) v_ = v[index].pop() out_map.append((k_,v_)) index += 1 index %= len(k) #print(out_map) out_unique = set([i[0] for i in out_map]) out_indices = [i[-1] for i in out_map] out_arr = arr.copy() #for i in out_map: # out_arr[i[-1]] = i[0] for i in set(range(len(arr))).difference(out_indices): out_arr[i] = random.choice(list(out_unique.difference([out_arr[i]]))) print(arr) print(out_arr) assert 1 - (np.count_nonzero(arr - out_arr) / len(arr)) == p assert set(np.unique(arr)) == set(np.unique(out_arr)) [0 0 1 1 2 2] [1 0 1 0 0 2] A: Here's a version that might be a little easier to follow: import math, random # generate array of random values a = np.random.rand(4500) # make a utility list of every position in that array, and shuffle it indices = [i for i in range(0, len(a))] random.shuffle(indices) # set the proportion you want to keep the same proportion = 0.5 # make two lists of indices, the ones that stay the same and the ones that get shuffled anchors = indices[0:math.floor(len(a)*proportion)] not_anchors = indices[math.floor(len(a)*proportion):] # get values of non-anchor indices, and shuffle them not_anchor_values = [a[i] for i in not_anchors] random.shuffle(not_anchor_values) # loop original array, if an anchor position, keep original value # if not an anchor, draw value from shuffle non-anchor value list and increment the count final_list = [] count = 0 for e,i in enumerate(a): if e in not_anchors: final_list.append(i) else: final_list.append(not_anchor_values[count]) count +=1 # test proportion of matches and non-matches in output match = [] not_match = [] for e,i in enumerate(a): if i == final_list[e]: match.append(True) else: not_match.append(True) len(match)/(len(match)+len(not_match)) Comments in the code explain the approach. A: (EDITED to include a different and more accurate approach) One should note that not all values of the shuffled fraction p (number of shuffled elements divided by the total number of elements) is accessible. The possible value of p depend on the size of the input and on the number of repeated elements. That said, I can suggest two possible approaches: * *split your input into pinned and unpinned indices of the correct size and then shuffle the unpinned indices. import numpy as np def partial_shuffle(arr, p=1.0): n = arr.size k = round(n * p) shuffling = np.arange(n) shuffled = np.random.choice(n, k, replace=False) shuffling[shuffled] = np.sort(shuffled) return arr[shuffling] The main advantage of approach (1) is that it can be easily implemented in a vectorized form using np.random.choice() and advanced indexing. On the other hand, this works well as long as you are willing to accept that some shuffling may return you some elements unshuffled because of repeating values or simply because the shuffling indexes are accidentally coinciding with the unshuffled ones. This causes the requested value of p to be typically larger than the actual value observed. If one needs a relatively more accurate value of p, one could just try performing a search on the p parameter giving the desired value on the output, or go by trial-and-error. *implement a variation of the Fisher-Yates shuffle where you: (a) reject swappings of positions whose value is identical and (b) pick only random positions to swap that were not already visited. def partial_shuffle_eff(arr, p=1.0, inplace=False, tries=2.0): if not inplace: arr = arr.copy() n = arr.size k = round(n * p) tries = round(n * tries) seen = set() i = l = t = 0 while i < n and l < k: seen.add(i) j = np.random.randint(i, n) while j in seen and t < tries: j = np.random.randint(i, n) t += 1 if arr[i] != arr[j]: arr[i], arr[j] = arr[j], arr[i] l += 2 seen.add(j) while i in seen: i += 1 return arr While this approach gets to a more accurate value of p, it is still limited by the fact that the target number of swaps must be even. Also, for inputs with lots of uniques the second while (while j in seen ...) is potentially an infinite loop so a cap on the number of tries should be set. Finally, you would need to go with explicit looping, resulting in a much slower execution speed, unless you can use Numba's JIT compilation, which would speed up your execution significantly. import numba as nb partial_shuffle_eff_nb = nb.njit(partial_shuffle_eff) partial_shuffle_eff_nb.__name__ = 'partial_shuffle_eff_nb' To test the accuracy of the partial shuffling we may use the (percent) Hamming distance: def hamming_distance(a, b): assert(a.shape == b.shape) return np.count_nonzero(a == b) def percent_hamming_distance(a, b): return hamming_distance(a, b) / len(a) def shuffling_fraction(a, b): return 1 - percent_hamming_distance(a, b) And we may observe a behavior similar to this: funcs = ( partial_shuffle, partial_shuffle_eff, partial_shuffle_eff_nb ) n = 12 m = 3 arrs = ( np.zeros(n, dtype=int), np.arange(n), np.repeat(np.arange(m), n // m), np.repeat(np.arange(3), 2), np.repeat(np.arange(3), 3), ) np.random.seed(0) for arr in arrs: print(" " * 24, arr) for func in funcs: shuffled = func(arr, 0.5) print(f"{func.__name__:>24s}", shuffled, shuffling_fraction(arr, shuffled)) # [0 0 0 0 0 0 0 0 0 0 0 0] # partial_shuffle [0 0 0 0 0 0 0 0 0 0 0 0] 0.0 # partial_shuffle_eff [0 0 0 0 0 0 0 0 0 0 0 0] 0.0 # partial_shuffle_eff_nb [0 0 0 0 0 0 0 0 0 0 0 0] 0.0 # [ 0 1 2 3 4 5 6 7 8 9 10 11] # partial_shuffle [ 0 8 2 3 6 5 7 4 9 1 10 11] 0.5 # partial_shuffle_eff [ 3 8 11 0 4 5 6 7 1 9 10 2] 0.5 # partial_shuffle_eff_nb [ 9 10 11 3 4 5 6 7 8 0 1 2] 0.5 # [0 0 0 0 1 1 1 1 2 2 2 2] # partial_shuffle [0 0 2 0 1 2 1 1 2 2 1 0] 0.33333333333333337 # partial_shuffle_eff [1 1 1 0 0 1 0 0 2 2 2 2] 0.5 # partial_shuffle_eff_nb [1 2 1 0 1 0 0 1 0 2 2 2] 0.5 # [0 0 1 1 2 2] # partial_shuffle [0 0 1 1 2 2] 0.0 # partial_shuffle_eff [1 1 0 0 2 2] 0.6666666666666667 # partial_shuffle_eff_nb [1 2 0 1 0 2] 0.6666666666666667 # [0 0 0 1 1 1 2 2 2] # partial_shuffle [0 0 1 1 0 1 2 2 2] 0.2222222222222222 # partial_shuffle_eff [0 1 2 1 0 1 2 2 0] 0.4444444444444444 # partial_shuffle_eff_nb [0 0 1 0 2 1 2 1 2] 0.4444444444444444 or, for an input closer to your use-case: n = 4500 m = 3 arr = np.repeat(np.arange(m), n // m) np.random.seed(0) for func in funcs: shuffled = func(arr, 0.5) print(f"{func.__name__:>24s}", shuffling_fraction(arr, shuffled)) # partial_shuffle 0.33777777777777773 # partial_shuffle_eff 0.5 # partial_shuffle_eff_nb 0.5 Finally some small benchmarking: n = 4500 m = 3 arr = np.repeat(np.arange(m), n // m) np.random.seed(0) for func in funcs: print(f"{func.__name__:>24s}", end=" ") %timeit func(arr, 0.5) # partial_shuffle 213 µs ± 6.36 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # partial_shuffle_eff 10.9 ms ± 194 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # partial_shuffle_eff_nb 172 µs ± 1.79 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
unknown
d11727
train
Check this codesanbox I made: https://codesandbox.io/s/stack-71649799-v-chip-data-table-item-slow-z7p2db?file=/src/components/Example.vue You can use the item slot of the data table. Some vuetify components comes with special sections for easier customization called slots, in this case the item slot of the data table let you customize individual colums content like this: <v-data-table :headers="headers" :items="desserts" :items-per-page="5" class="elevation-1" > <template #item.calories="{ item }"> <v-chip dark color="red darken-2">{{ item.calories }}</v-chip> </template> <template #item.fat="{ item }"> <v-chip dark color="orange darken-2">{{ item.fat }}</v-chip> </template> </v-data-table> If you're using es-lint you might encounter a warning mention something about the valid-v-slot rule, this is a known false positive that you can read more about in this GitHub issue thread, I personally just turn that es-lint rule off. For more info about data table slots, check the vuetify documentation page.
unknown
d11728
train
Assuming that #search is probably a text input field, you can add the following code right before your ajax request: // get the value that the user has typed var v = $(this).val(); // don\'t go on if less than 3 chars or // some other key was pressed that did not change the data if (v.length < 3 || v == $(this).data('prev-val')) return; // set the old value as the new one $(this).data('prev-val', v); // now call ajax Following a comment in the question, this does not deal with any time delay. A timer could easily be used to trigger the ajax request, and cancel any previous timer before setting a new one. But this would probably make matters more complicated for no good reason.
unknown
d11729
train
strlen(key) is invalid in later code as earlier code was injecting null characters in key[] whenever an 'a' or 'A' was used: if(islower(key[i])) { key[i] = key[i] - 'a'; Find the string length of key[] before changing its contents and use that int n = strlen(key); ... // k = j % strlen(key); k = j % n;
unknown
d11730
train
Looks like the only two things you need from URL are action and controller and if the action is "index" you don't need it. In this case I believe that you are doing it right. This is a slightly modified piece of code I was using in ASP.NET MVC project: string actionName = this.ControllerContext.RouteData.Values["action"].ToString(); string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString(); if (actionName.Equals("index", StringComparison.InvariantCultureIgnoreCase)) { actionName = string.Empty; } string result = $"/{controllerName}/{actionName}"; There is one more thing to mention: "areas". Once I was working on website which had them, so they may appear in your URL too if your website uses "area" approach. I hope it helps
unknown
d11731
train
We can use separate library(dplyr) library(tidyr) df1 %>% separate(products, into = paste0('product', 1:3), sep=",\\s+", extra = "merge") # id product1 product2 product3 #1 1001 milk cheese sugar #2 1002 milk <NA> <NA> #3 1003 cheese eggs <NA> Or cSplit which would automatically detect the number of elements without having to specify the columns library(splitstackshape) cSplit(df1, 'products', ', ') data df1 <- structure(list(id = 1001:1003, products = c("milk, cheese, sugar", "milk", "cheese, eggs")), class = "data.frame", row.names = c(NA, -3L)) A: Let's say we have non definite number of products in our dataframe (More than three). We can use separate_rows() from tidyverse without issues about the number of products and then reshape to wide. Here the code with data you shared (I added more items to see this approach). Here the code: library(tidyverse) #Data df <- structure(list(id = c(1001, 1002, 1003), products = c("milk, cheese, sugar, rice, soap, water", "milk", "cheese, eggs")), row.names = c(NA, -3L), class = "data.frame") The code: #Code df %>% separate_rows(products,sep = ', ') %>% group_by(id) %>% mutate(Var=paste0('V',1:n())) %>% pivot_wider(names_from = Var,values_from=products) %>% replace(is.na(.),'') Output: # A tibble: 3 x 7 # Groups: id [3] id V1 V2 V3 V4 V5 V6 <dbl> <chr> <chr> <chr> <chr> <chr> <chr> 1 1001 milk "cheese" "sugar" "rice" "soap" "water" 2 1002 milk "" "" "" "" "" 3 1003 cheese "eggs" "" "" "" ""
unknown
d11732
train
You can set up a temporary DataFrame with custom columns to sort and use its index to reorder the original: idx = (df .assign(Length=-df['Length'].sub(10).abs(), Name=pd.Categorical(df['Name'], categories=['Joe', 'Bob'], ordered=True) ) .sort_values(by=['Length', 'Score', 'Name'], ascending=False) .index ) # reorder values based on priority sorted_df = df.loc[idx] Alternative if only some names have a priority: d = {'Bob': 2} # in the assign of the previous code #.assign( Name=df['Name'].map(d).fillna(0) #) If you want to add a rank instead of sorting: df.loc[idx, 'rank'] = range(len(df))
unknown
d11733
train
by default, a string field will have a standard tokenizer, that will emit a single token "FRUIT12" for the "FRUIT12" input. You need to use a word_delimiter token filter in your field analyzer to allow the behavior your are expecting : GET _analyze { "text": "FRUIT12", "tokenizer": "standard" } gives { "tokens": [ { "token": "FRUIT12", "start_offset": 0, "end_offset": 7, "type": "<ALPHANUM>", "position": 0 } ] } ----------- and GET _analyze { "text": "FRUIT12", "tokenizer": "standard", "filters": ["word_delimiter"] } gives { "tokens": [ { "token": "FRUIT", "start_offset": 0, "end_offset": 5, "type": "<ALPHANUM>", "position": 0 }, { "token": "12", "start_offset": 5, "end_offset": 7, "type": "<ALPHANUM>", "position": 1 } ] } If your add the word_delimiter token filter on your field, any search query on this field will also have the word_delimiter token filter enabled ( unless you override it with search_analyzer option in the mapping ) so "FRUIT12" mono-term query will be "translated" to ["FRUIT", "12"] multi term query.
unknown
d11734
train
This should work: echo "PREPENDED STRING" | cat - /tmp/file | sed 's/test/test2/g' > /tmp/result A: Or just use only sed sed -e 's/test/test2/g s/^/PREPEND STRING/' /tmp/file > /tmp/result A: Or also: { echo "PREPENDED STRING" ; cat /tmp/file | sed 's/test/test2/g' } > /tmp/result A: Try: (printf "%s" "PREPENDED STRING"; sed 's/test/test2/g' /tmp/file) >/tmp/result The parentheses run the command(s) inside a subshell, so that the output looks like a single stream for the >/tmp/result redirect. A: If this is ever for sending an e-mail, remember to use CRLF line-endings, like so: echo -e 'To: [email protected]\r' | cat - body-of-message \ | sed 's/test/test2/g' | sendmail -t Notice the -e-flag and the \r inside the string. Setting To: this way in a loop gives you the world's simplest bulk-mailer. A: Another option: assuming the prepended string should only appear once and not for every line: gawk 'BEGIN {printf("%s","PREPEND STRING")} {gsub(/test/, "&2")} 1' in > out
unknown
d11735
train
Servlet2 must be without any mapping in annotations or in web.xml. Then you cannot use HttpServletRequest#getRequestDispatcher(String), which is a container managed method that checks those mappings. That condition is ridiculous and makes no sense. If you aren't going to use the Servlet container, don't make a Servlet. Make a service class that performs the actions you need. You don't need to make everything a Servlet. Your only (ridiculous) alternative is to instantiate Servlet2 and explicitly invoke its doGet method.
unknown
d11736
train
try this import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Chronometer; public class MainActivity extends AppCompatActivity { Chronometer simpleChronometer; Button start, stop, restart, setFormat, clearFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initiate views simpleChronometer = (Chronometer) findViewById(R.id.simpleChronometer); start = (Button) findViewById(R.id.startButton); stop = (Button) findViewById(R.id.stopButton); restart = (Button) findViewById(R.id.restartButton); setFormat = (Button) findViewById(R.id.setFormat); clearFormat = (Button) findViewById(R.id.clearFormat); // perform click event on start button to start a chronometer start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.start(); } }); // perform click event on stop button to stop the chronometer stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.stop(); } }); // perform click event on restart button to set the base time on chronometer restart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setBase(SystemClock.elapsedRealtime()); } }); // perform click event on set Format button to set the format of chronometer setFormat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setFormat("Time (%s)"); } }); // perform click event on clear button to clear the current format of chronmeter as you set through set format clearFormat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub simpleChronometer.setFormat(null); } }); } } A: I know it may be the little late, this can help someone later on stop = (Button) findViewById(R.id.stopButton); chronometer = findViewById(R.id.chronometerID); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { chronometer.stop(); chronometer.setBase(SystemClock.elapsedRealtime()); } });
unknown
d11737
train
You are incorrectly handling the files and everything else when inserting them into the database. All files that are already there are damaged and probably destroyed. addslashes() is no escaping function for a database. Always use the escaping function that comes with the DB extension you are using. If you are using mysqli, then the correct function must be mysqli_real_escape_string(). You should however have a look at prepared statements. These will use an different way of transferring the data that does not need escaping. Do pay attention however to the setting of magic quotes. The preferred setting is OFF, and the recent PHP versions starting with 5.4 have this feature removed already. So you have to deal with escaping the data you insert into the database anyway.
unknown
d11738
train
ID should always be unique to each element, so I am using a class instead. Use of parents() will give you the the container to find() the hidden inputs in to retrieve the values. $('.btnitemaddtotray').on('click',function() { var btn = $(this), row = btn.parents('td').first(); itemId = row.find('.itemid').val(), oid = row.find('.oid').val(); console.log(itemId,oid); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table><tr> <td colspan="2"> <input type="hidden" class="itemid" name="stockitemid" value="@item.ID"/> <input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID"/> <div class="btn-toolbar row-action"> <div class="btn-group pull-right"> <button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button> </div></div> </td></tr> <tr> <td colspan="2"> <input type="hidden" class="itemid" name="stockitemid" value="@item.ID2"/> <input type="hidden" class="oid" name="outletid" value="@item.OUTLET_ID2"/> <div class="btn-toolbar row-action"> <div class="btn-group pull-right"> <button class="btn btn-primary btnitemaddtotray" data-toggle="modal" data-target="#addtotrayModal" title="Add Item">Add Item</button> </div></div> </td></tr> </table>
unknown
d11739
train
I think it's you're just missing the className="loading" in <Loading />: import { Loading, MyComponent } from "./index"; import ReactDOM from "react-dom"; describe("MyComponent", () => { it("spying on ReactDOM", () => { const spy = jest.spyOn(ReactDOM, "render"); MyComponent.show(); expect(spy).toHaveBeenCalledWith( <Loading className="loading" />, document.body.querySelector(".loading-container") ); }); }); Alternatively, you can mock ReactDOM instead of spying on it: import { Loading, MyComponent } from "./index"; import ReactDOM from "react-dom"; jest.mock("react-dom", () => ({ __esModule: true, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { Events: [], }, createPortal: jest.fn(), findDOMNode: jest.fn(), flushSync: jest.fn(), hydrate: jest.fn(), render: jest.fn(), unmountComponentAtNode: jest.fn(), unstable_batchedUpdates: jest.fn(), unstable_createPortal: jest.fn(), unstable_renderSubtreeIntoContainer: jest.fn(), version: "17.0.1", })); describe("MyComponent", () => { it("mocking ReactDOM", () => { MyComponent.show(); expect(ReactDOM.render).toHaveBeenCalledWith( <Loading className="loading" />, document.body.querySelector(".loading-container") ); }); });
unknown
d11740
train
If you are using two GPU's let's say Intel GPU and NVIDIA GPU, then please choose graphic driver to NVIDIA GPU by opening NVIDIA control Panel. In case if you are using only one driver then please update NVIDIA GPU graphic driver.
unknown
d11741
train
Systematically build it up as you describe * *get hits and last hit per UserID and ProductID *select rows from this aggregated data frame that match max hits and max last_hit import io import pandas as pd df = pd.read_csv(io.StringIO(''' ProductID UserID Activity OS date time 392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000 764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000 1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000 1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000 2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000 3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000 '''), sep="\s", engine="python") df["date"] = pd.to_datetime(df["date"] + " " + df["time"]) # count hits per user and product after sorting so last_hit works dfh = df.sort_values(["UserID","date"]).groupby(["UserID","ProductID"]).agg(hits=("OS","size"),last_hit=("date","last")) # select the row with max hits and last hit dfh.loc[dfh["hits"].eq(dfh["hits"].max()) & dfh["last_hit"].eq(dfh["last_hit"].max())] output hits last_hit UserID ProductID U100040 Pr100513 2 2018-05-27 02:18:47.676
unknown
d11742
train
As I Know, It should be 10 gigabytes for one single database not for all, and about your last question, It shouldn't be like this. the limit is 10 gigs for each database and I don't think there is any limit for servers. and also this site might help you find out more about this.
unknown
d11743
train
If all first names had the same length, then you would be able to use sortrows, but in your case, that would require padding and modifying your array, anyway, so that you're better off converting it into "LAST FIRST MIDDLE" before applying sort. Fortunately, there's a simple regular expression for that: names = {'John Doe';'Roger Adrian';'John Fitzgerald Kennedy'}; names_rearranged = regexprep(names,'(.*) (\w*)$','$2 $1') names_rearranged = 'Doe John' 'Adrian Roger' 'Kennedy John Fitzgerald' [names_rearranged_sorted, idx_sorted] = sort(names_rearranged); names_sorted = names(idx_sorted) names_sorted = 'Roger Adrian' 'John Doe' 'John Fitzgerald Kennedy'
unknown
d11744
train
Probably the best route is do a custom lookup and change the extended data type of the key field to reflect that. In this way the change is reflected in all places. See form FiscalCalendarYearLookup and EDT FiscalYearName as an example of that. If you only need to change a single place, the easy option is to override performFormLookup on the calling form. You should also override the DisplayLength property of the extended data type of the long field. public void performFormLookup(FormRun _form, FormStringControl _formControl) { FormGridControl grid = _form.control(_form.controlId('grid')); grid.autoSizeColumns(false); super(_form,_formControl); } This will not help you unless you have a form, which may not be the case in this report scenario. Starting in AX 2009 the kernel by default auto-updates the control sizes based on actual record content. This was a cause of much frustration as the sizes was small when there was no records and these sizes were saved! Also the performance of the auto-update was initially bad in some situations. As an afterthought the grid control autoSizeColumns method was provided but it was unfortunately never exposed as a property. A: you can extends the sysTableLookup class and override the buildFromGridDesign method to set the grid control width. protected void buildFormGridDesign(FormBuildGridControl _formBuildGridControl) { if (gridWidth > 0) { _formBuildGridControl.allowEdit(true); _formBuildGridControl.showRowLabels(false); _formBuildGridControl.widthMode(2); _formBuildGridControl.width(gridWidth); } else { super(_formBuildGridControl); } }
unknown
d11745
train
I had the same problem and I solved it this way: * *First add gammu user to sudoers, with no password: type: $ sudo visudo and add: gammu ALL=(ALL) NOPASSWD: ALL *Then run gammu-smsd as root user: in /etc/init.d/gammu-smsd change USER=gammu to USER=root save it and don't forget to restart daemon: service gammu-smsd restart *In RunOnReceive script add sudo in front of gammu-smsd-inject: e.g.: sudo gammu-smsd-inject TEXT my_tel_num -text "Hello world!" I hope this will work for you too! P.S.: I use Gammu version 1.31.90.
unknown
d11746
train
With help from an expert the following works: def user_addgroup_handler(sender, instance, created, *args, **kwargs): # g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county))) # group = Group.objects.get(name=instance.business_location_county.name) # for g in CustomUser.objects.all(): # print(g.business_location_county_id) if created: # Get or create group new_group, created = Group.objects.get_or_create( name=instance.business_location_county.name, forum_id=instance.business_location_county.id) # add new group to user instance.groups.add(new_group) post_save.connect(user_addgroup_handler, sender=CustomUser)
unknown
d11747
train
First you need to add attribute enctype="multipart/form-data" to your form tag like this: <form class="form-horizontal hide form-data" role="form" enctype="multipart/form-data"> And formData can't be inspected in console window you should use this way for (var pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } Finally to submit your data use ajax call $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function (data) { alert(data) }, cache: false, contentType: false, processData: false });
unknown
d11748
train
Using the DateTime object it can be easy and accurate $dates = ['25/11/2021','24/11/2021','23/11/2021']; foreach ( $dates as $date){ $df = (DateTime::CreateFromFormat('d/m/Y', $date))->format('l d F Y'); echo "<li class='header'><h1>{$df}</h1></li>" ."\n"; } RESULTS <li class='header'><h1>Thursday 25 November 2021</h1></li> <li class='header'><h1>Wednesday 24 November 2021</h1></li> <li class='header'><h1>Tuesday 23 November 2021</h1></li> PHP Manual for DateTime object
unknown
d11749
train
Drawing the 'hash mark' is going to be the real problem. TreeView has a DrawMode property but its DrawItem event doesn't let you draw between the nodes. You need to handle this by changing the cursor to indicate what is going to happen. Use the GiveFeedback event, set e.UseCustomCursors to false and assign Cursor.Current to a custom cursor that indicates the operation. A: This article articulates the same issue and provides an approach somewhat similar to the one you are already following (with the exception that the thresholds are essentially percentages of the height of the tree node). Based on this, and the fact that when I was doing this before, that was the best approach I could find, I think you're basically on track.
unknown
d11750
train
* *You haven't closed the tag correctly for the "#addrow" button. *You can extract the values from the modal like so (after you give the <select> elements a proper id: var dayPickerSelect1 = $("#daypicker-select1").val(); var dayPickerSelect2 = $("#daypicker-select2").val(); *You can then pass the extracted values to the table like so: <input type="text" class="form-control" name="Day' + counter + '" value="' + dayPickerSelect1 + '"/> <input type="text" class="form-control" name="Session' + counter + '" value="' + dayPickerSelect2 + '"/>
unknown
d11751
train
1) You can use HTML5 & javaScript to take screenshots. This will work for sure. check more details here (function (exports) { function urlsToAbsolute(nodeList) { if (!nodeList.length) { return []; } var attrName = 'href'; if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) { attrName = 'src'; } nodeList = [].map.call(nodeList, function (el, i) { var attr = el.getAttribute(attrName); if (!attr) { return; } var absURL = /^(https?|data):/i.test(attr); if (absURL) { return el; } else { return el; } }); return nodeList; } function screenshotPage() { urlsToAbsolute(document.images); urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']")); var screenshot = document.documentElement.cloneNode(true); var b = document.createElement('base'); b.href = document.location.protocol + '//' + location.host; var head = screenshot.querySelector('head'); head.insertBefore(b, head.firstChild); screenshot.style.pointerEvents = 'none'; screenshot.style.overflow = 'hidden'; screenshot.style.webkitUserSelect = 'none'; screenshot.style.mozUserSelect = 'none'; screenshot.style.msUserSelect = 'none'; screenshot.style.oUserSelect = 'none'; screenshot.style.userSelect = 'none'; screenshot.dataset.scrollX = window.scrollX; screenshot.dataset.scrollY = window.scrollY; var script = document.createElement('script'); script.textContent = '(' + addOnPageLoad_.toString() + ')();'; screenshot.querySelector('body').appendChild(script); var blob = new Blob([screenshot.outerHTML], { type: 'text/html' }); return blob; } function addOnPageLoad_() { window.addEventListener('DOMContentLoaded', function (e) { var scrollX = document.documentElement.dataset.scrollX || 0; var scrollY = document.documentElement.dataset.scrollY || 0; window.scrollTo(scrollX, scrollY); }); } function generate() { window.URL = window.URL || window.webkitURL; window.open(window.URL.createObjectURL(screenshotPage())); } exports.screenshotPage = screenshotPage; exports.generate = generate; })(window); 2) You can also use html2canvas below is the simple example of how to implement. JS html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas) }); HTML <div id="capture" style="padding: 10px; background: #f5da55"> <h4 style="color: #000; ">Hello world!</h4> </div> download & include in the head section //* <script src="Scripts/jquer_latest_2.11_.min.js" type="text/javascript"></script> <script src="Scripts/html2canvas.js" type="text/javascript"></script> //*
unknown
d11752
train
Python as a built-in module called json, that provides a json.JSONDecoder and a json.JSONEncoder class, a JSON (JavaScript Object Notation) parser (json.loads) and few other functions. If you have your data.json file, you can convert it to Python... import json with open("data.json", 'r+') as file: my_data = json.load(file) ...edit it... my_data["Key"] = "New Value" ...and encode it back json.dump(my_data, file)
unknown
d11753
train
You need to update the form control value: if (this.formIdFromParent) { this.service.getFiles(this.formIdFromParent).subscribe(result => { this.fileData = result; this.formIdFromParent.controls['Notes'].setValue(this.fileData. GlobalNotes); }) }
unknown
d11754
train
AVI files are practically limited in size. when you force it to use OPENCV_MJPEG, it will only use OpenCV's own writing methods, which can only do AVI and MJPEG. if you need a different container, you have to use a different backend, such as FFMPEG. you can still have MJPG for a codec (fourcc).
unknown
d11755
train
With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming. You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device. You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time). One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) : <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png"> <link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png"> <link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png"> <link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png"> <link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png"> <link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192"> <link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160"> <link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96"> <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="mstile-144x144.png"> <meta name="msapplication-config" content="browserconfig.xml"> In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines: <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="/manifest.json"> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"> <meta name="theme-color" content="#ffffff"> A: Below given some information about fav Icon What Is FavIcon?  FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure. How It Works ?  Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference. <link rel="icon" href="favicon.ico" type="image/ico"/> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/> Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"  Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.  We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages A: you could take a look at the w3 how to, i think you will find it helpful your link tag attribute should be rel="icon" A: I use this on my site and it works great. <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico"/> A: There is a very simple method to set a favicon, which had been around for a long time AFAIK. Place the favicon.ico file in the default location. i.e http://www.yoursite.com/favicon.ico This works in almost every browser without a <link> tag. However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag A: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en-US"> <head profile="http://www.w3.org/2005/10/profile"> <link rel="icon" type="image/png" href="http://example.com/myicon.png"> </head> <body> ... </body> </html> rel="shortcut icon" should be rel="icon" Source: W3C A: From experience of my favicon.ico not appearing, I am sharing my experience. You can't get it to show until you put your website on a host, therefore, try put it on a localhost using XAMPP - http://www.apachefriends.org/en/xampp.html. This is how the favicon appears and like others recommended, change: rel="shortcut icon" to rel="icon" Also this way .png favicons can be used for slickness. A: <head> <link rel="shortcut icon" href="favicon.ico"> </head> A: In my site, I use this: <!-- for FF, Chrome, Opera --> <link rel="icon" type="image/png" href="/assets/favicons/favicon-16x16.png" sizes="16x16"> <link rel="icon" type="image/png" href="/assets/favicons/favicon-32x32.png" sizes="32x32"> <!-- for IE --> <link rel="icon" type="image/x-icon" href="/assets/favicons/favicon.ico" > <link rel="shortcut icon" type="image/x-icon" href="/assets/favicons/favicon.ico"/> To simplify your life, use this favicons generator http://realfavicongenerator.net A: This method is recommended <link rel="icon" type="image/png" href="/somewhere/myicon.png" /> A: Try put this in the head of the document: <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/> A: I use this https://realfavicongenerator.net/ to generate all the possible favicons scenarios and it is free.
unknown
d11756
train
Another way: data='''a b 0 (45.349586099999996, -75.81031967988278) 1 (-37.77922725, 175.2010323246593) 2 (-42.9945669, 170.7100413) 3 (-39.2711067, 174.154795) 4 (51.2800275, 1.0802533) 5 (-41.30222105, 172.89453190955697) 6 (-35.3712702, 173.7405337) 7 (-45.7255555, 168.2936808) 8 (-40.3284102, 175.8190684) 9 (-45.1299859, 169.5248818) 10 (-37.9503756, 176.93828736155422)''' df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python') df[['lat', 'lon']] = df.b.str[1:-1].str.split(',', expand=True) a b lat lon 0 0 (45.349586099999996, -75.81031967988278) 45.349586099999996 -75.81031967988278 1 1 (-37.77922725, 175.2010323246593) -37.77922725 175.2010323246593 2 2 (-42.9945669, 170.7100413) -42.9945669 170.7100413 3 3 (-39.2711067, 174.154795) -39.2711067 174.154795 4 4 (51.2800275, 1.0802533) 51.2800275 1.0802533 5 5 (-41.30222105, 172.89453190955697) -41.30222105 172.89453190955697 6 6 (-35.3712702, 173.7405337) -35.3712702 173.7405337 7 7 (-45.7255555, 168.2936808) -45.7255555 168.2936808 8 8 (-40.3284102, 175.8190684) -40.3284102 175.8190684 9 9 (-45.1299859, 169.5248818) -45.1299859 169.5248818 10 10 (-37.9503756, 176.93828736155422) -37.9503756 176.93828736155422 A: Data Position 0 (45.349586099999996,-75.81031967988278) 1 (-37.77922725,175.2010323246593) 2 (-42.9945669,170.7100413) 3 (-39.2711067,174.154795) 4 (51.2800275,1.0802533) 5 (-41.30222105,172.89453190955697) 6 (-35.3712702,173.7405337) 7 (-45.7255555,168.2936808) 8 (-40.3284102,175.8190684) 9 (-45.1299859,169.5248818) 10 (-37.9503756,176.93828736155422) Solution #Strip of the brackets if column is string and not tuple. #str.split column to make it a list #stack it to dataframe it pd.DataFrame(np.vstack(df['Position'].str.strip('\(\)').str.split(',')), columns=['Lat','Long']) Lat Long 0 45.349586099999996 -75.81031967988278 1 -37.77922725 175.2010323246593 2 -42.9945669 170.7100413 3 -39.2711067 174.154795 4 51.2800275 1.0802533 5 -41.30222105 172.89453190955697 6 -35.3712702 173.7405337 7 -45.7255555 168.2936808 8 -40.3284102 175.8190684 9 -45.1299859 169.5248818 10 -37.9503756 176.93828736155422
unknown
d11757
train
SymPy has a lambdify module for these purposes: from sympy.utilities.lambdify import lambdify func = lambdify((x1, x2), r.diff(x1)) func(1, 2) # evaluate the function efficiently at (1, 2)
unknown
d11758
train
You get the final URL you want to use for tracking purposes back with a Auth_OpenID_SuccessResponse object, in the claimed_id attribute. (The getDisplayIdentifier() method outputs a version more intended for human consumption, which may or may not be different.)
unknown
d11759
train
Despite the fact that using a VARCHAR(255) as a foreign key is probably highly inefficient and/or will require huge indices, I guess that generally an option that defines the foreign key of the other table would come in handy here, similar to targetForeignKey for belongsToMany associations. You may to want to suggest that as an enhancement. Result formatters Currently this doesn't seem to be possible out of the box using associations, so you'd probably have to select and inject the associated records yourself, for example in a result formatter. $Villas ->find() ->formatResults(function($results) { /* @var $results \Cake\Datasource\ResultSetInterface|\Cake\Collection\Collection */ // extract the custom foreign keys from the results $keys = array_unique($results->extract('complex')->toArray()); // find the associated rows using the extracted foreign keys $villas = \Cake\ORM\TableRegistry::get('Villas') ->find() ->where(['complex IN' => $keys]) ->all(); // inject the associated records into the results return $results->map(function ($row) use ($villas) { if (isset($row['complex'])) { // filters the associated records based on the custom foreign keys // and adds them to a property on the row/entity $row['complexs'] = $villas->filter(function ($value, $key) use ($row) { return $value['complex'] === $row['complex'] && $value['id'] !== $row['id']; }) ->toArray(false); } return $row; }); }); This would fetch the associated rows afterwards using the custom foreign keys, and inject the results, so that you'd end up with the associated records on the entities. See also Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields There might be other options, like for example using a custom eager loader that collects the necessary keys, combined with a custom association class that uses the proper key for stitching the results together, see * *API > \Cake\ORM\EagerLoader::_collectKeys() *API > \Cake\ORM\Association\SelectableAssociationTrait::_resultInjector()
unknown
d11760
train
Another form to do it is recode age_n (0/65=0 "0") (66/150=1 "over 65") So you have a dummy with your requirement (from 0 to 65, values change to 0, appearing a "0" in the table; from 66 to 150, values change to 1, appearing this time "over 65" in the table). If you want to maintain values of age_n, gen age_n2=age_n and do the process with age_n2 instead of age_n.
unknown
d11761
train
That's the most important bit to solve this problem: x = r * Math.cos(t) + offsetX; y = r * Math.sin(t) + offsetY; which is parametric form of circle equation... "r" is radius and "t" is 'progress' from 0 to 2π, (wiki) You can easily do that in JavaScript using either "canvas" or SVG (check Raphael.js library) A: Here's a great link :) arc I hope it works for you :)
unknown
d11762
train
This is indeed possible, as I have just done it. You need to trap the 'moveend' and 'move' events from the map being panned or zoomed (moveend is triggered at the end of a zoom, but you could trap 'zoomend' as well to be on the safe side). If you trap these using the parent map as the context then you can get the new map centre. Bear in mind that the map centre can change when the map is zoomed if the navigation control is being used and the zoom is done using the mouse. Then use the moveTo method (childmap.moveTo(). I've chosen the moveTo method as (although not well documented) this is what is always finally called in any pan or zoom event on any map. As an aside, calling moveTo will also cause the 'move', 'moveend' events to be triggered on the child map. If you make a collection of maps using json, and use jQuery, the actual code would look something like this (I'm assuming you know how to trap map events in OpenLayers); var newCentre = zoomedMap.getCenter(); $.each(maps, function (ind, map) { if (map !== zoomedMap) map.moveTo(newCentre, newZoom); }); where maps is my collection of maps, zoomedMap is the map the user actually triggered the pan or zoom event on (I've called it zoomeMap but it could just as easily be called pannedMap), and (obviously) map is the map in the collection that needs moving. I played around a bit before I settled for the above code. The advantage here is that $.each doesn't wait for the moveTo function to return, so you get a much slicker looking synch. Of course this wouldn't really be an issue if you're only synching two maps. I'm sorry to have posted this so long after the question was asked, but maybe it will help any new searchers out there.
unknown
d11763
train
Libraries like commons-beanutils can help you if you want to compare bean properties (values returned by getters) instead of comparing field values. However, if you want to stick with plain reflection, you should: * *Use Class.getDeclaredFields() instead of Class.getFields(), as the latter only returns the public fields. *Since fields only depend on their class, you should cache the result and keep the fields in a static / instance variable rather than invoking getDeclaredFields() for each comparison. *Once you have an object of that class (say o), in order to get the value of some field f for that particular object, you need to call: f.get(o). A: You might check out org.apache.commons.lang.builder.EqualsBuilder which will save you a lot of this hassle if you're wanting to do a field by field comparison. org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals(Object, Object) If you're wanting to compare fields yourself, check out java.lang.Class.getDeclaredFields() which will give you all the fields including non-public fields. To compare the value of the fields use f.get(qa).equals(f.get(qa4)) Currently, you are actually comparing the field instances and not the values. A: // If you want to have some fields, not all field then use this. public boolean compareObject(Object object) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String[] compareFields = { "fieldx", "fieldy","fieldz", "field15", "field19"}; // list of all we need for(String s : compareFields) { Field field = DcrAttribute.class.getDeclaredField(s); // get a list of all fields for this class field.setAccessible(true); if(!field.get(this).equals(field.get(object))){ //if values are not equal return true; } } return false; }
unknown
d11764
train
There is no now.Image in this code. if (now.Image) { return <img src={preview} /> } return <Message text={now.text} key={key} /> }); there may be now.Text which represents now.Image and preview in your code because you set it in this part of code setMessageList([...initMessageList, { text: preview, key: initMessageList.length }])
unknown
d11765
train
If you want links from not nested articles, try: articles = browser.find_elements_by_tag_name('article'): for article in articles: print(article.find_elements_by_xpath('./*[not(descendant-or-self::article)]/descendant-or-self::a')) A: Parse the article element with BeautifulSoup and get all the anchor tags in ease. from bs4 import BeautifulSoup articles = browser.find_elements_by_tag_name("article") links = [] for i in articles: soup = BeautifulSoup(i.get_attribute('outerHTML'), 'html5lib') a_tags = soup.findAll('a') links.extend(a_tags) Hope this helps! Cheers! A: using BeautifulSoup, try to find all <a> under <articla> like ('article a') then use find_parents() method of beautifulsoup. If length of ('article a').find_parents('article') is bigger than 2, that might be nested like this. <article> .. <article> .. <a> so if you remove them you will get <a> that has only one <article> parent all_a = soup.findAll('article a') direct_a = [i for i in all_a if len(i)>2]
unknown
d11766
train
Changed Version from "socket.io-client": "^4.5.1", To "socket.io-client": "^1.7.4", And Changed import {io} from "socket.io-client To import io from "socket.io-client
unknown
d11767
train
jQuery Tools Scrollable is iPad/touch friendly. As an example, checkout the custom scrollable slider on trekk.com (works on iPad) that I built with jQuery Tools. A: I recently used a plugin called Flexslider (http://flex.madebymufffin.com/) that supports swiping between images on iOS.
unknown
d11768
train
I figured using this: Go search here: /var/www/html/ A: I solved this by using the Duplicator plugin for wordpress, instead of the All-in-One WP migration. The Duplicator plugin will produce two files; an archive file and an installer file. This link here will tell you how to upload these: https://snapcreek.com/duplicator/docs/quick-start/?utm_source=duplicator_free&utm_medium=wordpress_plugin&utm_content=package_built_install_help&utm_campaign=duplicator_free#quick-040-q
unknown
d11769
train
For this i always use widget_tweaks * *Install it : pip install django-widget-tweaks . *Add 'widget_tweaks' to INSTALLED_APPS in settings.py after django apps and just before your apps. *Add {% load widget_tweaks %} to the top of the template you will customise. Now to add a class for a field "name" of form1 do : {{ form1.name|add_class:"baz" }} or add 2 and more {{ form1.name|add_class:"baz baz2 baz3" }} which will add class ="baz baz2 baz3" to your field html output You can also add attributes : {{ form1.name|attr:"size:200"|attr:"color:blue"}} and combine the two ^^ {{ form1.name|add_class:"baz baz2 baz3"|attr:"size:200"|attr:"color:blue"}} You can also test field type for an adapted output by including snippets according to type. it's what i do. Go consult the docs of widget_tweaks it works for me on Django 1.6 and 1.7 Hope it will help you
unknown
d11770
train
According to @Ryan, your problem is that you are running it in Python 2 instead of Python 3. Running it in Python 3 should fix it.
unknown
d11771
train
A f:selectItem that has noSelectOption set to true represents a "no selection" option, something like this: -- Select a Colour -- < noSelectOption was intended for this case Red Green Blue Tomato This item is rendered in the menu, unless hideNoSelectionOption is set to true in your menu component. In that case, the option is selected when the user interacts with the menu. Just bear in mind that if an entry is required and this "no selection" option is the one selected, there will be a validation error. An alternative that requires a little more of coding is to use a f:selectItem with value="#{null}", to represent the case in which an user did not select a value. If you have a converter you'll have to check for this null case and, if you feel like it, introduce some custom validators.
unknown
d11772
train
It is not because you saved it as jsp or html page. You need to add charset="UTF-8" to your script declaration as d3.js uses UTF characters. eg. <script src="http://d3js.org/d3.v3.js" charset="UTF-8"></script>
unknown
d11773
train
updating the googlePlayService should solve the problem. If its your emulator than you can try this way
unknown
d11774
train
Not really an answer to your question as you are using MD5. However as this thread pops up when searching for the error, I am attaching this to it. Similar errors happen when bcrypt is used to generate passwords for auth_basic: htpasswd -B <file> <user> <pass> Since bcrypt is not supported within auth_basic ATM, mysterious 500 errors can be found in nginx error.log, (usually found at /var/log/nginx/error.log), they look something like this: *1 crypt_r() failed (22: Invalid argument), ... At present the solution is to generate a new password using md5, which is the default anyway. Edited to address md5 issues as brought up by @EricWolf in the comments: md5 has its problems for sure, some context can be found in the following threads * *Is md5 considered insecure? *Is md5 still considered secure for single use authentications? Of the two, speed issue can be mitigated by using fail2ban, by banning on failed basic auth you'll make online brute forcing impractical (guide). You can also use long passwords to try and fortify a bit as suggested here. Other than that it seems this is as good as it gets with nginx... A: I was running Nginx in a Docker environment and I had the same issue. The reason was that some of the passwords were generated using bcrypt. I resolved it by using nginx:alpine. A: Do you want a MORE secure password hash with nginx basic_auth? Do this: echo "username:"$(mkpasswd -m sha-512) >> .htpasswd SHA-512 is not considered nearly as good as bcrypt, but it's the best nginx supports at the moment. A: I will just stick the htpassword file under "/etc/nginx" myself. Assuming it is named htcontrol, then ... sudo htpasswd -c /etc/nginx/htcontrol calvin Follow the prompt for the password and the file will be in the correct place. location / { ... auth_basic "Restricted"; auth_basic_user_file htcontrol; } or auth_basic_user_file /etc/nginx/htcontrol; but the first variant works for me A: I had goofed up when initially creating a user. As a result, the htpasswd file looked like: user: user:$apr1$passwdhashpasswdhashpasswdhash... After deleting the blank user, everything worked fine. A: I just had the same problem - after checking log as suggested by @Drazen Urch I've discovered that the file had root:root permissions - after changing to forge:forge (I'm using Forge with Digital Ocean) - the problem went away. A: Well, just use correct RFC 2307 syntax: passwordvalue = schemeprefix encryptedpassword schemeprefix = "{" scheme "}" scheme = "crypt" / "md5" / "sha" / altscheme altscheme = "x-" keystring encryptedpassword = encrypted password For example: sha1 for helloworld for admin will be * *admin:{SHA}at+xg6SiyUovktq1redipHiJpaE= I had same error cause i wrote {SHA1} what against RFC syntax. When i fixed it - all worked like a charm. {sha} will not work too. Only correct {SHA}. A: First, check out your nginx error logs: tail -f /var/log/nginx/error.log In my case, I found the error: [crit] 18901#18901: *6847 open() "/root/temp/.htpasswd" failed (13: Permission denied), The /root/temp directory is one of my test directories, and cannot be read by nginx. After change it to /etc/apache2/ (follow the official guide https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) everything works fine. === After executing the ps command we can see the nginx worker process maintained by the user www-data, I had tried to chown www-data:www-data /root/temp to make sure www-data can access this file, but it still not working. To be honest, I don't have a very deep understanding on Linux File Permissions, so I change it to /etc/apache2/ to fix this in the end. And after a test, you can put the .htpasswd file in other directories which in /etc (like /etc/nginx). A: I too was facing the same problem while setting up authentication for kibana. Here is the error in my /var/log/nginx/error.log file 2020/04/13 13:43:08 [crit] 49662#49662: *152 crypt_r() failed (22: Invalid argument), client: 157.42.72.240, server: 168.61.168.150, request: “GET / HTTP/1.1”, host: “168.61.168.150” I resolved this issue by adding authentication using this. sudo sh -c "echo -n 'kibanaadmin:' >> /etc/nginx/htpasswd.users" sudo sh -c "openssl passwd -apr1 >> /etc/nginx/htpasswd.users" You can refer this post if you are trying to setup kibana and got this issue. https://medium.com/@shubham.singh98/log-monitoring-with-elk-stack-c5de72f0a822?postPublishedType=repub A: In my case, I was using plain text password by -p flag, and coincidentally my password start with $ character. So I updated my password and thus the error was gone. NB: Other people answer helped me a lot to figure out my problem. I am posting my solution here if anyone stuck in a rare case like me. A: In my case, I had my auth_basic setup protecting an nginx location that was served by a proxy_pass configuration. The configured proxy_pass location wasn't returning a successful HTTP200 response, which caused nginx to respond with an Internal Server Error after I had entered the correct username and password. If you have a similar setup, ensure that the proxy_pass location protected by auth_basic is returning an HTTP200 response after you rule out username/password issues.
unknown
d11775
train
You cannot use template variable inside static tag like this: {% static 'clinic/img/{{ image }}' %} Instead use with and add filter {% with "clinic/img/"|add:image as image_url %}{% static image_url %}{% endwith %} A: You cannot use a variable inside a {% static %} tag. What you can do is to use get-static-prefix and construct the URL manually. For example: <img src="{% get_static_prefix %}clinic/img/{{ image }}">
unknown
d11776
train
When we deal with response from web server then we can't sure about objects and types. So it is better to check and use objects as per our need. See for your reference related to your question. if let dictionnary : NSDictionary = responseObject as? NSDictionary { if let newArr : NSArray = dictionnary.objectForKey("data") as? NSArray { yourArray = NSMutableArray(array: newArr) } } By this your app will never crashed as it is pure conditional for your needed objects with checking of types. If your "data" key is array then only it will proceed for your array. Thanks. A: The crash happens because you assume that the object you receive is NSMutableArray, even though the object has been created outside your code. In this case, an array that your code gets is an instance of an array optimized for handling a single element; that is why the cast is unsuccessful. When this happens, you can make a mutable copy of the object: array = (dictionnary["data"]! as! NSArray).mutableCopy() as! NSMutableArray and array = (responseObject as! NSArray).mutableCopy() as! NSMutableArray
unknown
d11777
train
Your code seems ok, but dont forget you may need to add the access token to the batch request like: $params['access_token']=[USER_ACCESS_TOKEN]; $ret_val = $facebookObj->api('/?batch='.json_encode($queries[$a]), 'POST', $params); And for testing you may want to create a new page with a couple of friends added and test it. Also remember you need to handle the response, the batch request will response with an array with the same length that the batch array, and each object may be a diferent code, true if it was send. Also you can try your FQL code in the Graph Explorer (clic here) Seems ok, but it shows a extrange result.
unknown
d11778
train
Use this: import scala.reflect.io.File File(".").toAbsolute A: I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs A: import scala.sys.process._ val cwd = "pwd".!! //*nix OS A: Use this System.getProperty("user.dir") Edit: A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html A: Use java.nio: import java.nio.file.Paths println(Paths.get(".").toAbsolutePath) Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link. A: os-lib makes it easy to get the current working directory and perform other filesystem operations. Here's how to get the current directory: os.pwd It's easy to build other path objects from os.pwd, for example: os.pwd/"src"/"test"/"resources"/"people.csv" The syntax is intuitive and easy to remember, unlike the other options. See here for more details on how to use the os-lib project.
unknown
d11779
train
in many ways. For instance, write a method that will do the conversion for you: private String convertChoice(String abbr) { if (abbr.equals("T")) return "Stone"; else if (abbr.equals("S")) return "Scissors"; else return "Paper"; } then use convertChoice(iChoice) instead of iChoice when updating the value in your JOptionPane. A: Well I don't know it's a good/bad way, but was just curious so tried this out , you can use a HashMap to write your "keys" and display its value when needed. Map<String,String> map=new HashMap(); map.put("p","paper"); map.put("t","Stone"); map.put("s","Scissor"); A demo short example: Scanner scan=new Scanner(System.in); System.out.println("T-Stone..P-paper..S-Scissors..enter"); String choice=scan.nextLine().toLowerCase().trim(); Map<String,String> map=new HashMap(); map.put("p","paper"); map.put("t","Stone"); map.put("s","Scissor"); //s b p-> scissor beats paper final String test="s b p , t b s , p b t"; String vals[]={"p","s","t"}; String ichoice=vals[new Random().nextInt(3)+0];//((max - min) + 1) + min if(ichoice.equalsIgnoreCase(choice)){ JOptionPane.showMessageDialog(null," Tie !!--"+map.get(ichoice)); System.exit(1); } String match=ichoice+" b "+choice; if(test.contains(match)) JOptionPane.showMessageDialog(null," CPU Won!!--!"+map.get(ichoice)); else JOptionPane.showMessageDialog(null," YOU Won!!--"+map.get(ichoice));
unknown
d11780
train
The one and only time you use htmlentities for anything is if and when you're outputting data into HTML, right then and there. E.g.: <p><?php echo htmlentities($data); ?></p> In any other context HTML entities are generally useless* and will only garble/change/destroy your data. Indeed, using it on a password, probably nowhere near any HTML context, is highly suspect. * Yes, you can probably find some specialised use case somewhere…
unknown
d11781
train
The API documentation seems pretty definite, no qualifications or weasel-wording: The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously. So the parent has to kill it, it won't go away when the parent terminates. A: Not a great solution, but you could always check periodically the PID of the parent from the children.
unknown
d11782
train
If lambda has got these IAM permissions it will show the custom loggers as well as default AWS invocation/error logs "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"
unknown
d11783
train
I am assuming that you want to obtain something like this: where you input a location in the A9 cell and a Weight in the B9 cell and it automatically puts the correct rate in the C9 cell. This can be achieved with the following formula (in the C9 cell): =ARRAYFORMULA(VLOOKUP(A9,A1:G5,HLOOKUP(B9,{A1:G1;COLUMN(A1:G1)},2,0),0)) which mixes VLOOKUP (you can read more about it here) to fetch the correct Location Code with HLOOKUP (you can read more about it here) to fetch the correct Weight. A: This can be done very simply by just nesting one FILTER inside another; as per the answer given by Oriel Castander you could use this formula in cell C9 instead: =filter(filter(B2:G5,A2:A5=A9),B1:G1=B9)
unknown
d11784
train
Try adding "BEGIN", "END" and "DELIIMITER", like this: DELIMITER $$ CREATE PROCEDURE `Search_contacts`(IN `in_owner_id` INT, IN `in_first_name` VARCHAR(255)) BEGIN IF in_first_name IS NOT NULL THEN SELECT * FROM `contacts` WHERE `owner_id` = in_owner_id AND `first_name` LIKE in_first_name; END IF; END $$ DELIMITER ;
unknown
d11785
train
I don't believe there's any way to get information for all URLs that match a certain pattern, I think you have to specify the individual URLs manually - this shouldn't be a bug problem if it's your own site, as you'll already have a database of all possible article URLs, but if you're checking someone else's site it could be difficult.
unknown
d11786
train
In order for that data to be posted to the server, you have to store it in a form value. HTML elements in their entirety aren't posted to the server. Only the key/value pairs of form elements are. (WebForms is trying to trick you into thinking that the whole page is posted to the server, but it's a lie.) Add a hidden form field to the page, something as simple as this: <asp:Hidden id="someHiddenField" /> Then in the JavaScript, set the value of that field: document.getElementById('<%= someHiddenField.ClientID %>').value = 'true'; Then when the page posts back to the server, the 'true' value will be in that hidden field: someHiddenField.Value A: asp:Hidden doesn't exist. only form elements can actually postback data. The server side will take the postback data and load it into the form element provided that the runat=server is set. in markup or html: <input type="hidden" runat="server" ID="txtHiddenDestControl" /> javascript: document.getElementById('<%= txtHiddenDestControl.ClientID %>').value = '1'; code behind: string postedVal = txtHiddenDestControl.Value.ToString();
unknown
d11787
train
For only "one select": var options = [ { text: 'item1', value: 'item1', selected: true}, { text: 'item2', value: 'item2', selected: false}, ]; function isValidSelection(v){ var l = options.filter(function(item){ return item.selected==true; }).length; var r = ( !v ) || (v && l==0); return r; } var teste1 = null; var $teste1 = $('#teste1-id') var install = function () { $teste1.bsMultiSelect({ options: options, setSelected: function(o,v){ if (isValidSelection(v)){ o.selected = v; return true; } else{ return false; } } }); } install(); <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@dashboardcode/[email protected]/dist/js/BsMultiSelect.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <label class="control-label" for="teste1-id">Test it (only one select allowed)</label> <div id="teste1-id"></div> <br/>
unknown
d11788
train
Here is an example of how to return a List<string> from an object mocked by NSubstitute: using System.Collections.Generic; using NSubstitute; using Xunit; public interface ISomeType { List<string> MyFunction(); } public class SampleFixture { [Fact] public void ReturnList() { var _mockedObject = Substitute.For<ISomeType>(); var myList = new List<string> { "hello", "world" }; _mockedObject.MyFunction().Returns(myList); // Checking MyFunction() now stubbed correctly: Assert.Equal(new List<string> { "hello", "world" }, _mockedObject.MyFunction()); } } The error you have described sounds like there are different types involved. Hopefully the above example will help show the source of the problem, but if not please post an example of the _mockedObject interface and the test (as suggested in @jpgrassi's comment).
unknown
d11789
train
Try this: Fiddle demo --Your table create table t (id int identity(1,1), col1 varchar(10), col2 varchar(10)) --Insert query insert into t select c1 + case when number = 1 then '' else convert(varchar(10),number-1) end col1, c2 + case when number = 1 then '' else convert(varchar(10),number-1) end col2 from master..spt_values cross join (values ('RAM','CA'),('SAM','IA'),('PAM','MI')) AS temp (c1,c2) where type='p' and number between 1 and 100 --Results | ID | COL1 | COL2 | ------|-------|------|-- | 1 | RAM | CA | | 2 | SAM | IA | | 3 | PAM | MI | | 4 | RAM1 | CA1 | | 5 | SAM1 | IA1 | | 6 | PAM1 | MI1 | | 7 | RAM2 | CA2 | | 8 | SAM2 | IA2 | | 9 | PAM2 | MI2 | | 10 | RAM3 | CA3 | | 11 | SAM3 | IA3 | | 12 | PAM3 | MI3 | ... A: Using a recursive CTE You could try something like DECLARE @Table TABLE( ID INT IDENTITY(1,1), [name] VARCHAR(20), location varchar(20) ) INSERT INTO @Table VALUES ('RAM','CA'), ('SAM','IA'), ('PAM','MI') DECLARE @NumberOfRows INT = 100 ;WITH RowIDs AS ( SELECT 1 RowID UNION ALL SELECT RowID + 1 FROM RowIDs WHERE RowID + 1 <= @NumberOfRows ) , JoinIDs AS ( SELECT RowID, ((RowID - 1) % 3 + 1) JoinID FROM RowIDs ) SELECT j.RowID, t.name, t.location FROM JoinIDs j INNER JOIN @Table t ON j.JoinID = t.ID OPTION (MAXRECURSION 0) SQL Fiddle DEMO
unknown
d11790
train
For android specific settings. (Setting up makefiles, the AndroidManifest.xml, etc.) refer to SDL2/docs/readme.android and general "command line android help" on the internet. Setting up the VS2015 solution generally goes as follows: * *Create new folder project *Put game source in project/src *Create shared items project in project/ *Create an android makefile project into project/android *Create an android basic application(ANT) project into project/android *Copy the contents of SDL2/android-proj to project/android *In the solution explorer check "show all files" and "include in project" all files from SDL2/android-proj except jni to the basic application project. *In the references of the basic app project add the makefile project. *In the references of the makefile project add the shared items project. *Edit project/android/jni/src/Android.mk to compile your files in projects/src *After building the makefile project, add its resulting .so files from project/android/libs/ to the basic app project. *Create other project like usual except instead of including source, just include shared items project in references. Here is where you can find the shared items project:
unknown
d11791
train
Add this to your css: input[type=submit]{ height: 22px; line-height: 18px; cursor: pointer; } A: Instead of using height and width like you are currently doing you should use padding because then the text is vertically centred. The reason that the is not being sent is because you are not currently using a form so you need to add a form tag around the stuff that you want in the form so you could use this: <form action='#' method='get'> <input class="menu_button" type="submit" value="Log in" /> </form> Here is a working fiddle: http://jsfiddle.net/Hive7/26tyd/3/ A: You just need to add below code in your code: box-sizing: border-box; -moz-box-sizing: border-box; And to adjust the hight and with I would sugegst you to play with "min-width" and "padding". As giving "Width" and "Height" can limit your button and if you have more test or padding the height and width will not let the background increase. Please see the updated code:- .menu_button { -moz-box-shadow:inset 0px -1px 0px 0px #000000; -webkit-box-shadow:inset 0px -1px 0px 0px #000000; box-shadow:inset 0px -1px 0px 0px #000000; background-color:#000000; -webkit-border-top-left-radius:0px; -moz-border-radius-topleft:0px; border-top-left-radius:0px; -webkit-border-top-right-radius:0px; -moz-border-radius-topright:0px; border-top-right-radius:0px; -webkit-border-bottom-right-radius:0px; -moz-border-radius-bottomright:0px; border-bottom-right-radius:0px; -webkit-border-bottom-left-radius:0px; -moz-border-radius-bottomleft:0px; border-bottom-left-radius:0px; text-indent:0; border:1px solid #fa1e0f; display:inline-block; color:#ffffff; font-family:Arial; font-size:12px; font-weight:normal; font-style:normal; text-decoration:none; text-align:center; text-shadow:1px 1px 0px #33302f; box-sizing: border-box; /*ADDED*/ -moz-box-sizing: border-box; /*ADDED*/ padding:5px; } Hope this helps! A: Try margin: 0; padding: 0; white-space: normal; box-sizing: content-box; The input tags are styled different by the user agent stylesheet than a tags. A: As I understand you need to style both elements the same? Here's one solution: JSFIDDLE DEMO .menu_button { -moz-box-shadow:inset 0px -1px 0px 0px #000000; -webkit-box-shadow:inset 0px -1px 0px 0px #000000; box-shadow:inset 0px -1px 0px 0px #000000; background-color:#000000; text-indent: 0; border: 1px solid #fa1e0f; display: inline-block; color: #fff; font: normal 12px/1 Arial; width: 58px; text-decoration: none; text-align: center; vertical-align: top; text-shadow: 1px 1px 0px #33302f; padding: 5px 0; ouotline: 0 none; margin: 0; } /*this is needed for firefox and buttons */ .menu_button::-moz-focus-inner { border: 0; padding: 0; outline: none; }
unknown
d11792
train
You should redirect internally as well so your code should looks like this : RewriteEngine on RewriteBase / RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC] RewriteRule ^ %1? [R=302,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ /detail.php?i=$1 [L] A: Try this: RewriteEngine on RewriteBase / RewriteCond %{THE_REQUEST} /detail\.php\?i=([^\s&][A-Za-z0-9-]+) [NC] RewriteRule ^ %1? [R=302,L]
unknown
d11793
train
To clear all nodes in the tree, you can call myTree.delete_node(myTree.get_node("#").children);
unknown
d11794
train
Why do you think it is any different from this probable SO question you are referring to? Its just that instead of inserting a line, you need to read your inputfile.txt into a variable as shown here and insert that into the file, instead of the value as clearly shown in the question. (links provided above) A: insert contents of "/inputFile.txt" into "/outputFile.txt" at line 90 with open("/inputFile.txt", "r") as f1: t1 = f1.readlines() with open("/outputFile.txt", "r") as f2: t2 = f2.readlines() t2.insert(90, t1) with open("/outputFile.txt", "w") as f2: f2.writelines(t2) That should do it
unknown
d11795
train
There's a Wordpress Search and Replace Tool that will do what you need. If you download a PHP script from the link, place it in the root of your site and then navigate to it will find and replace any term in the site database and / or files. Obviously make sure you remove after you're done and it's better to rename it something less obvious before you upload it.
unknown
d11796
train
* *no Select, Activate, ActiveCell, etc *no OnError *no Resume *iterate from bottom to top Option Explicit Sub dupAmps() Dim WS As Worksheet, C As Range Dim LR As Long Dim I As Long Set WS = Worksheets("sheet1") With WS LR = .Cells(.Rows.Count, 1).End(xlUp).Row End With For I = LR To 2 Step -1 Set C = WS.Cells(I, 1) If InStr(C, "&") > 0 Then C.EntireRow.Insert shift:=xlDown C.EntireRow.Copy C.Offset(-1, 0) End If Next I End Sub
unknown
d11797
train
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string: $('input[type=file]').change(function () { console.log(this.files[0].mozFullPath); }); https://jsfiddle.net/SCK5A/ A: Due to major security reasons, most browsers don't allow getting it so JavaScript when ran in the browser doesn't have access to the user file system. having said that, the Firefox is exceptional and provides the mozFullPath property but it will only return an empty string.
unknown
d11798
train
The companion object of a case class extends FunctionX[T1, T2, <CaseClass>] so that you can use it to construct instances of the case class. So, for example, if you have a case class case class Foo(i: Int, s: String) the compiler will generate a companion object object Foo extends (Int, String) ⇒ Foo with Product2[Int, String] { def apply(i: Int, s: String) = new Foo(i, s) // and some other stuff such as equals, hashCode, copy } This allows you to construct an instance of Foo like this: Foo(42, "Hello") instead of new Foo(42, "Hello") So, to conclude: the reason, why you can pass the Dept companion object as a function is because it is a function. A: Dept is not a "case class type", it's the companion object for the case class. It extends Function1 (and has .apply method, that's part of the interface), so you can use it wherever a function is expected. The second snipped fails because { x => Dept(x) } is it's own anonymous function, not Dept object. A: It has a lot of sense, because if you just give as paramenter Dept it will behave ass a function that takes a String as parameter, and return an instance of the class Dept, meaning a Dept object (It is like give the new or apply function as parameter), look that the following code is valid also: val c: Dept.type = Dept val dep = c("Name1") dep res1: Dept = Dept(Name1) dep.evaluate Charlie... res2: Unit = ()
unknown
d11799
train
MsgBox( Format(currentDate, "#0")) or other format you prefer A: Dim currentDate currentDate = Now * (8.64 * 10 ^ 11) + 109205 'MsgBox (DateAdd("d", -90, Now)) MsgBox (Format(currentDate(), "MM dd, yyy")) MsgBox (Format(Now(), "MM dd, yyy")) Now() displays a date currentDate is an over flow. How to format date in VBA?
unknown
d11800
train
Set AutoPostBack=true on btnAnswer. It's not triggering the server to act on the button click. A: If you want to get event btnAnswer_Click triggered , then you must render the same Content and assign the eventHandler in every pageload(ie; the page load after the client button click must render the button again and EventHandler must be assigned). Asp.net won't trigger the event if it doesn't find the controls in the pageload. Remember, after clicking a button, the page load event triggers first and then only the Click_event will be triggered. The RenderQuestions() must be called in the btnAnswer_Click Event too. This will avoid the a step back problem. In this scenario I would recommend you to learn about ajax (using jQuery library) requests in asp.net (using WebMethods or webservices) to avoid these postbacks.
unknown