qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
31,692,136
I have a `DataFrame` and running a `flatMap` on it. Inside the map function i am trying to append a new field to the given row. How can I do that? ``` def mapper(row): value = 0 #some computation here row.append(newvalue = value) #??? something like that return row data = sqlContext.jsonFile("data.json") mapped = data.flatMap(mapper) #do further mappings with the new field ```
2015/07/29
[ "https://Stackoverflow.com/questions/31692136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3568427/" ]
Following your lead I created something more flexible, and I hope it helps: ``` from pyspark.sql import Row def addRowColumn(row, **kwargs): rowData = row.asDict() for column in kwargs: rowData[column] = kwargs[column] return Row(**rowData) ``` And to use it on a single row, just call like this: ``` modifiedRow = addRowColumn(originalRow, test="Hello Column!") ``` To run on the entire dataset, just create an udf to change each row.
Figured it out, but i am not sure if it is the correct way. ``` def mapper(row): from pyspark.sql import Row value = 0 #some computation here data = row.asDict() data["newvalue"] = value return Row(**data) ```
65,553,557
I'm facing the error `failed to run custom build command for openssl-sys v0.9.60` while trying to build my rust program. Here are the `main.rs` and the `Cargo.toml` files. main.rs ```rust extern crate reqwest; fn main() { let mut resp = reqwest::get("http://www.governo.mg.gov.br/Institucional/Equipe").unwrap(); assert!(resp.status().is_success()); } ``` Cargo.toml ``` [package] name = "get_sct" version = "0.1.0" authors = ["myname <myemail>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] reqwest = "0.10.10" ``` I installed **openssl** locally (as suggested in this [question](https://stackoverflow.com/questions/57182594/error-failed-to-run-custom-build-command-for-openssl-v0-9-24)), using: ```sh git clone git://git.openssl.org/openssl.git cd openssl ./config --openssldir=/usr/local/ssl make make test sudo make install ``` Finally, I ran `export OPENSSL_DIR="/usr/local/ssl"` I noted I already had a anaconda instalation of **openssl** which was in my default path. To change the default path of **openssl** to the github instalation I ran `chmod -x MYPATH/anaconda3/bin/openssl` and now `which openssl` returns `/usr/local/bin/openssl`. I also have **pkg-config** installed (as suggested in this [question](https://stackoverflow.com/questions/43364214/why-doesnt-the-rust-crate-openssl-sys-compile)). Running `which pkg-config` returns `/usr/bin/pkg-config` However, when I run `cargo run` again the program print the same error message. Here is the entire error message: ``` > cargo run Compiling openssl-sys v0.9.60 Compiling tokio v0.2.24 Compiling pin-project-internal v0.4.27 Compiling pin-project-internal v1.0.2 Compiling mime_guess v2.0.3 Compiling url v2.2.0 error: failed to run custom build command for `openssl-sys v0.9.60` Caused by: process didn't exit successfully: `/PACKAGEPATH/target/debug/build/openssl-sys-db18d493257de4f7/build-script-main` (exit code: 101) --- stdout cargo:rustc-cfg=const_fn cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR unset cargo:rerun-if-env-changed=OPENSSL_LIB_DIR OPENSSL_LIB_DIR unset cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR unset cargo:rerun-if-env-changed=OPENSSL_INCLUDE_DIR OPENSSL_INCLUDE_DIR unset cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR unset cargo:rerun-if-env-changed=OPENSSL_DIR OPENSSL_DIR = /usr/local/ssl --- stderr thread 'main' panicked at 'OpenSSL library directory does not exist: /usr/local/ssl/lib', /home/lucas/.cargo/registry/src/github.com-1ecc6299db9ec823/openssl-sys-0.9.60/build/main.rs:66:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace warning: build failed, waiting for other jobs to finish... error: build faile ``` It looks like that rust is searching for ssl in `/usr/local/ssl/lib`. In fact, there is a `/usr/local/ssl` folder in my PC, but there is no `lib` there. What am I doing wrong here? How can make my local installation of openssl work with rust correctly?
2021/01/03
[ "https://Stackoverflow.com/questions/65553557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9381966/" ]
I have no experience with installing this myself but may be able to give some pointers. First of all about your effort to install OpenSSL. After cloning the repository, you do not select any particular branch before configuring and making. This means that you are building the `master` branch, which is an evolving version of OpenSSL 3.0.0. This is not a supported version according to [the crate's documentation](https://docs.rs/openssl/0.10.32/openssl/). In order to build a supported version of OpenSSL, you will have to switch to some 1.1.1 branch or tag. Alternatively, you can download the 1.1.1 version from [OpenSSL's download page](https://www.openssl.org/source/). That said, it does not seem necessary to install OpenSSL from source. Under the section [Automatic](https://docs.rs/openssl/0.10.32/openssl/#automatic), the documentation explains that the crate can deal with all kinds of typical OpenSSL installations. It may be easier for you to follow that, if possible in your case. If so, then you should unset the `OPENSSL_DIR` environment variable otherwise that will (continue to) override the crate's automatic mechanisms to find the OpenSSL installation. If you still want to stick with the [Manual](https://docs.rs/openssl/0.10.32/openssl/#manual) configuration, then indeed you should use environment variables, and `OPENSSL_DIR` seems a convenient one. However, it does not mean the same thing as the `openssldir` parameter that you used in your configure command `./config --openssldir=/usr/local/ssl`. To get the details, check out [the meaning of that configuration parameter](https://github.com/openssl/openssl/blob/master/INSTALL.md#openssldir). In fact, the crate's meaning of `OPENSSL_DIR` corresponds to [the `--prefix` setting](https://github.com/openssl/openssl/blob/master/INSTALL.md#prefix) (which you did not configure). The problem you are running into now is that your `OPENSSL_DIR` variable points to your directory for OpenSSL configuration files, whereas the crate expects it to point to the top of the actual OpenSSL installation directory tree (which in your case seems to reside at `/usr/local`).
I used the following commands on Ubuntu on Windows: ``` sudo apt install libudev-dev sudo apt install libssl-dev ```
29,552,699
I have a directory of files who's main purpose is to store php variables for inclusion into other files in the site. Each file contains the same set of variables, but with different values. for example: event1.php ``` <?php $eventActive = 'true'; $eventName = My First Event; $eventDate = 01/15; ?> ``` event2.php ``` <?php $eventActive = 'true'; $eventName = My Second Event; $eventDate = 02/15; ?> ``` In addition to calling these variables in other pages, I want to create a page that contains a dynamic list, based on the variables stored in each file within the directory. Something like (basic concept): ``` for each file in directory ('/events') { if $eventActive = 'true'{ <p><? echo $eventName ?></p> } } ``` What is the best way to do this?
2015/04/10
[ "https://Stackoverflow.com/questions/29552699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675078/" ]
Take a look at the API for what you're doing. <http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()> Specifically, Scanner.hasNextInt(). "Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input." So, your code: ``` while (!input.hasNextInt()) { input.next(); } ``` That's going to look and see if input hasNextInt(). So if the next token - one character - is an int, it's false, and skips that loop. If the next token isn't an int, it goes into the loop... and iterates to the next character. That's going to either: - find the first number in the input, and stop. - go to the end of the input, not find any numbers, and probably hits an IllegalStateException when you try to keep going. * Write down in words what you want to do here. * Use the API docs to figure out how the hell to tell the computer that. :) Get one bit at a time right; this has several different parts, and the first one doesn't work yet. * Example: just get it to read a file, and display each line first. That lets you do debugging; it lets you build one thing at a time, and once you know that thing works, you build one more part on it. * Read the file first. Then display it as you read it, so you know it works. * Then worry about if it has numbers or not.
A easy way to do this is read all the data from file in a way that you prefer (line by line for example) and if you need to take tokens, you can use split function (String.split see Java doc) or StringTokenizer for each line of String that you are reading using a loop, in order to create tokens with a specific delimiter (a space for example) so now you have the tokens and you can do something that you need with them, hope you can resolve, if you have question you can ask. Have a nice programming.
6,127,670
Alright, so, I haven't programmed anything useful in ages - last time I did was a year ago and as you can imagine my knowledge of programming is seriously rusty. (last thing I 'programmed' was a ren'py game over the weekend. One can imagine the limited uses of this. The most advanced C program I wrote was a tic-tac-toe game a year ago. So yeah.) Anyways, I've been given a job to write a program that takes two Excel files, both of which have a list of items, each associated with an ID. I need to write a program to search both files for IDs and if the IDs match, the program will need to create a new file with the matched IDs and items. This is insanely beyond my limited C capabilities. If anyone could help, I would seriously appreciate it. (also, if this is not possible with C, I'll do my best to work with any other languages)
2011/05/25
[ "https://Stackoverflow.com/questions/6127670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769944/" ]
Export the two files to .csv format and write a script to process the two files. For example, in PHP, you have built in csv read/write capabilities.
If you absolutely have to do this on xls/xlsx file from a process, you probably need a copy of Excel controlled by COM automation. You can do this in BV/VBA/C#/C++ whatever, some easier than others. Google for 'Excel automation'. Rgds, Martin
8,626,139
Hai I would like to use Birt with Struts 2. But I am getting the following error. > > HTTP Status 404 - There is no Action mapped for namespace / and action name frameset. > > > What could be the cause for this? Where this frameset comes from? `<birt:viewer id="birt_id" format="pdf" reportDesign="new_report.rptdesign" width="1024" height="500" showParameterPage="false">` ``` <birt:param name="uid" value="100" ></birt:param> </birt:viewer> ``` This is my .jsp page. When i try to load this page as the result of some action i am getting this error.
2011/12/24
[ "https://Stackoverflow.com/questions/8626139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032477/" ]
The [add()](http://es.php.net/manual/en/datetime.add.php) method requires PHP/5.3.0 or greater. Chances are that your host is using an older version. Alternative code for PHP/5.2: ``` $tempDate->modify('+1 month'); ```
When I upgraded to PHP 5.3, I had notices all over the place related to the use of the `date()` function because I hadn't set a default timezone, try setting one. <http://php.net/manual/en/function.date-default-timezone-set.php> It might not be related, but it's worth trying. Example: ``` date_default_timezone_set('America/New_York'); ``` You can reference the [list of supported timezones](http://www.php.net/manual/en/timezones.php) to find the one that's right for you. As far as the errors, try adding this to the beginning of your script or bootstrap file: ``` ini_set('display_errors', 1); error_reporting(E_ALL); ```
24,383,162
How to write a breeze query with 2 'where' conditions? the following doesn't work: ``` var query = breeze.EntityQuery.from("Boilers") .where('boilerMakeID', '==', $rootScope.boilerMakeID) .and('actueel', '==', true); ```
2014/06/24
[ "https://Stackoverflow.com/questions/24383162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913629/" ]
Use Predicates... <http://www.breezejs.com/sites/all/apidocs/classes/Predicate.html> ``` var pred1 = Predicate.create("boilerMakeID", "==", $rootScope.boilerMakeID); var pred2 = Predicate.create("actueel", "==", true); var newPred = pred1.and(pred2); var query = breeze.EntityQuery.from("Boilers").where(newPred) ```
Another way to use predicates... ``` var p1=new breeze.Predicate("boilerMakeId","==",$rootScope.boilerMakeID); var p2=new breeze.Predicate("actueel","==",true); var predicate=p1.and(p2); var query=breeze.EntityQuery.from("Boilers").where(predicate); ```
122,033
We have very quickly out-grown our Small Business Server 2008 current hardware and have decided to purchase a complete new server. What is the best and easiest way to move the server to new hardware? It is one complete box, we do not have any SAN's or any complicated setup. We do have a couple of SQL databases running on the server and we also use Exchange. I'm sure there must be some easy way to move everything :-) Would creating a backup (Using Windows Server backup) and then restoring it on the new server work?
2010/03/12
[ "https://serverfault.com/questions/122033", "https://serverfault.com", "https://serverfault.com/users/27916/" ]
Microsoft publishes a guide called "Migrating to Windows Small Business Server 2008 from Windows Small Business Server 2008" which describes the process of setting up an answer file and performing a migrate-install on the new hardware. You can find it here: <http://www.microsoft.com/downloads/details.aspx?FamilyID=31CBC5DD-21B1-4A6E-9A9D-740CE7605448&displaylang=en>
Have you considered moving to virtualization? This would be a great time, because you're changing hardware, but you want to keep the actual installation. Any of the p2v (physical to virtual) converters should be able to handle that.
57,462,562
I am reframing my last question, which is unanswered, and I have rewritten the problem following [Google's BasicLocation](https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample). My main activity is defined as: ``` public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { // private LocationCallback locationCallback; // private FusedLocationProviderClient mFusedLocationClient; private FusedLocationProviderClient mFusedLocationClient; protected Location mLastLocation; private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34; private static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.drawer_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(sectionsPagerAdapter); DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); ImageButton leftNav = findViewById(R.id.left_nav); ImageButton rightNav = findViewById(R.id.right_nav); leftNav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int tab = viewPager.getCurrentItem(); if (tab > 0) { tab--; viewPager.setCurrentItem(tab); } else if (tab == 0) { viewPager.setCurrentItem(tab); } } }); rightNav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int tab = viewPager.getCurrentItem(); tab++; viewPager.setCurrentItem(tab); } }); } @Override public void onStart() { super.onStart(); if (!checkPermissions()) { requestPermissions(); } else { getLastLocation(); } } ``` with latlang.[Lat,Lang] is in a seperate file: ``` public class latlang { public static double Lat; public static double Lang; } ``` and the location file, which is the first fragment in the viewpager is defined as: ``` public class SunFragment extends Fragment { List<SunSession> sunsList; Typeface sunfont; //to be called by the MainActivity public SunFragment() { // Required empty public constructor } // Keys for storing activity state. // private static final String KEY_CAMERA_POSITION = "camera_position"; private static final String KEY_LOCATION_NAME = "location_name"; public String location;//="No location name found"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retrieve location and camera position from saved instance state. if (savedInstanceState != null) { location = savedInstanceState.getCharSequence(KEY_LOCATION_NAME).toString(); System.out.println("OnCreate location "+location); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_sun, container, false); onSaveInstanceState(new Bundle()); //SecondFragment secondFragment = new SecondFragment(); //secondFragment.getDeviceLocation(); RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view); rv.setNestedScrollingEnabled(false); rv.setHasFixedSize(true); //MyAdapter adapter = new MyAdapter(new String[]{"Today", "Golden Hour", "Blue Hour", "Civil Twilight", "Nautical Twilight", "Astronomical Twilight", "Hello", "World"}); //rv.setAdapter(adapter); LinearLayoutManager llm = new LinearLayoutManager(getActivity()); rv.setLayoutManager(llm); System.out.println("location "+location); /* Reversegeocoding location */ String location="No location name found"; String errorMessage = ""; List<Address> addresses = null; Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault()); try { addresses = geocoder.getFromLocation( latlang.Lat, latlang.Lang, 1); } catch (IOException ioException) { // Catch network or other I/O problems. errorMessage = getString(R.string.service_not_available); // Log.e(TAG, errorMessage, ioException); if (getView() != null){ Snackbar.make(getView(), errorMessage, Snackbar.LENGTH_LONG).show(); } } catch (IllegalArgumentException illegalArgumentException) { // Catch invalid latitude or longitude values. errorMessage = getString(R.string.invalid_lat_long_used); if (getView() != null){ Snackbar.make(getView(), "Illegal Latitude = " + latlang.Lat + ", Longitude = " + latlang.Lang, Snackbar.LENGTH_LONG).show(); } } if (addresses == null || addresses.size() == 0) { if (errorMessage.isEmpty()) { System.out.println("Adress Empty No Address Found");// Snackbar.LENGTH_LONG).show(); location = "Lat:"+latlang.Lat+" Lang: "+latlang.Lang; } } else { location = addresses.get(0).getAddressLine(0);//+", "+ addresses.get(0).getLocality(); /* for(int i = 0; i <= addresses.get(0).getMaxAddressLineIndex(); i++) { location = addresses.get(0).getAddressLine(i); }*/ } ``` The problem with this is evident from the `logcat`: ``` I/System.out: location null I/Google Maps Android API: Google Play services package version: 17785022 I/Choreographer: Skipped 31 frames! The application may be doing too much work on its main thread. I/System.out: Position:0 I/System.out: Position:1 I/System.out: Position:2 I/zygote: Do full code cache collection, code=202KB, data=177KB I/zygote: After code cache collection, code=129KB, data=91KB I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int) I/zygote: Background concurrent copying GC freed 44415(2MB) AllocSpace objects, 7(136KB) LOS objects, 49% free, 3MB/6MB, paused 294us total 102.458ms I/System.out: Position:3 I/System.out: Position:4 I/zygote: Do partial code cache collection, code=193KB, data=126KB I/zygote: After code cache collection, code=193KB, data=126KB I/zygote: Increasing code cache capacity to 1024KB I/zygote: JIT allocated 71KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int) I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int) E/MainActivity: Latit: 37.42342342342342 ``` This shows, at the start, location is null, > > I/System.out: location null > > > then the recyclerview of the sunfragment is created ``` I/System.out: Position:0 I/System.out: Position:1 I/System.out: Position:2 ``` and after that I am getting the location: ``` E/MainActivity: Latit: 37.42342342342342 ``` Link of the complete code:<https://drive.google.com/file/d/1pMl_3Lf76sy82C0J4b-9ta4jbSHonJ2y/view?usp=sharing> Is it somehow possible to get the location first before creating the `sunfragment`'s `oncreateview`?
2019/08/12
[ "https://Stackoverflow.com/questions/57462562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005559/" ]
I found something wrong about your code (I may be wrong): 1. Why fields of `latlang` are `static`? It doesn't looks like they should. 2. At `SunFragment.onCreate()` you are reading `location` if `savedInstanceState != null`. `savedInstanceState` is not null only if activity that holds this fragment was restored from saved state. It may not happen at all. 3. You should use fragment's `arguments` (Bundle) to pass initial data to fragment 4. You should implement `Parcelable` interface for `latlang` to be able to pass custom class thru Bundle I think that's not everything but for me it seems like enough for this code to not work as you expected
By looking at the code, it seems you do not need a very accurate location, you will be fine with last known location. This value might be null in some cases, like you have already experienced. Simple answer to your question is no, you cannot get not null location before creating `SunFragment`. Following steps is to load location in background and update UI once found. 1. Request last known location in MainActivity 2. Keep a reference of last location in cache for easy loading and better user experience 3. If last location is null, request location updates until you get a good fix 4. Have a listener in `SunFragment` to track location updates **Here are some code you need (Please do read them)** Use the `LocationUtil` to handle location related events (I prefer `LocationManager` over `FusedLocationProviderClient`); ``` public class LocationUtil { public static void updateLastKnownLocation(Context context) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if(hasSelfPermission(context, new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})) { try { Location currentBestLocation; Location gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location lbsLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if(isBetterLocation(lbsLocation, gpsLocation)) { currentBestLocation = lbsLocation; } else { currentBestLocation = gpsLocation; } if(currentBestLocation == null) { requestLocationUpdates(lm); } else { updateCacheLocation(currentBestLocation); } } catch (SecurityException se) { // unlikely as permission checks se.printStackTrace(); } catch (Exception e) { // unexpected e.printStackTrace(); } } } private static void updateCacheLocation(Location location) { if(location == null) return; LocationLite temp = new LocationLite(); temp.lat = location.getLatitude(); temp.lon = location.getLongitude(); Gson gson = new Gson(); String locationString = gson.toJson(temp); AppCache.setLastLocation(locationString); } @SuppressLint("MissingPermission") private static void requestLocationUpdates(LocationManager lm) { try { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0.0F, new LocationListener() { @Override public void onLocationChanged(Location location) { updateCacheLocation(location); lm.removeUpdates(this); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { // doing nothing } @Override public void onProviderEnabled(String s) { // doing nothing } @Override public void onProviderDisabled(String s) { // doing nothing } }); }catch (Exception e) { e.printStackTrace(); } } private static boolean isBetterLocation(Location location, Location currentBestLocation) { int TWO_MINUTES = 1000 * 60 * 2; if (currentBestLocation == null) { // A new location is always better than no location return true; } if (location == null) { // A new location is always better than no location return false; } // Check whether the new location fix is newer or older long timeDelta = location.getTime() - currentBestLocation.getTime(); boolean isSignificantlyNewer = timeDelta > TWO_MINUTES; boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES; boolean isNewer = timeDelta > 0; // If it's been more than two minutes since the current location, use the new location // because the user has likely moved if (isSignificantlyNewer) { return true; // If the new location is more than two minutes older, it must be worse } else if (isSignificantlyOlder) { return false; } // Check whether the new location fix is more or less accurate int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy()); boolean isLessAccurate = accuracyDelta > 0; boolean isMoreAccurate = accuracyDelta < 0; boolean isSignificantlyLessAccurate = accuracyDelta > 200; // Check if the old and new location are from the same provider boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider()); // Determine location quality using a combination of timeliness and accuracy if (isMoreAccurate) { return true; } else if (isNewer && !isLessAccurate) { return true; } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) { return true; } return false; } private static boolean isSameProvider(String provider1, String provider2) { if (provider1 == null) { return provider2 == null; } return provider1.equals(provider2); } public static boolean hasSelfPermission(Context context, String[] permissions) { // Below Android M all permissions are granted at install time and are already available. if (!(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)) { return true; } // Verify that all required permissions have been granted for (String permission : permissions) { if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } } ``` Use `AppCache` to store last location; ``` public class AppCache { public static final String KEY_LAST_LOCATION = "_key_last_location"; private static SharedPreferences mPreference; static { mPreference = PreferenceManager.getDefaultSharedPreferences(App.getApp().getApplicationContext()); } public static String getLastLocation() { return mPreference.getString(KEY_LAST_LOCATION, null); } public static String getLastLocation(String defaultValue) { return mPreference.getString(KEY_LAST_LOCATION, defaultValue); } public static void setLastLocation(String lastLocation) { mPreference.edit().putString(KEY_LAST_LOCATION, lastLocation).commit(); } public static void registerPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { mPreference.registerOnSharedPreferenceChangeListener(listener); } public static void unregisterPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { mPreference.unregisterOnSharedPreferenceChangeListener(listener); } } ``` Put the following code into your `MainActivity` `onCreate()` This will call locationManager to get last known location and update app cache. ``` LocationUtil.updateLastKnownLocation(MainActivity.this); ``` Also replace `fetchLocation();` in `onRequestPermissionsResult` method with above line of code, so it will look like; ``` @Override public void onRequestPermissionsResult(...){ switch (requestCode) { case 101: { ... // permission was granted //fetchLocation(); LocationUtil.updateLastKnownLocation(MainActivity.this); } else { // Show some error } return; } } } ``` I did not use your latlang class. (Please make sure all class names follow Java coding standards) Instead use `LocationLite` to store location in cache. Also I used GSON google library to convert and restore pojo to JSON and backward. ``` public class LocationLite { public double lat; public double lon; public String address; } ``` Final changes in `SunFragment`. Make `SunAdapter` as a member variable, and `SharedPreferences.OnSharedPreferenceChangeListener` to listen to any changes on location value. ``` SunAdapter mAdapter; SharedPreferences.OnSharedPreferenceChangeListener mPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(AppCache.KEY_LAST_LOCATION.equalsIgnoreCase(key)) { // location value has change, update data-set SunSession sunSession = sunsList.get(0); sunSession.setId(sharedPreferences.getString(key, "No Location")); sunsList.add(0, sunSession); mAdapter.notifyDataSetChanged(); } } }; ``` Start listening to preference changes in `onStart()` and unregister in `onStop()` ``` @Override public void onStart() { super.onStart(); AppCache.registerPreferenceChangeListener(mPreferenceChangeListener); } @Override public void onStop() { super.onStop(); AppCache.unregisterPreferenceChangeListener(mPreferenceChangeListener); } ``` Finally when populating first `SunSession` use the following instead `location` local variable. So It will look like following; ``` sunsList.add( new SunSession( AppCache.getLastLocation("Searching location..."), "&#xf051;", sun_rise, "&#xf052;", sun_set, "&#xf0c9", moon_rise, "&#xf0ca", moon_set)); ``` That's all. Feel free to ask anything you do not understand.
193,563
Let me start with an example. Let $$\mathbf{A}=\begin{bmatrix}3&1\\2&3\\1&5\end{bmatrix},$$ and let $Q=\{\mathbf{q}\vert\mathbf{q}\in\Bbb R^3\_+ \land \sum\_i^n q\_i=1\}$ and $\alpha=\bigl(\frac{1}{2},\frac{1}{2},\frac{1}{2}\bigr)$. Abusing notation, let $\mathbf{q}^{\frac{1}{\alpha}}=\bigl(q\_1^{\frac{1}{\alpha\_1}},q\_2^{\frac{1}{\alpha\_2}},q\_3^{\frac{1}{\alpha\_3}}\bigr)=\bigl(q\_1^2,q\_2^2,q\_3^2\bigr).$ Consider the set $K=\{\mathbf{k}\in\Bbb R^2\_+\vert \mathbf{k}=\mathbf{A}^{\top}\mathbf{q}^{\frac{1}{\alpha}}\land \mathbf{q}\in Q\}.$ There exist two members of $K$ such that the $j$-th component of $\underline{\mathbf{k}}^j$ is lower than the $j$-th component of any other $\mathbf{k}\in K$. These can be easily identified using calculus. In this case, $\underline{\mathbf{k}}^1=\bigl(\frac{6}{11},\frac{211}{121}\bigr),$ that corresponds to $\mathbf{q}\_{\underline{\mathbf{k}}^1}=\bigl(\frac{2}{11},\frac{3}{11},\frac{6}{11}\bigr)$ is the $\mathbf{k}$ with the lowest first component and $\underline{\mathbf{k}}^2=\bigl(\frac{734}{529},\frac{15}{23}\bigr),$ corresponding to $\mathbf{q}\_{\underline{\mathbf{k}}^2}=\bigl(\frac{15}{23},\frac{5}{23},\frac{3}{23}\bigr)$, the one with the lowest second component. $K$, (blue) $\underline{\mathbf{k}}^1$ and $\underline{\mathbf{k}}^2$ (red) are shown in the following figure. [![figure](https://i.stack.imgur.com/A25Bp.jpg)](https://i.stack.imgur.com/A25Bp.jpg) I need to pinpoint those $\mathbf{k}$ that are on the convex part of the frontier of $K$ between $\underline{\mathbf{k}}^1$ and $\underline{\mathbf{k}}^2$, i.e., the yellow dots. In order to identify them, I 1. Choose $\beta\in[0,1]$ and compute $\hat{\mathbf{k}} =\beta\underline{\mathbf{k}}\_1+(1-\beta)\underline{\mathbf{k}}\_2.$ This yields a point in the straight segment that connects $\underline{\mathbf{k}}\_1$ and $\underline{\mathbf{k}}\_2,$ i.e., the green dots. 2. Determine the proportion $r=\frac{\hat k\_1}{\hat k\_2}.$ By construction $\frac{\underline{k}\_2^2}{\underline{k}\_1^2}\leq r \leq\frac{\underline{k}\_2^1}{\underline{k}\_1^1}.$ 3. Minimize $k\_1$ subject to $\mathbf{k}\in K$ and $k\_2=r k\_1.$ Let $k^\*\_1$ be the solution to this problem and $\mathbf{k}^\*=(k^\*\_1,rk^\*\_1).$ For every $\beta \in[0,1]$ this procedure should yield a $\mathbf{k}^\*$ that is on the frontier. These $\mathbf{k}^\*$ have an additional property: the solution to the problem $\max\sum\_{i=1}^n q\_i, s.t.\mathbf{A}^{\top}\mathbf{q}^{\alpha} \leq \mathbf{k}^\* \land \mathbf{q} \geq 0,$ denoted $\mathbf{q}^\*$, is such that $\sum\_i q\_i^\*=1.$ However, when I solve this maximization problem, only a handful of the $\mathbf{k}^\*$ are actually such that $\sum q^\*\_i=1$ (purple dots). This is very unfortunate, because what I'm really interested in are the KKT multipliers in this last problem, in particular those associated with the $\mathbf{A}^{\top}\mathbf{q}^{\alpha} \leq \mathbf{k}^\*$ constraints. I'm guessing that the problem can lie in the fact that $\mathbf{k}^\*$ identified in the minimization step are just approximations to the *true* $\mathbf{k}^\*$ on the frontier. However, increasing `WorkingPrecision` to, e.g., 30, only makes matters worse, as fewer $\mathbf{k}^\*$ result in $\sum q^\*\_i=1$. **Edit:** Do you believe this can be the case? If so, can you propose a workaround or a way of identifying the *true* $\mathbf{k}^\*$? Ideally this should work for any ${n\times J}$ matrix $\mathbf{A}$ with $a\_{ij}\geq0$ (and $a\_{ij}>0$ for most $ij$, there cannot be any rows or columns that consist only of $0$s), $Q=\{\mathbf{q}\vert \mathbf{q}\in\Bbb R^n\_+\land\sum\_i^n q\_i=1\}$ and an $\alpha\in\Bbb R^n\_+$ such that $\alpha\_i\in]0,1[$ $\forall i=1,\dots,n$. My code follows: ``` A = {{3, 1}, {2, 3}, {1, 5}}; t = Dimensions[A][[1]]; f = Dimensions[A][[2]]; qVec = Array[q, t]; αVec = ConstantArray[1/2, t]; onesVec = ConstantArray[1, t]; zerosVec = ConstantArray[0, t]; needs = Transpose[A].qVec^(1/αVec); kcrit = Table[ needs /. Minimize[ {needs[[i]], qVec.onesVec == 1, Thread[0 <= qVec <= 1]}, qVec, Reals][[2]], {i, 1, f}]; step = 1/100; grid = Flatten[Permutations /@ IntegerPartitions[1, {t}, Range[0, 1, step]], 1]; lg = Length[grid]; plotK = ListPlot[ Table[needs /. Thread[qVec -> grid[[i]]], {i, 1, lg}], AspectRatio -> 1, PlotRange -> {{0, 3.2}, {0, 5.2}}]; plotkcrit = ListPlot[kcrit, AspectRatio -> 1, PlotStyle -> Red]; grid = Flatten[Permutations /@ IntegerPartitions[1, {f}, Range[0, 1, step]], 1]; lg = Length[grid]; line = Table[Transpose[kcrit].grid[[i]], {i, 1, lg}]; plotline = ListPlot[line, PlotStyle -> Green]; frontier = {}; frontier2 = {}; success = 0; Do[ r = Table[line[[g, i]]/line[[g, 1]], {i, 1, f}]; k = needs /. Minimize[ Flatten[ {needs[[1]], qVec.onesVec == 1, Table[needs[[i]] == r[[i]] needs[[1]], {i, 2, f}], onesVec >= qVec >= zerosVec}], qVec, Reals][[2]]; AppendTo[frontier, k]; temp = NMaximize[{qVec.onesVec, onesVec >= qVec >= zerosVec, needs <= k}, qVec, Reals]; If[temp[[1]] == 1, success++; AppendTo[frontier2, needs /. temp[[2]]];];, {g, 1, lg}]; plotfrontier = ListPlot[frontier, PlotStyle -> Yellow]; plotfrontier2 = ListPlot[frontier2, PlotStyle -> Purple]; Show[ {plotK, plotline, plotfrontier, plotkcrit, plotfrontier2, Graphics[{Text["k1", {0.48, 1.75}], Text["k2", {1.4, 0.55}]}]}] Print["Purple over Yellow: ", success/lg] ``` **Follow-up:** I've tried Chris K.'s suggestion. His code is much faster than mine, but, again, is tantamount to identifying the boundary in yellow in my original post. If I check which of his $\mathbf{k}^\*$ result in $\sum q^\*\_i=1$, I obtain a very similar picture as above (orange is $\mathbf{k}^\*$ obtained with Chris's method, purple those $\mathbf{k}^\*$ that result in $\sum q^\*\_i=1$). It's striking that the number of purple points in both pictures is the same, 2% of the yellow/orange points, though the specific $\mathbf{k}^\*$ for which this happens are different. [![figure](https://i.stack.imgur.com/RHUhE.jpg)](https://i.stack.imgur.com/RHUhE.jpg) Also, I don't see how Chris's method would generalize to $n>3$, e.g., to $$\mathbf{A}=\begin{bmatrix}3&1\\2&3\\1&5\\5&\frac{1}{2}\end{bmatrix},$$
2019/03/19
[ "https://mathematica.stackexchange.com/questions/193563", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/60362/" ]
If I understand your problem correctly, I think you can derive the envelope using calculus. Basically you have a function `n` (your `needs`) of two variables `q1` and `q2` (`q3 == 1 - q1 - q2` since you write that the `q's` sum to one). ``` n[q1_, q2_] := Transpose[A].{q1^2, q2^2, (1 - q1 - q2)^2} ``` First, replicating your point plot: ``` points = ListPlot[Flatten[ Table[n[q1, q2], {q2, 0, 1, 0.01}, {q1, 0, 1 - q2, 0.01}] , 1]] ``` ![Mathematica graphics](https://i.stack.imgur.com/Xvsly.png) To find the envelope, set the determinant of the Jacobian matrix of the transformation `n` equal to zero and solve for one of the `q's` as a function of the other: ``` env = Solve[Det[D[n[q1, q2], {{q1, q2}}]] == 0, q2] ``` ![Mathematica graphics](https://i.stack.imgur.com/mqA80.png) Then you can inject `q2 /. env` into the definition of `n` and `ParametricPlot` (the first solution turns out to correspond to the lower envelope): ``` pp = ParametricPlot[n[q1, q2 /. env[[1]]], {q1, 0, 1}, PlotStyle -> Orange]; Show[points, pp] ``` ![Mathematica graphics](https://i.stack.imgur.com/uzR2h.png) You already knew the turning points (how exactly did you find those??), which can be used to restrict `q1` to the part you want: ``` pp = ParametricPlot[n[q1, q2 /. env[[1]]], {q1, 2/11, 15/23}, PlotStyle -> Orange]; Show[points, pp] ``` ![Mathematica graphics](https://i.stack.imgur.com/C5qJ3.png)
This is a full revamp of my previous answer (see the edit history for the old version.) Let ``` mat = {{3, 1}, {2, 3}, {1, 5}}; α = 1/2; ``` The idea is to construct a parametrization of $\mathbf q$ that automatically satisfies the constraints $\mathbf{q}\in\Bbb R^3\_+$ and $\|\mathbf q\|\_1=1$. An immediate choice is to use the parametrization of a [superellipsoid](https://en.wikipedia.org/wiki/Superellipsoid); in particular, the positivity constraint (i.e., keep only the first octant) allows a significant simplification of the parametric equations: ``` vecs[u_, v_] := {(Cos[u] Cos[v])^2, (Cos[u] Sin[v])^2, Sin[u]^2} ``` Visualize: ``` ParametricPlot3D[vecs[u, v], {u, 0, π/2}, {v, 0, π/2}, ViewPoint -> {1.3, 2.4, 2.}] ``` ![octant of a "flat" superellipsoid](https://i.stack.imgur.com/JJK1y.png) Thus, we can visualize the region $K$ like so: ``` ParametricPlot[(vecs[u, v]^(1/α)).mat, {u, 0, π/2}, {v, 0, π/2}] ``` ![region K](https://i.stack.imgur.com/BYaIr.png) Let us look at the lines of constant `u` and `v`: ![mesh lines](https://i.stack.imgur.com/IFf7R.png) Unfortunately, it seems the frontier desired is not part of the mesh lines, so we need to do some more work. One might notice that the frontier can be thought of as the [envelope](http://mathworld.wolfram.com/Envelope.html) of the mesh lines, so we can try deriving the envelope equation. ``` Det[D[(vecs[u, v]^(1/α)).mat, {{u, v}}]] // FullSimplify 7/8 Cos[u]^5 (-11 Sin[3 u] Sin[2 v] + 48 Sin[u]^3 Sin[4 v] + Sin[u] (21 Sin[2 v] + 4 Cos[u]^2 Sin[6 v])) ``` It seems simpler to solve for `v`, so let's take the factor containing it: ``` fac = -11 Sin[3 u] Sin[2 v] + 48 Sin[u]^3 Sin[4 v] + Sin[u] (21 Sin[2 v] + 4 Cos[u]^2 Sin[6 v]); ``` and make a substitution: ``` TrigExpand[fac /. v -> ArcSin[h]] // FullSimplify 64 h Sqrt[1 - h^2] (2 - 4 h^2 + h^4 + (-2 + 2 h^2 + h^4) Cos[2 u]) Sin[u] ``` We can work further with the factor that is quartic in `h`; let us find its roots (and impose constraints as well): ``` ArcSin[h] /. (Solve[2 - 4 h^2 + h^4 + (-2 + 2 h^2 + h^4) cos == 0 && -1 < cos < 1 && -1 < h < 1, h, Reals] /. cos -> Cos[2 u]) {ConditionalExpression[ ArcSin[Root[2 - 2 Cos[2 u] + (-4 + 2 Cos[2 u]) #1^2 + (1 + Cos[2 u]) #1^4 &, 2]], -1 < Cos[2 u] < 1], ConditionalExpression[ArcSin[Root[ 2 - 2 Cos[2 u] + (-4 + 2 Cos[2 u]) #1^2 + (1 + Cos[2 u]) #1^4 &, 3]], -1 < Cos[2 u] < 1]} ``` As it turns out, it is the second root that yields the required frontier: ``` Show[ParametricPlot[(vecs[u, v]^(1/α)).mat, {u, 0, π/2}, {v, 0, π/2}], ParametricPlot[With[{v = ArcSin[Root[2 - 2 Cos[2 u] + (-4 + 2 Cos[2 u]) #1^2 + (1 + Cos[2 u]) #1^4 &, 3]]}, (vecs[u, v]^(1/α)).mat], {u, 0, π/2}, PlotStyle -> Directive[AbsoluteThickness[4], ColorData[97, 3]]]] ``` ![frontier](https://i.stack.imgur.com/m8fz4.png) One can derive a more conventional parametric equation for the frontier, if desired: ``` With[{v = ArcSin[Root[2 - 2 Cos[2 u] + (-4 + 2 Cos[2 u]) #1^2 + (1 + Cos[2 u]) #1^4 &, 3]]}, (vecs[u, v]^(1/α)).mat] // ToRadicals // FullSimplify {1/4 (37 + 15 Cos[4 u] + 7 Sqrt[2] Sqrt[7 - 8 Cos[2 u] + 3 Cos[4 u]] - 2 Cos[2 u] (21 + 4 Sqrt[2] Sqrt[7 - 8 Cos[2 u] + 3 Cos[4 u]])), 1/4 (38 + 12 Cos[4 u] + 7 Sqrt[2] Sqrt[7 - 8 Cos[2 u] + 3 Cos[4 u]] - Cos[2 u] (42 + 5 Sqrt[2] Sqrt[7 - 8 Cos[2 u] + 3 Cos[4 u]]))} ``` which can then be converted to an implicit Cartesian equation: ``` eq = First[GroebnerBasis[Append[MapAll[TrigExpand, Thread[{x, y} == %]], Cos[u]^2 + Sin[u]^2 == 1], {x, y}, {Cos[u], Sin[u]}]] -2401 + 4116 x - 6321 x^2 + 2828 x^3 - 1587 x^4 + 2058 y + 2940 x y - 1050 x^2 y + 5520 x^3 y - 2352 y^2 - 84 x y^2 - 6318 x^2 y^2 + 574 y^3 + 2640 x y^3 - 363 y^4 ``` You can then obtain your $\underline{\mathbf{k}}^j$ like so: ``` ArgMin[{x, eq == 0}, {x, y}] {6/11, 211/121} ArgMin[{y, eq == 0}, {x, y}] {734/529, 15/23} ``` --- As I had noted, for a general $n\times j$ matrix, one would now need to use modified [hyperspherical coordinates](https://en.wikipedia.org/wiki/N-sphere#Spherical_coordinates); e.g. ``` vec[u_, v_, w_] = CoordinateTransformData[{"Hyperspherical", 4} -> "Cartesian", "Mapping", {1, u, v, w}]^2 ``` for a four-dimensional parametrization. This is a bit more elaborate to do, so I'll leave that for the next edit of this answer.
11,797,570
im tying to make these two items inline with each other, each list item has an image and button, the button should be underneath each image: i.e ``` <div id="cocktails"> <ul> <li> <img src ="http://bokertov.typepad.com/.a/6a00d83451bc4a69e2014e8a8f894b970d-800wi" width="100px" height="100px"> <button>Select</button> </li> <li> <img src ="http://bokertov.typepad.com/.a/6a00d83451bc4a69e2014e8a8f894b970d-800wi" width="100px" height="100px"> <button>Select</button> </li> </ul> </div> ``` The CSS: ``` #cocktails ul{margin:0;padding:0} #cocktails ul li{list-style-type:none;display:inline;padding:0} #cocktails ul li img{width:150px;height:150px;display:block;float:left;padding:0 10px} #cocktails ul li button{display:block;float:left} ``` but the buttons are not positioned as expected the jsfiddle is here: <http://jsfiddle.net/8KWGJ/>
2012/08/03
[ "https://Stackoverflow.com/questions/11797570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1551482/" ]
enclose buttons in li tags : ``` <div id="cocktails"> <ul> <li> <img src ="http://bokertov.typepad.com/.a/6a00d83451bc4a69e2014e8a8f894b970d-800wi" width="100px" height="100px"> </li> <li> <button>Select</button> </li> <li> <img src ="http://bokertov.typepad.com/.a/6a00d83451bc4a69e2014e8a8f894b970d-800wi" width="100px" height="100px"> </li> <li> <button>Select</button> </li> </ul> ``` and comment css as shown: ``` #cocktails{float:left;width:419px} #cocktails ul{margin:0;padding:0} #cocktails ul li{list-style-type:none;display:inline;padding:0} /*#cocktails ul li img{width:150px;height:150px;display:block;float:left;padding:0 10px}*/ /*#cocktails ul li button{display:inline;}*/ ```
This did the trick for me. ``` #cocktails ul{margin:0;padding:0} #cocktails ul li{list-style-type:none; width:150px; float:left; margin:10px;} #cocktails ul li img{width:150px;height:150px; } #cocktails ul li button{ margin-left:50px; width:50px} ```
3,914,970
Does anyone (please) know how to do this? I thought that there would be an easy way to achieve this but can't find anything about saving the contents of WebBrowser HTML.
2010/10/12
[ "https://Stackoverflow.com/questions/3914970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/471784/" ]
You might try something like this: (Assuming C# 4 and WPF 4) ``` dynamic doc = webBrowser.Document; var htmlText = doc.documentElement.InnerHtml; ``` Works for me...
Yous should use HttpWebRequest and HttpWebResponse objects. Simple sample (found in web, tested, working): ``` HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(@"http://www.[pagename].com"); myWebRequest.Method = "GET"; HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse(); StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream()); string myPageSource = string.Empty; myPageSource = myWebSource.ReadToEnd(); myWebResponse.Close(); ```
23,363,484
I have TextView with spans of type ClickableStringSpan defined as below: ``` public class ClickableStringSpan extends ClickableSpan { private View.OnClickListener mListener; int color; public ClickableStringSpan(View.OnClickListener listener,int color) { mListener = listener; this.color = color; } @Override public void onClick(View v) { mListener.onClick(v); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); ds.setColor(color); } } ``` I set clickable spans on my text like this: ``` spanStr.setSpan(new ClickableString(new linkedTextClickListener(), linkColor), startIndex, endIndex, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE); ``` Now I want to apply these string to EditTexts instead of TextViews. Everything is fine just Clickable strings are now not clicked anymore. I want to know how can I pass clicks on this sort of spans to their assigned clicklistener? **Update:** My main concern to edit text is I want to allow user select some part of text and share it meanwhile he/she can click on ClickableSpans.
2014/04/29
[ "https://Stackoverflow.com/questions/23363484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1080355/" ]
You need to set the TextView's/EditText's movement method to LinkMovementMethod to be able to get clicked links. Unfortunately that disables the ability to select text which works only if you set the movement method to ArrowKeyMovementMethod. <http://developer.android.com/reference/android/text/method/LinkMovementMethod.html> <http://developer.android.com/reference/android/text/method/ArrowKeyMovementMethod.html> To solve this I created an custom MovementMethod class that inherits from ArrowKeyMovementMethod and adds the ability to click links. : ``` /** * ArrowKeyMovementMethod does support selection of text but not the clicking of links. * LinkMovementMethod does support clicking of links but not the selection of text. * This class adds the link clicking to the ArrowKeyMovementMethod. * We basically take the LinkMovementMethod onTouchEvent code and remove the line * Selection.removeSelection(buffer); * which deselects all text when no link was found. */ public class EnhancedMovementMethod extends ArrowKeyMovementMethod { private static EnhancedMovementMethod sInstance; public static MovementMethod getInstance() { if (sInstance == null) { sInstance = new EnhancedMovementMethod (); } return sInstance; } @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget); } else if (action == MotionEvent.ACTION_DOWN) { Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0])); } return true; } /*else { Selection.removeSelection(buffer); }*/ } return super.onTouchEvent(widget, buffer, event); } } ``` All you need to do is set the movement method of your EditText and you're good to go: ``` yourEditTExt.setMovementMethod(EnhancedMovementMethod.getInstance()); ``` The code above only works with unformatted text, meaning once you decide to format your text using text styles (bold, italic etc.) or different font sizes, it won't find the clicked link any more. I do have the code to deal with formatted text but since that wasn't part of the question I made the sample code as short as possible.
The following code example should work for you, I have also tested and it gives you click events of `ClickableSpanString` May be you have forgot to add `setMovementMethod` ``` EditText spanEditText = (EditText)rootView.findViewById(R.id.edtEmailId); // this is the text we'll be operating on SpannableStringBuilder text = new SpannableStringBuilder("World Super Power God LOVE"); // make "World" (characters 0 to 5) red text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0); // make "Super" (characters 6 to 11) one and a half time bigger than the textbox text.setSpan(new RelativeSizeSpan(1.5f), 6, 11, 0); // make "Power" (characters 12 to 17) display a toast message when touched final Context context = getActivity().getApplicationContext(); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View view) { Toast.makeText(context, "Power", Toast.LENGTH_LONG).show(); } }; text.setSpan(clickableSpan, 12, 17, 0); // make "God" (characters 18 to 21) struck through text.setSpan(new StrikethroughSpan(), 18, 21, 0); // make "LOVE" (characters 22 to 26) twice as big, green and a link to this site. // it's important to set the color after the URLSpan or the standard // link color will override it. text.setSpan(new RelativeSizeSpan(2f), 22, 26, 0); text.setSpan(new ForegroundColorSpan(Color.GREEN), 22, 26, 0); // make our ClickableSpans and URLSpans work spanEditText.setMovementMethod(LinkMovementMethod.getInstance()); // shove our styled text into the TextView spanEditText.setText(text, BufferType.EDITABLE); ```
39,391,552
[I am unsure how to implement a sliding imageview like the one in the top of this screenshot.](http://i.stack.imgur.com/b45OG.jpg) I am using Eureka forms and I'm trying to include this sliding imageview as a header. At the moment I am using a custom view and this [Library](https://github.com/zvonicek/ImageSlideshow) I think the root of my issue is caused by the gesture recognizer and the method "click". Xcode throws an error on the `self.presentViewController(ctr,animated: true,completion:nil)` line. I understand it can't present a viewcontroller inside a UIView. I'm just unsure of how I can achieve the same result of presenting the view controller inside the UIView sub class. Here is my code: ``` class profilePicHeader: UIView { let slideshow = ImageSlideshow() var slideshowTransitioningDelegate: ZoomAnimatedTransitioningDelegate? override init(frame: CGRect) { super.init(frame: frame) let localSource = [ImageSource(imageString: "GardenExample")!,ImageSource(imageString: "OvenExample")!] slideshow.backgroundColor = UIColor.whiteColor() slideshow.pageControlPosition = PageControlPosition.UnderScrollView slideshow.pageControl.currentPageIndicatorTintColor = UIColor.lightGrayColor(); slideshow.pageControl.pageIndicatorTintColor = UIColor.blackColor(); slideshow.contentScaleMode = UIViewContentMode.ScaleAspectFill slideshow.setImageInputs(localSource) let recognizer = UITapGestureRecognizer(target: self, action: #selector(profilePicHeader.click)) slideshow.addGestureRecognizer(recognizer) slideshow.frame = CGRectMake(0, 0, 320, 200) slideshow.autoresizingMask = .FlexibleWidth self.frame = CGRectMake(0, 0, 320, 130) slideshow.contentMode = .ScaleAspectFit self.addSubview(slideshow) } func click() { let ctr = FullScreenSlideshowViewController() ctr.pageSelected = {(page: Int) in self.slideshow.setScrollViewPage(page, animated: false) } ctr.initialImageIndex = slideshow.scrollViewPage ctr.inputs = slideshow.images slideshowTransitioningDelegate = ZoomAnimatedTransitioningDelegate(slideshowView: slideshow, slideshowController: ctr) // Uncomment if you want disable the slide-to-dismiss feature on full screen preview // self.transitionDelegate?.slideToDismissEnabled = false ctr.transitioningDelegate = slideshowTransitioningDelegate self.presentViewController(ctr, animated: true, completion: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } ```
2016/09/08
[ "https://Stackoverflow.com/questions/39391552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6809177/" ]
Try this: ``` SET @partHello = SUBSTRING(@helloworld,CHARINDEX('=',@helloworld,0)+1,CHARINDEX('&',@helloworld,0)-(CHARINDEX('=',@helloworld,0))-1) PRINT @partHello ```
There is the solution : ``` DECLARE @helloworld NVARCHAR(100),@partHello NVARCHAR(10) SET @helloworld='HelloWorld=320&HelloSQL=20' SET @partHello = SUBSTRING(@helloworld,CHARINDEX('=',@helloworld,0)+1,CHARINDEX('&',@helloworld,0) -(CHARINDEX('=',@helloworld,0)+1)) PRINT @partHello ```
25,829
Recently there was a question that incidentally included an ungrammatical example: “¿[Puedo tener un vaso de agua](https://spanish.stackexchange.com/questions/25806/how-do-you-use-se-puede)?”, obviously a literal translation from English “¿May I have a glass of water?”. This wasn't the subject of the question but I think it would be useful to clarify the matter. So: how would you properly express, in Spanish, the request “to have (a drink, a bite, a piece of something)”?
2018/04/13
[ "https://spanish.stackexchange.com/questions/25829", "https://spanish.stackexchange.com", "https://spanish.stackexchange.com/users/14627/" ]
I think the crux of the matter is to learn which verbs are used to talk about eating and drinking. In English, when we eat or drink something, we use "to have." Some examples: > > Could we have chicken soup for lunch? > > > I'd like to have lunch before I hit the road. > > > In France people usually have a glass of wine with dinner. > > > In Spanish, in all these cases, **have** *doesn't work*. Here are the three examples, expressed idiomatically in Spanish: > > ¿Podríamos **tomar** caldo de pollo hoy al mediodía? > > > Me gustaría **comer** antes de lanzarme. > > > En Francia suelen **tomar** un vaso de vino con la cena. > > >
* ¿Puedo tomar un vaso de agua? * ¿Puedo tomar agua? * ¿Puedo tomar algo de agua? `¿Puedo tener un vaso de agua?` sounds like you are asking for confirmation whether you are capable or not of doing so. This does not mean you're thirsty and want some water. This may be correct in formal Spanish: ¿Puedo tomar un vaso de agua? Hope this was helpful.
3,429,791
Question. Given a positive semi-definite matrix $B$ does there exist a non-zero vector $z$ with all components non-negative such that all components of $Bz$ are non-negative? Here are some details (which you probably do not need, if you understand what is asked above). I posted an answer to the following question [check for a compact set](https://math.stackexchange.com/q/3428668) , and in my answer I used a claim which I believe ought to be true, but I do not know. Suppose that $B$ is an $m\times m$ positive semi-definite matrix. If $y,z$ are (column) vectors with $m$ components each, define $z\ge y$ if $z\_j\ge y\_j$ for all $1\le j\le m$, and define $z\neq y$ if $z\_j\neq y\_j$ for at least one $1\le j\le m$. Question. Does there exist $z\ge0$ with $z\neq0$ such that $Bz\ge0$ ? (That is, does there exist a non-zero vector $z$ with all components non-negative such that all components of $Bz$ are non-negative? Here $B$ is a positive semi-definite matrix, and $0$ is the zero vector with $m$-many components.) If $Bz=0$ for some non-zero $z\ge0$ then we are done. If $Bz$ is non-zero whenever $z\ge0$ is non-zero, but if the angle between $z$ and $Bz$ is zero, for some such $z$, then again we are done. If the angle is always non-zero, then we may define a vector field on a suitable sub-space of surface and use a combing, or a fixed-point theorem I would think, except I didn't think hard enough how to do this. Something like, consider only $z\ge0$ with $||z||=1$ and assign to such $z$ the non-zero vector $\frac{Bz}{||Bz||}-z$ (or perhaps, better, assign $Bz-z$ or $\frac{Bz-z}{||Bz-z||}$.) Or, perhaps it is just a matter of solving a certain system of equations, using the properties of the matrix $B$. (I do not know if $B$ is required to be symmetric in the linked question, it shouldn't matter, I think we could assume it if it helps.) I am sure the answer to this question ought to be known, and I would be grateful for any details or a reference. Thank you! I tend to believe the answer would come using methods of linear algebra and/or convex optimization, but I did come up with a topological (not purely topological, as it involves the standard metric) question which could be thought of as a generalization of the present one. [Do the closed unit disk $D$ and $f(D)$ intersect, if $||f(x)-x||\le2$ for all $x\in D$?](https://math.stackexchange.com/q/3429946)
2019/11/10
[ "https://math.stackexchange.com/questions/3429791", "https://math.stackexchange.com", "https://math.stackexchange.com/users/188367/" ]
When talking about a real function $f(x) = y$ all extremes of the function are either critical points, boundary points or points which diverge to infinity, so all you need to do is to look at the value of the function at these points to determine the maximum and the minimum of the function. Here you need to consider $$\lim\_{x\to\pm\infty}f(x) $$ as well. i think that's what confused you here, always consider the boundaries of the function you're looking at, which in the case of this function is $\pm\infty$ as it is defined for all real numbers.
To find out if a critical point is an extreme point, check the sign of the first derivative near that point -- that is, find out the value of the first derivative at points close to the point in question on either side. What do you check for -- a change of sign, either from $+$ to $-$ or vice versa. This is necessary and sufficient to show that the point in question is an extreme point. This means that if the first derivative maintains its sign close to where it vanishes, then you do not have an extreme point there. Here you have that $$f'(x)=\frac83x^{5/3}-\frac83x^{-1/3}=\frac83x^{-1/3}\left(x^2-1\right),$$ so that your critical points are $x=\pm 1.$
9,653,621
in a flash application i have to build i would like to find out what the target of the context menu is, which gets displayed when i ctrl-click. the reason for that: i created a custom context menu, which only displays over a certain area of the Sprite it belongs to. so there seems to be something "blocking the way". any ideas? thanks!
2012/03/11
[ "https://Stackoverflow.com/questions/9653621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039806/" ]
No, it is not possible. You can not make call from one simulator to another. Hope this helps.
Unfortunately it's impossible. You have to use a real devices if you want to test some stuff.
29,333
In the sentence, > > I asked her if she was going shopping and could get me some toothpaste > > > Is *shopping* a noun,verb or a gerund? Can we put two verbs together like this: “I am going swimming this, Friday.”
2014/07/16
[ "https://ell.stackexchange.com/questions/29333", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/8787/" ]
In this particular case, "to go shopping" is part of a broader pattern of "to go X-ing". Other examples include "I'm going bowling", "I'm going fishing", "I'm going running", etc. I would classify *shopping* in this case as a gerund. To answer your second question, most verbs that can be used in this pattern are leisure activities (hiking, swimming, riding). One interesting case is that "to go drinking" is fairly common, while "to go eating" is not. See [the wiktionary entry for *go*](http://en.wiktionary.org/wiki/go#Verb), definition 30.
Some grammar books don't use the specialised term 'gerund'. Michael Swan, in 'Practical English Usage' (3rd ed, 2005, section 293 and following), calls it the '-ing form'. He writes: > > We can use *-ing* forms (e.g. *smoking*, *walking*) not only as verbs, > but also like adjectives or nouns. Compare: > > > *You're **smoking** too much these days.* (verb: part of present progressive) > > > *There was a **smoking** cigarette end in the ashtray.* (adjective describing *cigarette end*) > > > ***Smoking*** is bad for you. (noun: subject of sentence) > > >
7,556,060
> > **Possible Duplicate:** > > [string split in java](https://stackoverflow.com/questions/3481828/string-split-in-java) > > > I have this `Key - Value` , and I want to separate them from each other and get return like below: ``` String a = "Key" String b = "Value" ``` so whats the easiest way to do it ?
2011/09/26
[ "https://Stackoverflow.com/questions/7556060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/879131/" ]
``` String[] tok = "Key - Value".split(" - ", 2); // TODO: check that tok.length==2 (if it isn't, the input string was malformed) String a = tok[0]; String b = tok[1]; ``` The `" - "` is a regular expression; it can be tweaked if you need to be more flexible about what constitutes a valid separator (e.g. to make the spaces optional, or to allow multiple consecutive spaces).
``` String[] parts = str.split("\\s*-\\s*"); String a = parts[0]; String b = parts[1]; ```
2,558
How can you automatically mute the audio in Windows every time you shut down?
2009/07/15
[ "https://superuser.com/questions/2558", "https://superuser.com", "https://superuser.com/users/1480/" ]
[AutoMute](http://www.karpolan.com/software/auto-mute/) - a little portable program designed specifically for this. Automatically mutes on logoff, shutdown, so the next start up is quiet. Also enables a keyboard shortcut for quick quieting down. ![alt text](https://i.stack.imgur.com/MhGkV.jpg)
This has been answered, and I'm sure the solution works. Still, I'm posting because this possible solution which does not require any third party application. It is a bit drastic in that it shuts down the audio subsystem (driver) completely, not just muting the mixer. Run a command prompt as administrator, and type the following: ``` net stop "Audiosrv" ``` to start the audio subsystem again, type the following: ``` net start "Audiosrv" ``` If you log off or sleep, this will work. A full shutdown/restart resets the audio back on. The possible downside is some programs might display an error message when trying to play audio while the audio subsystem is disabled. (Winamp shows an annoying message box, while iTunes simply pauses peacefully.)
41,092,129
My app crashes when I invoke alert dialogue within a list item. My app lists cars, every item has 2 buttons, each button calls alertdialog for yes/no answer. the app crashes with "You need to use a Theme.AppCompat theme (or descendant) with this activity." everytime I press the button. App code is as follows: AndroidManifest: ``` <activity android:name=".SplashScreen" android:theme="@style/generalnotitle"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".CarActivity" android:theme="@style/generalnotitle"></activity> </application> ``` Style: ``` <resources> <style name="generalnotitle" parent="Theme.AppCompat.Light"> <item name="android:windowNoTitle">true</item> <item name="android:screenOrientation">portrait</item> </style> </resources> ``` CarActivity.java ``` public class CarActivity extends AppCompatActivity { String[] car_tag, car_makemodel, car_owner_id; TypedArray car_pic; String[] aa_owner_id, aa_owner_name, aa_owner_tlf; String tlf, name; List<CarItem> carItems; ListView mylistview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("list start", "list start" ); getSupportActionBar().hide(); setContentView(R.layout.activity_list); mylistview = (ListView) findViewById(R.id.LList); setUpListView(); } public void setUpListView() { carItems = new ArrayList<CarItem>(); // gets car info car_pic = getResources().obtainTypedArray(R.array.a_carpic); car_tag = getResources().getStringArray(R.array.a_mat); car_makemodel = getResources().getStringArray(R.array.a_makemodel); car_owner_id = getResources().getStringArray(R.array.a_owner); //defines items for (int i = 0; i < car_tag.length; i++){ CarItem item = new CarItem(car_pic.getResourceId(i, -1), car_tag[i], car_makemodel[i], car_owner_id[i]); Log.e("CarActivity", car_tag[i] ); carItems.add(item); } //gets available owners aa_owner_id = getResources().getStringArray(R.array.a_id); aa_owner_name = getResources().getStringArray(R.array.a_name); aa_owner_tlf = getResources().getStringArray(R.array.a_tlf); //populates the list CarAdapter adapter = new CarAdapter(getApplicationContext(), carItems, aa_owner_id , aa_owner_name, aa_owner_tlf); mylistview.setAdapter(adapter); } } ``` CarAdapter.java ``` public class CarAdapter extends BaseAdapter { Context context; List<CarItem> carItems; String [] a_owner_id, a_owner_names, a_owner_tlf; String name, tlf, owner_id; CarAdapter(Context context, List<CarItem> carItems, String [] a_owner_id, String [] a_owner_names, String [] a_owner_tlf){ this.context = context; this.carItems = carItems; this.a_owner_id = a_owner_id; this.a_owner_names = a_owner_names; } public View getView(int position, View convertView, ViewGroup parent){ ViewHolder holder = null; LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); if (convertView == null){ convertView = mInflater.inflate(R.layout.row_car,null); holder = new ViewHolder(); holder.car_pic = (ImageView) convertView.findViewById(R.id.car_pic); holder.tag = (TextView) convertView.findViewById(R.id.tag); holder.makemodel = (TextView) convertView.findViewById(R.id.make_model); holder.owner = (TextView) convertView.findViewById(R.id.owner); holder.blck = (Button) convertView.findViewById(R.id.block); holder.mov = (Button) convertView.findViewById(R.id.move); CarItem row_pos = carItems.get(position); holder.car_pic.setImageResource(row_pos.getCar_pic()); holder.tag.setText(row_pos.getTag()); holder.makemodel.setText(row_pos.getMakemodel()); owner_id = row_pos.getOwner(); getOwner(owner_id); holder.owner.setText(name); holder.blck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBlockClick(); } }); holder.mov.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("CarAdapter move click", owner_id ); } }); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } return convertView; } private void onBlockClick() { Log.e("CarActivity", "CLICK block button" ); AlertDialog.Builder alertDlg = new AlertDialog.Builder(context); alertDlg.setMessage("Do you wish to inform " + name + "?"); alertDlg.setCancelable(false); alertDlg.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Get owner phone number getNumber(owner_id); Log.e("CarActivity YES DIALOG", tlf ); //Toast.makeText(getApplicationContext(),"Afasta-me o teu cangalho...", Toast.LENGTH_SHORT).show(); } }); alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.e("CarActivity", "CLICK NO DIALOG" ); } }); alertDlg.create().show(); } } ``` SOLUTION: when I set adapter, i was sending "getApplicationContext()" but instead i sent "this" and this way i could send the context to the adapter. CarActivity.java: before: ``` CarAdapter adapter = new CarAdapter(getApplicationContext(), carItems, aa_owner_id , aa_owner_name, aa_owner_tlf); ``` after: ``` CarAdapter adapter = new CarAdapter(this, carItems, aa_owner_id , aa_owner_name, aa_owner_tlf); ```
2016/12/11
[ "https://Stackoverflow.com/questions/41092129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3091252/" ]
``` fields: () => ({ field: {/*etc.*/} }) ``` is a function that implicitly returns an object (literal). Without using `()` JavaScript interpreter interprets the `{}` as a wrapper for the function body and not as an object. Without using parens: `()`, the `field: ...` statement is treated as a `label` statement and the function returns `undefined`. The equivalent syntax is: ``` fields: () => { // start of the function body // now we have to define an object // and explicitly use the return keyword return { field: {/*etc.*/} } } ``` So parents are not there for clarity. It's there for using implicit-returning feature of arrow functions.
It's for clarity's sake for the compiler as well as for the reader. The `field:` syntax in your example appears to be an unambiguous giveaway that this is an object literal, but take this code for instance: ```js let f = () => { field: 'value' } console.log(f()) //=> undefined ``` You would expect this to log an object with `field` set to `'value'`, but it logs `undefined`. Why? Essentially, what you see as an object literal with a single property, the compiler sees as a function body (denoted by opening and closing curly braces, like a typical function) and a single [label statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label), which uses the syntax `label:`. Since the expression following is it just a literal string, and it is never returned (or even assigned to a variable), the function `f()` effectively does nothing, and its result is `undefined`. However, by placing parentheses around your "object literal," you tell the compiler to treat the same characters as an expression rather than a bunch of statements, and so the object you desire is returned. (See [this article on the Mozilla Development Network](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals), from the comments section.) ```js let g = () => ({ field: 'value' }) console.log(g()) //=> { field: 'value' } ```
44,305,232
This is my site **<https://www.reportsbuyer.com/Home>** I want to remove Home in that url using htaccess. I given like this `RewriteRule ^(Home(/index)?|index(\.php)?)/?$ / [L,R=301]` but it will return <https://www.reportsbuyer.com/?/Home> like this. Please give me a solution. Thanks
2017/06/01
[ "https://Stackoverflow.com/questions/44305232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6333745/" ]
Here's the answer to new update: In API 33 we need runtime permission for push notification: Full documentation is available [here](https://developer.android.com/about/versions/13/changes/notification-permission) but you can simply use like below : in app level: ``` <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> ``` you can trigger the prompt using this: ``` pushNotificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS) ``` handle notification result: ``` private val pushNotificationPermissionLauncher = registerForActivityResult(RequestPermission()) { granted -> viewModel.inputs.onTurnOnNotificationsClicked(granted) } ```
Try this: In your Activity class, add the below code: ``` private static final int NOTIFICATION_PERMISSION_CODE = 123; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_activity); requestNotificationPermission(); // Some code } private void requestNotificationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY) == PackageManager.PERMISSION_GRANTED) return; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NOTIFICATION_POLICY)) { } ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NOTIFICATION_POLICY}, NOTIFICATION_PERMISSION_CODE ); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // Checking the request code of our request if (requestCode == NOTIFICATION_PERMISSION_CODE ) { // If permission is granted if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Displaying a toast Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show(); } else { // Displaying another toast if permission is not granted Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show(); } } } ```
1,268,665
People arrive to the ER of a hospital following a poisson process with $\lambda=2.1$ patients/hour. One of each 28 who arrives under this condition, dies. Calculate the probability of: (a) At least one of the patients that arrive today, dies. (b) The maximum of patients that die today, is 4. If I let $N(t)$ be the number of patients that arrive to the ER at time $t$ and I know that each patient dies with probability $\frac{1}{28}$, is the patient $k$ will be dead by time $t$ with probability $p(k)=\mathbb{P}[W\_k\leq t]\frac{1}{28}$? Can I use this to define $X(t)$ (the number of patients dead) in terms of $N(t)$, or what will be the best way to do this? Thanks in advance.
2015/05/05
[ "https://math.stackexchange.com/questions/1268665", "https://math.stackexchange.com", "https://math.stackexchange.com/users/237971/" ]
How does $\{a\}$ differ from $\{\{a\}\}$? Well, Omnomnomnom and vadim123 have pointed out the key differences, but perhaps a small elaboration will help. Is $a\in\{a\}$? Yes. Is $a\in\{\{a\}\}$? Well, $a\neq\{a\}$ so the answer is a resounding no. Ah, but do you know what it means for a set to be a subset of another set? If $A$ is a subset of $B$, then this is often denoted by $A\subseteq B$ and may be thought of as "if $x$ is $A$, then $x$ is in $B$"; symbolically, $A\subseteq B$ may be represented as $x\in A\to x\in B$. This illustrates some key points: * $a\in \{a\}$ * $\{a\}\in\{\{a\}\}$ * $\color{blue}{\{a\}\subseteq \{a\}}$ * $\color{blue}{\{a\}\not\in\{a\}}$ Pay special attention to the last two points highlighted in blue.
The set $\{\{a\}\}$ is the set whose only object is the set $\{a\}$. $\{a\}$, in turn, is a set whose only object is $a$. It might help to consider the set $$ \{a,\{a\},\{b\}\} $$ whose objects are $a$, the set $\{a\}$, and the set $\{b\}$. Note that this set is quite different from $\{a,b\}$.
597,426
Treating light as a wave, we define its frequency. We see that light with different frequency have different colour. But, why? In wave, what property or physical meaning does frequency provide?
2020/12/01
[ "https://physics.stackexchange.com/questions/597426", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/271983/" ]
Let us take the classical electromagnetic picture in which our 3d space is permeated by an electromagnetic field. This basically means that at any point in space we may define a field strength and direction $\mathbf{E}$ of the electric field, and also an associated magnetic field strength and direction $\mathbf{B}$. Let us for the moment assume that these strengths are fixed in time. Any charged particle located in this spatial point will then feel a Coulomb force, proportional to the strength of the field and along its respective direction. We speak of light as an electromagnetic wave since it produces a ripple through the electromagnetic field, much like a stone thrown into water produces ripples in the water's surface. Physically this means that at any point in space the value and direction of the electric and magnetic field oscillate with time. This also means that my charged particle will now feel a changing force where before it was fixed, and start moving with the wave. This is the actual observable effect of a ripple in the electromagnetic field, that we refer to as light. Now the frequency of the light is related to how quickly this oscillation of the field strength occurs. One may imagine that the charged particle can be made to oscillate very quickly or very slowly, depending on how fast $\mathbf{E}$ flips its sign. In your question you refer to the concept of colour specifically. Our eyes take the frequency of the ripples in the electromagnetic field which interacts with particles in your eye, and translate this oscillation frequency to a sensation that we percieve as colour. Obviously this is a heavily simplified picture, and I am not so well versed in biophysics so maybe someone else can help you out with the specifics there. I hope that at least the physical picture is somewhat clearer now.
> > What is the physical meaning of frequency in wave concept? > > > A wave doesn't necessarily have *a* frequency though periodic waves will have a [fundamental frequency](https://en.wikipedia.org/wiki/Fundamental_frequency). But not all waves are periodic. [For example](https://en.wikipedia.org/wiki/Wave_packet#/media/File:Wave_packet_(no_dispersion).gif), consider a single wave packet which is oscillatory but not periodic (note: the replaying animation below should not be interpreted as periodic *train* of wave packets) [![enter image description here](https://i.stack.imgur.com/Htn3G.gif)](https://i.stack.imgur.com/Htn3G.gif) For the case of a periodic wave, the fundamental frequency is the inverse of the period which is essentially the time required for the traveling wave spatial pattern to return to its starting pattern (starting at some arbitrary time $t\_0$). Consider for example a traveling wave described by $$\psi(x,t) = \cos(kx -\omega t),\quad\omega = kc$$ where $c$ is the speed of the traveling wave. Now, since $\cos(\cdot)$ is periodic in its argument: $$\cos(\phi + n\cdot 2\pi) = \cos(\phi)$$ where $n$ is an integer, it follows that $$\psi\left(x,t\_0 - \frac{2\pi}{\omega}\right) = \cos(kx - \omega t\_0 + 2\pi) = \cos(kx - \omega t\_0) = \psi(x,t\_0)$$ Thus, this wave has a period $T$ of $$T = \frac{2\pi}{\omega} = \frac{1}{\nu}$$ where $\nu = \frac{\omega}{2\pi}$ is the frequency of the wave $\psi(x,t)$. That is, the wave returns the starting spatial pattern after $T$ seconds. Since the frequency is the inverse of the period, the frequency of the wave tells one *how many times per second the wave's spatial pattern returns to its starting pattern*.
16,979,793
I have a ratchet chat server file ``` use Ratchet\Server\IoServer; use Ratchet\WebSocket\WsServer; use MyAppChat\Chat; require dirname(__DIR__) . '/vendor/autoload.php'; $server = IoServer::factory( new WsServer( new Chat() ) , 26666 ); $server->run(); ``` I using Websocket to connect with `ws` and it works fine ``` if ("WebSocket" in window) { var ws = new WebSocket("ws://ratchet.mydomain.org:8888"); ws.onopen = function() { // Web Socket is connected. You can send data by send() method. ws.send("message to send"); }; ws.onmessage = function (evt) { var received_msg = evt.data; }; ws.onclose = function() { // websocket is closed. }; } else { // the browser doesn't support WebSocket. } ``` I want secure connection, so I try to connect with SSL but is not work. ``` if ("WebSocket" in window) { var ws = new WebSocket("wss://ratchet.mydomain.org:8888"); ws.onopen = function() { // Web Socket is connected. You can send data by send() method. ws.send("message to send"); }; ws.onmessage = function (evt) { var received_msg = evt.data; }; ws.onclose = function() { // websocket is closed. }; } else { // the browser doesn't support WebSocket. } ``` My question is **how to connect websocket with SSL connection** Any idea?
2013/06/07
[ "https://Stackoverflow.com/questions/16979793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1451383/" ]
A few days ago I was looking for the answer of this question and I found this in the Github Ratchet issues: <https://github.com/ratchetphp/Ratchet/issues/489> The last answer, answered by [heidji](https://github.com/heidji), says this: > > I only added this comment for newbies like me who need a quick instruction how to implement SSL: > Via the ReactPHP docs you only need to construct the SecureServer mentioned in such manner: > > `$webSock = new React\Socket\Server('0.0.0.0:8443', $loop);` > `$webSock = new React\Socket\SecureServer($webSock, $loop, ['local_cert' => '/etc/ssl/key.pem', 'allow_self_signed' => true, 'verify_peer' => false]);` > > and then inject into the IoServer as mentioned by cboden above > > > So it seems that now there is a way to implement a secure websocket server with Ratchet without needing an HTTPS proxy. Here you have the SecureServer class documentation: <https://github.com/reactphp/socket#secureserver>
I was trying to do this for a subdomain. Ex: Redirect realtime.domain.org to localhost:8080 from apache. Here's how it worked. You can create a virtual host and proxy pass that. ``` <VirtualHost *:80> ServerName realtime.domain.org RewriteEngine On RewriteCond %{HTTP:Connection} Upgrade [NC] RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteRule /(.*) ws://localhost:8080/$1 [P,L] ProxyPreserveHost On ProxyRequests off ProxyPass / http://localhost:8080/ ProxyPassReverse / http://localhost:8080/ </VirtualHost> ``` So, all the requests to realtime.domain.org can be redirected to port 8080, where you can run the WebSocket handler.
10,867,390
I'm doing a fairly complex NHibernate transaction in a financial system, creating a payment, recording the ledger entries, checking to see if the payment is the total amount of an invoice, if so marking the invoice as paid in full, etc... lots of fun stuff. Naturally it has to happen inside a single transaction. When I try to commit the change to the session, I get the following error: ``` Error dehydrating property value for C3.DataModel.CFAPTransaction.Vendor ``` Googling this did not turn up many record. Can someone tell me what this means and where I need to focus my debugging efforts? **UPDATE** Per request, here is the full error message: > > > ``` > NHibernate.PropertyValueException: Error dehydrating property v alue for C3.DataModel.CFAPTransaction.Vendor ---> > > ``` > > NHibernate.HibernateException: Unable to resolve property: APVendorId > at NHibernate.Tuple.Entity.EntityMetamodel.GetPropertyIndex(String > propertyName) at > NHibernate.Tuple.Entity.AbstractEntityTuplizer.GetPropertyValue(Object > entity, String propertyPath) at > NHibernate.Persister.Entity.AbstractEntityPersister.GetPropertyValue(Object > obj, String propertyName, EntityMode entityMode) at > NHibernate.Type.EntityType.GetIdentifier(Object value, > ISessionImplementor session) at > NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, > Int32 index, Boolean[] settable, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) --- End of inner exception > stack trace --- at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, > Object obj, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Object obj, ISessionImplementor session) at > NHibernate.Action.EntityInsertAction.Execute() at > NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at > NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at > NHibernate.Engine.ActionQueue.ExecuteActions() at > NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource > session) at > NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent > event) at NHibernate.Impl.SessionImpl.Flush() at > NHibernate.Transaction.AdoTransaction.Commit() at > C3.DataModel.Repositories.NHUnitOfWork.Save() in > C:\projects\C3\C3.DataModel.Generated\Generated\NHibernateRepositories.generated.cs:line > 2659 at > C3.WebUI.Areas.Finance.Controllers.AccountsPayableController.CreatePayment(CreatePaymentModel > model) in > C:\projects\C3\C3.WebUI\Areas\Finance\Controllers\AccountsPayableController.cs:line > 434 > > > **UPDATE** Throwing NHibernate into DEBUG mode, I get a bunch of stuff like this: > > processing cascade > NHibernate.Engine.CascadingAction+SaveUpdateCascadingAction for: > C3.DataModel.APVendor > cascade NHibernate.Engine.CascadingAction+SaveUpdateCascadingAction for > collection: C3.DataModel.APVendor.Transactions > done cascade NHibernate.Engine.CascadingAction+SaveUpdateCascadingAction for > collection: C3.DataModel.APVendor.Transactions > done processing cascade NHibernate.Engine.CascadingAction+SaveUpdateCascadingAction for: > C3.DataModel.APVendor > NHibernate.Event.Default.AbstractFlushingEventListener ERROR Could not synchronize database state with session > NHibernate.PropertyValueException: Error dehydrating property value for C3.DataModel.CFAPTransaction.Vendor ---> > NHibernate.HibernateException: Unable to resolve property: APVendorId > at NHibernate.Tuple.Entity.EntityMetamodel.GetPropertyIndex(String > propertyName) at > NHibernate.Tuple.Entity.AbstractEntityTuplizer.GetPropertyValue(Object > entity, String propertyPath) at > NHibernate.Persister.Entity.AbstractEntityPersister.GetPropertyValue(Object > obj, String propertyName, EntityMode entityMode) at > NHibernate.Type.EntityType.GetIdentifier(Object value, > ISessionImplementor session) at > NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, > Int32 index, Boolean[] settable, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) --- End of inner exception > stack trace --- at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, > Object obj, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Object obj, ISessionImplementor session) at > NHibernate.Action.EntityInsertAction.Execute() at > NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at > NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at > NHibernate.Engine.ActionQueue.ExecuteActions() at > NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource > session) > C3.WebUI.Areas.Finance.Controllers.AccountsPayableController ERROR C3.WebUI.Areas.Finance.Controllers.AccountsPayableController: > No additional information. > NHibernate.PropertyValueException: Error dehydrating property value for C3.DataModel.CFAPTransaction.Vendor ---> > NHibernate.HibernateException: Unable to resolve property: APVendorId > at NHibernate.Tuple.Entity.EntityMetamodel.GetPropertyIndex(String > propertyName) at > NHibernate.Tuple.Entity.AbstractEntityTuplizer.GetPropertyValue(Object > entity, String propertyPath) at > NHibernate.Persister.Entity.AbstractEntityPersister.GetPropertyValue(Object > obj, String propertyName, EntityMode entityMode) at > NHibernate.Type.EntityType.GetIdentifier(Object value, > ISessionImplementor session) at > NHibernate.Type.ManyToOneType.NullSafeSet(IDbCommand st, Object value, > Int32 index, Boolean[] settable, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) --- End of inner exception > stack trace --- at > NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object > id, Object[] fields, Object rowId, Boolean[] includeProperty, > Boolean[][] includeColumns, Int32 table, IDbCommand statement, > ISessionImplementor session, Int32 index) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, > Object obj, ISessionImplementor session) at > NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, > Object[] fields, Object obj, ISessionImplementor session) at > NHibernate.Action.EntityInsertAction.Execute() at > NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at > NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at > NHibernate.Engine.ActionQueue.ExecuteActions() at > NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource > session) at > NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent > event) at NHibernate.Impl.SessionImpl.Flush() at > NHibernate.Transaction.AdoTransaction.Commit() at > C3.DataModel.Repositories.NHUnitOfWork.Save() in > C:\projects\C3\C3.DataModel.Generated\Generated\NHibernateRepositories.generated.cs:line > 2659 at > C3.WebUI.Areas.Finance.Controllers.AccountsPayableController.CreatePayment(CreatePaymentModel > model) in > C:\projects\C3\C3.WebUI\Areas\Finance\Controllers\AccountsPayableController.cs:line > 434 > > > It does not appear this is occurring when querying the database. I have a feeling it has problems with me creating a bunch of objects, relating them, and then trying to persist them, but that's a pure guess.
2012/06/03
[ "https://Stackoverflow.com/questions/10867390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610217/" ]
In my case it was a missing Identity Specification on the SQL-Server. Simple object: ``` public class Employee { public virtual int ID { get; set; } } ``` Mapping: ``` public class EmployeeMap : ClassMapping<Employee> { public EmployeeMap() { Id(x => x.ID, map => { map.Generator(Generators.Identity); map.UnsavedValue(0); }); } } ``` SQL: Here is the ID column with the primary key constraint. [![ID column with constraint](https://i.stack.imgur.com/B5mdz.png)](https://i.stack.imgur.com/B5mdz.png) And here you can see the missing Identity Specification, which is causing the problem. [![Missing Identity Specification](https://i.stack.imgur.com/rxVfU.png)](https://i.stack.imgur.com/rxVfU.png) To solve the problem, you have to specify the ID column as `IDENTITY` i.e. ``` CREATE TABLE EMPLOYEE ( ID int NOT NULL IDENTITY(0, 1) ); ```
In my case, the exception was accurately identifying the property that was the cause of the error. I had a many-to-one property that was lacking a `cascade` definition. `"save-update"` prevents the error: ``` <many-to-one name="FocusType" cascade="save-update" class="MyInfrastructure.FocusType, MyInfrastructure"> <column name="FocusTypeId" sql-type="int" not-null="false" /> </many-to-one> ```
42,993,456
How can I sum the below: ``` > result.vol3 [,1] [1,] 272225 [2,] 523750 [3,] 20211 [4,] 316165 [5,] 9941469 [6,] 193755 [7,] 40663 [8,] 236746 [9,] 25902 [10,] 79943 [11,] 585326 [12,] 129376 ... till [100,] ``` Its a matrix, but within the matrix its a data.frame/array. I'm unable to compute using colSums or any other straightforward method.
2017/03/24
[ "https://Stackoverflow.com/questions/42993456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7609563/" ]
For me, the issue happens, when I use UPPERCASE UUID, instead of lowercase one: ``` // does not work: $ rvictl -s F320D3ED185C4CD28FC96E48119D6E39 // works: $ rvictl -s f320d3ed185c4cd28fc96e48119d6e39 ```
here is what worked for me: Make sure that all letters are lower case, took me a min to figure this out. ``` za:news za$ rvictl -s 8adca3ef84c9d647d32644a30cc448185ae39108 Starting device 8adca3ef84c9n647d32644a30cc448185de39108 [SUCCEEDED] with interface rvi0 ``` The new interface is now added, this one rvi0: ``` $ ifconfig -l lo0 gif0 stf0 en0 en1 en2 p2p0 awdl0 bridge0 `rvi0` ``` When running the command with all upper case,upper cased UUID number, no sterr no stdout either, just dies silently: ``` za$ rvictl -s 8ADCA3EF84C9D647N32644A30CC448185DE39108 za$ rvictl -L Could not get list of devices ```
30,724,566
I am new to uiautomator.In a screen i want to select an element with its resource id.But there is so many elements have the same resource id(for example in Instagram app profile all videos and images having the same resource id ).Is there any way so that i can get a list of all these elements with same resource id ?Only distinguishable feature for the element is its index.
2015/06/09
[ "https://Stackoverflow.com/questions/30724566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4277129/" ]
I got its solution.I just edit my.csproj file by hand and remove the 'CodesignEntitlements' key. I found this solution from [here](http://forums.xamarin.com/discussion/39534/cant-build-ios-in-xamarin-studio-5-7-1-through-5-9) and thank you Gerald Versluis for helping me through facing this problem.
The details from Gerald Versluis were helpful for me. The got me 90% of the way through the task. I was getting the same build error on Visual Studio 2015 with Mac Mini build host. The solution for me was to go back to Certificates, Identifiers & Profiles in <https://developer.apple.com/account/ios/profile/create> and ENSURE that I configured a profile. here is an image [![enter image description here](https://i.stack.imgur.com/9G54q.png)](https://i.stack.imgur.com/9G54q.png) It was only after I did that did I see a record available for download in the Accounts modal windows of the XCode preferences, as shown below. [![enter image description here](https://i.stack.imgur.com/ryPmM.png)](https://i.stack.imgur.com/ryPmM.png) After I clicked "Download All" THEN the build was successful in VS 2015. Hope this helps someone who has followed Gerald's detailed steps above, since that got me 90% there. Thank you. Also, keep this logic in mind: I was unable to build in VS until I was able to build succcessfully in Xamarin Studio Community.
290,780
I ended up in situation with a TCP port in listen mode with no process assigned to it. Is there a way to close this port without restarting server? Checking port status: ``` me> netstat -tan | grep 8888 tcp 0 0 :::8888 :::* LISTEN ``` Looking for process responsible: ``` me> lsof -i -P | grep 8888 ``` *Above command returns nothing*
2011/07/15
[ "https://serverfault.com/questions/290780", "https://serverfault.com", "https://serverfault.com/users/87790/" ]
Try `netstat -ltpn | grep 8888`
You are describing an impossible scenario. I believe what the previous posters are missing is the fact that you are trying to map a port to a process which you do not own. Therefore your `lsof` returns nothing since those tools do not have permission view the `/proc` entries that would facilitate that port -> PID mapping. Your `netstat` command is lacking a -p flag as well. Run those commands as `root` then things will be much clearer.
25,285,717
Refer to <https://stackoverflow.com/a/387733/418439>, ``` // Define a class like this function Person(name, gender){ // Add object properties like this this.name = name; this.gender = gender; } // Add methods like this. All Person objects will be able to invoke this Person.prototype.speak = function(){ alert("Howdy, my name is" + this.name); } // Instantiate new objects with 'new' var person = new Person("Bob", "M"); // Invoke methods like this person.speak(); // alerts "Howdy, my name is Bob" ``` How to define [namespace](https://stackoverflow.com/questions/881515/javascript-namespace-declaration) as well?
2014/08/13
[ "https://Stackoverflow.com/questions/25285717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/418439/" ]
Check this ref:- [here](https://stackoverflow.com/questions/881515/javascript-namespace-declaration) ``` var yourNamespace = { foo: function() { }, bar: function() { } }; ... yourNamespace.foo(); ```
I once made an example file (for my own use), so I'll share that here, maybe you will find it useful (warning: it contains more than just namespaces): ``` //http://www.crockford.com/javascript/private.html //http://www.dustindiaz.com/namespace-your-javascript/ //http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/ //adding the whole shabang to a namespace var NameSpace = (function (params) { //initialising constructor with parameter //call as "var testObject = new MyConstructor("test");" //then accessing the public members: "testObject.publicMember = 123;" function MyConstructor(param, param2) { //initialising public instance member variables //these could also be added by calling "testObject.[newMemberName] = [value];" to create a new property //can be accessed by private and public methods this.publicMember = param; this.secondPublicMember; //initialising private instance member variables //private variables can only be added at creation time //can be accessed by private methods, but not by the object's own public methods. var privateMember = param2; var secondPrivateMember; //creates a private function, NOT accessible by public functions (ONLY by internal private and privileged ones) //has access to all private/public functions and variables? function PrivateFunction(params) { //place code here //note this notation is short for "var PrivateFunction = function PrivateFunction(params) {};" } //creates a privileged function, accessible by all public (and private?) functions //has access to all private/public functions and variables this.PrivilegedFunction = function (params) { //place code here }; } //creating a public function, accessible by calling "testObject.PublicFunction(params)" //can also be done by calling "testObject.[newFunctionName] = function (params) {};" //has access to all public members and functions MyConstructor.prototype.PublicFunction = function (params) { //place function code here }; ``` }; Again, this was just a mockup I made for myself using the links mentioned at the top.
19,746,563
At first, I parsed an array `JSON` file with a loop using [jshon](http://kmkeen.com/jshon/), but it takes too long. To speed things up, I thought I could return every value of `id` from every index, repeat with `word` another type, put these into variables, and finally join them together before echo-ing. I've done something similar with files using `paste`, but I get an error complaining that the input is too long. If there is a more efficient way of doing this in `bash` without too many dependencies, let me know. I forgot to mention that I want to have the possibility of colorizing the different parts independently (red **id**). Also, I don't store the json; it's piped: ``` URL="http://somewebsitewithanapi.tld?foo=no&bar=yes" API=`curl -s "$URL"` id=`echo $API | jshon -a -e id -u` word=`echo $API | jshon -a -e word -u | sed 's/bar/foo/'` red='\e[0;31m' blue='\e[0;34`m' #bash colors echo "${red}$id${x}. ${blue}$word${x}" #SOMEHOW CONCATENATED SIDE-BY-SIDE, # PRESERVING THE ABILITY TO COLORIZE THEM INDEPENDENTLY. ``` My input (piped; not a file): ``` [ { "id": 1, "word": "wordA" }, { "id": 2, "word": "wordB" }, { "id": 3, "word": "wordC" } ] ``` Tried: ``` jshon -a -e id -u : ``` That yields: ``` 1 2 3 ``` And: ``` jshon -a -e text -u : ``` That yields: ``` wordA wordB wordC ``` Expected result after joining: ``` 1 wordA 2 wordB 3 wordC 4 wordD ```
2013/11/02
[ "https://Stackoverflow.com/questions/19746563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908703/" ]
you can use the [json](/questions/tagged/json "show questions tagged 'json'") parser `jq`: ``` jq '.[] | "\(.id) \(.word)"' jsonfile ``` It yields: ``` "1 wordA" "2 wordB" "3 wordC" ``` If you want to get rid of double quotes, pipe the output to [sed](/questions/tagged/sed "show questions tagged 'sed'"): ``` jq '.[] | "\(.id) \(.word)"' jsonfile | sed -e 's/^.\(.*\).$/\1/' ``` That yields: ``` 1 wordA 2 wordB 3 wordC ``` --- **UPDATE**: See [Martin Neal's](https://stackoverflow.com/users/255244/martin-neal) comment for a solution to remove quotes without an additional `sed` command.
The paste solution you're thinking of is this: ``` paste <(jshon -a -e id -u < foo.json) <(jshon -a -e word -u < foo.json) ``` Of course, you're processing the file twice. You could also use a language with a JSON library, for example ruby: ``` ruby -rjson -le ' JSON.parse(File.read(ARGV.shift)).each {|h| print h["id"], " ", h["word"]} ' foo.json ``` ``` 1 wordA 2 wordB 3 wordC ``` --- ``` API=$(curl -s "$URL") # store ids and words in arrays id=( $(jshon -a -e id -u <<< "$API") ) word=( $(jshon -a -e word -u <<< "$API" | sed 's/bar/foo/') ) red='\e[0;31m'; blue='\e[0;34m' x='\e[0m' for (( i=0; i<${#id[@]}; i++ )); do printf "%s%s%s %s%s%s\n" "$red" "${id[i]}" "$x" \ "$blue" "${word[i]}" "$x" done ```
45,664,251
I have seen a post similar to this but one answer used ajax and the other form/post. I can't figure why this won't work. Grateful for any explanation - Cheers. ``` <script > <select name="region" id="region" tags="region"> <?php echo $regionList; ?> </select> function getQuote(){ e = document.getElementById("region"); region = e.options[e.selectedIndex].value; linkTarget = "http://tatgeturlpage.com' + '?region=' + region "; return "window.location=" + linkTarget; } </script> <input type="button" onclick="getQuote()" value="Get Quote"> ```
2017/08/13
[ "https://Stackoverflow.com/questions/45664251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8458905/" ]
Try this: ``` class TextEdit : public QTextEdit{ public: TextEdit(QWidget *parent = 0): QTextEdit(parent) {} protected: void insertFromMimeData(const QMimeData *source){ if(source->hasText()){ setHtml(source->text()); } else{ QTextEdit::insertFromMimeData(source); } } }; ```
You cannot paste html code directly with indented spaces. Try to copy it on MS word first and then from there, paste it anywhere else.
875
I’ve heard this phrase used a lot by [Evildea](https://www.youtube.com/user/Evildela), and also in writing in various places (Reddit, Telegram, etc.). If I’m assuming correctly, this is a pretty straightforward word-for-word translation of the English “what the f?ck” (even though *fek* is not the same word). However, I’m not a native English speaker and leaning upon my knowledge of Esperanto (although still considering myself a *komencanto*), this seems grammatically awkward to me. As in, there is no verb, there is *la* that feels out of place… So, am I correct at thinking that this is wrong use of the language and an Anglicism, or am I missing something here? I’m tempted to ask for alternatives but that that is not a good use of the site and should be the subject of another question.
2016/09/19
[ "https://esperanto.stackexchange.com/questions/875", "https://esperanto.stackexchange.com", "https://esperanto.stackexchange.com/users/124/" ]
Kio la fek’! – Ĉu havas ian sencon diskuti pri "gramatika ĝusteco", kiam iu eligas ekkrion de konsterno, surprizo, malŝato, naŭzo aŭ feliĉo aŭ ŝerco aŭ simple volas ŝoki? Ŝajnas esti interesa vortigo por aldoni emocian forton al ia ajn frazo. Se oni volas trovi ion gramatikan, oni povas laŭ sia plaĉo aldoni vortojn ellasitajn kaj subkomprenendajn por fari kompletan, belan, laŭgramatikan frazon. Kompreneble, post tia filozofiumado, la trivortaĵo estos perdinta sian tutan esprimpovon kaj eblan ĉarmon.
I would say it is, and it started popularity as a joke, like many elements of living language usage. I wouldn't worry too much about it. There is a whole subgenre of this kind of jokes that some Esperantists on the internet decided to call "salamandri", in the range of reptile words of krokodili and aligatori, which means to say something with Esperanto words but which is only really understandable with context from another language. For example with my native Dutch we have jokes like Sinjoro Kadavro for bongusta (heerlijk = very tasteful, where split up heer = mister, lord and lijk = corpse) and Iru vian koridoron (ga je gang, do as you like, where gang is dutch for hallway).
172,886
The words "nitpicking" and "pedantic" actually define this phenomenon of pointing out others' minor mistakes. I have only this urge to do the nitpicking; I don't necessarily point out that petty mistake but I really have this urge to do the nitpicking and give a damn care to the exasperated sighs. So, is there a good word for this "urge to do the nitpicking"? Again, I am not asking for words that define this nitpicking phenomenon, just the urge to uphold it. Edit (choosing the answer): I kind of liked the phrase *obsessive-compulsive corrector* suggested by GMB below... its only shortcoming being its being sort of a medical jargon (as well as a phrase). Then I rediscovered the term *twitch*, which relates broadly to my urge. Ermanen came up with probably the best answer — *censorious*. At first, I didn't like the word, since it described me as a person who finds fault in almost everything. But I guess I can soften it — "I am just a little bit of censorious."
2014/05/25
[ "https://english.stackexchange.com/questions/172886", "https://english.stackexchange.com", "https://english.stackexchange.com/users/77085/" ]
*Perfectionist* may be a interesting word, but does not infer the meaning of "correcting *other's* mistakes", but that may be repaired with some context. Example: > > Larry is a perfectionist, he always organises the sheets of paper on my desk. > > >
Consider *exacting* and [exactingness](http://www.merriam-webster.com/thesaurus/exactingness). > > Use the adjective [exacting](http://www.vocabulary.com/dictionary/exacting) to describe something or someone very precise or strict in its requirements. If you teacher has exacting standards about spelling and punctuation, you'd better check your final paper. > > >
45,849,831
Well, I've been building a web application for a couple weeks now, and everything good. I got to the part that I had to test in Internet Explorer, and of all of the things that came up (all fixed except for one), Object.entries() is not supported. I've been doing some research and try to come up with a simple alternative, but no luck at all. To be more specific, I'm bringing an object from an API, to fill options for `<select></select>` fields I have to filter some information, just like this: ``` Object.entries(this.state.filterInfo.sectorId).map(this.eachOption) // Function eachOption = ([key, val], i) => { return( <option value={val} key={i}>{val}</option> ); } ``` So everything works correctly except for Internet Explorer. The thing is that in this particular component I'm rendering over 30 `<select></select>` fields. IF there is a solution that doesn't require me to rebuild everything, it would be amazing. Is there a simple solution? A way around this? Thanks in advance.
2017/08/23
[ "https://Stackoverflow.com/questions/45849831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5025361/" ]
The usual first item to research when you want to use a newer API in an older browser is whether there is a simple polyfill. And, sure enough there is a pretty simple polyfill for `Object.entries()` shown on the [MDN doc site](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Polyfill): ``` if (!Object.entries) Object.entries = function( obj ){ var ownProps = Object.keys( obj ), i = ownProps.length, resArray = new Array(i); // preallocate the Array while (i--) resArray[i] = [ownProps[i], obj[ownProps[i]]]; return resArray; }; ```
Use shim/polyfill like this one: <https://github.com/es-shims/Object.entries>
31,303,281
I want to add some C++ source files to my Android Studio project that are not in the project tree. I'm new to Gradle, and tried to research this as much as possible. From what I read, the following build.gradle file should work, but it doesn't. The bit about `jni.sourceDirs` came from this post: <http://www.shaneenishry.com/blog/2014/08/17/ndk-with-android-studio/> Is this the right approach? ``` apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.mycompany.myapp" minSdkVersion 22 targetSdkVersion 22 ndk { moduleName "mymodule" ldLibs "log" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } sourceSets.main { jni.srcDirs '../external/source/dir' } } ```
2015/07/08
[ "https://Stackoverflow.com/questions/31303281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484943/" ]
Have a look at my article about this: <http://www.sureshjoshi.com/mobile/android-ndk-in-android-studio-with-swig/> > > There are two things you need to know here. By default, if you have > external libs that you want loaded into the Android application, they > are looked for in the (module)/src/main/jniLibs. You can change this > by using setting sourceSets.main.jniLibs.srcDirs in your module’s > build.gradle. You’ll need a subdirectory with libraries for each > architecture you’re targeting (e.g. x86, arm, mips, arm64-v8a, etc…) > > > The code you want to be compiled by default by the NDK toolchain will > be located in (module)/src/main/jni and similarly to above, you can > change it by setting sourceSets.main.jni.srcDirs in your module’s > build.gradle > > > And a sample Gradle file from that page: ``` apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.sureshjoshi.android.ndkexample" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" ndk { moduleName "SeePlusPlus" // Name of C++ module (i.e. libSeePlusPlus) cFlags "-std=c++11 -fexceptions" // Add provisions to allow C++11 functionality stl "gnustl_shared" // Which STL library to use: gnustl or stlport } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } ``` Also, when specifying external to the /jni directory, try using the full build path (using one of the macros, eg): ``` '${project.buildDir}/../../thirdParty/blah/blah/' ```
Here, you get the idea: ``` android.ndk { moduleName = "mydemo" //Specify a library relative to this project path CFlags.add('-I' + String.valueOf(project.buildDir) + '/../my/inc/path') //or CPP cppFlags.add('-I' + String.valueOf(project.buildDir) + '/../my/inc/path') //Linker works the same way ldFlags.add("-L/custom/lib/path") ldLibs.addAll(["log", "GLESv2", "myCustomLibrary"]) } ```
550,379
A man is in a room, with $n$ passages leading out. For passage $i$, $i = 1,...,n$, there is probability $p\_i$ of escaping, $q\_i$ of being killed and $r\_i$ of returning to the room, where $p\_i + q\_i + r\_i = 1$. In which order should the man try the passages so as to maximise his chances of eventual escape? I am trying to formulate this as a dynamic programming problem, but am not sure how to associate costs with it. I am also not sure if I need to use discounting for the "death" scenario. Any help would be greatly appreciated.
2013/11/03
[ "https://math.stackexchange.com/questions/550379", "https://math.stackexchange.com", "https://math.stackexchange.com/users/103584/" ]
If you only have two passages, your chance of escape is $p\_a+r\_ap\_b$ or $p\_b+r\_bp\_a$. Use $r\_a=1-p\_a-q\_a$, this is $p\_a+p\_b-q\_ap\_b-p\_ap\_b$ or $p\_a+p\_b-p\_ap\_b-q\_bp\_a$. So choose passage $A$ if $q\_ap\_b<p\_aq\_b$, or $p\_a/q\_a>p\_b/q\_b$. This means that you should choose in decreasing order of $p\_i/q\_i$.
Make best use of your resources. Or, in other words minimize cost. You only fail to escape if you die, but you have greater chance of dying if you fail to escape: because you must risk your life again. Try that passage which has greatest positive difference between increase in probability of escape if going by another passage and increase in probability of death if going by another passage. Then try the passage with the next such greatest difference, and so on, assuming you can try every passage once. Or repeat the first passage if many tries are allowed. This would maximize chance of escape. So this is an iterative solution in general.
59,125,299
I have a string: ``` Your dog is running up the tree. ``` I want to be able to split it on every kth space but have overlap. For example on every other space: ``` Your dog is running up the tree. out = ['Your dog', 'dog is', 'is running', 'running up', 'up the', 'the tree'] ``` On every second space: ``` Your dog is running up the tree. out = ['Your dog is', 'dog is running', 'is running up', 'running up the', 'up the tree'] ``` I know I can do something like ``` >>> i=iter(s.split('-')) >>> map("-".join,zip(i,i)) ``` But this does not work for the overlapping I want. Any ideas?
2019/12/01
[ "https://Stackoverflow.com/questions/59125299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7572374/" ]
I suggest splitting at every whitespace first and then joining the desired amount of words back together while iterating over the list ```py s = 'Your dog is running up the tree.' lst = s.split() def k_with_overlap(lst, k): return [' '.join(lst[i:i+k]) for i in range(len(lst) - k + 1)] k_with_overlap(lst, 2) ['Your dog', 'dog is', 'is running', 'running up', 'up the', 'the tree.'] ```
I tried the following, the answer seem to be what you might be expecting. ``` def split(sentence, space_num): sent_array = sentence.split(' ') length = len(sent_array) output = [] for i in range(length+1-space_num): list_comp = sent_array[i:i+space_num] output.append(' '.join(list_comp)) return output print(split('the quick brown fox jumped over the lazy dog', 5)) ``` the output is as below (try changing the space\_num as per your requirement). ``` ['the quick brown fox jumped', 'quick brown fox jumped over', 'brown fox jumped over the', 'fox jumped over the lazy', 'jumped over the lazy dog'] ```
43,375,664
I have project that reads 100 text file with 5000 words in it. I insert the words into a list. I have a second list that contains english stop words. I compare the two lists and delete the stop words from first list. It takes 1 hour to run the application. I want to be parallelize it. How can I do that? Heres my code: ``` private void button1_Click(object sender, EventArgs e) { List<string> listt1 = new List<string>(); string line; for (int ii = 1; ii <= 49; ii++) { string d = ii.ToString(); using (StreamReader reader = new StreamReader(@"D" + d.ToString() + ".txt")) while ((line = reader.ReadLine()) != null) { string[] words = line.Split(' '); for (int i = 0; i < words.Length; i++) { listt1.Add(words[i].ToString()); } } listt1 = listt1.ConvertAll(d1 => d1.ToLower()); StreamReader reader2 = new StreamReader("stopword.txt"); List<string> listt2 = new List<string>(); string line2; while ((line2 = reader2.ReadLine()) != null) { string[] words2 = line2.Split('\n'); for (int i = 0; i < words2.Length; i++) { listt2.Add(words2[i]); } listt2 = listt2.ConvertAll(d1 => d1.ToLower()); } for (int i = 0; i < listt1.Count(); i++) { for (int j = 0; j < listt2.Count(); j++) { listt1.RemoveAll(d1 => d1.Equals(listt2[j])); } } listt1=listt1.Distinct().ToList(); textBox1.Text = listt1.Count().ToString(); } } } } ```
2017/04/12
[ "https://Stackoverflow.com/questions/43375664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3903589/" ]
I fixed many things up with your code. I don't think you need multi-threading: ``` private void RemoveStopWords() { HashSet<string> stopWords = new HashSet<string>(); using (var stopWordReader = new StreamReader("stopword.txt")) { string line2; while ((line2 = stopWordReader.ReadLine()) != null) { string[] words2 = line2.Split('\n'); for (int i = 0; i < words2.Length; i++) { stopWords.Add(words2[i].ToLower()); } } } var fileWords = new HashSet<string>(); for (int fileNumber = 1; fileNumber <= 49; fileNumber++) { using (var reader = new StreamReader("D" + fileNumber.ToString() + ".txt")) { string line; while ((line = reader.ReadLine()) != null) { foreach(var word in line.Split(' ')) { fileWords.Add(word.ToLower()); } } } } fileWords.ExceptWith(stopWords); textBox1.Text = fileWords.Count().ToString(); } ``` You are reading through the list of stopwords many times as well as continually adding to the list and re-attempting to remove the same stopwords over and again due to the way your code is structured. Your needs are also better matched to a HashSet than to a List, as it has set based operations and uniqueness already handled. If you still wanted to make this parallel, you could do it by reading the stopword list once and passing it to an async method that will read the input file, remove the stopwords and return the resulting list, then you would need to merge the resulting lists after the asynchronous calls came back, but you had better test before deciding you need that, because that is quite a bit more work and complexity than this code already has.
One issue I see here that can help improve performance is `listt1.ConvertAll()` will run in O(n) on the list. You are already looping to add the items to the list, why not convert them to lower case there. Also why not store the words in a hash set, so you can do look up and insertion in O(1). You could store the list of stop words in a hash set and when you are reading your text input see if the word is a stop word and if its not add it to the hash set to output the user.
9,842,137
I've a page like this: ``` <html> <head> <style type="text/css"> #mainDiv{ height: 100%; } #myDiv{ overflow: auto; width: 400px; } </style> </head> <body> <div id="mainDiv"> <div id="myDiv">content</div> </div> </body> </html> ``` I wish `mainDiv` was entirely contained in the screen (without scrollbars). This div contains `myDiv` and `myDiv` height depends on the screen height in such a way that its bottom border has a 30px margin from the screen bottom (or `mainDiv` bottom). What can I do?
2012/03/23
[ "https://Stackoverflow.com/questions/9842137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/688916/" ]
The "smaller half" of `int x` is `x/2`. The "bigger half" is `x/2 + x%2` or `x - x/2`. Note that "smaller" and "bigger" refer to the absolute value, so in the case of negative `x`, `bigger < smaller`. Of course, if `x` is always odd and positive, then `x%2` will be `1` and the bigger half can also be computed as `x/2 + 1`.
This would be my recommended way: ``` int low = floor(x / 2.0f); int high = ceil(x / 2.0f); ``` I find it to be more concise than the `x/2 + x%2` version. This version also benefits from the fact that the output will be correct if you happen to run it using an even number. EDIT: People seemed to complain about me using floating point for integers, well here is a completely bitwise based version: ``` int a = 9; int b = a >> 1; int c = b | (a & 0x1); ``` The only caveat with #2 is that if the input is negative, the results will not be what is expected.
31,646
the code block I copy outside emacs, which is not auto-indent when yanking in org type `org-return-indent` -> yank code block -> indent manually: ``` *** headline | v *** headline { code block } v *** headline { code block } ``` expecting the yank and indent in a one step
2017/03/23
[ "https://emacs.stackexchange.com/questions/31646", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/14750/" ]
Here is a elisp function that should do what you want ``` (defun yank-with-indent () (interactive) (let ((indent (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (message indent) (yank) (narrow-to-region (mark t) (point)) (pop-to-mark-command) (replace-string "\n" (concat "\n" indent)) (widen))) ```
Here is a different approach, maybe someone will find this useful. This is a minor mode that patches `get-text-property` to fake the property `'yank-handler`, which indicates which function to use for inserting. Then I use `insert-rectangle` for that. That way, this also works with `helm-ring`. ``` (defvar my/is-rectangle-yanking nil) (defun my/insert-rectangle-split (string) (let ((rows (split-string string "\n")) (my/is-rectangle-yanking t)) (save-excursion (insert (make-string (length rows) ?\n))) (insert-rectangle rows) (delete-char 1))) (defun my/get-text-property-rectangle-yank (fun pos prop &optional object) (let ((propv (funcall fun pos prop object))) (if propv propv (when (and (eq prop 'yank-handler) (stringp object) (not my/is-rectangle-yanking)) '(my/insert-rectangle-split))))) (define-global-minor-mode my/yank-as-rectangle "Minor mode to yank as rectangle. This patches `get-text-property' to put `insert-rectangle' as the insert function (`yank-handler')." :init-value nil :lighter " Rec" (if (not my/yank-as-rectangle) (advice-remove 'get-text-property #'my/get-text-property-rectangle-yank) (advice-add 'get-text-property :around #'my/get-text-property-rectangle-yank))) ```
123,195
You are in a toilet and someone knocks on the door. What do you say to him so that he won't enter? Is there a formal and an informal phrase?
2017/03/21
[ "https://ell.stackexchange.com/questions/123195", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/51453/" ]
You can say almost anything you like, but obvious choices are things like "Occupied!" (to describe the state of the bathroom stall, which is occupied by you) or "Don't come in!" (the basic imperative). Or you can simply make some obvious noise to signal your presence, like grunting.
I personally would say, "I won't be long." In the event that I had severe bowel problems I might say, "I'm sorry, I could be some time." The advantage of this is that it gives the person knocking an indication of how long they will have to wait - they may need the facility urgently!
62,732,038
I am reading Web Scraping with Python 2nd Ed, and wanted to use Scrapy module to crawl information from webpage. I got following information from documentation: <https://docs.scrapy.org/en/latest/topics/request-response.html> > > callback (callable) – the function that will be called with the > response of this request (once it’s downloaded) as its first > parameter. For more information see Passing additional data to > callback functions below. If a Request doesn’t specify a callback, the > spider’s parse() method will be used. Note that if exceptions are > raised during processing, errback is called instead. > > > My understanding is that: 1. pass in url and get resp like we did in *requests* module resp = requests.get(url) 2. pass in resp for data parsing parse(resp) The problem is: 1. I didn't see where resp is passed in 2. Why need to put self keyword before parse in the argument 3. self keyword was never used in parse function, why bothering put it as first parameter? 4. can we extract url from response parameter like this: url = response.url or should be url = self.url ``` class ArticleSpider(scrapy.Spider): name='article' def start_requests(self): urls = [ 'http://en.wikipedia.org/wiki/Python_' '%28programming_language%29', 'https://en.wikipedia.org/wiki/Functional_programming', 'https://en.wikipedia.org/wiki/Monty_Python'] return [scrapy.Request(url=url, callback=self.parse) for url in urls] def parse(self, response): url = response.url title = response.css('h1::text').extract_first() print('URL is: {}'.format(url)) print('Title is: {}'.format(title)) ```
2020/07/04
[ "https://Stackoverflow.com/questions/62732038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3849539/" ]
Your solution is using localstorage: ``` var sec = 0; tmpSec = localStorage.getItem('secs') if (tmpSec != null) { sec = parseInt(tmpSec,10); } function pad ( val ) { return val > 9 ? val : "0" + val; } setInterval( function(){ ++sec localStorage.setItem('secs', sec) document.getElementById("seconds").innerHTML=pad(sec%60); document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10)); document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10)); }, 1000); ``` Here is an example of interval which saved in localStorage <https://github.com/syronz/micro-games/blob/master/02%20idle%20game/progress.html>
``` var sec = 0; ``` that is going to reset your timer each time it is run. But instead code it this way: ``` sessionStorage.sec = "0"; // only execute this when you want to reset your counter. setInterval( function(){ var sec = parseInt(sessionStorage.sec); sec++; sessionStorage.sec = sec.toString(); document.getElementById("seconds").innerHTML=pad(sec%60); document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10)); document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10)); }, 1000); ```
58,940
I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure? ``` CREATE PROCEDURE getOrder (@orderId as numeric) AS BEGIN select order_address, order_number from order_table where order_id = @orderId select item, number_of_items, cost from order_line where order_id = @orderId END ``` I need to be able to iterate through both result sets individually. EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option. The result sets returned by the procedures are not the same data types or number of columns.
2008/09/12
[ "https://Stackoverflow.com/questions/58940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1836/" ]
The short answer is: you can't do it. From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested. To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax: ``` INSERT INTO #Table (...columns...) EXEC MySproc ...parameters... ``` You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
Note that there's an extra, undocumented limitation to the INSERT INTO ... EXEC statement: it cannot be nested. That is, the stored proc that the EXEC calls (or any that it calls in turn) cannot itself do an INSERT INTO ... EXEC. It appears that there's a single scratchpad per process that accumulates the result, and if they're nested you'll get an error when the caller opens this up, and then the callee tries to open it again. Matthieu, you'd need to maintain separate temp tables for each "type" of result. Also, if you're executing the same one multiple times, you might need to add an extra column to that result to indicate which call it resulted from.
4,174,780
Im trying to start to use Unity but i got stock in a point. I have a Context class and a Repository class being resolved by the container. My Repository class take a Context ctor parameter as a Dependency. My Config file: container: ``` <register type="IGeneralContext" mapTo="Data.EF.EFContext, Data.EF"> <lifetime type="singleton" /> <constructor> <param name="connectionString"> <value value="anyConnStr"/> </param> </constructor> </register> <register type="IClienteRepository" mapTo="Repository.EF.ClientRepository, Repository.EF"> <constructor> <param name="context"> <dependency type="Data.EF.EFContext, Data.EF"/> </param> </constructor> </register> ``` And now, I want that a new instance of IGeneralContext get constructed when Resolve is called AND the old one was already released. See: ``` using (IGeneralContext context = container.Resolve<IGeneralContext>()) //NEW CONTEXT INSTANCE { IClienteRepository rep = container.Resolve<IClienteRepository>(); // USE DEPENDENCY AS SINGLETON Cliente nc = new Cliente() { }; rep.Add(nc); context.CommitChanges(); } // DISPOSE CONTEXT using (IGeneralContext context = container.Resolve<IGeneralContext>()) //BRAND NEW CONTEXT INSTANCE { IClienteRepository rep = container.Resolve<IClienteRepository>(); // USE DEPENDENCY AS SINGLETON Cliente nc = new Cliente() { }; rep.Add(nc); context.CommitChanges(); } // DISPOSE CONTEXT IClienteRepository rep1 = container.Resolve<IClienteRepository>(); // NEW CONTEXT AGAIN Cliente cliente1= rep1.GetById(1); ``` Any idea how to solve it using Unity? Tks.
2010/11/13
[ "https://Stackoverflow.com/questions/4174780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506967/" ]
After analysing better James suggestion, I found a good alternative. There is a new way to delegate the instantiations to a factory: ``` container.RegisterType<IMyInterface, MyConcrete>(new InjectionFactory(c => MyFactoryClass.GetInstance())); ``` And also it is possible to extend the configuration file to do it for you. See ctavares post at CodePlex, he/she has a very nice example. <http://unity.codeplex.com/Thread/View.aspx?ThreadId=219565>
You might want to take a step back and look at your design. I found out that most of the time I thought I needed some complex DI configuration, the problem was actually in my design. Here are a few options you could consider: 1) Use a factory for creating repositories and supply the context to that factory: ``` var repositoryFactory = container.Resolve<IRepositoryFactory>(); using (var context = container.Resolve<IGeneralContext>()) { var rep = repositoryFactory.Create<IClienteRepository>(context); // ... } public class RepositoryFactory : IRepositoryFactory { public TRepository Create<TRepository>(IGeneralContext context) where TRepository : IRepository { var repository = Container.Resolve<TRepository>(); repository.Context = context; return repository; } } ``` 2) Try making the repositories part of the context: ``` using (var context = container.Resolve<IGeneralContext>()) { var nc = new Cliente() { }; context.Clientes.Add(nc); // ... } ``` If it is not possible to put all those repository properties on the context itself, you might want to create a wrapper object: ``` using (var context = container.Resolve<NorthwindContext>()) { var nc = new Cliente() { }; context.ClienteRepository.Add(nc); // ... } public class NorthwindContext { private IGeneralContext context; private IRepositoryFactory repFactory; public NorthwindContext(IGeneralContext context, IRepositoryFactory repFactory) { this.context = context; this.repFactory = repFactory; } public IClienteRepository Clientes { get { return this.repFactory .Create<IClienteRepository>(this.context); } } public IOrderRepository Orders { get { return this.repFactory .Create<IOrderRepository>(this.context); } } public void CommitChanges() { this.context.CommitChanges(); } } ``` You also might want to try minimizing the amount of calls to the container. Try to inject as much as you can through the constructor. [Here is an interesting SO question](https://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc) about the Unit of Work pattern (= context) and repositories that might be helpful. I hope this helps.
946
Near the end of The Artist, George Valentin is looking at his own reflection superimposed on a tuxedo in a shop window (the scene used in the trailer) when a cop comes strolling around the corner. George notices him and his smile fades. The cop approaches George with a seemingly friendly manner and speaks to him but there's no title card so we (at least those of us who don't lip-read!) can't tell what he is saying. The camera dwells on him for some time, cutting to a very tight close-up on his mouth as he talks, and then we see George backing away, looking confused or possibly disturbed. What's going on in this scene? What is it telling us?
2012/01/18
[ "https://movies.stackexchange.com/questions/946", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/314/" ]
Artist in the first layer, gives a very strong story about a period of time in film history that some main actors of silent era fall from their popularity, the other good example of this kind of caters is Sunset Blvd. In this scene Valentin sees himself in the reflection of the mens furnishing shop, first to remember about the elements of attraction in science, second to remind us about most important reason to be an actor on that time, the body. If we remember the first dancing scene behind the curtain by Valentin and Peppy Miller remember that the director shows us only the foot of Miller because the important element is the body. By interring the police as a representation of the society norm, Valentine came back from his imagination, the reflection, to the real world, and importance of speaking in life more than body. As we see the police officer is very still and we see from his long shot to his mouth closing up, this new norm embarrassing him. The director emphasized on this change by the previous scene when Valentin sees all of his staff in the store and not any more in the guest room or other places.
I would offer this: What nationality were cops portrayed as back then? The answer: IRISH. I would bet that both the cop and all the other "mouths talking" had accents, thus amplifying George's own predicament.
33,192,732
I am able to make queries to my `images` table and correctly pull my records, but I'm looking to modify my query to include the `body` field from my foreign table that is connected to my primary table via the `description_id`. I have created the relationship within my database, but wasn't sure if changes were needed to my sequelize model code or if a simple change to my query will achieve what I'm looking for. Here is my query: ``` router.get('/:pattern/:color/result', function(req, res, image){ console.log(req.params.color); console.log(req.params.pattern); Images.findAll({ where: { pattern: req.params.pattern, color: req.params.color }, attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource', 'description_id'] }).then(function(image){ console.log(image.description_id); //console.log(doc.descriptions_id); res.render('pages/result.hbs', { pattern : req.params.pattern, color : req.params.color, image : image }) }); }); ``` Here is my `images` model: ``` var Sequelize = require('sequelize'); var sequelize = new Sequelize('db', 'admin', 'pwd', { host: 'localhost', port: 3306, dialect: 'mysql' }); var Images = sequelize.define('images', { pattern: { type: Sequelize.STRING, field: 'pattern' }, color: { type: Sequelize.STRING, field: 'color' }, imageUrl: { type: Sequelize.STRING, field: 'imageUrl' }, imageSource: { type: Sequelize.STRING, field: 'imageSource' }, description_id: { type: Sequelize.INTEGER, field: 'description_id' } }); module.exports = Images; ``` `description` model: ``` var Sequelize = require('sequelize'); var sequelize = new Sequelize('db', 'admin', 'pwd', { host: 'localhost', port: 3306, dialect: 'mysql' }); var Description = sequelize.define('description', { color: { type: Sequelize.STRING, field: 'color' }, body: { type: Sequelize.STRING, field: 'body' } }); module.exports = Description; ```
2015/10/17
[ "https://Stackoverflow.com/questions/33192732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1061892/" ]
``` public static void swapPairs(int[] arr){ int length = arr.length%2 == 0? arr.length : arr.length-1; for(int i=0; i<length; i=i+2) { int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } // print the array for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); } } ```
``` final int[] number = new int[] { 1, 2, 3, 4, 5, 6, 7 }; int temp; for (int i = 0; i < number.length; i = i + 2) { if (i > number.length - 2) { break; } temp = number[i]; number[i] = number[i + 1]; number[i + 1] = temp; } for (int j = 0; j < number.length; j++) { System.out.print(number[j]); } ```
44,770,882
I am trying to install create a new app in Ruby on Rails and I cannot get passed this error: ``` $ gem install pg ``` > > ERROR: While executing gem ... (Errno::EACCES) > Permission denied @ rb\_sysopen - /Users/stormyramsey/.rbenv/versions/2.3.2/lib/ruby/gems/2.3.0/gems/pg-0.21.0/.gemtest > > >
2017/06/27
[ "https://Stackoverflow.com/questions/44770882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7448253/" ]
Its a permissions issue. You could fix it with this: ``` sudo chown -R $(whoami) /Library/Ruby/Gems/* ``` or possibly in your case ``` sudo chown -R $(whoami) /Users/stormyramsey/.rbenv/versions/2.3.2/lib/ruby/gems/* ``` **What does this do:** This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.
please run: ``` sudo gem install pg ```
9,992,893
I have an Excel file which has a column formatted as date in the format `dd-mm-YYYY`. I need to convert that field to text. If I change the field type excel converts it to a strange value (like `40603`). I tried the text function but it gives me Error 508. Any help?
2012/04/03
[ "https://Stackoverflow.com/questions/9992893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407468/" ]
You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this `="Today is "&TEXT(A1,"dd-mm-yyyy")` You can change the "dd-mm-yyyy" part as required
If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P
109,000
I came across this phrase/these words while reading a novel. What does it mean? Like If I say : > > 1. I cried myself. > 2. I wanted to cry myself. > > > Does it mean crying over oneself? I mean crying over something wrong one has done? Here is the quote where I read it: > > A queer look came over John Arable's face. He seemed almost ready to cry himself. > > > *Chapter 1, Charlotte's Web*
2016/11/10
[ "https://ell.stackexchange.com/questions/109000", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/43257/" ]
> > I cried myself > > > is equivalent to > > I cried myself **(as well).** > > > Where "myself" indicates that some other person (--self) probably cried initially. Another possible usage is to mean that person X responded by doing Y, but the speaker cried. That would typically be written better as > > **(Joanne was stunned.)** Myself, I cried. > > > There is an additional usage which is different; > > I cried myself **(silly | hoarse | to sleep)** > > > which is a way of saying the speaker cried till they were hoarse, etc.
In the context you are using it, it basically means "as well", so in your examples: > > 1. I cried **as well**. > 2. I wanted to cry **as well**. > > > in other words someone else is already crying. The other context as already mentioned is something additional like: > > I cried myself **to sleep**. > > > which basically "I cried until I went to sleep" or "I used crying to get to sleep", as you would use for "I rocked the baby to sleep".
58,470,268
I'm finishing an app that needs user data entry fields. I modeled it with a small number of data elements to streamline the development. Today I attempted to add additional elements and was astounded to find that I could only add 10 views to a view. So I tried the simplest of designs (below). If I added 11 "things" to the view it immediately presented the error on the top item, whatever it was: "Argument passed to call that takes no arguments" Doesn't matter whether I call the outside container a ScrollView, VStack, List or Form. Same behavior. Doesn't matter whether the Text/TextField sub units are in a VStack or not. So I went back to basics - just added ten Text views. No problem. Add an eleventh and it blows up. Here's one of the variants - but all I need to do was add 10 simple Text views to get it to break. I must be missing something really basic here. I checked for a newer release of Xcodebut I have Version 11.2 beta 2 (11B44), the latest. ``` @State private var textField1: String = "Pass to the ListCell" @State private var textField2: String = "2" //more of these var body: some View { NavigationView { VStack { //extract the VStack and create a separate struct ListCell(tfString: textField1) VStack { Text("Text Field") TextField("Placeholder", text: $textField2) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } VStack { Text("Text Field") TextField("Placeholder", text: $textField3) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } //more of the above VStacks Text("6") Text("7") Text("8") Text("9") Text("10") //Spacer() //Text("11") } } } ``` Any guidance would be appreciated.
2019/10/20
[ "https://Stackoverflow.com/questions/58470268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2698617/" ]
Use `Group {...}` <https://developer.apple.com/documentation/swiftui/group> ``` var body: some View { NavigationView { VStack { //extract the VStack and create a separate struct ListCell(tfString: textField1) Group { VStack { Text("Text Field") TextField("Placeholder", text: $textField2) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } VStack { Text("Text Field") TextField("Placeholder", text: $textField3) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } } //more of the above VStacks Group { Text("6") Text("7") Text("8") Text("9") Text("10") } //Spacer() //Text("11") } } } ```
`ViewBuilder`s in SwiftUI take between 0 and 10 elements into their initializer anything more than that and you have to start grouping them using `Group`, `VStack`, `HStack`, `List`, `ForEach` and so on. The best approach is to start extracting a few elements that belong together into separate Views, for example: ``` struct FormCell: View { @Binding var inputString: String var body: some View { VStack { Text("Text Field") TextField("Placeholder", text: $inputString) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() } } } ``` Next if you have a few of them, you can group them using `ForEach` and `List` or `VStack`.
6,632,971
What is the difference between `std::array` and `std::vector`? When do you use one over other? I have always used and considered `std:vector` as an C++ way of using C arrays, so what is the difference?
2011/07/09
[ "https://Stackoverflow.com/questions/6632971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452307/" ]
`std::array` is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data. `std::vector` is a small class containing pointers into the heap. (So when you allocate a `std::vector`, it always calls `new`.) They are slightly slower to access because those pointers have to be chased to get to the arrayed data... But in exchange for that, they can be resized and they only take a trivial amount of stack space no matter how large they are. [edit] As for when to use one over the other, honestly `std::vector` is almost always what you want. Creating large objects on the stack is generally frowned upon, and the extra level of indirection is usually irrelevant. (For example, if you iterate through all of the elements, the extra memory access only happens once at the start of the loop.) The vector's elements are guaranteed to be contiguous, so you can pass `&vec[0]` to any function expecting a pointer to an array; e.g., C library routines. (As an aside, `std::vector<char> buf(8192);` is a great way to allocate a local buffer for calls to `read/write` or similar without directly invoking `new`.) That said, the lack of that extra level of indirection, plus the compile-time constant size, can make `std::array` significantly faster for a very small array that gets created/destroyed/accessed a lot. So my advice would be: Use `std::vector` unless (a) your profiler tells you that you have a problem *and* (b) the array is tiny.
I use my own personal hand coded `Array<>` template class, which has a simpler API compared with `std::array` or `std::vector`. For example: To use a dynamic Array: ``` Array<> myDynamicArray; // Note array size is not given at compile time myDynamicArray.resize(N); // N is a run time value ... ``` To use a static Array, fixed size at compile time: ``` Array<100> myFixedArry; ``` I believe it has a better syntax than `std::array`, or `std::vector`. Also extremely efficient.
25,463,279
I'm using the below boilerplate PyQt4 code with the goal of capturing all the HTML generated by javascript on a page: ``` import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) self.mainFrame().load(QUrl(url)) self.app.exec_() def _loadFinished(self, result): self.frame = self.mainFrame() self.app.quit() def getHtml(str_url): r_html = Render(str_url) html = r_html.frame.toHtml() return html ``` I then created a test page to see if it works: ``` <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#test').text('This is a test!') }); </script> </head> <body> <div id="test"></div> </body> </html> ``` so running ``` getHtml('http://www.mytestpage.com') ``` I'd expect to see the HTML with the 'This is a test!' text rendered in the div. However the HTML is being returned with that piece absent. What am I doing wrong? Is the code not waiting for page to fully load? Or am I misunderstanding the use case?
2014/08/23
[ "https://Stackoverflow.com/questions/25463279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438637/" ]
I have the solution! I added: averagevalue=total/MarkListView.getChildCount(); which is the number of childs. ``` void addNumberFromText() { double total=0; double averagevalue=0; for(int i=0;i<MarkListView.getChildCount();i++) { View wantedView = MarkListView.getChildAt(i); markresult = (TextView)wantedView.findViewById(R.id.subjectmark); double value=Double.parseDouble(markresult.getText().toString()); total+=value; averagevalue=total/MarkListView.getChildCount(); } markresult1 = (TextView)findViewById(R.id.average); markresult1.setText(Double.toString(averagevalue)); markresult1.setText(String.format("%.2f", averagevalue)); ``` Thanks for the responses, all were similar and correct. Thank you!
From your code, it seems that you haven't calculated the average like you say. You calculated the total but forgot to calculate the average by dividing the total by your total list items. Hope it helps.
10,022,524
I'm going through a Ruby tutorial and I can't grasp the += statement. Google isn't helping, "Ruby +=" only searches for "Ruby". Help is appreciated. Sample: ``` num = -10 num += -1 if num < 0 puts num #=> -11 ```
2012/04/05
[ "https://Stackoverflow.com/questions/10022524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1123584/" ]
``` num += -1 ``` is an equivalent of ``` num = num + -1 ``` or, for this example ``` num = num - 1 ``` which, in turn, can be written as ``` num -= 1 ```
The segment `a += b` is just the short form for `a = a + b`. So your statement: ``` num += -1 if num < 0 ``` will simply subtract one (by adding `-1` which is ... quaint, that's probably as polite as I can be) from `num` if it is already negative (if `num < 0`)..
43,195,729
HashMap vs ConcurrentHashMap, when the value is AtomicInteger or LongAdder, is there any harm in using HashMap in a multithreaded environment ?
2017/04/03
[ "https://Stackoverflow.com/questions/43195729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7811214/" ]
Yes, there is. An object being of type `AtomicInteger` or `LongAdder` just means that the object itself is safe in a concurrent modification operation (i.e. if two threads try to modify it, they will do so one after the other). However, if the map containing the objects itself is of type 'HashMap', then concurrent modification operations of the map are not safe. For instance, if you want to add a key-value pair only if the key doesn't already exist in the map, you cannot safely use the `putIfAbset()` operation anymore because it's not synchronized/thread-safe in `HashMap`. And if you do use it, then it is possible that two threads will execute call this method at the same time, both of them reaching the conclusion that the map doesn't have they key, and then both of them adding a key-value pair, resulting in one of them overwriting the other other's value.
You cannot use a HashMap in a multithreaded environment. The reason is as follows: If multiple threads operate on a simple HashMap they can **damage the internal structure of the HashMap** which is an array of linked lists. The links can go missing or go in circles. The result will be that the HashMap will be totally unusable and corrupt. This is the reason you should always use a concurrentHashMap in a multithreaded environment regardless of what value you want to store in the map itself. Now, in a concurrentHashMap of a type say map< String val, 'any number'> 'any number' could be a LongAdder or an AtomicLong etc. Remember that not all operations on a concurrentHashMap are threadsafe by default. Therefore, if you use say a LongAdder then you could write the following atomic operation without any need to synchronize: ``` map.putIfAbsent(a string key, new LongAdder()); map.get("abc").increment(); ```
12,389,948
I'm using Bootstrap 2.1.1 and jQuery 1.8.1 and trying to use Typeahead's functionality. I try to display a **label** and use an **id** like a standard `<select />` Here is my typeahead initialization: ``` $(':input.autocomplete').typeahead({ source: function (query, process) { $('#autocompleteForm .query').val(query); return $.get( $('#autocompleteForm').attr('action') , $('#autocompleteForm').serialize() , function (data) { return process(data); } ); } }); ``` Here is the kind of JSON that I'm sending ``` [{"id":1,"label":"machin"},{"id":2,"label":"truc"}] ``` How can I tell `process()` to display my labels and store the selected ID in another hidden field?
2012/09/12
[ "https://Stackoverflow.com/questions/12389948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305189/" ]
The problem I have seen with some of these solutions, is that the `source` function is called repeatedly on every keyup event of the input box. Meaning, the arrays are being built and looped over on every keyup event. This is not necessary. Using a closure, you can process the data only once, and maintain a reference to it from within the `source` function. In addition, the following solution solves the global namespace problem of @Gerbus's solution, and also allows you to play with the array of data once the user has selected something (for example, removing that item from the list). ``` // Setup the auto-complete box of users var setupUserAcUi = function(data) { var objects = []; var map = {}; $.each(data, function(i, object) { map[object.name] = object; objects.push(object.name); }); // The declaration of the source and updater functions, and the fact they // are referencing variables outside their scope, creates a closure $("#splitter-findusers").typeahead({ source: function(query, process) { process(objects); }, updater: function(item) { var mapItem = map[item]; objects.splice( $.inArray(item, objects), 1 ); // Remove from list // Perform any other actions } }); }; // `data` can be an array that you define, // or you could pass `setupUserAcUi` as the callback to a jQuery.ajax() call // (which is actually how I am using it) which returns an array setupUserAcUi(data); ```
The selected answer doesn't deal with non unique labels (e.g. a person's name). I'm using the following which keeps the default highlighter formatting: ``` var callback = function(id) { console.log(id); }; $('.typeahead',this.el).typeahead({ source: function (query, process) { var sourceData = [ {id:"abc",label:"Option 1"}, {id:"hfv",label:"Option 2"}, {id:"jkf",label:"Option 3"}, {id:"ds",label:"Option 4"}, {id:"dsfd",label:"Option 5"}, ]; var concatSourceData = _.map(sourceData,function(item){ return item.id + "|" + item.label; }); process(concatSourceData); }, matcher : function(item) { return this.__proto__.matcher.call(this,item.split("|")[1]); }, highlighter: function(item) { return this.__proto__.highlighter.call(this,item.split("|")[1]); }, updater: function(item) { var itemArray = item.split("|"); callback(itemArray[0]); return this.__proto__.updater.call(this,itemArray[1]); } }); ```
48,327,221
I want to add my `items` values on the existing `f['ECPM_medio']` column I made some modifications on the `items values` to have `0.8 to 0.9`values of each numbers. the problem is when I try to add these new numbers to the existing column... I paste the same number on all rows! ``` import pandas as pd jf = pd.read_csv("Cliente_x_Pais_Sitio.csv", header=0, sep = ",") del jf['Fill_rate'] del jf['Importe_a_pagar_a_medio'] a = jf.sort_values(by=["Cliente","Auth_domain","Sitio",'Country']) f = a.groupby(["Cliente","Auth_domain","Sitio","Country"], as_index=False)['ECPM_medio'].min() del a['Fecha'] del a['Subastas'] del a['Impresiones_exchange'] f.to_csv('Recom_Sitios.csv', index=False) for item in f['ECPM_medio']: item = float(item) if item <= 0.5: item = item * 0.8 else: item = item * 0.9 item = float("{0:.2f}".format(item)) item for item in item: f['ECPM_medio'] = item f.to_csv('Recom_Sitios22.csv', index=False) ```
2018/01/18
[ "https://Stackoverflow.com/questions/48327221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8717507/" ]
You should create a function and then apply it with lambda. Example: ``` def myfunc(item): item = float(item) if item <= 0.5: item = item * 0.8 else: item = item * 0.9 item = float("{0:.2f}".format(item)) return item f['ECPM_medio'] = f['ECPM_medio'].apply(lambda x: myfunc(x)) ```
You can do this using Pandas vectorized operations, ``` df['ECPM_medio'] = np.where(df['ECPM_medio'] <= 0.5, df['ECPM_medio'] * 0.8, df['ECPM_medio']* 0.9) ```
78,903
Is it possible to iterate over a Map in an aura:iteration. It doesn't give me a compile or runtime error but it doesn't appear to work. My thought is that it works similarly to $.each in jquery. ``` <aura:attribute type="Map" name="myMap" default="{key1: 'item1', key2: 'item2'}" /> <aura:iteration items="{!myMap}" indexVar="key" var="item"> {!key} : {!item} </aura:iteration> ```
2015/06/05
[ "https://salesforce.stackexchange.com/questions/78903", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/21077/" ]
I came across this question and was a little discouraged, but looks like things might have changed since some of these answers were provided. I found [this page](https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/ref_attr_types_collection.htm) in the Lightning Components documentation. All the way at the bottom, and really easy to overlook is what appears to be instructions for iterating over an Apex Map returned from a server-side controller. I tried it out and it actually works! This controller function populates a picklist `<ui:inputSelect ... />` in a Lightning Component by iterating over an Apex Map. I guess this doesn't exactly answer the original question, but maybe the workaround is to do the iteration in a controller function and provide those results to the view. ``` ({ doInit : function(component, event, helper) { // Create the action var action = component.get("c.getApexMap"); // Add callback behavior for when response is received action.setCallback(this, function(response) { var state = response.getState(); console.log(state); if (component.isValid() && state === "SUCCESS") { //loop through map returned from Server, populating client picklist as we go var clientMap = response.getReturnValue(); //the apex map returned from server var opt = new Array(); //this will be our picklist options for(key in clientMap) { //this iterates over the returned map opt.push({ class: "optionClass", label: clientMap[key].labelField__c, value: clientMap[key].valueField__c }); } component.find("myPicklist").set("v.options", opt); } else { console.log("Failed with state: " + state); } }); // Send action off to be executed $A.enqueueAction(action); } }) ```
Not a straight Yes to the original question. The Maps can not go in directly, but we can use some thing like this. Maps or list, all the collections are same for lightning components as it considers all these variables as json. Try the following: Component: ``` <aura:component > <aura:attribute name="colercodes" type="list"/> <ui:button press="{!c.getColCodes}" label="Display Colors" /> <aura:iteration items="{!v.colercodes}" indexVar="key" var="col"> <p> <aura:set attribute="style" value="{!col.BGvalue}"/> {!key}: {!col.key} - {!col.value} </p> </aura:iteration> </aura:component> ``` ComponentController.js: ``` ({ getColCodes: function(component) { var cols = []; cols.push({ value: '#F0F8FF', BGvalue: 'background:#F0F8FF', key: 'AliceBlue' }); cols.push({ value: '#00FFFF', BGvalue: 'background:#00FFFF', key: 'Aqua' }); cols.push({ value: '#FAEBD7', BGvalue: 'background:#FAEBD7', key: 'AntiqueWhite' }); cols.push({ value: '#7FFFD4', BGvalue: 'background:#7FFFD4', key: 'Aquamarine' }); component.set("v.colercodes", cols); } }) ``` =================== I happened to use something like this in one of my projects: ``` ({ doInit : function(component, event, helper) { var action = component.get("c.returnArticles");//Fetching Map/queryresult from Controller action.setCallback(this, function(a) { component.set("v.ArticleMap", a.getReturnValue()); var Arts = component.get("v.ArticleMap"); console.log(Arts); var artsTemp = []; for (Art in Arts){ console.log(Art); var temp = Arts[Art] for (keyofMap in temp){ //pushing the articles into Map/ List of component attribute artsTemp.push({ key: keyofMap, value: temp[keyofMap] }); } } component.set("v.ArticleList", artsTemp); }); $A.enqueueAction(action); } }) ``` Note: I was returning database.query() from the apex controller there. We can not directly use the maps like we do in VF pages, we can pass that maps to json variable as they are and use them in components. HTH
65,982,187
When i run this code, it should render ``` Hello World! ``` But it render, ``` Loading... ``` Here is my code: ``` import React, { Component } from 'react'; class GroupsHomePage extends Component { constructor() { super() this.state={ groupInfo:[] } } componentDidMount(){ let store = JSON.parse(localStorage.getItem('login')) var url = 'http://127.0.0.1:8000/myapi/groupsdata/'+this.props.groupId+'/?format=json' fetch(url,{ method:'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token, }, }) .then(res=>res.json().then(result=>{ this.setState({groupInfo: result}) })) } render() { console.log(this.state.groupInfo) if(this.state.groupInfo.length){ return ( <div> <p>Hello World!</p> </div> ); }else{ return( <div className='container'> <p>Loading...</p> </div> ) } } } export default GroupsHomePage; ``` When i run the code, in console it shows: > > [ ] > > > > > {id: 6, name: "ffff", member: 0, admin: {id: 7, first\_name: "test6", last\_name: "test6"}} > > > why it shows **Loading...** instead of **Hello World!**?
2021/01/31
[ "https://Stackoverflow.com/questions/65982187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348041/" ]
So firstly your default groupInfo state should be an empty object in constructor like this groupInfo:{} And to check length your 'if' condition would be this ``` if(Object.keys(this.state.groupInfo).length > 0) ``` This condition is used for JSON object keys different from Array
Try this. `console.log(typeof(this.state.groupInfo))` I think groupInfo is of object type. So in console if you see the output of above line object then change the if condition to ``` if(this.state.groupInfo){ ``` --- Also you should not use ``` if(this.state.groupInfo.length){ ``` if you have groupInfo already defined as []. Because it will give you true and i think you only want to run this if condition when you have some data in groupInfo array. ``` if(this.state.groupInfo.length !== 0){ ``` Is good way
44,736,967
I found below function which copy data from csv to Postgres, it also creates table dynamically from csv, I want similar function but it should do for text files. I am not from development background and I have to load a txt file to Postgres table dynamically. is it possible to make below function to work with txt files? ``` create or replace function public.load_csv_file ( target_table text, csv_path text, col_count integer ) returns void as $$ declare iter integer; -- dummy integer to iterate columns with col text; -- variable to keep the column name at each iteration col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet begin set schema 'public'; create table insert_from_csv (); -- add just enough number of columns for iter in 1..col_count loop execute format('alter table insert_from_csv add column col_%s text;', iter); end loop; -- copy the data from csv file execute format('copy insert_from_csv from %L with delimiter '','' quote ''"'' csv ', csv_path); iter := 1; col_first := (select col_1 from insert_from_csv limit 1); -- update the column names based on the first row which has the column names for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first) loop execute format('alter table insert_from_csv rename column col_%s to %s', iter, col); iter := iter + 1; end loop; -- delete the columns row execute format('delete from insert_from_csv where %s = %L', col_first, col_first); -- change the temp table name to the name given as parameter, if not blank if length(target_table) > 0 then execute format('alter table insert_from_csv rename to %I', target_table); end if; end; $$ language plpgsql; ``` Any help from experts would help me a lot.
2017/06/24
[ "https://Stackoverflow.com/questions/44736967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3845299/" ]
You can round the seconds to the nearest multiple of 30, and then add the difference between the rounded and the original value to the date: ``` extension Date { func nearestThirtySeconds() -> Date { let cal = Calendar.current let seconds = cal.component(.second, from: self) // Compute nearest multiple of 30: let roundedSeconds = lrint(Double(seconds) / 30) * 30 return cal.date(byAdding: .second, value: roundedSeconds - seconds, to: self)! } } ``` That should be good enough to *display* the rounded time, however it is not exact: A `Date` includes also fractional seconds, so for example "11:30:10.123" would become "11:30:00.123" and not "11:30:00.000". Here is another approach which solves that problem: ``` extension Date { func nearestThirtySeconds() -> Date { let cal = Calendar.current let startOfMinute = cal.dateInterval(of: .minute, for: self)!.start var seconds = self.timeIntervalSince(startOfMinute) seconds = (seconds / 30).rounded() * 30 return startOfMinute.addingTimeInterval(seconds) } } ``` Now `seconds` is the time interval since the start of the current minute (including fractional seconds). That interval is rounded to the nearest multiple of 30 and added to the start of the minute.
I used the answer by Martin R to write a more generic version to round by any time period. **Answer is outdated and only works with time, check gist for the latest version.** <https://gist.github.com/casperzandbergenyaacomm/83c6a585073fd7da2e1fbb97c9bcd38a> ``` extension Date { func rounded(on amount: Int, _ component: Calendar.Component) -> Date { let cal = Calendar.current let value = cal.component(component, from: self) // Compute nearest multiple of amount: let roundedValue = lrint(Double(value) / Double(amount)) * amount let newDate = cal.date(byAdding: component, value: roundedValue - value, to: self)! return newDate.floorAllComponents(before: component) } func floorAllComponents(before component: Calendar.Component) -> Date { // All components to round ordered by length let components = [Calendar.Component.year, .month, .day, .hour, .minute, .second, .nanosecond] guard let index = components.index(of: component) else { fatalError("Wrong component") } let cal = Calendar.current var date = self components.suffix(from: index + 1).forEach { roundComponent in let value = cal.component(roundComponent, from: date) * -1 date = cal.date(byAdding: roundComponent, value: value, to: date)! } return date } } ``` To round to x minutes you need to also floor the seconds so this also contains the floor method I wrote. How to use: ``` let date: Date = Date() // 10:16:34 let roundedDate0 = date.rounded(on: 30, .second) // 10:16:30 let roundedDate1 = date.rounded(on: 15, .minute) // 10:15:00 let roundedDate2 = date.rounded(on: 1, .hour) // 10:00:00 ```
1,941,589
I came accross this problem and was confuse why P(E|Fi) = 1/6 when i = 2,3,4,5,6 Shouldn't P(E|Fi) = 1/5 since i = 1 cannot complete a sum of 8 with any given Fi?, Find the probability of rolls an 8 with a fair pair of dice using law of total probability. ``` Fi = {1st fie equals i} , i = 1 , ... , 6 ``` and `P(E|Fi) = 1/6, i = 2,3,4,5,6 while P(E|F1) = 0` ``` Thus P(E) = (5/36); P(EFi) = 1/36, i = 2, ... , 6 = 0, i = 1 ```
2016/09/26
[ "https://math.stackexchange.com/questions/1941589", "https://math.stackexchange.com", "https://math.stackexchange.com/users/70716/" ]
The meaning of $P(E | F\_i)$ is the probability that $E$ occurs given that $F\_i$ occurs. Now I can see your reasoning as follows: You are saying that $ 1 = P(E | F\_1) + P(E | F\_2) + \ldots + P(E | F\_6)$. You probably think this is because *one of the* $F\_i$ *has to happen*, and therefore if $E$ has happened, then one of the $F\_i$ has surely happened before it. But $F\_1$ cannot happen, so the probability of all the others is $\frac{1}{5}$. However, this is not correct. The reason for that is the following inequality: $$P (A | (B \cup C)) = \frac{P(A \cap (B \cup C))}{P(B \cup C)}\neq \frac{P(A \cap B)}{P(B)} + \frac{P(A \cap C)}{P(C)} = P(A | B) + P(A | C)$$. You can see why just from definition of $|$ notation. Now, $F\_1 \text{ or } F\_2 \ ... \text{ or } F\_6$ occurs with probability $1$, however, it is not true that $P( E | (F\_1 \text{ or } F\_2 ... \text{ or } F\_6)) = P(E | F\_1) + P(E | F\_2) + \ldots + P(E| F\_6)$. Hence your thinking is wrong. Therefore, the answer $\frac{5}{36}$ comes purely from working by definition. I know this is confusing. If you want a clearer explanation, please demand it.
Suppose you have already rolled the first die. If it is a $1$, then there is no chance of rolling the second die to get a sum of $8$. Otherwise, there is a $1/6$ chance that when you roll the second die, your sum will be $8$. That is why it is $1/6$ instead of $1/5$.
53,243,766
This is a function I defined in order to find the smallest value in a list using recursion.However,I called the function twice within itself, which I think it's a bit weird. Is there a way around the function `append()`?. We haven't studied it yet so I'm asking whether there could be a simpler way to get the same solution by not using `append()`? ``` def minimum(lst): """ parameters : lst of type list return : the value of the smallest element in the lst """ if len(lst) == 1: return lst[0] if lst[0] < lst[1]: lst.append(lst[0]) return(minimum(lst[1:])) return(minimum(lst[1:])) ```
2018/11/10
[ "https://Stackoverflow.com/questions/53243766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I guess you could do this to avoid append: ``` def minimum(lst): if len(lst)==1: return lst[0] if lst[0] < lst[1]: return minimum(lst[0:1]+ lst[2:]) else: return minimum(lst[1:]) ``` but i think this one is better with only one call to minimum: ``` def minimum(lst): if len(lst) == 1: return lst[0] s = minimum(lst[1:]) return s if s < lst[0] else lst[0] ```
Use an additional variable? ``` def minimum(lst, current_min=None): if not lst: return current_min if current_min is None: current_min = lst[0] elif lst[0] < current_min: current_min = lst[0] return minimum(lst[1:], current_min) ```
5,157,176
I want to debug a Windows service but it pops an error message saying > > Cannot start service from the command > line or a debugger. A windows service > must be installed using > installutil.exe and then started with > the Server explorer, windows services > Administrative tools or the NET start > command. > > > I don't really have any idea about this error..... [![enter image description here](https://i.stack.imgur.com/p445y.png)](https://i.stack.imgur.com/p445y.png)
2011/03/01
[ "https://Stackoverflow.com/questions/5157176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536426/" ]
To prevent this error occurring and allow the service to run outside of the usual service controller you can check the `Environment.UserInteractive` flag. If it is set you can run the service with output to the console instead of letting it run to the ServiceBase code that returns that error. Add this to the start of Program.Main(), before the code that uses ServiceBase to run the service: ``` if (Environment.UserInteractive) { var service = new WindowsService(); service.TestInConsole(args); return; } ``` As the OnStart and OnStop methods are `protected` in your service you need to add another method to that class which you can run from Main() and calls those methods for you, such as: ``` public void TestInConsole(string[] args) { Console.WriteLine($"Service starting..."); this.OnStart(args); Console.WriteLine($"Service started. Press any key to stop."); Console.ReadKey(); Console.WriteLine($"Service stopping..."); this.OnStop(); Console.WriteLine($"Service stopped. Closing in 5 seconds."); System.Threading.Thread.Sleep(5000); } ``` Finally, make sure the output is a console application in the project's properties. You can now run the service executable like any other and it will start as a console. If you start it from Visual Studio the debugger will attach automatically. If you register it and start it as a service it will run properly as a service without any changes. The only difference I've found is that when running as a console application the code does not write to the event log, you might want to output anything you would normally log there to the console as well. This service debugging technique is one of those explained on [learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/framework/windows-services/how-to-debug-windows-service-applications)
There is a nuget package made to solve this problem: `install-package WindowsService.Gui` [![Image of the runner GUI](https://i.stack.imgur.com/KLjYU.png)](https://i.stack.imgur.com/KLjYU.png) **What does the package do?** It helps by creating a Play/Stop/Pause UI when running with a debugger attached, but also allows the windows service to be installed and run by the Windows Services environment as well. All this with one line of code! What is Service Helper Being someone who writes Windows Services a lot, it can be frustrating to deal with the headaches involved in debugging services. Often it involves tricks, hacks, and partial workarounds to test all of your code. There is no "just hit F5" experience for Windows Services developers. Service Helper solves this by triggering a UI to be shown if a debugger is attached that simulates (as closely as possible) the Windows Services Environment. The github project is here: <https://github.com/wolfen351/windows-service-gui> **How to use?** The easiest way to get Windows Service Helper in your project is to use the NuGet package ServiceProcess.Helpers on the NuGet official feed. Simply make a few changes to the typical code in the "Program.cs" for your application: ``` using System.ServiceProcess; using ServiceProcess.Helpers; //HERE namespace DemoService { static class Program { static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; //ServiceBase.Run(ServicesToRun); ServicesToRun.LoadServices(); //AND HERE } } } ``` Disclosure: I'm the maintainer of this project Note: The UI is optional
652,375
I would like to convert the ZFS output of "10.9T" to actual bytes, using something in a line or two, rather than run generic math functions, and if conditions for `T`, `G`, `M`, etc.. Is there an efficient way to do this? For now, I have something like this: ``` MINFREE="50G" POOLSIZE=`zpool list $POOLNAME -o size` #Size 10.9T POOLSIZE=$(echo "$POOLSIZE" | grep -e [[:digit:))] #10.9T POOLFREE=500M #as an example let p=POOLSIZE x=POOLFREE y=MINFREE z=POOLSIZE; CALC=$(expr "echo $((x / y))") if [ "${CALC}" < 1 ]; then # we are less than our min free space echo alert fi ``` This produces an error: can't run the expression on `10.9T`, or `50G` because they arent numbers. Is there a known `bash` function for this? I also like the convenience of specifying it like i did there in the `MINFREE` var at the top. So an easy way to convert would be nice. [This](https://pinkbubblegumtongue.wordpress.com/2015/08/18/checking-quotas-free-space-in-zfs/) is what I was hoping to avoid (making case for each letter), the script looks clean though. **Edit**: Thanks for all the comments! Here is the code I have now. , relevant parts atleast; ``` POOLNAME=san INFORMAT=auto #tip; specify in Gi, Ti, etc.. (optional) MINFREE=500Gi OUTFORMAT=iec NOW=`date`; LOGPATH=/var/log/zfs/zcheck.log BOLD=$(tput bold) BRED=${txtbld}$(tput setaf 1) BGREEN=${txtbld}$(tput setaf 2) BYELLOW=${txtbld}$(tput setaf 3) TXTRESET=$(tput sgr0); # ZFS Freespace check #poolsize, how large is it POOLSIZE=$(zpool list $POOLNAME -o size -p) POOLSIZE=$(echo "$POOLSIZE" | grep -e [[:digit:]]) POOLSIZE=$(numfmt --from=iec $POOLSIZE) #echo poolsize $POOLSIZE #poolfree, how much free space left POOLFREE=`zpool list $POOLNAME -o free` #POOLFREE=$(echo "$POOLFREE" | grep -e [[:digit:]]*.[[:digit:]].) POOLFREE=$(echo "$POOLFREE" | grep -e [[:digit:]]) POOLFREE=$(numfmt --from=$INFORMAT $POOLFREE) #echo poolfree $POOLFREE #grep -e "vault..[[:digit:]]*.[[:digit:]].") #minfree, how low can we go, before alerting MINFREE=$(numfmt --from=iec-i $MINFREE) #echo minfree $MINFREE #FORMATTED DATA USED FOR DISPLAYING THINGS #echo formattiing sizes: F_POOLSIZE=$(numfmt --from=$INFORMAT --to=$OUTFORMAT $POOLSIZE) F_POOLFREE=$(numfmt --from=$INFORMAT --to=$OUTFORMAT $POOLFREE) F_MINFREE=$(numfmt --from=$INFORMAT --to=$OUTFORMAT $MINFREE) F_MINFREE=$(numfmt --from=$INFORMAT --to=$OUTFORMAT $MINFREE) #echo printf "${BGREEN}$F_POOLSIZE - current pool size" printf "\n$F_MINFREE - mininium freespace allowed/as specified" # OPERATE/CALCULATE SPACE TEST #echo ... calculating specs, please wait.. #let f=$POOLFREE m=$MINFREE x=m/f; declare -i x=$POOLFREE/$MINFREE; # will be 0 if has reached low threshold, if poolfree/minfree #echo $x #IF_CALC=$(numfmt --to=iec-i $CALC) if ! [ "${x}" == 1 ]; then #printf "\n${BRED}ALERT! POOL FREESPACE is low! ($F_POOLFREE)" printf "\n${BRED}$F_POOLFREE ${BYELLOW}- current freespace! ${BRED}(ALERT!}${BYELLOW} Is below your preset threshold!"; echo else printf "\nPOOLFREE - ${BGREEN}$F_POOLFREE${TXTRESET}- current freespace"; #sleep 3 fi ```
2021/06/01
[ "https://unix.stackexchange.com/questions/652375", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/111873/" ]
There is no good way to convert `zfs`'s human-readable numbers to actual bytes. The human-readable numbers are rounded off and therefore inexact. If you want exact numbers, use the `-p` option (machine parseable), and the output will be in bytes, which you can parse and format however you wish. ``` $ zfs list tank/var; zfs list -p tank/var NAME USED AVAIL REFER MOUNTPOINT tank/var 8.33G 387G 6.90G /var NAME USED AVAIL REFER MOUNTPOINT tank/var 8948584448 415137447936 7407120384 /var ``` But parsing `zfs`'s human-readable output and converting to "exact" numbers is not possible. Since the human readable numbers are only specified to (say) three significant figures, your "exact" extrapolation will also be accurate only to three figures. ``` TiB=$((2**40)) GiB=$((2**30)) # MINFREE=$((50*$TiB)) # 50 TiB MINFREE=$((50*$GiB)) # 50 GiB POOLFREE=$(zpool list -Hpo free "$POOLNAME") #Free in bytes if [ "$POOLFREE" -lt "$MINFREE" ]; then printf "alert\n" else printf "no alert -- %d bytes free >= %d byte minimum\n" "$POOLFREE" "$MINFREE" fi ```
`zpool list` can provide the numbers in bytes. e.g. listing three pools (15T, 29T, and 416G) on my main zfs server. First, without `-H` and `-p`: ```none $ zpool list -o name,size,alloc,free,capacity NAME SIZE ALLOC FREE CAP backup 14.5T 6.15T 8.40T 42% export 29T 17.8T 11.2T 61% ganesh 416G 169G 247G 40% ``` And again, with `-H` and `-p` ```none $ zpool list -H -p -o name,size,alloc,free,capacity backup 15994458210304 6763872280576 9230585929728 42 export 31885837205504 19592775573504 12293061632000 61 ganesh 446676598784 181604904960 265071693824 40 ``` The output is tab separated, so is easily processed with `awk` or `cut` or whatever you like (even a shell while read loop if you [insist](https://unix.stackexchange.com/q/169716/7696)). The `capacity` field is the percentage used, so is particularly useful if you want to email an alert if a pool gets below 10% or 20% free. * `-H` is `Scripted mode. Do not display headers, and separate fields by a single tab instead of arbitrary space.` * `-p` prints "parseable" as opposed to "human readable" format (i.e. bytes) BTW, recent versions of ZFS have the `zfs` and `zpool` man pages split into separate pages for their sub-commands, properties, concepts, etc. If that's what you're running, see the man pages for `zpool-list` and `zpoolprops` for more details. Otherwise, just `man zpool`.
6,086,912
Is the following singleton implementation data-race free? ``` static std::atomic<Tp *> m_instance; ... static Tp & instance() { if (!m_instance.load(std::memory_order_relaxed)) { std::lock_guard<std::mutex> lock(m_mutex); if (!m_instance.load(std::memory_order_acquire)) { Tp * i = new Tp; m_instance.store(i, std::memory_order_release); } } return * m_instance.load(std::memory_order_relaxed); } ``` Is the `std::memory_model_acquire` of the load operation superfluous? Is it possible to further relax both load and store operations by switching them to `std::memory_order_relaxed`? In that case, is the acquire/release semantic of `std::mutex` enough to guarantee its correctness, or a further `std::atomic_thread_fence(std::memory_order_release)` is also required to ensure that the writes to memory of the constructor happen before the relaxed store? Yet, is the use of fence equivalent to have the store with `memory_order_release`? **EDIT**: Thanks to the answer of John, I came up with the following implementation that should be data-race free. Even though the inner load could be non-atomic at all, I decided to leave a relaxed load in that it does not affect the performance. In comparison to always have an outer load with the acquire memory order, the thread\_local machinery improves the performance of accessing the instance of about an order of magnitude. ``` static Tp & instance() { static thread_local Tp *instance; if (!instance && !(instance = m_instance.load(std::memory_order_acquire))) { std::lock_guard<std::mutex> lock(m_mutex); if (!(instance = m_instance.load(std::memory_order_relaxed))) { instance = new Tp; m_instance.store(instance, std::memory_order_release); } } return *instance; } ```
2011/05/22
[ "https://Stackoverflow.com/questions/6086912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19630/" ]
That implementation is **not** race-free. The atomic store of the singleton, while it uses release semantics, will only synchronize with the matching acquire operation—that is, the load operation that is already guarded by the mutex. It's possible that the outer relaxed load would read a non-null pointer before the locking thread finished initializing the singleton. The acquire that is guarded by the lock, on the other hand, is redundant. It will synchronize with any store with release semantics on another thread, but at that point (thanks to the mutex) the only thread that can possibly store is the current thread. That load doesn't even need to be atomic—no stores can happen from another thread. See [Anthony Williams' series on C++0x multithreading](http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-6-double-checked-locking.html).
See also [call\_once](http://en.cppreference.com/w/cpp/thread/call_once). Where you'd previously use a singleton to do something, but not actually use the returned object for anything, call\_once may be the better solution. For a regular singleton you *could* do call\_once to set a (global?) variable and then return that variable... Simplified for brevity: ``` template< class Function, class... Args> void call_once( std::once_flag& flag, Function&& f, Args&& args...); ``` * Exactly one execution of exactly one of the functions, passed as f to the invocations in the group *(same flag object)*, is performed. * No invocation in the group returns before the abovementioned execution of the selected function is completed successfully
37,797,992
I need to count the characters from a to z in an array. For example I have an array like this: ``` ["max","mona"] ``` The desired result would be something like this: a=2, m=2, n=1, o=1, x=1 It would be great, if anyone could help me :)
2016/06/13
[ "https://Stackoverflow.com/questions/37797992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464200/" ]
You can use two `forEach` loops and return object ```js var ar = ["max", "mona"], o = {} ar.forEach(function(w) { w.split('').forEach(function(e) { return o[e] = (o[e] || 0) + 1; }); }); console.log(o) ``` Or with ES6 you can use arrow function ```js var ar = ["max","mona"], o = {} ar.forEach(w => w.split('').forEach(e => o[e] = (o[e] || 0)+1)); console.log(o) ``` As @Alex.S suggested you can first use `join()` to return string, then `split()` to return array and then you can also use `reduce()` and return object. ```js var ar = ["max", "mona"]; var result = ar.join('').split('').reduce(function(o, e) { return o[e] = (o[e] || 0) + 1, o }, {}); console.log(result) ```
The solution using `Array.join`, `Array.sort` and `String.split` functions: ``` var arr = ["max","mona"], counts = {}; arr = arr.join("").split(""); // transforms the initial array into array of single characters arr.sort(); arr.forEach((v) => (counts[v] = (counts[v])? ++counts[v] : 1)); console.log(counts); // {a: 2, m: 2, n: 1, o: 1, x: 1} ```
167,542
$$ \frac{|x|-|y|}{1+|xy|} $$ How can I reduce the amount of code without losing quality? What are your tips? Your comments on the structure, logic, in general, everything. How to make the type of data entered by the user determined automatically? ``` using System; class taskTwo { static void Main() { int x, y; // Declare variables double z, w; Console.WriteLine("Please, enter two the numbers"); x = int.Parse(Console.ReadLine()); //The user enters y = int.Parse(Console.ReadLine()); if (x == 0 && y == 0)//If two zeros are entered, then the numerator is zero. { Console.WriteLine("The numerator and denominator can not be zero"); } else { z = Math.Abs(x) - Math.Abs(y);//Know what the numerator is equal to if (z == 0)//If the numerator is zero, then ... { Console.WriteLine("Numerator is zero, division is impossible"); } else { w = z / (1 + Math.Abs(x) * Math.Abs(y)); //Final calculation Console.WriteLine("W = " + w); //Display the result on the screen } } }} ```
2017/07/06
[ "https://codereview.stackexchange.com/questions/167542", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/142832/" ]
You really should improve your code formatting. Code which is formatted well (indentation, concise brackets) is easier to read and understand. I'd also suggest you to improve your variable naming a bit. For example `z` isn't too descriptive. Instead I'd name it `numerator` and name `w` `result`. You don't need to declare your variables at the top of your method. You rather [should](https://codereview.stackexchange.com/questions/6283/variable-declaration-closer-to-usage-vs-declaring-at-the-top-of-method) declare them closer to the usage. Your comments describe what you are doing. It's not what you should be doing. Comments [should](https://stackoverflow.com/a/390817/3533380) rather describe *why* are you doing what you are doing. Compare my below final formatting to yours ``` using System; class TaskTwo { static void Main() { Console.WriteLine("Please, enter two the numbers"); int x = int.Parse(Console.ReadLine()); int y = int.Parse(Console.ReadLine()); // If two zeros are entered, then the numerator is zero if (x == 0 && y == 0) { Console.WriteLine("The numerator and denominator can not be zero"); } else { // Know what the numerator is equal to double nominator = Math.Abs(x) - Math.Abs(y); //If the numerator is zero, then ... if (z == 0) { Console.WriteLine("Numerator is zero, division is impossible"); } else { // Final calculation double result = nominator / (1 + Math.Abs(x) * Math.Abs(y)); // Display the result on the screen Console.WriteLine("Result = " + result); } } } } ```
> > How can I reduce the amount of code without losing quality? > > > Well... there is no quality yet ;-) and actually you are going to gain some code if you want to improve it. I won't try to prove whether there are numbers that can break this fraction in any way but for the sake of the review let's assume the denominator can be zero. --- The first improvement you can make is to create a class and a method for the formula because in a real application you wan't to write some test before you let anyone use it so how about a `Calculator`? I don't know if this formula has any special name so I just named it `Fraction1`. Apart from putting it in a testable calculator you should work on the names. What is `z` or `w`? How are those letters related to the formula? If you are splitting it into multiple variables then give them resonable names. Should it happen that the denominator is `0` then the `DivideByZeroException` is to be thrown and handeled. ``` class Calculator { public double CalcFraction1(double x, double y) { var numerator = Math.Abs(x) - Math.Abs(y); var denominator = (1 + Math.Abs(x) * Math.Abs(y)); if (denominator == 0) { throw new DivideByZeroException(); } return numerator / denominator; } } ``` You now have a calculator that works. The next step is to read from the console... but maybe you want to read the numbers until the input is correct? Currently it would crash if you enter a letter. So create a helper for it that will try to parse the input until it's a valid value. Instead of using `int` for this job you could use `double` to get more precision: ``` private static double ReadNumber() { double value; while (!double.TryParse(Console.ReadLine(), out value)) { } return value; } ``` The last step is to put everything together, this is, create the calculator, read the the numbers and calculate the result or handle the exception if it wasn't possible: ``` void Main() { var calculator = new Calculator(); Console.WriteLine("Please, enter two numbers"); var x = ReadNumber(); var y = ReadNumber(); try { Console.WriteLine($"W = {calculator.CalcFraction1(x, y)}"); } catch (DivideByZeroException) { Console.WriteLine("Cannot calculate fraction1 because the denominator is zero."); } } ``` You should always try to encapsulate pieces of code that should be tested or can work and be reused independently for example you could copy/paste the `ReadNumber` method and use it for a different console application or tune it and add additional output about an invalid number without touching any other part. This is what we always try to achieve. Small units that do their job well and can be use like pieces of puzzle to build something bigger, something useful.
10,852
I have been asked to come up with an interface for a website that stores information about certifications and companies who hold those certifications. From the search logs I know users mostly search for a type of certificate but also will search for a particular company to see what certificates they hold. The problem is that the results pages will be completely different. I know that if users look for a certificate they need to be able to view and filter a list of records with attributes relevant to *certificates*. If users look for a company they need to be able to view and filter a list of records with attributes relevant to *companies*. The two sets of attributes are, unfortunately, mutually exclusive and this is why I think the best approach is two types of result screen. My question: is using two types of result screen the only option or am I missing something? tx
2011/09/05
[ "https://ux.stackexchange.com/questions/10852", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4701/" ]
I don't think you're missing anything. This sounds like you have two users groups with different objectives and they should be treated as such: IMO you should have two different search forms and two different result pages. Having one form and result page only sound good in theory (less pages, less to learn, one page for all needs etc.) but actually isn't good for the user's experience because in both cases (looking for a company vs. looking for certificates) he will have to deal with stuff he doesn't care about.
A follow-on to @Phil's answer is that if you cannot easily distinguish queries for the two types of cases, you might consider generating a separate tab for each type of result and let the user select the one they want. (if you have a good guess as to the type of query, you can pre-select the corresponding tab.) This might give people a clue that other kinds of searches are possible, in case they have a different information need in the future. But I would argue for keeping the results separate and creating different displays for each type to reflect the fundamental differences.
46,675,819
I'm trying to use multer to process a profile photp upload on the frontend to the backend but keep getting this error: ``` { [Error: Unexpected field] code: 'LIMIT_UNEXPECTED_FILE', field: 'file', storageErrors: [] } ``` Below is my code: register.ejs: ``` <div class="form-group"> <input class="form-control" type="file" name="image" id="image"> </div> ``` ajax.js: ``` $('form').submit(function(e) { e.preventDefault(); var formData = new FormData(this); // var img = cropper.getCroppedCanvas().toDataURL(); // formData.append('img',img); $.ajax({ url: '/register', type: 'POST', data: formData, processData: false, contentType: false, success: function () { console.log('Upload success'); }, error: function () { console.log('Upload error'); } }); }); ``` app.js: ``` var multer = require('multer'); var cloudinary = require('cloudinary'); ... // MULTER var storage = multer.diskStorage({ destination: function(req, file, callback) { callback(null, "./public/uploads"); }, filename: function(req, file, callback) { callback(null, Date.now() + file.originalname); } }); var upload = multer({ storage : storage}).single("image"); app.post("/register", function(req, res) { upload(req, res, function(err){ if(err) { console.log(err); return res.send("Error uploading file."); } res.send("Upload success"); }); }); ``` I also get an undefined object when I try to get req.body.img or req.file. Maybe the formdata is not populated properly? Can anyone shed some light for me?
2017/10/10
[ "https://Stackoverflow.com/questions/46675819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5091363/" ]
It says on `multer` [docs](https://www.npmjs.com/package/multer) that you should pass `enctype="multipart/form-data"` attribute to your `<form>` element. I'm not really familiar with `ajax`, but I think you may have to set `contentType:` in `ajax.js` to `"multipart/form-data"`. I also had a similar error, but it was caused by non-matching text-field keys.
I have also face the same issue, instead of using > > var upload = multer({ storage : storage}).single('image'); > > > use the fields() method which allow to handle multiple files at once > > app.use(multer({ storage : storage}).fields([{name:'image',maxCount:1}])); > > > file data store in req.files , then you can simply handle the files that error occur when you try to handle multiple form data object in single multer middleware, you can use the `storage` option to store different files in different locations. further more can go thought official doc
12,122,021
I am looking for a Python implementation of an algorithm which performs the following task: **Given two directed graphs, that may contain cycles, and their roots, produce a score to the two graphs' similarity.** (The way that Python's `difflib` can perform for two sequences) Hopefully, such an implementation exists. Otherwise, I'll try and implement an algorithm myself. In which case, what's the preferable algorithm to implement (with regard to simplicity). The way the algorithm works is of no importance to me, though its' complexity is. Also, an algorithm which works with a different data-structure is also acceptable, as long as a graph, such as I described, can be represented with this DS. I'll emphasize, an implemetation would be much nicer. **Edit:** It seems an isomorphism algortihm is not relevant. It was suggested that graph edit distance is more to the point, which narrows down my search to a solution that either **executes graph edit distance** or **reduces a graph to a tree and then performs tree edit distance**. The nodes themseleves consist of a few lines of assembly code each.
2012/08/25
[ "https://Stackoverflow.com/questions/12122021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614978/" ]
Another method is to use what is called *Eigenvector Similarity*. Basically, you calculate the Laplacian eigenvalues for the adjacency matrices of each of the graphs. For each graph, find the smallest *k* such that the sum of the *k* largest eigenvalues constitutes at least 90% of the sum of all of the eigenvalues. If the values of *k* are different between the two graphs, then use the smaller one. The similarity metric is then the sum of the squared differences between the largest *k* eigenvalues between the graphs. This will produce a similarity metric in the range [0, ∞), where values closer to zero are more similar. For example, if using `networkx`: ``` def select_k(spectrum, minimum_energy = 0.9): running_total = 0.0 total = sum(spectrum) if total == 0.0: return len(spectrum) for i in range(len(spectrum)): running_total += spectrum[i] if running_total / total >= minimum_energy: return i + 1 return len(spectrum) laplacian1 = nx.spectrum.laplacian_spectrum(graph1) laplacian2 = nx.spectrum.laplacian_spectrum(graph2) k1 = select_k(laplacian1) k2 = select_k(laplacian2) k = min(k1, k2) similarity = sum((laplacian1[:k] - laplacian2[:k])**2) ```
I think the way you define similarity is not very standard, so it is probably easier to find the implementations for the isomorphism check, graph edit distance and maximum common subgraph and then combine those yourself. One should understand, however, that calculating such a similarity measure might be costly, so if there're a lot of graphs you might want to do some sort of screening first. [igraph](http://cneurocvs.rmki.kfki.hu/igraph/) can check for isomorphism, for example. **EDIT:** actually you probably only need the edit distance, since the presence of an MCS is usually irrelevant, as I pointed out above, and two graphs will be isomorphic anyway if the edit distance is 0.
9,591,023
I have two problems. One is that it is only pulling one row and sending it to ms fax when there are a few hundred to be sent. The other is that it doesn't pull any more after that first and it throws an error. I thought I was closing out my connections. I don't understand what the problem is. I have included the code and error. Service1.cs ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Timers; using MySql.Data.MySqlClient; using FAXCOMLib; using FAXCOMEXLib; namespace ProcessFaxes { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } public static Timer timer = new Timer(); protected override void OnStart(string[] args) { timer.Elapsed += new ElapsedEventHandler(Tick); timer.Interval = 600000; // every 10 minutes timer.Enabled = true; // Console.ReadLine(); } protected override void OnStop() { } public static void Tick(object source, ElapsedEventArgs e) { string connString = "Server=localhost;Port=3306;Database=communications;Uid=root;password=pass;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); MySqlConnection connupdate = new MySqlConnection(connString); MySqlCommand commandupdate = connupdate.CreateCommand(); command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'"; //command.CommandText = "UPDATE blah blah"; //conn.Open(); //conn.ExecuteNonQuery(); //conn.Close(); try { conn.Open(); connupdate.Open(); } catch (Exception ex) { // Console.WriteLine(Ex.Message); LogException(ex.ToString()); throw; // or whatever you want to do with it } MySqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { //Console.WriteLine(reader["filepath"].ToString()); SendFax(reader["id"].ToString(), reader["filepath"].ToString(), @"C:\FAXDOC\" + reader["filepath"].ToString(), reader["account"].ToString(), reader["fax"].ToString(), reader["fax_orig"].ToString()); string id = reader["id"].ToString(); commandupdate.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'"; commandupdate.ExecuteNonQuery(); } } conn.Close(); connupdate.Close(); } public static void SendFax(string DocumentId, string DocumentName, string FileName, string RecipientName, string FaxNumber, string RecipientHomePhone2) { if (FaxNumber != "") { try { FAXCOMLib.FaxServer faxServer = new FAXCOMLib.FaxServerClass(); faxServer.Connect(Environment.MachineName); FAXCOMLib.FaxDoc faxDoc = (FAXCOMLib.FaxDoc)faxServer.CreateDocument(FileName); faxDoc.RecipientName = RecipientName; faxDoc.FaxNumber = FaxNumber; faxDoc.BillingCode = DocumentId; faxDoc.DisplayName = DocumentName; faxDoc.RecipientHomePhone = RecipientHomePhone2; int Response = faxDoc.Send(); faxServer.Disconnect(); } catch (Exception Ex) { // Console.WriteLine(Ex.Message); LogException(Ex.ToString()); throw; // or whatever you want to do with it } } } public static void LogException(string ErrorDescription) { // The name of our log in the event logs string Log = "Process Faxes"; // Check to see fi the log for AspNetError exists on the machine // If not, create it if ((!(EventLog.SourceExists(Log)))) { EventLog.CreateEventSource(Log, Log); } // Now insert your exception information into the AspNetError event log EventLog logEntry = new EventLog(); logEntry.Source = Log; logEntry.WriteEntry(ErrorDescription, EventLogEntryType.Error); } } } ``` error ``` Event Type: Error Event Source: Process Faxes Event Category: None Event ID: 0 Date: 3/6/2012 Time: 2:01:06 PM User: N/A Computer: FAXSERVER Description: MySql.Data.MySqlClient.MySqlException (0x80004005): Too many connections at MySql.Data.MySqlClient.MySqlStream.ReadPacket() at MySql.Data.MySqlClient.NativeDriver.Open() at MySql.Data.MySqlClient.Driver.Open() at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() at MySql.Data.MySqlClient.MySqlPool.GetConnection() at MySql.Data.MySqlClient.MySqlConnection.Open() at ProcessFaxes.Service1.Tick(Object source, ElapsedEventArgs e) in C:\Documents and Settings\bruser\My Documents\Visual Studio 2010\Projects\ProcessFaxes\ProcessFaxes\Service1.cs:line 56 ```
2012/03/06
[ "https://Stackoverflow.com/questions/9591023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1046434/" ]
I think you should refactor a bit. I explained a little in a comment above, but here's how I would change it (I added some comments for you too): ``` public static void Tick(object source, ElapsedEventArgs e) { // Prevent another Tick from happening if this takes longer than 10 minutes (source as Timer).Enabled = false; // It would be better practice to put this in a settings or config file // so you can change it without having to recompile your application string connString = "Server=localhost;Port=3306;Database=communications;Uid=root;password=pass;"; // I won't change them here, but since these classes implement IDisposable, // you should be using a using statement around them: // using (var conn = new MySqlConnection(connString)) // { // // use conn // } MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); MySqlCommand updateCommand = conn.CreateCommand(); command.CommandText = "SELECT * FROM outbox WHERE `faxstat` = 'Y' AND `fax` <> '' AND `faxpro` = 'PENDING'"; try { conn.Open(); MySqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { SendFax(reader["id"].ToString(), reader["filepath"].ToString(), @"C:\FAXDOC\" + reader["filepath"].ToString(), reader["account"].ToString(), reader["fax"].ToString(), reader["fax_orig"].ToString()); string id = reader["id"].ToString(); // I would use a prepared statement with either this query // or a stored procedure with parameters instead of manually // building this string (more good practice than worrying about // SQL injection as it's an internal app updateCommand.CommandText = "UPDATE outbox SET `faxpro` = 'DONE' WHERE `id` = '" + id + "'"; updateCommand.ExecuteNonQuery(); } } } catch (Exception ex) { LogException(ex.ToString()); throw; } finally { // If you're not going to use using-statements, you might want to explicitly // call dispose on your disposable objects: // command.Dispose(); // updateCommand.Dispose(); conn.Close(); // conn.Dispose(); } // Enable the timer again (source as Timer).Enabled = true; } ``` As to why you're only receiving one row when you're expecting many, I suspect your SQL is at fault.
You should not be using a timer. A timer fires at regular intervals, and does not care if the previous event has completed or not. Look at using a [Background Worker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to send your faxes, having it loop over the queue, and then pause when the queue is empty.
3,004,752
$(x^2 + 2 + \frac{1}{x} )^7$ Find the coefficient of $x^8$ Ive tried to combine the $x$ terms and then use the general term of the binomial theorem twice but this does seem to be working. Does anyone have a method of solving this questions and others similar efficiently? Thanks.
2018/11/19
[ "https://math.stackexchange.com/questions/3004752", "https://math.stackexchange.com", "https://math.stackexchange.com/users/594817/" ]
In order to get $x^8$ in the product you have to have either $$x^2 x^2 x^2 x^2 \times 2^3$$ or$$ x^2 x^2 x^2 x^2 x^2 (1/x)(1/x)$$ There are $\binom 7 4 $ of the first type and $ \binom 7 5$ of the second type. Thus the coefficient of $x^8$ is $8(35)+21 = 301$
The answer is 301. Just trust your plan of the twofold use of the binomial formula: First step $$\left((x^2+2)+\frac{1}{x}\right)^7=\sum \_{k=0}^7 \binom{7}{k} \left(x^2+2\right)^k x^{k-7}$$ Second step $$\left(x^2+2\right)^k=\sum \_{m=0}^k 2^{k-m} x^{2 m} \binom{k}{m}$$ Hence you get a double sum in which the power of $x$ is $2m+k-7$, setting this equal to $8$ we get $k = 15-2m$. This leaves this single sum over $m$ $$\sum \_{m=0}^7 2^{15-3 m} \binom{7}{15-2 m} \binom{15-2 m}{m}$$ Since, for $n, m = 0,1,2,...$ the binomial coefficient $\binom{n}{m}$ is zero unless $n\ge m$ we find $7\ge 15-2m \to m \ge 4$ and $15-2m\ge m \to m\le 5$. Hence only the terms with $m=4$ and $m=5$ contribute to the sum giving $280$ and $31$, respectively, the sum of which is $301$.
105,923
In high-school level books (for example the german standard text: "Dorn-Bader") I have often seen an explanation of the Lorentz force as on the following picture: ![enter image description here](https://i.stack.imgur.com/eHiQk.gif) The textbooks consider the superposition of the circular field of the wire and the homogenous field of the magnet (sure the homogenity doesn't matter here). Then the net field as you can see on the picture above on the right is larger on one side of the wire (here on the right) and smalle on the other one. So far so good. However why does this **explain** the occurence and direction of the Lorentz force. Do do so, one would need another principle for example that the wire always wants to go to the weaker field regions or something like this. And this principle should be somehow more evident than the Lorentz-force itself (which you can "see" experimentally). But how is this needed principle exacly forumlated? Why it is correct? Is there any good reason that it is more evident than just taking the Lorentz-force as an experimental fact? Would be great if someone could clarify the logic of this, evaluate the soundness of the argument and embedd it conceptually and mathematically in the big picture of electromagnetic theory. Additionally I want to know if the above cited "explanation" has any common name and if there are university level textbooks which proceed in a similar way. I feel that this argument goes back to Michael Faraday (just by the style of reasoning) - so if someone has a reference to the orgin of the argument I would be interested in it, too. By the way: The magnetic field in the above cited book ("Dorn Bader") is introduced by the interaction of permament magnets...
2014/03/31
[ "https://physics.stackexchange.com/questions/105923", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/6581/" ]
While the field is $\vec F = q\vec v \times \vec B$, it is not a terribly intuitive process. The closest one comes to a vector-product in the real world is the Coralis force, where the wind goes clockwise around a low, and anticlockwise around a high. A moving charge sets up a circular magnetic field, which is one direction or the other, depending on the sign of the charge. When this moves into a magnetic field, the fields add on one side, and subtract on the other side, so that charge is pushed perpendicular both to the field, and to the direction of travel. In the case of a conductor, like this example, the charge is bound to a rod, and the rod is moved outwards (or inwards) to the magnet, as the current is flowing one way or the other. Where the charge is not restricted to a mechanical device (like a peice of wire), the charge travels in a circle, and such devices are known as **cyclotrons**. Permanent magnets are used, because these are able to produce a constant $\vec B$. An electromagnet is necessarily an changing-flux and changing-current thing, and thus can not make a constant flux-field. The vector-product is not symmetric, ie $\vec A \times \vec B = -\vec B \times \vec A$, and since it is a parity thing in both 2d and 3d, one can use *either* a left-hand rule or a right hand rule. But it must be used consistantly, like it's ok for everyone to drive on the left or on the right of the road, but everyone's got to do the same. So we ram the right-hand rule, for rotating A onto B gives A×B. It's just a way of keeping tabs on the symmetry-breaking process. Jeffimenko's "Electricity and Magnetism" gives the formula alone, but vector relations occupy the full first chapter. Like Heaviside, J supposes a healthy dose of vector arithmetic is needed before electricity is mentioned. The text i used at uni in the seventies (Grant and Phillips 'Electromagnetism'), shows essentially the diagram in two parts (the poles, and then some pages later the wire), but both indicate three orthogonal vectors. No name is attached to it, but it pretty much represents the notional way (legal metrology), that one would define this event: bereft of the complexities where the geometry adds additional factors to the product.
The deflection of a current-carrying wire, the deflection of the electron and also the Hall effects are all based on the same principle. One can break down both the Lorentz force and the Hall effects to the movement of an electron in the magnetic field as the easiest process to analyze. It has been pointed out many times in this forum that the external magnetic field does not spend any energy to deflect the charges. However, since the deflection is (equivalent to) an acceleration, energy is required for this. Where does this energy come from? A static charge in a magnetic field is not deflected. Although, something happens anyway. Every charge is at the same time also a magnetic dipole. This is not mentioned very often, but for example the electron has an [unique value](https://physics.nist.gov/cgi-bin/cuu/Value?muem%7Csearch_for=electron-neutron) for its magnetic moment. The magnetic dipole of the electron and the external magnetic field interact and **the electron is aligned with its poles at the external magnetic field**. Since only a moving electron (as for the Lorentz force phenomenon the current in the wire) is deflected in the magnetic field, the thought is obvious that the **kinetic energy of the charge is involved** in the energy turnover for the deflection. In this [article](https://www.osti.gov/etdeweb/biblio/6898393) a connection is made between the radiation of electromagnetic energy and the magnetic dipole moment. (Thanks to *anna v* for pointing this out [here](https://physics.stackexchange.com/questions/635718/if-the-magnetic-force-doesnt-change-the-speed-of-a-moving-charge-can-it-be-thou)). If one wants, one can find an explanation for the cause of the Lorentz force. It **is the emission of EM radiation which causes the deflection of the charges**. For the Lorentz force this is not noticed, but should be detectable by a loss of energy at the wire (temperature increase and increase of the electrical resistance). However, in the synchrotron or for [free-electron laser](https://en.wikipedia.org/wiki/Free-electron_laser), this EM radiation is obvious or even desired for the latter device.
56,190,339
This is my code I have successfully sorted and got my final result to be what I wanted. Now I want to also sort so that the object name that contains the key word "newitem" will always get sorted to the bottom. ``` var testgogo = { "newitemwrewt": { "brand": { "gdhshd": true }, "stock": 2, "sold": 3 }, "other": { "brand": { "gdhshd": true }, "stock": 2, "sold": 3 }, "newitemncnc": { "brand": { "gdhshd": true }, "stock": 2, "sold": 3 }, }; finalresult = Object .keys(testgogo) .sort( (a, b) => (testgogo[a].stock !== undefined) - (testgogo[b].stock !== undefined) || testgogo[a].stock - testgogo[b].stock || testgogo[b].sold - testgogo[a].sold )[0]; console.log(finalresult); ``` Thanks for any help
2019/05/17
[ "https://Stackoverflow.com/questions/56190339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11165692/" ]
Javascript objects can't be ordered. If you need that data to be in an order you should make it an array.
You could sort the [entries](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) of the object based on whether the key [`includes`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes) the string `"newitem"`. Then use [`Object.fromEntries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) to convert the sorted entries back to an object ```js const testgogo={newitemfgre:{brand:{gdhshd:!0},stock:2,sold:3},fruit:{brand:{grgrdgdr:!0,ggyugy:!0},stock:3,sold:2},vegetable:{brand:{htrhtr:!0},stock:1,sold:1},newitemwrewt:{brand:{gdhshd:!0},stock:2,sold:3},other:{brand:{gdhshd:!0},stock:2,sold:3},newitemncnc:{brand:{gdhshd:!0},stock:2,sold:3},snack:{brand:{htrhr:!0},stock:1,sold:4},afga:{brand:{gdhshd:!0},stock:1,sold:2},other:{brand:{gdhshd:!0},stock:2,sold:3}}; const str = "newitem"; const sortedEntries = Object.entries(testgogo) .sort((a, b) => a[0].includes(str) - b[0].includes(str)); const output = Object.fromEntries(sortedEntries) console.log(output) ``` Subtracting booleans returns a 1, -1 or 0. ``` true - false === 1 false - true === -1 true - true === 0 ``` So, if `a[0]` has `"newitem"` but `b[0]` doesn't, the key at `a[0]` will be moved to the end of the entries array.
17,114,317
I've added a user selected theme option to my app. Each relevant element (mostly UIViews) conditionally change their appearance dependent on the state of an NSUserDefaults BOOL. This worked fine when I was setting the state using a #define followed by Build and Run. But, I need the UI to "refresh" when the user flips a switch. In theory *I think* I need to cascade a setNeedsDisplay down from self.window. Is there a smart way to achieve this. I've tried working down through the subViews using @mattmook's solution in the link below but it doesn't go far enough and I'm not certain it's the best way to achieve what I'm trying to do. [iPhone Programming setNeedsDisplay not working](https://stackoverflow.com/questions/1117229/iphone-programming-setneedsdisplay-not-working) Can someone either confirm that this is the best method or suggest something simpler? Thanks, Steve
2013/06/14
[ "https://Stackoverflow.com/questions/17114317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1168863/" ]
Make the interested views listen to a notification. When data change, send a notification and let all the views update themselves. In general, it's better to have such functionality decentralized.
That depends on how you actually apply the color change. Did you subclass each UIView object that you are using to ensure that it fetches its color from whereever and changes it accoringly before drawing itself? Such as overwriting drawRect like this: ``` - (void) drawRect:... { if (somehowFetchTheUserDefaultsBoolValueHere) { self.tint = [UIColor redColor]; // details here may vary depedning on the actual superclass } else { self.tint = [UIColor greenColor]; } [super drawRect:...]; } ``` (Just showing the principle. There are actually smarter ways of coding that.) If you did that then `setNeedsDisplay` on the current view controller's `self.view` would do. (on the main thread if in doubt) Alternative: If you perform the tinting by any other means then you need to execute that code which tints all currently presented views. That is in most cases the view controller on top. For all other view controllers you could place the tinting code in their `viewWillAppear` method. Works fine. Did that myself just rechently. However, subclassing all views could be more efficient as it means a once-off effort only, depending on the total size of your app. Plus it could be re-used in other apps.
2,399,112
Consider this Python code for printing a list of comma separated values ``` for element in list: print element + ",", ``` What is the preferred method for printing such that a comma does not appear if `element` is the final element in the list. ex ``` a = [1, 2, 3] for element in a print str(element) +",", output 1,2,3, desired 1,2,3 ```
2010/03/08
[ "https://Stackoverflow.com/questions/2399112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357024/" ]
It's very easy: ``` print(*a, sep=',') ``` [Print lists in Python (4 Different Ways)](https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/)
That's what [`join`](http://docs.python.org/library/stdtypes.html#str.join) is for. ``` ','.join([str(elem) for elem in a]) ```
29,406,902
I recently migrated my app to Material Design and I stumbled upon this problem with my Alert Dialogs: ![dialog appears to be having two backgrounds and I don't know how to get rid of the outer background](https://i.stack.imgur.com/G9KqO.png) I'm applying the dialog style like this: `<item name="android:alertDialogTheme">@style/Theme.AlertDialog</item>` and **Theme.AlertDialog** looks like this: ``` <style name="Theme.AlertDialog" parent="Base.V14.Theme.AppCompat.Dialog"> <item name="colorPrimary">@color/theme_primary</item> <item name="colorPrimaryDark">@color/theme_primary_dark</item> <item name="colorAccent">@color/theme_accent_dark</item> </style> ``` This is happening on my Kitkat device and it works fine on Lollipop. Can you help me with getting rid of that outer background?
2015/04/02
[ "https://Stackoverflow.com/questions/29406902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1102276/" ]
The point is here: ``` <style name="Theme.AlertDialog" parent="Base.V14.Theme.AppCompat.Dialog"> ... <item name="colorPrimary">@color/theme_primary</item> <item name="colorPrimaryDark">@color/theme_primary_dark</item> <item name="colorAccent">@color/theme_accent_dark</item> ... <item name="android:windowBackground">@android:color/transparent</item> ... </style> ```
As [ironman](https://stackoverflow.com/users/6343685/ironman) told me [here](https://stackoverflow.com/questions/40738437/weird-behavior-when-applying-theme-to-dialog-under-api-21), be sure that you import the right class. Right : `import android.support.v7.app.AlertDialog;` Wrong : `import android.app.AlertDialog;`
37,311,443
I'm currently trying to create a responsive menu button for my navigation bar, and it does not seem to be responding to a mouse click. ```js $("span.nav-btn").click(function() $("ul.nav-toggle").slidetoggle(); }) ``` [Fiddle](https://jsfiddle.net/dh86ea79/6/)
2016/05/18
[ "https://Stackoverflow.com/questions/37311443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6353427/" ]
Your line is building a formula but passing a range into it instead of just the address of the range, use `.Address(ReferenceStyle:=xlR1C1`. Once that is there, remove the square parenthesis:- ``` Worksheets(" Branded").Range("A1").Formula = "=COUNTIFS(" & r.Address(ReferenceStyle:=xlR1C1) & ":" & r2.Address(ReferenceStyle:=xlR1C1) & ",RC2,R21C22:R71C22,R2C)" ``` It shows up as a `#value` but then we don't have the full data set to test with.
I realized that I had made a mistake in the full line. With the above answer I figured out that it needs to be. ``` Worksheets(" Branded").Range("A1").Formula = "=COUNTIFS(" & r.Address(ReferenceStyle:=xlR1C1) & ",RC2, " & r2.Address(ReferenceStyle:=xlR1C1) & ",R2C)" ```
24,389,491
I have a simple pair of client and server programs. Client connects to server and when it does connect, the server replies with a "Hello there" message. How should I modify the program if I want the client and server programs to run on different systems? Here is the code for the client side.. ``` package practice; import java.io.*; import java.net.*; public class DailyAdviceClient { public static void main(String args[]) { DailyAdviceClient dac = new DailyAdviceClient(); dac.go(); } public void go() { try { Socket incoming = new Socket("127.0.0.1",4242); InputStreamReader stream = new InputStreamReader(incoming.getInputStream()); BufferedReader reader = new BufferedReader(stream); String advice = reader.readLine(); reader.close(); System.out.println("Today's advice is "+advice); } catch(Exception e) { System.out.println("Client Side Error"); } } } ``` and here is the code for the server ``` package practice; import java.io.*; import java.net.*; public class DailyAdviceServer { public static void main(String args[]) { DailyAdviceServer das = new DailyAdviceServer(); das.go(); } public void go() { try { ServerSocket serversock = new ServerSocket(4242); while(true) { Socket outgoing = serversock.accept(); PrintWriter writer = new PrintWriter(outgoing.getOutputStream()); writer.println("Hello there"); writer.close(); } } catch(Exception e) { System.out.println("Server Side Problem"); } } } ```
2014/06/24
[ "https://Stackoverflow.com/questions/24389491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3760100/" ]
just change "127.0.0.1" on the client with the server's IP and make sure the port 4242 is open.
``` Socket incoming = new Socket("127.0.0.1",4242); ``` This is creating a socket listening to the server at the address `127.0.0.1` on port `4242`. If you change the server to another address, for example of a different pc, then change the ip address that your socket is listening to. It is also worth noting that you will probably have to open up or allow access to the ports you are using.
2,277,175
Since there aren no respositories for value objects. **How can I load all value objects?** Suppose we are modeling a blog application and we have this classes: * Post (Entity) * Comment (Value object) * Tag (Value object) * PostsRespository (Respository) I Know that when I save a new post, its tags are saved with it in the same table. But how could I load all tags of all posts. **Should PostsRespository have a method to load all tags?** I usually do it, but I want to know others opinions
2010/02/16
[ "https://Stackoverflow.com/questions/2277175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/187762/" ]
I am currently working through a similar example. Once you need to uniquely refer to tags they are no long simple value objects and may continue to grow in complexity. I decided to make them their own entities and create a separate repository to retrieve them. In most scenarios they are loaded or saved with the post but when they are required alone the other repository is used. I hope this helps. EDIT: In part thanks to this post I decided to restructure my application slightly. You are right that I probably was incorrectly making tags an entity. I have since changed my application so that tags are just strings and the post repository handles all the storage requirements around tags. For operations that need posts the tags are loaded with them. For any operation that just requires tags or lists of tags the repository has methods for that.
Here is my take in how I might solve this type of problem in the way that I'm currently practicing DDD. If you are editing something that requires tags to be added and removed from such as a Post then tags may be entities but perhaps they could be value objects and are loaded and saved along with the post either way. I personally tend to favor value objects unless the object needs to be modified but I do realize that there is a difference between entity object modeled as read only "snapshots" and actual value objects that lack identity. The tricky part is that perhaps sometimes what you would normally think of as a key could be part of a value object as long as it is not used as identity in that context and I think tags fall into this category. If you are editing the tags themselves then it is probably a separate bounded context or at least a separate aggregate in which tags are themselves are the aggregate root and persisted through a repository. Note that the entity class that represents tags in this context doesn't have to be the same entity class for tags used in Post aggregate. If your listing available tags on the display for read only purposes such as to provide a selection list, then that is probably a list of value objects. These value objects can but don't have to be in the Domain Model since they are mainly about supporting the UI and not about the actual domain. Please chime in if anybody has any thoughts on why my take on this might be wrong but this is the way I've been doing it.
41,384
Let me explain: I'm writing a game where the Earth gets a massive biological attack from an alien race in the close future, and only a small part of the planet's life survived (few dozens of humans and animals). The explanations for those events are discovered by the player during the game, and are: 1. The alien race is a [type III civilization](https://en.wikipedia.org/wiki/Kardashev_scale), and eliminates all the intelligent life in the universe that achieves [quantum supremacy](https://www.alphr.com/the-future/1008428/what-is-quantum-supremacy-the-future-of-quantum-computers-relies-on-it). 2. This happens because the only possible way to detect life that is several light years in distance is through [quantum disturbance events](https://newatlas.com/quantum-entanglement-speed-10000-faster-light/26587/) that are caused by quantum processors, and can be captured by the type III civilization on the other side of the universe instantly. 3. The biological attack is a viral/bacterial weapon, and the reason why there are a few survivors is because their bodies achieved [symbiosis](https://en.wikipedia.org/wiki/Symbiosis). The main goal is that the plot is the "solution" to the [Fermi paradox](https://en.wikipedia.org/wiki/Fermi_paradox). Humans do not find any aliens that are close because all the life in the universe is constantly wiped out by the first race that achieved type III, to protect its monopoly, and they detect a rising intelligent race when it innocently creates quantum computers. Avoiding plot holes and trying to explain everything to avoid being a "generic alien invasion" is the goal with all that sci-fi, and I think that I can't balance it correctly, because I want to hit a broader audience. [This question](https://writing.stackexchange.com/questions/33500/how-do-you-explain-the-details-of-something-technical-to-a-non-technical-audienc) relates a lot to my feeling, but the solution does not satisfies me. My main concern is with the explanation 2. I feel that I need to give the viewer the reason why "only today" the invasion happened and why, and I can't find a better excuse to that. It seems solid, but a bit narrow and forced in my opinion. I'm open to changing the plot as much as necessary. **EDIT** Thank you all for the answers. Every one of them contains important tips that I will consider when writing the game. So, just to summarize: 1. I will put the deep sci-fi concepts into some optional lore, giving the player the freedom to read if he/she wants to 2. Focus on the gameplay, fun, battle system; 3. Avoid over-explanations, as this may cause more plot holes 4. I will remove the "how" completely. A type III civ is godlike to us and have unimaginable tech, therefore multiple ways to detect life on earth. How they detect is not important.
2019/01/17
[ "https://writers.stackexchange.com/questions/41384", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/36152/" ]
As somebody that likes to play role playing games, I love it when the game gives me the **option** to read up on the lore. Some games do this very well, like the books you can read in the Elder Scrolls games. They're completely optional, so anybody that wants to read them can, but anyone that just wants to play the game can also do that. In case of a sci-fi game, you could for example have data pads (I'm sure I got this idea from some game, but not sure which anymore) which, when picked up, saves a log a player can then read anytime they want. This is a great way to provide more background information to those interested in it. You could then even have them in varying formats. For example one is a scientific report, while another is an entry in someone's personal diary.
Let me point out a different risk of providing a too detailed description of how the aliens learned about it: The risk of unnecessarily contradicting established science, and thus losing exactly those who would otherwise be most likely to enjoy detailed descriptions. In this particular case, it is clear to me (a physicist working in quantum physics) that your knowledge in this area is based basically on popular science articles (which, I regret, are often terribly misleading). If you just say they detect it through some quantum gravitational effect unknown to us, that's enough for me to keep suspension of disbelief (we don't have a successful theory of quantum gravity yet). Or some post-quantum effect. Or basically, anything we don't yet know. But if you try to explain it through entanglement, without invoking something we don't know yet, for me that breaks suspension of disbelief the same way it does if you claim in a Hard Science Fiction story that a Ford model T can go to space if you just select the right gear and then turn on the lights.
29,873,023
I run my code then I put in an integer, press enter, then I get an extra input space. In the extra input space I put in a number then I get the input space I want where it says "Write A Line". It only adds the numbers I put in the first input space and the extra input space. Please help. (P.S Sorry for code's format) My Output: Write An Integer (put my input here) (put my input here) Write An Integer (put my input here) I don't want that 2nd input option. ``` public static void main(String eth[]){ System.out.println("Write An Integer"); Scanner input = new Scanner(System.in); if (input.hasNextInt()){ } else System.out.println("Play By The Rules"); Scanner input1 = new Scanner(System.in); int a = input1.nextInt(); { System.out.println("Write An Integer"); Scanner input2 = new Scanner(System.in); int b = input2.nextInt(); int answer = (a+b); System.out.println(answer); } } } ```
2015/04/26
[ "https://Stackoverflow.com/questions/29873023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4833262/" ]
The extra space you're getting is from a logical error in first `if` statement. If `input.hasNextInt()` is true, then it will skip over `else` but call the `Scanner` directly below because it is not grouped with the `else` statement. Also, this only allows for two attempts for `input1` and one for `input2`. Therefore, I'd switch to a `while` loop for each and create a method to read in integers instead of duplicating code. ``` public static void main(String eth[]) { int a = readInt(); int b = readInt(); int answer = (a + b); System.out.println(answer); } private static int readInt() { System.out.println("Write An Integer"); Scanner input = null; while(!(input = new Scanner(System.in)).hasNextInt()){ System.out.println("Play By The Rules, Write An Integer"); } return input.nextInt(); } ```
> > Use single instance for > Scanner and make sure close the scanner input after operation > > > Refer code below > > > ``` public static void main(String eth[]) { System.out.println("Write An Integer"); Scanner input = new Scanner(System.in); if (input.hasNextInt()) { } else System.out.println("Play By The Rules"); int a = input.nextInt(); { System.out.println("Write An Integer"); int b = input.nextInt(); int answer = (a + b); System.out.println(answer); input.close(); } } ```
38,019,336
Question :- Write a program to take five numbers by user and search a number is found or not. My attempt :- ``` #include<stdio.h> #include<conio.h> void main () { int a=2,b;char directory[5];int i; printf("enter a number you want to find"); scanf("%d",&a); for(i=0;i<5;i++) { scanf("%d",&directory[i]); } if(a=directory[i]); printf("number is found"); else printf("number not found"); getch(); } ``` Description of the problem :- I already gave `int a = 2` and after entering 5 values including 2 as one of the input but the output is coming out to be number not found.. suggest me the changes or the part which i need to work on. Thank you! **EDIT 1:-** after doing the changes proposed in the answer the code looks like this but i am still not getting the correct output ``` #include<stdio.h> #include<conio.h> void main () { int a=2,b;char directory[5];int i; printf("enter a number you want to find"); scanf("%d",&a); for(i=0;i<5;i++) { scanf("%d",&directory[i]); if (a==directory[i]) { printf("number is found"); } else printf("number not found); } } getch(); } ```
2016/06/24
[ "https://Stackoverflow.com/questions/38019336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6510116/" ]
`%d` is expecting an `int` but `char directory[5]` is `char` values. This should be called as ``` int directory[5]; ``` Also you are only looking at the value of `i` which at the end of the for loop previously would be 5 in the array in the line: ``` if(a=directory[i]); ``` You should instead have a for loop saying: ``` for(i = 0; i < 5; i++) { if(a == directory[i]) { printf("number is found"); } else { printf("number not found"); } } ``` Two more things you should notice about my `if` are the `==` and the ending. Using a single `=` is an assignment which means a will now equal the value of `directory[i]` and check the boolean value if `a` is true (anything besides 0) or false (0). Writing it as `==` is what you want to check if they have the same value. At the end of your `if` you have a semi colon. That makes the `if` pointless. The block will stop at the end of it. **EDIT** In your new edit you are still using a `char` array instead of `int` ``` char directory[5]; ``` Should be: ``` int directory[5]; ``` I assume it was just a copy paste issue but you are missing the opening { in your else. Either take out the closing } or add the other. Also assuming a copy paste issue for this one but you are missing the closing " in the line: ``` printf("number not found); ```
And you didnt initialize .It's logic fault ``` int directory[5] ```
3,908
I've been offered one of my dream internships for this next summer. I'll be working as a "Program Manager" for a top notch software company. For some examples of what I mean by PM, take a look at [Joel's article](http://www.joelonsoftware.com/items/2009/03/09.html) as well as [Microsoft's PM internship description](http://careers.microsoft.com/careers/en/us/tech-software-internships.aspx#urswintern-3). This is my first internship in this position. Up until this point, I've been working as a developer. This is sort of a change of paths, but I feel like it's a great opportunity. I want to spend a lot of time preparing for this internship before I get there. My goal is to be a valuable member of the team as quickly as possible. Here's what I already have on my agenda: * Read [How to Win Friends and Influence People](http://rads.stackoverflow.com/amzn/click/0671723650) * Read [DRiVE](http://rads.stackoverflow.com/amzn/click/1594484805) * Read [Making Things Happen](http://rads.stackoverflow.com/amzn/click/0596517718) * Review development methods (Scrum, agile, etc.), focusing on the method that my team uses How else should I prepare to be the best Program Manager I can be?
2011/11/19
[ "https://pm.stackexchange.com/questions/3908", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/1448/" ]
I would add another item to your "reading list" and that is [Zapp! the Lightning of Empowerment](http://rads.stackoverflow.com/amzn/click/0449002829). In my opinion as, as a Program Manager your most powerful day to day tool will be in the form of written and verbal communication. You will be talking with customers, team members and other teams. Essentially you will be filling the communication gap that exists between them. Fill this gap and empower your team providing direction, suggestions & feedback. As this is an internship: * Don't be afraid to ask questions * Learn from mistakes made **and more importantly** take responsibility for your actions and decisions * Have fun and get to know your collegues
The PMI's [Practice Standard for Program Management](http://www.pmi.org/PMBOK-Guide-and-Standards/Standards-Library-of-PMI-Global-Standards.aspx) is a wealth of information on the general components of program management and the various moving pieces involved. Like all standards, it is not a methodology, but an inventory of possible elements in a program and a conceptual framework of how they all hang together.
10,117,334
I have problem with activation of graphical layout. I want to see what I have done in XML, but graphical layout doesn't show any thing. Also in res/layout, I right clicked on each XML files then went to "Open with/Legacy android drawable editor". Still nothing! How can I activate it? Thanks ![enter image description here](https://i.stack.imgur.com/FBNIA.png)
2012/04/12
[ "https://Stackoverflow.com/questions/10117334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/513413/" ]
CONTEXT: editable HTML of <https://code.google.com/apis/ajax/playground/?type=visualization#line_chart> (using Firefox or Chorme). Instructions for help you in the problem: * suppose you need a box with width=500px and height=400px. * check Javascript at new google.visualization.LineChart(), if the width and height inicializations are 500 and 400. * check if style of the HTML tag (perhaps div) of renderization place (id="visualization") is style="width: 800px; height: 400px;". * check if style of the HTML parent tag (any) of renderization place is bigger than 500 and 400, or is 100%. Another solution is by "HTML cut": use overflow:hidden. **EXAMPLE OF CASE WITH SCROLL** ```js // ... piece of your javacascript. new google.visualization.LineChart(document.getElementById('visualization')). draw(data, {curveType: "function", width: 800, height: 400, vAxis: {maxValue: 10}} ); } google.setOnLoadCallback(drawVisualization); ``` ```html <!-- ... piece of your HTML --> <div id="container" style="width:400px;overflow:scroll;"> <div id="visualization" style="width: 800px; height: 400px;"></div> </div> ``` **HTML SOLUTION (fix the container width)** ``` <!-- ... piece of your HTML --> <div id="container" style="width:800px;overflow:scroll;"> <div id="visualization" style="width: 800px; height: 400px;"></div> </div> ``` **ANOTHER SIMPLE HTML SOLUTION (use overflow:hidden)** ``` <!-- ... piece of your HTML --> <div id="container" style="width:400px;overflow:hidden;"> <div id="visualization" style="width: 800px; height: 400px;"></div> </div> ``` ... or reduce all, Javascript and HTML widths and heights, etc.
Using : ``` <script src="https://www.google.com/jsapi"></script> <script> google.load("visualization", "1", {packages:["corechart"]}); var data = new google.visualization.DataTable(); //init your data var options = { width: "100%", height: "100%", //other options } var chart = new google.visualization.LineChart(document.getElementById('chart')); chart.draw(data, options); </script> .... <body> <div id="chart"></div> </body> ``` You ensure that the graph will fit the div you're using. Then to resize the graph set `style="width: ...px; height: ...px;"` with the desired size : ``` <body> <div style="width: 800px; height: 400px;" id="chart"></div> </body> ```
11,063,054
I have created a wix installer project which is working fine. It installs my application on system easily. whenever if there is any change in any file or service, i uninstall msi from controk panel and installs new msi on system. But whenever i install new msi, application's all setting change after new installation, that doesn't sound good. For sort out this, i am using Upgrade code in Product.wxs file. But when i install new msi after build, but is shows given error: ``` Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel ``` So, i want to update windows application package whenever there is any change in files and with same Product id. I just want to update installed msi, dont want to remove that.
2012/06/16
[ "https://Stackoverflow.com/questions/11063054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298386/" ]
You cannot use the same ProductId to do upgrades, you need to change it. The best way is to set ProductId="\*" and this will change it for every build. You will also need to increase the version number and this best done by using the main exe assembly version number. See <http://wix.sourceforge.net/manual-wix3/major_upgrade.htm> for more info.
You can use the same `ProductCode` to update an installed MSI. Basically you increment the `ProductVersion`, rebuild the MSI (with new `PackageCode`) and do a minor update with a command line such as: ``` msiexec /i <path to new msi> REINSTALL=ALL REINSTALLMODE=vomus. ``` In my experience this not commonly used because if you're going to rebuild the MSI you may as well upgrade with a major upgrade. If all you want are updates to a few files and you're not ready to ship a complete MSI file, then that's what patches are for. Rebuild the MSI as above, then build a patch - the patch is the delta between the two MSI files, see docs for MsiMsp.exe.
5,142,842
How do I export a graph to an .eps format file? I typically export my graphs to a .pdf file (using the 'pdf' function), and it works quite well. However, now I have to export to .eps files.
2011/02/28
[ "https://Stackoverflow.com/questions/5142842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459179/" ]
The easiest way I've found to create postscripts is the following, using the `setEPS()` command: ``` setEPS() postscript("whatever.eps") plot(rnorm(100), main="Hey Some Data") dev.off() ```
Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to `setEPS()` ``` cairo_ps("image.eps") plot(1, 10) dev.off() ```
9,460,153
Can someone give me a good reason why ViewState isn't stored on the server by default? Why not send a small session token in place of ViewState, which can then be mapped to whatever ViewState info is needed on the server, to prevent the whole ViewState being posted back and forwards multiple times. Am I missing something?
2012/02/27
[ "https://Stackoverflow.com/questions/9460153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692456/" ]
Scalability - imagine how much server resources would be needed if a complex WebForms page was viewed by 1M users. Server would need to hold ViewState for at least the duration of the session timeout. Automatic server side cleanup of viewstate would also be problematic - user may be viewing several pages at once so ViewState for all pages would need to be retained. **Edit** There are several techniques discussed in [these posts](https://stackoverflow.com/search?tab=relevance&q=viewstate%20server) on how to move viewstate to the server. However, before you do that, it would be a good idea to remove unnecessary viewstate from controls / pages which don't need it (e.g. View only / no postback rendering). I'm guessing now, but when viewstate was designed 10 years or so ago, 1GB RAM on a 32 bit server was about as good as it got, and MS presumably had to think of hosting providers wanting load 100's of apps per server. So bandwidth was probably viewed as cheaper than server Ram and disk storage.
The root cause is using client side view state is that server doesn't know the current state of the page. If a user is anxious, does multiple (partial) postback on the page, without waiting the response, browser will send out multiple partial postback requests, that each request create a new view state on server side, which will eventually flush out the initial view state in the browser. Finally the user does his last postback, at that time, the inital copy is gone, thus exception is thrown. Also server side view state impacts server performance and user experience. If a user doesn't interact with the page for a day or a long time, the view state on server will expire. When the user posts back the page later, an exception is thrown. For instance I watch youtube video of length 40 minutes. Yesterday I watched the first half, didn't close the tab but hiberated my computer. Today I continue watchig the last half, and post back something, the page will get errored out if the view state is in server and expired.
7,810,288
I'm running all my apps to make sure it's not just one app, and in every app I have, when I run on the iOS5 simulator or device, the `viewWillAppear` method gets called twice on every view. I have a simple `NSLog(@"1");`, and this appears twice in my console every time. Is this just me, or is something going on? (It only gets called once in iOS4) This is the code calling the view that calls viewWillAppear twice: ``` CloseDoorViewController *closeVC; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { closeVC = [[ CloseDoorViewController alloc] initWithNibName:@"CloseDoorViewIpad" bundle:nil]; } else { closeVC = [[ CloseDoorViewController alloc] initWithNibName:@"CloseDoorViewController" bundle:nil]; } [self.view addSubview:closeVC.view]; [self presentModalViewController:closeVC animated:NO]; ```
2011/10/18
[ "https://Stackoverflow.com/questions/7810288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/458960/" ]
Because you are displaying the view twice. First time by adding the view as a subview of the current view: ``` [self.view addSubview:closeVC.view]; ``` Second time by pushing the view's controller on top of current view's controller: ``` [self presentModalViewController:closeVC animated:NO]; ``` I'm not sure why in iOS4 the `viewWillAppear` was only called once, because iOS5 is correct to call it twice, given that you are displaying the view twice as explained above. Just remove one of the lines and it would be fine (I'd recommend removing the `addSubview` and retain the `presentModalViewController` one).
If you want to restore the old (iOS 4) behavior in your view controller you should implement the following method: ``` - (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers { return NO; } ```
5,303,799
I have a table in Oracle that records events for a user. This user may have many events. From these events I am calculating a reputation with a formula. My question is, what is this best approach to do this in calculating and returning the data. Using a view and using SQL, doing it in code by grabbing all the events and calculating it (problem with this is when you have a list of users and need to calculate the reputation for all), or something else. Like to hear your thoughts. ``` Comments * (.1) + Blog Posts * (.3) + Blog Posts Ratings * (.1) + Followers * (.1) + Following * (.1) + Badges * (.2) + Connections * (.1) = 100% ``` One Example ``` Comments: This parameter is based on the average comments per post. • Max: 20 • Formula: AVE(#) / max * 100 = 100% • Example: 5 /10 * 100 = 50% ``` Max is that maximum number to get all that percentage. Hope that makes some sense. We are calculating visitation, so all unique visits / date of membership is another. The table contains an event name, some meta data, and it is tied to that user. Reputation just uses those events to formulate a reputation based on 100% as the highest. ``` 85% reputation - Joe AuthorUser been a member for 3 years. He has: • written 18 blog posts o 2 in the past month • commented an average of 115 times per month • 3,000 followers • following 2,000 people • received an average like rating of 325 per post • he's earned, over the past 3 years: o 100 level 1 badges o 50 level 2 badges • he's connected his: o FB account o Twitter account ```
2011/03/14
[ "https://Stackoverflow.com/questions/5303799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280602/" ]
I have a tool to "dump" an entire SQL Compact file as SQL script, that you can then run against a SQLite db - <http://exportsqlce.codeplex.com>
1. Export CSV file(s) from SQL CE, import into SQLite, or 2. Use ODBC to connect to both databases and move data from one to the other
4,009,505
I'm trying to get the following code to work, but I can't find good-enough documentation on how C++ handles public vs. private inheritance to allow me to do what I want. If someone could explain why I can't access `Parent::setSize(int)` or `Parent::size` using private inheritance or `Parent::size` using public inheritance. To solve this, to I need a `getSize()` and `setSize()` method in Parent? ``` class Parent { private: int size; public: void setSize(int s); }; void Parent::setSize(int s) { size = s; } class Child : private Parent { private: int c; public: void print(); }; void Child::print() { cout << size << endl; } int main() { Child child; child.setSize(4); child.print(); return 0; } ```
2010/10/24
[ "https://Stackoverflow.com/questions/4009505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267493/" ]
Change Parent to: ``` protected: int size; ``` If you want to access the `size` member from a derived class, but not from outside the class, then you want `protected`. Change Child to: ``` class Child: public Parent ``` When you say `class Child: private Parent`, you are saying it should be a secret that Child is a Parent. Your `main` code makes it clear that you want Child to be manipulated as a Parent, so it should be public inheritance.
When you use private inheritance, all public and protected members of the base class become private in the derived class. In your example, `setSize` becomes private in `Child`, so you can't call it from `main`. Also, `size` is already private in `Parent`. Once declared private, a member always remains private to the base class regardless of the type of inheritance.
3,931,351
I went through this before posting: *[How can I echo HTML in PHP?](https://stackoverflow.com/questions/1100354/easiest-way-to-echo-html-in-php)* And I still couldn't make it work. I'm trying to echo this: ``` <div> <h3><a href="#">First</a></h3> <div>Lorem ipsum dolor sit amet.</div> </div> <div> ``` But I still can't find a way to make the tags "" and '' disappear. What do I have to do?
2010/10/14
[ "https://Stackoverflow.com/questions/3931351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463065/" ]
Try the *heredoc*-based solution: ``` echo <<<HTML <div> <h3><a href="#">First</a></h3> <div>Lorem ipsum dolor sit amet.</div> </div> <div> HTML; ```
There isn't any need to use echo, sir. Just use the tag <plaintext>: ``` <plaintext> <div> <h3><a href="#">First</a></h3> <div>Lorem ipsum dolor sit amet.</div> </div> ```
328,649
I believe C is a good language to learn the principles behind programming. What do you stand to learn in lower level languages that are "magicked" away from high level ones, such as Ruby?
2016/08/17
[ "https://softwareengineering.stackexchange.com/questions/328649", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/242560/" ]
> > I know C is a good language to learn the principles behind programming. > > > I disagree. C is absent too many features to learn principles behind programming. C's features for creating abstractions are terrible, and abstraction is one of the key principles behind programming. If you want to learn how hardware works, and hence some mechanical sympathy for the machine, you should learn machine code, aka the instruction set architecture, and also study the cache construction of modern CPUs. Note that I am not recommending assembly language, just understand the hardware instructions, so you understand what a compiler generates. If you want to learn programming principles, use a modern language like Java, C#, or Swift, or one of the dozens of others like Rust. Also, study the different kinds of programming paradigms, including functional.
C and the (Abstract) Machine ============================ Most programming languages are described in terms of abstract machines. Then, [they are implemented using sets of tools like compilers, linkers, assemblers, interpreters, static analyzers, intermediate languages, and hardware](https://softwareengineering.stackexchange.com/a/300669/76809) that will collectively produce a result that honors at least all the expected behavior of the abstract machine, as observed by a program. C is not an exception to the above rule. It is described in terms of an abstract machine which has no notion of your actual hardware. As such, when people say that C teaches you how your computer actually works, what they usually mean is that C teaches you how C works. But C being so pervasive in systems programming, it's understandable that a lot of people start confusing it with the computer itself. And I would personally go as far as to say that knowing how C works is often more important than knowing how the computer itself works. But still, C and the computer *are* different things. Actual hardware is actually complicated -- in ways that make the C spec read like a children's book. If you're interested in how your hardware works, you can always look up a manual and start writing code in an assembler. Or you can always start learning about digital circuits so that you can design some hardware on your own. (At the very least, you will appreciate how high-level C is.) How *do* you learn? And how do *you* learn? =========================================== Okay, actually learning about hardware involves things other than C. But can C teach anything else to programmers today? I think it depends. * There are some who would say that you can better learn a concept **by working in an environment that offers it and encourages it, often in multiple ways.** * There are some who would say that you can better learn a concept **by working in an environment that doesn't offer it and where you instead have to build it yourself.** Don't be too quick to choose one of these possibilities. I've been writing code for many years and I still have no idea which one is the correct answer, or whether the correct answer is just one of the two, or whether there is such a thing as a correct answer on this issue. I'm slightly inclined to believe that you should probably eventually apply both options, loosely in the order I described them in. But I don't think this is really a technical matter, I think it's a mostly educational one. Every person seems to learn in significantly different ways. Exclusively in C ================ If you answered the above question by at least involving the second option I proposed, then you already have a few answers under your belt: anything that can be learned in higher-level languages can be better learned by re-inventing it in C or at least expanded by adding C to the mix. But, regardless of your answer, there are certainly a few things that you can learn almost exclusively from C (and perhaps a handful of other languages). * C is historically important. It is a milestone that you can look at and appreciate where we came from and maybe get a bit more context about where we're going. You can appreciate why certain limitations exist and you can appreciate that certain limitations have been lifted. * C can teach you to work in unsafe environments. In other words, it can train you to watch your back when the language (any language) can't or won't do it for you, for any reason. This can make you a better programmer even in safe environments because you'll produce fewer bugs on your own and because you will be able to turn off safety temporarily in order to squeeze some extra speed out of your otherwise safe program (e.g. use of pointers in C#), in those cases where safety comes with a runtime cost. * C can teach you that every object has storage requirements, a memory layout, the fact that memory can be accessed through a finite address space, and so on. While other languages don't need your attention on these matters, there are a few cases where some acquired intuition can help you make more informed decisions. * C can teach you about the details of linkage and object files and other intricacies through its build system. This can give you a useful hands-on understanding on how a natively compiled program often goes from source code to execution. * C can bend your mind to think in novel ways through the concept of undefined behavior. Undefined behavior is one of my favorite concepts in software development, because the study of its implications on non-classical compilers is a unique mental exercise that you can't quite get from other languages. However, you'll have to reject trial-and-error and start studying the language in a careful and deliberate way before you can fully appreciate this aspect. * But perhaps the most important realization that C can grant you, being a small language, is the idea that [all programming boils down to data and operations](https://en.wikipedia.org/wiki/Algorithms_%2B_Data_Structures_%3D_Programs). You might like to look at things as modular classes with hierarchies and interfaces with virtual dispatch, or elegant immutable values that are operated on using pure mathematical functions. And that's all fine -- but C will remind you that it's all just *data + operations*. It's a useful mindset because it allows you to bring down quite a few mental barriers.
1,430,987
I have looked this up on the net but I am asking this to make sure I haven't missed out on something. Is there a built-in function to convert HashSets to Lists in C#? I need to avoid duplicity of elements but I need to return a List.
2009/09/16
[ "https://Stackoverflow.com/questions/1430987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65488/" ]
Two equivalent options: ``` HashSet<string> stringSet = new HashSet<string> { "a", "b", "c" }; // LINQ's ToList extension method List<string> stringList1 = stringSet.ToList(); // Or just a constructor List<string> stringList2 = new List<string>(stringSet); ``` Personally I'd prefer calling `ToList` is it means you don't need to restate the type of the list. Contrary to my previous thoughts, both ways allow covariance to be easily expressed in C# 4: ``` HashSet<Banana> bananas = new HashSet<Banana>(); List<Fruit> fruit1 = bananas.ToList<Fruit>(); List<Fruit> fruit2 = new List<Fruit>(bananas); ```
There is the Linq extension method `ToList<T>()` which will do that (It is defined on `IEnumerable<T>` which is implemented by `HashSet<T>`). Just make sure you are `using System.Linq;` As you are obviously aware the `HashSet` will ensure you have no duplicates, and this function will allow you to return it as an `IList<T>`.
160,196
The mad scientist community is...mad, to put it kiddie-appropriately. Their logic has the tendency to make 0% sense 100% of the time (provided, of course, that they ever bring it up.) So you can imagine a field scientist's confusion when the community tasked him to imagine a hybrid between a wild bison (they never specified which species) and a wild aurochs through their bones alone because hybrids between wild bison and ***domesticated*** aurochs are so done before. The problem with that is that the scientist has observed only live bison and never once studied their skeletons, and he had never seen a live wild aurochs. (In fairness, ***NO ONE*** has seen a live wild aurochs for roughly three centuries.) In short, he couldn't tell the two species apart just by looking at their bones. In order to save his skin, he would need help from a higher power (that's us.) So, comprehensively speaking, just by looking at the bones alone, how would the field scientist differentiate a wild bison from a wild aurochs?
2019/11/06
[ "https://worldbuilding.stackexchange.com/questions/160196", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/10274/" ]
They are fairly easy to tell apart from just bones. --------------------------------------------------- From the bones there are several obvious differences. Well start from the most obvious and work down. the shape of the skull is an easy one and the first thing you look at in mammals. bison skulls are much wider/shorter proportionally and have smaller horns. Even a damaged skeleton will show this obvious difference. below we have an american bison skulls followed by an auroch skull. the difference holds true for european bison although the difference is smaller. [![enter image description here](https://i.stack.imgur.com/5ozHs.jpg)](https://i.stack.imgur.com/5ozHs.jpg) [![enter image description here](https://i.stack.imgur.com/CQCOC.jpg)](https://i.stack.imgur.com/CQCOC.jpg) Between the american bison and the auroch there is a big difference in the hump which is much larger in bison and has a much stronger down curve in the thoracic spine and the position of the neck is much lower, again this difference is less pronounced in european bison but still noticeable. This also gives aurochs a much more horizontal profile. General size can also be an indicator, american bison are bigger, but of course this only works if you are sure you have an adult. and the difference is almost nonexistent with european bison. If they only have a few bones this could easily lead to them being confused. Auroch tails are longer, not that you are likely to find all the tail bones. I am sure someone who specializes in pleistocene mammals can spot a few more differences. Skeleton of an auroch and bison. [![enter image description here](https://i.stack.imgur.com/AH6ZI.jpg)](https://i.stack.imgur.com/AH6ZI.jpg) [![enter image description here](https://i.stack.imgur.com/wRGjg.jpg)](https://i.stack.imgur.com/wRGjg.jpg) <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.534.6285>
The most obvious difference in the skeleton along the "hump". As you can see from L.Dutch's image the bison has a more pronounced hump over the shoulders. While that is primarily muscle, it has a skeletal structure that is significantly more pronounced in the bison than the aurochs.
18,263,097
I have asked a similar question earlier but I have narrowed it down and would like to start a new question. The following script inserts a To and From dates into a DB record. I want to add the option of skipping every other week. The following is very close however, it skips the first week which I don't want it to do. Is there a way that I can use the COUNT feature and only use the ODD number records from the Count and insert those? ``` $week_day = date('w', $curr); # 0 - 6 to access the $week array if ($week[$week_day]) { # skip if nothings in this day $date = date('Y-m-d', $curr); $sql->query("SELECT COUNT(schedule_id) FROM $pageDB WHERE doctor_id = $doc_id AND schedule_date = '$date'"); if (!$sql->result(0)) { # skip if this is already defined $date = date('Y-m-d', strtotime("+1 week", $curr)); $sql->query("INSERT INTO $pageDB (schedule_date, time, doctor_id, location_id) VALUES ('$date', '".$week[$week_day]."', $doc_id, '".$location[$week_day]."')"); } } ```
2013/08/15
[ "https://Stackoverflow.com/questions/18263097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2687614/" ]
Instead of putting all your options tags in the array, you can just put the numbers and use PHP to create the tags for you: ``` $miltimes = array('0000', '0030', '0100', '0130', '0200', '0230', '0300', '0330', '0400', '0430', '0500', '0530', '0600', '0630', '0700', '0730', '0800', '0830', '0900', '0930', '1000', '1030', '1100', '1130', '1200', '1230', '1300', '1330', '1400', '1430', '1500', '1530', '1600', '1630', '1700', '1730', '1800', '1830', '1900', '1930', '2000', '2030', '2100', '2130', '2200', '2230', '2300', '2330'); $select = '<select id="time_out_1" name="'.$data[$id]['time_out']."\">\n"; foreach ($miltimes as $key => $value){ $selected = ($value == '0030') ? ' selected' : ''; $select .= "\t<option value=\"$value\"$selected>$value</option>\n"; } $select .= "</select>\n"; echo $select; ```
If you are trying to set a time based on the values and if your time values are strings then ``` $matchtime = "1000"; $defaulttime = "0500" foreach($miltimes as $miltime) { $timematched = ($miltime == $matchtime) ? $miltime : $defaulttime; echo $timematched; } ``` Although it is better to have **only** time values in your array and to use a built-in function like [strtotime](http://php.net/manual/en/function.strtotime.php) when comparing time. That way you wont be making string comparisons.
157,888
Not [Git](https://en.wikipedia.org/wiki/Git), but [GitHub](https://en.wikipedia.org/wiki/GitHub)... single or multiple repositories, GitHub-style documentation, etc.
2012/12/07
[ "https://meta.stackexchange.com/questions/157888", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/116/" ]
Generally, Stack Overflow is fine, but as random pointed out in his comment, it depends what is being asked: <https://stackoverflow.com/questions/tagged/github> GitHub is certainly a tool commonly used by programmers, per the FAQ. I like to think one of the best ways to decide what to ask is to first observe what is being asked and answered well by the community. (This should also explain why things that are popular for the wrong reasons, that are opinion pieces rather than science, are deeply problematic at SE.) Since you specified > > suppose it's a question about github-style docs, or repository organization > > > That implies it could be opinion-y, or a bit too specific to GitHub's own peculiarities. Overall though GitHub is so *overwhelmingly* a programmer site that some opinion and/or specificity to GitHub is likely to be OK.
And it turns out the GitHub guys concur with Jeff! From [the announcement](https://groups.google.com/forum/?fromgroups=#!topic/github/TbbbBkAm-jk) where they shut down their Google Groups group: > > After three glorious years, we're shutting down this Google Group next > Monday, May 9th, 2011. > > > You can always contact Official GitHub Support by emailing > sup...@github.com or visiting <https://github.com/contact> > > > As for unofficial help, we recommend Stack Overflow: > <https://stackoverflow.com/questions/tagged/github> > > >
19,457,479
I am new to the site and I am having trouble with a scalable website I am creating. The problem appears when downsizing the screen to below 650px. For some reason the background for my menu is disappearing. I've gone over the code numerous times and cannot find my error. Please help! Here is the link to my page: <http://mnice.mydevryportfolio.com/portfolio/> Here is the Media CSS code that I have in place so far: ``` /************************************************************************************ smaller than 980 *************************************************************************************/ @media screen and (max-width: 980px) { /* pagewrap */ #pagewrap { width: 95%; } /* content */ #content { width: 60%; padding: 3% 4%; } /* sidebar */ #sidebar { width: 30%; } #sidebar .widget { padding: 8% 7%; margin-bottom: 10px; } /* embedded videos */ .video embed, .video object, .video iframe { width: 100%; height: auto; min-height: 300px; } } /************************************************************************************ smaller than 650 *************************************************************************************/ @media screen and (max-width: 650px) { /* header */ #header { height: auto; } /* search form */ #searchform { position: absolute; top: 5px; right: 0; z-index: 100; height: 40px; } #searchform #s { width: 70px; } #searchform #s:focus { width: 150px; } /* main nav */ #main-nav { position: static; } /* site logo */ #site-logo { margin: 15px 100px 5px 0; position: static; } /* site description */ #site-description { margin: 0 0 15px; position: static; } /* content */ #content { width: auto; float: none; margin: 100px 0; } /* sidebar */ #sidebar { width: 100%; margin: 0; float: none; } #sidebar .widget { padding: 3% 4%; margin: 0 0 10px; } /* embedded videos */ .video embed, .video object, .video iframe { min-height: 250px; } } /************************************************************************ smaller than 560 **************************************************************************/ @media screen and (max-width: 480px) { /* disable webkit text size adjust (for iPhone) */ html { -webkit-text-size-adjust: none; } /* main nav */ #main-nav a { font-size: 90%; padding: 10px 8px; } } ``` And then the main CSS Style Page: ``` /************************************************************************ RESET ****************************************************************************/ html, body, address, blockquote, div, dl, form, h1, h2, h3, h4, h5, h6, ol, p, pre, table, ul, dd, dt, li, tbody, td, tfoot, th, thead, tr, button, del, ins, map, object, a, abbr, acronym, b, bdo, big, br, cite, code, dfn, em, i, img, kbd, q, samp, small, span, strong, sub, sup, tt, var, legend, fieldset { margin: 0; padding: 0; } img, fieldset { border: 0; } /* set image max width to 100% */ img { max-width: 100%; height: auto; width: auto\9; /* ie8 */ } /* set html5 elements to block */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } /************************************************************************************ GENERAL STYLING *************************************************************************************/ body { background: url(images/background.png); font: .81em/150% Arial, Helvetica, sans-serif; color: #000; } a { color: #026acb; text-decoration: none; outline: none; } a:hover { text-decoration: underline; } p { margin: 0 0 1.2em; padding: 0; } /* list */ ul, ol { margin: 1em 0 1.4em 24px; padding: 0; line-height: 140%; } li { margin: 0 0 .5em 0; padding: 0; } /* headings */ h1, h2, h3, h4, h5, h6 { line-height: 1.4em; margin: 20px 0 .4em; color: #000; } h1 { font-size: 2em; } h2 { font-size: 1.6em; } h3 { font-size: 1.4em; } h4 { font-size: 1.2em; } h5 { font-size: 1.1em; } h6 { font-size: 1em; } /* reset webkit search input styles */ input[type=search] { -webkit-appearance: none; outline: none; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { display: none; } /************************************************************************************ STRUCTURE *************************************************************************************/ #pagewrap { width: 980px; margin: 0 auto; } /************************************************************************************ HEADER *************************************************************************************/ #header { position: relative; height: 180px; } /* site logo */ #site-logo { position: absolute; top: 0px; } #site-logo a { font: bold 30px/100% Arial, Helvetica, sans-serif; color: #fff; text-decoration: none; } /* site description */ #site-description { font: italic 100%/130% "Times New Roman", Times, serif; color: #fff; position: absolute; top: 95px; } /* searchform */ #searchform { position: absolute; right: 10px; bottom: 6px; z-index: 100; width: 160px; } #searchform #s { width: 140px; float: right; background: #fff; border: none; padding: 6px 10px; /* border radius */ -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; /* box shadow */ -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.2); -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,.2); box-shadow: inset 0 1px 2px rgba(0,0,0,.2); /* transition */ -webkit-transition: width .7s; -moz-transition: width .7s; transition: width .7s; } /************************************************************************************ MAIN NAVIGATION *************************************************************************************/ #main-nav { width: 100%; background: #ccc; margin: 0; padding: 0; position: absolute; left: 0; bottom: 0; z-index: 100; /* gradient */ background: #6a6a6a url(images/nav-bar-bg.png) repeat-x; background: -webkit-gradient(linear, left top, left bottom, from(#b9b9b9), to(#6a6a6a)); background: -moz-linear-gradient(top, #b9b9b9, #6a6a6a); background: linear-gradient(-90deg, #b9b9b9, #6a6a6a); /* rounded corner */ -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; /* box shadow */ -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.3), 0 1px 1px rgba(0,0,0,.4); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.3), 0 1px 1px rgba(0,0,0,.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.3), 0 1px 1px rgba(0,0,0,.4); } #main-nav li { margin: 0; padding: 0; list-style: none; float: left; position: relative; } #main-nav li:first-child { margin-left: 10px; } #main-nav a { line-height: 100%; font-weight: bold; color: #fff; display: block; padding: 14px 15px; text-decoration: none; text-shadow: 0 -1px 0 rgba(0,0,0,.5); } #main-nav a:hover { color: #fff; background: #474747; /* gradient */ background: -webkit-gradient(linear, left top, left bottom, from(#282828), to(#4f4f4f)); background: -moz-linear-gradient(top, #282828, #4f4f4f); background: linear-gradient(-90deg, #282828, #4f4f4f); } /************************************************************************************ CONTENT *************************************************************************************/ #content { background-image: url(images/containerbackground_blur.png); margin: 30px 0 30px; padding: 20px 35px; width: 700px; float: left; /* rounded corner */ -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; /* box shadow */ -webkit-box-shadow: 0 1px 3px rgba(0,0,0,.4); -moz-box-shadow: 0 1px 3px rgba(0,0,0,.4); box-shadow: 0 1px 3px rgba(0,0,0,.4); } /* post */ .post { margin-bottom: 40px; } .post-title { margin: 0 0 5px; padding: 0; font: bold 26px/120% Arial, Helvetica, sans-serif; } .post-title a { text-decoration: none; color: #000; } .post-meta { margin: 0 0 10px; font-size: 90%; } .main-image { margin: 0 0 15px; text-align: center; } /************************************************************************************ SIDEBAR *************************************************************************************/ #sidebar { width: 200px; float: right; margin: 30px 0 30px; } .widget { background: #fff; margin: 0 0 30px; padding: 10px 20px; /* rounded corner */ -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; /* box shadow */ -webkit-box-shadow: 0 1px 3px rgba(0,0,0,.4); -moz-box-shadow: 0 1px 3px rgba(0,0,0,.4); box-shadow: 0 1px 3px rgba(0,0,0,.4); } .widgettitle { margin: 0 0 5px; padding: 0; } .widget ul { margin: 0; padding: 0; } .widget li { margin: 0; padding: 6px 0; list-style: none; clear: both; border-top: solid 1px #eee; } /************************************************************************************ FOOTER *************************************************************************************/ #footer { clear: both; color: #ccc; font-size: 85%; } #footer a { color: #fff; } /************************************************************************************ CLEARFIX *************************************************************************************/ .clearfix:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; } .clearfix { display: inline-block; } .clearfix { display: block; zoom: 1; } ``` Any help would be appreciated!
2013/10/18
[ "https://Stackoverflow.com/questions/19457479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2079047/" ]
You changed the positioning context ``` @media screen and (max-width: 650px) #main-nav { position: static; } ``` If you remove `static` the bg color returns...then it's just a matter of tweaking the position values.
The problem is in your media queries which are responsible for changing the layout on different screen sizes: go ahead and add this: ``` @media screen and (max-width: 650px) #main-nav { bottom: inherit; } ```
18,654,386
Can any explain what this section of code does: `_num = (_num & ~(1L << 63));` I've have been reading up on RNGCryptoServiceProvider and came across <http://codethinktank.blogspot.co.uk/2013/04/cryptographically-secure-pseudo-random.html> with the code, I can follow most the code except for the section above. I understand it ensuring that all numbers are positive, but I do not know how its doing that. Full code ``` public static long GetInt64(bool allowNegativeValue = false) { using (RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider()) { byte[] _obj = new byte[8]; _rng.GetBytes(_obj); long _num = BitConverter.ToInt64(_obj, 0); if (!allowNegativeValue) { _num = (_num & ~(1L << 63)); } return _num; } } ``` Any help explaining it would be appreciated
2013/09/06
[ "https://Stackoverflow.com/questions/18654386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608448/" ]
This is purely the watch window that is showing you the `char byte` value and the actual `char string` vaule. So, from [ASCII Table](http://www.asciitable.com/) you can see that `48 is '0'` and `49 is '1'`
As per the C# Reference, each char from char array shows the Decimal value of it
10,348,778
I have a table that has the following columns ``` table: route columns: id, location, order_id ``` and it has values such as ``` id, location, order_id 1, London, 12 2, Amsterdam, 102 3, Berlin, 90 5, Paris, 19 ``` Is it possible to do a sql select statement in postgres that will return each row along with the id with the next highest order\_id? So I want something like... ``` id, location, order_id, next_id 1, London, 12, 5 2, Amsterdam, 102, NULL 3, Berlin, 90, 2 5, Paris, 19, 3 ``` Thanks
2012/04/27
[ "https://Stackoverflow.com/questions/10348778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610171/" ]
``` select id, location, order_id, lag(id) over (order by order_id desc) as next_id from your_table ```
Creating testbed first: ``` CREATE TABLE route (id int4, location varchar(20), order_id int4); INSERT INTO route VALUES (1,'London',12),(2,'Amsterdam',102), (3,'Berlin',90),(5,'Paris',19); ``` The query: ``` WITH ranked AS ( SELECT id,location,order_id,rank() OVER (ORDER BY order_id) FROM route) SELECT b.id, b.location, b.order_id, n.id FROM ranked b LEFT JOIN ranked n ON b.rank+1=n.rank ORDER BY b.id; ``` You can read more on the window functions in the [documentation](http://www.postgresql.org/docs/current/interactive/tutorial-window.html).
20,211,896
Is it possible to integrate JSHint into Jenkins without using the Checkstyle or JSLint reporter? The reason why I want to do this is because both reporters by default also show *non-errors*, which is not what I want (see also [JSHint shows non-errors for checkstyle reporter](https://stackoverflow.com/questions/20194681/jshint-shows-non-errors-for-checkstyle-reporter)). Is there a way to integrate JSHint directly?
2013/11/26
[ "https://Stackoverflow.com/questions/20211896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333873/" ]
I had similar problem last week, but I use grunt to run jshint. I simply override jshint options, here is example code: ``` jshint: { options: { jshintrc: '../config/.jshintrc', }, src1: [ 'file1.js', 'file2.js' ], src2: [ 'source/file3.js', 'source/file4.js' ], jenkins: { options: { jshintrc: '../config/.jshintrc', reporter: 'checkstyle', reporterOutput: 'jshint.xml', }, src: [ "<%= jshint.src1 %>", "<%= jshint.src2 %>" ] }, } ``` So when you want run jslint on jenkins you simply run: ``` grunt jshint:jenkins ``` and output is generated to .xml file. I hope this may help you.
I would like to point out that jsHint will now work with the Report Violations, but you must set the report type to `jslint-xml`. Here is a sample for the Ant task: ``` <jshint dir="${js.dir}"> options="${jshint.options}"> <include name="**/*.js"/> <exclude name="**/*.min.js"/> <report type="jslint-xml"/> </jshint> ``` Use the violations plugin for Jenkins, and put the name of your `_jsHint_ XML output in the space for`jslint`. And, it's actually documented in the `README.md` too. I missed it.