text
stringlengths 175
47.7k
| meta
dict |
---|---|
Q:
Jquery HTML/CSS Geting all spans data-name atributes
This question has to do with this other here.
I found part of the problem and would like someone to help me to solve it altogether.
I discovered that in fact my old script works and i only need to adapt it correctly. See the following situation
Using this javascript
var addCartData = function(params) {
$("#content-wrapper .get-all div ").each(function(index, element){
$(element).find("span").each(function(){
if($(this).attr("data-name")) {
if (startsWith($(this).attr("data-name"),"itemAmount")) {
//rtn.replace((rtn == 'itemAmount') ? "." : ","), "");
params[$(this).attr("data-name") + (index+1)] = $(this).html().replace(($(this).html() ?',':","),".");
alert($(this).html().replace(($(this).html() ?',':","),"."));
} else {
params[$(this).attr("data-name") + (index+1)] = $(this).html();
}
}
});
});
};
I'm getting all data-names [itemId, itemDescription, itemAmount, itemQuantity] inside spans elements, then the script is working perfectly. But, because design issues, i need to make the script [or similar] works with the same way [getting all span data-name] for the following html code:
<div class='get-all'>
<div class='left-wrapper'>
<div class='field-wrapper'>
<div class='field'>
<span class='product-id' data-name='itemId'>5</span>
<img src='carousel/images/120231671_1GG.jpg' width='52' height='52'>
<span class='final-descript' data-name='itemDescription'>Panfleto 80x40 500un</span>
<span class='product-id' data-name='itemAmount'>225,99</span>
<span class='product-id' data-name='itemQuantity'>1</span>
</div>
<div class='fix'></div>
<div class='field'>
<span class='review-price'>R$ 225,99</span>
</div>
</div>
<div class='field-wrapper'>
<div class='field'>
<span class='product-id' data-name='itemId'>4</span>
<img src='carousel/images/120231671_1GG.jpg' width='52' height='52'>
<span class='final-descript' data-name='itemDescription'>Samsung-G-Duos</span>
<span class='product-id' data-name='itemAmount'>699,80</span>
<span class='product-id' data-name='itemQuantity'>1</span>
</div>
<div class='fix'></div>
<div class='field'>
<span class='review-price'>R$ 699,80</span>
</div>
</div></div>
<div class='left-wrapper'>
<span class='f-itens'>Valor total dos itens</span><span id='fff' class='f-value'>925,79</span>
<hr class='f-hr' />
<span class='f-itens'>Frete</span><span class='f-value' id='f-value'> - </span>
<hr class='f-hr' />
<div class='f-itens tots'>Total a pagar</div><span class='f-value' id='pagar' >-</span>
</div>
</div>
<!------------------------------------------------------------------------------------------->
The problem is that using the same script for this new html I get the items several times, tripled, for example, rather than get the value $ 225.99 once, I receive 3 times. So does the other fields. How can I adapt the script so you can get the date-names only once as when used with the old html code??
A:
This is not enough since you have many DIV tags
Try to change this specific line in your javascript code:
This
$("#content-wrapper .get-all div ").each(function(index, element){
to
$("#content-wrapper .get-all .field-wrapper ").children("field").each(function(index, element){
When you only put DIV tag in your javascript (notice you have 3 DIV tags) your code travel to search all SPAN tags that they are belong (children) to then.
A:
As requested by @V.Salles, I'm re-posting my comment as an answer, since it led to the solution.
I'm not sure what you are referring to when you say "new html" and
"old html", but maybe this will work due to being more specific: if
you replace $("#content-wrapper .get-all div ").each( with
$("#content-wrapper .get-all").find("div.field").each( . This should
target the container for each set of fields so that the inner part
goes through each field only once.
As per @V.Salles, the following adjustment to my suggestion has solved the problem:
$("#content-wrapper .get-all").find("div.field-wrapper").each(
| {
"pile_set_name": "StackExchange"
} |
Q:
php combine array - arthmetically add values
How do I combine these two arrays, so that the keys stay the same, but the values are arithmetically determined?
Note - the keys might not always line up in each array, per my example:
$Array1 = ([4] => 100, [5] => 200, [6] => 100, [7] => 400 );
$Array2 = ([2] => 300, [5] => -100, [16] => -500, );
Desired output:
$Array3 = ([2] => 300, [4] => 100, [5] => 100, [6] => 100, [7] => 400, [16] => -500);
Edit: improve arrays to highlight why a "foreach" wont work
A:
You can use array_map for this:
$Array3 = array_map(function($a,$b) {return $a+$b;},$Array1,$Array2);
However this will only work if you have the same keys in both arrays (which, in your example, you don't).
If this is an issue, the easiest workaround would probably be:
$allKeys = array_merge(array_keys($Array1),array_keys($Array2));
$Array3 = Array();
foreach($allKeys as $k) {
$Array3[$k] = (isset($Array1[$k]) ? $Array1[$k] : 0)
+(isset($Array2[$k]) ? $Array2[$k] : 0);
}
EDIT Just realised the above code is not optimal. Rewriting:
$allKeys = array_unique(array_merge(array_keys($Array1),array_keys($Array2)));
// rest of code as above
Actually not sure if the overhead of repeated keys is more or less than the overhead of checking uniqueness...
A:
You can foreach over each array and add them to a result array.
//$array3 = array();
//foreach($array1 as $k=>$v){
// $array3[$k] = $v;
//}
$array3 = $array1;
foreach($array2 as $k=>$v){
$array3[$k] = isset($array3[$k]) ? $array3[$k]+$v : $v;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What could cause a "java.lang.IllegalArgumentException: Type mismatch" in GAE Query?
I have two code snippets which I am trying to run on the development server of Google App Engine SDK v1.8.8 for Java.
The first:
return datastore.get(KeyFactory.createKey(Kinds.Provider,provider_id));
works as expected and returns the Provider Entity from the Data Store.
But when I tried to change it to a projection Query so that it will return only
Filter filter=new FilterPredicate(Entity.KEY_RESERVED_PROPERTY,
Query.FilterOperator.EQUAL,
KeyFactory.createKey(Kinds.Provider,provider_id));
Query q = new Query(Kinds.Provider)
.setFilter(filter)
.addProjection(new PropertyProjection("address", String.class))
.addProjection(new PropertyProjection("last_modified", String.class));;
}
PreparedQuery pq = datastore.prepare(q);
log.info("query:" + q.toString());
Entity result = pq.asSingleEntity();
I am getting a the following Exception:
java.lang.IllegalArgumentException: Type mismatch.
at com.google.appengine.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:96)
at com.google.appengine.api.datastore.RawValue.asType(RawValue.java:61)
at com.google.appengine.api.datastore.PropertyProjection.getValue(PropertyProjection.java:65)
at com.google.appengine.api.datastore.EntityTranslator.createFromPb(EntityTranslator.java:29)
at com.google.appengine.api.datastore.QueryResultsSourceImpl.processQueryResult(QueryResultsSourceImpl.java:199)
at com.google.appengine.api.datastore.QueryResultsSourceImpl.loadMoreEntities(QueryResultsSourceImpl.java:106)
at com.google.appengine.api.datastore.QueryResultIteratorImpl.ensureLoaded(QueryResultIteratorImpl.java:155)
at com.google.appengine.api.datastore.QueryResultIteratorImpl.nextList(QueryResultIteratorImpl.java:110)
at com.google.appengine.api.datastore.LazyList.forceResolveToIndex(LazyList.java:93)
at com.google.appengine.api.datastore.LazyList.resolveToIndex(LazyList.java:73)
at com.google.appengine.api.datastore.LazyList.resolveToIndex(LazyList.java:56)
at com.google.appengine.api.datastore.LazyList.isEmpty(LazyList.java:260)
at com.google.appengine.api.datastore.PreparedQueryImpl.asSingleEntity(PreparedQueryImpl.java:74)
logging the querys .toString() yeilds:
SELECT last_modified, address FROM Provider WHERE __key__ = Provider(99)
Any Ideas on what might be the reason for this exception?
A:
OK, Found It.
within the DB last_modified is actually a Long so it should have been
.addProjection(new PropertyProjection("last_modified", Long.class));
Thank you for listening and I hoe this might help someone in the future...
| {
"pile_set_name": "StackExchange"
} |
Q:
facebook sdk Graphrequest object returns null in android
i am trying to fetch facebook user details like name, userid, email,location,gender. i am getting response in log with user information but unable to store in session or sent to another activity, like form Login Activity to Main Activity bellow id my code in Login Activity
public class LoginActivity extends AppCompatActivity {
LoginButton fbloginbtn;
CallbackManager callbackManager;
private EditText username_login,password_login;
Typeface tf;
ProfilePictureView profilePictureView;
AccessTokenTracker accessTokenTracker;
ProfileTracker mprofileTracker;
private ProgressDialog progressDialog;
private Session session;
private Button loginbtn;
private TextView register;
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new Session(LoginActivity.this);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
username_login = (EditText) findViewById(R.id.login_username);
password_login = (EditText) findViewById(R.id.login_password);
loginbtn = (Button) findViewById(R.id.login_btn);
register = (TextView) findViewById(R.id.register);
tf= Typeface.createFromAsset(getAssets(),"fonts/Roboto-Thin.ttf");
username_login.setTypeface(tf);
password_login.setTypeface(tf);
fbloginbtn = (LoginButton) findViewById(R.id.fb_login_btn);
callbackManager = CallbackManager.Factory.create();
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(intent);
finish();
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username = username_login.getText().toString();
String password = password_login.getText().toString();
if(username.trim().length() > 0 && password.trim().length() > 0){
checkLogin(username,password);
}else{
Toast.makeText(LoginActivity.this,"Please Enter The Credentials!", Toast.LENGTH_LONG).show();
}
}
});
callbackManager = CallbackManager.Factory.create();
LoginManager loginManager = LoginManager.getInstance();
fbloginbtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
//Profile profile = Profile.getCurrentProfile();
getProfileInformationFacebook(accessToken);
Log.e("login res", loginResult.toString());
session.setFblogin(true);
//Intent fblogin = new Intent(LoginActivity.this,MainActivity.class);
//startActivity(fblogin);
//finish();
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Your Login is Cancel ", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
private void checkLogin(final String username, final String password) {
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppURLs.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
String userId = jObj.getString("user_id");
String uname = jObj.getString("uname");
//JSONObject subObj = new JSONObject("user");
//String userName = subObj.getString("name");
if (userId != null) {
session.setLogin(true);
session.setMember(userId , uname);
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
intent.putExtra("user_id", userId);
intent.putExtra("uname", uname);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Post params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("username", username);
params.put("password", password);
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
//Exit on press twice
boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
// fb user informaiton
public void getProfileInformationFacebook(AccessToken accToken) {
GraphRequest request = GraphRequest.newMeRequest(
accToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("object", object.toString());
String fbId = null;
String fbBirthday = null;
String fbLocation = null;
String fbEmail = null;
String fbName = null;
String fbGend = null;
String fbPropic = null;
try {
fbId = object.getString("id");
fbEmail = object.getString("email");
fbName = object.getString("name");
fbGend = object.getString("gender");
fbBirthday = object.getString("birthday");
JSONObject jsonObject = object.getJSONObject("location");
fbLocation = jsonObject.getString("name");
//fbPropic = "https://graph.facebook.com/\"+ fbId +\"/picture?type=small";
session.FbLogindata(fbId, fbName, fbPropic, fbLocation, fbGend, fbEmail);
Intent fbdata = new Intent(LoginActivity.this, MainActivity.class);
fbdata.putExtra("fbid",object.getString("id"));
fbdata.putExtra("fbname",object.getString("name"));
fbdata.putExtra("email",object.getString("email"));
fbdata.putExtra("gender",object.getString("gender"));
fbdata.putExtra("location",jsonObject.getString("name"));
// main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(fbdata);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,location,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
}
getting NullPointerException
in my main activiry
fbuname = (TextView) mHeaderView.findViewById(R.id.user_name);
fbuemail = (TextView) mHeaderView.findViewById(R.id.user_email);
Bundle inBundle = getIntent().getExtras();
if (inBundle != null){
String Fbid = inBundle.getString("fbid");
String Fbname = inBundle.getString("fbname");
fbuname.setText(Fbname);
fbuemail.setText(Fbid);
}
in in my logcat
E/object: {"id":"1913429202227853","gender":"female","name":"Asesha George"}
my imports
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
please comment if you have any doubts
A:
try this your updated method
public void getProfileInformationFacebook(AccessToken accToken) {
GraphRequest request = GraphRequest.newMeRequest(
accToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("object", object.toString());
String fbId = null;
String fbBirthday = null;
String fbLocation = null;
String fbEmail = null;
String fbName = null;
String fbGend = null;
String fbPropic = null;
try {
if(object.has("id")){
fbId = object.getString("id");
}
else {
fbId = "";
}
if(object.has("email")){
fbEmail = object.getString("email");
}
else {
fbEmail = "";
}if(object.has("name")){
fbName = object.getString("name");
}
else {
fbName ="";
}if(object.has("gender")){
fbGend = object.getString("gender");
}
else {
fbGend = "";
}if(object.has("birthday")){
fbBirthday = object.getString("birthday");
}
else {
fbBirthday = "";
}if(object.has("location")){
JSONObject jsonObject = object.getJSONObject("location");
if(object.has("name"))
fbLocation = jsonObject.getString("name");
else
fbLocation ="";
}
else {
fbLocation ="";
}
//fbPropic = "https://graph.facebook.com/\"+ fbId +\"/picture?type=small";
session.FbLogindata(fbId, fbName, fbPropic, fbLocation, fbGend, fbEmail);
Intent fbdata = new Intent(LoginActivity.this, MainActivity.class);
fbdata.putExtra("fbid",fbId);
fbdata.putExtra("fbname",fbName);
fbdata.putExtra("email",fbEmail);
fbdata.putExtra("gender",fbGend);
fbdata.putExtra("location",fbLocation);
// main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(fbdata);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,location,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
add compile 'org.jsoup:jsoup:1.10.2' in build.gradle and change import org.json.JSONObject;
instead of import com.google.gson.JsonObject; in your Login activity then has method working properly
| {
"pile_set_name": "StackExchange"
} |
Q:
How to test if zeros have changed to ones (but not the other way around)
I have a binary mask which at some point I'm updating. It's ok for 1s in my old mask to become 0s but the other way around is not allowed. How can I assert using some binary operations that none of the 0s in the mask have turned into 1s?
A:
if (~old & new)
If you also want to know which bits changed from 0 to 1, just read each bit in bits = ~old & new;. If you just want to know if any 0s became 1s, that first line of code will do.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the value set for NaN, POSITIVE_INFINITY and some other constants in Double class?
What is the value set for NaN, POSITIVE_INFINITY and some other constants in Double class? From the source code, I see that they are set to themselves, but how does that work?
public final class Double extends Number implements Comparable<Double> {
public static final double POSITIVE_INFINITY = POSITIVE_INFINITY;
public static final double NEGATIVE_INFINITY = NEGATIVE_INFINITY;
public static final double NaN = NaN;
public static final double MAX_VALUE = MAX_VALUE;
public static final double MIN_VALUE = MIN_VALUE;
...
}
Thanks.
A:
At least in OpenJDK 8, OpenJDK 9 and OpenJDK 10, they are in the source code:
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
public static final double NaN = 0.0d / 0.0; // (*)
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023;
public static final double MIN_VALUE = 0x0.0000000000001P-1022;
(*) In case you're wondering about the "d"...
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Setup Issue.
private void ReadText(string text)
{
string add = "http://translate.google.com/translate_tts?tl=ta&q=";
add += HttpUtility.UrlEncode(text, Encoding.GetEncoding("utf-8"));
try
{
using (var client = new WebClient())
{
try
{
client.Headers[HttpRequestHeader.UserAgent] =
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"; }
catch
{
MessageBox.Show("Intenet error");
}
try
{
client.DownloadFile(add, "mp3CriationTest.mp3");
}
catch
{
MessageBox.Show("NAudio Error");
}
}
}
catch (WebException e3)
{
MessageBox.Show("ReadText error: " + e3);
}
}
I am using nAudio to do google text-to-speech(tts). This code working much better for me when I run on visual studio debug(F5). But When I created setup file I ll get the exception message "NAudio Error". So its obvious there is a problem on saving/creating "mp3CriationTest.mp3" on Application folder of my setup. But Creating "mp3CriationTest.mp3" on debug folder is works fine when I use Visual Studio debug(F5).
Can anyone know what was the issue? Plaese help.
A:
You cannot write directly into the program files folder unless you have administrative privileges. You can save the file to the application data folder (environment specified); like
string fileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + "mp3test.mp3";
client.DownloadFile(add, fileName);
| {
"pile_set_name": "StackExchange"
} |
Q:
Android HttpPost javax.net.ssl.SSLProtocolException unrecognized name
I am trying to post some data to an api from an Android tablet, but I keep getting an SSLProtocolException and I can't figure out the problem.
This is the error I keep getting:
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x7bccbdc8: Failure in SSL library, usually a protocol error
error:14077458:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 unrecognized name (external/openssl/ssl/s23_clnt.c:741 0x73d67718:0x00000000)
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:468)
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.<init>(OpenSSLSocketImpl.java:717)
W/System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:688)
W/System.err﹕ at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:70)
W/System.err﹕ at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
W/System.err﹕ at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:221)
W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1227)
W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:677)
W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err﹕ at com.example.casper.bilfinger.sendJSONdata.doInBackground(sendJSONdata.java:130)
W/System.err﹕ at com.example.casper.bilfinger.sendJSONdata.doInBackground(sendJSONdata.java:54)
W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err﹕ W/System.err﹕at java.lang.Thread.run(Thread.java:841)
W/System.err﹕ Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x7bccbdc8: Failure in SSL library, usually a protocol error
W/System.err﹕ error:14077458:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 unrecognized name (external/openssl/ssl/s23_clnt.c:741 0x73d67718:0x00000000)
W/System.err﹕ W/System.err﹕at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err﹕ W/System.err﹕at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:425)
W/System.err﹕ ... 23 more
And this is the code I'm using.
public class sendJSONdata extends AsyncTask<String, String, String>{
String httpAuthUser=*username*;
String httpAuthPassword=*password*;
String Bedrijf;
String Naam;
String Functie;
String Vestiging;
String Telefoonnummer;
String Email;
String Opmerkingen;
String GesprokenMet;
Context context;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
public sendJSONdata(String[] values,Context context)
{
Bedrijf= values[0];
Naam= values[1];
Functie= values[2];
Vestiging= values[3];
Telefoonnummer= values[4];
Email= values[5];
Opmerkingen= values[6];
GesprokenMet= values[7];
this.context=context;
//System.setProperty("jsse.enableSNIExtension", "false");
}
protected String doInBackground(String... strings) {
///Build JSON object and fill with your data
JSONObject subpostMessage = new JSONObject();
try {
subpostMessage.put("emailAdres", Email);
subpostMessage.put("Naam", Naam);
subpostMessage.put("Bedrijfsnaam", Bedrijf);
subpostMessage.put("Telnummer", Telefoonnummer);
subpostMessage.put("Functie", Functie);
subpostMessage.put("Vestiging", Vestiging);
subpostMessage.put("Opmerkingen", Opmerkingen);
subpostMessage.put("GesprokenMet", GesprokenMet);
} catch (JSONException e) {
e.printStackTrace();
}
//Connect to HttpClient with basic Aut
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpclient = new MyHttpClient(httpParameters,context);//new DefaultHttpClient(httpParameters);//
HttpPost httppost = new HttpPost(*Https to php file");
String base64EncodedCredentials = "Basic " + Base64.encodeToString((httpAuthUser + ":" + httpAuthPassword).getBytes(), Base64.NO_WRAP);
httppost.setHeader("Authorization", base64EncodedCredentials);
String responseStr = null;
try {
// Add your data to te connection
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("postData", subpostMessage.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("httpPost: ",httppost.getMethod());
Log.d("ValuePairs- name: ",nameValuePairs.get(0).getName()+ " val: "+ nameValuePairs.get(0).getValue());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//Recover result response
responseStr = EntityUtils.toString(response.getEntity());
Log.d("JSON ATTEMPT","Response: "+responseStr);
} catch (ClientProtocolException e) {
Log.d("JSON ATTEMPT","Response:CPerror "+e.toString());
} catch (IOException e) {
Log.d("JSON ATTEMPT","Response:IOerror "+e.toString());
}
return responseStr;
}
protected void onPostExecute(String result) {
if (result == null) {
//Request Failed
return;
}
//System.out.println("RECEIVED RESPONSE: " + result);
try {
JSONObject jObj = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(String... values) {
}
}
And the place where its called.
void postJSONdata()
{
String[] values = new String[8];
values[0]=bnaam.getText().toString();
values[1]=naam.getText().toString();
values[2]=functie.getText().toString();
values[3]=vestiging.getText().toString();
values[4]=tele.getText().toString();
values[5]=mail.getText().toString();
values[6]=opmerking.getText().toString();
values[7]=gesprokenmet.getText().toString();
sendJSONdata task = new sendJSONdata(values,getApplicationContext());
task.execute();
}
This error is thrown on any jdk I try (6,7,8),
Most of the post I found suggested it had to do with SNI which was introduced in 7 but with 6 I still have the same error.
A:
This problem is caused by the configuration of the server, combined with no or invalid support of SNI by the client. The server will return with the unrecognized_name alert if no SNI was used or if SNI was used with the wrong name. Thus you need to make sure that you use a Java version which supports SNI, enable it and also use the correct name to access the server.
| {
"pile_set_name": "StackExchange"
} |
Q:
How is 'classOf' expression represented in scala AST
I'm new to the Scala AST concepts.
I need to traverse a Scala code tree that contains an expression such as:
classOf[org.apache.commons.lang3.ArrayUtils]
I need to be able to identify this case when pattern matching on scala.reflect.internal.Trees.Tree.
For instance I know that it is not case _:Apply
What is the correct pattern in order to successfuly match this expression?
A:
A classOf[C] is represented as a Literal(value), where value.tag == ClazzTag, and value.typeValue is a Type representing C. You can match on it as:
case Literal(value) if value.tag == ClazzTag =>
val tpe = value.typeValue
// do something with `tpe`
See https://github.com/scala-js/scala-js/blob/ec5b328330276b9feb20cccadd75e19d27e887d3/compiler/src/main/scala/org/scalajs/nscplugin/GenJSCode.scala#L2043 for a real-world example.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cities XL not starting after windows reinstall
I have reinstalled my windows XP and now cities XL is giving error "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"
Is there any solution other then reinstalling the whole game again? I think some registry entries will solve the problem but i don't have them.
A:
Add registry from here http://www.regfiles.net/file/86/
And install vcredist_x86.exe (Visual C++ Redist) from CitiesXL folder
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery showing related xml categories
I have an xml file like this:
<?xml version="1.0" ?>
<scketchit>
<categories>
<category title="MANGA" />
<category title="MARVEL" />
</categories>
<comics>
<comic title="Comic number 1">
<date>21/02/2011</date>
<category>MANGA</category>
</comic>
<comic title="Comic number 2">
<date>13/02/2011</date>
<category>MARVEL</category>
</comic>
<comic title="Comic number 4">
<date>12/02/2011</date>
<category>MANGA</category>
</comic>
</comics>
</scketchit>
and i want to convert the categories items into links and when i click in this categories show in a div the corresponding comics
I'm new to jquery and this is the jquery i'm writting:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "comics.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find('categories').eq(0).find('category').each(function () {
$("#categories-data1").append('<div class="title"><a href="#" class="CategoryTab">' + $(this).attr('title') + '</a></div>');
});
var nav_link = $('.CategoryTab');
nav_link.click( function() {
alert( $(xml).find("category:contains('" + nav_link.html() + "')").closest('comic').html() );
});
}
I don't know if iwhat i'm doing is well done and i cant show the comic items for every category.
How would you do all this?
Thanks in advance.
A:
i have it working now but i'm sure it can be done in another simple and clean way ¿?
$(document).ready(function(){
$.ajax({
type: "GET",
url: "categories.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find('categories').eq(0).find('category').each(function () {
$("#categories-data1").append('<div class="title"><a href="#" class="CategoryTab">' + $(this).attr('title') + '</a></div>');
});
var nav_link = $('.CategoryTab');
nav_link.click( function() {
var cat = $(this).html();
$("#posts").empty();
$(xml).find('comic').each(function()
{
var comic = $(this).attr('title');
var category = $(this).children('category').text();
if(category == cat) {
$("#posts").append('<p>' + comic + '</p>');
}
})
});
}
May anyone tell me what of what i've done should be done in another way?
Thank you very much.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set color for first row in Datagrid
I have a datagrid on a wpf (mvvm) project.
the datagrid sort is showing the last item added to the collection as the first row.
i want to color the first row (in order to highlight new item added to the collection)
I've seen some similar questions about this manner but none of them are really related to what i am looking for.
i have tried to use a IValueConverter but it doesnt seems to be the right path for me as i need to get a unique identifier for the first row and change all the rest of the rows in order to classified it as a "First Row".
my object model for the items in the collection looks like this:
public class Messages
{
public string Date {get; set;}
public string Sender{get; set;}
public string Content{get; set;}
}
*EDIT
Forgot to add the converter code...
of course this will color all rows to red, as i dont know how to affect the other rows when the collection changes.
class DateToColorConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (Convert.ToDateTime(value) >= DateTime.Now.AddMinutes(-1))
{
return "Red";
}
else
return "Yellow";
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
A:
You can use RelativeSource with Mode set to PreviousData to identify whether dataGrid row is first one or not. For first row PreviousData will return null.
Apply DataTrigger on DataGridRow in ItemContainerStyle:
<DataGrid>
<DataGrid.ItemContainerStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="LightBlue"/>
<Style.Triggers>
<DataTrigger
Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}"
Value="{x:Null}">
<Setter Property="Background" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.ItemContainerStyle>
</DataGrid>
| {
"pile_set_name": "StackExchange"
} |
Q:
Precession in the vector model of angular momentum - quantum mechanics?
The vector model of angular momentum in quantum mechanics says that, for example, the angular momentum vector $\mathbf{L}$ precesses about its projection on the $z$ axis, like this:
We can add $\mathbf{L}$ and $\mathbf{S}$ to make $\mathbf{J}$, so that $\mathbf{L}$ and $\mathbf{S}$ precess about $\mathbf{J}$, like this:
NOW:
1) Does the direction of precession (clockwise or anticlockwise) matter?
2) This is just a model, $\mathbf{L}$ and $\mathbf{S}$ do not actually precess, right?
So why do use this model?
Is it a way to take into account the fact that we don't know $L_x$ and $L_y$?
A:
My quantum mechanics teacher, always say to me, that those models for "see" the spin and the angular momentum, are not correct.
the reason is that the picture of an electron precessing associated with the spin in't correct because the spin is'nt associated with any spacial coordinate. in quantum mechanics is better abandon those pictures, the important are the properties of L and S and the measure.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I call a method from another class within a listbox?
In my listbox form I want to make it possible to call a method from a class in a different folder. Here is what I thought I was meant to do:
public void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
SharedClasses.Form.FormConsole newFormConsole =
new SharedClasses.Form.newFormConsole();
}
A:
You are creating a new instance of the FormConsole class, which I'm guessing is probably not what you wanted to do.
What you probably want to do is have the form that contains your ListBox have a reference to an existing instance of FormConsole. Then you can call methods on that instance.
So, somewhere in the class that contains your ListBox:
private FormConsole _myForm;
You can set that in the constructor for your class, or provide a getter and setter:
public FormConsole MyForm
{
get { return _myForm; }
set { _myForm = value; }
}
// and/or...
public ListBoxForm(FormConsole myForm)
{
MyForm = myForm;
}
Then you can call (public) methods on myForm:
public void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
MyForm.MyMethod();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get table using relationships in Entity Framework
I am using EF Core 2.1 and i'm trying to get Profile from Authentication but every time i get it i found it null and i don't now where is the problem.
And for authentication i can get profiles.
Entities:
[Table("USER_AUTHENTICATION")]
public class Authentication
{
public int ID { get; set; }
//...some code
[ForeignKey("ProfileID")]
public Profile Profile { get; set; }
public virtual int ProfileID { get; set; }
}
[Table("USER_PROFILE")]
public class Profile
{
public Profile()
{
Authentication = new HashSet<Authentication>();
}
public int ID { get; set; }
//... some code
public virtual ICollection<Authentication> Authentication { get; set; }
}
DataContext
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<Authentication> Authentications { get; set; }
public DbSet<Profile> Profiles { get; set; }
public Profile GetById(int currentUserId)
{
var user = _context.Authentications.Find(currentUserId);
Console.WriteLine(user.Profile); //<--- here is the probelm null//
return _context.Profiles.Find(user.ProfileID);
}
How can i use relations with correct way
A:
You need use include for sub-entity and change Find to SingleOrDefault.
Add Include
var user = _context.Authentications.Include(p => p.Profile).SingleOrDefault(currentUserId);
return user.Profile;
| {
"pile_set_name": "StackExchange"
} |
Q:
Using sqlalchemy scoped_session in theading.Thread
I'm having problems using sqlalchemy together with threading.
import queue
import threading
import sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.scoping import scoped_session
engine = create_engine('sqlite:///:memory:', echo=False)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
Base.metadata.create_all(engine)
sessionfactory = sessionmaker(bind=engine)
# called by each thread
def write_name(q, name, sessionfactory):
session = scoped_session(sessionfactory)
ed_user = User(name=name, fullname='Power', password='edspassword')
session.add(ed_user)
session.commit()
q.put(name)
names = ["Max", "Austin"]
q = queue.Queue()
for u in names:
t = threading.Thread(target=write_name, args = (q, u, sessionfactory))
t.daemon = True
t.start()
s = q.get()
This results in:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users [SQL: 'INSERT INTO users (name, fullname, password) VALUES (?, ?, ?)'] [parameters: ('Max', 'Power', 'edspassword')]
but it works fine to add and read data in the main thread. Furthermore I assume I need to use threading over multiprocess because scoped_session uses thread local storage.
A:
The main problem is that you can't have multiple connections to a SQLite database that only exists in memory, because each connection will create a new empty database. See the SQLAlchemy docs on this. In short, you need to create the engine like this to make sure that is only one instance that can be shared across threads.
from sqlalchemy.pool import StaticPool
engine = create_engine('sqlite://:memory:',
connect_args={'check_same_thread': False},
poolclass=StaticPool, echo=True)
Once you do that, you don't need scoped_session, because the point of scoped_session is to create one connection per each thread and you specifically can't do that here.
Also, note that you should have only one scoped_session instance if you want it to work correctly (with a non-SQLite engine). You should treat it as global variable and then it will be able to handle the thread-local stuff.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use ngModelChange with Pipe
Here is the follow Html input :
<input matInput [ngModel]="myDates[i][month]|number:'1.2-2'" (ngModelChange)="myDates[i][month]=$event" (blur)="singleUpdate('cargo', j + 1, myDates[i][month], i)">
in this case, when I input 1, the result become 1.00
However when I input 12, the result become 1.002 not 12.00
how can i fix this issue ?
A:
Technically the output you are getting is correct, because the number pipe tries to format the input as soon as it gets the value within the ngModel.
And also ngModelChange will not help you in this case. It will output the same.
You got to utilize blur event and DecimalPipe. Also you can use two way binding for ngModel with [()] syntax.
template
<input [(ngModel)]="myDates" (blur)="formatNumber()">
component.ts
import { DecimalPipe } from '@angular/common';
constructor(private decPipe: DecimalPipe) {}
formatNumber() {
this.myDates = this.decPipe.transform(this.myDates, '1.2-2');
}
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
If then command yielding string as output in r
I am trying to calculate after-tax income for each household in a data frame like this:
id hhinc
1 1 53880
2 2 49501
3 3 37525
4 4 28791
5 5 91049
6 6 133000
7 7 12299
8 8 23000
9 9 58100
10 10 9764
where hhinc is household income.
I then created the following function to calculate the taxes paid by each household:
taxpaid = function(hhinc) {
if (hhinc > 0 & hhinc <= 19999) {tax = 0}
else if (hhinc > 20000 & hhinc <= 49999) {tax = (hhinc - 20000)*.15}
else if (hhinc > 50000 & hhinc <= 199999) {tax = 4499.85 + ((hhinc - 50000)*.25)}
else if (hhinc > 200000 & hhinc <= 999999) {tax <- 37499.75 + ((hhinc - 200000)*.39)}
else if (hhinc > 1000000) {tax <- 311999.61 + ((hhinc - 1000000)*.85)}
return(tax)
}
Since this function only works for a scalar input, I vectorized the function:
taxpaid_vec = Vectorize(taxpaid, vectorize.args = "hhinc")
However, when I use this function to calculate the taxes paid, I receive non-numeric outputs. I therefore cannot subtract the taxes paid from each household's income to determine the after-tax income. I would like to know how to fix my code so that get a numeric output for taxes paid.
A:
Replace if/else to ifelse to make your function vectorized.
taxpaid = function(hhinc) {
ifelse(hhinc > 0 & hhinc <= 19999, 0,
ifelse(hhinc > 20000 & hhinc <= 49999, (hhinc - 20000)*.15,
ifelse(hhinc > 50000 & hhinc <= 199999, 4499.85 + ((hhinc - 50000)*.25),
ifelse(hhinc > 200000 & hhinc <= 999999, 37499.75 + ((hhinc - 200000)*.39),
ifelse(hhinc > 1000000, 311999.61 + ((hhinc - 1000000)*.85), NA)))))
}
Apply the function
df$tax_income <- taxpaid(df$hhinc)
df
# id hhinc tax_income
#1 1 53880 5469.85
#2 2 49501 4425.15
#3 3 37525 2628.75
#4 4 28791 1318.65
#5 5 91049 14762.10
#6 6 133000 25249.85
#7 7 12299 0.00
#8 8 23000 450.00
#9 9 58100 6524.85
#10 10 9764 0.00
You might also look in to ?dplyr::case_when for handling such nested conditions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Improve performance of ggplotly when plotting time-series heatmap
I'm building an interactive time-series heatmap in R using Plotly and Shiny. As part of this process, I'm re-coding heatmap values from continuous to ordinal format - so I have a heatmap where six colours represent specific count categories, and those categories are created from aggregated count values. However, this causes a major performance issue with the speed of the creation of heatmap using ggplotly(). I've traced it to the tooltip() function from Plotly which renders interactive boxes. Labels data from my heatmap somehow overload this function in a way that it performs very slowly, even if I just add a single label component to the tooltip(). I'm using a processed subset of COVID-19 outbreak data from Johns Hopkins CSSE repository. Here is a simplified heatmap code, which also uses The Simpsons colour theme from ggsci:
#Load packages
library(shiny)
library(plotly)
library(tidyverse)
library(RCurl)
library(ggsci)
#Read example data from Gist
confirmed <- read_csv("https://gist.githubusercontent.com/GeekOnAcid/5638e37c688c257b1c381a15e3fb531a/raw/80ba9704417c61298ca6919343505725b8b162a5/covid_selected_europe_subset.csv")
#Wrap ggplot of time-series heatmap in ggplotly, call "tooltip"
ggplot_ts_heatmap <- confirmed %>%
ggplot(aes(as.factor(date), reorder(`Country/Region`,`cases count`),
fill=cnt.cat, label = `cases count`, label2 = as.factor(date),
text = paste("country:", `Country/Region`))) +
geom_tile(col=1) +
theme_bw(base_line_size = 0, base_rect_size = 0, base_size = 10) +
theme(axis.text.x = element_text(angle = 45, hjust = 1),legend.title = element_blank()) +
scale_fill_manual(labels = levels(confirmed$cnt.cat),
values = pal_simpsons("springfield")(7)) +
labs(x = "", y = "")
ggplotly(ggplot_ts_heatmap, tooltip = c("text","label","label2"))
Performance improves once tooltip = c("text","label","label2") is reduced (for instance to tooltip = c("text")). Now, I know that delay is not "massive", but I'm integrating this with a Shiny app. And once it's integrated with Shiny and scaled with more data, it is really, really, really slow. I don't even show all variables in tooltip and its still slow - you can see it in the current version of the app when you click on 'confirmed' cases.
Any suggestions? I've considered alternative interactive heatmap packages like d3heatmap, heatmaply and shinyHeatmaply but all those solutions are more intended for correlation heatmaps and they lack customisation options of ggplot.
A:
If you rewrite it as "pure" plotly (without the ggplotly conversion), it will be much faster. Around 3000 times even. Here's the result of a very small benchmark:
Unit: milliseconds
expr min lq mean median uq max neval
a 9929.8299 9929.8299 9932.49130 9932.49130 9935.1527 9935.1527 2
b 3.1396 3.1396 3.15665 3.15665 3.1737 3.1737 2
The reason why ggplotly is much slower, is that it doesnt recognize the input as a heatmap and creates a scatterplot where each rectangle is drawn separately with all the necessary attributes. You can look at the resulting JSON if you wrap the result of ggplotly or plot_ly in plotly_json().
You can also inspect the object.size of the plots, where you will see that the ggplotly object is around 4616.4 Kb and the plotly-heatmap is just 40.4 Kb big.
df_colors = data.frame(range=c(0:13), colors=c(0:13))
color_s <- setNames(data.frame(df_colors$range, df_colors$colors), NULL)
for (i in 1:14) {
color_s[[2]][[i]] <- pal_simpsons("springfield")(13)[[(i + 1) / 2]]
color_s[[1]][[i]] <- i / 14 - (i %% 2) / 14
}
plot_ly(data = confirmed, text = text) %>%
plotly::add_heatmap(x = ~as.factor(date),
y = ~reorder(`Country/Region`, `cases count`),
z = ~as.numeric(factor(confirmed$`cnt.cat`, ordered = T,
levels = unique(confirmed$`cnt.cat`))),
xgap = 0.5,
ygap = 0.5,
colorscale = color_s,
colorbar = list(tickmode='array',
title = "Cases",
tickvals=c(1:7),
ticktext=levels(factor(x = confirmed$`cnt.cat`,
levels = unique(confirmed$`cnt.cat`),
ordered = TRUE)), len=0.5),
text = ~paste0("country: ", `Country/Region`, "<br>",
"Number of cases: ", `cases count`, "<br>",
"Category: ", `cnt.cat`),
hoverinfo ="text"
) %>%
layout(plot_bgcolor='black',
xaxis = list(title = ""),
yaxis = list(title = ""));
| {
"pile_set_name": "StackExchange"
} |
Q:
Launcher icon in Android not showing
Are there any special guidelines to put launcher icon in Android 7.1.1 ?
Because I added a logo in manifest file and its showing in all Android versions but not in my phone. Anyone got a clue?
A:
In Manifest.xml, please check have to set icons for both android:icon="@mipmap/ic_app_icon" and android:roundIcon="@mipmap/ic_app_icon":
Here is the full code :
<application
android:allowBackup="true"
android:icon="@mipmap/ic_app_icon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_app_icon"
android:supportsRtl="true"
android:theme="@style/AppTheme">
| {
"pile_set_name": "StackExchange"
} |
Q:
git push heroku master takes forever
I'm using a VM based on Ubuntu 12.04 (ruby 1.9.2p290 and rails 3.1.0) and my app work perfectly on local. I'm using git and when I try to git push heroku master it doesn't work:
git push heroku master
I get: "Counting objects: 435, done. Compressing objects: 100% (215/215), done. Writing objects: 100% (435/435), 73.35 KiB, done. Total 435 (delta 171), reused 435 (delta 171) "
And it never finish, so it doesn't push anything to heroku. The terminal standby forever. I'm new to heroku and git sorry if the question was obvious :)
Operative System information:
jobs
[1]+ Running git push heroku master &
ps -x
PID TTY STAT TIME COMMAND
1078 ? Ssl 0:00 gnome-session --session=ubuntu
1135 ? Sl 0:00 /usr/bin/VBoxClient --clipboard
1147 ? Sl 0:00 /usr/bin/VBoxClient --display
1154 ? Sl 0:00 /usr/bin/VBoxClient --seamless
1162 ? Sl 0:19 /usr/bin/VBoxClient --draganddrop
1167 ? Ss 0:00 /usr/bin/ssh-agent /usr/bin/dbus-launch --exit-with-s
1171 ? S 0:00 /usr/bin/dbus-launch --exit-with-session gnome-sessio
1172 ? Ss 0:01 //bin/dbus-daemon --fork --print-pid 5 --print-addres
1246 ? Sl 0:00 /usr/bin/gnome-keyring-daemon --start --components=se
1250 ? Sl 0:02 /usr/lib/gnome-settings-daemon/gnome-settings-daemon
1329 ? S 0:00 /usr/lib/gvfs/gvfsd
1334 ? Sl 0:00 /usr/lib/gvfs//gvfs-fuse-daemon -f /home/ubuntu/.gvfs
1401 ? Sl 0:03 metacity
1417 ? S 0:00 /usr/lib/i386-linux-gnu/gconf/gconfd-2
1421 ? S
1426 ? Sl 0:01 unity-2d-panel
1427 ? Sl 0:07 unity-2d-shell
1430 ? S 0:00 /usr/lib/pulseaudio/pulse/gconf-helper
1447 ? Sl 0:01 /usr/lib/bamf/bamfdaemon
1450 ? Sl 0:00 /usr/lib/gnome-settings-daemon/gnome-fallback-mount-h
1453 ? Sl 0:02 nautilus -n
1455 ? Sl 0:00 /usr/lib/policykit-1-gnome/polkit-gnome-authenticatio
1457 ? Sl 0:00 bluetooth-applet
1468 ? Sl 0:00 nm-applet
1482 ? S 0:00 /usr/lib/gvfs/gvfs-gdu-volume-monitor
1500 ? Sl 0:00 /usr/lib/gvfs/gvfs-afc-volume-monitor
1504 ? S 0:00 /usr/lib/gvfs/gvfs-gphoto2-volume-monitor
1518 ? S 0:00 /usr/lib/gvfs/gvfsd-trash --spawner :1.9 /org/gtk/gvf
1521 ? Sl 0:01 /usr/lib/unity/unity-panel-service
1523 ? Sl 0:00 /usr/lib/dconf/dconf-service
1539 ? Sl 0:00 /usr/lib/indicator-datetime/indicator-datetime-servic
1541 ? Sl 0:00 /usr/lib/indicator-printers/indicator-printers-servic
1543 ? Sl 0:00 /usr/lib/indicator-messages/indicator-messages-servic
1545 ? Sl 0:00 /usr/lib/indicator-session/indicator-session-service
1547 ? Sl 0:00 /usr/lib/indicator-application/indicator-application-
1549 ? Sl 0:00 /usr/lib/indicator-sound/indicator-sound-service
1574 ? S 0:00 /usr/lib/geoclue/geoclue-master
1591 ? S 0:00 /usr/lib/ubuntu-geoip/ubuntu-geoip-provider
1597 ? Sl 0:00 /usr/lib/gnome-disk-utility/gdu-notification-daemon
1603 ? S 0:00 /usr/lib/gvfs/gvfsd-metadata
1609 ? Sl 0:00 /usr/lib/indicator-appmenu/hud-service
1620 ? Sl 0:00 /usr/lib/unity-lens-applications/unity-applications-d
1622 ? Sl 0:00 /usr/lib/unity-lens-files/unity-files-daemon
1624 ? Sl 0:00 /usr/lib/unity-lens-music/unity-music-daemon
1626 ? Sl 0:00 /usr/bin/python /usr/lib/unity-lens-video/unity-lens-
1653 ? Sl 0:00 /usr/bin/zeitgeist-daemon
1661 ? Sl 0:00 telepathy-indicator
1668 ? Sl 0:00 /usr/lib/zeitgeist/zeitgeist-fts
1672 ? Sl 0:00 zeitgeist-datahub
1676 ? S 0:00 /bin/cat
1682 ? Sl 0:00 /usr/lib/telepathy/mission-control-5
1701 ? Sl 0:00 gnome-screensaver
1703 ? Sl 0:00 /usr/bin/python /usr/lib/unity-scope-video-remote/uni
1728 ? Sl 0:05 gnome-terminal
1734 ? S 0:00 gnome-pty-helper
1738 pts/2 Ss 0:00 bash
1796 ? Sl 0:00 update-notifier
1954 pts/2 S 0:00 git push heroku master
1955 pts/2 S 0:00 ssh git@heroku.com git-receive-pack 'polar-island-471
1959 pts/2 R+ 0:00 ps -x
A:
There are many reasons why your push to Heroku can timeout. In my experience, the most common reason is due to site size, and by site size, I mean 3 things: the size of your git repo, the size of your site that gets pushed to Heroku (git repo - ignored files), and the size of the gems you use. Heroku is not particularly robust when it comes to accommodating big sites (or long running processes, for that matter) and if you get too big, you can cause your push to hang / timeout and intermittently too, which can be perplexing.
.git folder
I have had the site get unexplainably large and saw that over time my .git folder in the root of the project had grown to 600mb. Thank goodness I noticed a warning in the heroku deploy chatter that warned me that my git repo was too large. Anyway, since that folder is managed by git behind the scenes, I ended up starting a fresh git repo and moving my code over to it, which shrunk my site by 90%.
.slugignore
Another pitfall that caused my site to become large enough to timeout was allowing things like logs, my temp directory, and my solr indexing directory to be included in the project. After I excluded all of those folders in my .slugignore file, pushing became very fast. And yes, you could get the same basic effect using .gitignore, but there are some things that I like to manage through git, but ignore when pushing to heroku. That's when the .slugignore comes in handy.
gems
By completing the steps above, I reduced my site to a reasonable size, but still had occasional timeouts. Then I realized that gems contribute to your site size too. So I removed a handful of unused gems from my gemfile, and I was able to reduce my slug compile time from 900+ seconds to 250 seconds and my overall deployment time from 15+ minutes with frequent timeouts to under 10 minutes. What a relief to not have to wait so long for each deploy and risk timing out half the time.
Depending on your particular setup, any or all of these factors can really hurt you. In my case I was doing everything wrong. However, even if you are not timing out, you may still want to prune your site as much as possible to cut down your deployment time.
how to make heroku not suck
http://www.stormconsultancy.co.uk/blog/development/6-ways-to-get-more-bang-for-your-heroku-buck-while-making-your-rails-site-super-snappy/
A:
The reason was, that my connection was very slow. It was the Access Point of my smartphone.
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieve current and localized month
instead of writing array of months in desired language, and doing a function to replace date('m') with localized month... I believe there should be some fast and easy way to echo current month, after all its Wordpress?
I have define('WPLANG', 'hr');
A:
global $wp_locale;
echo $wp_locale->get_month( date( 'm' ) );
| {
"pile_set_name": "StackExchange"
} |
Q:
escaping $ sign for String.replace
At following String.replace line, lossLocation.state$ ,
the $ sign is removed after the replace,
i need to keep the $, as it is used in the variable.
'{0}'.replace(
'{0}'
, 'categories.Country === \'$formData.lossLocation.state$\'.toUpperCase()')
It gives me
"categories.Country === '$formData.lossLocation.state'.toUpperCase()"
The expected outcome should be
"categories.Country === '$formData.lossLocation.state$'.toUpperCase()"
i've tried the following but still been removed when replace
state\$
A:
As it states in String.prototype.replace(). To escape '$' in replacement content, you should use '$$' instead of '\$'.
So a proper way of constructing it would be
'{0}'.replace('{0}',
'categories.Country === \'$formData.lossLocation.state$\'.toUpperCase()'
.replace(/\$/g, '$$$$')
)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write while members of class still exist in page condition
In jquery or js, preferably jQuery or js that is well supported, how can I do a while with the condition that there are still members of the class on the page.
What I am doing in the suite of the while is systematically removing the elements in the class, but I can not remove them all at once.
Let's say the class is .card.
Here is my code:
$('#dismissAllButton').click(function(){
while($('.dataCard').length>0){
$('.right').eq(0).remove();
$('#left').children('.dataCard').first().addClass('animated').addClass('right');
setTimeout(function(){
$('.right').eq(0).remove();
$('#right').children('.dataCard').first().addClass('animated').addClass('right');
}, 150);
}
});
HTML:
<div id="left">
<div class="dataCard"></div>
<div class="dataCard"></div>
</div>
<div id="right">
<div class="dataCard"></div>
<div class="dataCard"></div>
</div>
A:
You don't need a while loop. Instead, first iterate over each list, then within each list, iterate over each card. This allows you to set a delay on removing the card based on which list it is in so that you can get the effect of removing 1 by 1 from each list at the same time.
$("#dismissAllButton").on("click", function() {
$("#left, #right").each(function(i){
$(".dataCard",this).each(function(ii) {
var card = $(this);
setTimeout(function() {
card.addClass("right");
setTimeout(function() {
card.remove();
},500);
}, i*250+ii*500); // adjust `250` and `500` as needed.
});
});
});
Demo
250 is the delay between left and right, and 500 is the animation duration (dont forget to also update the css transition to reflect that)
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Python's UUID to generate unique IDs, should I still check for duplicates?
I'm using Python's UUID function to create unique IDs for objects to be stored in a database:
>>> import uuid
>>> print uuid.uuid4()
2eec67d5-450a-48d4-a92f-e387530b1b8b
Is it ok to assume that this is indeed a unique ID?
Or should I double-check that this unique ID has not already been generated against my database before accepting it as valid.
A:
You should always have a duplicate check, even though the odds are pretty good, you can always have duplicates.
I would recommend just adding a duplicate key constraint in your database and in case of an error retry.
A:
I would use uuid1, which has zero chance of collisions since it takes date/time into account when generating the UUID (unless you are generating a great number of UUID's at the same time).
You can actually reverse the UUID1 value to retrieve the original epoch time that was used to generate it.
uuid4 generates a random ID that has a very small chance of colliding with a previously generated value, however since it doesn't use monotonically increasing epoch time as an input (or include it in the output uuid), a value that was previously generated has a (very) small chance of being generated again in the future.
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing method parameters/arguments to method reference - bind, anonymous, named
I have multiple places in my code where i use method references(i.e. just the method name with no arguments) but I need to pass it specefic arguments.
I don't want to insert an anonymous method b.c. it makes the code unreadable.
I've told I can use the .bind method, but I don't know how to use it properly. Can some one elaborate on how to do this.
Here is one example of where I need to to to this.
How do I use bind to add in parameters to ajax_signin?
if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',ajax_signin,b);}
A:
If you want ajax_signin() to get called with parameters, then you have to make a separate function that you can pass to ajax that calls ajax_signin() with the appropriate parameters. There are a couple ways to do this:
Using an anonymous function:
if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',function() {ajax_signin("parm1","parm2")},b);}
Creating your own named function:
function mySignIn() {
ajax_signin("parm1","parm2");
}
if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',mySignIn,b);}
If you want to use .bind() and you are sure you are only running in browsers that support .bind() or you have a shim to make .bind() always work, then you can do something like this:
if(d===0){ajax('arche_model.php',serialize(c)+'&a=signin',ajax_signin.bind(this, "parm1","parm2"),b);}
The .bind() call creates a new function that always has a specific this ptr and always has "parm1" and "parm2" as it's first two parameters.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is the use of "de" mandatory or optional here? And what function does it serve?
Rien ne me met plus en transe que d'affronter un adversaire très fort.
Rien ne me ferait plus plaisir que de vous revoir.
Je pensais que de savoir ce qui s'était réellement passé m'apaiserait.
When you say "Affronter un adversaire très fort me met en transe.", you will never place "de" before "affronter", correct?
Then, why is it necessary to include "de" in these three instances? And what is the meaning of "de" here?
A:
In all your sentences, the infinitive is the subject of a verb, sometimes suggested:
[(D')affronter un adversaire très fort] me met en transe. Rien ne me met plus en transe que [cela]
[(De) vous revoir] me ferait plaisir. Rien ne me ferait plus plaisir que [cela].
Je pensais que [(de) savoir ce qui s'était réellement passé] m'apaiserait.
Each time, I've put the verb in bold and the infinitive phrase in brackets.
When an infinitive is the subject of a verb, de-marking is always possible, but only obligatory when the infinitive is post-verbal and a dummy pronoun (ça or il) appears on the verb. It almost always is included with the "Rien ne [verb] plus que + [infinitive]" construction of your first two examples (1). In all other contexts, de appears very rarely, mostly in high-register writing.
In this, this de functions like other prepositions which take nouns as their objects:
(À) Cécile, je (ne) lui ai jamais parlé
Je (ne) lui ai jamais parlé, à Cécile
(De) Cécile, j(e n)'en ai jamais parlé
J(e n)'en ai jamais parlé, de Cécile
So:
When you say "Affronter un adversaire très fort me mets en transe.", you will never place "de" before "affronter", correct?
Incorrect, but this is optional and uncommon.
Then, why is it necessary to include "de" in these three instances? And what is the meaning of "de" here?
It is not necessary. De functions as an optional subject marker for infinitives, although this is not how native speakers are taught to think about it.
(1) But not always, for example this quote from a random blog, writen in a formal register: "Rien ne me plait plus qu’être dans de beaux endroits"
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding together GetCount Results
Is there anyway to add together GetCount Results? I am using GetCount to find the number of selected features for multiple layers but when I try to add them all together I get an error message saying it is an unsupported operand type for +: 'Result' and 'Result'.
SampledFaild = arcpy.GetCount_management('SamplingFaild')
SampledValid = arcpy.GetCount_management('SamplingValid')
Total = SampledFaild + SampledValid
A:
As the error message indicates, the return value of GetCount_management is a Result object. The documentation for GetCount includes an example of how to extract the return value, by casting the Result.GetOutput() value to integer.
Rewriting your code to use Style Guide for Python (PEP 8) recommended leading lowercase variable names, the result is:
sampledFaild = arcpy.GetCount_management('SamplingFaild')
sampledValid = arcpy.GetCount_management('SamplingValid')
total = int(sampleFaild.getOutput(0)) + int(sampleValid.getOutput(0))
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does SWT Table has spaces between columns in Windows 7
I asked a similar question before (it has all the screenshot and everything):
SWT Table.setLinesVisible(false) does not seem to work on Windows 7
After digging deeper, I observed two (surprising) things:
It actually has nothing to do with setLinesVisible() as I
initially assumed. Those dark column dividing lines are not "lines",
in fact, if I setLinesVisible(true) using a light color, I'll see
that the dark "lines" are to the left of the lines. In other words,
it appears the reason that those dark dividers exist is because the
background the column cell is not fully filled, it looks like there's
1 or 2 pixels at the right end of the cell that's not properly
painted to the desired cell background but is instead showing the
table background color.
If I switch to an (much) older swt jar (talking about 3-5 years
old), then that "crack" doesn't show up.
So this undesirable behavior only happens with newer swt jars on windows7.
Can someone please advise?
A:
Isn't that one of those bugs? Table or tree grid lines cover part of selection in win 7 or Tables: empty lines should not have a grid.
If not, you can write some post on swt forum.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to disable Javascript when using Selenium by JAVA?
I'm using selenium for web test by JAVA.
I want to stop JavaScript on Firefox Browser,Google Chrome Browser,IE Browser.
I tried this code on Firefox Browser.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("javascript.enabled", false);
WebDriver driver = new FirefoxDriver(profile);
But it's return this error on second line.
Exception in thread "main" java.lang.IllegalArgumentException: Preference javascript.enabled may not be overridden: frozen value=true, requested value=false
How to disable Javascript when using Selenium each Browser?
If you know about this problem,Please help me!
A:
Use noscript addon for firefox. Right click on the Add to Firefox button and Save link as that will give you the option to save the .xpi. Then, configure the the Firefox profiler as follows.
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"PATH\TO\noScript.xpi");
IWebDriver driver = new FirefoxDriver(profile);
driver.Navigate().GoToUrl("http://localhost:8080/");
| {
"pile_set_name": "StackExchange"
} |
Q:
Coercing the value of a shapeless record
I have a wrapper around a shapeless record.
I want to extract a value from that record, and prove that it is an instance of a polymorphic type, e.g. List[_]
import shapeless._
import shapeless.record._
import shapeless.ops.record._
import shapeless.syntax.singleton._
case class All[L <: HList](containers: L) {
def getValue[Value, A](containerKey: Witness)
(implicit sel: Selector.Aux[L, containerKey.T, Value],
equiv: Value =:= List[A]
): List[A] =
equiv.apply(containers.get(containerKey))
}
Right now, I can call getValue if I explicitly specify the type params Value and A, but since i'm working with much more complex types than List, I really need these type params to be inferred.
val all = All(
'x ->> List[Int](1, 2, 3) ::
'y ->> List[String]("a", "b") ::
'z ->> 90
HNil
)
// doesn't compile: Cannot prove that Value =:= List[A].
all.getValue('x)
// compiles
all.getValue[List[Int], Int]('x)
Is there a way to extract a value, coerce it to e.g. List[_], while not having to specify any type params?
Note that this strategy works completely fine if I want to prove that value is a simple monomorphic type , e.g. Value =:= Int, just not for Value =:= List[A]
A:
There are at least two ways to do it, and both involve changing the signature of getValue.
First, you can just use a constrained generic parameter:
def getValue[R <: List[_]](containerKey: Witness)
(implicit sel: Selector.Aux[L, containerKey.T, R]): R =
containers.get(containerKey)
Note that because we're using R as return type, the compile-time information about result won't be lost. You just won't be able to call this function if the value at a containerKey is not a list.
Second, you can use subtype bounds. I have no idea why it works, really. I suspect that using too strict constraints causes the compiler to dismiss some solutions that use refinement types. This works both if you replace the type parameter in Selector with a bounded wildcard:
def getValue[A](containerKey: Witness)
(implicit sel: Selector.Aux[L, containerKey.T, _ <: List[A]]): List[A] =
containers.get(containerKey)
Or if you use subtyping evidence <:< instead of equality =:=:
def getValue[Value, A](containerKey: Witness)
(implicit sel: Selector.Aux[L, containerKey.T, Value],
equiv: Value <:< List[A]
): List[A] =
equiv.apply(containers.get(containerKey))
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a realloc equivalent in C++?
In C, we have malloc(), free(), and realloc(). In C++ we have new(), delete() and their array versions. Is there a C++ realloc function? I'm implementing some low level stuff in embedded land and just realized there was no realloc function to pair up with the C++ functions and wanted to make sure I wasn't missing anything. I'm guessing "placement new" into a new, separate buffer is the closest match, but wanted to be sure.
Restating the question a bit as I'm getting some answer a bit far afield.
I have implemented device level malloc/new/realloc/etc. functions on my embedded device and wanted to double check to be sure there was no C++ realloc type function that I was unaware of.
A:
No, there is no direct equivalent. You would have to do the implementation yourself. Since a class really shouldn't change its size, this isn't really an issue. Move semantics can handle most of these cases.
However, there are some classes that use header info + tail end allocated data. To code these 'properly' you would have to override the operator new() and operator delete() function for the class to handle this additional 'flexible' data. How you 'reallocate' the data is specific to your needs.
If this doesn't answer your question, post an example of what you are attempting.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select random document with filter with pymongo?
I found, that to select random document, I need to use $sample command:
// Get one random document from the mycoll collection.
db.mycoll.aggregate(
{ $sample: { size: 1 } }
)
but what if I need to filter documents and THEN take random one?
I am processing documents, which are not processed yet with
query = {'start_time': {'$exists': False}}
hp_entries = mongo.hyperparameters_collection.find(query)
How would I do with random?
A:
As any other aggregation stage it takes input from the previous stage.
Prepend the $sample with $match to filter the documents. E.g.:
db.hyperparameters_collection.aggregate([
{ "$match": { "start_time": { "$exists": False } } },
{ "$sample": { "size": 1 } }
])
| {
"pile_set_name": "StackExchange"
} |
Q:
div with dynamic min-height based on browser window height
I have three div elements: one as a header, one as a footer, and a center content div. the div in the center needs to expand automatically with content, but I would like a min-height such that the bottom div always at least reaches the bottom of the window, but is not fixed there on longer pages.
For example:
<div id="a" style="height: 200px;">
<p>This div should always remain at the top of the page content and should scroll with it.</p>
</div>
<div id="b">
<p>This is the div in question. On longer pages, this div needs to behave normally (i.e. expand to fit the content and scroll with the entire page). On shorter pages, this div needs to expand beyond its content to a height such that div c will reach the bottom of the viewport, regardless of monitor resolution or window size.
</div>
<div id="c" style="height: 100px;">
<p>This div needs to remain at the bottom of the page's content, and scroll with it on longer pages, but on shorter pages, needs to reach the bottom of the browser window, regardless of monitor resolution or window size.</p>
</div>
A:
Just look for my solution on jsfiddle, it is based on csslayout
html,
body {
margin: 0;
padding: 0;
height: 100%; /* needed for container min-height */
}
div#container {
position: relative; /* needed for footer positioning*/
height: auto !important; /* real browsers */
min-height: 100%; /* real browsers */
}
div#header {
padding: 1em;
background: #efe;
}
div#content {
/* padding:1em 1em 5em; *//* bottom padding for footer */
}
div#footer {
position: absolute;
width: 100%;
bottom: 0; /* stick to bottom */
background: #ddd;
}
<div id="container">
<div id="header">header</div>
<div id="content">
content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>
</div>
<div id="footer">
footer
</div>
</div>
A:
I found this courtesy of ryanfait.com. It's actually remarkably simple.
In order to float a footer to the bottom of the page when content is shorter than window-height, or at the bottom of the content when it is longer than window-height, utilize the following code:
Basic HTML structure:
<div id="content">
Place your content here.
<div id="push"></div>
</div>
<div id="footer">
Place your footer information here.
</footer>
Note: Nothing should be placed outside the '#content' and '#footer' divs unless it is absolutely positioned.
Note: Nothing should be placed inside the '#push' div as it will be hidden.
And the CSS:
* {
margin: 0;
}
html, body {
height: 100%;
}
#content {
min-height: 100%;
height: auto !important; /*min-height hack*/
height: 100%; /*min-height hack*/
margin-bottom: -4em; /*Negates #push on longer pages*/
}
#footer, #push {
height: 4em;
}
To make headers or footers span the width of a page, you must absolutely position the header.
Note: If you add a page-width header, I found it necessary to add an extra wrapper div to #content. The outer div controls horizontal spacing while the inner div controls vertical spacing. I was required to do this because I found that 'min-height:' works only on the body of an element and adds padding to the height.
*Edit: missing semicolon
A:
If #top and #bottom have fixed heights, you can use:
#top {
position: absolute;
top: 0;
height: 200px;
}
#bottom {
position: absolute;
bottom: 0;
height: 100px;
}
#central {
margin-top: 200px;
margin-bot: 100px;
}
update
If you want #central to stretch down, you could:
Fake it with a background on parent;
Use CSS3's (not widely supported, most likely) calc();
Or maybe use javascript to dynamically add min-height.
With calc():
#central {
min-height: calc(100% - 300px);
}
With jQuery it could be something like:
$(document).ready(function() {
var desiredHeight = $("body").height() - $("top").height() - $("bot").height();
$("#central").css("min-height", desiredHeight );
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true
I'm getting
DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true
line 1 of https://core4.gatewayedi.com/v1/caqhcoreiv/caqhcorev4.svc?wsdl
error when using wsimport to generate java classes off of a wsdl file.
Is there any workaround or solution to this issue, specifically when using wsimport?
Following is the command I used as well as the complete response I got from wsimport:
wsimport" -Xnocompile -extension -clientjar my.jar -d . -generateJWS https://core4.gatewayedi.com/v1/caqhcoreiv/caqhcorev4.svc?wsdl
parsing WSDL...
[ERROR] DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
line 1 of https://core4.gatewayedi.com/v1/caqhcoreiv/caqhcorev4.svc?wsdl
[ERROR] DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
Failed to read the WSDL document: https://core4.gatewayedi.com/v1/caqhcoreiv/caqhcorev4.svc?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not wsdl:definitions.
[ERROR] Could not find wsdl:service in the provided WSDL(s):
At least one WSDL with at least one service definition needs to be provided.
Failed to parse the WSDL.
Downloading the WSDL and associated metadata
Exception in thread "main" java.lang.IllegalStateException: DOMStreamReader: Calling next() at END_DOCUMENT
at com.sun.xml.internal.ws.streaming.DOMStreamReader._next(DOMStreamReader.java:764)
at com.sun.xml.internal.ws.streaming.DOMStreamReader.next(DOMStreamReader.java:737)
at com.sun.xml.internal.ws.util.xml.XMLStreamReaderToXMLStreamWriter.bridge(XMLStreamReaderToXMLStreamWriter.java:92)
at com.sun.tools.internal.ws.util.WSDLFetcher.fetchFile(WSDLFetcher.java:121)
at com.sun.tools.internal.ws.util.WSDLFetcher.fetchWsdls(WSDLFetcher.java:86)
at com.sun.tools.internal.ws.wscompile.WsimportTool.buildWsdlModel(WsimportTool.java:437)
at com.sun.tools.internal.ws.wscompile.WsimportTool.run(WsimportTool.java:190)
at com.sun.tools.internal.ws.wscompile.WsimportTool.run(WsimportTool.java:168)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.tools.internal.ws.Invoker.invoke(Invoker.java:159)
at com.sun.tools.internal.ws.WsImport.main(WsImport.java:42)
A:
Looks like the behavior of the wsimport command is sensitive case. This answer mentions something similar.
The client was generate with (wsimport bundle with Oracle JDK version 1.8.0_202-b08):
wsimport -Xnocompile -extension -clientjar my.jar -d . -generateJWS https://core4.gatewayedi.com/V1/CAQHCoreIV/caqhcoreV4.svc?wsdl
The principal difference is the use of sensitive case in the URL. The URL https://core4.gatewayedi.com/V1/CAQHCoreIV/caqhcoreV4.svc?wsdl matches
with the location entry in the WSDL file.
| {
"pile_set_name": "StackExchange"
} |
Q:
between query for dates not working as i want
i am working on SQL query which take records between two dates "from" To "to" as show in below picture.my query working well but when i change "to" date from 24 to 23 then it does not display the record of 23 date,means last row not display.
my SQL query is given below:
select * from prescription_master where (pr.date between @from_date and @to_date) or (pr.date=@to_date)
i want that the record of 23 date also display when i select 23 date from "to" date picker.for this purpose i use "or (pr.date=@to_date)" in above query but it not working.how i can solve this.
A:
You have to handle time part:
select *
from prescription_master
where (CAST(pr.date AS DATE) between @from_date and @to_date)
or (CAST(pr.date AS DATE) = @to_date)
-- this also will made a query non-SARGable
When you provide parameter the date is set to 23-06-2019 00:00:00 and you are comparing it with 23-06-2019 13:08:00
| {
"pile_set_name": "StackExchange"
} |
Q:
Package listings and Perl here documents with apostrophes
I sometimes write ordinary English prose in my here documents in a Perl usage sub, for example
--[no]alias [don't] use the alias list in the ini file (default noalias)
The problem is the a single apostrophe seems to disturb the listings package. A short example:
\documentclass[article]{memoir}
\usepackage{listings}
\lstset{language=Perl,stringstyle=\slshape}
\begin{document}
\begin{lstlisting}
my $commentA = "Please, don't do this";
my $commentB = "But do this";
print <<HERE;
Please, don't do this
But do this
HERE
my $commentC = "Please, don't do this";
my $commentD = "But do this";
\end{lstlisting}
\end{document}
This results (with MiKTEX/TeXstudio) in
The apostrophe in commentA is ignored, while the one in the here document seems to be interpreted as an opening quote.
I have tried to escape the here terminator, but to no avail. Any suggestions (short of avoiding apostrophes in here documents)?
A:
You can add a morestring for these here statements. With the s option you can have a pair of delimiters, though this is not quite clear in the documentation:
\documentclass[article]{memoir}
\usepackage{listings}
\lstset{language=Perl,stringstyle=\slshape}
\begin{document}
\begin{lstlisting}[morestring={[s]{<<HERE;}{HERE}}]
my $commentA = "Please, don't do this";
my $commentB = "But do this";
print <<HERE;
Please, don't do this
But do this
HERE
my $commentC = "Please, don't do this";
my $commentD = "But do this";
\end{lstlisting}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Get SQL Logs
I've searched extensively for help but have found nothing, what I'm trying to do is backup the SQL log files (Management > SQL Server Logs) to a csv or text file.
Is there a way to do this with C#?
A:
From http://technet.microsoft.com/en-us/library/ms187885(v=sql.105).aspx
View the SQL Server error log by using SQL Management Studio or any
text editor. By default, the error log is located at Program
Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n
files.
So you can use the Directory.EnumerateFiles class to enumerate the files and File.ReadAllText to read the text from each file.
A:
You should be able to get the error log path via the SQL Server SMO assembly:
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
namespace SQLLogsToText
{
internal class Program
{
private static void Main(string[] args)
{
string errorLogPath = null;
using (var sqlConnection = new SqlConnection(@"Integrated Security=SSPI; Data Source=(local)\SQLEXPRESS"))
{
var serverConnection = new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection);
var server = new Server(serverConnection);
errorLogPath = server.ErrorLogPath;
}
if (errorLogPath != null)
{
// Enumerate Files
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
NullReferenceException in VB.NET after upgrade to 4.0
I have a VB.NET solution that I just upgraded. It was originally in .NET 1.1, I upgraded to .NET 2.0 and verified that it would build and run correctly. Then I upgraded from 2.0 to 4.0. It is still building with no errors, but when I try to run I am getting a NullReferenceException in Global.asax.vb. The really weird thing is, the line that is throwing the exception is this:
Dim dt As System.Data.DataTable
I am not trying to use the variable, just declare it. Further down a Function is called that returns a DataTable and sets the variable, but I don't even get to that line. It is throwing the NullReferenceException on the Dim line. Has anyone run across this before? Is this some issue with upgrading?
Edit
Okay, this is the first line in a function. The surrounding code looks like this.
Private Function GetUserRoles() As String
Dim dt As System.Data.DataTable
Dim oDBLookup As New DBLookups
I updated it to this, which should make no difference.
Private Function GetUserRoles() As String
Dim oDBLookup As New DBLookups
Dim dt As System.Data.DataTable
Now, the NullReferenceException is happening on the new first line in the function.
Dim oDBLookup As New DBLookups
The GetUserRoles() Function is the first line in Application_AuthenticateRequest that isn't a Dim or If statement.
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the user
Dim authCookie As HttpCookie = Context.Request.Cookies("GROUPCOOKIES")
Dim Groups As String
Dim noGroups As Boolean = False
If authCookie Is Nothing Then
Groups = GetUserRoles()
I did a Rebuild Solution before posting. This is a web application and the only files I see in the bin folder are the dll files I am referencing. I'm not sure what else I should clean up.
A:
It sounds like the solution may not have rebuilt properly and is appearing to throw the exception there even though it's actually occurring somewhere else because the source is different than the debug symbols. Try cleaning the solution, manually deleting all your bin and obj directories, then rebuilding and re-running.
| {
"pile_set_name": "StackExchange"
} |
Q:
O if do codigo php não executa só o else
<form method="GET">
salário: <input type="number" name="salario"> <br>
tempo de serviço (em meses): <input type="number" name="tds"> <br>
n° reclamações: <input type="number" name="rec"> <br>
<input type="submit" name="calcular">
</form>
<?php
if (!empty($_GET["salario"]) && !empty($_GET["tds"]) && !empty($_GET["rec"])) {
$salario=$_GET["salario"];
$tds=$_GET["tds"];
$rec=$_GET["rec"];
$nsal=($salario*0.2);
if (($salario > 1000) && ($tds > 12) && ($rec == 0)) {
echo "Você foi promovido, parabéns.";
echo "E ganhou um aumento de salário. Seu novo salário é: $nsal";
} else{
echo "Sem novidades, volte depois.";
}
}
?>
A:
O problema é que você está usando o empty() para o rec, se o valor for 0, o PHP considera com vazio. Troque o empty() por isset() que vai funcionar.
Veja o exemplo:
if (isset($_GET["salario"]) && isset($_GET["tds"]) && isset($_GET["rec"])) {
// lógica aqui
}
Espero ter ajudado.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java: Runtime.exec to get Linux distro name
I would like to check distro name, but I have got problem with bash executing command. Why this code works ok and print folder content
String cmd[] = {"ls","-a"};
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec(cmd);
BufferedReader read=new BufferedReader(new InputStreamReader(proc.getInputStream()));
while(read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
But cmd[] = {"cat","/etc/*-release"}; doesnt? It simply doesn't print anything, neither error nor distro. Ofc. it works in terminal. What is wrong with that?
A:
The reason it works in Bash is that Bash recognizes /etc/*-release as a glob and performs the necessary filename-expansion. Process doesn't do that; it just calls cat with the exact argument you specify. (In other words, you're running the equivalent of the Bash command cat '/etc/*-release'.)
One option, I suppose, is to actually call Bash and let it handle that for you:
String cmd[] = { "bash", "-c", "cat /etc/*-release" };
but I think it makes more sense to use the Java file-system API to search /etc for a file whose name ends in -release, and read that file's contents normally. (See the Javadoc for java.io.File and the Javadoc for java.io.FileReader.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Saving images to localStorage using fetch() and blob()
Unfortunately there aren't any working examples of a code mentioned in the title.
All found around were either a bit old-fashioned like canvas or too long.
fetch('https://www.stevensegallery.com/320/240')
.then(pic => pic.blob())
.then(pic => localStorage['pic'] = pic);
Is there any concise one-liner to do it without writing a separate function?
A:
Finally made it not too heavy. Also had to JSON.parse it before putting into actual source.
fetch('https://source.unsplash.com/300x170/?girl')
.then(pic => pic.blob())
.then(pic => {
const fr = new FileReader();
fr.onload = () => {
const dataURL = fr.result;
document.getElementById('pic').src = dataURL;
localStorage['pic'] = JSON.stringify(dataURL);
}
fr.readAsDataURL(pic);
});
<img id='pic' />
| {
"pile_set_name": "StackExchange"
} |
Q:
Что за Команда sudo apt-get install software-properties-common
sudo apt-get install software-properties-common что она ставит?
A:
Как описано в apt-show software-properties-common
Это программное обеспечение обеспечивает абстракцию используемых репозиториев apt.
Это позволяет вам легко управлять своими
дистрибутивами и независимыми поставщиками программного обеспечения.
На практике это означает, что он предоставляет некоторые полезные скрипты для добавления и удаления PPA:
$ dpkg -L software-properties-common | grep 'bin/'
/usr/bin/add-apt-repository
/usr/bin/apt-add-repository
плюс резервные копии DBUS, чтобы сделать то же самое с помощью программного обеспечения и обновлений GUI.
Без него вам нужно будет добавлять и удалять репозитории (например, PPA) вручную путем редактирования /etc/apt/sources.list и / или любых вспомогательных файлов в /etc/apt/sources.list.d
| {
"pile_set_name": "StackExchange"
} |
Q:
Sublime Text 2 doesn't stay pinned to the launcher
I use Sublime Text 2 in Ubuntu. The program downloads and runs on it's own without an installer (sort of like a portable app, I guess). When I pin it to the launcher, it only stays until I restart the computer. Then I have to dig it up again and repin it. This wasn't an issue in 11.04.
A:
It won't stay in the launcher because it doesn't have a *.desktop file. You can create a *.desktop file by hand (surprisingly complicated!) or you can simply use some guy's PPA to install Sublime Text 2. (The package includes the requisite *.desktop file.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Include arbitrary field in Rails model JSON output
I'm using Rails as a REST server, and one of my models has a description field. In that model's JSON representation, I need to output both the regular description field AND an arbitrary non-DB attribute called description_markdown that is just the description run through a markdown filter. I already know how to run text through markdown using redcarpet, like:
@post = Post.find(params[:id])
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :lax_html_blocks => true)
description_markdown = markdown.render(@post.description).html_safe
But what I really need is to make description_markdown an attribute on @post (like @post.description_markdown), and have it output in @post's JSON representation.
A:
I normally use RABL gem to build JSON views for my APIs -- it gives you a lot of flexibility on building JSON responses, such as creating custom child nodes, adding arbitrary code. Check it out.
But, to answer your question, you can probably overwrite as_json method of Post to include the return of description_markdown. Something like (not tested):
#post.rb
class Post < ActiveRecord::Base
def description_markdown
...
end
...
def as_json(options)
super(:only => [:attributes_you_want], :methods => [:description_markdown])
end
...
end
Then, in controller:
render :json => @post
Hope, it helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Python, why is my for-loop excluding the number before a specific number only when that number is the last in the array?
I am working on a codingbat problem, and I am getting unexpected results when the excluded number is at the end of the array.
def sum13(nums):
a = []
if len(nums) == 0:
return 0
for i in range(len(nums)):
if nums[i] == 13 or nums[i-1] == 13:
continue
a.append(nums[i])
return sum(a)
The code should append all numbers in the array to list a and return the sum, excluding any instances of the number 13 and the number immediately following it. It works fine for most of the tests, but when the array ends in 13, it doesn't append the number at index 0 to the list, returning the wrong result.
A:
When i is 0, nums[-1] is evaluated. nums[-1] is the last element of nums. Therein lies your problem.
If nums[-1] is 13, continue is executed, so nothing is appended to nums
| {
"pile_set_name": "StackExchange"
} |
Q:
Does a long time storage wallet need to be online?
I have a offline computer that has never been connected to a network. I use this computer for long time storage of sensitive data, all data transfer to and from this computer is done by USB memory. I want to move most of my bitcoins to this computer, so will it work this way:
Install bitcoin wallet on the offline computer and generate public address.
Send bitcoin from my online wallet to the address of the offline wallet.
Download bitcoin blockchain on a online computer and move it to the offline computer by USB memory?
A:
You don't need the 3rd step for long-term storage. You don't plan to spend your bitcoins any time soon when you're looking for long-term storage. If you download the blockchain now, it will long be outdated when you want to spend your money and you may as well only download it then. Or you choose a wallet which doesn't require you to download the entire blockchain.
Technically, the computer holding your private key doesn't have to be connected to the internet as a transaction can by signed by software running on that computer, then be transferred via a thumb drive to computer connected to the internet, and be broadcast from this second computer. This has the disadvantage that the blockchain has to be downloaded to the point where the transaction which was made to the long-term storage address has been confirmed. So you'll have to decide between [downloading the blockchain and being able to spend your money without the computer holding the private key being connected to the internet] and [not downloading the blockchain but having to transfer the private key to an online computer when finally spending the money].
Electrum can do this. I don't know whether other wallets can do it, too, because I only use Electrum.
Note that you don't even have to have any computer hold the private key. A private key is just a 256 bit number (default case; few restrictions on the range of values it can take, but almost all 256 bit numbers are valid private keys and that's really all there is to them, no magic involved). Numbers can be written down on paper.
Alternatively, you can use a brainwallet.
All 3 have things you can lose to lose your money:
Wallet on computer:
Malware can delete the wallet or encrypt it. (Can happen through infection via thumb drive.)
Your hard drive (+ backups) can break.
Some larger damage (e.g. house burning down) can break the entire computer, including the hard drive.
Paper wallet:
You can lose the piece of paper.
Damage can happen to your piece of paper. (The writing can fade, a fluid can be poured onto it, etc.)
A member of your family might find it and throw it away.
If you print it, a part of the private key may not be printed. This actually happened to someone who asked for help on this StackExchange site. They printed their private key in wallet import format but it didn't entirely fit on the page.
If you write it down by hand, you might make mistakes.
Brain wallet:
You can forget the passphrase.
Combination is possible:
If you have a private key on a computer, you can write it down. Again, the private key is just a number.
If you have a private key written down, you can make it a wallet on a computer.
If you have a brainwallet, you can write the private key down or make it a wallet on a computer.¹
¹ You can't go in the opposite direction without actually remembering the private key (which is absolutely not recommended). Remembering an Electrum seed (which looks like this: "constant forest adore false green weave stop guy fur freeze giggle clock") reliably may actually be possible but I still advise you to use the standard method of creating a brainwallet if you want to use one.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the difference between String.Empty and "" (empty string)?
In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?
A:
In .NET prior to version 2.0, "" creates an object while string.Empty creates no objectref, which makes string.Empty more efficient.
In version 2.0 and later of .NET, all occurrences of "" refer to the same string literal, which means "" is equivalent to .Empty, but still not as fast as .Length == 0.
.Length == 0 is the fastest option, but .Empty makes for slightly cleaner code.
See the .NET specification for more information.
A:
what is the difference between String.Empty and "", and are they
interchangable
string.Empty is a read-only field whereas "" is a compile time constant. Places where they behave differently are:
Default Parameter value in C# 4.0 or higher
void SomeMethod(int ID, string value = string.Empty)
// Error: Default parameter value for 'value' must be a compile-time constant
{
//... implementation
}
Case expression in switch statement
string str = "";
switch(str)
{
case string.Empty: // Error: A constant value is expected.
break;
case "":
break;
}
Attribute arguments
[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression
// or array creation expression of an attribute parameter type
A:
The previous answers were correct for .NET 1.1 (look at the date of the post they linked: 2003). As of .NET 2.0 and later, there is essentially no difference. The JIT will end up referencing the same object on the heap anyhow.
According to the C# specification, section 2.4.4.5:
http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.
Someone even mentions this in the comments of Brad Abram's post
In summary, the practical result of "" vs. String.Empty is nil. The JIT will figure it out in the end.
I have found, personally, that the JIT is way smarter than me and so I try not to get too clever with micro-compiler optimizations like that. The JIT will unfold for() loops, remove redundant code, inline methods, etc better and at more appropriate times than either I or the C# compiler could ever anticipate before hand. Let the JIT do its job :)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I treat elements in a list as variables inside a module?
I want to be able to assign values to a list element inside a module. For example if I have:
testscan[listin_] :=
Module[{zz},
Do[listin[[1]] = zz; Print[{zz, listin[[1]]}], {zz, 1, 2, 1}]]
Given:
testscan[{a, 1, 3, 1}]
Returns:
{1,a}
{2,a}
What I want it to return:
{1,1}
{2,2}
So its not just the output I care about, I want 'a' in this case to be able to reassigned to anything. Any ideas? Thanks a lot for your time.
LH- it is indeed a that I want to modify. The page you linked to is on the right track, but doesn't quite give me what I need yet. For example using your setPart function:
in:
foo = {a, 1, 3, 1};
setPart[foo, 1, xxx];
foo
out:
{xxx, 1, 3, 1}
But then for:
IN:
Clear[listin];
testscan[listin_] :=
Module[{}, setPart[listin, 1, \[Pi]]; Print[{listin[[1]], listin}]]
testscan[{a, 1}]
out:
{a,{a,1}}
So setPart doesn't seem to work inside modules as the way I have it. Can you offer my any further assistance? Again, thank you so much for your time.
Leonid - I am fairly new to Mathematica so I wasn't sure about these subtleties, but now its pretty clear that indeed I am just trying to find workarounds instead of a proper solution. The 'true' problem I am working on is trying to scan a parameter space of varying numbers of parameters subject to some constraints (I am interested in any number of constraints just out of curiosity, but in reality no more than 2 constraints in the actual). So it would look something like :
TestScan[c1,...,cm,{list1,....listn}]
Where the ci are constraints and the list_i's take the form {x_i,x_i_initial, x_i_final, x_i_increment} that will be fed to a Do loop.
For example I might have a constraint like x^2+y^2+z^2=1, I want to scan over values of y and z, solve for the corresponding values of x, then store all the possible solutions in a list. By putting the variables I want to scan over in an array it seems easier since then I can have Mathematica see the size of the array, and run the proper number of Do loops. Obviously if I just put the variables in a function like
TestScan[c1,...,cm,x_i,x_i_initial, x_i_final, x_i_increment,....]
it works, but I would have to change the code every time I change the number of variables in the constraints. So this to me boils down to my earlier question of how to make Mathematica see a part of a list as a variable that I can then increment in a Do loop inside a Module.Do you have any advice how I could achieve this without such work-arounds, and hopefully without bothering you any more? Thanks a ton for your time. DB
A:
You should have included the error messages. There are several problems with this code. First, you can only assign to parts of an expression, if it is stored in some symbol. This is because expressions are immutable in Mathematica. I discuss this here. In your case, you pass the list itself. So, the first step would be to use pass-by-reference semantics (emulated by Hold - attributes) and write
SetAttributes[testscan, HoldAll];
testscan[listin_] :=
Module[{zz},
Do[
listin[[1]] = zz; Print[{zz, listin[[1]]}],
{zz, 1, 2, 1}
]
]
and then use it as
lst = {a, 1, 3, 1};
testscan[lst]
which gives the desired outcome, bacause now the input list is stored in a variable which is passed unevaluated (as a reference, more or less).
It is important to note however, that the a in lst was not modified, but rather replaced by new values, so that now
?lst
Global`lst
lst={2,1,3,1}
If you really want to modify a, I recommend reading this answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
TFS 2015 - Build failed due to exception in the test assemblies
I am trying to run a newly created Build in TFS but i am getting an error as shown in the screenshot below :
Build Configuration
I tried to debug the Unit Test project on my machine and even on the TFS server, it worked fine. So i am not able to understand if there is any configuration missing or issue in the test assemblies code?
A:
Update
Since VS is installed after the build agent configured. Then reregister the build agent with TFS, since the system capabilities are only discovered when the agent is first configured -- any changes made after that are not captured.
First you could also Enable Verbose Debug Mode for TFS Build vNext by add system.debug=true to get more detail log info for trobuleshooting.
According to your build log and configuration, the error occurs after code coverage warning.
Try to uncheck the code coverage option and trigger the build again.
As a prerequisite to using Code Coverage, the first thing to do is to install Visual Studio Enterprise version on the build agent.
| {
"pile_set_name": "StackExchange"
} |
Q:
load data from cache with NSURL doesn't work
i'm trying to load a photo from my cache directory.
this is the code where i write the photo into a cache folder:
+(BOOL)writeAData:(NSData *)imageData atURL:(NSURL *)fileUrl
{
return [imageData writeToURL:fileUrl atomically:YES];
}
this code works fine, but i have problems when i try to load the code from the cache folders:
i use the method initWithContentsOfURL inside a block:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageUrl];
this is the format of url
file://localhost/Users/MarcoMignano/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/0E8E54D8-9634-41CF-934B-A7315411F12F/Library/Caches/image_cache/Meyer%20Library.jpg
the URL is correct, but when i try to use the method above i get this error:
..... [__NSCFString isFileURL]: unrecognized selector sent to instance 0x8a0c5b0 .....
that is the code when i take the url of my model:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
self.photos = [PhotoAlreadyDisplayed getAllPicture];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([sender isKindOfClass:[UITableViewCell class]]) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if (indexPath) {
if ([segue.identifier isEqualToString:@"Show Image"]) {
if ([segue.destinationViewController respondsToSelector:@selector(setImageUrl:)]) {
NSURL *url = [[self.photos objectAtIndex:indexPath.row] valueForKey:@"url"];
[segue.destinationViewController performSelector:@selector(setImageUrl:) withObject:url];
[segue.destinationViewController setTitle:[self titleForRow:indexPath.row]];
}
}
}
}
}
whats wrong with the URL? how can i fix it? thank you
i have find the solution:
when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:@"url"]];
Now all works fine, thank you so much for yours help
A:
solution: when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:@"url"]];
Now all works fine, thank you so much for yours help
| {
"pile_set_name": "StackExchange"
} |
Q:
CURL PHP POST interferes with JSON
I currently have an API script that returns JSON. It has worked up until I tried to add in a curl php POST script before it. The curl script is working on it's own, and it is also working in the API script. However the JSON code is not being returned.
Is there something fundamentally wrong with this approach below?
Thanks in advance.
EDIT: The curl script works 100% on its own.
Said script is also working inside the below, it's just that the JSON does not return.
$name = "foo";
$age = "bar";
//set POST variables
$url = 'https://www.example.com';
$fields = array(
'name' => urlencode($name),
'age' => urlencode($age)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return json_encode(
array(
"status" => 1,
"message" => "Success!",
"request" => 10
)
);
A:
You need to do the following use echo and also use CURLOPT_RETURNTRANSFER if not the output would be transferred directly to the page instead of $result
$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);
header('Content-type: application/json');
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't bind params using [FromQuery] ASP Net Core 2 API
I'm new in ASP Net Core 2, I want to bind different parameters that come from URL query string to action parameters in my action:
[HttpGet("{page}&{pageSize}&{predicate}", Name = "GetBuildingsBySearchCriteria")]
public IActionResult GetBuildingsBySearchCriteria([FromHeader] string idUser, [FromQuery]int page, [FromQuery]int pageSize, [FromQuery]string predicate)
{
....
}
When I test my action using postman, I set the idUser in header and other parameters in URL, example:
http://localhost:51232/api/buildings/page=1&pageSize=10&predicate=fr
The result is that I receive the idUser that I send from the header but other parameters are empty.
Do I miss something or what is wrong in my code?
A:
If those parameter are meant to be in the query then there is no need for them in the route template
In
[HttpGet("{page}&{pageSize}&{predicate}", Name = "GetBuildingsBySearchCriteria")]
"{page}&{pageSize}&{predicate}" are placeholders in the route template, which is why the [FromQuery] fails to bind the parameters.
[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want to apply.
emphasis mine
Based on the example URL shown and assuming a root route, then one option is to use
[Route("api/[controller]")]
public class BuildingsController: Controller {
//GET api/buildings?page=1&pageSize=10&predicate=fr
[HttpGet("", Name = "GetBuildingsBySearchCriteria")]
public IActionResult GetBuildingsBySearchCriteria(
[FromHeader]string idUser,
[FromQuery]int page,
[FromQuery]int pageSize,
[FromQuery]string predicate) {
//....
}
}
or alternatively you can use them in the route like
[Route("api/[controller]")]
public class BuildingsController: Controller {
//GET api/buildings/1/10/fr
[HttpGet("{page:int}/{pageSize:int}/{predicate}", Name = "GetBuildingsBySearchCriteria")]
public IActionResult GetBuildingsBySearchCriteria(
[FromHeader]string idUser,
[FromRoute]int page,
[FromRoute]int pageSize,
[FromRoute]string predicate) {
//....
}
}
Reference Model Binding in ASP.NET Core
| {
"pile_set_name": "StackExchange"
} |
Q:
absolute ignoring parent padding
I am using bootstrap and I am trying to create my own dropdown menu on right side.
I Tried below css.But its ignoring parents padding.But when I use position : relative Its working fine but its pushing the text contents down.So I want absolute overlay but also Preserve the parent padding.
.menu
{
background:#ccc;
top: 50px;
right: 0px;
position: absolute;
clear: both;
}
Here is the fiddle with html - http://jsfiddle.net/97bqun6s/
P.s: my parent is bootstrap .container class whose padding varies for screen sizes.
A:
When you use position: absolute on an element then that element will be positioned within its closest 'non static' parent container's content area and padding box. You can refer to the Box Model for reference.
A simple solution would be to say right: 15px. This will offset the side-nav from the right to align with the rest of the container.
See this jsFiddle
EDIT:
Since the padding of the container is variable this may not be a viable solution.
You could instead add a wrapper div just inside the container
<div class="container">
<div class="content-wrap">
...
</div>
</div>
and position it relative.
.content-wrap {
position: relative;
}
See updated jsFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Removing forks in a shell script so that it runs well in Cygwin
I'm trying to run a shell script on windows in Cygwin. The problem I'm having is that it runs extremely slowly in the following section of code. From a bit of googling, I believe its due to there being a large amount of fork() calls within the script and as windows has to use Cygwins emulation of this, it just slows to a crawl.
A typical scenario would be in Linux, the script would complete in < 10 seconds (depending on file size) but in Windows on Cygin for the same file it would take nearly 10 minutes.....
So the question is, how can i remove some of these forks and still have the script return the same output. I'm not expecting miracles but I'd like to cut that 10 minute wait time down a fair bit.
Thanks.
check_for_customization(){
filename="$1"
extended_class_file="$2"
grep "extends" "$filename" | grep "class" | grep -v -e '^\s*<!--' | while read line; do
classname="$(echo $line | perl -pe 's{^.*class\s*([^\s]+).*}{$1}')"
extended_classname="$(echo $line | perl -pe 's{^.*extends\s*([^\s]+).*}{$1}')"
case "$classname" in
*"$extended_classname"*) echo "$filename"; echo "$extended_classname |$classname | $filename" >> "$extended_class_file";;
esac
done
}
Update: Changed the regex a bit and used a bit more perl:
check_for_customization(){
filename="$1"
extended_class_file="$2"
grep "^\(class\|\(.*\s\)*class\)\s.*\sextends\s\S*\(.*$\)" "$filename" | grep -v -e '^\s*<!--' | perl -pe 's{^.*class\s*([^\s]+).*extends\s*([^\s]+).*}{$1 $2}' | while read classname extended_classname; do
case "$classname" in
*"$extended_classname"*) echo "$filename"; echo "$extended_classname | $classname | $filename" >> "$extended_class_file";;
esac
done
}
So, using the above code, the run time was reduced from about 8 minutes to 2.5 minutes. Quite an improvement.
If anybody can suggest any other changes I would appreciate it.
A:
Put more commands into one perl script, e. g.
check_for_customization(){
filename="$1" extended_class_file="$2" perl -n - "$1" <<\EOF
next if /^\s*<!--/;
next unless /^.*class\s*([^\s]+).*/; $classname = $1;
next unless /^.*extends\s*([^\s]+).*/; $extended_classname = $1;
if (index($extended_classname, $classname) != -1)
{
print "$ENV{filename}\n";
open FILEOUT, ">>$ENV{extended_class_file}";
print FILEOUT "$extended_classname |$classname | $ENV{filename}\n"
}
EOF
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Condensing Batch File to a Single Line
I'm programatically creating a batch file. Limitations in the language I'm using (old delphi) mean I can't write to separate lines to the .bat. So my batch has to be a single line.
I have read this and was able to condense a few of the lines. But using the double ampersands && doesn't work for some of the lines and I haven't had success with the ping pause either.
Here's where I am at...
@echo off & setlocal enableextensions&&set myfolder_=Z:\MyFolder
for /f "delims=" %%f in ('dir /o:d /a:-d /b "%myfolder_%\*.mp3"') do (set latest_=%myfolder_%\%%~nxf)
if defined latest_ (echo rem latest file "%latest_%"&xcopy "%latest_%" "Z:\MyFolder\PlayMe" /V /D /Y) else (echo No designated files found in "%myfolder_%")
Pause
Is it possible to further reduce the lines of code to a single line so that the batch still runs?
A:
You need to include ENABLEDELAYEDEXPANSION in your setlocal and use !var! in place of %var%
| {
"pile_set_name": "StackExchange"
} |
Q:
How to trim off symbols from NSNumber?
Im making an iOS app to do with currency. My app receives the value of maybe: $4. This value the app receives is put into an NSNumber. The trouble is the value actualy has a $ in it. How do I trim out the $ in the NSNumber? Or would I be better of putting it into an NSString?
A:
Use NSNumberFormatter:
// set up your number formatter
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
// get a string that you'll be converting to a NSNumber
NSString *myNumberString = [NSString stringWithFormat:@"$4"]
// convert then print to the console
NSNumber *myNumber = [numberFormatter numberFromString:myNumberString];
NSLog(@"myNumber: %@", myNumber);
This should accomplish what you're looking to do. myNumberString will need to be altered to contain whatever string you're receiving.
NSNumberFormatter Documentation: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Problem with Regex.Match vs Regex.IsMatch
i'm trying to replace a text which contains url's with the text with the tags and i'm trying to use something like this, but i just don't get why this is not working, maybe i'm too tired too see it. Here goes my test:
[Test]
public void Check() {
string expUrl = @"^(https?://)"
+ @"?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
+ @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
+ @"|" // allows either IP or domain
+ @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
+ @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]" // second level domain
+ @"(\.[a-z]{2,6})?)" // first level domain- .com or .museum is optional
+ @"(:[0-9]{1,5})?" // port number- :80
+ @"((/?)|" // a slash isn't required if there is no file name
+ @"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
const string url = "http://www.google.com";
var b = Regex.IsMatch(url, expUrl);
Assert.IsTrue(b);
var text = string.Format("this is a link... {0} end of link", url);
var resul = Regex.Match(text, expUrl);
Assert.IsTrue(resul.Success);
}
Why the url variable passes the IsMatch Check, but doesn't pass the Match check? thanks in advance.
A:
Because you started your regex with ^ and ended with $. Those specify that the match must begin at the start of the string and end at the end. Since your match is in the middle, it was not found.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android: Making the width and the height of a custom view equal
I am using a custom view (CoordinateGridView) in XML like this:
<com.android.catvehicle.CoordinateGridView
android:id="@+id/coordinateGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
I am trying to get the width of the CoordinateGridView to fill the entire width of the screen. The height should then match the width -- therefore, the custom view should always be drawn as a square.
How do I do this?
A:
Override the onMeasure function in CoordinateGridView:
public void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
setMeasuredDimension(size, size);
}
See https://github.com/chiuki/android-square-view for a full example.
| {
"pile_set_name": "StackExchange"
} |
Q:
select and modify material in a three.js scene
i have a scene(object) json file with this structure that i load with ObjectLoader.
Once added in a scene i want to modify texture to add parameters like THREE.SmoothShading, add an envMap...
i know how to find an object: var obj = scene.getObjectByName( "bas", true );
but i have to idea how to select a material and make modification that apply to all object using this material
Can't find anything on the web, could someone help please ?
best regards
A:
This is how you can traverse your scene and set the castShadow flag on your objects. You can add more checks in there.
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.castShadow = true;
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve the original file name using PowerShell
Suppose I renamed multiple files by mistake and now I want change the file name as it was earlier.
example: The original name of file was “Test” through PowerShell we renamed it to “Tested” and again we want to retrieve the original name back and I don’t remember.
A:
Unfortunately Windows doesn't store these information by default. You can enable auditing for a file (right click -> properties -> Security -> advanced -> auditing) to store these information in the future but right now, the answer is: It isn't possible.
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap 4 column order not working on mobile
I want to use order-width-pos from bootstrap 4 but for some reason its not working on the mobile view. It works fine up until the point where it snaps to the mobile viewsize and I dont know why.
https://codepen.io/anon/pen/zRpQeG
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<section>
<div class="container">
<div class="row ">
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-6 order-xs-last order-md-last order-lg-first box">
<h1>col 1</h1>
<hr/>
</div>
<div class=" col-xl-3 col-lg-6 col-md-6 col-lg-6 order-xs-first order-lg-first box">
<h1>Col 2</h1>
<hr/>
</div>
<div class=" col-xl-6 col-md-12 order-md-first order-xs-first order-lg-last box">
<h1>Col 3</h1>
<hr/>
</div>
</div>
</div>
</section>
A:
There is no more xs with Bootsrtrap V4 so remove it and it will work.
The new version of Bootstrap is mobile first so no prefix (sm, md, lg) is equivalent to extra-small device. If you specifiy sm it is equivalent to small device and up.
As you can read in the documentation:
Grid breakpoints are based on minimum width media queries, meaning
they apply to that one breakpoint and all those above it (e.g.,
.col-sm-4 applies to small, medium, large, and extra large devices,
but not the first xs breakpoint)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<section>
<div class="container">
<div class="row ">
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-6 order-last order-md-last order-lg-first box">
<h1>col 1</h1>
<hr/>
</div>
<div class=" col-xl-3 col-lg-6 col-md-6 col-lg-6 order-first order-lg-first box">
<h1>Col 2</h1>
<hr/>
</div>
<div class=" col-xl-6 col-md-12 order-md-first order-first order-lg-last box">
<h1>Col 3</h1>
<hr/>
</div>
</div>
</div>
</section>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to resolve Array Index OutOfBoundsException
I have the below code. When I execute it, I get the below error. I run the same code in another step, it works fine, but in the current step it fails.
java.util.concurrent.ExecutionException: java.lang.ArrayIndexOutOfBoundsException: 17
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def dbData = queryResults;
def mailTable = "<table style='border: 1px solid #ccc;border-collapse: collapse;'>";
def size = 17;
mailTable += "<tr style='border-top: 3px solid #ccc;'><b><u><td style='padding: 10px;bgcolor=#4169E1;'>SKU</td><td style='padding: 10px;bgcolor=#4169E1;'>Currency</td><td style='padding:10px;bgcolor=#4169E1;'>Source</td><td style='padding: 10px;bgcolor=#4169E1;'>Pricing Sort</td><td style='padding: 10px;bgcolor=#4169E1;'>Role</td><td style='padding: 10px;bgcolor=#4169E1;'>Product Manager</td><td style='padding: 10px;bgcolor=#4169E1;'>Price</td><td style='padding: 10px;bgcolor=#4169E1;'>Layout</td><td style='padding: 10px;bgcolor=#4169E1;'>Description</td><td style='padding: 10px;bgcolor=#4169E1;'>Reference</td><td style='padding: 10px;bgcolor=#4169E1;'>Global</td><td style='padding: 10px;bgcolor=#4169E1;'>Status</td><td style='padding: 10px;bgcolor=#4169E1;'>Material</td><td style='padding: 10px;bgcolor=#4169E1;'>Business</td><td style='padding: 10px;bgcolor=#4169E1;'>SB</td><td style='padding: 10px;bgcolor=#4169E1;'>Group</td><td style='padding: 10px;bgcolor=#4169E1;'>GPH Code</td></u></b></tr>"
/**
* filling the html table with opportunity info
* */
def index;
dbData.each {row ->
mailTable += "<tr style='border-top: 3px solid #ccc;'>";
for (index = 0; index < size; ++index) {
mailTable += "<td style='padding: 10px;'>" + row.getAt(index) + "</td>";
}
mailTable += "</tr>";
}
mailTable += "</table>";
A:
You're getting the Array Index OutOfBoundsException because you're trying to access element in an empty Array (0 elements) most likely. I'd suggest you check if the Array is empty before you attempt to get elements from it.
I'm not quite sure which Array is throwing the error in your code as I can't tell what the database call does. But I'd guess it's either dbData or mailTable.
Try something like this:
if (dbData.length != 0) {
//run your code here that access the elements
} else { //do nothing..or whatever you want to happen when it's empty, maybe
error? }
| {
"pile_set_name": "StackExchange"
} |
Q:
try/except in django, good practices
This part of code represents a index of my web page
eg: 127.0.0.1:8000/
def IndexView(request):
try:
profile = request.user.get_profile()
except User.DoesNotExist:
return render_to_response('index.html',
{'request': request,},
context_instance=RequestContext(request))
return render_to_response('index.html',
{'request': request, 'profile' : profile},
context_instance=RequestContext(request))
Why i'm still getting this error on debug?
AttributeError at /
'AnonymousUser' object has no attribute 'get_profile'
thanks in advance
A:
You need to add this check:
from django.shortcuts import render
def index_view(request):
if request.user.is_authenticated():
profile = request.user.get_profile()
return render(request,'index.html',{'profile': profile})
else:
return redirect('login/')
Or, you can use the built-in decorator which ensures that your view is only called with a logged in user:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def index_view(request):
profile = request.user.get_profile()
return render(request,'index.html',{'profile': profile})
If you use the login_required decorator you need to make sure you have a LOGIN_URL setting that points to the view that handles the login form for your site. By default this is /accounts/login/
I changed the method name to lowercase as CamelCase is usually for classes in Python. Also, you don't need two return statements since you are rendering the same template. Instead, in your index.html template you can do:
{% if profile %}
You have a profile!
{% else %}
You don't
{% endif %}
Tips and tricks with authentication are listed at the authentication entry in the documentation.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to fetch records according to largest first
How to fetch records according to largest first?
Example
SELECT marks FROM students
marks
50
20
80
65
35
But I want to fetch details according to highest marks like this
Marks
80
65
50
35
20
A:
You should just user ORDER BY the column you want and ASC or DESC for ascending or descending ordering
SELECT marks FROM students ORDER BY marks DESC
| {
"pile_set_name": "StackExchange"
} |
Q:
How many ways can a from be filled out?
In a survey, viewers are given a list of 20 TV programmes. They are asked to label their three
favourites 1, 2 and 3, and to put a tick against those they have heard of (if any) from the
remaining 17. In how many ways can the form be filled out? (Assume that everyone has three
favourite programmes to nominate.)
A:
Choose favourite 1... $20$ ways
Choose favourite 2... $19$ ways
Choose favourite 3... $18$ ways
For each of the 17 remaining programmes decide whether or not to tick it... $2^{17}$ ways
So answer is $20*19*18*2^{17}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Sending JSON to PHP using ajax, troubles with data
my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
A:
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
A:
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
A:
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic
| {
"pile_set_name": "StackExchange"
} |
Q:
What is being said in the purely Native American language scenes in Jim Jarmusch’s “Dead Man?”
While Jim Jarmusch’s film Dead Man (1995) is a 19th century American period piece that contains mostly American English dialogue, there are a few scenes in the film that are spoken purely in Native American languages without translation or subtitles. As explained on Wikipedia; bold emphasis is mine:
The film is also notable as one of the rather few films about Native Americans to be directed by a non-native and offer nuanced and considerate details of the individual differences between Native American tribes free of common stereotypes. The film contains conversations in the Cree and Blackfoot languages, which were intentionally not translated or subtitled, for the exclusive understanding of members of those nations, including several in-jokes aimed at Native American viewers. The Native character was also played by an Indigenous American actor, Gary Farmer, who is a Cayuga.
That all sounds fine. But does any translation of the dialogue exist anywhere?
A:
Okay, I found a post on Reddit from 2015 that essentially asks the same question as this question. And there is an answer there that provides translation of some of the dialogue, but it is in a PDF format.
So I am posting that translation here as plain text—with some copy edits and formatting tweaks—so it’s easier to read. Here is the scene with “Nobody” and his girlfriend translated by Dorothy Thunder from the University of Alberta from Cree to English:
Girlfriend: Tâp’we cî ôma ewînakasiyan? (Is it true that you are going to leave me?)
Nobody: Nîcimos! (My sweetheart!)
Girlfriend: Ketweyan kîya esaweyimikâsot maskwa mâka ki-tâpwem kîminîcâkanis! (You say you are a gifted/blessed bear but a true/real bastard. I pray here to night moon every night you to have a child but you don’t agree to it. This is not me — I am still young and kind — you dick/penis!)
Nobody: Nîcimos! (My sweetheart!)
Girlfriend: Nikiskeyihten, nikiskeyihten keyâpic ka-nitaweyimin! Ekosi! (I know, I know that you will still want me! That’s it!)
Nobody: Nîcimos! (My sweetheart!)
Girlfriend: Awas! (Get out of here! / Get lost!)
Nobody: Ceskwa! Nîcimos, ceskwa! (Wait! My sweetheart, wait!)
And here is info on the scenes in the Makah Village near the end of the film translated by Maria Parker Pascua and according to her those scenes are in the Makah language and the tribes mentioned were Cree and Blackfoot. Leaving in some descriptions for context from the translator:
The 6th scene has Makah words when they arrive by canoe on the Columbia River to a Native Village.
Nobody: Hello! Is that you folks, my Makah people (A form of greeting in Makah). I am Nobody.
The next part is not as clear, but it sounds like he is continues on to say something like:
Nobody: Needing an Indian Doctor (Shaman/Healer).
Nobody: Give. (Like give help or maybe give them the sick man?)
The last scene with Native language is also Makah, but the first part sounds a little clipped.
Nobody: Hello! Is that you folks? (A form of greeting in Makah). It’s a nice day!
And a village man answers him with:
Village Man: Yes. It is a nice day.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does "do sea on classes" mean?
I see this sentence on https://twitter.com/jfbastien/status/1003697787911966720
A: I've made my submissions for @cpponsea, have you?
B: Sorry, I only do Sea on Classes
C: you can do classes on the sea at C++ on Sea - and in class, too
Google tells me nothing: do sea do sea on class
A:
Its a joke, a pun based on the fact that C (the programming language) and "sea" sound the same.
There is going to be a conference C++ on Sea, in a coastal town (some coastal towns have the suffix -on-sea, eg Southend-on-sea). The pun is then continued, as "on the sea" means in a boat; C++ has classes but C does not.
So if you were programming in C++, in a classroom on a boat, while attending the conference you could be said to be doing "classes on the sea at C++ on Sea - and in class".
| {
"pile_set_name": "StackExchange"
} |
Q:
how to writhe a Php inside HTML with substr
I write this bellow code
<div class="description"><?php echo substr($data['description'],strpos($data['description'],$info['title']),100); ?></div>
when I change method to this bellow code I get an error!!
<?php echo'<div class="description">'.substr('.$data['description'].',strpos('.$data['description'].','.$info['title']).',100).'</div>'; ?>
error: Parse error: syntax error, unexpected T_STRING...
A:
You need to write your PHP code inside <?php and ?> tags.
You cant just write your php code as a string. PHP interpreter needs to know what code should be interpreted.
EDIT:
You cant put variables names in quotes. Try this:
<?php echo '<div class="description">' . substr($data['description'], strpos($data['description'], $info['title']), 100) . '</div>'; ?>
| {
"pile_set_name": "StackExchange"
} |
Q:
Installed trigger app, installed node.js, trigger says it can't run npm on Mac
New Mac user account. I install the Trigger.io (TriggerToolkit) app for the Mac. It fires up a tab with the apps. I can run the iOS simulator from it - so it is plausibly working installation. I have installed node.js from the node.js website, using the Mac package.
I have node.js as /usr/local/bin/npm (version 1.1.43).
It is found when I type "npm" at a command line.
The path "/usr/local/bin" is on my $PATH.
"/usr/local/bin" is set in my /etc/paths file, system wide.
So the npm executable should be findable by any user, at any time (before or after login, running a terminal, etc).
When I use the web page for the web run, it's OK, until it tries to run npm.
[DEBUG] running run_web((), {})
[DEBUG] Running: npm install
[DEBUG] failed to run npm: do you have Node.js installed and on your path? while running run_web((), {})
[ERROR] failed to run npm: do you have Node.js installed and on your path?
I guess that the problem must be something to do with an assumption about the path for npm. What's the assumption? What can I symlink to make this work?
Note that npm is found by "forge run web". This is something specific to the way that TriggerToolkit.app is working.
A:
Update: this is fixed as of v1.4.6:
http://docs.trigger.io/en/v1.4/release-notes.html#v1-4-6
Previous answer:
Unfortunately I think the error message here isn't great and reflects a general problem with starting the node app.
We are aware of one issue with dependencies which started occurring after Node 0.8. Can you check what Node version you have:
node --version
If it's 0.8, then a temporary workaround to this problem is to use the command line tools and:
forge build
Then manually update development/web/package.json to refer to express 2.5.10, then
forge run web
Sorry for the trouble, we'll report back here when that's fixed
| {
"pile_set_name": "StackExchange"
} |
Q:
socket.io - emitting from within an anonymous function
I am quite new to the world of async. I am trying to do everything with callbacks at first before using any of the libraries out there. I think I have a closure problem, but don't know what to do about it.
Here is some code:
namespace.on('connection', function(socket){
var newClient = socket.id//just in case the a new user logged on between declaration and use
socket.join('room1')
function newConnection(positionCallback, hashCallback, newUser){
namespace.to(socket.id).emit('hello', {yo:'works'})
for(var i=0; i< cardCounter ;i++){
var keyVal = 'card:'+ cardArray[i]
redis.hgetall(keyVal, function (err, storedMsg) {
namespace.to(socket.id).emit('hello', {yo:'doesnt work'})
hashCallback(storedMsg, newUser)
});
if(i==cardCounter-1){
positionCallback()
}
}
}
function onConnectionComplete(){
namespace.to(socket.id).emit('hello', {yo:'works'})
}
function onHashComplete(hashObject, newUser){
namespace.to(newUser).emit('hello', {yo:'doesnt work'})
}
newConnection(onConnectionComplete, onHashComplete, newClient)
}
I have placed some socketio emits around the place to pinpoint where things go wrong.
Any emits outside of the call to redis work as expected. As soon as I go inside that anonymous function - nada.
That said, I have console.log()'ed everything inside that function. I get the right results from redis, I have the right user, and namespace is defined.
I just can't emit the result.
I would have thought that the anonymous function had access to the scope just outside it - but not the other way around. I don't see what is not making it across...
Also I know that some people don't like the if statement to invoke a callback, but that might be a discussion for another day.
A:
It was a closure problem! Just not what I was expecting.
I also, ahem, don't really understand it.
The callback isn't the problem, getting variables accessible inside the redis response function is. I would have thought that any variables declared in a parent/ancestor function are available to children/decedent functions.
In this instance I needed to create a function inside the loop, and explicitly pass variables for it to be available inside a closure.
Here is the stackoverflow question that pointed me in the right direction:
How can I access the key passed to hgetall when using node_redis?
| {
"pile_set_name": "StackExchange"
} |
Q:
Contradiction in Davis–Putnam–Logemann–Loveland (DPLL) Method?!
As we see on page $10,11$ and $12$ on Google Books we know about Unit Clause (UC) and Pure Literal (PL) in DPLL Algorithms. in the following example if assign value $0$ to variables is prior to assign $1$ to variables, PL and UC is used, but I think just UC is used.
$\{\lnot A \lor B \lor C\}, \{A \lor \lnot B \lor C\}, \{A \lor B \lor \lnot C\}, \{A \lor B \lor C\}$
any idea why our solution is differ with answer sheet that say PL and UC is used?
Edit:
I think we have following diagram that in node (3) we can use PL or UC.
A:
Let $\Phi$ the initial set of four clauses as above.
Def 15. A pure literal is a literal $l$ that appears in at least one clause of $\Phi$ while $\lnot l$ doers not appear in any clause of $\Phi$.
Thus, initially, there are no pure literals.
Def 16. A unit clause is a clause with exactly one unknown literal in it.
Thus, initially, there are no unit clauses.
So, you have to apply $DPLL(\Phi)$ selecting e.g. the variable $A$ and branching with:
$DPLL(\Phi|_{A=0})$ and $DPLL(\Phi|_{A=1})$.
For the left branch:
1) $\{ 1∨B∨C \}, \{ 0∨¬B∨C \}, \{ 0∨B∨¬C \}, \{ 0∨B∨C \}$.
Now I suppose you can simplify, according to the rules,:
$1 \lor p \equiv 1$ and $0 \lor p \equiv p$,
to:
1') $\{ 1 \}, \{ ¬B∨C \}, \{ B∨¬C \}, \{ B∨C \}$.
After the first step, again neither pure literals nor unit clauses in this branch.
Then we can go on with $B$; for $B=0$ we have:
1'1) $\{ ¬C \}, \{ C \}$
and for $B=1$:
1'2) $\{ C \}$.
Now we can apply either PL or UL, satisfying this branch.
For the right branch:
2) $\{ 0∨B∨C \}, \{ 1∨¬B∨C \}, \{ 1∨B∨¬C \}, \{ 1∨B∨C \}$.
Simplifying again, we have:
2') $\{ B∨C \}, \{ 1 \}, \{ 1 \}, \{ 1 \}$.
Here we can apply the Pure-Literal rule setting both $B$ and $C$ to $1$, proving again that the formula is SAT.
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP date function producing incorrect result
Am currently running the following PHP version on my laptop
PHP Version 7.0.31-1+ubuntu16.04.1+deb.sury.org+1
Problem is when i run the below piece of code
echo date('b e, Y', strtotime('2013-02-01'));
i get the following output
b Africa/Nairobi, 2013
and yet it is supposed to produce the following output
Feb 1, 2013
What could be causing this?
A:
I think you might want to read the documentation for the date() function again. There is no b option that I'm aware of and:
e - Timezone identifier (added in PHP 5.1.0)
To achieve that result you'd want:
echo date('M j, Y', strtotime('2013-02-01'));
M - A short textual representation of a month, three letters
j - Day of the month without leading zeros
A:
Try simply this M j, Y, See more formatting at official php documentation http://php.net/manual/en/function.date.php
echo date('M j, Y', strtotime('2013-02-01'));
M A short textual representation of a month, three letters e.g Jan through Dec
j Day of the month without leading zeros e.g 1 to 31
Y A full numeric representation of a year, 4 digits e.g: 1999 or 2003
DEMO: https://3v4l.org/97Uvq
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add a circle shaped button with swift?
I am trying to make this simple UI
Now the orange and darkblue are simple two views (the darkblue will have a nested tableview), but how would i make the button with some simple animation? Should i use CALayer or can i make use of the Interface Builder?
A:
I would have done it through code:
let button2 = UIButton()
button2.frame = CGRectMake(0, 0, 100, 100)
button2.layer.borderColor = UIColor.whiteColor().CGColor
button2.layer.borderWidth = 2
button2.layer.cornerRadius = 50
button2.setTitle("button", forState: .Normal)
button2.backgroundColor = UIColor.blueColor()
button2.addTarget(self, action: "buttonAction", forControlEvents: .TouchUpInside)
button2.setTitleColor(UIColor(red: 233/255, green: 64/255, blue: 87/255, alpha: 1), forState: UIControlState.Normal)
self.view.addSubview(button1)
| {
"pile_set_name": "StackExchange"
} |
Q:
Mechanize not logging in to site properly
After spending the best part of 3 hours getting nowhere, i thought i would ask a question myself.
i am using python and mechanize's Browser. I am trying to login to my home router. i can get to the login page, fill the password field (eg br.form['password'] = 'mypassword' etc), but now i am stuck because no matter what i try, i always get sent to a page saying i am forbidden/session has timed out i am handling cookies with a cookie jar, i have handled robots, but it still doesnt love me enough to let me login.... help?
if you have any suggestions as to why i can not login successfully, please, please, please share xxx
EDIT:
it does have javascript, but i am simulating it
**EDIT2:**
i just realized that the javascript i am simulating is for pressing the disconnect button on the previous page...... probably fix my problem if i emulate the javascript for this page ......
i am faking the user agent
i will have a look w/ wireshark xxx
ps thanks for replying so fast xx
UPDATE:
sigh. i think it may just be one of those things where you just have to say f it and move on because i am emulating the javascript it needed exactly as it is done (just checking, MD5 == hashlib.md5("...").hexdigest()?).... thanks anyway people xxx
A:
Since you have to deal with Javascript, I'd try to use WebDriver. It has Python bindings and it's not that hard to use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't deny user access to a library when he is inside the "All Users" group
I'm trying to give an user access to just one folder in our main library, first I gave him permission to access the Site and then I went on the folder that I would like him to have access to and stopped inheriting the permissions, then I added him as an Editor.
The problem that I'm having is that when I give him permission to access the Site he's added in to a group called "All Users" and this group is granted access by default to the entire library, what I expected was to see him listed outside of the group where I could edit the Library permissions and remove him.
I would appreciate any help on this.
Thanks
I'm on SharePoint foundation 2013.
A:
i dont know if you have done this: but cant you give access to the list only? you dont need to give him/her access to the site...
You need to goto the list settings and remove inheritance. Now go to permissions for this list and add the user there! Remove any instance of the user from the site groups and users.
when the user access the list directly(url to list) obviously he would have access depending on what view you gave him to have access to.
If he were to try and goto any other page it would show an access denied page!
| {
"pile_set_name": "StackExchange"
} |
Q:
mysqli - php - returning all results from multiple tables
There is actually alot of answers for questions like that. But everything I found around here was to Join two tables with "like" values. But that isn't what I need.
I want to query two tables, that is almost exactly the same but with different values inside of it.
tbl_one and tbl_two (exemple names) has "id, title, date, content" its just the same. But inside of tbl_one has differente values of tbl_two.
And then, it's time to query. I could make two queries calling for tbl_one and after tbl_two, but it means that I'll have to print in different "whiles" and I don't want this. I need to print the results in only one "while", so I thought about one query to result from different tables, is that a way to do this?
For make it straight, I need to print the results in a while like this:
while($row = $result->fetch_array()) {
// my results printed
}
Where $result is the result from the query from the two previous tables.
I tried... "select * from tbl_one, tbl_two". Life would be a lot easier if this works.
A:
Use union all to combine your queries i.e.
select * from tbl_one
union all select * from tbl_two
| {
"pile_set_name": "StackExchange"
} |
Q:
Scrambled number conversion for numbers with 10 or more digits
This is a quite simple piece of code. It takes an integer and decomposes its decimal digits using quotient and remainder. On each call, it prints a line with r characters 'I', where r is the last digit, then calls itself with the quotient as its new argument.
decToUnary 0 = return ()
decToUnary n = let (q, r) = quotRem n 10 in
do
putStrLn (take r "IIIIIIIIII")
decToUnary q
It works correctly for numbers with less than 10 digits, but for 10 or more digits it scrambles the output. What am I doing wrong, and why does it work this way?
Here are some examples of output, the first is correct, the second is wrong:
*Main> decToUnary 5432
II
III
IIII
IIIII
*Main> decToUnary 5432101234
IIIIIIII
III
IIIIIIIII
III
III
I
IIIIIII
III
I
I
A:
This is an integer overflow question. maxBound :: Int is 2147483647 (on 32-bit machines), so values greater than that overflow.
Use Integer instead of Int: Integer is not a fixed length integer so it won't overflow.
Edit: As applicative notes, you will then need to replace the take r "IIIIIIIIII" with take (fromIntegral r) "IIIIIIIIII" or genericTake r "IIIIIIIIII"; I'd prefer genericReplicate r 'I'.
genericTake and genericReplicate are both in Data.List.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does inheritance can affect performances of an application?
I wonder if performances of an application could be improved by using the more superclasses you can. My question is about Kotlin, but I assume the answer will be the same for Java.
Let's say you have this inheritance schema (the right class is a subclass of the class on his left):
A < B < C < D < E < F < G < ... And so on until Z.
Saying you don't need all the stuff defined in all the subclasses, but only the attributes and the functions of the A class. For an obscure reason, your code uses only Z class.
My question is quite simple: If you change your code to only use A class instead of Z class, will the code be more performant?
Thank you in advance for your answers.
A:
If
"change your code to only use A class instead of Z class"
includes construction, then there is a trivial answer:
Creating and storing an object with less attributes/fields is cheaper than creating an object with more attributes, both in terms of memory and in terms of time it takes to initialize.
Other than that, I would not expect a significant effect on performance.
That said, I wouldn't worry about performance here - choose the type that provides the best abstraction for what you want to do with this. If your code doesn't care what specific subclass you are using and doesn't need any of the functionality provided by the subclasses, use the more general type. That way your code remains more flexible. If your code however needs such functionality at some point, i.e. you have to introduce casts further down the line, then you have gone too far.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java GUI shows blank until resize
I have written a java gui code for many options available on it. the gui is also set visible true but it doesn't show until I pick its border and drag them to resize the gui window. After manually resizing it, it shows everything. Also, the textlabels and the textfields and buttons are not in new lines, they are placed one after one. Please tell me whats wrong with that: here is a part of code:
public static void initGUI(){
JFrame fr = new JFrame();
Container cont = fr.getContentPane();
cont.setLayout( new FlowLayout( ) );
FlowLayout layout = new FlowLayout();
cont.setLayout(layout);
frame.setSize(200,300) ;
frame.setVisible(true) ;
JTextField tName = new JTextField(30);
JTextField tCNIC = new JTextField(15);
JLabel nameLabel = new JLabel("Name:");
JLabel cnicLabel = new JLabel("CNIC #:");
cont.add(nameLabel);
cont.add(tName);
cont.add(cnicLabel);
cont.add(tCNIC);
JButton Cancel = new JButton ("Canel" );
JButton OK = new JButton ("OK" );
savebtn.setPreferredSize(new Dimension(150, 50));
retbtn.setPreferredSize(new Dimension(150, 50));
cont.add(savebtn);
cont.add(retbtn);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
A:
frame.setVisible(true) ;
The above statement should be invoked AFTER all the components have been added to the frame. So it should be the last statement in your method.
Also, you should be invoking:
frame.pack();
instead of setSize(), before making the frame visible so all the components are displayed at their preferred size.
| {
"pile_set_name": "StackExchange"
} |
Q:
Overloading [ ] with a template type
I have a class that takes 2 template types, one for key (K) and one for value (V).
When trying to overload square brackets, I get an error saying "no operator "[]" matches these operands.
template <typename K, typename V>
class MyMap
{
KeyPair<K, V>* Pairs;
int Count = 0;
public:
MyMap()
{
Pairs = new KeyPair<K, V>[100];
}
V& operator[] (const K& key)
{
for (int i = 0; i < Count; ++i)
{
if (key == Pairs[i].Key)
{
return Pairs[i].Value;
}
}
}
};
Then when trying to use it in main...
MyMap<string, int>* myMap = new MyMap<string, int>();
// This gives me a "no operator "[]" matches these operands.
cout << myMap["hello"] << endl;
I have read a lot of other solutions where they know the type for the key, but is it possible to use a template type of a key when overloading like this?
Thanks :)
A:
MyMap<string, int>* myMap = new MyMap<string, int>();
myMap here is a pointer. You meant:
cout << (*myMap)["hello"] << endl;
As oisyn noted, operator[] must be made public as well.
Also:
Don't use raw new/delete. Use smart pointers.
Actually, you probably don't need to allocate. Just create the map on the stack.
You're unnecessarily copying the key in your operator[]. Take it by const&.
| {
"pile_set_name": "StackExchange"
} |
Q:
Como preencher setText do TextView a partir de um ArrayList?
Eu recebo um array com itens de interesses e devo setá-los no setText de um determinado TextView.
Quero que apareçam todos os itens deste array, na tela, na horizontal. Em meu xml de layout, somente coloquei 1 textView para receber todos os itens que vierem neste array.
Minha dúvida, tenho que montar um ListView, na horizontal, para receber este array e apresentá-lo na tela? Ou, posso simplesmente pegar os itens e colocá-los na propriedade setText deste TextView?
Segue o código:
@BindView(R.id.txtInterests)
TextView txt_interests;
CommunityPresenter presenter;
UserCommunity selectedUser;
List<String> interest = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setEnterTransition(new Fade());
}
setContentView(R.layout.activity_ride_request);
ButterKnife.bind(this);
presenter = new CommunityPresenter(this);
first.setText(presenter.getDay(0));
second.setText(presenter.getDay(1));
third.setText(presenter.getDay(2));
user = new SessionManager();
selectedUser = CommunityService.i(getContext()).selectedUser;
reloadView();
send_offer_request.setOnClickListener(presenter.sendRequestOnClickListener(0));
send_ask_request.setOnClickListener(presenter.sendRequestOnClickListener(1));
populateInterests();
}
private void populateInterests() {
RequestManager.UsersInterests(selectedUser.id, new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
//array com os interesses
interest = new Gson().fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").toString(), new TypeToken<ArrayList<String>>() {
}.getType());
txt_interests.setText(); //preencher o TextView com os interesses
}
});
}
A:
De acordo com seu questionamento, vou tentar responder de forma simples baseando nos dados e código que você disponibilizou.
Pelo que percebemos, você declarou uma variável do tipo List<String> cujo nome é interest, que ocasionalmente seriam os interesses que você quer atribuir ao seu TextView.
Para que você capture cada item, é necessário você percorrer toda sua lista. Existem diversas maneiras de você percorrer e capturar elementos de uma lista e uma delas é usar um foreach. Abaixo segue um exemplo bem básico:
String interests = "";
for(String str: interest){
interests+="\n"+str;
}
txt_interests.setText(interests);
Como de preferência sua, querendo que apareça os itens na horizontal, eu inserir um \n para fazer uma quebra de linha no qual o próximo "interesse" aparecerá uma abaixo do outro.
Atualização
Como nosso amigo ressaltou nos comentário, existe uma discussão antiga que frequentemente aparece no Java que é o uso errado da concatenação de Strings, que pode acarretar numa perda de performance e trashing de memória.
O uso do operador + parece inocente, mas o código gerado produz algumas surpresas. Usando um StringBuilder para concatenação pode na verdade produzir um código que é significativamente mais rápido do que usando um String. Segue abaixo:
StringBuilder interests = new StringBuilder();
for(String str: interest){
interests.append("\n").append(str);
}
txt_interests.setText(interests);
Para saber mais detalhes, você pode ler este artigo que fala sobre as diferenças entre String, StringBuilder e StringBuffer em Java.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the property of "reflecting monomorphisms" for a functor, implies its faithfulness?
I can see why
If $F$ is faithful, then it reflects monomorphisms.
My question is does the inverse holds? More generally, I would like to ask:
What are the alternative ways of defining the faithfulness of functors (Apart from "..one which its restriction to home sets is bijective)
Thank you very much.
A:
No. Let $C$ be a groupoid. Then any functor $F : C \to D$ reflects monomorphisms (because every morphism in $C$ is a monomorphism) but most of them are not faithful.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sextortion with actual password not found in leaks
I have received one of those typical sextortion scams ("drive-by exploit", filmed by webcam (mine has tape on it), pay bitcoin etc.). The thing is that an old password of mine is included (I don't even remember where I used it), but searching the password on HaveIBeenPwned returns nothing (I have previously been notified of two leaks, Last.FM and MyFitnessPal, but those accounts use different passwords).
That got me wondering: since this seems to be a rather old password, how complete are databases like HaveIBeenPwned, and where could I report such a new exploit, other than the authorities?
A:
While services like HaveIBeenPwned are fairly extensive, there are still many stolen user / password lists that have not been revealed to the public eye. Maybe a company didn't actually disclose what happened, never realized anything happened, and/or no researcher has yet found the list. Unless you somehow find the list that included that password somewhere, there isn't a good option to try and report this incident.
A:
Services like HaveIBeenPwned only store passwords that have been publicly leaked in attacks. They have no way of knowing if you have changed your password since, and they have no way of knowing if your password has been leaked via other means.
EDIT: just noticed that you were searching your passwords on there. You might have better luck searching usernames or email addresses
A:
To add, Troy Hunt has previously stated that there are occasions where he has been in receipt of compromised credentials and has decided NOT to include those in HIBP.
https://www.troyhunt.com/the-red-cross-blood-service-australias-largest-ever-leak-of-personal-data/
"As a result, I offered to permanently delete the copy I was sent and not load it into HIBP. As of Thursday evening, that's precisely what I did - permanently deleted every trace of it I had. This isn't unprecedented, I took the same steps as part of the clean-up in the wake of the VTech data breach and for all the same reasons it made sense then, it makes sense now. As with VTech, this should give those who were exposed in the incident just a little bit more peace of mind that their data has been contained to the fullest extent possible."
In practice, the ones in HIBPe will have already been in circulation amongst the 'bad guys' for some time, and have either already been exploited or have been determined to be not worth the effort.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android - How to get saved contact id
I want to get saved contact id and i used following way to retrieve it but the problem is it's returning the wrong id.
public static String addContact(FragmentActivity activity, String displayname, String mobilenumber, String homeemail) {
String DisplayName = displayname;
String MobileNumber = mobilenumber;
String homeemailID = homeemail;
int contactID = 0;
ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<ContentProviderOperation>();
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
// ------------------------------------------------------ Names
if (DisplayName != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
}
// ------------------------------------------------------ Mobile Number
if (MobileNumber != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
}
// ------------------------------------------------------ homeEmail
if (homeemailID != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, homeemailID)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME).build());
}
// Asking the Contact provider to create a new contact
try {
// activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
// contentProviderOperation);
ContentProviderResult[] res = activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash + 1, length));
} catch (Exception e) {
e.printStackTrace();
}
return contactID;
}
I think it passing the wrong contact data uri.Please help me to get correct contact id.
A:
Try this way:
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
// Get values from contacts database:
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
sort не работает с std::bind
Почему код не работает, если вместо 3 вставить число меньше 6. И как это можно исправить?
Код должен сортировать вектор с помощью функтора std::greater, который должен применять 1 параметр. Сделать это нужно с помощью std::bind.
#include <set>
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <iterator>
#include <string>
#include <functional>
using namespace std;
template<typename T>
static void PrintVector(const std::vector<T> &v)
{
for (auto iterator = v.begin(); iterator != v.end(); ++iterator)
{
std::cout << *iterator << " ";
}
std::cout << std::endl;
}
int main()
{
vector<int> v = { 1, 8, 7, 4, 3, 6, 2, 5 };
PrintVector(v);
auto greater_binded = bind(greater<int>(), placeholders::_1, 3);
sort(v.begin(), v.end(), greater_binded);
PrintVector(v);
return 0;
}
A:
Алгоритм std::sort предполагает наличие strict weak ordering для функций сравнения (25.4 Sorting and related operations)
3 For all algorithms that take Compare, there is a version that uses
operator< instead. That is, comp(*i, *j) != false defaults to *i < *j
!= false. For algorithms other than those described in 25.4.3 to
work correctly, comp has to induce a strict weak ordering on the
values.
Это значит, что не допускается, что если comp( a, b ) есть true, то одновременно и comp( b, a ) также true.
Если вы хотите разбить массив на партиции, то используйте стандартный алгоритм std::partition. Например,
std::partition( v.begin(), v.end(), greater_binded );
Если необходимо, то затем каждую партицию можно отсортировать отдельно.
| {
"pile_set_name": "StackExchange"
} |
Q:
In Peano arithmetic, can we define inequality using successor?
In Peano arithmetic (first order), we first define natural numbers using a successor function and Peano axioms, then we define addition (and multiplication), and then, we define inequality, as:
$a\leq b\leftrightarrow\exists c\left(a+c=b\right)$
Is there any way to define inequality first, directly from the successor function and Peano axioms? (I mean, if I don't need addition for my purpose, why define it?).
A:
In a precise sense, the answer is no. Namely, let $PA_{succ}$ be the set of PA-theorems in the language containing only the symbol for the successor function; then we can show:
There are models of $PA_{succ}$ with no definable linear ordering.
In particular, this means that there is no first-order formula using only successor which PA proves defines a linear ordering.
Specifically, consider the structure (in the language of successor only) $\mathbb{N}+\mathbb{Z}+\mathbb{Z}$. This is a model of $PA_{succ}$ (this takes a bit of work, but isn't hard), but has no definable linear ordering: consider any automorphism swapping the two $\mathbb{Z}$-parts.
(A bit more thought also shows that there is no formula in the language of successor alone which defines a linear ordering in the standard model $\mathbb{N}$; the key ingredient is the proof that $PA_{succ}$ is complete. And in fact thinking along these lines ultimately shows that no model of $PA_{succ}$ has a definable linear ordering.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating pandas series from two given pd.Series
I'm having a pandas issue.
So I have a pd.Series, serie_1, that looks like the following:
timestamp
2010-05-01 2
2010-06-01 1
2010-07-01 2
2010-08-01 3
2010-09-01 0
2010-10-01 5
And I have another pd.Series, serie_2, that looks like the following:
timestamp
2010-02-01 0
2010-03-01 0
2010-04-01 0
2010-05-01 1
2010-06-01 1
2010-07-01 2
2010-08-01 3
2010-09-01 0
2010-10-01 2
Note that serie_2 starts in 2010-02-01, while serie_1 starts in 2010-05-01. I need to create a pd.Series, call it output_serie, from both serie_1 and serie_2, so that output_serie.index is serie_2.index, and output_serie.values is equal to serie_1.values/serie_2.values.
the output would look like the following:
timestamp
2010-02-01 0
2010-03-01 0
2010-04-01 0
2010-05-01 2
2010-06-01 1
2010-07-01 1
2010-08-01 1
2010-09-01 0
2010-10-01 2
It is not a coincidence that, in both serie_1 and serie_2, 0 valued timestamps are the same (for example, in 2010-09-01).
The only problem is that serie_2 starts in 2010-02-01, and I need to keep those months with the 0 value in the final pd.Series.
Any help on this issue will be highly appreciated.
A:
In [53]: serie_1.divide(serie_2).fillna(0).astype(int)
Out[53]:
2010-02-01 0
2010-03-01 0
2010-04-01 0
2010-05-01 2
2010-06-01 1
2010-07-01 1
2010-08-01 1
2010-09-01 0
2010-10-01 2
dtype: int64
This is the setup I used:
import pandas as pd
serie_1 = pd.Series([2, 1, 2, 3, 0, 5], index=pd.DatetimeIndex(["2010-05-01", "2010-06-01", "2010-07-01", "2010-08-01", "2010-09-01", "2010-10-01", ]), )
serie_2 = pd.Series([0, 0, 0, 1, 1, 2, 3, 0, 2], index=pd.DatetimeIndex(["2010-02-01", "2010-03-01", "2010-04-01", "2010-05-01", "2010-06-01", "2010-07-01", "2010-08-01", "2010-09-01", "2010-10-01", ]), )
| {
"pile_set_name": "StackExchange"
} |
Q:
generating html from xml+xslt from jdeveloper
When I am trying to generate HTML from XML+XSLT in jdeveloper 10g using a java class I am getting following error
XML-22108: (Error) Invalid Source - URL format is incorrect.
XML-22000: (Fatal Error) Error while parsing XSL file (no protocol: headerMenu.xsl)
But when I am compiling the file with another jdk from command line it is working fine.
Following is my code snippet
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(xslHeaderMenu)); //takes the xsl
System.out.println("...xsl for header navigation menu block included...");
transformer.transform(new javax.xml.transform.stream.StreamSource(xmlDataFile),
new javax.xml.transform.stream.StreamResult(new FileOutputStream(htmlHeaderMenu))); //takes the xml and generates html for header menu
Please advice how can I generate inside jdeveloper
A:
In the javadoc for StreamSource, the string method says that it 'Must be a String that conforms to the URI syntax', which you 'headerMenu.xsl' isn't.
I would try:
tFactory.newTransformer(
new javax.xml.transform.stream.StreamSource(
new File(xslHeaderMenu))); //takes the xsl
as File can take an abstract filename (also for the other streamsource)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use `java2wsdl` on a class that `implements`?
I am generating wsdl using java2wsd. My class is
public class REWS {...}.
I just added implements HttpSessionListener like so:
public class REWS implements HttpSessionListener {...}
and I started getting the NoClassDefFoundError error for HttpSessionListener.
I can build the REWS class, but once I want to generate stub with java2wsdl I get NoClassDefFoundError.
How to I tell java2wsdl to take HttpSessionListener from /Tomcat/lib/servlet-api.jar? How do I include servlet-api.jar?
A:
That is a bad design, indeed.
First, let's recall what interfaces are for. Interfaces establish a strong design contract in your class, stronger than declaring the inherited methods "the plain old way". WSDL defines interfaces too, even if java2wsdl works on classes.
You use interfaces because they are parameters of framework methods, allowing you to provide them your own implementation of a contract. With WSDL, it's slightly different. The WSDL is the contract and is self-powered. You don't need anything more in a WSDL except the XSD schemas that are explicitly imported.
So: why does one implement HttpSessionListener? As stated by documentation, a properly registered session listener is activated by the framework when session changes. Is this part of the design contract of your publicly-accessible web service? Absolutely not!!
By implementing, you are implicitly exporting to the public two methods that are for internal use, so you are trying (but won't ever succeed) to declare two additional methods to your public service that handle session changes. That's not only wrong, but impossible because HttpSessionEvent is simply not exportable to XSD!
The proposal
Don't implement this interface on your WS class. Use your custom implementation as a class member and let it interact with your WS class according to what your web service does. I'm not an expert in Tomcat but web services don't use session and cookies, so I doubt you'll ever deal with the session in a web service.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to dump all the XMM registers in gdb?
I can dump the all the integer registers in gdb with just:
info registers
for the xmm registers (intel) I need a file like:
print $xmm0
print $xmm1
...
print $xmm15
and then source that file. Is there an easier way?
A:
(gdb) apropos registers
collect -- Specify one or more data items to be collected at a tracepoint
core-file -- Use FILE as core dump for examining memory and registers
info all-registers -- List of all registers and their contents
...
The last one is the one you want.
A:
The fine manual says:
(gdb) info all-registers
| {
"pile_set_name": "StackExchange"
} |
Q:
Behavior of Non-Hyperbolic Equilibria?
So I'm working on a differential equation problem concerning epidemics - we're using the Kermack-McKendrick model. I've reached a point where I need to sketch phase portraits near my equilibria, however, I'm a little lost with my results. After evaluating my equilibria via the jacobian matrix (once I've linearized) I end up with eigenvalues of $\lambda=0$ and $\lambda=-a$, ($a>0$)
So since I have a real $\lambda=0$ I have a non-hyperbolic equilibira correct? Does this negate my linearization? Is this not a robust case? When I look at the trace-determinant criteria the only value that I can interpret would be when $-a=0$ at which point I think I have a star point but I'm not entirely sure... I could use some direction as to best sketch a phase portrait here...
If it helps, the system I am modeling is:
$$S'=-rIS$$
$$I'=rIS-aI$$
A:
Every point on the axis $I=0$ is a fixed point and every solution starting from $(S_0,I_0)$ in the nonnegative quadrant converges to some point $(S_\infty,0)$. The only case when $S_\infty=0$ is if $S_0=0$.
To see this, note that $S'+I'=-aI$ hence $S'=-rSI=bS(-aI)=bS(S'+I')$ with $b=r/a$.
If $S\ne0$, this is solved by $S'S^{-1}=b(S'+I')$, that is, $\log|S|=b(S+I)+$Constant, or, $$S=S_0\,\mathrm e^{-b(S_0+I_0)}\,\mathrm e^{b(S+I)}.$$ In particular, for every positive $S_0$ and $I_0$, $S_\infty$ is the unique solution in the interval $(0,S_0)$ of the identity $$S_\infty\,\mathrm e^{-bS_\infty}=S_0\,\mathrm e^{-b(S_0+I_0)}.$$
$\qquad\qquad\qquad\qquad$
| {
"pile_set_name": "StackExchange"
} |
Q:
How not to reload Spacy?
When using Spacy and cross importing functions that use it, I would like to avoid having to reload the language models.
Should I pass the loaded model (often named nlp()) as a parameter ? Or is there something more elegant / efficient to do ?
E.g. of what I have today:
module.py
nlp = spacy.load('fr_core_news_md') # IMPORTS ONCE (long time...)
def my_function():
... does something with spacy...
return
main.py
from module import my_function
nlp = spacy.load('fr_core_news_md') # IMPORTS AGAIN (long time...)
my_function()
Thanks for your help !
A:
If you're using a model in your application, you definitely only want to load it once and then pass around the nlp object. This isn't only faster, it also ensures consistency: if you modify the pipeline to add components or if the vocabulary is updated at runtime, you want those changes reflected across your entire application.
That said, the French loading times are unfortunately a bit slow at the moment, because they require more static data. This should hopefully improve in the upcoming versions. You can find more details and solutions in this thread. Summary:
Cut down the list of tokenizer exceptions yourself and limit them to what you need.
Serve your model via a microservice and expose an API endpoint that accepts text you want to process and returns the JSON-formatted predictions. This works especially well if you only need the model to extract something from your text.
| {
"pile_set_name": "StackExchange"
} |
Q:
I dropped my Nikon D5100 and the mirror was stuck
... and i was able to fix that with a small screwdriver putting it back into place with help of a youtube video. The problem i have now is that when i take a picture through the viewfinder of my camera, it looks different then when i take it via live view. I will attach two pictures that should look exactly the same and you will see what i mean.
This is not about exposure or anything, the problem is that i'm "aiming" at the same point and this is the difference. The first picture is taken through the viewfinder.
Did anyone have this problem already and maybe knows how this could be caused and how i can fix it?
A:
So you're close but no cigar on getting the mirror back in position. It's not seating all the way back down to where it should in the "down" position, so when you take a shot through the viewfinder, that extra bit of an angle is tricking you into thinking things are a bit lower or higher than they actually should be to hit the sensor when the mirror rises and the shutter opens.
It's definitely a mechanical rather than electron issue. Have another good look at the mirror and work out if it's either not seating far enough, or if something's bent and it's retracting too far on the spring.
I'm playing with a D5300 and there's a fair amount of tension on the mirror keeping it in place.. are you experiencing that too? Be gentle.. use a toothpick.
K
| {
"pile_set_name": "StackExchange"
} |
Q:
Expand an edittext dynamically
I would like to do the following on Android:
Click on an image --> an icon on the touched spot should appear
When I click that spot again, an EditText should appear
This EditText should expand dynamically when I type in stuff
The original image should be saved with the EditText and the text that I typed in
What would be the best way to accomplish that?
To my knowledge the image can be set to an onClickListener/onTouchListener, and once onClick/onTouch is called, I should be able to add an icon to that location, where the icon is an image and is set to an onTouchListener as well.
When I click on that image, an edittext should appear - not sure how to make it expand dynamically though?
Once the text is entered and a button is clicked, the entire image - with the text in the edittext - should be saved - how would I do that? Draw on a canvas?
Help would be highly appreciated! :)
A:
Step 1
Your Views should be inside a RelativeLayout in order to place them top of each other. When you press your ImageView, small one will be set to Visible (it must be invisible inside xml file or programmatically).
imgV.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
imageViewButton.setVisibility(View.VISIBLE);
}
});
Step 2
When you press small image, EditText will become visible. Same as instucted above.
imageViewButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
editText.setVisibility(View.VISIBLE);
}
});
Step 3
Your EditText expands automatically when typing if you set width to match_parent and height to wrap_content.
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
Step 4
When you want to save your Layout, implement this in your onClick event. (In the example below, it is a LinearLayout but you will have a RelativeLayout, I suppose you can change it according to your needs)
According to the answer on How to save the layout view as image or pdf to sd card in android?
Add permission in the manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use the code below
LinearLayout content = findViewById(R.id.rlid);
content.setDrawingCacheEnabled(true);
Bitmap bitmap = content.getDrawingCache();
File file,f;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
file =new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
if(!file.exists())
{
file.mkdirs();
}
f = new File(file.getAbsolutePath()+file.seperator+ "filename"+".png");
}
FileOutputStream ostream = new FileOutputStream(f);
bitmap.compress(CompressFormat.PNG, 10, ostream);
ostream.close();
}
catch (Exception e){
e.printStackTrace();
}
| {
"pile_set_name": "StackExchange"
} |
Q:
If $X$ is a complete, separable, and perfect metric space, then a map $f$ is topologically transitive if and only if it has a dense orbit.
Let $X$ be a complete, separable, and perfect metric space. I'm trying to show that for map $f : X \rightarrow X$, topological transitivity is equivalent to having a dense orbit.
Dense orbit $\implies$ transitivity: Let $U, V \subset X$. Since there exists $x \in X$ such that $\text{Orb}(x) = \{x, f(x), f^2(x), \dots\} = \{x_1, x_2, x_3, \dots\}$ is dense in $X$, then there exist $n,m \in \mathbb{N}$ such that $x_n := f^n(x) \in U$ and $x_m := f^m(x) \in V$. WLOG assume $n>m$. Since $x_n \in f^{n-m}(\{x_m\})$, then $x_n \in U \cap f^{n-m}(V)$, therefore $f$ is transitive.
I don't know how to show the inverse though, how would I prove that transitivity implies dense orbit?
A:
Let $\{U_k\}$ be a countable basis for the topology. For each $k$ let $V_k$ be the elements of $X$ that visit $U_k$ after some number of applications of $f$. Then $V_k$ is open and dense. By the Baire category theorem, $\cap_k V_k$ is nonempty. An element of this intersection has a dense orbit.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it good practice to add a column specifying test set and train set?
I found a tutorial a while back but cannot locate it again that created an extra column in both the train and the test set that specified true or false for being the training set. I have the code but could not locate where I found it.
titanic.train$IsTrainingSet <- TRUE
titanic.test$IsTrainingSet <- FALSE
Is this good practice or bad practice? I'm just curious because I like how easy it is to split the data after performing your data cleaning and manipulation as below.
titanic.train <- titanic.full[titanic.full$IsTrainingSet == TRUE,]
titanic.test <- titanic.full[titanic.full$IsTrainingSet == FALSE,]
I know there are probably going to be answers of "do what you want to do" but I just didn't know if this was bad practice for any reason to add another column to the data.
A:
Will expand my comment. The tutorial the OP is referring to is here
https://www.kaggle.com/hiteshp/head-start-for-data-scientist
The author of the tutorial put the two sets together to look at all the data. Now a warning: before doing something like that you should check that the two sets have the same characteristics (or as sometime said that they come from the same distribution), otherwise you may end up drawing very wrong conclusions. Better would be to compare the two sets to check if the test set is representative of the training one. That would be much more helpful.
Sometime the dev/test sets are coming from different sources, so be aware of doing something like that, as it may be dangerous.
I hope it helps, Umberto
| {
"pile_set_name": "StackExchange"
} |
Q:
QmlApplicationViewer::setFixedSize does not reflect the same size in xwininfo
How can one control the size of QmlApplicationViewer ? I am using QmlApplicationViewer as a launcher for QML application, and in QML, I set size as...
QmlApplicationViewer viewer;
viewer.setFixedSize(1280,720);
but on X11 side, if i query size. it does not match the size requested in Cpp side.
xwininfo -root -children | grep application_name
can anyone please tell, how can I control the size from with in Qt/QML code ?
Thanks in advance for any tip.
A:
What one could do, if one can't get WM to play nice/or has no window manager, is to set
this flag on your top-level window right after the constructor and
before the setFixedSize():
viewer.setWindowFlags(viewer.windowFlags() | Qt::X11BypassWindowManagerHint);
Please note the documentation for this flag:
"Bypass the window manager completely. This results in a borderless
window that is not managed at all (i.e., no keyboard input unless you
call QWidget::activateWindow() manually)."
| {
"pile_set_name": "StackExchange"
} |
Q:
Recommended approaches for making my code swiggable?
I'm currently refactoring a Tcl plugin library written in C++. Originally the code was hand-written. A second library exists that does the same thing for Java.
The refactored library will be a single C++ library that can be used to create bindings to different languages.
My first tests with SWIG are promising. However, a lot of junk is generated as well. Various base classes and utilities are all exported. These don't make sense from the scripting point of view and only increase clutter.
Possible solutions that I can think of are:
Use #ifndef SWIG in the original codebase to filter out unneeded code
Create a SWIG-compatible wrapper around the API classes.
Differentiate between public and private headers. Public headers are pure abstract base classes that contain no implementation. The private headers inherit and implement them. Only SWIG the public headers.
The opposite of the above solution: inherit a SWIG-compatible class for each API class.
I'm currently leaning towards solution 3 at the moment. However, I'm not really certain so I'd like to know the SO community's opinion on this. Feel free to share your thoughts.
Update
I forgot to list one solution:
Code that should not exported by SWIG should probably not be in the public section of your class.
Perhaps this is the answer. I'll have another look on Monday.
Update
I settled with a solution. See my answer.
A:
Any approach that means that the C++ library becomes less useful to the C++ user is not the ideal solution.
#ifdef SWIG in the middle of .hpp files: Muddies up your C++ with unnecessary cruft, so it's not ideal
SWIG Specific Interface: This is a viable option, but only makes sense if the code you want to expose to SWIG is significantly higher level then the base C++ API.
Public vs Private interface: Might make sense, but again you have to ask at what cost to the C++ user of the API? Are you limiting the public interface too much? Who has access to the private interface? Should the pImpl idiom be considered instead?
SWIG Compatible Class for each interface: Probably more work than necessary.
First and foremost, to keep your SWIG related code separate from the rest of the API.
You probably don't want to import the .hpp files directly into SWIG (if SWIG wasn't considered during the initial design of the library), but if you do, you want to use a SWIG .i file to help you clean up the mess. There are three basic approaches we use, each with different use cases.
First, direct inclusion. This is useful if you know your API is nice and clean and well suited for parsing by SWIG:
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
%include "MyClass.hpp" // included and parsed directly by SWIG
The second case is for code that is most of the way there. This is code that had SWIG taken into consideration, but really needed some stuff for the C++ user that we didn't want to expose to SWIG:
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
%ignore MyClass::someFunction(); // This function really just causes us problems
%include "MyClass.hpp" // included and parsed directly by SWIG
The third case, and probably the one you want to use, is to directly choose which functions you want to expose to SWIG.
// MyClass.i
%{
#include "MyClass.hpp" // included for the generated .cxx file
%}
// With this example we provide exactly as much information to SWIG as we want
// it to have. Want it to know the base class? Add it. Don't want it to know about
// a function? Leave it out. want to add a new function? %extend it.
class MyClass
{
void importantFunction();
void importantFunction2();
}
| {
"pile_set_name": "StackExchange"
} |