text
stringlengths
64
81.1k
meta
dict
Q: DB2 start tuning needs privilege When I run "start tuning" by db2 data studio it gives me the below message. This still happens when I run it under user "db2inst", the default user which I configured when I installed db2 on RedHat 7.2 A: @ Mark Barinstein many thanks to you because you made it easier for me This worked with me with below two steps :- 1- [db2inst@localhost ~]$ db2 connect to TESTDB 2- [db2inst@localhost ~]$ db2 "CALL SYSPROC.SYSINSTALLOBJECTS('EXPLAIN', 'C', '', current_user)"
{ "pile_set_name": "StackExchange" }
Q: Does the first MapActivity instance always leak? While investigating memory issues in our application, it turns out that if the application Activity is a MapActivity, the first instance of it won't be finalized. Leading to other memory leak such as the view passed to setContentView. Does anyone notice that before? Here is the testing code showing that "MainActivity : 1" is not finalized whereas it is if MainActivity inherits from Activity. To test, one needs to change device or emulator orientation many times. import com.google.android.maps.MapActivity; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class MainActivity extends MapActivity { private static final String defaultTag = "MA"; private static final boolean isDebugModeActivate = true; private static final boolean isClassTagDisplayed = false; private static final boolean isWebModeActivate = false; static public void d(Object thiso, String message) { String tag = defaultTag + (isClassTagDisplayed == true ? "_" + thiso.getClass().getSimpleName() : ""); message = (isClassTagDisplayed == false ? thiso.getClass().getSimpleName() + " : " : "") + message; Log.d(tag, message); } public MainActivity() { counter++; uid++; id = uid; d(this, id + " tst constructor (" + counter + ")"); } private static int counter = 0; private static int uid = 0; private final int id; protected void finalize() throws Throwable { counter--; d(this, id + " tst finalize (" +counter + ") "); super.finalize(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected boolean isRouteDisplayed() { return false; } } Thank you, David A: Perhaps you should exchange notes with NickT here
{ "pile_set_name": "StackExchange" }
Q: Directional slopes. The surface given by $z = x^2 - y^2$ is cut by the plane given by $y = 3x$, producing a curve in the plane. Find the slope of this curve at the point $(1,3,-8)$. In order to solve this problem, I substituted $y$ with $3x$ and get $z = 8x^2$. My understanding of the slope of this curve is $dz\over dx$. However, they want me to use the direction vector of $y=3x$, i.e, $<3,-1,0>$ and take the dot product of this with the gradient evaluated at $(1,3,-8)$. Can someone explain me when to use the former and when to use the latter ? A: $z=-8x^2$ is the projection of the curve to the plane $y=0$. The slope of this projection is in general not the slope of your curve.
{ "pile_set_name": "StackExchange" }
Q: Built in Approval workflow not started on item edit event I have requirement where when a user enter new item in a list first approver approves it then publisher approves it. Once publisher approves it the text will be visible to all. I have used SharePoint built in Approval for that where I have set my workflow to start when new item created and item is changed. When I Add new item workflow triggers and process of approving the item works fine and update the workflow status as completed. But when I edit the same item, Workflow on item changed is not fired. Can any one tell me how to set SharePoint built in workflow to start on new item created as well as item change events. FYI: I have set content approval to "No" in my versioning settings. A: After lots of investigation I found that I have selected checkBox for "After the workflow is completed: Update the approval status (use this workflow to control content approval)". Here I have not selected require content to be approved option for my list and for the same list I was updating approval status once workflow get completed. What I observed is deselecting this option my workflow get fired successfully on new item created and Item change events.
{ "pile_set_name": "StackExchange" }
Q: Creating WIX MSI Dynamically without Candle/Light If I would like to dynamically create an MSI installer, is there a way to do this without including the wix sdk applications such as candle.exe and light.exe? If my application is written in C#, could I reference the Microsoft.Deployment.WindowsInstaller.Package.dll, or some other wix dlls, and create a new MSI file for instance? I basically want to dynamically create an msi file, using a console application, without having to reference the wix console applications. A: If my application is written in C#, could I reference the Microsoft.Deployment.WindowsInstaller.Package.dll, or some other wix dlls, and create a new MSI file for instance? Yes. Those Microsoft.Deployment.* DLLs are referred to as the "Deployment Tools Foundation", and they are documented in dtf.chm and dtfapi.chm files in the doc folder of your wix installation. Creating a new MSI from scratch would start like this: string path = "path/to/myinstaller.msi"; using (var db = new Database(path, DatabaseOpenMode.Create)) { // lots of SQL queries to put stuff in the database here } Alternatively, you could copy an existing template MSI file, and then use SQL queries to modify it. You would also need to package binary files and add them to the database. You can do that by opening the msi with the InstallPackage class. In any case, creating an installer in this way will require detailed knowledge of the Windows Installer Database Tables.
{ "pile_set_name": "StackExchange" }
Q: efrc gives error length-1 array can be converted to python I'm trying to calculate the bit error rate in python with numpy. The code looks like this: EbbyNo = arange(0,16,1) ebno = 10**(EbbyNo/10) BER2 = (3/8)*erfc(cmath.sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) But it's giving me the error: BER2 = (3/8)*erfc(cmath.sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) TypeError: only length-1 arrays can be converted to Python scalars A: cmath does not support numpy arrays: BER2=(3/8)*erfc(sqrt(ebno*(2/5)))+(1/4)*erfc(3*sqrt(2/5*ebno)) You seem to be importing a lot of functions as from foo import * this can really trip you up. Also you are using ints (for example 2/5) instead of floats so the equation above just returns an array of all zero's: >>> 2/5 0 >>> 2./5 0.4 I suggest: >>> import numpy as np >>> import scipy.special as sp >>> EbbyNo=np.arange(0.,16.,1) >>> ebno=10**(EbbyNo/10) >>> BER2=(3./8)*sp.erfc(np.sqrt(ebno*(2./5)))+(1./4)*sp.erfc(3*np.sqrt(2./5*ebno)) >>> BER2 array([ 1.40982603e-01, 1.18997473e-01, 9.77418560e-02, 7.74530603e-02, 5.86237373e-02, 4.18927600e-02, 2.78713278e-02, 1.69667344e-02, 9.24721374e-03, 4.39033609e-03, 1.75415062e-03, 5.64706106e-04, 1.38658689e-04, 2.42337855e-05, 2.76320800e-06, 1.84185551e-07])
{ "pile_set_name": "StackExchange" }
Q: Retrieve asp.net membership security answer This question was discussed many times. Most of them(99.99%) said no way. Asp.net Membership-How to match security answer explicitly? MembershipProvider.GetPassword algorithm How to get security question answer in .net sql membership provider? However there is an answer say yes. http://throughexperience.blogspot.com/2009/06/how-to-retrieve-memberships.html So I am confused. Which one is right? A: The last article clearly states that you can dencrypt password answer only if it is stored as 'Encrypted' or 'Clear'. In other words, it doesn't work if passwords (and password answers) are stored as 'Hashed'. By default, passwordFormat is 'Hashed' unless you explicity mentions it. http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.passwordformat.aspx Note: If your password are stored as 'Encrypted', please make sure you use the same machine key to decrypt it.
{ "pile_set_name": "StackExchange" }
Q: Grails - Bind parameter to command object field of a different name If I have a command object SomeClassCommand with a String field someField but want to bind data from a parameter params.otherField, how do I go about doing that? Is there an annotation I can put in the command object? A: Actually there is a horrendous work around which defies the purpose of auto binding in your case. def map = [:] map.someField = params.otherField //plus set all the other params to map map << params def commandObj = new SomeCommandObj() //Explicitly bind map to command object bindData(commandObj, map) It really is horrendous, because you are doing extra work only to bind data. You could have directly set values to Command Object. I would suggest either to change the command object field name or the parameter field name, which ever is controllable. AFAIK there is no annotation available unless you have your own utility to do such.
{ "pile_set_name": "StackExchange" }
Q: Increase document size in Cloudant I'm storing large amounts of JSON data in Cloudant. I see there is a request limit of 10mb and a document limit of 1mb from the docs I'm needing to raise this limit but have been unsuccessful. I've tried retrieving a AuthSession by calling through curl to the _session endpoint and using the token to send via curl -X PUT "https://cloudanthost.cloudantnosqldb.appdomain.cloud/_node/_local/_config/couchdb/max_document_size" \ -d "4294967296" \ --cookie "AuthSession=NzNmMTAyNTUtNTFiMy00MmFlLTk1MDItMmFmYmY3NjI5MjFmLWJsdWVtaXg6NUNDQ0RCMDc6rVSibzKdb2l2x0LFSQHhA9YmGc0" \ -H "X-CouchDB-WWW-Authenticate: Cookie" \ -H "Content-Type:application/x-www-form-urlencoded" This returns { "error":"forbidden", "reason":"server_admin access is required for this request" } Has anyone has success in increasing these limits or is it blocked? A: Sorry - that’s a hard limit that cannot be changed for good reasons. For optimal use of Cloudant, stick to small documents. Needing larger than the limit documents points to a data model issue, or that Cloudant isn’t a good fit for your use case.
{ "pile_set_name": "StackExchange" }
Q: modify multiple html files with Powershell I need to modify over a thousand html files in a certain directory. I need to remove all the content and replace it with the html below. What would be the best way of doing this? <html xmlns:v="urn:schemas-microsoft-com:vml"> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> Please use the Supplemental Information Browser to view approvad Servie Bulletins </body> </html> A: If all you need to do is overwrite the contents of the files, just copy that HTML into a file in a different directory (for example, into ..\template.html), and then execute for %d in (*.html) do copy /Y ..\template.html %d in the directory in which all of the files you need to overwrite are. You don't even need Powershell to simply overwrite a group of files with exactly the same content.
{ "pile_set_name": "StackExchange" }
Q: Eclipse upgrade juno to kepler. Eclipse wont start Hi i tried to upgrade my eclipse using like this. How to upgrade Eclipse for Java EE Developers? But now my Eclipse start and close. I tried clean start. I don't want to install clean 4.3 because i have to much settings and plugins to migrate. At the moment i am working on clean 4.3 with copied old plugins folder but it sometimes closing automatically when building workspace. I would prefer to resurrect old eclipse because i have to much things to configure and it will take a lot of time to do that. I will try working on new one but i would be glad to resurrect old one. A: If we have eclipse.ini -Xms2048m -Xmx512m Kelpler will crash on start. Juno is working with this settings. But when we have lower eclipse.ini. Eclipse is starting. -Xms512m -Xmx512m The only problem left is to how force Kepler to dont crash -Xms bigger than 512m (I have 8gb of ram) And 512m is to small for me to build workspace :/ EDIT Solution is also increase Xmx to 2048
{ "pile_set_name": "StackExchange" }
Q: Cant change element ID again I have two buttons- one to follow an id by PHP, another to Unfollow. This is my PHP code for that- if(!mysql_num_rows($result)) { echo ' <form method="post" action="includes/follow.php" target="action" id="followform"> <input type="hidden" name="following" value="'. $row['id'].'"></input> <input type="hidden" name="follower" value="'.$info->id.'"></input> <input type="hidden" name="following_name" value="'. $row['username'] .'"></input> <input type="hidden" name="following_img" value="'. $row['u_imgurl'].'"></input> <button class="Follow_button" id="follow" type="submit"><table><tr><td>Follow</td><td> <img src="img/system/plus.png" width="20px"></td></tr></table></button> </form>'; } else { echo ' <form method="post" action="includes/unfollow.php" target="action" id="unfollowform"> <input type="hidden" name="following" value="'. $row['id'].'"></input> <input type="hidden" name="follower" value="'.$info->id.'"></input> <input type="hidden" name="following_name" value="'. $row['username'] .'"></input> <input type="hidden" name="following_img" value="'. $row['u_imgurl'].'"></input> <button class="Follow_button" id="unfollow" type="submit"><table><tr><td>UnFollow</td><td> <img src="img/system/cross.png" width="20px"></td></tr></table></button> </form>'; } The forms update the back end through an iframe. My problem was to change the buttons from Follow to Unfollow and Vice Versa. I made a script- <script> $('#follow').click(function(e){ setTimeout(function () { $('form#followform').attr('action', 'includes/unfollow.php'); $("#follow").html("<table><tr><td>UnFollow</td><td> <img src='img/system/cross.png' width='20px'></td></tr></table>"); $('button#follow').attr('id', 'unfollow'); }, 50); }); $('#unfollow').click(function(e){ setTimeout(function () { $('form#unfollowform').attr('action', 'includes/follow.php'); $("#unfollow").html("<table><tr><td>Follow</td><td> <img src='img/system/plus.png' width='20px'></td></tr></table>"); $('button#unfollow').attr('id', 'follow'); }, 50); }); </script> This serves my purpose, but here is the real problem- When I click on the button once, it gives out desired appearance, but when I again click it, it does not identify the new id, thus does not change it. The problem lies with the JQuery i suppose. Can someone help me? Thanks in advance. A: The click() event will only be triggered with elements that are created already. The element that the 'unfollow' id is referring to does not exist when you bind it. Try using the event on() $(document).on('click','#follow',function(e){ your code}); $(document).on('click','#unfollow',function(e){ your code});
{ "pile_set_name": "StackExchange" }
Q: Google Maps : Fragment and Layout inflator error I get the following error stating that the class definition was not found. I do not understand this error and do not even know how this error is generating. I'm sharing my layout and activity here Map Activity: public class Maps extends FragmentActivity { private GoogleMap myMap; LocationManager lm; LocationListener locationListener; Location mLoc; int code; boolean zoomb = true; ArrayList<String> ambulances = new ArrayList<String>(); boolean directioncheck = false; ListView listview; ArrayList<String> itemlist = new ArrayList<String>(); ArrayAdapter<String> adapter; ArrayList<Marker> markerlist; Direction direction = new Direction(); ArrayList<LatLng> pline = new ArrayList<LatLng>(); LatLng currentmarker; Integer cid; String provider = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); /* * Check if any of the radios (Mobile Data or Wi-Fi) are on. */ final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if(telephonyManager.getDataState() == 0 && wifiManager.isWifiEnabled() == false && manager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) { AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this); ad.setTitle("First-Responder"); ad.setMessage("Your network and gps providers are off. Please enable one of them."); ad.setPositiveButton("Network", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub AlertDialog.Builder network = new AlertDialog.Builder(Maps.this); network.setTitle("First-Responder"); network.setMessage("Please choose between Wi-Fi and Mobile Data"); network.setPositiveButton("Wi-Fi", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS); startActivity(intent); provider = "network"; } }); network.setNegativeButton("Mobile Data", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent (android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS); startActivity(intent); provider = "network"; } }); network.show(); } }); ad.setNegativeButton("GPS", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); provider = "gps"; } }); ad.show(); } if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) { provider = "network"; } else if (wifiManager.isWifiEnabled()) { provider = "network"; } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { provider = "gps"; } listview = (ListView)findViewById(R.id.listView); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist); listview.setAdapter(adapter); markerlist = new ArrayList<Marker>(); FragmentManager myFragmentManager = getSupportFragmentManager(); SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map); myMap = mySupportMapFragment.getMap(); myMap.setMyLocationEnabled(true); myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new MyLocationListener(); Intent intent = getIntent(); code = intent.getIntExtra("key", 0); if (provider != null) { mLoc = lm.getLastKnownLocation(provider); } if (mLoc != null) { query(mLoc); } listview.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getApplicationContext(), Integer.toString(markerlist.size()), Toast.LENGTH_LONG).show(); LatLng point = markerlist.get(position).getPosition(); CameraUpdate center = CameraUpdateFactory.newLatLng(point); myMap.animateCamera(center, 2000, null); } }); myMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { @Override public void onInfoWindowClick(final Marker marker) { // TODO Auto-generated method stub AlertDialog.Builder ad = new AlertDialog.Builder(Maps.this); ad.setTitle("First-Responder"); ad.setMessage("Would you like directions?"); ad.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int arg1) { myMap.clear(); query(mLoc); currentmarker = marker.getPosition(); LatLng pt = marker.getPosition(); direction.getmapsinfo(myMap, pt, mLoc, itemlist, adapter); listview.setClickable(false); } }); ad.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub //ok, do nothing dialog.cancel(); } }); ad.show(); } }); } public void query(Location loc) { switch (code) { case 1: new GetHospitals() .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.toString(mLoc.getLatitude()) + "," + Double.toString(mLoc.getLongitude()) + "&rankby=distance&types=hospital&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ"); break; case 2: new GetHospitals() .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.toString(mLoc.getLatitude()) + "," + Double.toString(mLoc.getLongitude()) + "&rankby=distance&types=police&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ"); break; case 3: new GetHospitals() .execute("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + Double.toString(mLoc.getLatitude()) + "," + Double.toString(mLoc.getLongitude()) + "&rankby=distance&types=fire_station&sensor=false&key=AIzaSyAPrOxAoTKUdaXtktg4B2QrdPZO5SpM0VQ"); break; case 4: Database db = new Database(Maps.this); LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude()); ambulances = db.sort(point); placemarkers(ambulances); db.close(); break; } } /** * Assigns a number according to distance the nearest ambulance. * @param ambulances */ private void placemarkers(ArrayList<String> ambulances){ Bitmap myWrittenBitmap; for(int i = 0; i < ambulances.size(); i++){ String item = ambulances.get(i); Marker m; myWrittenBitmap = customImage(i+1, R.drawable.ambulance_launcher); String[] values = item.split(","); String name = values[0]; String number = values[1]; String itemlat = values[2]; String itemlong = values[3]; LatLng point = new LatLng(Double.parseDouble(itemlat), Double.parseDouble(itemlong)); m = myMap.addMarker(new MarkerOptions().position(point).title(name).snippet(number).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap))); markerlist.add(m); if(!directioncheck){ itemlist.add(Integer.toString(i+1)+" "+ name); adapter.notifyDataSetChanged(); } } LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude()); CameraUpdate center = CameraUpdateFactory.newLatLng(point); CameraUpdate zoom = CameraUpdateFactory.zoomTo(12); myMap.moveCamera(center); myMap.animateCamera(zoom); } // adding custom images to markers. private Bitmap customImage(int index, int resource ){ Bitmap bm; Bitmap myWrittenBitmap; Canvas canvas; Paint txtPaint; bm = BitmapFactory.decodeResource(getResources(), resource); myWrittenBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_4444); // create a Canvas on which to draw and a Paint to write text. canvas = new Canvas(myWrittenBitmap); txtPaint = new Paint(); txtPaint.setColor(Color.RED); txtPaint.setTextSize(12); txtPaint.setFlags(Paint.ANTI_ALIAS_FLAG); txtPaint.setTypeface(Typeface.DEFAULT_BOLD); //draw ref bitmap then text on our canvas canvas.drawBitmap(bm, 0, 0, null); canvas.drawText(Integer.toString(index), 10,10 , txtPaint); return myWrittenBitmap; } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { if (loc != null) { mLoc = new Location(loc); //query(mLoc); } } @Override public void onProviderDisabled(String provider) { Context context = Maps.this; AlertDialog.Builder ad = new AlertDialog.Builder(context); ad.setTitle("Warning!"); ad.setMessage("Provider: " + provider + " disabled"); if(provider.equals("network")) { String button1String = "Enable network"; ad.setPositiveButton(button1String, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); } ad.show(); } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.maps, menu); return true; } public String readConnectionString(String URL) { StringBuilder stringBuilder = new StringBuilder(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(URL); try { HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } inputStream.close(); } else { Log.d("ConnectionString", "Failed to connect"); } } catch (Exception e) { Log.d("ConnectionString", e.getLocalizedMessage()); } return stringBuilder.toString(); } private class GetHospitals extends AsyncTask<String, Void, String> { protected String doInBackground(String... urls) { return readConnectionString(urls[0]); } protected void onPostExecute(String JSONString) { try { JSONObject jsonObject = new JSONObject(JSONString); JSONArray EmergencyItems = new JSONArray( jsonObject.getString("results")); for (int i = 0; i < EmergencyItems.length(); i++) { JSONObject EmergencyItem = EmergencyItems.getJSONObject(i); Double lat = Double.parseDouble(EmergencyItem .getJSONObject("geometry") .getJSONObject("location").getString("lat")); Double lng = Double.parseDouble(EmergencyItem .getJSONObject("geometry") .getJSONObject("location").getString("lng")); LatLng point = new LatLng(lat,lng); Bitmap myWrittenBitmap; Marker m; switch (code) { case 1: myWrittenBitmap = customImage(i+1, R.drawable.hsp_launcher); m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap))); if(directioncheck == false){ itemlist.add(Integer.toString(i+1)+" "+ EmergencyItem.getString("name")); adapter.notifyDataSetChanged(); } markerlist.add(m); break; case 2: myWrittenBitmap = customImage(i+1, R.drawable.pol_launcher); m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap))); if(directioncheck == false){ itemlist.add(Integer.toString(i+1)+" "+ EmergencyItem.getString("name")); adapter.notifyDataSetChanged(); } markerlist.add(m); break; case 3: myWrittenBitmap = customImage(i+1, R.drawable.fire_launcher); m = myMap.addMarker(new MarkerOptions().position(point).title(EmergencyItem.getString("name")).snippet(EmergencyItem.getString("vicinity")).icon(BitmapDescriptorFactory.fromBitmap(myWrittenBitmap))); if(directioncheck == false){ itemlist.add(Integer.toString(i+1)+" "+ EmergencyItem.getString("name")); adapter.notifyDataSetChanged(); } markerlist.add(m); break; } } if(zoomb) { LatLng point = new LatLng(mLoc.getLatitude(), mLoc.getLongitude()); CameraUpdate center = CameraUpdateFactory.newLatLng(point); CameraUpdate zoom = CameraUpdateFactory.zoomTo(12); myMap.moveCamera(center); myMap.animateCamera(zoom); zoomb=false; } } catch (Exception e) { Log.d("EmergencyItem", e.getLocalizedMessage()); } } } /** used upon resuming the application. * */ @Override public void onResume(){ super.onResume(); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); Log.v(null, "Maps's onResume Method !!!"); } /** * Android onPause method. Clears any stored location in location manager. */ @Override public void onPause(){ super.onPause(); lm.removeUpdates(locationListener); zoomb = true; Log.v(null, "Maps's onPause Method !!!"); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(direction.getDirections() != null){ Log.v("!NullDirection", "!NULL"); outState.putStringArrayList("DIRECTIONS", direction.getDirections()); Preferences.writeLatLng(this, Preferences.MLAT, currentmarker); } else { Log.v("NullDirection", "NULL"); } } /** * */ @Override protected void onRestoreInstanceState(Bundle inputState){ Log.v("INRESTORE", "onRestoreInstanceState"); if(inputState != null){ if(inputState.containsKey("DIRECTIONS")){ itemlist.clear(); //adapter.clear(); adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,itemlist); ArrayList<String> tempitemlist = inputState.getStringArrayList("DIRECTIONS"); Log.v("FIRST DIRECTION", Integer.toString(itemlist.size())); for(int i = 0; i < tempitemlist.size(); i++){ itemlist.add(tempitemlist.get(i)); adapter.notifyDataSetChanged(); } directioncheck = true; } if(Preferences.readMarker(this, Preferences.MLAT) != null){ LatLng pts = Preferences.readMarker(this, Preferences.MLAT); currentmarker = pts; direction.getmapsinfo(myMap, pts, mLoc, itemlist, adapter); } } } } Layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fare_check_frame" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="316dp" class="com.google.android.gms.maps.SupportMapFragment" /> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> LOgcat: 04-26 17:31:48.426: W/ActivityThread(338): Application emergency.contact is waiting for the debugger on port 8100... 04-26 17:31:48.445: I/System.out(338): Sending WAIT chunk 04-26 17:31:48.465: I/dalvikvm(338): Debugger is active 04-26 17:31:48.645: I/System.out(338): Debugger has connected 04-26 17:31:48.645: I/System.out(338): waiting for debugger to settle... 04-26 17:31:48.845: I/System.out(338): waiting for debugger to settle... 04-26 17:31:49.045: I/System.out(338): waiting for debugger to settle... 04-26 17:31:49.245: I/System.out(338): waiting for debugger to settle... 04-26 17:31:49.455: I/System.out(338): waiting for debugger to settle... 04-26 17:31:49.655: I/System.out(338): waiting for debugger to settle... 04-26 17:31:49.855: I/System.out(338): waiting for debugger to settle... 04-26 17:31:50.055: I/System.out(338): waiting for debugger to settle... 04-26 17:31:50.261: I/System.out(338): waiting for debugger to settle... 04-26 17:31:50.462: I/System.out(338): waiting for debugger to settle... 04-26 17:31:50.664: I/System.out(338): waiting for debugger to settle... 04-26 17:31:50.865: I/System.out(338): debugger has settled (1490) 04-26 17:31:51.655: V/(338): MainActivity's onResume Method !!! 04-26 17:31:56.235: V/(338): MainActivity's onPause Method !!! 04-26 17:31:59.945: W/dalvikvm(338): VFY: unable to resolve static field 863 (MapAttrs) in Lcom/google/android/gms/R$styleable; 04-26 17:31:59.945: D/dalvikvm(338): VFY: replacing opcode 0x62 at 0x000e 04-26 17:31:59.955: D/dalvikvm(338): VFY: dead code 0x0010-00ae in Lcom/google/android/gms/maps/GoogleMapOptions;.createFromAttributes (Landroid/content/Context;Landroid/util/AttributeSet;)Lcom/google/android/gms/maps/GoogleMapOptions; 04-26 17:32:32.257: D/AndroidRuntime(338): Shutting down VM 04-26 17:32:32.257: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560) 04-26 17:32:32.355: E/AndroidRuntime(338): FATAL EXCEPTION: main 04-26 17:32:32.355: E/AndroidRuntime(338): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable 04-26 17:32:32.355: E/AndroidRuntime(338): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source) 04-26 17:32:32.355: E/AndroidRuntime(338): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 04-26 17:32:32.355: E/AndroidRuntime(338): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.Activity.setContentView(Activity.java:1657) 04-26 17:32:32.355: E/AndroidRuntime(338): at emergency.contact.Maps.onCreate(Maps.java:84) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:99) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123) 04-26 17:32:32.355: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683) 04-26 17:32:32.355: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method) 04-26 17:32:32.355: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507) 04-26 17:32:32.355: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 04-26 17:32:32.355: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 04-26 17:32:32.355: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method) 04-26 17:33:21.955: I/Process(338): Sending signal. PID: 338 SIG: 9 04-26 17:34:35.256: W/ActivityThread(367): Application emergency.contact is waiting for the debugger on port 8100... 04-26 17:34:35.265: I/System.out(367): Sending WAIT chunk 04-26 17:34:35.285: I/dalvikvm(367): Debugger is active 04-26 17:34:35.475: I/System.out(367): Debugger has connected 04-26 17:34:35.475: I/System.out(367): waiting for debugger to settle... 04-26 17:34:35.675: I/System.out(367): waiting for debugger to settle... 04-26 17:34:35.875: I/System.out(367): waiting for debugger to settle... 04-26 17:34:36.075: I/System.out(367): waiting for debugger to settle... 04-26 17:34:36.285: I/System.out(367): waiting for debugger to settle... 04-26 17:34:36.496: I/System.out(367): waiting for debugger to settle... 04-26 17:34:36.705: I/System.out(367): waiting for debugger to settle... 04-26 17:34:36.905: I/System.out(367): waiting for debugger to settle... 04-26 17:34:37.105: I/System.out(367): waiting for debugger to settle... 04-26 17:34:37.305: I/System.out(367): debugger has settled (1496) 04-26 17:34:38.215: V/(367): MainActivity's onResume Method !!! 04-26 17:34:41.395: V/(367): MainActivity's onPause Method !!! 04-26 17:34:41.546: W/dalvikvm(367): VFY: unable to resolve static field 863 (MapAttrs) in Lcom/google/android/gms/R$styleable; 04-26 17:34:41.546: D/dalvikvm(367): VFY: replacing opcode 0x62 at 0x000e 04-26 17:34:41.546: D/dalvikvm(367): VFY: dead code 0x0010-00ae in Lcom/google/android/gms/maps/GoogleMapOptions;.createFromAttributes (Landroid/content/Context;Landroid/util/AttributeSet;)Lcom/google/android/gms/maps/GoogleMapOptions; 04-26 17:34:53.168: D/AndroidRuntime(367): Shutting down VM 04-26 17:34:53.168: W/dalvikvm(367): threadid=1: thread exiting with uncaught exception (group=0x40015560) 04-26 17:34:53.265: E/AndroidRuntime(367): FATAL EXCEPTION: main 04-26 17:34:53.265: E/AndroidRuntime(367): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable 04-26 17:34:53.265: E/AndroidRuntime(367): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source) 04-26 17:34:53.265: E/AndroidRuntime(367): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 04-26 17:34:53.265: E/AndroidRuntime(367): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.Activity.setContentView(Activity.java:1657) 04-26 17:34:53.265: E/AndroidRuntime(367): at emergency.contact.Maps.onCreate(Maps.java:84) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.os.Handler.dispatchMessage(Handler.java:99) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.os.Looper.loop(Looper.java:123) 04-26 17:34:53.265: E/AndroidRuntime(367): at android.app.ActivityThread.main(ActivityThread.java:3683) 04-26 17:34:53.265: E/AndroidRuntime(367): at java.lang.reflect.Method.invokeNative(Native Method) 04-26 17:34:53.265: E/AndroidRuntime(367): at java.lang.reflect.Method.invoke(Method.java:507) 04-26 17:34:53.265: E/AndroidRuntime(367): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 04-26 17:34:53.265: E/AndroidRuntime(367): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 04-26 17:34:53.265: E/AndroidRuntime(367): at dalvik.system.NativeStart.main(Native Method) EDIT: had to set the target Api to google api. A: Did you import the google library correctly? It seems like it can't see its own resources.
{ "pile_set_name": "StackExchange" }
Q: Hasse Invariant of an Elliptic Curve Is there a general method to calculate the Hasse Invariant for any elliptic curve over any finite field? I have read about the Hasse Invariant on page 140 in 'The Arithmetic of Elliptic Curves' but I would like some more explanation. Thanks A: Yes, there is. In a word, if your curve is $y^2=x^3+ax^2+bx+c=f(x)$, then you look at the coefficient of $x^{p-1}$ in $f^{(p-1)/2}$. That’s the Hasse invariant, and it’s actually there in Th. 4.1(a) on p. 140. It seems to me that there’s a shorter proof of this single fact — if you’re interested, let me know in a comment, or e-mail me.
{ "pile_set_name": "StackExchange" }
Q: FTPClient's isAvailable and is Connected return true but storeFileStream returns null I'm uploading lots of files (about 2000) using Commons-net FTPClient. I'm checking connection before each upload using isAvailable() & isConnected() methods and reconnect if connection closed. after uploading some files (variable) storeFileStream returns null (that means "data connection cannot be opened" as javadoc) while isAvailable() & isConnected() both are true !! What is the problem? How can I check data connection availability? Thanks A: How can I check data connection availability? Try to use it. There is no 'dial tone' in TCP, so methods with names like isConnected() can't do anything more than tell you (1) whether you have ever connected, and, if you're lucky, (2) whether you have subsequently closed the connection or encountered an I/O error on it. I'm not familiar with the API you mention but the isConnected() methods of the JDK classes don't do anything beyond (1).
{ "pile_set_name": "StackExchange" }
Q: How to prevent log output from Apache Commons Exec I am using Apache Commons Exec on a web application in JBoss 4.2.3. Whenever I call Apache Exec it outputs all the console output in the log and this is a lot of output and it could easily fill in my logs in a production environment. How can I prevent this log from printing and only show error logs? Regards A: In your log4j.properties file for your web app add a line that looks something like this following... log4j.logger.org.apache.commons.exec=ERROR A: You can also disable the stdout/stderr/stdin streams from the process by supplying it null streams. This way you don't need to fiddle with the logging levels if you really have no use for the output. executor.setStreamHandler(new PumpStreamHandler(null, null, null));
{ "pile_set_name": "StackExchange" }
Q: What are the big differences among the D&D editions? I've been out of the loop for a while, and I used to play AD&D 2nd ed, but today I find there are a lot of different versions that have fairly different gameplay. Can anyone summarize the really big differences, the ones (maybe top three?) that are the 'killer features' of the different editions? What makes each edition play differently than the others? A: OD&D (1974) - The original game had only three classes (Cleric, Fighter, Magic User). Cleric spells up to 5th level, Magic user spells up to 6th level. Every attack except for certain monster abilities did 1d6 damage if it hit. There wasn't a lot of difference between characters in terms of combat capabilities. Characteristics didn't have many modifiers. OD&D plus Greyhawk Supplement (1975) - The Greyhawk supplement transformed OD&D into a form of older edition D&D that is recognizable by most gamers today. Characteristics have more modifiers and exceptional strength was introduced. Variable damage dice for different weapons and creatures was introduced. The number of spell levels increased. Holmes Edition, B/X D&D, Mentzer D&D (1977, 1981, 1983) - Similar to OD&D plus Greyhawk including selected elements from other supplements, with the rules rewritten for clarity and organization. Playing a Race meant playing a class. For example a Dwarf used only the Dwarf Class. Both B/X and Mentzer were divided in distinct books that focused on a specific range of levels. Later the Mentzer version was combined into the Rules Compendium. The biggest difference between these rules and AD&D was found in higher level play. Mentzer D&D had specific rules for running domain, mass combat, and even becoming a immortal i.e. god. AD&D 1st Edition (1977) - OD&D plus Supplements plus Strategic Review articles are combined, rewritten, and organized into a three book set. One of the reason behind this edition was to standardize how D&D was played to make running tournaments easier. The most popular version of older edition D&D. Bonuses for characteristics roughly go up to +4 and are capped at 18 except for exceptional strength. A lot of extra details are added in Gygax's distinctive writing style. Some sections are poorly designed or understood like the unarmed combat rules, initiative, psionics, human dual classing, etc. While other are widely adopted, classes, races, spells, magic items, etc. Characters select a race and a class. Non-human race can multi class which involves splitting experience between multiple classes. Non-humans were generally limited to a max level (often low). AD&D 1st Edition plus Unearthed Arcana (1985) - This version shifted the power level of the game upwards by allowing increased level limits for non-human, new classes that were slightly more powerful, and weapon specialization for fighters. Later AD&D hardback books (the two Survival books) expanded the use of non-weapon proficiencies as a skill system. AD&D 2nd Edition (1989) - Still basically AD&D 1st Edition but the rules have been reorganized and rewritten for clarity. Some content like half-orc, demons, and assassins were removed or changed due to media pressure. Character customization was expanded by using non-weapon proficiencies as a skill system and by allowing characters to take kits that confer various benefits. Combat has been redesigned to overcome the issues with initiative and unarmed combat that were part of the previous edition of AD&D. Because of the success of Dragonlance, much of AD&D 2nd Edition run was focused on customizing the rules for specific settings or themes. TSR released a lot of different settings like Dark Sun, Birthright, and others. AD&D 2nd Edition Skills and Powers (1995) - Player's Option: Skill and Powers introduced several rule systems that allowed extensive customization of a character. D&D 3rd Edition (2000) - The first edition created by Wizards of the Coast, 3rd Edition took the idea of Skill and Powers and developed a cleaner system for customizing characters by designing the classes so a level of one class can stack on top of another class. A single level chart was introduced and a each level a character could take a new class or add another level of a class they already had. In addition feats were added to allow characters to further customize their abilities. A true skill system was introduced and integrated into the game. The underlying d20 system worked by rolling equal to or higher than a target number and adding various bonus. This was used across the game in a standard way. Problems developed at higher levels as the number of options increased to the point where players had a tough time resolving their actions. In addition, when various supplements were combined, characters could be built that were considerably more powerful than other combinations. This version was also noted for releasing the d20 system under the Open Game License, which ignited a vigorous third party market. D&D 3.5 Edition(2003) - This edition featured only small changes to the core game (and was mostly-but-not-entirely compatible with books written for 3rd Edition), but had its own extensive line of supplements which magnified the role of feats, prestige classes, and multiclassing in character customization. This version of D&D is still the baseline for many D20 games some still in print and active development. Notably the Pathfinder 1st edition game by Paizo is based on the System Reference Document for D&D 3.5. D&D 4th Edition (2008) - This edition is a completely new game with only a few game mechanics carried over from the 3rd Edition. It has a simple set of core rules and defines all character and monster abilities as exceptions which are described in standard terms. Higher level combat has been simplified, and each class has been designed to have a specific role in combat. Every class has a diverse set of combat options to use. The use of a battlegrid and miniatures is part of the core rules. Classes and monster generally have a high fantasy flavor. There are multiple ways to heal centered on a new mechanic called healing surges. Combat takes noticeably longer than any prior edition except perhaps for high level 3rd edition combat. While not present at the game's launch, this edition is noted for popular use of on-line computer tools, particularly an online character builder that integrates content from all the supplements. Wizards of the Coast originally intended to create a "virtual tabletop" as well, but the project was never completed. D&D Essentials (2010) - This was an alternative set of core books for 4th Edition, with simplified classes intended for first-time players. Essentials was designed to be cross-compatible with 4th Edition, with different versions of the classes usable side-by-side. D&D 5th edition (2014) - This is the current edition of D&D. This edition is being released when the market leader is not the previous edition of D&D but rather a rival product made by Paizo called Pathfinder. Unlike D&D 4th edition this edition draws on much of the mechanics introduced in classic D&D (OD&D to AD&D 2nd Edition) and D&D 3rd Edition. It allows for more character customization than classic D&D but less than 3rd edition. The distinct features of D&D 5th edition are flexibility and bounded accuracy. D&D 5e has a simple core along with several options that allows referee to make their game feel more like a particular past edition. Options include allowing feats (3e), tactical combat (3e & 4e), multi-classing (3e), and backgrounds (2e). Bounded Accuracy is the most distinct feature of D&D 5e. As stated in this article the d20 rolls to see if the character hits or succeeds in a task have been changed to an absolute scale where the difference between the highest level and the lowest is drastically reduced compared to previous editions. In its place, higher levels characters and creature have more hit points, more options for completing tasks, and increased damage along with more ways of doing damage. An immediate consequence is that the difficulty of the to hit roll or the task is not expected to increase as the character levels. A: Trying for a "short and sweet" summary here. Wikipedia has a lot of detail on this topic. OD&D/BD&D (original "white box" D&D, BECMI, Rules Cyclopedia) Fairly simple rules, designed for the GM to fill in all kinds of situations via "rulings" in play. Small sets of classes with little mechanical customization. Gameplay varies, but the general reputation is a "Fafhrd and the Gray Mouser" aesthetic: trying to acquire treasure through cleverness. (Not exclusively so: BECMI has rules for godlike characters, for instance.) Inspiration for a number of "retroclones" and OSR (Old School Renaissance) games. AD&D (Advanced Dungeons & Dragons, AD&D 2nd Edition; note that these exist concurrently with BD&D) D&D attempts to go a bit broader and deeper, particularly with more rules that address the setting outside the dungeon (they're kind of a patchwork, in my opinion). A variety of character classes (especially if you count class kits). Slow shift towards "high-fantasy" style, with epic quests and powerful characters. Numerous published settings, some of which include their own mechanical add-ons and customizations. D&D3.x (3rd Edition, 3.5 Edition; Pathfinder and other third-party D20 games) More uniform mechanics compared to its predecessors, with established specific rules for a lot of stuff that OD&D might just leave open to the group, including rules that rely on discrete positioning in combat (i.e. a grid). Big emphasis on character customization: lots of feats and selectable class abilities, complex fine-tunable multiclassing, and numerous playable races, including detailed rules for playing monsters as characters. More focus on explicit balance than its predecessors, e.g. with "wealth by level" guidelines; multiplicity of options still tends to supersede balance, however. High-powered "epic fantasy" feel, particularly at higher levels. Basis of a number of D20 games, some of which resemble D&D3.x closely while others only use the basic resolution mechanic. D&D4 (4th Edition, Essentials) Big emphasis on tactical choice: the game is designed around grid-based combat with lots of abilities that don't just deal damage but move enemies around, apply conditions, &c. Character customization through a variety of classes and lots of selectable abilities for each class. Classes are designed to fill explicit party roles, and balanced based on a unified resource model. Probably the most focused edition, and the one most willing to kill off "sacred cows" if they conflict with the overall design goals. "Action-fantasy" feel, fairly consistent across all levels. D&D5 (5th Edition, still being released) Big emphasis on the six ability scores above all else. Has an ethos of rulings not rules, and rule modularity. An increased focus on non-mechanical backgrounds and personalities, and "feel" rather than "legalism." Unique mechanics and concepts include, Bounded Accuracy, Advantage/Disadvantage, Inspiration, and Class Path subclass system. A: Part of the initial editions had to do with the fact that Gary Gygax (creator) had studied anthropology so a lot of it ended up boiling down to certain social strata, gritty realism (despite all the magic), and (let's face it) Tolkien derived setting with a rather broad scale of difficulty. 3rd Edition was released as an easy edition to learn, and 4th edition dropped a lot of the pretenses about the game's relation to social skills and became more focused on cinematic style combat. (Most of my gaming group refers to D&D 4e as "Table WoW") Is there a specific element you want to read/run/whatever? There's a quote hanging on the internets stating more or less, "1st ed tested players, while 4E tests characters." I would have to agree with that statement. 1st, 2nd, AD&D (and all other permutation in that "generation") relied heavily on player intelligence, even when playing the oft low charisma "Meat Shield/Tank" which is why I said 'gritty realism'. There was no weapon scaling, and even different damages for weapons against different sized targets (such as a five foot blade having more it can cut through on a giant than a man). I found the system only as forgiving as the DM since despite the strong urging to min/max there were still plenty of caps in effect. Contrariwise, the 3rd, 3.5, and 4th editions (and other permutations in the "modern generation") were more concerned with ease of play and less chart checking. What this led to is/was the tendency that even though the game tried to make a more open forum, and one a lot more forgiving to multi-classing, it lent far too much into the realm of specializing. Starting at roughly level 6 or 7, if you weren't dedicated to a few select things your character could do, you would become lost compared to anything at an equal "challenge rating". One thing that 4e did that I preferred over 3(.5)e was the ability to later swap out powers, enabling a player to realize that something they selected became irrelevant or maybe just less fun. However, this also enables the exponential power gaps to continue for a character that tries to be balanced.
{ "pile_set_name": "StackExchange" }
Q: Sprintf floating a 18,16 float with right padding zeros I'm trying to get float (18,16) with padding zeros to the right, but this isn't working because it always ends with a 1 instead of a zero. My guess it's because I've specified it wrong but I'm not sure how to do it correct. Sample: 12.12234 must become 12.122340000000000 and 1.01 must become 1.01000000000000. To achieve this I'm using sprintf('%18.016f', $fMyFloat); but this always ends with a 1 instead of a 0. Obviously I'm overseeing something, I just don't know what. Any help is greatly appreciated. A: This test code: $data = array( 12.12234, 1.01 ); foreach($data as $fMyFloat){ echo sprintf('%18.016f', $fMyFloat) . PHP_EOL; } ... prints this in my 64-bit computer: 12.1223399999999994 1.0100000000000000 You are facing the well-known problem of floating point precision. Converting integers from base 10 to base 2 is pretty straightforward (and exact) but base 10 floating point numbers cannot always be represented exactly in base 2. This issue isn't specific to PHP but there's a warning in the PHP manual: Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision Your only chance to achieve such precision is to manipulate numbers as strings. PHP bundles two arbitrary precision libraries that can help you when you need to do match with strings: GNU Multiple Precision and BC Math. Here's a little hack with bcmath: $data = array( '12.12234', '1.01' ); bcscale(16); foreach($data as $fMyFloat){ echo bcdiv($fMyFloat, 1) . PHP_EOL; } It this case, though, you can probably use simple string functions: $data = array( '12.12234', '1.01' ); foreach($data as $fMyFloat){ list($a, $b) = explode('.', $fMyFloat); echo $a . '.' . str_pad($b, 16, 0) . PHP_EOL; }
{ "pile_set_name": "StackExchange" }
Q: property binding in caliburn micro I have an image on a view and I want to create a property on ViewModel which I can bind into it. The problem is that I don’t know what type of object should I create on ViewModel. I can create a text object. I want to be able to do these: Set the source property of image ( an image from application resource) can change and resize the image during run time. set the image source to an image from hard disk. Should I create only one object on ViewModel or can I create several objects and each of them bind to one parameter of image control? A: Create a property to each of distinct data, and bound to it. It can be either primitive types like string or int, or it can be a custom class that wrap those values. If you choose that letter option, that you also need to make sure to bind to the correct property on the custom object that you've created.
{ "pile_set_name": "StackExchange" }
Q: Vector Layer group by properties I brought in a vector shapefile with around a total of 20 different pressures. I want to make this vector into two different shapefiles. One for the property "Pressure" of lines that have under 20 pressure and another for the same property that has a pressure of 20 and over. I know of the Vector > Split Vector Layer command but that splits the one shapefile into 20 different ones. A: I would probably do the following: Use the Field Calculator to create a new field and then use an expression like: if( "Pressure" < 20, 0, 1 ) This will add a '0' to all features with a pressure value less than 20, otherwise will it will add a '1'. Run the Vector > Data Management Tools > Split Vector Layer tool and select the new field to produce two shapefiles. A: Select all the lines with a pressure < 20 and then save it to a new file making sure to check save only selected features. Then invert the selection (look in the selection expression menu) and then save again.
{ "pile_set_name": "StackExchange" }
Q: Cannot get session value In the header ( header.phtml ) I start the session : <?php if (session_status() == PHP_SESSION_NONE) session_start(); ?> <!DOCTYPE html> <html> <head> ... Now in other page I want to set a session value : <script type="text/javascript"> $(document).ready(function() { $("#add_reservS").on("click", function(e) { <?php $_SESSION['nb_ajout_client'] = 0; ?> }); ... Then I increment this session value in other page : public function ajouterExecAction($src = '', $pk_src = ''){ $client = new Client(); $client->ajouter($_POST); if ($src == '') $this->response->redirect('ReferentielClient'); else { $_SESSION['nb_ajout_client']++; ... } ... } Now inside another page I want to get this session value : <script type="text/javascript"> $(document).ready(function() { $("#btn_retour").on("click", function() { var back = "<?php echo $previous; ?>"; if (back == "list_reserv") window.history.back(); else { var nb_back = "<?php echo $_SESSION['nb_ajout_client']; ?>"; alert("session nb ajout client = "+nb_back); // nb_back is blank ! } }); }); </script> The alert show a blank value ! So what is wrong in my approach ? A: You must start each document with session_start();. While it is no longer required to be the very first line, it does need to be present before you do anything with a session in the file. It is common to start the session from a common include file which is then included in every page which needs the session. Thus you only need to write it once.
{ "pile_set_name": "StackExchange" }
Q: Problem in the flow of custom back button when using UIView controller I am new to iphone development.I have created a button in UIView controller.On clicking the button it navigates to a another UITableView controller .On clicking the row of the table leads to another UIView controller which has also another table in it.On clicking the row of this table leads to another UIWebView.I have created a custom back button placed on the navigation bar of the UIView controllers and UIWebview.On clicking on the back button just leads me to the main page with a button and not to its just previous UIView. -(IBAction) goemenbutton : (id) sender { [self.view removeFromSuperview]; } The above method is used for all the custom back button.Please help me out to get the correct flow for the back button.Thanks. A: You should probably look at using UINavigationController instead of interchanging several views within one UIViewController. The UINavigationController takes care of a lot of things for you, including back buttons with proper titles and nice animations. It also helps you structure your code and gives you more flexibility down the road. A UIWebview is not a UIViewController and can not be pushed onto the NavigationController. You should probably look at wrapping it into a UIViewController.
{ "pile_set_name": "StackExchange" }
Q: Are lethal injections painless? It is often claimed that lethal injections are a painless and humane method of applying the death penalty. Do lethal injections result in either no, or minimal, pain? A: The killing is done in several steps. First, the convicted are given a high dose of barbiturates (about 10-15 times the normal dose), which causes them to fall unconscious within a few seconds. Then pancuronium, and finally a massive overdose of potassium chloride are injected. The former is similar to curare (indio arrow poison) in that it paralyzes muscles (thus causing apnea). If the person was not already unconscious at that time, this would be very inconvenient (not strictly painful, but nevertheless really really uncomfortable). The latter (potassium chloride) is actually harmless, but in this massive overdose causes a cardiac arrest and convulsions. Which, again, would be very painful, if the person was not already unconscious, and under pancuronium. So, in short, yes. Painless.
{ "pile_set_name": "StackExchange" }
Q: In John 8:44, what is the accurate translation of "πατὴρ αὐτοῦ", and what does the phrase mean? In John 8:44 the last phrase has some ambiguity. It talks about Devil, that he is liar and the father of: it...KJV. thereof...ASV. lies...ESV and GNB. الكذاب...سميث/فاندايك، الكذاب=the liar. الكذب... الحياة، الأخبار السارة، اليسوعية. الكذب=the lying. This is the phrase in GNT: "πατὴρ αὐτοῦ." John 8:44 (KJV); Ye are of {cf15I your} father the devil, and the lusts of your father ye will do. He was a murderer from the beginning, and abode not in the truth, because there is no truth in him. When he speaketh a lie, he speaketh of his own: for he is a liar, and the father of it. The phrase in KJV and ASV is unclear. The phrase in ESV and GNB is clear but not accurate translation of the Greek phrase. I accept intuitionally that Devil is "liar and father of liars." So, what is the accurate translation of the phrase?, And could you explain it to me? A: The literal Greek (Scrivener Textus Receptus) reads something like: ὅταν λαλῇ - hotan lalē - whenever he may/might speak (λαλῇ is subjunctive) τὸ ψεῦδος - to pseudos - the lie ἐκ τῶν ἰδίων λαλεῖ - ek tōn lalei - out of his own he speaks ὅτι ψεύστης ἐστὶ - hoti pseustēs esti - for a liar he is καὶ ὁ πατὴρ αὐτοῦ - kai ho patēr autou - and the father of IT (Aside from the use of ἐστὶν rather than ἐστὶ there seems to be no difference between the Textus Receptus Greek and the Nestle-Aland version upon which most modern Protestant English translations are based). The word αὐτοῦ ("IT" above) is the genitive case of both the masculine αυτός and the neuter αυτό, so perhaps one could argue that it could belong with either ψεύστης (liar) - which is masculine - or with ψεῦδος (lie) - which is neuter. Other language considerations aside, it seems that the "IT" was understood to belong with "the lie". The verse is/was understood by many to be an allusion to the very first lie in human history, in the Garden. John Chrysostom (4th c. Byzantine Greek), for example, wrote "For the devil first was the father of a lie, when he said, In the day that ye eat thereof your eyes shall be opened [Genesis 3:5], and he first used it. For men use a lie not as a thing proper, but alien to their nature, but [for the devil it is] proper" (Homily LIV on John).
{ "pile_set_name": "StackExchange" }
Q: Perché questa frutta si chiama "tabacchiera"? Durante un recente viaggio in Italia ho scoperto che la frutta della fotografia si chiama "tabacchiera", parola che mi è sembrata molto curiosa.                                                             (Fonte della immagine) Beh, perlomeno è così come la chiamava il fruttivendolo perché non ho trovato questa accezione in nessuno dei dizionari che ho consultato. Si trova qualcosa su Wikipedia, ma non so fino a che punto le informazioni che si includono là sono affidabili (la prima cosa che si vede è una frase evidenziata e indicata come "senza fonte"). La mia domanda è: da dove proviene questo nome, "tabacchiera", per questa frutta? Veramente si chiama così perché assomiglia a una tabacchiera? (personalmente non riesco a immaginare una scatoletta per tabacco con la forma di questa frutta). In spagnolo usiamo il termine "paraguayo" per designarla (in catalano sono "paraguaians", ma non so perché è una di quelle parole che, perlomeno a Barcellona, quasi tutti dicono in castigliano): non so neanche da dove proviene questo nome (e non ho trovato nulla al riguardo), forse dovrei chiederlo in Spanish.SE. A: Su questo blog ho trovato: È la pesca “Tabacchiera” così chiamata per la sua forma piatta, a disco, che ricorda appunto quella di una tabacchiera. In questo altro blog invece Il suo nome scientifico è Prunis persica, varietà platycarpa ossia dal corpo piatto: la tabacchiera appartiene a pieno diritto alla famiglia delle pesche. Fu introdotta in Europa attraverso la Persia, pur se le sue origini sono cinesi, come per diverse piante della famiglia delle Rosacee ormai diventate comuni in Europa quali il ciliegio e il melo. In Sicilia l’antica pesca tabacchiera La sua è una storia curiosa. È opinione comune che la si chiami tabacchiera nel Sud Italia e saturnia o saturnina al Centro Nord. Le forme più antiche di questa pianta si sono sempre chiamate tabacchiera. Come utilmente sottolineato da @DaG anche su Zanichelli si può trovare un riferimento: pesca tabacchiera, varietà a forma schiacciata, profumo intenso, polpa bianca, succosa e dolce, coltivata in aree limitate della Sicilia e della Romagna.
{ "pile_set_name": "StackExchange" }
Q: Time difference in seconds (as a floating point) >>> from datetime import datetime >>> t1 = datetime.now() >>> t2 = datetime.now() >>> delta = t2 - t1 >>> delta.seconds 7 >>> delta.microseconds 631000 Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to do it with datettime, that would be great. Otherwise it'll look ugly: t1 = datetime.now() _t1 = time.time() t2 = datetime.now() diff = time.time() - _t1 A: for newer version of Python (Python 2.7+ or Python 3+), you can also use the method total_seconds: from datetime import datetime t1 = datetime.now() t2 = datetime.now() delta = t2 - t1 print(delta.total_seconds()) A: combined = delta.seconds + delta.microseconds/1E6 A: I don't know if there is a better way, but: ((1000000 * delta.seconds + delta.microseconds) / 1000000.0) or possibly: "%d.%06d"%(delta.seconds,delta.microseconds)
{ "pile_set_name": "StackExchange" }
Q: What exactly are the 'voids' in the Fringe parallel universe? From what I can tell the primary reason that the other parallel universe is seeking to destroy our universe is because they presume that the voids that appear there are being caused by this universe. I get that the voids started occuring when Walter crossed over to get the other Peter, but what exactly is causing these voids? A: The voids are micro-black holes (the amber is used to "seal" these). Traveling between the two universes probably requires bending space (I assume some kind of inter-universe wormhole is created). It could be that these wormholes then pinch off into just a black hole, which then needs to be sealed. Since travel between the two universes seems to have originated 'over here', we might deduce that creating a wormhole is more controlled, since we get to choose where we start. It looks like the other end of the wormhole might be more unstable, which would explain why the voids only occur 'over there', and not 'over here'.
{ "pile_set_name": "StackExchange" }
Q: Javascript causing error to emailsender.php I have this javascript code to do not redirect when user press submit after fill form inputs. The problem is: When I use this javascript my emailsender.php just don't work and I don't know why. var form = $('#main-contact-form'); form.submit(function(event) { event.preventDefault(); var form_status = $('<div class="form_status"></div>'); $.ajax({ url: $(this).attr('action'), beforeSend: function() { form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Enviando E-mail...</p>').fadeIn()); } }).done(function(data) { form_status.html('<p class="text-success">E-mail enviado com sucesso</p>').delay(3000).fadeOut(); }); }); I'm using phpmailer EDIT: emailsender.php <?php session_start(); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); if (array_key_exists("submit", $_POST)){ require_once 'class.phpmailer.php'; require_once 'class.smtp.php'; $mail = new PHPMailer(); $nome = $_POST['username']; $email = $_POST['useremail']; $texto = $_POST['usermessage']; $corpo = "<strong>Nome:</strong> $nome<br /><strong>E-mail:</strong> $email<br /><strong>Mensagem:</strong><br /><br />$texto"; $mail->Host = 'mail.XXXXXXX.com.br'; $mail->IsSMTP(); $mail->SMTPAuth = true; $mail->Port = 465; $mail->Username = '[email protected]'; $mail->Password = 'XXXXXXX'; $mail->From = $email; $mail->FromName = $nome; $mail->Subject = 'XXXXXXX'; $mail->AddAddress('[email protected]'); $mail->IsHTML(true); $mail->Body = $corpo; if ($mail->Send()) { echo 'ok'; } } ?> html form: <form action="sendemail" id="main-contact-form" name="contact-form" method="post"> <div class="row wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="300ms"> <div class="col-sm-6"> <div class="form-group"> <input type="text" id="username" name="username" class="form-control" placeholder="Nome" required="required"> </div> </div> <div class="col-sm-6"> <div class="form-group"> <input type="email" id="useremail" name="useremail" class="form-control" placeholder="E-mail" required="required"> </div> </div> </div> <div class="form-group"> <textarea name="usermessage" id="usermessage" class="form-control" rows="4" placeholder="Mensagem" required="required"></textarea> </div> <div class="form-group"> <button type="submit" name="submit" id="submit" class="btn-submit">Enviar</button> </div> </form> A: You forgot to pass data and type in your ajax code. var form = $('#main-contact-form'); form.submit(function(event) { event.preventDefault(); var form_status = $('<div class="form_status"></div>'); $.ajax({ type:"POST", url: $(this).attr('action'), data: form.serialize(), beforeSend: function(){ form.prepend(form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Enviando E-mail...</p>').fadeIn()); } }).done(function(data) { form_status.html('<p class="text-success">E-mail enviado com sucesso</p>').delay(3000).fadeOut(); }); }); Please also change your <form action="emailsender.php" Note that this will never be true since your are using ajax if (array_key_exists("submit", $_POST)),Your other option is check the other keys. sample if(isset($_POST['username']) && isset($_POST['useremail'] && isset($_POST['usermessage']))){ //YOUR SEND EMAIL CODE }
{ "pile_set_name": "StackExchange" }
Q: how to get one click - after click nested li element I have problem to identify clicked li element, her is html structure: <section class="right_menu" id="right_menu"> <div class="menu_pusher"> <ul id="0"> <li><a href="#">Product_1</a></li> <li><a href="#">Product_2</a></li> <li><a href="#">Product_3</a></li> <li><a href="#">Product_4</a></li> <li class="Product_5"><a href="#">Product_5</a> <ul> <li class="Article_1"><a href="#">Article_1</a> <ul> <li><a href="#">Detail_1</a></li> <li><a href="#">Detail_2</a></li> <li><a href="#">Detail_3</a></li> </ul> </li> <li><a href="#">Article_2</a></li> <li><a href="#">Article_3</a></li> <li><a href="#">Article_4</a></li> </ul> </li> <li><a href="#">Product_4</a></li> </ul> </div> </section> So when i click in Product_5 alert give me Product_5 and so is ok but when I clikc then in Article_1 alert give me Article_1 and then Product_5 agein, it look like double click but I dont now way. This is javascript code: function has_ul(element){ if((element.getElementsByTagName('li').length >= 1)) return true; else return false; } $(document).ready(function() { $('#right_menu .menu_pusher ul li').on('click',rout);}) var timeout = 500; var closetimer = 0; var ddmenuitem = 0, open = false; function rout(){open?jsddm_close():jsddm_open(this);} function jsddm_open(el) { //open=true; jsddm_canceltimer(); if(has_ul(el)){ var lef = parseInt($('.menu_pusher').css("left")) - 220; alert(el.className); $('.menu_pusher').css('left', lef); return false; } } function jsddm_close() { if(ddmenuitem) ddmenuitem.css('display', 'none'); open=false;} function jsddm_timer() { closetimer = window.setTimeout(jsddm_close, timeout);} function jsddm_canceltimer() { if(closetimer) { window.clearTimeout(closetimer); closetimer = null;}} So way I get to li element click? Here is link to this example: https://jsfiddle.net/rwqc9bje/ A: Try to handle the event on a element instead of li... This should avoid having this double event behavior.
{ "pile_set_name": "StackExchange" }
Q: Converting Number to String Is it possible to convert a number column to a string one , changing '.' for ',' and maintaning two decimal places on QGIS ? A: It is possible to do so using the field calculator. The round expression converts your number to the needed decimal places, then the to_string expression converts to string and the replace will replace your dot with a comma. The expression should look like this: replace(( to_string( ( round( "yourfield", 2)))), '.', ',') Edit: this is to address the situation where the number has no decimal digits and the OP wants to pad with 1 or 2 zeros. Using the field calculator, create a new field with a string type and use the following expression: CASE WHEN (length("string") - strpos( "string", ',') = 1) THEN "string" + '0' WHEN (length("string") - strpos("string", ',') = length("string")) THEN "string" + ',00' ELSE "string" END Replace "string" with the name of the field you created in the previous step. To explain a bit what is going on in the expression, length returns the number of characters in a string value, strpos(haystack, needle) returns the position of needle in the given string and finally "string" + '0' is a string concatenation expression.
{ "pile_set_name": "StackExchange" }
Q: How to Save IP address By INET_ATON in CakePHP 2.x? I want to use MySQL INET_ATON function to save IP address by CakePHP 2.x? My code is here and not work correctly! $this->loadModel('MyModel'); $data = array(); $ip = '8.8.8.8'; $data['ip'] = 'INET_ATON('.$ip.')'; $this->MyModel->save($data); And i do not use $this->MyModel->query(). For Example: $this->MyModel->query("INSERT INTO `my_table` (`ip`) VALUES (INET_ATON('8.8.8.8'))") A: Use This Code. Correctly Work. $this->loadModel('MyModel'); $data = array(); $ip = '8.8.8.8'; $data['MyModel']['ip'] = DboSource::expression('INET_ATON("'.$ip.'")'); $this->MyModel->save($data);
{ "pile_set_name": "StackExchange" }
Q: Lua - Handling 64 bits number on 32 bit lua compiler Currently I am trying to decode data (using lua). Data I have is 64 bit hexadecimal (big endian). That specific number needs to be converted to little endian. Beside that other bitwise operations are going to be applied later based on the internal logic. Now, initially I thought that things are going to be easy, having in mind that I can use bitop and simply apply any bitwise operations I would like to. Now, unfortunately, I have (and please make a note that I am not able to change this), 32 bit lua compiler, hence, I am not simply able to use these operations. There are 2 questions which I would like to ask: If i have hex 800A000000000000 how can I use 32 bitwise operations (specifically in this case operations like bit.bswap, bit.rshift, bit.lshift from the library i shared above) on this hexadecimal number? Is it possible to split this number on 2 parts, and then apply operations on each of them and then merge them together again? If that is the case, how? Do you have any good reference (like a good book) which I can use to familiarize myself with algorithms and what I can do and what I cannot when we are talking about bitwise operations (expecially representing huge numbers using multiple small chunks ) Prior asking this question, I found and read other references to the same subject, but all of them are more related with specific cases (which is hard to understand unless you are familiar with the subject): lua 64-bit transitioning issue Does Lua make use of 64-bit integers? Determine whether Lua compiler runs 32 or 64 bit Comparing signed 64 bit number using 32 bit bitwise operations in Lua A: After more detailed investigation regarding this topic, testing and communication with other people which opinion is relevant to this subject, posting an answer: In this specific case, it really does not matter do you have 32 bit or 64 bit compiler (or device). The biggest integer you are able to represent based on lua doc: 64-bit floats can only represent integers up to 53 bits of precision, and the hex number I used as an example is bigger then that. This means that any kind of general bit-wise operations are not going to work for these numbers. Basically, this question can be reconstructed in: "How I can use bit wise operations in lua on full 64 bits?". Only solution is to use libraries for this one or to implement it by yourself (separating 64 bit number to two 32 bit numbers and implementing bit wise operators by yourself)
{ "pile_set_name": "StackExchange" }
Q: pass variable to php page using ajax jquery? index.html <?php while($admin_data=mysql_fetch_row($query2)){ ?> <tr> <td><?php echo $admin_data[0];?></td> <td><?php echo $admin_data[1];?></td> <td><?php echo $admin_data[2];?></td> <td><?php echo $admin_data[3];?></td> <td><a href="javascript:void()" id="delete">Delete</a></td> </tr> <div id="result_delete"></div> <?php } ?> jquery file <script> $(document).ready(function(){ $("#delete").click(function(){ $("#result_delete").load("delete.php"); }); }); </script> delete.php <?php include "db/db.php"; if($_GET['drop']){ $drop=$_GET['drop']; } echo $drop; ?> how to pass value to delete.php page. i want to pass a variable to url thanks for your answers A: IDS are SINGULAR they can not repeat. Use a class. <td><a href="javascript:void()" class="delete">Delete</a></td> and $(".delete").click(function(){ better yet $("#tableId").on("click", ".delete", function(){ And hopefully the <div id="result_delete"></div> does not live right after the TR since that is invalid HTML markup. Since you can not figure out how to get the id, it is simple. $("#tableId").on("#click", ".delete")function(){ var val = encodeURIComponent($(this).data("val")); $("#result_delete").load("delete.php?drop=" + val); }); Doing a delete request with a get request is a bad idea
{ "pile_set_name": "StackExchange" }
Q: How to browse my own source code in QtCreator debugger during debuging with QtCreator I cannot browser my own source code. I build qt sources with the debug option and as you can see the filenames of the qt source code itself are visible and I can browse them with no problem. But somehow the CONFIG+=debug has no effect on my build. build output: Running build steps for project tcpconnector... Starting: "/usr/local/Trolltech/Qt-4.7.4-DEBUG/bin/qmake" /home/user1/server/src-server/server.pro -r -spec linux-g++-64 CONFIG+=debug The process "/usr/local/Trolltech/Qt-4.7.4-DEBUG/bin/qmake" exited normally. Starting: "/usr/bin/make" ... In the screenshot from the QtCreator debugger you can see that my own code Server::deleteDuplicateConnection is grayed out. A: Like written in the comment. This just seemed to be a random phenomenon.
{ "pile_set_name": "StackExchange" }
Q: System.Data.SqlClient.SqlException: 'Incorrect syntax near 'USERNAME'.' I'm trying to make a login and I keep getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near 'USERNAME'.' Here is my code SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Omar\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"); SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From [LOGIN] were USERNAME ='" + textBox1.Text +"' and PASSWORD='"+ textBox2.Text +"'",con); DataTable dt = new DataTable(); sda.Fill(dt); A: You're getting voted down not just because this is a duplicate question but because your attempt wraps two security problems in a single piece of code. So let's take this step by step. 1) Your actual problem is you mispelt WHERE. Your corrected code would look something like SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Omar\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"); SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From [LOGIN] where USERNAME ='" + textBox1.Text +"' and PASSWORD='"+ textBox2.Text +"'",con); DataTable dt = new DataTable(); sda.Fill(dt); But you don't need a data adapter or a table, you can return a count from SQL directly. So you could do something like string sql = "select count(*) from users where username = '" + username + "' and password = '" + password + "'"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand command = new SqlCommand(query, conn)) { int result = (int)command.ExecuteScalar(); if (result > 0) { /// login sucessful } } } This would work, but you have a security vulnerability called SQL injection. If we look at a correct login your SQL string would be select count(*) from login where username = 'alice' and password = 'bob' This works fine, but if I enter the classic example of SQL injection for a login page as the password, ' OR 1=1 -- then your SQL string becomes this; select count(*) from login where username = 'alice' and password = '' OR 1=1 --' This line of SQL will always return 1, because it's highjacked the SQL via SQL injection, adding an OR clause at the end of the statement, OR 1=1 which is always going to be true. It then uses SQL comment syntax to comment out whatever comes after it. So now I can login as anyone at all, even usernames that don't exist. 2) The correct way to build SQL strings, if you don't want to use ORMs that do this for you (and really, use an ORM, all the protection is automatic) is to use a parameterized query, which takes the input and formats it in such a way that any special characters aren't taken as SQL commands, like so string sql = "select count(*) from login where username = @username and password = @password"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand command = new SqlCommand(query, conn)) { command.Parameters.Add(new SqlParameter("@username", username)); command.Parameters.Add(new SqlParameter("@password", password)); int result = (int)command.ExecuteScalar(); if (result > 0) { /// login sucessful } } } The parameters are in the SQL query as @parameterName, and then added with command.Parameters.Add(). Now you've avoid SQL injection 3) However this still a security problem. You're storing your passwords in plaintext. If I can gain access to your SQL database (via SQL injection, or you leaving the server open to the world) once I have a copy of the database I have your usernames and passwords and your company is going to end up on haveibeenpwned. You shouldn't be doing this. Passwords should be protected, not via encryption, but via what is called hashing and salting. This transforms the passwords into a value that is derived from it via a one way function, it takes the password, feeds it into some math, and the result out the other side represents the password, but you can't go back the other way, you can't figure out the password from the salted hash. Then when you compare logins, you compute the hash again, and use that in your comparison, in an ORM driven query or a parameterised query. Now, with all that in mind, I'd strongly advise you to avoid doing any of this yourself. C# & ASP.NET have libraries for usernames and passwords in ASP.NET Identity. I would much rather see you use that, not just because I happen to be the PM owner for that and for .NET Security as a whole, but because it does everything right for you, without you having to do any work. If this is for a real world application please take some time to go through the OWASP project, it has lots of examples of security problems and details on how to fix them. A: Please... learn about parameters; the code you have is open to SQL injection, which is a huge problem (especially, but not just, on a login form) learn about not storing plain-text passwords, instead using salted cryptographic hashes learn about IDisposable; multiple of the objects involved here are disposable and need using don't use DataTable unless you know why you're using it - there is no reason whatsoever to use it here learn about tools that will help do all of the above for you and when, and only when, you have the above "down": fix the typo Here's a version using "dapper", that covers most of this: using (var con = SqlConnection(@"...not shown...")) { var hash = HashPasswordUsingUsernameAsSalt( textBox1.Text, textBox2.Text); // impl not shown int count = con.QuerySingle<int>(@" select COUNT(1) from [LOGIN] where [USERNAME]=@cn and [PW_HASH]=@hash", new { cn = textBox1.Text, hash }); // TODO: do something with count }
{ "pile_set_name": "StackExchange" }
Q: lucene.net problem with wildcard "*" hello i have a question to lucene searching syntax the "" is a wildcard. when i search te : i find test ,... but when i search *st i don't find "test :> whats the issue? and i have a search concerning the text and an other search concerning the filename in the filename search i use ""+searchstring "" in the textsearch just "searchstring" what can i do when i search both, but filename with "" "" parser = New MultiFieldQueryParser(New [String]() {"title", "bodytext"}, New StandardAnalyzer()) A: hmm http://lucene.apache.org/java/2_3_2/queryparsersyntax.html#Wildcard%20Searches -->Note: You cannot use a * or ? symbol as the first character of a search. well i think that's it :/
{ "pile_set_name": "StackExchange" }
Q: TCP Client-Server communications I have developed this simple TCP Server/Client communication program, and am looking for ways of lowering the code footprint where possible.Side note, Both Classes are Main as they run independently, though interact. TCPClient package socketUse; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.Socket; import java.net.SocketTimeoutException; class TCPClient { public static void main(String[] args) throws Exception { try { String input; String modedInput; System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:"); BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); @SuppressWarnings("resource") Socket client = new Socket("localhost", 22003); client.setSoTimeout(3000); while(true) { DataOutputStream outToServer = new DataOutputStream(client.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream())); input = inFromUser.readLine(); outToServer.writeBytes(input + '\n'); modedInput = inFromServer.readLine(); System.out.println("You Sent: " + modedInput); try { Thread.sleep(2000); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } } catch(SocketTimeoutException e) { System.out.println("Timed Out Waiting for a Response from the Server"); } } } TCPServer package socketUse; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; class TCPServer { public static void main(String[] args) throws Exception { try { String TCPclientMess; String returnMess; @SuppressWarnings("resource") ServerSocket input = new ServerSocket(22003); while(true) { Socket connectionSocket = input.accept(); BufferedReader iptFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream optToClient = new DataOutputStream(connectionSocket.getOutputStream()); TCPclientMess = iptFromClient.readLine(); System.out.println("You Sent: " + TCPclientMess); returnMess = TCPclientMess; optToClient.writeBytes(returnMess); } } catch(Exception e) { e.getStackTrace(); } } } A: Efficiency / logic In the while loop in the client class, you recreate a DataOutputStream and a BufferedReader from the socket in every single iteration. This is just silly. It would be better to create these objects before the loop. Closing resources You didn't close any of the resources you open. As of Java 7, an easy way to properly close everything is using the try-with-resources idiom, for example: try ( Socket connectionSocket = input.accept(); BufferedReader iptFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream optToClient = new DataOutputStream(connectionSocket.getOutputStream()) ) { String TCPclientMess = iptFromClient.readLine(); System.out.println("You Sent: " + TCPclientMess); String returnMess = TCPclientMess; optToClient.writeBytes(returnMess); } Limit variables to the smallest necessary scope In both implementation you declare some variables at the top, when that's really not needed and may invite mistakes. It's best to declare variables at the smallest scope where you really need them. For example, instead of: String input; // ... while(true) { BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream())); input = inFromUser.readLine(); // ... This is better: while(true) { BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream())); String input = inFromUser.readLine(); // ... Hardcoded values Instead of hardcoding "localhost", 22003, 3000, it would be better to put these values in constants with descriptive names, for example: private static final int TIMEOUT_MILLIS = 3000; private static final String SERVER_HOST = "localhost"; private static final int SERVER_PORT = 22003; Redundant variable In TCPServer, the message read from the client input stream is stored in the TCPclientMess variable, and then assigned to the returnMess variable, which is not used for anything else. You don't need both variables, one of them would be enough. Naming You have a String named TCPclientMess. The convention is to use camelCase for variable names.
{ "pile_set_name": "StackExchange" }
Q: error TS5023: Unknown compiler option 'p' I am facing this issue while running the task in Visual studio code. Here is the screen shot for reference. here is the code for tasks.json { // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format "version": "0.1.0", "command": "tsc", "isShellCommand": true, "args": ["-p", "."], "showOutput": "always", "problemMatcher": "$tsc" } and code for tsconfig.json { "compilerOptions": { "noImplicitAny": true, "noEmitOnError": true, "sourceMap": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "es5", "module": "commonjs", "moduleResolution": "node" }, "exclude": [ "node_modules", "wwwroot", "typings" ], "compileOnSave": true } and code for systemjs.config.js /** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */ (function (global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, }; var ngPackageNames = [ 'common', 'compiler', 'core', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade', ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/' + pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' }; }; // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages } System.config(config); })(this); Please help me in resolving this issue i have no idea what i did wrong. A: seairth is correct, you can run tsc --version to see if it is the new version of tsc you just installed, or tsc --help to see if -p is the supported option, e.g. I've installed a new version 2.5.2, but when I run tsc --version, it always report 1.0.3 it should be caused by path conflicting, delete the tsc path in Microsoft SDK from PATH environment, e.g. C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\; should solve the problem.
{ "pile_set_name": "StackExchange" }
Q: Migrating data from PostgreSQL to SQL Server 2012 best practice I am looking to migrate data from SQL Server to Postgres. I have been able to get a dump file from my Postgres database and want to restore it to SQL Server 2012. What are the best practices for doing such a task? If you cannot simple restore the Postgres dump file to SQL Server is there a better way of transferring data from Postgres to SQL Server? A: I would look at using GDAL. A script similar to the below will connect to PostgreSQL and transfer the support.support table from SQL server, this one is also re-projecting the data into ESPG:27700. ogr2ogr -overwrite -update -f "PostgreSQL" PG:"host=127.0.0.1 port=5432 dbname=databasename user=postgres password=*******" -f MSSQLSpatial "MSSQL:server=servername;database=databasename;UID=support;PWD=*****" support.support -lco OVERWRITE=yes -lco SCHEMA=public -a_srs EPSG:27700 -progress This script can be easily switched around to transfer from Postgres to SQL Server: ogr2ogr -overwrite -update -f MSSQLSpatial "MSSQL:server=servername;database=databasename;UID=username;PWD=********" -f "PostgreSQL" PG:"host=127.0.0.1 port=5432 dbname=databasenaem user=postgres password=*******" public.support -lco OVERWRITE=yes -lco SCHEMA=public -a_srs EPSG:27700 -progress My favourite guide to installing GDAL is https://sandbox.idre.ucla.edu/sandbox/tutorials/installing-gdal-for-windows if you have not used it before. There are other ways such as using python that I am not to familiar with but I would like to know more about too.
{ "pile_set_name": "StackExchange" }
Q: Make a listActivity work with 2 items per row I'm having trouble setting my listView up to work with two textViews per item in the list. This is my code. I know there is something fundamentally wrong with the way that I try to implement two different arrays, but I haven't been able to figure this out. Not sure if hashMaps would be the way to go. private String[] nums= { "One", "Two", "Three" }; private String[] names= { "HoneyComb", "JellyBean", "ICS" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); int[] ids = {android.R.id.text1, android.R.id.text2}; SimpleAdapter<String> adapter = new SimpleAdapter(this, names, android.R.layout.simple_list_item_2, nums, ids); setListAdapter(adapter); } I would really like to stick with SimpleAdapter if possible. A: Tyr this one private String[] nums= { "One", "Two", "Three" }; private String[] names= { "HoneyComb", "JellyBean", "ICS" }; List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); for(int i=0;i<nums.lenght();i++){ HashMap<String, String> hm = new HashMap<String,String>(); hm.put("txt1", nums[i]); hm.put("txt2", names[i]); aList.add(hm); } // Keys used in Hashmap String[] from = { "txt1","txt2" }; // Ids of views in listview_layout int[] to = {R.id.txt1,R.id.txt2}; // Instantiating an adapter to store each items // R.layout.listview_layout defines the layout of each item SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to); setListAdapter(adapter); } listview_layout.xml is <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/txt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15dp" /> <TextView android:id="@+id/txt2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" /> </LinearLayout>
{ "pile_set_name": "StackExchange" }
Q: Delete multiple Inputs on click with JS I paginated my Project (endless, without click) and when the next page is loaded, a input select2 input field in a Modal is getting replicated. So after a bit of scrolling I have couple duplicates. So I tried to delete the duplicates like: $(".modalOpen").click(function(){ $('.theLangu1:eq(0)').next("span").remove(); $('.theLangu1').children().find(...).remove(); $('.theLangu1:eq(1)').remove(); ... }) but nothing worked. The code looks like this in the console: So the first one needs to stay alive but the rest has to be removed. ($('.theLangu1:eq(0)').remove(); does remove everything except one but it also deletes the necessary one so it does not help). Another Problem is that I have multiple <input> and other select2 fields so its not done by simply removing everything (I tried). So it needs to be something in the direction $(".theLangu1").children().find/next... Any jQuery expert here to tell me how to remove duplicates or all inputs except the first one? A: You can use the not CSS psuedo-selector $('.theLangu1').parent() .find(".theLangu1:not('.theLangu1:first-child')") .remove(); You can use the not JQuery method $('.theLangu1').parent() .find(".theLangu1").not(".theLangu1:first-child") .remove(); https://jsfiddle.net/rwh7wd37/1/
{ "pile_set_name": "StackExchange" }
Q: Getting highest level parent from json code with php I'm struggling on getting the get the highest id as a separate record in case there is a sub, or more subs out of a json array. <?php $data = json_decode(' [{"id":122943, "children":[{"id":48614}]}, {"id":10009, "children":[{"id":74311, "children":[{"id":17988}]}]}]'); function parseJsonArray($jsonArray, $parentID = 0) { $return = array(); foreach ($jsonArray as $subArray) { $returnSubSubArray = array(); if (isset($subArray->children)) { $returnSubSubArray = parseJsonArray($subArray->children, $subArray->id); } $return[] = array('id' => $subArray->id, 'parentID' => $parentID); $return = array_merge($return, $returnSubSubArray); } return $return; } $readbleArray = parseJsonArray($data); $i=0; foreach($readbleArray as $row){ $i++; echo("update cmm_master set parent = '".$row['parentID']."', sort = '".$i."' , master = '????' where PCR = '".$row['id']."' ")."<br>"; echo ("\r\n"); } ?> With the example above I'm trying the get the master record for each item and the outcome should be: parent = '122943', sort = '1' , master = '122943' where PCR = '122943' parent = '122943', sort = '2' , master = '122943' where PCR = '48614' parent = '10009', sort = '3' , master = '10009' where PCR = '10009' parent = '10009', sort = '4' , master = '10009' where PCR = '74311' parent = '74311', sort = '5' , master = '10009' where PCR = '17988' Thanks for your help or information A: Try to use this code: <?php $data = json_decode(' [ {"id":122943, "children":[ {"id":48614} ] }, {"id":10009, "children":[ {"id":74311, "children":[ {"id":17988} ]} ]} ] '); function parseJsonArray($jsonArray, $parentID = 0, $masterID = 0) { $return = array(); foreach ($jsonArray as $subArray) { $returnSubSubArray = array(); if (isset($subArray->children)) { $returnSubSubArray = parseJsonArray($subArray->children, $subArray->id, !$parentID ? $subArray->id : $masterID); } $return[] = array('id' => $subArray->id, 'parentID' => !$parentID ? $subArray->id : $parentID, 'masterID' => !$parentID ? $subArray->id : $masterID); $return = array_merge($return, $returnSubSubArray); } return $return; } $readbleArray = parseJsonArray($data); $i = 0; foreach ($readbleArray as $row) { $i++; echo ("update cmm_master set parent = '" . $row['parentID'] . "', sort = '" . $i . "' , master = '".$row['masterID']."' where PCR = '" . $row['id'] . "' "); echo("\r\n"); } ?> It's output looks like: update cmm_master set parent = '122943', sort = '1' , master = '122943' where PCR = '122943' update cmm_master set parent = '122943', sort = '2' , master = '122943' where PCR = '48614' update cmm_master set parent = '10009', sort = '3' , master = '10009' where PCR = '10009' update cmm_master set parent = '10009', sort = '4' , master = '10009' where PCR = '74311' update cmm_master set parent = '74311', sort = '5' , master = '10009' where PCR = '17988'
{ "pile_set_name": "StackExchange" }
Q: How application that use twitter API is communicating with twitter I want to implement similar API as twitter and what to know how it's implemented. I didn't read much about oAuth and didn't develop twitter app. When user click on button it execute javascript that popup new window with twitter page and user click connect or authenticate an app. How processing is passed back to application and how application know that on twitter side execution is finished and user authorize the app? A: You need to provide callback function/url of your application where twitter returns with access token after the twitter side execution is finished.
{ "pile_set_name": "StackExchange" }
Q: How to get the raw data from kendo dataSource? I am getting kendo grid data from backend and setting it to kendo grid options alignedProcessesToRiskGridOptions now data is displaying in the grid , but i also wanted to get raw data to write some logic, How can i get data from dataSource or directly calling RiskService AngularJs factory and assign it to var gridData? ctrl.js $scope.alignedProcessesToRiskGridOptions = RiskService.alignedProcessToRiskGrid(); $scope.alignedProcessesToRiskGridOptions.dataSource = RiskService.getAlignedProcessesToRiskGridDataSource($stateParams.riskId); gridData = $scope.alignedProcessesToRiskGridOptions.dataSource.data(); console.log('RISK DATA', gridData); factory.js getAlignedProcessesToRiskGridDataSource: function(riskKey) { var countNew = 0; return new kendo.data.DataSource({ type: 'json', serverPaging: true, serverSorting: true, serverFiltering: true, transport: { read: function(options) { var gridSearchObject = { skip: options.data.skip, take: options.data.take, pageSize: options.data.pageSize, page: options.data.page, sorting: options.data.sort, filter: options.data.filter }; return $http.post( 'app/risk/rest/allAlignedProcessesToRisk/' + riskKey, gridSearchObject).success( function(data) { countNew = data.totalCount; options.success(data.resultDTOList); }); } }, A: According to the kendo documentation, there are at least a couple ways to get at the actual data from a datasource. There is the view method Returns the data items which correspond to the current page, filter, sort and group configuration. Compare with the data method, which will return data items from all pages, if local data binding and paging are used. There is the data method Gets or sets the data items of the data source. If the data source is bound to a remote service (via the transport option) the data method will return the service response. Every item from the response is wrapped in a kendo.data.ObservableObject or kendo.data.Model (if the schema.model option is set). If the data source is bound to a JavaScript array (via the data option) the data method will return the items of that array. Every item from the array is wrapped in a kendo.data.ObservableObject or kendo.data.Model (if the schema.model option is set). Since you are using the data method, you should be able to access the data via the properties and methods of the resulting object. You should be able to check the length of gridData via console.log(gridData.length), as well checking any individual object within the data via an array index console.log(gridData[0]). Further you should be able to check properties of the objects via console.log(gridData[0].firstProperty). If none of these work, then it is likely because the datasource is not being checked with the context of query or fetch. If you check out this example, you will see that the data is being evaluated inside of the fetch function. You can find more information about the Kendo DataSource in their online documentation. Lastly, you can see an example of the different ways I use the Kendo datasource in this question about the kendo grid.
{ "pile_set_name": "StackExchange" }
Q: Store csv data as rows or columns in view of the needed processing? Assume I have some data a csv-Files like ObjectName, PropertyA, PropertyB, PropertyC "Name1", 3, 1, 4 "Name2", 1, 5, 9 "Name3", 2, 6, 5 ... and a typical question I want to answer would be For which Object is PropertyX maximal? I have two approaches for this and would be thankful for some Input. Approach 1 I define a class like struct Object { std::String name; int a; int b; int c; }; Store the data in a class like class ObjectCollection { std::vector<Object> collection; } And provide two functions size_t ObjectCollection::getMaxIndexOfA() size_t ObjectCollection::getMaxIndexOfB() size_t ObjectCollection::getMaxIndexOfC() Now these Functions would essentially be the same and look like size_t maxIndex = -1; int max = std::numeric_limits<int>::min(); for (size_t i = 0; i < collection.size(); ++i) { if (collection[i].a > max) { maxIndex = i; max = collection[i].a; } } return maxIndex; It bothers me that I would have to write and maintain the same code twice. Approach 2 Store the data in a class like class ObjectCollection { std::vector<String> names; std::vector<int> a; std::vector<int> b; std::vector<int> c; } Then I could provide methods like const std::vector<int>& ObjectCollection::getA() const; const std::vector<int>& ObjectCollection::getB() const; const std::vector<int>& ObjectCollection::getC() const; And use a single function to find the maximum which I have to call as getMaxIndex( collection.getA() ); where size_t getMaxIndex(const std::vector<int>&) would be essentially the same as in approach 1. I think I prefer the second approach, but it bothers me that in this case there is no class representing a single Object. Is it weird/bad design to store the data as in the second approach? Is there another smart approach I didn't think about? By the way, I am more concerned with the choice between these two approaches than the fact that I should probably use std::max_element to find the index. A: Is there another smart approach I didn't think about? If your properties are of the same type and behave similar, why not address them by an index? enum PropIndex{PropertyA=0, PropertyB=1, PropertyC=2}; struct Object { std::String name; std::vector<int> property(3); // use PropIndex to access the value you want // if that helps for convenience, you can also add getters and setters like this one int getA(){ return property(PropertyA); } // ... but then you should consider to make the public members // ... all private, and provide proper public getters/setter for all of them }; Now you need to implement your maximum function only once (with an additional parameter which Property you want).
{ "pile_set_name": "StackExchange" }
Q: Encrypting a string but receiving an infinite loop Problem: I was trying to encrypt a std::string password with a single rule: Add "0" before and after a vowel So that bAnanASplit becomes b0A0n0a0n0A0Spl0i0t. However, I got stuck in an infinite loop. Here is the code: const std::string VOWELS = "AEIOUaeiou"; std::string pass = "bAnanASplit"; //Add zeroes before and after vowels for (int i = 0; i < pass.length(); ++i) { i = pass.find_first_of(VOWELS, i); std::cout << pass << "\n"; if(i != std::string::npos) { std::cout << pass[i] << ": " << i << "\n"; pass.insert(pass.begin() + i++, '0'); pass.insert(pass.begin() + ++i, '0'); } } ...And the result: bAnanASplit A: 1 b0A0nanASplit a: 5 b0A0n0a0nASplit A: 9 b0A0n0a0n0A0Split i: 15 b0A0n0a0n0A0Spl0i0t b0A0n0a0n0A0Spl0i0t A: 2 b00A00n0a0n0A0Spl0i0t a: 8 b00A00n00a00n0A0Spl0i0t A: 14 b00A00n00a00n00A00Spl0i0t i: 22 b00A00n00a00n00A00Spl00i00t b00A00n00a00n00A00Spl00i00t ... Any help? This sure seems strange. Edit: All the answers were useful, and therefore I have accepted the one which I think best answers the question. However, the best way to solve the problem is shown in this answer. A: Never, ever, modify the collectionl/container you are iterating upon! Saves you a lot of trouble that way. Let's start with your code and generate a new string with vowels surrounded by 0. const std::string VOWELS = "AEIOUaeiou"; std::string pass = "bAnanASplit", replacement; //Add zeroes before and after vowels for (auto ch : pass) { if(VOWELS.find(ch) != std::string::npos) replacement += '0' + ch + '0'; else replacement += ch; } And there you have it! A: As the OP seems to look for the exact reason for the misbehavior, I thought to add another answer as the existing answers do not show the exact issue. The reason for the unexpected behavior is visible in following lines. for (int i = 0; i < pass.length(); ++i) { i = pass.find_first_of(VOWELS, i); ... Problem 1: The loop counter i is an int (i.e. a signed int). But std::string::find_first_of returns std::string::npos if there's no match. This is usually the maximum number representable by an unsigned long. Assigning a huge unsigned value to a shorter signed variable will store a totally unexpected value (assuming you are not aware of that). In this case, i will becomes -1 in most platforms (try int k = std::string::npos; and print k if you need to be sure). i = -1 is valid state for the loop condition i < pass.length(), so the next iteration will be allowed. Problem 2: Closely related to the above problem, same variable i is used to define the start position for the find operation. But, as explained, i will not represent the index of the character as you would expect. Solution: Storing a malformed value can be solved by using the proper data type. In the current scenario, best options would be using std::string::size_type as this is always guaranteed to work (most probably this will be equal to size_t everywhere). To make the program work with the given logic, you will also have to use a different variable to store the find result. However, a better solution would be using a std::stringstream for building the string. This will perform better than modifying a string by inserting characters in the middle. e.g. #include <iostream> #include <sstream> int main() { using namespace std; const string VOWELS = "AEIOUaeiou"; const string pass = "bAnanASplit"; stringstream ss; for (const char pas : pass) { if (VOWELS.find(pas) == std::string::npos) { ss << pas; } else { ss << '0' << pas << '0'; } } cout << pass << "\n"; cout << ss.str() << endl; }
{ "pile_set_name": "StackExchange" }
Q: Tar archive parser - custom implementation I'm learning python and for educational purposes I implemented tar archive parser. I'm not beginner programmer. I would like to receive some feedback and tips about code, what can I improve, what could be done better and so on. Implementation: tar.py #!/usr/bin/env python3 import io import os import sys import math import json class Tar: BLOCK_SIZE = 512 def __init__(self, file_path): if not file_path or len(file_path) == 0: raise ValueError("Bad file path") self.file_path = file_path def __enter__(self): self.input_stream = open(self.file_path, "rb") self.headers = [] return self def __exit__(self, type, value, traceback): self.close() def close(self): if self.input_stream: self.input_stream.close() def get_all_files(self): self.__scan() return list(map( lambda f: FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag), self.headers )) def extract_file(self, file_name, target_folder=os.getcwd()): if not file_name or len(file_name) == 0: raise ValueError("Bad file name") if not target_folder or len(target_folder) == 0: raise ValueError("Bad target folder") self.__scan() result = list(filter( lambda fh: fh.flag == 0 and fh.file_name == file_name, self.headers )) if len(result) == 0: raise RuntimeError("File '{}' not found".format(file_name)) fh = result[0] leaf = os.path.basename(fh.file_name) f_path = os.path.join(target_folder, leaf) self.__extract(fh, f_path) def extract_all(self, target_folder=os.getcwd()): if not target_folder or len(target_folder) == 0: raise ValueError("Bad target folder") self.__scan() for fh in self.headers: f_path = os.path.join(target_folder, fh.file_name) if fh.flag == 5: # if directory os.makedirs(f_path, exist_ok=True) elif fh.flag == 0: # if regular file parent = os.path.dirname(os.path.abspath(f_path)) os.makedirs(parent, exist_ok=True) self.__extract(fh, f_path) def __extract(self, fh, file_name): with open(file_name, "wb") as f: if fh.file_size > 0: total = 0 bytes_left = fh.file_size self.input_stream.seek(fh.offset, 0) while bytes_left > 0: data = self.input_stream.read(Tar.BLOCK_SIZE) data = data[:bytes_left] f.write(data) bytes_left -= len(data) def __scan(self): # iterate over headers if len(self.headers) == 0: while True: block = self.input_stream.read(Tar.BLOCK_SIZE) if len(block) < Tar.BLOCK_SIZE: break h = self.__get_file_header(block) if not len(h.magic) > 0: break # ommit regular file bytes if h.flag == 0: h.set_offset(self.input_stream.tell()) if h.file_size > 0: if h.file_size % Tar.BLOCK_SIZE != 0: bytes_to_skeep = math.ceil(h.file_size / Tar.BLOCK_SIZE) * Tar.BLOCK_SIZE else: bytes_to_skeep = h.file_size self.input_stream.seek(bytes_to_skeep, 1) self.headers.append(h) def __get_file_header(self, block): try: file_name = self.__get_file_name(block) file_mode = self.__get_file_mode(block) uid = self.__get_uid(block) gid = self.__get_gid(block) file_size = self.__get_file_size(block) mtime = self.__get_mtime(block) chksum = self.__get_chksum(block) type_flag = self.__get_type_flag(block) linkname = self.__get_linkname(block) magic = self.__get_magic(block) version = self.__get_version(block) uname = self.__get_uname(block) gname = self.__get_gname(block) devmajor = self.__get_devmajor(block) devminor = self.__get_devminor(block) prefix = self.__get_prefix(block) except Exception as e: raise RuntimeError("Broken file") from e header = FileHeader(file_name, file_size, file_mode, uid, gid, mtime, chksum, type_flag, linkname, magic, version, uname, gname, devmajor, devminor, prefix) return header def __get_file_name(self, block): # string offset, size = 0, 100 fname = self.__get_block_data(block, offset, size) fname = fname[0:fname.find(b'\x00')].decode().strip() return fname def __get_file_mode(self, block): # string offset, size = 100, 8 mode = self.__get_block_data(block, offset, size) mode = mode[:mode.find(b'\x00')].decode().strip() return mode def __get_uid(self, block): # string offset, size = 108, 8 uid = self.__get_block_data(block, offset, size) uid = uid[:uid.find(b'\x00')].decode().strip() return uid def __get_gid(self, block): # string offset, size = 116, 8 gid = self.__get_block_data(block, offset, size) gid = gid[:gid.find(b'\x00')].decode().strip() return gid def __get_file_size(self, block): # int offset, size = 124, 12 size = self.__get_block_data(block, offset, size) size = size[:size.find(b'\x00')].decode().strip() if len(size) > 0: size = int(size, 8) else: size = 0 return size def __get_mtime(self, block): # int offset, size = 136, 12 mtime = self.__get_block_data(block, offset, size) mtime = mtime[:len(mtime)-1] mtime = mtime[:mtime.find(b'\x00')].decode().strip() if len(mtime) > 0: mtime = int(mtime, 8) else: mtime = 0 return mtime def __get_chksum(self, block): # int offset, size = 148, 8 chksum = self.__get_block_data(block, offset, size) chksum = chksum[:chksum.find(b'\x00')].decode().strip() if len(chksum) > 0: chksum = int(chksum) else: chksum = 0 return chksum def __get_type_flag(self, block): # int offset, size = 156, 1 flag = self.__get_block_data(block, offset, size) if flag == b'\x00': flag = 0 elif flag == b'x': flag = 11 else: flag = int(flag) return flag def __get_linkname(self, block): # string (applicable if type_flag = 1 or 2) offset, size = 157, 100 linkname = self.__get_block_data(block, offset, size) return linkname[:linkname.find(b'\x00')].decode().strip() def __get_magic(self, block): # string offset, size = 257, 6 magic = self.__get_block_data(block, offset, size) magic = magic[:magic.find(b'\x00')].decode().strip() return magic def __get_version(self, block): # string offset, size = 263, 2 version = self.__get_block_data(block, offset, size) version = version[:len(version)-1].decode().strip() return version def __get_uname(self, block): # string offset, size = 265, 32 uname = self.__get_block_data(block, offset, size) uname = uname[:uname.find(b'\x00')].decode().strip() return uname def __get_gname(self, block): # string offset, size = 297, 32 gname = self.__get_block_data(block, offset, size) gname = gname[:gname.find(b'\x00')].decode().strip() return gname def __get_devmajor(self, block): # string offset, size = 329, 8 devmajor = self.__get_block_data(block, offset, size) devmajor = devmajor[:devmajor.find(b'\x00')].decode().strip() return devmajor def __get_devminor(self, block): # string offset, size = 337, 8 devminor = self.__get_block_data(block, offset, size) devminor = devminor[:devminor.find(b'\x00')].decode().strip() return devminor def __get_prefix(self, block): # string offset, size = 345, 155 prefix = self.__get_block_data(block, offset, size) prefix = prefix[:prefix.find(b'\x00')].decode().strip() return prefix def __get_block_data(self, block, offset, size): return block[offset:offset+size] class FileSnapshot: def __init__(self, file_name, file_size, file_mode, flag): self.file_name = file_name self.file_size = file_size self.file_mode = file_mode self.flag = flag def __repr__(self): return self.file_name class FileHeader: def __init__(self, file_name, file_size, file_mode, uid, gid, mtime, chksum, flag, linkname, magic, version, uname, gname, devmajor, devminor, prefix): self.file_name = file_name self.file_size = file_size self.file_mode = file_mode self.uid = uid self.gid = gid self.mtime = mtime self.chksum = chksum self.flag = flag self.linkname = linkname self.magic = magic self.version = version self.uname = uname self.gname = gname self.devmajor = devmajor self.devminor = devminor self.prefix = prefix def set_offset(self, offset): self.offset = offset def usage(): u = """ Usage: tar.py <archive.tar> --list List all files in the archive tar.py <archive.tar> --extract-all Extract all files from the archive tar.py <archive.tar> --extract <file> Extract single file from the archive """ print(u) sys.exit(1) if __name__ == "__main__": try: if len(sys.argv) > 2: archive = sys.argv[1] operation = sys.argv[2] with Tar(archive) as t: if operation == "--list": files = t.get_all_files() for f in files: print(f) elif operation == "--extract-all": t.extract_all() elif operation == "--extract": if len(sys.argv) > 3: file_name = sys.argv[3] t.extract_file(file_name) else: usage() else: usage() except Exception as e: print("Error: {}".format(str(e))) sys.exit(1) tartest.py #!/usr/bin/env python3 import unittest import tar import os class TarTest(unittest.TestCase): def test_get_all_files(self): # given with tar.Tar("tartest.tar") as t: # when files = t.get_all_files() # then self.assertTrue(len(files) == 5) self.assertTrue(self.containsFile(files, "tartest/a.txt")) self.assertTrue(self.containsFile(files, "tartest/b.txt")) self.assertTrue(self.containsFile(files, "tartest/foo/c.txt")) def test_extract_file(self): # given with tar.Tar("tartest.tar") as t: # when t.extract_file("tartest/a.txt") t.extract_file("tartest/foo/c.txt") # then self.assertTrue(os.path.isfile("a.txt")) self.assertTrue(self.fileContains("a.txt", "This is file a")) self.assertTrue(os.path.isfile("c.txt")) self.assertTrue(self.fileContains("c.txt", "This is file c")) os.remove("a.txt") os.remove("c.txt") def test_extract_all(self): # given with tar.Tar("tartest.tar") as t: # when t.extract_all() # then self.assertTrue(os.path.isdir("tartest")) self.assertTrue(os.path.isdir("tartest/foo")) self.assertTrue(os.path.isfile("tartest/a.txt")) self.assertTrue(os.path.isfile("tartest/b.txt")) self.assertTrue(os.path.isfile("tartest/foo/c.txt")) os.system("rm -rf tartest") def containsFile(self, files, file_name): for f in files: if f.file_name == file_name: return True return False def fileContains(self, file_name, content): with open(file_name) as f: return content == f.read().splitlines()[0] if __name__ == '__main__': unittest.main() A: I can offer some tips for making your code more pythonic. General It's good practice to add a docstring for each module, class, and documented function. Imports io and json are unused. In the Tar.__extract method, the variable total is unused. class Tar not file_path or len(file_path) == 0: If the user inputs an empty string, not file_path is sufficient (and None is not a possible value unless input manually). More to the point, you are not exactly detecting a "bad file path". You could use os.path.exists for a more robust check. Alternatively, don't validate the path at all, and consider a try... except OSError block in your __enter__ method; this will avoid race conditions. (You perform similar checks in extract_file and extract_all that can also be changed.) You have an __enter__ method and an __exit__ method, which allows your class to be used with a context-manager, excellent! However, you also provide a close function, without providing a corresponding open function, which means that close could never be reasonably called by the user. Eliminate close or add open. You invoke name-mangling by using double-underscores on methods like __extract; this is fine to prevent truly "private" data members from clashing with those from a superclass or subclass, but on methods it makes inheriting from your class (say, to extend it with logging features) unnecessarily difficult. To mark a member as "private", a single leading underscore is enough. Similarly, in the interest of being able to subclass your class, you should consider self.BLOCK_SIZE instead of Tar.BLOCK_SIZE (though maybe this is a constant of the tar format?). list(map(...)): It's generally more clear to replace this with a list comprehension (and as opposed to lambda, sometimes more performant): def get_all_files(self): self._scan() return [FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag) for f in self.headers] list(filter(...)): To get the first match, it's generally better to use a generator comprehension: def extract_file(...): ... try: result = next(fh for fh in self.headers if fh.flag == 0 and fh.file_name == file_name) except StopIteration: raise RuntimeError("File '{}' not found".format(file_name)) ... class FileSnapshot, class FileHeader There is a lot of boilerplate code here, that could be eliminated with e.g. the @dataclass decorator. from dataclasses import dataclass ... @dataclass class FileSnapshot: file_name : str file_size : int ... __repr__ methods are generally supposed to return code that will reproduce the object; consider renaming this method to __str__ instead. __main__ Take advantage of the standard library argparse module. For example, it makes extending your --extract switch to extract multiple files easier, provides error checking and usage strings, and can be used to initialize archive as a Tar automatically. from argparse import ArgumentParser ... if __name__ == '__main__': parser = ArgumentParser(description='.tar archive extractor') parser.add_argument('archive', type=Tar, help='...') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', action='store_true', help='List files') group.add_argument('--extract-all', action='store_true', help='Extract all') group.add_argument('--extract', nargs='+', help='Extract some') args = parser.parse_args() with args.archive as t: ... Code Here's my take on your code #!/usr/bin/env python3 '''TODO: docstring''' import os import math from dataclasses import dataclass class Tar: '''TODO docstring''' BLOCK_SIZE = 512 def __init__(self, file_path): self.file_path = file_path self.input_stream = None self.headers = [] def __enter__(self): self.input_stream = open(self.file_path, "rb") self.headers = [] return self def __exit__(self, exc_type, exc_value, exc_traceback): if self.input_stream is not None: self.input_stream.close() def get_all_files(self): '''TODO docstring''' self._scan() return [FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag) for f in self.headers] def extract_file(self, file_name, target_folder=os.getcwd()): '''TODO docstring''' self._scan() try: fh = next(fh for fh in self.headers if fh.flag == 0 and fh.file_name == file_name) except StopIteration: raise RuntimeError("File '{}' not found".format(file_name)) leaf = os.path.basename(fh.file_name) f_path = os.path.join(target_folder, leaf) self._extract(fh, f_path) def extract_all(self, target_folder=os.getcwd()): '''TODO docstring''' self._scan() for fh in self.headers: f_path = os.path.join(target_folder, fh.file_name) if fh.flag == 5: # if directory os.makedirs(f_path, exist_ok=True) elif fh.flag == 0: # if regular file parent = os.path.dirname(os.path.abspath(f_path)) os.makedirs(parent, exist_ok=True) self._extract(fh, f_path) def _extract(self, fh, file_name): with open(file_name, "wb") as f: if fh.file_size > 0: bytes_left = fh.file_size self.input_stream.seek(fh.offset, 0) while bytes_left > 0: data = self.input_stream.read(Tar.BLOCK_SIZE) data = data[:bytes_left] f.write(data) bytes_left -= len(data) def _scan(self): # iterate over headers if len(self.headers) == 0: while True: block = self.input_stream.read(Tar.BLOCK_SIZE) if len(block) < Tar.BLOCK_SIZE: break h = self._get_file_header(block) if not len(h.magic) > 0: break # omit regular file bytes if h.flag == 0: h.offset = self.input_stream.tell() if h.file_size > 0: if h.file_size % Tar.BLOCK_SIZE != 0: bytes_to_skeep = math.ceil(h.file_size / Tar.BLOCK_SIZE) * Tar.BLOCK_SIZE else: bytes_to_skeep = h.file_size self.input_stream.seek(bytes_to_skeep, 1) self.headers.append(h) def _get_file_header(self, block): try: return FileHeader( self._get_file_name(block), self._get_file_size(block), self._get_file_mode(block), self._get_uid(block), self._get_gid(block), self._get_mtime(block), self._get_chksum(block), self._get_type_flag(block), self._get_linkname(block), self._get_magic(block), self._get_version(block), self._get_uname(block), self._get_gname(block), self._get_devmajor(block), self._get_devminor(block), self._get_prefix(block) ) except Exception as e: raise RuntimeError("Broken file") from e def _get_file_name(self, block): # string offset, size = 0, 100 fname = self._get_block_data(block, offset, size) fname = fname[0:fname.find(b'\x00')].decode().strip() return fname def _get_file_mode(self, block): # string offset, size = 100, 8 mode = self._get_block_data(block, offset, size) mode = mode[:mode.find(b'\x00')].decode().strip() return mode def _get_uid(self, block): # string offset, size = 108, 8 uid = self._get_block_data(block, offset, size) uid = uid[:uid.find(b'\x00')].decode().strip() return uid def _get_gid(self, block): # string offset, size = 116, 8 gid = self._get_block_data(block, offset, size) gid = gid[:gid.find(b'\x00')].decode().strip() return gid def _get_file_size(self, block): # int offset, size = 124, 12 size = self._get_block_data(block, offset, size) size = size[:size.find(b'\x00')].decode().strip() if len(size) > 0: size = int(size, 8) else: size = 0 return size def _get_mtime(self, block): # int offset, size = 136, 12 mtime = self._get_block_data(block, offset, size) mtime = mtime[:len(mtime)-1] mtime = mtime[:mtime.find(b'\x00')].decode().strip() if len(mtime) > 0: mtime = int(mtime, 8) else: mtime = 0 return mtime def _get_chksum(self, block): # int offset, size = 148, 8 chksum = self._get_block_data(block, offset, size) chksum = chksum[:chksum.find(b'\x00')].decode().strip() if len(chksum) > 0: chksum = int(chksum) else: chksum = 0 return chksum def _get_type_flag(self, block): # int offset, size = 156, 1 flag = self._get_block_data(block, offset, size) if flag == b'\x00': flag = 0 elif flag == b'x': flag = 11 else: flag = int(flag) return flag def _get_linkname(self, block): # string (applicable if type_flag = 1 or 2) offset, size = 157, 100 linkname = self._get_block_data(block, offset, size) return linkname[:linkname.find(b'\x00')].decode().strip() def _get_magic(self, block): # string offset, size = 257, 6 magic = self._get_block_data(block, offset, size) magic = magic[:magic.find(b'\x00')].decode().strip() return magic def _get_version(self, block): # string offset, size = 263, 2 version = self._get_block_data(block, offset, size) version = version[:len(version)-1].decode().strip() return version def _get_uname(self, block): # string offset, size = 265, 32 uname = self._get_block_data(block, offset, size) uname = uname[:uname.find(b'\x00')].decode().strip() return uname def _get_gname(self, block): # string offset, size = 297, 32 gname = self._get_block_data(block, offset, size) gname = gname[:gname.find(b'\x00')].decode().strip() return gname def _get_devmajor(self, block): # string offset, size = 329, 8 devmajor = self._get_block_data(block, offset, size) devmajor = devmajor[:devmajor.find(b'\x00')].decode().strip() return devmajor def _get_devminor(self, block): # string offset, size = 337, 8 devminor = self._get_block_data(block, offset, size) devminor = devminor[:devminor.find(b'\x00')].decode().strip() return devminor def _get_prefix(self, block): # string offset, size = 345, 155 prefix = self._get_block_data(block, offset, size) prefix = prefix[:prefix.find(b'\x00')].decode().strip() return prefix def _get_block_data(self, block, offset, size): return block[offset:offset+size] @dataclass class FileSnapshot: '''TODO: docstring''' file_name: str file_size: int file_mode: str flag: int def __str__(self): return self.file_name @dataclass class FileHeader: '''TODO: docstring''' file_name: str file_size: int file_mode: str uid: str gid: str mtime: int chksum: int flag: int linkname: str magic: str version: str uname: str gname: str devmajor: str devminor: str prefix: str offset: int = 0 if __name__ == "__main__": def main(): from argparse import ArgumentParser parser = ArgumentParser(description='.tar archive extractor') parser.add_argument('archive', type=Tar, help='The tar archive file') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', action='store_true', help='List all files in the archive') group.add_argument('--extract-all', action='store_true', help='Extract all files from the archive') group.add_argument('--extract', nargs='+', dest='files', help='Extract specified files from the archive') args = parser.parse_args() with args.archive as t: if args.list: files = t.get_all_files() for file in files: print(file) elif args.extract_all: t.extract_all() else: for file in args.files: t.extract_file(file) main()
{ "pile_set_name": "StackExchange" }
Q: Advance knowledge of community deletions? My answer to a question from 2016, https://math.stackexchange.com/questions/1792625/is-the-sine-of-a-transcendental-angle-transcendental-or-algebraic was downvoted a couple of hours ago, and then a minute later the question was deleted by the Community user. I assume the downvote was cast in order to pave the way for the deletion, but how did the downvoter know that the Roomba was making its rounds and would be there in a minute? A: I think that it is relatively safe to assume that the tasks which run daily are scheduled on the same time. (Similarly, scripts which run once a week/once a month are most likely scheduled on the same day of the week/month and on the same time or at least near the same time.)1 So if somebody noticed on a few occasions that roomba deleted questions around 03:00 AM, it is natural to expect the same time on other days. You can have a look at a graph showing distribution of deletion time of questions to see that the biggest peek is around this time. (I have purposely looked only at deletions of questions - not at all posts - since we're talking about roomba.) Similarly, you can see clusters of deleted questions around this time if you look at time of deletions of questions - to do this, you can use some of the queries mentioned in this answer. It is difficult to say whether or not some users actually prefer to downvote shortly before the scheduled task - since we do not have data on times of downvotes2 and the Votes table does not contain data for deleted posts. 1To be more precise, the weekly roomba task actually runs 7 days since the last run, according to this answer: What is the cause of this sudden drop in CV queue size? The same answer confirms 3 AM as the scheduled time for the daily roomba task. (This answer was also quoted here: Why does the Unanswered Question count drop on Saturdays?) 2 Votes table and timeline only show date for votes. See: Why is vote time missing in the SE data dump and SEDE?
{ "pile_set_name": "StackExchange" }
Q: How to combine all columns of a dataframe into one column? I have a dataframe with all columns named "Standard Deviation", 265 columns in total. I want to combine them all in this way: a b c d 0 a0 b0 c0 d0 1 a1 b1 c1 d1 2 a2 b2 c2 d2 3 a3 b3 c3 d3 4 a4 b4 c4 d4 becomes A 0 a0 1 a1 2 a2 3 a3 4 a4 5 b0 6 b1 7 b2 8 b3 9 b4 10 c0 11 c1 12 c2 13 c3 14 c4 15 d0 16 d1 17 d2 Stack() combines them in a different way. I've tried concat but get an error: df = pd.concat(df['Standard Deviation'], ignore_index=True) >>TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" Here is what the dataframe looks like: Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation ... Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation Standard Deviation 0 5.7735e-05 N/A 5.7735e-05 N/A N/A N/A N/A N/A N/A N/A ... N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A 1 0.00050914 N/A 0.000337704 N/A 8.27103 N/A N/A N/A N/A N/A ... N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A 2 7.61074e-05 N/A 1.35277e-05 N/A 1.73205 N/A N/A N/A N/A N/A ... N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A 3 2.74651e-05 N/A 1.85562e-05 N/A 270 N/A N/A N/A N/A N/A ... N/A N/A N/A N/A N/A N/A N/A N/A N/A N/A A: Option 1: column = pd.Series(df.values.flatten()) # or df if you want Oprtion 2: df.melt().drop('variable',axis=1)
{ "pile_set_name": "StackExchange" }
Q: Element wise sum of two fixed length arrays of integers Say i have two fixed length arrays of unsigned integers. How do i element wise sum those arrays (into first) without looping or with a lesser number loops? uint64_t foo[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; uint64_t bar[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ... // funky code without loop so that // foo now is {0, 2, 4, 6, 8, 10, 12, 14, 16, 18} The related question: is it possible to sum multiple uint64_t integers in one operation?. (i bet this could be done with sse) The question in general is: what is the fastest way to sum two fixed length arrays of integer type (in place into first one)? A: You can use _mm_add_epi64 to add two 64 bit ints per iteration. I wouldn't expect a dramatic improvement over straight scalar code though. If you don't want an explicit loop then you can just unroll this into 5 operations.
{ "pile_set_name": "StackExchange" }
Q: assertion in first order logic Can anybody give me an idea how to write this assertion in in first order logic? X has not passed one or more of the prerequisites for A. Here, X is the name of a person and A is a constant representing a course name. A: Expressing properties of elements of the universe in first order logic is mostly achieved through defining appropriate relations. So for this you might like to consider relations like: $P(x)$ - $x$ is a person, $C(x)$ - $x$ is a course, $Pre(x,y)$ - $x$ is a prerequisite of $y$ (note that this doesn't actually say that $x$ and $y$ are courses), $Pass(x,y)$ - $x$ has passed course $y$. (The parentheses are just included for clarity - you may have seen different notation where relations are written without.) Then the rest is just building the logical formula, which in this case should be fairly obvious. $notready(x,a) \equiv P(x) \wedge C(a) \wedge \exists y(C(y) \wedge Pre(y,a) \wedge \neg Pass(x,y)) $
{ "pile_set_name": "StackExchange" }
Q: Evaluating $\sum_{r=0}^{10}\frac{\binom{10}{r}}{\binom{50}{30+r}}$ The question is to evaluate $$\sum_{r=0}^{10}\frac{\binom{10}{r}}{\binom{50}{30+r}}$$I tried rewriting the expression as $$\sum_{r=0}^{10}\frac{\binom{20-r}{10}\binom{30+r}{r}}{\binom{50}{30}\binom{20}{10}}$$ I am facing trouble on how to further simplify the numerator.Any ideas?Thanks. A: $$\begin{align} \sum_{r=0}^{10}\frac {\displaystyle\binom {10}r}{\displaystyle\binom{50}{30+r}} &=\frac {\color{blue}{\displaystyle\sum_{r=0}^{10}\displaystyle\binom {20-r}{10}\binom {30+r}{30}}}{\color{}{\displaystyle\binom {50}{20}\binom {20}{10}}}\\\\ &=\frac {\color{blue}{\displaystyle\binom {51}{41}}}{\color{green}{\displaystyle\binom {50}{20}\binom {20}{10}}} &&\scriptsize\color{blue}{\text{using }\sum_{r=0}^{a-b}\binom {a-r}b\binom {c+r}d=\binom {a+c+1}{b+d+1}}\\\\ &=\frac {\displaystyle\binom {51}{10}}{\color{green}{\displaystyle\binom {50}{10}\binom {40}{10}}} &&\scriptsize \color{green}{\text{using }\color{green}{\binom ab\binom bc=\binom ac\binom {a-c}{b-c}}} \\\\ &= \frac {51\cdot 10!\;30!}{41!}\\\\ &=\color{red}{\frac 3{2\; 044\; 357\; 744}}\\\\ \end{align}$$ See also wolframalpha confirmation here and here. NB: The first line makes use of the following: $$\begin{align} \binom {20}{10}\binom {10}r&=\binom {20}r\binom {20-r}{10} &&\scriptsize\text{using }\binom ab\binom bc=\binom ac\binom {a-c}{b-c}\\ \color{orange}{\binom {50}{20}}\binom {20}{10}\binom {10}r&=\color{orange}{\binom {50}{20}}\binom {20}r\binom {20-r}{10} &&\scriptsize\text{multiplying by }\binom {50}{20}\\ \color{purple}{\binom{50}{10}\binom{40}{10}}\binom{10}r &=\binom {50}{20}\binom {20}r\binom{20-r}{10} &&\scriptsize\text{using }\binom ab\binom bc=\binom ac\binom {a-c}{b-c}\\ &=\color{green}{\binom{50}{30+r}\binom{30+r}{30}}\binom{20-r}{10} &&\scriptsize\text{using }\binom ab\binom {a-b}c=\binom a{b+c}\binom {b+c}{b}\\ \frac{\displaystyle\binom{10}r}{\displaystyle\binom{50}{30+r}}&= \frac {\displaystyle\binom{20-r}{10}\binom{30+r}{30}}{\displaystyle\binom {50}{10}\binom {40}{10}} \end{align}$$
{ "pile_set_name": "StackExchange" }
Q: no find() method on xml object After extracting the tags I require from an xml document I have two set of tags that I want to iterate over. For one of the sets I get the message: Uncaught TypeError: Object #<Element> has no method 'find' I find this strange as I get them in the same way and if I write them to the console they are there. var rows = response.getElementsByTagName("row"); for(var i = 0; i < rows.length; ++i) { var northWalls = rows[i].getElementsByTagName("north"); var westWalls = rows[i].getElementsByTagName("west"); console.log(westWalls); //this prints as I expect for(var j = 0; j < northWalls.length; ++j) { var x = cellWidth * j; var y = cellWidth * i; if(i != 0 && northWalls[j].find("north").text() == false) {//north drawWall(ctx, x, y, x + cellWidth, y); } if(j != 0 && westWalls[j].find("west").text() == false) { //this find method gives the error drawWall(ctx, x, y, x, y + cellWidth); } } } Why would one of these give me this error and not the other one. [EDIT]After the advice from @sabof I ended up with this: for(var i = 0; i < rows.length; ++i) { var northWalls = rows[i].getElementsByTagName("north"); var westWalls = rows[i].getElementsByTagName("west"); for(var j = 0; j < northWalls.length; ++j) { var x = cellWidth * j; var y = cellWidth * i; if(i != 0 && northWalls[j].firstChild.nodeValue === "false") {//north drawWall(ctx, x, y, x + cellWidth, y); } if(j != 0 && westWalls[j].firstChild.nodeValue === "false") {//west drawWall(ctx, x, y, x, y + cellWidth); } } } A: a) JavaScript arrays don't have a .find method. You are probably looking for .indexOf. b) .getElementsByTagName returns a pseudo-array, and pseudo-arrays don't have array methods. .indexOf returns an index of the found element, or -1, if nothing is found. It can be "forced" on a pseudo array like this: Array.prototype.indexOf.call(theArray, 'thing') There are other errors in your code. Chances are you are confusing the API of DOM elements, with the jQuery API.
{ "pile_set_name": "StackExchange" }
Q: Can I completely exclude a pane title? I'd like to apply several panes without title to a panel (in Drupal 7). I can select Override title and leave the input field blank, but this still leaves the wrapping HTML. <div class="panel-heading"> <h2 class="panel-title"></h2> </div> Can I completely exclude a title? A: I learnt adding <none> to the title field does this.
{ "pile_set_name": "StackExchange" }
Q: How to structure many-to-many relationships in cosmos db I'm working on a new project and it was recommended to me that I have a look at Cosmos DB to use for my data store for it because it's going to be a global SaaS application servicing potentially hundreds of thousands of users. As this is my first foray into NoSQL databases I've inevitably run into a lot of things I have to learn but I feel like I've been slowly getting it and have actually become quite excited about it. Now here comes the kicker: I have a relatively simple data structure that I just can't seem to wrap my head around how you'd implement and I've pretty much resigned to the fact that it might just be a workload which doesn't really work well in non-relational databases. But as I said I'm completely green so I'm here for a sanity check in case there's something obvious that I'm missing I have a data structure consisting of a "user" object and a "post" object and I need to relate them based on unbounded arrays of tags to basically create customized feeds they look like this User: { id: 1, name: "username", interests: [ "fishing", "photography", "stargazing", ] } Post: { id: 1, title: "My post title", body: "My post content", tags: [ "tennis", "sport", "photography", ] } I want to return a list of all posts which has one or more of a given users interests in their tags so basically a query like this: SELECT DISTINCT VALUE Posts FROM Posts JOIN tag IN Posts.Tags WHERE tag IN <<user.interests>> In SQL I'd create a table of users and a table of posts and join them based on shared tags/interests but I can't for the life of me figure out how to denormalize this (if possible). Have I really run into one of the impossible flows of NoSQL on my first attempt with only 2 objects? Or am I just being a total noob? A: You're on the right track! There are two really good articles that describe how to model data for NoSQL. Definitely worth a read if you're new to this type of data store. Data modeling in Azure Cosmos DB, in particular the section on many-to-many relationships. and How to model and partition data on Azure Cosmos DB using a real-world example Hope you find this helpful.
{ "pile_set_name": "StackExchange" }
Q: ListView scroll to selected item I have a ListView with an edit text and a button below it. When I click on a listView item the keyboard appears and push up the edit text and the button. I want the list to scroll to the selected item. Any idea? Thanks A: You can use ListView's setSelection(int position) method to scroll to a row. A: You could use ListView's smoothScrollToPosition(int position) to scroll to a particular location in the list. A: For a direct scroll: getListView().setSelection(11); For a smooth scroll: getListView().smoothScrollToPosition(11); To Scroll to top getListView().setSelectionAfterHeaderView(); Note try to call it in post because sometime listview is not yet created while you calling it's method getListView().postDelayed(new Runnable() { @Override public void run() { lst.setSelection(15); } },100L);
{ "pile_set_name": "StackExchange" }
Q: Unwind works properly until I add a prepareForSegue I need help with this app I am building. If you need to see the full code, I can post it, but here is the scenario: I have 3 UIViewControllers, SMPViewController, SMPLetterViewController and SMPDetailsViewController. In SMPViewController I have a prepareForSegue, and an UnWind: -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ SMPLetterViewController *destination = [segue destinationViewController]; destination.lblSectionText = _lblForSectionTitles; } -(IBAction)returnToMain:(UIStoryboardSegue *)segue{ //just return to Home page } In SMPLetterViewController I have a prepareForSegue, an UnWind and a button titled, “Back” that connects with the UnWind of the SMPViewController: -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ SMPDetailsViewController *destination = [segue destinationViewController]; destination.lblTextLetter = _lblWordSort; } -(IBAction)returnToLetterList:(UIStoryboardSegue *)segue{ //just return to Letter page } In the SMPDetailsViewController, I have a button titled, “Home” which connects the UnWind of the SMPViewController, and a button titled, “Back” which connects with the UnWind of the SMPLetterViewController. When I run the program everything is working properly except the Back button on the SMPLetterViewController, it keeps crashing my App. with an error telling me something is wrong with the lblTextLetter in the prepareForSegue in the SMPLetterViewController. When I comment out the prepareForSegue in the SMPLetterViewController everything works great, except I cannot transfer the information to the SMPDetailsViewController. To me the prepareForSegue’s in both the SMPViewController and SMPLetterViewController syntax is correct so why does it not work and why is it singling out the lblTextLetter? Any ideas as to what is wrong? Do I just need another pair of eyes as I am missing something? Thanks for any help, socamorti A: In storyboard add segue identifier and change your prepareForSegue to something like that: -(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([[segue identifier] isEqualToString:@"YOUR_IDENTIFIER"]) { SMPDetailsViewController *destination = [segue destinationViewController]; destination.lblTextLetter = _lblWordSort; } } And do something like that for your second prepareForSegue as well. This issue happens because when you run unwind action the prepareForSegue is called as well.
{ "pile_set_name": "StackExchange" }
Q: How to execute code after selection of item in a form on ruby on rails? I'm on the form of training_project I have a select2 element: <%= f.input_field :contractId, collection: Contract.all, prompt: 'Convenzione', class: 'form-control select2' %> after the user select the contract i need to do: <% @contract = Contract.find(@training_project.contractId) @training_project.farmId = @contract.farmId @farm = Farm.find(@training_project.farmId) if @training_project.farmId && Farm.exists?(@training_project.farmId) %> All of this for get the farm info in relation with the contract selected. Thanks for your help! A: Two solutions, one without JS The form needs to be submitted to the server. For this you need a route, a controller and an action. and one with JS: You will need to register a change event and trigger an AJAX call to an action in a controller (see above). Please investigate this a bit further and then give more details if you need more help. Also please note that in Ruby snake_case os preferred over camelCase. So i suggest you change contractId to contract_id and so on.
{ "pile_set_name": "StackExchange" }
Q: Advice for reference the same image for several nodes? I need to show the same image for a several nodes. I have uploaded the image to the server. But, I am not sure how to accomplish or reference this using the image field. Do you have any experience that you can share it? or any other way that I can do this? A: In my case the easiest was to do the following steps: In content/media add the picture. In your content type create a field type File. Save your content type. When you add your new content, in your new field, use select media and choose the file that just upload it. Note: If you delete the new content and there is no other content that reference that picture or file, the file will be deleted and you need to upload it again. I created my content by using web services. So, I needed to do this programatically. The only I needed was the fid. In my case I need to use services to create the content type, after testing you need the following and to tell if it should be displayed or not. This is the code in case anyone feels it is useful. $node->field_file_name_field ['und'][0]['fid']='fid number'; $node->field_file_name_field['und'][0]['display']='1'; If you feel there is a better way or another way to do this. It be great to hear it.
{ "pile_set_name": "StackExchange" }
Q: Can I have RequiredFieldValidator to check for more than one ControlToValidate? I am having 3 TextBoxes in a row and then a Next button. On clicking Next button, the control would go to the next page only if ALL of the 3 TextBoxes contain some user-entered text. Is there any option by which I can check whether all of the TextBoxes contain some text by using RequiredFieldValidator (rather than going for different RequiredFieldValidator for each ControlToValidate)? I am currently having following code: <tr> <td class="style1"> <asp:Label ID="lblDOB" runat="server" Font-Bold="True" Font-Italic="False" Font-Size="Medium" ForeColor="Black" Text="Date of Birth"></asp:Label> </td> <td> <asp:TextBox ID="txtA" runat="server" Width="45px"></asp:TextBox> <asp:TextBox ID="txtB" runat="server" Width="45px"></asp:TextBox> <asp:TextBox ID="txtC" runat="server" Width="45px"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="txtA" ErrorMessage="Please enter Text"> </asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="txtB" ErrorMessage="Please enter Text"> </asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="txtC" ErrorMessage="Please enter Text"> </asp:RequiredFieldValidator> </td> </tr> So, instead of having 3 different RequiredFieldValidators, I want to use only a single RequiredFieldValidator which checks if all the 3 TextBoxes contain some text. How can I achieve this? A: Your best bet is to use CustomValidator and combine with either client side javascript or server side c#/vb.net code.
{ "pile_set_name": "StackExchange" }
Q: Google Spreadsheets API with OAuth2.0 using Javascript I'm trying to access a private Google Spreadsheet using Javascript. I have sucessfully authorized with OAuth2.0 and can see a listing of all my Google Drive docs. What I can't seem to do is get into a specific spreadsheet. Code is as follows with the relevant spreadsheet code in the function "retrieveAllFiles". A lot of this is culled from Google tutorials. var clientId = 'working'; var apiKey = 'working'; var scopes = 'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds'; function handleClientLoad() { console.log('inside handleClientLoad function'); gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); } function checkAuth() { console.log('inside checkAuth function'); gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); console.log('finished checkAuth function'); } function handleAuthResult(authResult) { console.log('inside handleAuthResult function'); var authButton = document.getElementById('authButton'); authButton.style.display = 'none'; if (authResult && !authResult.error) { //Access token has been succesfully retrieved, requests can be sent to the API. apiCalls(); } else { //No access token could be retrieved, show the button to start the authorization flow. authButton.style.display = 'block'; authButton.onclick = function() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); }; } } function apiCalls() { console.log('inside apiCalls function'); gapi.client.load('drive', 'v2', function() { retrieveAllFiles(callback); }); } function retrieveAllFiles(callback) { $.get('http://spreadsheets.google.com/feeds/spreadsheets/private/full', function(data) { console.log('get request processed'); console.log(data); }); console.log('inside retrieveAllFiles function'); var retrievePageOfFiles = function(request, result) { request.execute(function(resp) { result = result.concat(resp.items); var nextPageToken = resp.nextPageToken; if (nextPageToken) { request = gapi.client.drive.files.list({ 'pageToken': nextPageToken }); retrievePageOfFiles(request, result); } else { callback(result); } }); } var initialRequest = gapi.client.drive.files.list(); retrievePageOfFiles(initialRequest, []); } function callback(result) { console.log('all should be loaded at this point'); console.log(result); $('#drive-list').append('<ul class="items"></ul>'); $.map(result, function(v,i){ $('.items').append('<li>' + v.title + ':' + v.id + '</li>'); }); } So to be clear, the end result currently is a listing of all my Google Drive docs, but no console.log for "get data processed". I'm not getting any error messages in the console, so I can't tell what is going on. Thanks. A: Final solution compiled from a bunch of different sources, hopefully this will help someone. var scopes = 'https://spreadsheets.google.com/feeds'; var clientId = 'working'; var apiKey = 'working'; function handleClientLoad() { console.log('inside handleClientLoad function'); gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth,1); } function checkAuth() { console.log('inside checkAuth function'); gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); console.log('finished checkAuth function'); } function handleAuthResult(authResult) { console.log('inside handleAuthResult function'); console.log(gapi.auth.getToken()); var authButton = document.getElementById('authButton'); authButton.style.display = 'none'; if (authResult && !authResult.error) { //Access token has been successfully retrieved, requests can be sent to the API. loadClient(); } else { //No access token could be retrieved, show the button to start the authorization flow. authButton.style.display = 'block'; authButton.onclick = function() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); }; } } function loadClient() { console.log('inside loadClient function'); var token = gapi.auth.getToken().access_token; var urlLocation = ''; //Get this from the URL of your Spreadsheet in the normal interface for Google Drive. //This gives a spitout of ALL spreadsheets that the user has access to. var url = 'https://spreadsheets.google.com/feeds/spreadsheets/private/full?access_token=' + token; //This gives a list of all worksheets inside the Spreadsheet, does not give actual data var url = 'https://spreadsheets.google.com/feeds/worksheets/' + urlLocation + '/private/full?access_token=' + token; //This gives the data in a list view - change the word list to cells to work from a cell view and see https://developers.google.com/google-apps/spreadsheets/#working_with_cell-based_feeds for details var url = 'https://spreadsheets.google.com/feeds/list/' + urlLocation + '/od6/private/full?access_token=' + token; console.log(url); $.get(url, function(data) { console.log(data); }); }
{ "pile_set_name": "StackExchange" }
Q: Cannot call `JSON.parse` with `localStorage.getItem(...)` Just added Flow types to a project I'm working on and progressively adding types until I got to this error: Cannot call JSON.parse with localStorage.getItem(...) bound to text because null or undefined [1] is incompatible with string [2] This comes from a expression: const myVar = JSON.parse(localStorage.getItem('itemName')) I understand why I get this error (except maybe the "bound to text" part), but couldn't find a way around it. I'd appreciate any help here! A: So, the function localStorage.getItem can return null values and flow wants you to tackle them before parsing it. As JSON.parse only takes a string, you can do the following: localStorage.getItem("key") || '{}' So, if it returns null. The empty object string is chosen, which JSON.parse can parse into an empty object.
{ "pile_set_name": "StackExchange" }
Q: Creating Python button saves edited file I'm new with tkinter and was wondering if anyone can point me in the right direction. I'm wondering on how to over write a previously saved file without the saveasdialog, like how an actual save function would be implemented. I'm currently using it to save a .txt file with different points for my project. The save as function works. Would I have to find the directory and change it somehow? Is there any easier way to do this? Heres what I have so far for both save and saveas: def saveFile(self): method = self.method.current() try: with open(self.f,'w') as outputFile: if(method==0): method.write() except AttributeError: self.save_as def saveFileAs(self): f = filedialog.asksaveasfile(mode='w', defaultextension=".txt") method = self.method.current() #used to write to .txt file and does save if(method == 0): # f.write() to save to .txtfile A: If you want a save function that silently overwrites the current file, the basic thing to do is save a reference to the file name/location that the user chose, and then the next time you save you can reuse it instead of asking for a new one. The following (taken from a program of mine) has a "plain" save function that checks if there's a save file name on record, and either uses it (if it exists) or goes to the "save as" function. The plain version happens to have a return value so that it can interact with a load (open) function elsewhere in the program (asks the user whether to save unsaved work before loading a new file). def save_plain(self, *args): """ A plain save function. If there's no preexisting file name, uses save_as() instead. Parameter: *args: may include an event """ if self.savename: # if there's a name self.save(self.savename) # then use it elif self.save_as(): # else, use save_as instead return True # successful save returns True return False # else, return False def save_as(self, *args): """ A save as function, which asks for a name and only retains it if it was given (canceling makes empty string, which isn't saved). Parameter: *args: may include an event """ temp = filedialog.asksaveasfilename(defaultextension=".txt", \ filetypes=(('Text files', '.txt'),('All files', '.*'))) # ask for a name if temp: # if we got one, self.savename = temp # retain it self.save(temp) # and pass it to save() return True return False def save(self, filename): """ Does the actual saving business of writing a file with the given name. Parameter: filename (string): the name of the file to write """ try: # write the movelist to a file with the specified name with open(filename, 'w', encoding = 'utf-8-sig') as output: for item in self.movelist: output.write(item + "\n") self.unsaved_changes = False # they just saved, so there are no unsaved changes except: # if that doesn't work for some reason, say so messagebox.showerror(title="Error", \ message="Error saving file. Ensure that there is room and you have write permission.")
{ "pile_set_name": "StackExchange" }
Q: How do I prove it formally? If $f(z)=\sum_{k=0}^\infty a_k z^k$ and $g(z)=\sum_{k=0}^\infty b_k z^k$ are two power series whose radii of convergence are $1$. Let the product of $f.g$ has a power series representation $\sum_{k=0}^\infty c_k z^k$ on the open disk. Is the statement true or false? My attempt:- I took $a_k=1$ and $b_k=1$ , By Cauchy's product $c_k=k+1$. $\sum_{k=0}^\infty c_k z^k$. So, it is convergence in the unit disk. The statement is true. How do I prove it formally? A: The Cauchy-Hadamard Radius Formula implies $\lim \sup_{k\to \infty}|a_k|^{1/k}\le 1\ge \lim \sup_{k\to \infty}|b_k|^{1/k}.$ For $r>0$ let $S(r)=\{0\}\cup \{k>0: |a_k|^{1/k}\ge 1+r \lor |b_k|^{1/k}\ge 1+r\}.$ Then $S(r)$ is finite. Let $M(r)=\max S(r).$ Let $P(r)=\max \{\max \{|a_k|,|b_k|\}: k\le M(r)\}.$ Let $c_k=\sum_{i=0}^k a_i b_{k-j}.$ Given $r>0,$ consider any $k$ large enough that $k>3M(r)$ and $(1+r)^k>P(r).$ If $i+j=k$ then ......(I). If $M(r)< i<k-M(r)$ then $j>M(r)$ so $|a_ib_j|<(1+r)^i(1+r)^j=(1+r)^k<(1+r)^{2k}.$ .....(II). If $i\le M(r)$ then $j>M(r)$ so $|a_ib_j|\le P(r)(1+r)^j<(1+r)^k(1+r)^j\le (1+r)^{2k}.$ ....(III). If $i\ge k-M(r)$ then $j<M(r)<i$ so $|a_ib_j|\le (1+r)^iP(r)<(1+r)^i(1+r)^k\le(1+r)^{2k}.$ So for all sufficiently large $k$ we have $|c_k|^{1/k}\le (\,\sum_{i=0}^k|a_ib_{k-j}|\,)^{1/k}\le$ $ (\,\sum_{i=0}^k(1+r)^{2k}\,)^{1/k}=$ $=(1+r)^2(1+k)^{1/k}.$ Since $\lim_{k\to \infty}(1+k)^{1/k}=1,$ we infer that $\lim \sup_{k\to \infty}|c_k|^{1/k}\le (1+r)^2 $ for every $r>0,$ and hence $\lim \sup_{k\to \infty}|c_k|^{1/k}\le 1.$ The C-H Radius Formula then implies that $\sum_kc_kx^k$ converges whenever $|x|<1.$
{ "pile_set_name": "StackExchange" }
Q: What is wrong with my use of the Compass @font-face mixin? I'm including the Open Sans font in my website by using SASS and the Compass font-face mixin as follows: @include font-face("Open Sans", font-files( "../fonts/opensans-light/OpenSans-Light-webfont.woff", "../fonts/opensans-light/OpenSans-Light-webfont.ttf", "../fonts/opensans-light/OpenSans-Light-webfont.svg#open_sanslight" ), "../fonts/opensans-light/OpenSans-Light-webfont.eot", 200); @include font-face("Open Sans", font-files( "../fonts/opensans-regular/OpenSans-Regular-webfont.woff", "../fonts/opensans-regular/OpenSans-Regular-webfont.ttf", "../fonts/opensans-regular/OpenSans-Regular-webfont.svg#open_sansregular" ), "../fonts/opensans-regular/OpenSans-Regular-webfont.eot", normal); @include font-face("Open Sans", font-files( "../fonts/opensans-semibold/OpenSans-Semibold-webfont.woff", "../fonts/opensans-semibold/OpenSans-Semibold-webfont.ttf", "../fonts/opensans-semibold/OpenSans-Semibold-webfont.svg#open_sanssemibold" ), "../fonts/opensans-semibold/OpenSans-Semibold-webfont.eot", 600); @include font-face("Open Sans", font-files( "../fonts/opensans-bold/OpenSans-Bold-webfont.woff", "../fonts/opensans-bold/OpenSans-Bold-webfont.ttf", "../fonts/opensans-bold/OpenSans-Bold-webfont.svg#open_sansbold" ), "../fonts/opensans-bold/OpenSans-Bold-webfont.eot", bold); I formerly just used CSS3 @font-face as follows: @font-face { font-family: 'Open Sans'; src: url('../fonts/opensans-light/OpenSans-Light-webfont.eot'); src: url('../fonts/opensans-light/OpenSans-Light-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans-light/OpenSans-Light-webfont.woff') format('woff'), url('../fonts/opensans-light/OpenSans-Light-webfont.ttf') format('truetype'), url('../fonts/opensans-light/OpenSans-Light-webfont.svg#open_sanslight') format('svg'); font-weight: 200; font-style: normal; } @font-face { font-family: 'Open Sans'; src: url('../fonts/opensans-regular/OpenSans-Regular-webfont.eot'); src: url('../fonts/opensans-regular/OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans-regular/OpenSans-Regular-webfont.woff') format('woff'), url('../fonts/opensans-regular/OpenSans-Regular-webfont.ttf') format('truetype'), url('../fonts/opensans-regular/OpenSans-Regular-webfont.svg#open_sansregular') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'Open Sans'; src: url('../fonts/opensans-semibold/OpenSans-Semibold-webfont.eot'); src: url('../fonts/opensans-semibold/OpenSans-Semibold-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans-semibold/OpenSans-Semibold-webfont.woff') format('woff'), url('../fonts/opensans-semibold/OpenSans-Semibold-webfont.ttf') format('truetype'), url('../fonts/opensans-semibold/OpenSans-Semibold-webfont.svg#open_sanssemibold') format('svg'); font-weight: 600; font-style: normal; } @font-face { font-family: 'Open Sans'; src: url('../fonts/opensans-bold/OpenSans-Bold-webfont.eot'); src: url('../fonts/opensans-bold/OpenSans-Bold-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/opensans-bold/OpenSans-Bold-webfont.woff') format('woff'), url('../fonts/opensans-bold/OpenSans-Bold-webfont.ttf') format('truetype'), url('../fonts/opensans-bold/OpenSans-Bold-webfont.svg#open_sansbold') format('svg'); font-weight: bold; font-style: normal; } Which worked perfectly well. And at the top of my scss file I have: @import "compass/css3/font-face"; A: Have look to your config.rb file would help but, assuming there nothing relative in it, the generated path in your css should look like this /{css_dir}/../fonts/opensans-semibold/OpenSans-Semibold-webfont.eot In your config.rb use relative_assets = true and set fonts_dir = "../fonts" otherwise by default your generated url will start with ```fonts/````. You can then use @include font-face( as you did but by discarding "../fonts" in your urls. If the folder containing the compiled css is outside your sass project then I recommend you to use http_fonts_path to avoid any mistake in urls. It will allow you to specify an absolute url starting from your app or website DocumentRoot directory. In the following example fonts files are placed in '/static/fonts' : config.rb http_fonts_path = "/static/fonts" # relative_assets = true # replace static by your public asset folder path !! comment relative_assets = true if you use http_fonts_path !! my.scss* @include font-face("Open Sans", font-files( "opensans-semibold/OpenSans-Semibold-webfont.woff", "opensans-semibold/OpenSans-Semibold-webfont.ttf" ), "opensans-semibold/OpenSans-Semibold-webfont.eot" ); Run compass clean after each change to config.rb
{ "pile_set_name": "StackExchange" }
Q: Is there any memory limitation for saving .mp3 data to iOS device using iOS application I am developing an application, that has a module downloading MP3 files from a server and save the last 5 downloads to iOS device. For this I am using NSFileManager and document directory (each downloads has 40MB to 60MB). Now I am facing some issues, that is four downloads save successfully and during the 5th download time the application automatically delete the first downloads and some time the app shows crashes. My question is, is there any memory limitation for save large file (above 500MB) to iOS device? If any limitation, what is the maximum size? A: As per my knowledge Apple uses HFS Plus file system, and it can have max file size up to 8 exabyte 1 EB = 1000000000000000000B = 1018 bytes = 1000000000gigabytes = 1000000terabytes Hope this will help you
{ "pile_set_name": "StackExchange" }
Q: SAS: Cannot use where or if condition for specific variable. I have a dataset which has a variable. I could do proc freq to show following table: However I would like to output the observations were serumt=0.3: data new; set AIM12_OAW; where serumt=0.3; run; I got error message as following: NOTE: No observations were selected from data set WORK.AIM12_OAW. NOTE: There were 0 observations read from the data set WORK.AIM12_OAW.WHERE serumt=0.3; I tried where serumt=0.21 still no observations. The weird thing was if I did where serumt=0.12 it would output one observation (should be 6). If I did proc freq data=aim12_onw; table serumt; by serumt; run; The output would be: I cannot understand why the variable serumt could not be selected by where or if statement. I did check the format of serumt. It looks normal for me. I have no idea how to deal with this variable. Thank you so much for comments. A: Sounds like it might be a floating point precision issue - try something like where round(serumt,0.01) = 0.30.
{ "pile_set_name": "StackExchange" }
Q: Making ReasonML/Bucklescript output ES5 compatible code While using ReasonML and Bucklescript, is it possible to configure Bucklescript so it won't generate export statements? I'd prefer if the generated code could be used as is in a browser, that is, being ES5 (or ES6) compatible. Edit: OK, while trying out the tool chain a bit more, I realize just turning off the export is not enough. See example below: function foo(x, y) { return x + y | 0; } var Test = /* module */[ /* foo */foo ]; exports.Test = Test; This code will pollute global namespace if exports is removed, and is simply broken from an ES5 compatibility viewpoint. Edit 2: Reading on Bucklescript's blog, this seems not possible: one OCaml module compiled into one JavaScript module (AMDJS, CommonJS, or Google module) without name mangling. Source. A: BuckleScript can output modules in a number of different module formats, which can then be bundled up along with their dependencies using a bundler such as webpack or rollup. The output is not really intended to be used as a stand-alone unit, since you'd be rather limited in what you could do in any case, as the standard and runtime libraries are separate modules. And even something as trivial as multiplication will involve the runtime library. You can configure BuckleScript to output es6 modules, which can be run directly in the browser as long as your browser supports it. But that would still require manually extracting the standard and runtime libraries from your bs-platform installation. The module format is configured through the package-specs property in bsconfig.json: { ... "packages-specs": ["es6-global"] /* Or "es6" */ } Having said all that, you actually can turn off exports by putting [@@@bs.config { no_export }] at the top of the file. But this is undocumented since it's of very limited use in practice, for the above mentioned reasons.
{ "pile_set_name": "StackExchange" }
Q: How to using Objective C Class in Swift framework? I'm coding a swift framework project, needs to call functions from other objective-c framework, when I try to using bridge header, I got error, Is possible to using Objective C class in Swift framework project ? UPDATED: the error was :0: error: using bridging headers with framework targets is unsupported Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1 A: My solution is to wrap the Objective-C classes to a framework, then import the framework to my swift framework.
{ "pile_set_name": "StackExchange" }
Q: How to combine two cells experience into one We have gathered data from participants for job. Now we have data in the form given below. Experience-1(Cell1) (5 Years 4 Month) Experience-2(Cell2) (4 Year 9 Month) Now want to combine both cells experience and want to calculate the total experience like 10 Years 1 Month A: Suppose the wording for experiences will always be in the form of x Year(s) y Month(s), and all experiences are listed in a column such as below: Presume you have given a name to the above list as List_Exp, you can use the following array formula, which needs to be confirmed by pressing Ctrl+Shift+Enter in the formula bar, to find the total months first: =SUMPRODUCT(--TRIM(MID(SUBSTITUTE(List_Exp," ",REPT(" ",100)),{1,200},100)),IF(ROW($A$1:INDEX($A:$A,ROWS(List_Exp)))>0,{12,1})) Here I used TRIM+MID+SUBSTITUTE+REPT functions to extract the year and month figure from the original string, which is {5,4;4,9;1,2;1,1;10,9} from the above example, then use SUMPRODUCT to work out the total months by finding corresponding multipliers {12,1;12,1;12,1;12,1;12,1} using IF+ROW+INDEX functions. Then you can convert the Total Months to Years and Months as shown below: If you do not want to use helper cells (Cell D3:D6) in the above example, you can give a name to the Total Months figure as Ttl_Mth, and combine the following formulas into one: Figure for Years: =INT(Ttl_Mth/12) Word for Years: ="Year"&IF(INT(Ttl_Mth/12)>1,"s","") Figure for Months: =MOD(Ttl_Mth,12) Word for Months: ="Month"&IF(MOD(Ttl_Mth,12)>1,"s","") Combined: =INT(Ttl_Mth/12)&" "&"Year"&IF(INT(Ttl_Mth/12)>1,"s","")&" "&MOD(Ttl_Mth,12)&" "&"Month"&IF(MOD(Ttl_Mth,12)>1,"s","") Please see below a test result for a new list of experiences: [Hint] I recommend to convert the list of experiences into a Table before giving a name to the list. The benefit is that each time you add or replace values in the list (which is actually a one-column table), the named range will be automatically updated so the calculations will also be updated automatically.
{ "pile_set_name": "StackExchange" }
Q: How to split an RTF file into lines? I am trying to split an RTF file into lines (in my code) and I am not quite getting it right, mostly because I am not really grokking the entirety of the RTF format. It seems that lines can be split by \par or \pard or \par\pard or any number of fun combinations. I am looking for a piece of code that splits the file into lines in any language really. A: I coded up a quick and dirty routine and it seems to work for pretty much anything I've been able to throw at it. It's in VB6, but easily translatable into anything else. Private Function ParseRTFIntoLines(ByVal strSource As String) As Collection Dim colReturn As Collection Dim lngPosStart As Long Dim strLine As String Dim sSplitters(1 To 4) As String Dim nIndex As Long ' return collection of lines ' ' The lines can be split by the following ' ' "\par" ' ' "\par " ' ' "\par\pard " ' ' Add these splitters in order so that we do not miss ' ' any possible split combos, for instance, "\par\pard" is added before "\par" ' ' because if we look for "\par" first, we will miss "\par\pard" ' sSplitters(1) = "\par \pard" sSplitters(2) = "\par\pard" sSplitters(3) = "\par " sSplitters(4) = "\par" Set colReturn = New Collection ' We have to find each variation ' ' We will look for \par and then evaluate which type of separator is there ' Do lngPosStart = InStr(1, strSource, "\par", vbTextCompare) If lngPosStart > 0 Then strLine = Left$(strSource, lngPosStart - 1) For nIndex = 1 To 4 If StrComp(sSplitters(nIndex), Mid$(strSource, lngPosStart, Len(sSplitters(nIndex))), vbTextCompare) = 0 Then ' remove the 1st line from strSource ' strSource = Mid$(strSource, lngPosStart + Len(sSplitters(nIndex))) ' add to collection ' colReturn.Add strLine ' get out of here ' Exit For End If Next End If Loop While lngPosStart > 0 ' check to see whether there is a last line ' If Len(strSource) > 0 Then colReturn.Add strSource Set ParseRTFIntoLines = colReturn End Function
{ "pile_set_name": "StackExchange" }
Q: Spring MVC resource versioning adding the ResourceUrlEncodingFilter I'm trying to get the new resource versioning from 4.1 working. From http://spring.io/blog/2014/07/24/spring-framework-4-1-handling-static-web-resources and http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-config-static-resources I can't seem to register the ResourceUrlEncodingFilter correctly. How do you do that so it picks up urls in jsp? I'm using javaconfig and in my extended WebMvcConfigurerAdapter --> addResourceHandlers method I have registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/META-INF/resources/static/") .resourceChain(true) .addResolver( new VersionResourceResolver() .addFixedVersionStrategy("1.1.0", "/**/*.js") .addContentVersionStrategy("/**")); This seems to work as I can get the changes in a controller @Autowired private ResourceUrlProvider resourceUrlProvider; @RequestMapping(value = "/test", method = RequestMethod.GET) public String homePub() { logger.debug("js = '{}'", this.resourceUrlProvider.getForLookupPath("/static/test.js")); logger.debug("css = '{}'", this.resourceUrlProvider.getForLookupPath("/static/test.css")); return "test"; } Will output DEBUG TestController - js = '/static/1.1.0/test.js' DEBUG TestController - css = '/static/styles/test-4c517674c05348b2aa87420e7adc420b.css' Initially urls in jsp's are ignored so I added container.addFilter("resourceUrlEncodingFilter", ResourceUrlEncodingFilter.class).addMappingForUrlPatterns( null, true, "/*"); To my implementation of WebApplicationInitializer This gives the exception below java.lang.IllegalStateException: Failed to determine lookup path: /test/static/test.js So at least I know the filter is being called it just hasn't picked up my handlers I tried adding a resource handler for /test/static/** as well but that didn't help. Changing the isMatchAfter to false stops the exception but the filter doesn't seem to be called. The jsp is question is very simple <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %> <c:url value='/static/test.js'/> So I guess that's not how to set up the ResourceUrlEncodingFilter, how should it be added A: There seems to be a bug https://jira.spring.io/browse/SPR-12279 You need to add @Override public HandlerMapping resourceHandlerMapping() { SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) super.resourceHandlerMapping(); handlerMapping.setInterceptors(this.getInterceptors()); return handlerMapping; } And extend WebMvcConfigurationSupport instead of WebMvcConfigurerAdapter There are other problems https://jira.spring.io/browse/SPR-12281 And the securityFilter causes it problems but the above should get the basics working Update: release of 4.1.2 solves these problems
{ "pile_set_name": "StackExchange" }
Q: Form post to db only once, php a form is posted to db only once, i have to delete the row in db for the form to post new form data again. I tried several modifications from internet but didnt allowed me to post after the first successful time Form: <form action="post.php" method="POST"> <h5>A form:</h5> <input class="right-inputs" id="field1" type="number" name="field1" placeholder="Enter stuff"> <input class="right-inputs" id="field2" type="text" name="field2" value="" readonly> <script src="js/insert.js"></script> <button class="btn-cmn" type="submit" name="submit">post</button> </form> post.php: <?php include_once 'db.php'; $var1 = $_POST['field1']; $var2 = $_POST['field2']; $sql = "INSERT INTO `a_table` (column1, column2) VALUES ('$var1', '$var2')"; mysqli_query($conn, $sql); mysqli_close($conn); header("Location: page.php?post=success"); ?> db.php: <?php $dbServername = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "database_sample"; $conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName); ?> your table structure look like : A: I think You have Primary Key in your table that not automatic generate value. So you can't add more row while have same Primary key.. Make sure you generate unique key for primary or have auto increment number for this.
{ "pile_set_name": "StackExchange" }
Q: Finding all values x and y of with complex numbers pt.2 Thank you for your help last time. This time, the problem is different. It is: $$\frac{x+yi+2+3i}{2x+2iy-3} = i+2$$ x and y are assumed to be real numbers. Basically my first trouble is knowing the conjugate of the denominator. Would it be $2x-2iy-3$ or $2x-2iy+3$? Secondly, I am unsure how to multiply the numerator by the denominator. I tried $(x+2)+i(y+3)\cdot (2x-3)+2iy$ or $(x+2)i(y+3) \cdot (2x+3) + 2iy $ depending on what the conjugate of the denominator is. Are either of these on the correct path? A: Write $2x+2iy-3$ as $(2x-3)+2yi$, so its conjugate is $(2x-3)-2yi$, but you don't need to multiply $(2x-3)+2yi$ by its conjugate. Just note that $$\frac{x+yi+2+3i}{2x+2iy-3} = i+2 \implies x+yi+2+3i=(2x+2iy-3)(i+2).$$ If we write every term in the form $a+bi$ we get $(x+2)+(y+3)i=((2x-3)+2yi)(2+i)$, then $(x+2)+(y+3)i=(4x-2y-6)+(2x+4y-3)i$. This lead us to the system: \begin{cases} x + 2 = 4x-2y-6 \\ y+3=2x+4y-3 \end{cases} with solution $x=\frac{36}{13}$ and $y=\frac{2}{13}$.
{ "pile_set_name": "StackExchange" }
Q: SWRevealViewController insertObject:atIndex object cannot be nil i'm a new developper with storyboard.i try to make a app with a slide-out menu. To do this, i use the library : SWRevealViewController and the tutorial : http://www.appcoda.com/ios-programming-sidebar-navigation-menu/ . i follow the tutorial, but i load the application, i'have this error : Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil' my app crash on this line : [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer]; how can i set self.revealViewController ? here my storyboard UPDATED: to understand my app, startviewController is used to download and store data, after downloading, the mainViewcontroller is showed. i want my slide out menu on my mainviewcontroller, but i cant not do. here the code i add to my mainviewController viewdidload : - (void)viewDidLoad { [super viewDidLoad]; self.contentView.autoresizesSubviews = YES; _sharedUser = [User sharedUser]; ///slide out menu // Change button color //SWRevealViewController *revealViewController = [self.navigationController.storyboard instantiateViewControllerWithIdentifier:@"RevealViewController"]; _sidebarButton.tintColor = [UIColor redColor]; // Set the side bar button action. When it's tapped, it'll show up the sidebar. _sidebarButton.target = self.revealViewController; _sidebarButton.action = @selector(revealToggle:); // Set the gesture [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer]; //end slide out self.contentView.backgroundColor = [UIColor cyanColor]; if (_sharedUser.tokenString) { } else{ [self showHomeWithoutLogginView]; } } A: I'm looking at the tutorial you are following. According to your screenshot, there are some stuff missing in your storyboard. The RevealViewController should be connected with two controllers: a front viewController (for displaying content) and a rear viewController (for showing the navigation menu): Credits for the image: http://www.appcoda.com/ios-programming-sidebar-navigation-menu/ Those connections (segues) should be marked as "reveal view controller" and each of them have to be named accordingly: "sw_front" and "sw_rear". Then you have to add the menu items in the navigation menu (rear view controller) and connect each cell to the corresponding viewController, give the segues a name and mark them as a SWRevealViewController class. You may want to connect the front view controller to the viewController you want to be shown first. I strongly suggest you make the tutorial as it is. I think I used it in the past and it worked pretty well. If you have any doubt about it don't hesitate to ask. Best of lucks!
{ "pile_set_name": "StackExchange" }
Q: SQL Server hash algorithms If my input length is less than the hash output length, are there any hashing algorithms that can guarantee no collisions. I know by nature that a one way hash can have collisions across multiple inputs due to the lossy nature of the hashing, especially when considering input size is often greater than output size, but does that still apply with smaller input sizes? A: Use a symmetric block cipher with a randomly chosen static key. Encryption can never produce a duplicate because that would prevent unambiguous decryption. This scheme will force a certain output length which is a multiple of the cipher block size. If you can make use a variable-length output you can use a stream cipher as well.
{ "pile_set_name": "StackExchange" }
Q: "Gray code" for building teams Motivation. In a team of $n$ people, we had the task to build subteams of a fixed size $k<n$ such that every day, $1$ person of the subteam is replaced by another person in the team, but not in the subteam (so that the new subteam consisted of $k$ again). The question arose if and for what choices of $k$ and $n$ the subteam schedule can be built to contain each choice of $k$ people out of the team exactly once. Formal version. For any set $X$ and positive integer $k$, let $[X]^k$ be the collection of subset of $X$ having $k$ elements. For $n\in\mathbb{N}$ let $[n] =\{1,\ldots,n\}$. For integers $1< k < n$ we define a graph $G(n, k)$ by $V(G(n,k)) = [[n]]^k$ and $$E(G(n,k)) = \big\{\{A, B\} : A, B \in [[n]]^k \land |A\cap B| = k-1\big\}.$$ For what choices of $1< k < n$ does $G(n,k)$ have a Hamiltonian path? Bonus question: Replace "path" by "cycle" in the original question. (The bonus question need not be answered for acceptance.) A: This seems to be possible for all choices of $k$ and $n$. I found a page here by Dr. Ronald D. BAKER describing a more than sixty year old 'revolving door algorithm'. When enumerating the k-element subsets of and n-set we are implicitly enumerating the partitions of the n-set into parts, one of size s=k and the other of size t=n-k. Hence the problem is often described as the enumeration of (s,t)-combinations. Suppose the think of the set as a collection of people and imagine them being divided into two adjacent rooms, k people in one room with the remaining n-k people in the other room. Now further imagine that there is a revolving door connecting the two rooms, and a change consists of an individual from each room entering that revolving door and exchanging sides. This analogy is the source of the moniker revolving door algorithm. W. H. Payne created the following algorithm in 1959. The call to visit might, for example, output the k-subset or it might do the computations of an algorithm which needs all k-element subsets. Each k-subset is referenced by an index-list $c_k \dots c_2c_1$, the indices of the elements belonging to the subset sorted in order. Notice the code makes extensive use of conditionals, the branching command goto and line labels†. algorithm RevDoorSubset(n, k) Array C[1..k+1] R1: for i ← 1 to k do // initialize C C[i] ← i-1 end for C[k+1] ← n R2: visit(C[ ], k) // Do whatever is needed w/ subset (just print?) R3: if (k is odd) // the easy cases if ( C[1]+1 < C[2] ) C[1] ← C[1]+1 goto R2 else j ← 2 goto R4 fi else if ( C[1] > 0 ) C[1] ← C[1]-1 goto R2 else j ← 2 goto R5 fi fi R4: if ( C[j] ≥ j ) // try to decrease C[j] C[j] ← C[j-1] C[j-1] ← j-2 goto R2 else j ← j+1 fi R5: if ( C[j] + 1 < C[j+1] ) // try to increase C[j] C[j-1] ← C[j] C[j] ← C[j] + 1 goto R2 else j ← j + 1 if ( j ≤ k) goto R4 fi fi return end I've converted the algorithm to JavaScript; I don't think MathOverflow supports Stack Snippets but I've managed to host a working demo here in the Sandbox on Meta Stack Exchange. Click the 'Run code snippet' below the code, change the values of $n$ and $k$ and click 'Generate'. You can also try it online here in case the Sandbox fails. It seems this algorithm produces Hamiltonian cycles, but to prove it I'll need some sleep first. A: The following recursive description of a revolving door sequence is taken from here, where it is also proved that it generates a Hamilton cycle. The $k$-subsets of $\{1,\dots,n\}$ are identified with the bitstrings of length $n$ with exactly $k$ entries equal to $1$. Let $R(k,n)$, denote the binary $\binom{n}{k}\times n$-matrix whose rows correspond to the required sequence of the $k$-sets. Then $$R(0,n)=\begin{pmatrix}0&0&\dots&0\end{pmatrix},\qquad R(n,n)=\begin{pmatrix}1&1&\dots&1\end{pmatrix},$$ and for $1\leqslant k\leqslant n-1$, we obtain $R(k,n)$ by writing down the $\binom{n-1}{k}$ rows of $R(k,n-1)$, putting an additional $0$ in front, and below this writing the $\binom{n-1}{k-1}$ rows of $R(k-1,n-1)$ in reverse order, putting an additional $1$ in front. The precise Knuth reference mentioned in a comment above is Section 7.2.1.3. Generating all combinations in TAOCP, Volume 4A - Combinatorial Algorithms, Part 1. Here's an interesting related result: If $n=2k-1$ then $\binom{n}{k}=\binom{n}{k-1}$, and we can hope that in the process every $(k-1)$-set is visited exactly once. That this is possible used to be the middle level conjecture which is now a theorem due to Torsten Mütze: Proof of the middle levels conjecture. Proceedings of the London Mathematical Society 112.4 (2016): 677-713. A: Theorem. The graph $G(n,k)$ is Hamiltonian if $n\ge3$ and $0\lt k\lt n$. Proof. If $k=1$ or $k=n-1$ it's obvious, because $G(n,k)\cong K_n$ in those cases. Now consider the graph $G=G(n,k)$ where $2\le k\le n-2$. Let $$S=\{A\in[[n]]^k:1\in A\},\quad S'=\{A\in[[n]]^k:1\notin A\}.$$ Since the induced subgraphs $G[S]$ and $G[S']$ are isomorphic to $G(n-1,k-1)$ and $G(n-1,k)$ respectively, they are Hamiltonian by the inductive hypothesis. Moreover, since the graphs are edge transitive, we can choose a Hamiltonian cycle $C$ in $G[S]$ containing the edge $$\{A,B\}=\{\{1,\dots,k\},\ \{1,\dots,k-1,k+1\}\}$$ and a Hamiltonian cycle $C'$ in $G[S']$ containing the edge $$\{A',B'\}=\{\{2,\dots,k,k+2\},\ \{2,\dots,k+1\}\}.$$ Now we get a Hamiltonian cycle in $G$ by removing the edges $\{A,B\}$ and $\{A',B'\}$ from $C\cup C'$, and replacing them with $\{A,A'\}$ and $\{B,B'\}$.
{ "pile_set_name": "StackExchange" }
Q: In $Z_2[i]$, why is $(1+i)(1+i) = 0$? $i\cdot i$ = $-1 = 1 \in Z_2$, so $(1+i)(1+i) = 1+i+i+1 = 2+2i = 2(1+i)$ Why does this equal 0? Where has my (modular) arithmetic gone wrong? A: As $2 \equiv 0 \mod 2$ Therefore, $2=0$ in $\mathbb Z_2.$
{ "pile_set_name": "StackExchange" }
Q: Looping UITapGestureRecognizer only added to last one not all of them So I'm up to the point that I'm creating UIViews programmatically based on the amount of an array which is returned from JSON. Everything seems to be going ok except for the loop which is supposed to add the tap to each of the views but it is only adding it to one view. Only prints on the last UIView. func addsubviews(howmany: Int) -> Void{ let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap")) for x in 1...howmany{ guard let v = UINib(nibName: "DealsView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? UIView else { return } v.translatesAutoresizingMaskIntoConstraints = false guard let lbl = v.viewWithTag(99) as? UILabel else { return } lbl.text = "Here is a new Label for Loop: " + "\(x)" self.allContainer.addSubview(v) v.backgroundColor = UIColor.white var horizontalConstratint1 = NSLayoutConstraint() var horizontalConstratint2 = NSLayoutConstraint() var verticalConstraint1 = NSLayoutConstraint() heightConstraint = v.heightAnchor.constraint(equalToConstant: 100) horizontalConstratint1 = v.leadingAnchor.constraint(equalTo: (v.superview?.leadingAnchor)!, constant: 10) horizontalConstratint2 = v.trailingAnchor.constraint(equalTo: (v.superview?.trailingAnchor)!, constant: -10) if prevView == nil{ verticalConstraint1 = v.topAnchor.constraint(equalTo: (v.superview?.topAnchor)!, constant: 20) }else { if let pv = prevView as? UIView { verticalConstraint1 = v.topAnchor.constraint(equalTo: (pv.bottomAnchor), constant: 20) } } NSLayoutConstraint.activate([horizontalConstratint1,horizontalConstratint2,verticalConstraint1]) prevView = v } if let pv = prevView as? UIView { print("final constratint") NSLayoutConstraint.activate([ self.allContainer.bottomAnchor.constraint(equalTo: pv.bottomAnchor, constant: 20) ]) } for views in self.allContainer.subviews{ print("adding views") views.addGestureRecognizer(tap) } } After some trial and error... The tap recognizer added for each loop: let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(sender:))) the action which will be where the action goes on the tap: func handleTap(sender: UITapGestureRecognizer) { // You can get the view here by writing let myv = sender.view print(myv) } A: You have just a single UITapGestureRecognizer before your view loop starts. AFAIK, tap gesture recognizers can only be attached to one view at a time. Check out this question. To solve this, try writing this line: let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap")) inside your view loop. To find out what view was tapped, make your selector handleTap take an argument like so: Selector("handleTap:") and the method itself like this: func handleTap(sender: UITapGestureRecognizer? = nil) { // You can get the view here by writing let v = sender.view }
{ "pile_set_name": "StackExchange" }
Q: How to continue the sequence of the unique numbers in the excel sheet after closing the userform? I am facing a problem in getting the sequence of the unique numbers(Serial number) when the userform is closed and opened later on. Firstly, when I fill the data in the userform everything is captured in the excel sheet perfectly with correct sequence; if I close the userform and run the code by filling the userform with new data the unique ID's are again starting from "1" but not according to the excel sheet row number which was previously saved. Below is the code I tried: Private Sub cmdSubmit_Click() Dim WB As Workbook Dim lr As Long Set WB = Workbooks.Open("C:\Users\Desktop\Book2.xlsx") Dim Database As Worksheet Set Database = WB.Worksheets("Sheet1") eRow = Database.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row lr = Database.Range("a65536").End(xlUp).Row With Sheets("Sheet1") If IsEmpty(.Range("A1")) Then .Range("A1").Value = 0 Else Database.Cells(lr + 1, 1) = Val(Database.Cells(lr, 1)) + 1 End If End With Database.Cells(eRow, 4).Value = cmbls.Text Database.Cells(eRow, 2).Value = txtProject.Text Database.Cells(eRow, 3).Value = txtEovia.Text Database.Cells(eRow, 1).Value = txtUid.Text Call UserForm_Initialize WB.SaveAs ("C:\Users\Desktop\Book2.xlsx") End Sub Private Sub Worksheet_Change(ByVal Target As Range) Dim maxNumber If Not Intersect(Target, Range("B:B")) Is Nothing Then ' don't run when more than one row is changed If Target.Rows.Count > 1 Then Exit Sub ' if column A in the current row has a value, don't run If Cells(Target.Row, 1) > 0 Then Exit Sub ' get the highest number in column A, then add 1 and write to the ' current row, column A maxNumber = Application.WorksheetFunction.Max(Range("A:A")) Target.Offset(0, -1) = maxNumber + 1 End If End Sub Private Sub UserForm_Initialize() With txtUid .Value = Format(Val(Cells(Rows.Count, 1).End(xlUp)) + 1, "0000") .Enabled = False End With With txtProject .Value = "" .SetFocus End With End Sub In this image if you see unique id's are repeating 1 and 2, but I need as 1,2,3,4.... A: I think this is where the issue is coming from. You need to re-calculate the last row every time the user form is Initialized. Private Sub UserForm_Initialize() Dim ws as Worksheet: Set ws = Thisworkbook.Sheets("Database") With txtUid .Value = Format(ws.Range("A" & ws.Rows.Count).End(xlUp) + 1, "0000") .Enabled = False End With With txtProject .Value = "" .SetFocus End With End Sub
{ "pile_set_name": "StackExchange" }
Q: functions that are great for timing code to run after a delay -- is "timing" an adjective or gerund? Source: JavaScript for Kids: A Playful Introduction to Programming by Nick Morgan Example: In this chapter, you learned how to write JavaScript that runs only when you want it to. The setTimeout and setInterval functions are great for timing code to run after a delay or at certain intervals. If you want to run code when the user does something in the browser, you can use events like click and mousemove, but there are many others. I'm a little bit confused with whether the word timing is used as an adjective that describes code or a gerund with code being the object of the verb timing. I'm leaning more toward the gerund option, however, because that simply makes much more sense here semantically. I'm not sure though. What do you think? A: Objects of prepositions want nouns or noun phrases, so for timing means timing has to be a noun. -ing forms of words that act as nouns are a form of verbal called gerunds. While gerunds work as nouns, since they are a verbal, they can take objects. So code is the object of the verbal timing.
{ "pile_set_name": "StackExchange" }
Q: tick to be displayed button on button and to reduce its opacity when it's clicked I would like for a tick to be shown and its opacity reduced on a button once it is clicked. #btnTicketType{ margin-bottom:2%; margin-top:10%; width:95%; height:15em; font-size:1.5em; } #seatnumber{ display:block; width:100%; text-align:center; font-size:1em; } #rectangle{ height:100%; width:100%; overflow:auto; outline-color:black; outline-style:solid; } <div id="rectangle"> <div class="col-md-3"> <button id="btnTicketType" class="btn btn-default">Button 1</button> <small id="seatnumber">Text 1</small> </div> <div class="col-md-3"> <button id="btnTicketType" class="btn btn-default">Button 2</button> <small id="seatnumber">Text 2</small> </div> <div class="col-md-3"> <button id="btnTicketType" class="btn btn-default">Button 3</button> <small id="seatnumber">Text 3</small> </div> } </div> <br /> It would be nice if also to reduce the opacity of the button once the tick shows so that the tick would be more prominent for the user. A: I've created a HTML/CSS/JavaScript snippet that does the following things: Includes a 'tick' on each button; and Once a button is clicked, it fades out You can see a working example on JSFiddle. Your question is a tad confusing, as the question title and body say different things: Display Tick on button and reduce opacity when its clicked Versus: I would like for a tick to be shown on a button once it is clicked. The CSS for this snippet can be easily modified to achieve either result. Working Snippet $( '.btnTicketType' ).click(function() { $(this).addClass('clicked-button'); }); .btnTicketType { margin-bottom: 2%; margin-top: 10%; width: 95%; height: 15em; font-size: 1.5em; transition: all 1s; } .seatnumber{ display: block; text-align: center; font-size: 1em; } #rectangle{ overflow: auto; outline-color: black; outline-style: solid; } .clicked-button { opacity: .1; } <link href="https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="rectangle"> <div class="col-md-3"> <button class="btnTicketType btn btn-default" value=""> <i class="fa fa-check" aria-hidden="true"></i> Button 1 </button> <small class="seatnumber">Text 1</small> </div> <div class="col-md-3"> <button class="btnTicketType btn btn-default" value=""> <i class="fa fa-check" aria-hidden="true"></i> Button 2 </button> <small class="seatnumber">Text 2</small> </div> <div class="col-md-3"> <button class="btnTicketType btn btn-default" value=""> <i class="fa fa-check" aria-hidden="true"></i> Button 3 </button> <small class="seatnumber">Text 3</small> </div> </div> Additional Notes A <button> element is semantically valid: The HTML <button> element represents a clickable button. A <button> element can contain other HTML elements if required: <button> elements are much easier to style than <input> elements. You can add inner HTML content (think <em>, <strong> or even <img>), and make use of :after and :before pseudo-element to achieve complex rendering while <input> only accepts a text value attribute. Based on the above definitions, I've used Font Awesome to add the check icon to your buttons. Your HTML incorrectly reused ID attributes. An id="btnTicketType" attribute must be unique, and cannot be reused in valid HTML. If you need to style multiple elements, it's better to use a class="btnTicketType" instead. I replaced the repeated ID attributes with classes instead for the HTML in my snippet. If you're using the <button> element in a <form>, the value="" attribute will be submitted with the form. From the MDN documentation: value The initial value of the button. It defines the value associated with the button which is submitted with the form data. This value is passed to the server in params when the form is submitted.
{ "pile_set_name": "StackExchange" }
Q: Missing ceph vfs module for Samba I am trying to use the samba ceph vfs module. I installed samba-vfs-modules but the ceph.so module doesn't show up in /usr/lib/x86_64-linux-gnu/samba/vfs/ This mailing list post would seem to indicate the version of samba I have should include this module. user@kubuntu:~$ cat /etc/issue Ubuntu 14.04.3 LTS \n \l user@kubuntu:~$ samba --version Version 4.1.6-Ubuntu Perhaps the ceph.so module has been broken out into a separate package? I used http://packages.ubuntu.com/ to search for the ceph.so filename but didn't pick up anything in any of the releases. Is this supposed to be installed from source or am I missing something? A: I did end up installing Samba from source to add direct support for the Ceph distributed file system and it worked beautifully. Using Samba to directly access Ceph did seem to work better then resharing either kernel or fuse mount points. I have not tried Erik's answer as the problem is already solved.
{ "pile_set_name": "StackExchange" }
Q: Threading in Producer-Consumer pattern first sorry about my bad english. I 've code this for reading .csv file, one by one and after read, it 'll be removed. The .csv file format is like this: ID Name ParentID ------------------------ 0 [Root] 1 A 0 2 B 0 3 C 1 4 D 2 and the result will be [Root] _A __C _B __D just like the tree. But I just can execute on 1 file and after the first time, the consumer never wakes up again, so please help me fix this or explain how call this reason and the way to fix. Thanks a lot. class Program { static ProducerConsumer PrdCos; static string[] file; static void Main(string[] args) { string directory = ""; PrdCos = new ProducerConsumer(); Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); directory = Input_directory(); file = null; while (true) { if (Check_exist(directory) == true) break; else { Console.WriteLine("Please Reinput \n"); directory = Input_directory(); } } file = Directory.GetFiles(directory, "*.csv"); Console.WriteLine("\n-------------------------Program Start------------------------------"); Thread thread = new Thread(new ThreadStart(consumeJob)); Thread thread2 = new Thread(new ThreadStart(procedureJob)); thread.IsBackground = true; thread2.IsBackground = true; thread.Start(); thread2.Start(); //delete file //for (int i = 0; i < file.Length; i++) // File.Delete(file[i]); Console.ReadLine(); while(Console.ReadKey(true).Key == ConsoleKey.Enter) { Console.WriteLine("press ctr + c to exit"); } } static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e){} static void procedureJob() { if (file.Length > 0) { foreach (string str in file) { PrdCos.Produce(str); Thread.Sleep(1000); } } } static void consumeJob() { List<string> a = new List<string>(); a = file.ToList(); //for(int i = 0; i<a.Count;i++) //{ PrdCos.Consume(); Thread.Sleep(100); //} } static string Input_directory() { string str = ""; Console.Write("Input file Directory: "); str = Console.ReadLine(); return str; } static bool Check_exist(string path) { int Count; string[] file; //string fileName = ""; string filePath; filePath = path; if (Directory.Exists(filePath) != true) // Check file path exist { Console.WriteLine("{0} is not valid Directory!!!", path); return false; } else { Count = Directory.GetFiles(filePath, "*").Length; file = Directory.GetFiles(filePath, "*.csv"); } if (Count == 0) { Console.WriteLine("Folder is Empty!!!"); return false; } if (Count > 0 && file.Length == 0) { Console.WriteLine("Input File not Valid!!!"); return false; } return true; } } public class ProducerConsumer { Queue queue = new Queue(); object locker = new object(); int node = 0; int NODE = 0; public void Produce(string path) { Console.WriteLine("Processing Produce"); lock (locker) { try { //foreach (string mPath in path) //{ var reader = new StreamReader(File.OpenRead(path)); System.Collections.Generic.List<string> Str1 = new System.Collections.Generic.List<string>(); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line.Split(',').Length > 3) { Console.WriteLine("File's Data Is Wrong Format!!!"); return; } Str1.Add(line); } reader.Close(); queue.Enqueue(Str1); Thread.Sleep(2000); //} } catch (Exception ex) { Console.WriteLine(ex); } } Console.WriteLine("Finished Processing Produce"); } public void Consume() { Console.WriteLine("Processing Consume"); List<string> ParentId = new List<string>(); DataRow[] row = { }; lock (locker) { try { if (queue.Count > 0) { foreach (System.Collections.Generic.List<string> str in queue) { try { node = 0; NODE = 0; NODE = str.Count() - 1; PrintData(str, 0, str); Console.WriteLine("\n"); } catch (Exception ex) { Console.Write(ex); } } Console.WriteLine("Finished Processing Consume"); Thread.Sleep(1000); } } catch (Exception ex) { Console.WriteLine(ex); } //while (queue.Count == 0) //{ // Monitor.Wait(locker); // queue.Dequeue(); //} //if (queue == null) // return; //Thread.Sleep(100); } } private void PrintWithIndent(string value, int indent) { node++; Console.WriteLine("{0}{1}", new string(' ', indent), value);// prtValue[1]); } public void PrintData(List<string> Str, int indent, List<string> StrMain) { List<string> child = new List<string>(); string[] Value = null; string[] ValueMain = null; for (int i = 0; i < Str.Count; i++) { if (node >= NODE) return; child = new List<string>(); ValueMain = Str[i].Split(','); if (Str[i].ToString() == StrMain[0].ToString()) continue; else PrintWithIndent(ValueMain[1], indent); foreach (string mStr in StrMain) { Value = mStr.Split(','); if (Value[2] == ValueMain[0]) child.Add(mStr); } child = child.OrderBy(x => (x.Split(',')[1])).ToList(); //Sort by Alphabet if (child.Count > 0) { PrintData(child, indent + 1, StrMain); } } } } A: The first problem I notice is that your consumer is ending. There are more problems than that though - I would suggest you throw it away and start again. First you need to make sure you properly understand the pattern. Then you need to relate the classic pattern to threading in .Net. Once you understand the conceptual level stuff, you should also investigate Parallel LINQ (PLINQ) and the Task Parallel Library (TPL) - using these for your producer/consumer will save a lot of time and bugs (no more locking, you can have threads that block while they wait, etc.). Here are some other references that may help: Most efficient way of writing a single producer/single consumer queue Efficient consumer thread with multiple producers An efficient way of starting an arbitrary number of consumer threads?
{ "pile_set_name": "StackExchange" }
Q: How can I specify an application name when logging in? I was looking at the login history of my Salesforce API account and I noticed there was a column for application name. I would love to be able to specify that when performing a login so I can determine which applications are logging in and when. Right now I am using the SOAP version of their API, but, I didn't see a property I could specify when logging in. A: REST API When using the REST API you need to create a Connected App (Setup/Create/Apps). The name of your connected application will be the name displayed in the application column. If someone knows how to specify a name for the SOAP API I would welcome someone to update my answer.
{ "pile_set_name": "StackExchange" }
Q: Get URL of actual page in MVC Controller On my MVC project I have a 'Contact Us' form on the footer of the Layout page so the 'Contact Us' form appears on each page of the website. I have to check each time the form is submitted, on which page was it, I mean the url of the page that submitted the 'Contact Us' form in its POST method. For example on the homepage: http://www.test.com/myWebSite.Site/Home I need the get: Home But the problem is that when I submit the form with a POST request, in the Action, Request.Url always gives me that: (The root of the Controller and the Action..) http://www.test.com/myWebSite.Site/Shared/SubmitContactForm I think that what I need is the URL of the step before... I am not sure how to do that, any idea? A: Just a thought (if I understand your question correctly, apologies if not): In your layout page contact form, add two hidden inputs to pass in and use: <input type="hidden" name="currentAction" value="@ViewContext.RouteData.Values["Action"].ToString()"> <input type="hidden" id="currentController" value="@ViewContext.RouteData.Values["Controller"].ToString()"> this will give you the exact controller and action served even though your form is located on the shared layout view
{ "pile_set_name": "StackExchange" }
Q: What exactly does 'Wipe available diskspace' do? One of the options offered when you right click the desktop or within a Nautilus window is "wipe available diskspace." I'd think that means all unused diskspace but assumptions can be dangerous. I don't want to try it only to find out that available meant "all". I can't remember seeing this option before 12.04. I was asked to provide an image but unfortunately when right clicking to get the drop down menu, the print screen function doesn't respond thereby making an image impossible. It appears that no responder so far has actually used this nautilus option. Jorge suggested that the feature was actually nautilus-wipe and I verified that is the case by removing nautilus-wipe and seeing that the menu option is now gone. Documentation for nautilus-wipe is almost non-existent and what little I found was superficial and contradictory. This doesn't leave me with a warm and fuzzy feeling regarding my using an application or feature that purports to "wipe disk" without a clear definition of what is wiped. A: I think you are correct. It would wipe the available disk space and not system files or personal files. Unless wipe has changed from the days of 9.10 it "should" be fine to use. As a side note, there are other utilities in the repos that work like bleachbit if security is a factor for you.
{ "pile_set_name": "StackExchange" }
Q: Can't open downloaded video with PhoneGap I download my files with: var fileTransfer = new FileTransfer(); fileTransfer.download( url, target, .. ); And then i open them later with: window.open(targetUrl, '_blank', 'location=no'); It works for PDF, XLX, DOCX etc. but not for AVI or MP4. It opens the Video Player with a Play Button and a 'loading..' Text. If i try to open the AVI or MP4 directly it plays the files just fine. What am I doing wrong? Thanks! Edit: I use a iPad Edit2: The Error: webView:didFailLoadWithError - 204: Plug-in handled load A: I found the solution to my question: Streaming of Videos in the browser is supported and playing local files is not. A native plugin will do the trick
{ "pile_set_name": "StackExchange" }
Q: Fixing /etc/network/interfaces I recently tried to get my USB to Ethernet adaptor working (see this question, it's currently not working), since my computers built-in ethernet adaptor started becoming flaking and often simply stops working. While browsing the web in hope of finding a solution I tried numerous suggestions and modified my /etc/network/interfaces and /etc/NetworkManager/NetworkManager.conf a number of times, without saving, unfortunately, the original. Now my network manager GUI looks crazy (for privacy I "blued out" my Wifi connection) How can I revert it to the original? The /etc/network/interfaces and /etc/NetworkManager/NetworkManager.conf currently read auto eth0 allow-hotplug eth0 iface eth0 inet dhcp resp. auto eth0 allow-hotplug eth0 iface eth0 inet dhcp[main] plugins=ifupdown,keyfile,ofono dns=dnsmasq [ifupdown] managed=true A: Create a live USB with the same version of Ubuntu that you are using. Boot from it Mount your hard drive Copy the files you want to revert from the live image to your installation hard drive. Reboot and remove the USB Alternatively, you can boot the iso in a Virtualbox. In my Ubuntu 16.04, those files look like this: /etc/network/interfaces # interfaces(5) file used by ifup(8) and ifdown(8) auto lo iface lo inet loopback /etc/NetworkManager/NetworkManager.conf [main] plugins=ifupdown,keyfile,ofono dns=dnsmasq [ifupdown] managed=false
{ "pile_set_name": "StackExchange" }
Q: Clicking the Firebase dynamic link does not call the application (_: continue: restorationHandler :) method in AppDelegate Using Firebase Dynamic Links, I want to be able to click a link to open an iOS app. The app is under development and is not yet on the AppStore. I set it while looking at the document, but even if the app is started by clicking the link, the application (_: continue: restorationHandler :) method in AppDelegate is not called. I set it according to the following procedure. Is something wrong?   Add "pod 'Firebase / DynamicLinks'" to Podfile and install Open the .xcworkspace file Create Dynamic Links “https://XXXX.page.link/test” Access “https://XXXX.page.link/apple-app-site-association” {"applinks":{"apps":[],"details":[{"appID":"XXXXXXX.[Bundle ID]","paths":["NOT /_/","/"]}]}} Create a URL type to use for dynamic links Enable "Associated Domains" and add "applinks: XXXX.page.link" Implement AppDelegate as below import UIKit import Firebase import FirebaseDynamicLinks @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in // ... } return handled } @available(iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool { return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "") } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) { // Handle the deep link. For example, show the deep-linked content or // apply a promotional offer to the user's account. // ... return true } return false } } A: I was calling the scene method of SceneDelegate. class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let rootView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: rootView) self.window = window window.makeKeyAndVisible() } guard let userActivity = connectionOptions.userActivities.first(where: { $0.webpageURL != nil }) else { return } print("url: \(userActivity.webpageURL!)") } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { print("url: \(userActivity.webpageURL!)") } ... }
{ "pile_set_name": "StackExchange" }
Q: Python nested list comprehension (accessing nested elements) I'm having trouble understanding the syntax here. matrix_a = [[1, 2], [3, 4], [5, 6]] matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [a for a, b in matrix_a] output: [1, 3, 5] [a for b, a in matrix_a] output: [2, 4, 6] I understand a little about how list-comprehensions work, but I don't understand the syntax when accessing certain elements within a nested list. I just can't wrap my head around this syntax. How is this syntax working? What does the comma represent? What does a for a mean? Can you explain whats going on under the hood? And finally how would you do this with matrix_b A: If you convert it to a for loop it might be easier to see..? res = [] for item in matrix_a: a, b = item # a = item[0]; b = item[1] res.append(a) you're basically unpacking the individual items in the list and picking one of them.
{ "pile_set_name": "StackExchange" }
Q: dojoConfig can't find script assets when running on IIS I have the following simplified project structure | |-app.js |-components | | | |-someModule.js my dojoConfig looks like this: dojoConfig = { async: true, tlmSiblingOfDojo: false, packages: [{ name: "components", location: '/components' }], cacheBust: true }; I am loading those files like this: define(["esri/geometry/webMercatorUtils", "esri/map", "components/CoordinateTransutils", "components/SettingsManager" ], function(WebMercatorUtils, Map, CoordinateTransUtils, SettingsManager) { } ); locally I am developing using nodes http-server, which does work fine. Deployed on IIS however I am receiving errors which do look like this: Failed to load resource: the server responded with a status of 404 (Not Found) init.js:41 Error: scriptError at d (init.js:15) at HTMLScriptElement.<anonymous> (init.js:40) (anonymous) @ init.js:41 init.js:41 src: dojoLoader init.js:41 info: Array(2)0: "/components/CoordinateTransUtils.js?1496989376094"1: Eventlength: 2__proto__: Array(0) The problem at hand is: why is it working on a local dev server, but not on IIS? A: I use something like this: var dojoConfig = (function () { var base = location.href.split("/"); base.pop(); base = base.join("/"); return { async: true, isDebug: true, packages: [{ name: "components", location: base + "/components" }] }; })(); and it works without problem both locally and on IIS server.
{ "pile_set_name": "StackExchange" }
Q: Calling factory from directives controller in Angular.js I am trying to learn Angular.js, I am using ng-boiler-plate to manage my test application. However I have ran into a ptoblem and can't see the reason for it not working. Basically I am trying to inject a Factory and then call it from a directives controller. However when I try to call it I get an error reporting the factory name (in this case dashboardFac) is undefined. I will include the directive and factory below: Directive: angular.module( 'locationSelector', [ 'ngBoilerplate.locationFactory' ] ) .directive( 'locationSelector', function() { return { restrict: 'A', //template: '<h3>asdfasdfasd</h3>', templateUrl : 'components/locationSelector/locationSelector.tpl.html', link: function( scope, element, attrs ) { console.log("link working "); var $input = angular.element( document.querySelector( '#location' ) ); $input.bind('focus', function() { console.log("stay focused son"); }); }, controller: function($scope, dashboardFac, $element){ $scope.locyTexy = ""; $scope.api = dashboardFac; console.log($scope.api); $scope.change = function() { console.log("asdfasd"); dashboardFac.assets.getLocations().then(function(result){ }); }; } }; }) ; Factory: angular.module( 'ngBoilerplate.locationFactory', [ ]).factory('dashboardFac', function($http, $q){ this.assets = { getLocations: function(args) { var deferred = $q.defer(); var parmUrl = "will be some url eventually"; $http.jsonp({ method: 'GET', url: parmUrl }). success(function(data, status) { deferred.resolve(data); }). error(function(data, status) { deferred.reject(data); }); return deferred.promise; } }; }); Any help would be greatly apprieacted, I have a feeling I am missing something fundamental but hopefully someone can help point me in the right direction. Thanks in advance. A: You must inject dashboardFac factory to directive: .directive( 'locationSelector', function(dashboardFac) { […] })
{ "pile_set_name": "StackExchange" }
Q: Getting ORA-00918: column ambiguously defined: running this SQL: SELECT Name AS "Avatar Name", COUNT(WEAPON_ID) AS "Active Weapons Held |", SUM(W.COST) AS "Total Weapons Cost" FROM Avatar A, Weapon_Held H, Weapon W WHERE A.Avatar_ID=H.AVATAR_ID AND H.WEAPON_ID=W.WEAPON_ID Group by Name; A: First, never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Second, use table aliases, but use them everywhere: SELECT Name AS "Avatar Name", COUNT(H.WEAPON_ID) AS "Active Weapons Held", SUM(W.COST) AS "Total Weapons Cost" FROM Avatar A JOIN Weapon_Held H ON A.Avatar_ID = H.AVATAR_ID JOIN Weapon W ON H.WEAPON_ID = W.WEAPON_ID Group by Name; A: You're getting the error because you have multiple tables in your query that have the same name and it doesn't know where to pull it from. Try changing your query to the following: SELECT A.Name AS "Avatar Name", COUNT(H.WEAPON_ID) AS "Active Weapons Held |", SUM(W.COST) AS "Total Weapons Cost" FROM Avatar A JOIN Weapon_Held H ON A.Avatar_ID=H.AVATAR_ID JOIN Weapon W ON H.WEAPON_ID=W.WEAPON_ID Group by A.Name;
{ "pile_set_name": "StackExchange" }
Q: Fastest way to search value in a python dictionaries containing arrays I have a python dictionary of below format : {'Company': [{'doc': 'Apple', 'applicable_for': None, 'is_default': 0}, {'doc': 'Microsoft', 'applicable_for': None, 'is_default': False}], 'Branch': [{'doc': 'California', 'applicable_for': None, 'is_default': 0}, {'doc': 'Boston', 'applicable_for': None, 'is_default': False}]} What is the best way to know if "Apple" exist inside key "company". A: Fast if you return as soon as possible: def has_apple(d): for company in d["company"]: if(company["doc"] == "apple"): return True return False This returns true just after found the company without iterating further
{ "pile_set_name": "StackExchange" }
Q: 2 Variables in a Python 'all' Function I am trying to use a python 'all' function to evaluate a set of conditions. I want to use 2 different for loops in the function but I am not sure if this can be done. Here is what I am trying to do: Box = all([counter != puzzleBoard[x][y] for x in range(9) and y in range(9)]) I want to check if a variable counter is equal to any of the spaces on my 9x9 board. I have tried a few variation of for loops and and statements but haven't found anything that works yet. A: Your list-comprehension has a syntax error, change the and to for to create a nested for loop like so Box = all([counter != puzzleBoard[x][y] for x in range(9) for y in range(9)]) Also note that you can use a generator function instead of list comprehension too Box = all(counter != puzzleBoard[x][y] for x in range(9) for y in range(9))
{ "pile_set_name": "StackExchange" }
Q: Method disassembly of Objective C Mach-O with Radare 2 Is is possible to retrieve the dissassembly of Objective-C methods declared in Mach-O files using Radare 2 ? A: Essentially, it's the following workflow: r2 -A /path/to/binary // load the binary and perform initial analysis afl // print function symbols pdf @sym.of.interest // disassemble pdc @sym.of.interest // "decompile" or generate pseudo code Here is an example of how to disassemble a function of MachoViewer: @0x4B6169:/$ r2 -A /Applications/MachOView.app/Contents/MacOS/MachOView 2>/dev/null -- Run .dmm* to load the flags of the symbols of all modules loaded in the debugger [0x100001da0]> afl | grep sym.__MachOLayout_get 0x10000b252 4 49 sym.__MachOLayout_getSectionByIndex:_ 0x10000b283 4 49 sym.__MachOLayout_getSection64ByIndex:_ 0x10000b2b4 4 49 sym.__MachOLayout_getSymbolByIndex:_ 0x10000b2e5 4 49 sym.__MachOLayout_getSymbol64ByIndex:_ 0x10000b316 4 49 sym.__MachOLayout_getDylibByIndex:_ [0x100001da0]> pdf @sym.__MachOLayout_getSymbolByIndex:_ ;-- func.10000b2b4: ;-- method.MachOLayout.getSymbolByIndex:: ╒ (fcn) sym.__MachOLayout_getSymbolByIndex:_ 49 │ 0x10000b2b4 55 push rbp │ 0x10000b2b5 4889e5 mov rbp, rsp │ 0x10000b2b8 89d0 mov eax, edx │ 0x10000b2ba 488b151f760f. mov rdx, qword [rip + 0xf761f] ; [0x1001028e0:8]=176 LEA sym._OBJC_IVAR___MachOLayout.symbols ; sym._OBJC_IVAR___MachOLayout.symbols │ 0x10000b2c1 488b0c17 mov rcx, qword [rdi + rdx] │ 0x10000b2c5 488b541708 mov rdx, qword [rdi + rdx + 8] ; [0x8:8]=0x280000003 │ 0x10000b2ca 4829ca sub rdx, rcx │ 0x10000b2cd 48c1fa03 sar rdx, 3 │ 0x10000b2d1 4839d0 cmp rax, rdx │ ┌─< 0x10000b2d4 7306 jae 0x10000b2dc │ │ 0x10000b2d6 488b04c1 mov rax, qword [rcx + rax*8] │ ┌──< 0x10000b2da eb07 jmp 0x10000b2e3 │ ││ ; JMP XREF from 0x10000b2d4 (sym.__MachOLayout_getSymbolByIndex:_) │ │└─> 0x10000b2dc 488d05e5fd0a. lea rax, [rip + 0xafde5] ; 0x1000bb0c8 ; sym.__MachOLayoutgetSymbolByIndex:_::notfound ; sym.__MachOLayoutgetSymbolByIndex:_::notfound │ │ ; JMP XREF from 0x10000b2da (sym.__MachOLayout_getSymbolByIndex:_) │ └──> 0x10000b2e3 5d pop rbp ╘ 0x10000b2e4 c3 ret [0x100001da0]> quit Generating some form of pseudo code ("decompiling") works similarly through the ingeniously logic command input: [0x100001da0]> pdc @sym.__MachOLayout_getSymbolByIndex:_ function sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4 () { loc_0x10000b2b4: push rbp rbp = rsp eax = edx rdx = qword sym._OBJC_IVAR___MachOLayout.symbols //[0x1001028e0:8]=176 ; "__text" rcx = qword [rdi + rdx] rdx = qword [rdi + rdx + 8] //[0x8:8]=0x280000003 rdx -= rcx rdx >>= 3 var = rax - rdx jae 0x10000b2dc //unlikely { loc_0x10000b2dc: //JMP XREF from 0x10000b2d4 (sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4) rax = [sym.__MachOLayoutgetSymbolByIndex:_::notfound] //method.__MachOLayoutgetSymbolByIndex:_.notfound ; 0x1000bb0c8 ; method.__MachOLayoutgetSymbolByIndex:_.notfound do { loc_0x10000b2e3: //JMP XREF from 0x10000b2da (sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4) pop rbp } while (?); } while (?); } return; } Inside hopper v4 you can do the same as follows: hopperv4 -e /Applications/MachOView.app/Contents/MacOS/MachOView This opens hopper and you can click on the "Proc." tab, and search for the function. Once you click on it, you will see the following disassembly (radare2 1.5.0 0 @ darwin-x86-64 git.1.5.0, commit: HEAD build: 2017-05-31__14:31:32): 000000010000b2b4 push rbp ; Objective C Implementation defined at 0x1000f5de8 (instance method), DATA XREF=0x1000f5de8 000000010000b2b5 mov rbp, rsp 000000010000b2b8 mov eax, edx 000000010000b2ba mov rdx, qword [_OBJC_IVAR_$_MachOLayout.symbols] 000000010000b2c1 mov rcx, qword [rdi+rdx] 000000010000b2c5 mov rdx, qword [rdi+rdx+8] 000000010000b2ca sub rdx, rcx 000000010000b2cd sar rdx, 0x3 000000010000b2d1 cmp rax, rdx 000000010000b2d4 jae loc_10000b2dc 000000010000b2d6 mov rax, qword [rcx+rax*8] 000000010000b2da jmp loc_10000b2e3 loc_10000b2dc: 000000010000b2dc lea rax, qword [__ZZ32-[MachOLayout getSymbolByIndex:]E8notfound] ; CODE XREF=-[MachOLayout getSymbolByIndex:]+32 loc_10000b2e3: 000000010000b2e3 pop rbp ; CODE XREF=-[MachOLayout getSymbolByIndex:]+38 000000010000b2e4 ret Clearly, the pseudo-code inside hopper is at this moment still quite better than what I could get inside radare2. The above disassembly in pseudo code inside hopper (v4.2.1) reads: struct nlist * -[MachOLayout getSymbolByIndex:](void * self, void * _cmd, unsigned int arg2) { rax = arg2; rcx = self->symbols; if (rax < SAR(*(self + *_OBJC_IVAR_$_MachOLayout.symbols + 0x8) - rcx, 0x3)) { rax = *(rcx + rax * 0x8); } else { rax = -[MachOLayout getSymbolByIndex:]::notfound; } return rax; }
{ "pile_set_name": "StackExchange" }
Q: Separating Javascript from HTML In the DIV there is js like: onclick, onkey down etc.. How do I set this up on a new javascript file without losing the functionality. I already have a external js file. And I want to add the 'onclick' stuff in there. But I'm not sure how to do it, and to make it work. Can someone help me? <!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" type="text/css" href="raad.css"> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> <div id="container"> <h1>Raad het goede nummer!</h1> <div id="message_txt"></div> <form id="userInput" name="userInput" method="post"> <input id="input_txt" name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,3);" onKeyUp="limitText(this.form.limitedtextfield,3);" maxlength="3"> <br /> <button id="guess_btn" type="button" onclick="guessNumber()">RAAD</button> <br /> <button id="playAgain_btn" type="button" onclick="initGame()">OPNIEUW</button> </form> </div> <script type="text/javascript" src="raad.js"></script> </body> </html> A: You can move all event handler attributes away from HTML into JS using addEventListener. So, for example, this: <input id="input_txt" name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,3);" onKeyUp="limitText(this.form.limitedtextfield,3);" maxlength="3"> should become this: HTML <input id="input_txt" name="limitedtextfield" type="text" maxlength="3"> JS var input_txt = document.getElementById('input_txt'); input_txt.addEventListener('keydown', function(e){ limitText(this.form.limitedtextfield,3); }); input_txt.addEventListener('keyup', function(e){ limitText(this.form.limitedtextfield,3); }); Ideally, you could use a common function for the callback, like this: function handleInputKeys() { limitText(this.form.limitedtextfield,3); } And then simply have: input_txt.addEventListener('keyup', handleInputKeys); Next example, this: <button id="guess_btn" type="button" onclick="guessNumber()">RAAD</button> Should be: HTML <button id="guess_btn" type="button">RAAD</button> JS var guess_btn = document.getElementById('guess_btn'); guess_btn.addEventListener('click', guessNumber); etc...
{ "pile_set_name": "StackExchange" }
Q: Adding Existing column at the end of another column within a dataframe I have a csv file extracted from a pdf file it contains 6 columns of which 2 columns are repeated thrice in such a way that : S D S D S D 1 A 3 C 5 E 2 B 4 D 6 F Now I wanted to join them into a single column like this : S D 1 A 2 B 3 C 4 D 5 E 6 F Anyone please help me on how to do this using pandas. A: I would concatenate values at numpy level to not be bored by the column names: result = pd.DataFrame(np.concatenate([df.iloc[:, i:i+2].values for i in range(0, len(df.columns), 2)]), columns = df.columns[:2]) With this dataframe: S D S.1 D.1 S.2 D.2 0 1 A 3 C 5 E 1 2 B 4 D 6 F it gives: S D 0 1 A 1 2 B 2 3 C 3 4 D 4 5 E 5 6 F
{ "pile_set_name": "StackExchange" }
Q: Assigning a value to IEnumerable type of integer How can I assign a value to the IEnumerable type of integer array in VB.Net? I need to add the: dim id as integer=obj.id to the array dim arr As IEnumerable(Of Integer) A: You cannot. IEnumerable(Of T) does not provide any methods or properties for changing any of the values in the enumeration. Consider why you think your variable arr needs to be of type IEnumerable. If you get an IEnumerable instance from elsewhere, you could add the contents of that enumeration to a list and then add additional values to your list. Alternatively, even if you want to declare arr as IEnumerable for some reason, note that you need to instantiate a concrete list class anyway, to which you can add values before hiding everything behind the IEnumerable interface for later read-only access.
{ "pile_set_name": "StackExchange" }