qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
17,487,872
I want to add lines to /etc/my.conf as "sudo" using Shell. Without logging as sudo, I can do: ``` { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` But when: ``` sudo { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` I get an error: ``` sudo: {: command not found character_set_server=utf8 [mysql] default-character-set=utf8 ..... ``` What am I doing wrong?
2013/07/05
[ "https://Stackoverflow.com/questions/17487872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185098/" ]
Firstly, use cat with a here-doc rather than a series of echoes. It's much cleaner. You can use the special form with a dash which strips leading tabs (tabs, not spaces!) to let you indent the here-doc to make it stand out. Secondly, you can do the redirection as sudo by using `sudo sh -c` to start a root subshell, in which you then run cat doing the redirection. Putting it together: ``` sudo sh -c "cat >>/etc/my.conf" <<-EOF [mysqld] default-character-set=utf8 character_set_server=utf8 [mysql] default-character-set=utf8 EOF ``` I don't know of a more direct way to write a stream to a file as root. It's a shame if there really isn't one.
To make everything easier you should place the commands in a script, and let sudo execute that script.
17,487,872
I want to add lines to /etc/my.conf as "sudo" using Shell. Without logging as sudo, I can do: ``` { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` But when: ``` sudo { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` I get an error: ``` sudo: {: command not found character_set_server=utf8 [mysql] default-character-set=utf8 ..... ``` What am I doing wrong?
2013/07/05
[ "https://Stackoverflow.com/questions/17487872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185098/" ]
An alternative to launching a new shell is to use the `tee` command: ``` { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } | sudo tee -a /etc/my.conf > /dev/null ``` or ``` sudo tee -a /etc/my.conf >/dev/null <<-EOF [mysqld] default-character-set=utf8 character_set_server=utf8 [mysql] default-character-set=utf8 EOF ```
To make everything easier you should place the commands in a script, and let sudo execute that script.
17,487,872
I want to add lines to /etc/my.conf as "sudo" using Shell. Without logging as sudo, I can do: ``` { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` But when: ``` sudo { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } >> /etc/my.conf ``` I get an error: ``` sudo: {: command not found character_set_server=utf8 [mysql] default-character-set=utf8 ..... ``` What am I doing wrong?
2013/07/05
[ "https://Stackoverflow.com/questions/17487872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185098/" ]
Firstly, use cat with a here-doc rather than a series of echoes. It's much cleaner. You can use the special form with a dash which strips leading tabs (tabs, not spaces!) to let you indent the here-doc to make it stand out. Secondly, you can do the redirection as sudo by using `sudo sh -c` to start a root subshell, in which you then run cat doing the redirection. Putting it together: ``` sudo sh -c "cat >>/etc/my.conf" <<-EOF [mysqld] default-character-set=utf8 character_set_server=utf8 [mysql] default-character-set=utf8 EOF ``` I don't know of a more direct way to write a stream to a file as root. It's a shame if there really isn't one.
An alternative to launching a new shell is to use the `tee` command: ``` { echo "[mysqld]" echo "default-character-set=utf8" echo "character_set_server=utf8" echo "[mysql]" echo "default-character-set=utf8" } | sudo tee -a /etc/my.conf > /dev/null ``` or ``` sudo tee -a /etc/my.conf >/dev/null <<-EOF [mysqld] default-character-set=utf8 character_set_server=utf8 [mysql] default-character-set=utf8 EOF ```
69,248,698
Hi today I installed java 17 and eclipse(with latest version- 2021‑09). But after all configuration it is showing JavaSE-16 as jdk version. I ignored it and started writing a program with sealed classes. Then it is showing an error. I managed to solve the problem by installing the Java-17 support plugin from eclipse marketplace. Is it possible in eclipse without installing anything.
2021/09/20
[ "https://Stackoverflow.com/questions/69248698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16436946/" ]
The release notes state this: > > Supports Java 17, including Pattern Matching for Switch (Preview), > Sealed Classes, and more **via Eclipse Marketplace** > > > That means currently you have to install the plugin, later support will be included. You might also want to read this: <https://www.eclipse.org/eclipse/news/4.21/jdt.php>
Install java 17 plugin from [this](https://marketplace.eclipse.org/content/java-17-support-eclipse-2021-09-421) link. Then your likely to have a [content assist error](https://stackoverflow.com/questions/69357171/eclipse-2021-09-code-completion-not-showing-all-methods-and-classes). Fix it by [this](https://stackoverflow.com/a/69381206/17022570) answer.
69,248,698
Hi today I installed java 17 and eclipse(with latest version- 2021‑09). But after all configuration it is showing JavaSE-16 as jdk version. I ignored it and started writing a program with sealed classes. Then it is showing an error. I managed to solve the problem by installing the Java-17 support plugin from eclipse marketplace. Is it possible in eclipse without installing anything.
2021/09/20
[ "https://Stackoverflow.com/questions/69248698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16436946/" ]
The release notes state this: > > Supports Java 17, including Pattern Matching for Switch (Preview), > Sealed Classes, and more **via Eclipse Marketplace** > > > That means currently you have to install the plugin, later support will be included. You might also want to read this: <https://www.eclipse.org/eclipse/news/4.21/jdt.php>
The support should be official with Eclipse 4.22 (Q4 2021) > > [Java 17](https://www.eclipse.org/eclipse/news/4.22/jdt.php#Java_17) > -------------------------------------------------------------------- > > > Java 17 is out and Eclipse JDT supports Java 17 in 4.22. > > > The release notably includes the following Java 17 features: > > > * [JEP 306](https://openjdk.java.net/jeps/306): Restore Always-Strict Floating-Point Semantics. > * [JEP 406](https://openjdk.java.net/jeps/406): Pattern Matching for switch (Preview). > * [JEP 409](https://openjdk.java.net/jeps/409): Sealed Classes (Final). > > > Please note that preview option should be on for preview language features. >For an informal introduction of the support, please refer to J\*\*[ava 17 Examples wiki](https://wiki.eclipse.org/Java17/Examples)\*\*. > > >
69,248,698
Hi today I installed java 17 and eclipse(with latest version- 2021‑09). But after all configuration it is showing JavaSE-16 as jdk version. I ignored it and started writing a program with sealed classes. Then it is showing an error. I managed to solve the problem by installing the Java-17 support plugin from eclipse marketplace. Is it possible in eclipse without installing anything.
2021/09/20
[ "https://Stackoverflow.com/questions/69248698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16436946/" ]
Install java 17 plugin from [this](https://marketplace.eclipse.org/content/java-17-support-eclipse-2021-09-421) link. Then your likely to have a [content assist error](https://stackoverflow.com/questions/69357171/eclipse-2021-09-code-completion-not-showing-all-methods-and-classes). Fix it by [this](https://stackoverflow.com/a/69381206/17022570) answer.
The support should be official with Eclipse 4.22 (Q4 2021) > > [Java 17](https://www.eclipse.org/eclipse/news/4.22/jdt.php#Java_17) > -------------------------------------------------------------------- > > > Java 17 is out and Eclipse JDT supports Java 17 in 4.22. > > > The release notably includes the following Java 17 features: > > > * [JEP 306](https://openjdk.java.net/jeps/306): Restore Always-Strict Floating-Point Semantics. > * [JEP 406](https://openjdk.java.net/jeps/406): Pattern Matching for switch (Preview). > * [JEP 409](https://openjdk.java.net/jeps/409): Sealed Classes (Final). > > > Please note that preview option should be on for preview language features. >For an informal introduction of the support, please refer to J\*\*[ava 17 Examples wiki](https://wiki.eclipse.org/Java17/Examples)\*\*. > > >
13,063,717
I am trying to write some C++ code in the momentics IDE with the project type as 'C++ Cascades Application'. To my surprise there's no Intellisense support. Does anyone know how to enable intellisense with C++?
2012/10/25
[ "https://Stackoverflow.com/questions/13063717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71292/" ]
You always need to optimize the *bottleneck* of your application. In a game, the speed of the engine is critical to the performance of the application. Hence, optimization makes sense there. In a line-of-business application, which spends X ms waiting for the execution of a database query, and Y << X ms drawing the user interface and executing actual "business code", optimizing Y does *not* make sense. Since X is the critical factor here, it's the *database engines* that are usually written in C, C++ or some other "high performance" language.
In short points: C or C++ gives you the posibility to work with many more details at a lower level so you can get performance and memory gains from where you can, and that is really required cause a game requires pretty high performance requirements for drawing and redrawing things continuosly. However such details are not generally required in bussines line apps because first of all they dont do as many "operations" that require intensive work so that allows use for managed code even though that gives you certain penalties they are not very observable cause the physical workload is lower. So the point is use the right tool for the right job. You dont use a scooter to do agriculture and you dont need a tractor to deliver pizza.
13,063,717
I am trying to write some C++ code in the momentics IDE with the project type as 'C++ Cascades Application'. To my surprise there's no Intellisense support. Does anyone know how to enable intellisense with C++?
2012/10/25
[ "https://Stackoverflow.com/questions/13063717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71292/" ]
It's not primarily about the language, it's the platform. In .Net you can't use SSE, your ability to use the GPU is limited; some lock-free multithreaded algorithms can only really be implemented as originally intended (versioned pointers) in native code (and if multithreading is important, an efficient lock-free structure can provide great speed improvements); memory management is automatic in .Net whereas in high-performance scenarios you can gain a great speed benefit by micro-managing memory (separate mini-heaps for different object types), and you can vector through memory - which also links back to SSE where frequently you will have multiple pointers vectoring through large buffers, feeding values into SSE operations. To name just a few. These things are things that Business apps typically don't concern themselves with because if performance is really crucial at this level then it's likely to be a server it's running on ~(desktop apps are unlikely - even in trading scenarios it's likely to be the server that needs to be real-time), and a business who needs that performance will just chuck a faster machine at it; or a blade centre. In a retail game environment it has to work on lots of different configurations of hardware, and so it makes sense to try and squeeze every last drop of performance out of whatever hardware the user is running. I guess that more answers why C++ is used to code most games, rather than why .Net is ubiquitous in business - the lack of need of such performance potential is a factor, of course, as is I think the shorter development life cycle (generally speaking). However there are more factors. In some ways, though, it's like comparing apples to cows. You select the tech that best fits the problem.
In short points: C or C++ gives you the posibility to work with many more details at a lower level so you can get performance and memory gains from where you can, and that is really required cause a game requires pretty high performance requirements for drawing and redrawing things continuosly. However such details are not generally required in bussines line apps because first of all they dont do as many "operations" that require intensive work so that allows use for managed code even though that gives you certain penalties they are not very observable cause the physical workload is lower. So the point is use the right tool for the right job. You dont use a scooter to do agriculture and you dont need a tractor to deliver pizza.
13,063,717
I am trying to write some C++ code in the momentics IDE with the project type as 'C++ Cascades Application'. To my surprise there's no Intellisense support. Does anyone know how to enable intellisense with C++?
2012/10/25
[ "https://Stackoverflow.com/questions/13063717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71292/" ]
It's not primarily about the language, it's the platform. In .Net you can't use SSE, your ability to use the GPU is limited; some lock-free multithreaded algorithms can only really be implemented as originally intended (versioned pointers) in native code (and if multithreading is important, an efficient lock-free structure can provide great speed improvements); memory management is automatic in .Net whereas in high-performance scenarios you can gain a great speed benefit by micro-managing memory (separate mini-heaps for different object types), and you can vector through memory - which also links back to SSE where frequently you will have multiple pointers vectoring through large buffers, feeding values into SSE operations. To name just a few. These things are things that Business apps typically don't concern themselves with because if performance is really crucial at this level then it's likely to be a server it's running on ~(desktop apps are unlikely - even in trading scenarios it's likely to be the server that needs to be real-time), and a business who needs that performance will just chuck a faster machine at it; or a blade centre. In a retail game environment it has to work on lots of different configurations of hardware, and so it makes sense to try and squeeze every last drop of performance out of whatever hardware the user is running. I guess that more answers why C++ is used to code most games, rather than why .Net is ubiquitous in business - the lack of need of such performance potential is a factor, of course, as is I think the shorter development life cycle (generally speaking). However there are more factors. In some ways, though, it's like comparing apples to cows. You select the tech that best fits the problem.
You always need to optimize the *bottleneck* of your application. In a game, the speed of the engine is critical to the performance of the application. Hence, optimization makes sense there. In a line-of-business application, which spends X ms waiting for the execution of a database query, and Y << X ms drawing the user interface and executing actual "business code", optimizing Y does *not* make sense. Since X is the critical factor here, it's the *database engines* that are usually written in C, C++ or some other "high performance" language.
67,604,427
I've created App Clip for my application , but i can't auto sign it , i am getting 2 errors : > > Automatic signing failedXcode failed to provision this target. Please > file a bug report at <https://feedbackassistant.apple.com> and include > the Update Signing report from the Report navigator. > > > Provisioning profile "iOS Team Provisioning Profile: x.x.x.clip" > doesn't match the entitlements file's value for the > com.apple.developer.parent-application-identifiers entitlement. > > > When i create new app with new appclip its working fine , but when i try it on my current app its not working same issue again and again , I've tried almost every solution in the community same issue . I've posted my question here after i've spent days trying to fix this issue. ``` xCode : Version 12.5 (12E262) MacNook pro : 2020 macOS Big Sur 11.2.3 ```
2021/05/19
[ "https://Stackoverflow.com/questions/67604427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3059001/" ]
There are two values that need to match up. First, locate the provisioning profile Xcode is using for your App Clip (they're in `~/Library/MobileDevice/Provisioning Profiles`) and inspect it by highlighting the file and pressing space. The parent ID value in there: [![enter image description here](https://i.stack.imgur.com/AqaKu.png)](https://i.stack.imgur.com/AqaKu.png) ..has to match the same field in your `.entitlements` file in your App Clip target in Xcode. If it doesn't you can just edit the entitlement manually.
Pietro is correct. I would just add that when the error mentions the bundle identifier (from the app or the app clip), they mean the FULL bundle identifier (TeamID + bundle id). The Team ID prefix looks like `ABC123DEF456` and the bundle identifier like `com.example.app`. This means you must make sure that when you head for [developer.apple.com](https://developer.apple.com), you must make sure that you create the App ID for the app clip **with the same TeamID prefix as the parent app**! This way, the full bundle identifier should look like this: * for the app: `ABC123DEF456.com.example.app` * for the app clip: `ABC123DEF456.com.example.app.clip`. A good way to check that is to go in the Finder to `~/Library/MobileDevice/Provisioning Profiles`, find the provisioning profile for the app clip and quicklook it to check that.
46,516,752
I'm trying to use jQuery / jQuery UI in an Angular 4 app generated by Microsoft's SpaTemplate/JavaScript Services (dontnet new angular). This is not using Angular-CLI, and there is no angular-cli.json file. I've searched for this already, found a few hits on SO for projects generated with the CLI which I can't seem to make work with my project. I've installed jQuery and jQuery-UI via NPM (jQuery was there already, but I uninstalled and reinstalled it per another SO post answer). This puts them both in the node\_modules folder, as well as listing them in the webpack.config.vendor.js, package.json, and package-lock.json files. webpack.config.vendor.js: ``` entry: { vendor: [ '@angular/animations', '@angular/common', '@angular/compiler', '@angular/core', '@angular/forms', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', 'jquery', 'jquery-ui', 'bootstrap', 'bootstrap/dist/css/bootstrap.css', 'es6-shim', 'es6-promise', 'event-source-polyfill', 'zone.js', ] }, ``` package.json ``` "dependencies": { "jquery": "^3.2.1", "jquery-ui": "^1.12.1", //others removed to keep this short ``` }, package-lock.json (dependencies section) ``` "jquery": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/jquery/-/jquery-3.2.1.tgz", "integrity": "sha1-XE2d5lKvbNCncBVKYxu6ErAVx4c=" }, "jquery-ui": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/jquery-ui/-/jquery-ui-1.12.1.tgz", "integrity": "sha1-vLQEXI3QU5wTS8FIjN0+dop6nlE=" }, ``` Now, where I'm lost is just how to use them in the component TS files. I know jQuery is working because this template uses Bootstrap and the hamburger nav works on mobile just fine. Bootstrap is using jQuery to make the drop down animation. Other posts have said to add this to the component TS file: ``` declare var $:any; ``` Doing just that results in an error when I try to do $('#myElement').datepicker() in the ngOnInit section of the component: > > > ``` > vendor.js?v=HQi6Yanr6lb0tcDpEWxOLi8IMea49FFYgwADBy-xMjk:31 ERROR Error: Uncaught (in promise): ReferenceError: $ is not defined > ReferenceError: $ is not defined > > ``` > > Another SO post said to do this instead of the declar: ``` import * as $ from 'jQuery'; ``` Which then gives me a different error due to it not knowing about jQuery-UI: > > [ts] Property 'datepicker' does not exist on type > 'JQuery'. > > > Lastly another answer said this (for Angular2): ``` import $ from 'jquery'; import 'jqueryui'; ``` However, the jquery import doesn't work because it says jquery has no default export. And I also had to change jqueryui to jquery-ui. Either way, that doesn't work either. What am I missing? I seem to be finding conflicting answers out there, and they are all related to an app generated with Angular-CLI which I didn't have the luxury of using. Thanks for any help.
2017/10/01
[ "https://Stackoverflow.com/questions/46516752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/721429/" ]
``` CREATE TABLE IF NOT EXISTName ``` You are missing a space between the keyword `EXIST` and the table name `Name`.
You can simply add the block of code in a try-catch block and then put debug point on it and determine the exception and correct it. e.g ``` try { //block of code in which you have an error or you want to debug } catch(e: Exception) { // you can use log for seeing error or you can simply view errors by //putting debug point and pressing alt+mouse_left_click after executing //line to get value of exception instance } ```
16,070
I have purchased a high quality ZS6BKW from the U.K. I have it suspended up about 40' between 2 trees. There is 30' of coax from the ladder line to the radio (Kenwood TS-870).SWR on the MFJ269 shows below 1.5 from 80m all the way up to 10m. SWR on the radio shows below 1.5 too. However, I cannot hear anything on any band. Nothing whatsoever. On 40m I get some voice VERY faint on 7.070.00 and 7.095.00. As far as I have read on google I can use any length of coax from the ladder line (which is a specific length) to the radio. Any ideas?
2020/02/07
[ "https://ham.stackexchange.com/questions/16070", "https://ham.stackexchange.com", "https://ham.stackexchange.com/users/5784/" ]
I have a homemade ZS6BKW antenna so I might be able to provide some insight, even though I've only used it for a few weeks now. I get good reception on 40m and 20m with it (when conditions are favorable), and have not spent much time on the other bands. No tuner except for the built-in one on the IC-7300. With it in a less-than-ideal inverted V formation, and with my QTH laying between mountains in Colorado, USA, I've still reached Antarctica and Australia on WSPR, and around North America on FT8 and SSB. The first thing that makes me think something is wrong is that you're seeing a 1.5:1 SWR on 80m. The ZS6BKW is not an 80m antenna without a tuner. Mine shows 5.5:1, and the "standard" design should be north of 4:1 unless you've got some relay-controlled stuff going on. I think you're seeing some kind of fake resonance (akin to a dummy load), unless perhaps your feedline is resonant which is also not good. You also should see very, very high (> 5:1) SWR on 60, 30, and 15m. If you're seeing low SWR on those bands, I guarantee you something is wrong with the antenna or your feedline. I would recommend picking up a NanoVNA and adapters or some other antenna analyzer. You should see clear dips below 3:1 for 40, 20, 17, and 12m, with part of 10 and 6m bands covered, and a slight dip for 80m that would require a tuner. If you do see the proper dips in SWR, and you've tested your feedline, then I would try doing something like WSPR and see who reports you on the other bands, or trying to reach a friend at an agreed upon time and frequency, or tune in to a nearby WebSDR to listen for yourself. If it helps, here is what the NanoVNA shows as SWR for my ZS6BKW antenna, as measured at the feedpoint, when I was in the process of trimming it (it was a little long here for 20m). Notice the 80m dip on the far left edge of the chart is about 6:1 (each horizontal line is about 1 SWR with the bottom edge being 1:1). [![ZS6BKW NanoVNA](https://i.stack.imgur.com/modWg.jpg)](https://i.stack.imgur.com/modWg.jpg) **Edit:** I missed from your question that the MFJ-269 is an antenna analyzer, I assumed it was some kind of inline SWR meter in the shack. I would confirm with it that you have high SWR at the feedpoint on 80/60/30/15, and that you do not have a short (low-Z). I think it might be possible that a short at the end of the ladder line where it meets the dipole legs might result in a false low SWR reading, but someone with more experience with antenna modeling might be able to confirm or deny that.
I was going to suggest your coax might be too short as the package my ZS6BKW suggests over 70 ft etc (Might be even more) Glad u got it fixed. I am new to this antenna and still sorting SWR on various bands. Seems like 7300 internal tuner not sufficient for tuning some of the higher SWR bands like 15.
27,900,458
I've this method to read the database: class BDUtilities ``` private Context context; private BDHelper bd; private SQLiteDatabase db_reader; private SQLiteDatabase db_writer; public BDUtilities(Context context){ this.context = context; this.bd = new BDHelper(context); this.db_reader = bd.getReadableDatabase(); this.db_writer = bd.getWritableDatabase(); } public ArrayList<Boolean> getPreferences() { ArrayList<Boolean> resultados = new ArrayList<Boolean>(); if (checkBeforeUse()) { try { int user_id = getUserId(); Cursor c = db_reader.rawQuery("select cb_save_login, cb_save_pic_after_share," + "cb_upload_anonym, cb_init_cat_pref, user_id from prefs where user_id = ?", new String[] { String.valueOf(user_id) }); if (c.getCount() > 0){ c.moveToFirst(); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_login")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_pic_after_share")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_upload_anonym")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_init_cat_pref")))); c.close(); } else { c.close(); } } finally { //both error //bd.close(); //db_reader.close(); //error: //01-12 06:05:36.370: E/AndroidRuntime(1681): java.lang.IllegalStateException: //attempt to re-open an already-closed object: SQLiteDatabase: //data/data/com.example.photopt/databases/projeto_ddm.db } } return resultados; } ``` I've tried to close **db\_reader** that has **bd\_reader = database.getReadableDatabase();** but has error. This code: This doesn't return error but after some uses it shows this: > > 01-12 05:51:29.647: W/SQLiteConnectionPool(1762): A SQLiteConnection > object for database > '/data/data/com.example.photopt/databases/projeto\_ddm.db' was leaked! > Please fix your application to end transactions in progress properly > and to close the database when it is no longer needed. > > >
2015/01/12
[ "https://Stackoverflow.com/questions/27900458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2940812/" ]
you are not closing `db_writer` Regardless of not using it, you still open it at the intialisation. ``` this.db_writer = bd.getWritableDatabase(); ``` It is recommended to close it also, else the connection is leaked. ``` this.db_writer.close(); ``` Better yet would be to write a helper method that you can call: ``` public void CloseDb() { if(db_writer.isOpen()) db_writer.close(); if(db_reader.isOpen()) db_reader.close(); } ``` You can then call `CloseDb()` where appropriate (still need to close cursors as per normal). This method checks its open before closing, so does not try to close it twice. You do not normally close a `Databasehelper` from within itself though. Usually once you have finished using it in an from an `activity`. (Call `CloseDb()` from your activity once you have finished, aka, `onPause` or `onDestroy`.)
Try this.... ``` if (c.getCount() > 0){ c.moveToFirst(); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_login")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_pic_after_share")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_upload_anonym")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_init_cat_pref")))); c.close(); bd.close(); } else { c.close(); bd.close(); } ```
27,900,458
I've this method to read the database: class BDUtilities ``` private Context context; private BDHelper bd; private SQLiteDatabase db_reader; private SQLiteDatabase db_writer; public BDUtilities(Context context){ this.context = context; this.bd = new BDHelper(context); this.db_reader = bd.getReadableDatabase(); this.db_writer = bd.getWritableDatabase(); } public ArrayList<Boolean> getPreferences() { ArrayList<Boolean> resultados = new ArrayList<Boolean>(); if (checkBeforeUse()) { try { int user_id = getUserId(); Cursor c = db_reader.rawQuery("select cb_save_login, cb_save_pic_after_share," + "cb_upload_anonym, cb_init_cat_pref, user_id from prefs where user_id = ?", new String[] { String.valueOf(user_id) }); if (c.getCount() > 0){ c.moveToFirst(); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_login")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_save_pic_after_share")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_upload_anonym")))); resultados.add(parse(c.getString(c.getColumnIndex("cb_init_cat_pref")))); c.close(); } else { c.close(); } } finally { //both error //bd.close(); //db_reader.close(); //error: //01-12 06:05:36.370: E/AndroidRuntime(1681): java.lang.IllegalStateException: //attempt to re-open an already-closed object: SQLiteDatabase: //data/data/com.example.photopt/databases/projeto_ddm.db } } return resultados; } ``` I've tried to close **db\_reader** that has **bd\_reader = database.getReadableDatabase();** but has error. This code: This doesn't return error but after some uses it shows this: > > 01-12 05:51:29.647: W/SQLiteConnectionPool(1762): A SQLiteConnection > object for database > '/data/data/com.example.photopt/databases/projeto\_ddm.db' was leaked! > Please fix your application to end transactions in progress properly > and to close the database when it is no longer needed. > > >
2015/01/12
[ "https://Stackoverflow.com/questions/27900458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2940812/" ]
you are not closing `db_writer` Regardless of not using it, you still open it at the intialisation. ``` this.db_writer = bd.getWritableDatabase(); ``` It is recommended to close it also, else the connection is leaked. ``` this.db_writer.close(); ``` Better yet would be to write a helper method that you can call: ``` public void CloseDb() { if(db_writer.isOpen()) db_writer.close(); if(db_reader.isOpen()) db_reader.close(); } ``` You can then call `CloseDb()` where appropriate (still need to close cursors as per normal). This method checks its open before closing, so does not try to close it twice. You do not normally close a `Databasehelper` from within itself though. Usually once you have finished using it in an from an `activity`. (Call `CloseDb()` from your activity once you have finished, aka, `onPause` or `onDestroy`.)
this code stops the leak and fixes cursor problems. ``` public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper sInstance; private static final String DATABASE_NAME = "database_name"; private static final String DATABASE_TABLE = "table_name"; private static final int DATABASE_VERSION = 1; public static DatabaseHelper getInstance(Context context) { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. if (sInstance == null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } /** * Constructor should be private to prevent direct instantiation. * make call to static factory method "getInstance()" instead. */ private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } } ```
76,586
I am new to multiplayer mode in GOW3 . I am limited to a choice of two simple weapons. I have noticed I have to shoot a lot in order to injure an opponent but a lot of them can take me down with a single shot. Can I keep weapons that I pick up in multiplayer games for later matches? Thanks.
2012/07/12
[ "https://gaming.stackexchange.com/questions/76586", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/9633/" ]
This game is not like CoD in that you are always limited to the first five starting weapons (Lancer, Retro Lancer, Sawed-Off, Gnasher, Hammerburst). From the multiplayer options menu, you can rotate your primary and secondary weapons between these. However, you will never be able to start with weapons other than these. During multiplayer matches, one useful strategy is to learn where better weapons are in each map and try to get them (e.g., if you like using the Longshot, know where it is on each map). You also mentioned that you have to shoot a lot to kill but go down easily. This may be due to a few factors. One is that they may have better accuracy then you and are getting headshots. This game has been out since September, so don't be suprised that people are ridiculously accurate. Another issue is the perfect active reload. Your opponents may be emptying clips at the beginning of the match to get to perfect active reload for quicker kills. To perfect active reload, while reloading, press the right bumper button while the moving line is within the white line. This will have varying affects on your weapons (e.i., some will gain damage, lose spread, or increase fire rate). This is a necessary skill in order to survive in multiplayer.
Hint - The X Button is the use / interact button for picking up weapons/ammo, Screen shot below:) ![Hold X to pick up and switch weapons](https://i.stack.imgur.com/HyhaF.jpg) Heres a list of all the changes in the Gears of War 3 weapons since beta: Heres a list of ALL the weapons on Gears of War 3: <http://www.ign.com/wikis/gears-of-war-3/Weapons> Heres the controls for Gears of War 3 for XBOX Live; it shows the button to switch weapons and pick up weapons :) <http://gearsofwar.wikia.com/wiki/Controls> To change starting weapons, Watch this video which shows step by step how to customize both starting weapons and skins:
46,286,118
``` data <- data.frame(foo = c(0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), bar = c(1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0)) ``` Hi, Here I am having a data frame with two columns foo and bar. I want to create a new column Complete, based on foo and bar data. * If foo and bar is zero then complete should be 0. * If foo is one and bar is 0 then complete should be one. * If bar is 1 and foo is 0 then complete should be two. For example. ``` foo bar complete 0 0 0 1 0 1 0 1 2 ``` **Edit:** If `foo==1` and `bar==1` then `NA`.
2017/09/18
[ "https://Stackoverflow.com/questions/46286118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628070/" ]
You can create a named vector (`vect` in this example) and lookup values from that vector using `match` ``` vect = c("0 0" = 0, "1 0" = 1, "0 1" = 2) unname(vect[match(with(data, paste(foo, bar)), names(vect))]) # [1] 2 1 0 0 NA 0 2 0 1 NA 1 ```
There's a lot of ways to do this, some more efficient depending on how many conditions you have. But a basic way is: ``` data$New_Column <- with(data,ifelse(foo == 0 & bar == 0, 0, ifelse(foo == 1 & bar == 0, 1, ifelse(foo == 0 & bar == 1, 2, NA)))) # foo bar New_Column #1 0 1 2 #2 1 0 1 #3 0 0 0 #4 0 0 0 #5 1 1 NA #6 0 0 0 #7 0 1 2 #8 0 0 0 #9 1 0 1 #10 1 1 NA #11 1 0 1 ```
46,286,118
``` data <- data.frame(foo = c(0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), bar = c(1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0)) ``` Hi, Here I am having a data frame with two columns foo and bar. I want to create a new column Complete, based on foo and bar data. * If foo and bar is zero then complete should be 0. * If foo is one and bar is 0 then complete should be one. * If bar is 1 and foo is 0 then complete should be two. For example. ``` foo bar complete 0 0 0 1 0 1 0 1 2 ``` **Edit:** If `foo==1` and `bar==1` then `NA`.
2017/09/18
[ "https://Stackoverflow.com/questions/46286118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628070/" ]
Following suit, using `NA` when both columns are 1. Start with the row sums. If any of them are 2 (the number of columns), replace it with `NA`. Then multiply that by the `max.col()` value. ``` rs <- rowSums(data) cbind(data, complete = max.col(data) * replace(rs, rs == 2, NA)) # foo bar complete # 1 0 1 2 # 2 1 0 1 # 3 0 0 0 # 4 0 0 0 # 5 1 1 NA # 6 0 0 0 # 7 0 1 2 # 8 0 0 0 # 9 1 0 1 # 10 1 1 NA # 11 1 0 1 ``` If you don't wish to assign new objects, you can use a local environment or wrap it up into a function: ``` local({ rs <- rowSums(data) max.col(data) * replace(rs, rs == 2, NA) }) # [1] 2 1 0 0 NA 0 2 0 1 NA 1 ```
You can create a named vector (`vect` in this example) and lookup values from that vector using `match` ``` vect = c("0 0" = 0, "1 0" = 1, "0 1" = 2) unname(vect[match(with(data, paste(foo, bar)), names(vect))]) # [1] 2 1 0 0 NA 0 2 0 1 NA 1 ```
46,286,118
``` data <- data.frame(foo = c(0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), bar = c(1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0)) ``` Hi, Here I am having a data frame with two columns foo and bar. I want to create a new column Complete, based on foo and bar data. * If foo and bar is zero then complete should be 0. * If foo is one and bar is 0 then complete should be one. * If bar is 1 and foo is 0 then complete should be two. For example. ``` foo bar complete 0 0 0 1 0 1 0 1 2 ``` **Edit:** If `foo==1` and `bar==1` then `NA`.
2017/09/18
[ "https://Stackoverflow.com/questions/46286118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628070/" ]
If an algebraic approach is sought, we can try one of the lines below: ``` with(data, 2L * bar + foo + 0L * NA^(bar & foo)) with(data, 2L * bar + foo + NA^(bar & foo) - 1L) with(data, (2L * bar + foo) * NA^(bar & foo)) ``` All return > > > ``` > [1] 2 1 0 0 NA 0 2 0 1 NA 1 > > ``` > > ### Explanation The expression `2L * bar + foo` is treating `bar` and `foo` as digits of a binary number. The difficulty is to return `NA` in case of `foo == 1 & bar == 1`. For that, `bar` and `foo` are treated as logical values. If both are `1`, i.e., `TRUE` then `NA^(bar & foo)` returns `NA`, otherwise `1`. If one operand of an expression is `NA` so is the overall expression. So, there are several possibilities to combine `NA^(bar & foo)` with `2L * bar + foo`. I wonder which is the fastest. ### Benchmark So far, 7 different approaches have been posted by * [d.b](https://stackoverflow.com/a/46286220/3817004) * [Balter](https://stackoverflow.com/a/46286229/3817004) * [PoGibas](https://stackoverflow.com/a/46286275/3817004) * [Rich Scriven](https://stackoverflow.com/a/46286394/3817004) * Frank (in chat) * [user 20650 in a comment](https://stackoverflow.com/questions/46286118/creating-a-new-column-based-on-two-old-columns-in-a-data-frame/46293443#comment79543464_46286118) * [Uwe](https://stackoverflow.com/a/46293443/3817004) The OP has supplied his sample data as type `double`. As I have seen remarkable different timings for `integer` and `double` values on other occasions, the benchmark runs will be repeated for each type to investigate the impact of data type on the different approaches. ### *Benchmark data* The benchmark data will consist of 1 million rows: ``` n_row <- 1e6L set.seed(1234L) data_int <- data.frame(foo = sample(0:1, n_row, replace = TRUE), bar = sample(0:1, n_row, replace = TRUE)) with(data_int, table(foo, bar)) ``` > > > ``` > bar > foo 0 1 > 0 249978 250330 > 1 249892 249800 > > ``` > > ``` data_dbl <- data.frame(foo = as.double(data_int$foo), bar = as.double(data_int$bar)) ``` ### *Benchmark code* For benchmarking, the `microbenchmark` package is used. ``` # define check function to compare results check <- function(values) { all(sapply(values[-1], function(x) all.equal(values[[1]], x))) } library(dplyr) data <- data_dbl microbenchmark::microbenchmark( d.b = { vect = c("0 0" = 0, "1 0" = 1, "0 1" = 2) unname(vect[match(with(data, paste(foo, bar)), names(vect))]) }, Balter = with(data,ifelse(foo == 0 & bar == 0, 0, ifelse(foo == 1 & bar == 0, 1, ifelse(foo == 0 & bar == 1, 2, NA)))), PoGibas = with(data, case_when(foo == 0 & bar == 0 ~ 0, foo == 1 & bar == 0 ~ 1, foo == 0 & bar == 1 ~ 2)), Rich = local({rs = rowSums(data); max.col(data) * replace(rs, rs == 2, NA)}), Frank = with(data, ifelse(xor(foo, bar), max.col(data), 0*NA^foo)), user20650 = with(data, c(0, 1, 2, NA)[c(2*bar + foo + 1)]), uwe1i = with(data, 2L * bar + foo + 0L * NA^(bar & foo)), uwe1d = with(data, 2 * bar + foo + 0 * NA^(bar & foo)), uwe2i = with(data, 2L * bar + foo + NA^(bar & foo) - 1L), uwe2d = with(data, 2 * bar + foo + NA^(bar & foo) - 1), uwe3i = with(data, (2L * bar + foo) * NA^(bar & foo)), uwe3d = with(data, (2 * bar + foo) * NA^(bar & foo)), times = 11L, check = check) ``` Note that only the result vector is created *without* creating a new column in `data`. The approach of PoGibas was modified accordingly. As mentioned above, there might be speed differences in using `integer` or `double` values. Therefore, I wanted to test also the effect of using integer constant, e.g., `0L, 1L`, versus double constants `0, 1`. ### *Benchmark results* First, for input data of type `double`: > > > ``` > Unit: milliseconds > expr min lq mean median uq max neval cld > d.b 1687.05063 1700.52197 1707.72896 1706.48511 1715.46814 1730.62160 11 e > Balter 287.89649 377.42284 412.59764 452.75668 458.21178 472.92971 11 d > PoGibas 152.90900 154.82164 176.09522 158.23214 165.73524 333.48223 11 c > Rich 67.43862 68.68331 76.42759 77.10620 82.42179 89.90016 11 b > Frank 170.78293 174.66258 192.85203 179.69422 184.55237 333.74578 11 c > user20650 20.11790 20.29744 22.32541 20.81453 21.11509 34.45654 11 a > uwe1i 24.86296 25.13935 28.38634 25.60604 28.79395 45.53514 11 a > uwe1d 24.90034 25.05439 28.62943 25.41460 29.47379 41.08459 11 a > uwe2i 25.21222 25.59754 30.15579 26.29135 33.00361 47.13382 11 a > uwe2d 24.38305 25.09385 29.46715 25.41951 29.11112 45.05486 11 a > uwe3i 23.27334 23.95714 27.12474 24.28073 25.86336 44.40467 11 a > uwe3d 23.23332 23.65073 27.60330 23.96620 29.53911 40.41175 11 a > > ``` > > Now, for input data of type `integer`: > > > ``` > Unit: milliseconds > expr min lq mean median uq max neval cld > d.b 591.71859 596.31904 607.51452 601.24232 617.13886 636.51405 11 e > Balter 284.08896 297.06170 374.42691 303.14888 465.27859 488.19606 11 d > PoGibas 151.75851 155.28304 174.31369 159.18364 163.50864 329.00412 11 c > Rich 67.79770 71.22311 78.38562 77.46642 84.56777 96.55540 11 b > Frank 166.60802 170.34078 192.19833 180.09257 182.43584 350.86681 11 c > user20650 19.79204 20.06220 21.95963 20.18624 20.42393 30.13135 11 a > uwe1i 27.54680 27.83169 32.36917 28.08939 37.82286 45.21722 11 ab > uwe1d 22.60162 22.89350 25.94329 23.10419 23.74173 47.39435 11 a > uwe2i 27.05104 27.57607 27.80843 27.68122 28.02048 28.88193 11 a > uwe2d 22.83384 22.93522 23.22148 23.12231 23.41210 24.18633 11 a > uwe3i 25.17371 26.44427 29.34889 26.68290 27.08276 47.71379 11 a > uwe3d 21.68712 21.83060 26.16276 22.37659 28.40750 43.33989 11 a > > ``` > > For both `integer` and `double` input values, the approach by *user20650* is the fastest. Next are my algebraic approaches. Third is `Rich`s solution but three times slower than the second. The type of input data has the strongest impact on `d.b`'s solution and to a lesser extent on *Balter*'s. The other solutions seem to be rather invariant. Interestingly, there seems to be no remarkable difference from using `integer` or `double` constants in my algebraic solutions.
You can create a named vector (`vect` in this example) and lookup values from that vector using `match` ``` vect = c("0 0" = 0, "1 0" = 1, "0 1" = 2) unname(vect[match(with(data, paste(foo, bar)), names(vect))]) # [1] 2 1 0 0 NA 0 2 0 1 NA 1 ```
46,286,118
``` data <- data.frame(foo = c(0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), bar = c(1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0)) ``` Hi, Here I am having a data frame with two columns foo and bar. I want to create a new column Complete, based on foo and bar data. * If foo and bar is zero then complete should be 0. * If foo is one and bar is 0 then complete should be one. * If bar is 1 and foo is 0 then complete should be two. For example. ``` foo bar complete 0 0 0 1 0 1 0 1 2 ``` **Edit:** If `foo==1` and `bar==1` then `NA`.
2017/09/18
[ "https://Stackoverflow.com/questions/46286118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628070/" ]
Following suit, using `NA` when both columns are 1. Start with the row sums. If any of them are 2 (the number of columns), replace it with `NA`. Then multiply that by the `max.col()` value. ``` rs <- rowSums(data) cbind(data, complete = max.col(data) * replace(rs, rs == 2, NA)) # foo bar complete # 1 0 1 2 # 2 1 0 1 # 3 0 0 0 # 4 0 0 0 # 5 1 1 NA # 6 0 0 0 # 7 0 1 2 # 8 0 0 0 # 9 1 0 1 # 10 1 1 NA # 11 1 0 1 ``` If you don't wish to assign new objects, you can use a local environment or wrap it up into a function: ``` local({ rs <- rowSums(data) max.col(data) * replace(rs, rs == 2, NA) }) # [1] 2 1 0 0 NA 0 2 0 1 NA 1 ```
There's a lot of ways to do this, some more efficient depending on how many conditions you have. But a basic way is: ``` data$New_Column <- with(data,ifelse(foo == 0 & bar == 0, 0, ifelse(foo == 1 & bar == 0, 1, ifelse(foo == 0 & bar == 1, 2, NA)))) # foo bar New_Column #1 0 1 2 #2 1 0 1 #3 0 0 0 #4 0 0 0 #5 1 1 NA #6 0 0 0 #7 0 1 2 #8 0 0 0 #9 1 0 1 #10 1 1 NA #11 1 0 1 ```
46,286,118
``` data <- data.frame(foo = c(0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1), bar = c(1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0)) ``` Hi, Here I am having a data frame with two columns foo and bar. I want to create a new column Complete, based on foo and bar data. * If foo and bar is zero then complete should be 0. * If foo is one and bar is 0 then complete should be one. * If bar is 1 and foo is 0 then complete should be two. For example. ``` foo bar complete 0 0 0 1 0 1 0 1 2 ``` **Edit:** If `foo==1` and `bar==1` then `NA`.
2017/09/18
[ "https://Stackoverflow.com/questions/46286118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8628070/" ]
If an algebraic approach is sought, we can try one of the lines below: ``` with(data, 2L * bar + foo + 0L * NA^(bar & foo)) with(data, 2L * bar + foo + NA^(bar & foo) - 1L) with(data, (2L * bar + foo) * NA^(bar & foo)) ``` All return > > > ``` > [1] 2 1 0 0 NA 0 2 0 1 NA 1 > > ``` > > ### Explanation The expression `2L * bar + foo` is treating `bar` and `foo` as digits of a binary number. The difficulty is to return `NA` in case of `foo == 1 & bar == 1`. For that, `bar` and `foo` are treated as logical values. If both are `1`, i.e., `TRUE` then `NA^(bar & foo)` returns `NA`, otherwise `1`. If one operand of an expression is `NA` so is the overall expression. So, there are several possibilities to combine `NA^(bar & foo)` with `2L * bar + foo`. I wonder which is the fastest. ### Benchmark So far, 7 different approaches have been posted by * [d.b](https://stackoverflow.com/a/46286220/3817004) * [Balter](https://stackoverflow.com/a/46286229/3817004) * [PoGibas](https://stackoverflow.com/a/46286275/3817004) * [Rich Scriven](https://stackoverflow.com/a/46286394/3817004) * Frank (in chat) * [user 20650 in a comment](https://stackoverflow.com/questions/46286118/creating-a-new-column-based-on-two-old-columns-in-a-data-frame/46293443#comment79543464_46286118) * [Uwe](https://stackoverflow.com/a/46293443/3817004) The OP has supplied his sample data as type `double`. As I have seen remarkable different timings for `integer` and `double` values on other occasions, the benchmark runs will be repeated for each type to investigate the impact of data type on the different approaches. ### *Benchmark data* The benchmark data will consist of 1 million rows: ``` n_row <- 1e6L set.seed(1234L) data_int <- data.frame(foo = sample(0:1, n_row, replace = TRUE), bar = sample(0:1, n_row, replace = TRUE)) with(data_int, table(foo, bar)) ``` > > > ``` > bar > foo 0 1 > 0 249978 250330 > 1 249892 249800 > > ``` > > ``` data_dbl <- data.frame(foo = as.double(data_int$foo), bar = as.double(data_int$bar)) ``` ### *Benchmark code* For benchmarking, the `microbenchmark` package is used. ``` # define check function to compare results check <- function(values) { all(sapply(values[-1], function(x) all.equal(values[[1]], x))) } library(dplyr) data <- data_dbl microbenchmark::microbenchmark( d.b = { vect = c("0 0" = 0, "1 0" = 1, "0 1" = 2) unname(vect[match(with(data, paste(foo, bar)), names(vect))]) }, Balter = with(data,ifelse(foo == 0 & bar == 0, 0, ifelse(foo == 1 & bar == 0, 1, ifelse(foo == 0 & bar == 1, 2, NA)))), PoGibas = with(data, case_when(foo == 0 & bar == 0 ~ 0, foo == 1 & bar == 0 ~ 1, foo == 0 & bar == 1 ~ 2)), Rich = local({rs = rowSums(data); max.col(data) * replace(rs, rs == 2, NA)}), Frank = with(data, ifelse(xor(foo, bar), max.col(data), 0*NA^foo)), user20650 = with(data, c(0, 1, 2, NA)[c(2*bar + foo + 1)]), uwe1i = with(data, 2L * bar + foo + 0L * NA^(bar & foo)), uwe1d = with(data, 2 * bar + foo + 0 * NA^(bar & foo)), uwe2i = with(data, 2L * bar + foo + NA^(bar & foo) - 1L), uwe2d = with(data, 2 * bar + foo + NA^(bar & foo) - 1), uwe3i = with(data, (2L * bar + foo) * NA^(bar & foo)), uwe3d = with(data, (2 * bar + foo) * NA^(bar & foo)), times = 11L, check = check) ``` Note that only the result vector is created *without* creating a new column in `data`. The approach of PoGibas was modified accordingly. As mentioned above, there might be speed differences in using `integer` or `double` values. Therefore, I wanted to test also the effect of using integer constant, e.g., `0L, 1L`, versus double constants `0, 1`. ### *Benchmark results* First, for input data of type `double`: > > > ``` > Unit: milliseconds > expr min lq mean median uq max neval cld > d.b 1687.05063 1700.52197 1707.72896 1706.48511 1715.46814 1730.62160 11 e > Balter 287.89649 377.42284 412.59764 452.75668 458.21178 472.92971 11 d > PoGibas 152.90900 154.82164 176.09522 158.23214 165.73524 333.48223 11 c > Rich 67.43862 68.68331 76.42759 77.10620 82.42179 89.90016 11 b > Frank 170.78293 174.66258 192.85203 179.69422 184.55237 333.74578 11 c > user20650 20.11790 20.29744 22.32541 20.81453 21.11509 34.45654 11 a > uwe1i 24.86296 25.13935 28.38634 25.60604 28.79395 45.53514 11 a > uwe1d 24.90034 25.05439 28.62943 25.41460 29.47379 41.08459 11 a > uwe2i 25.21222 25.59754 30.15579 26.29135 33.00361 47.13382 11 a > uwe2d 24.38305 25.09385 29.46715 25.41951 29.11112 45.05486 11 a > uwe3i 23.27334 23.95714 27.12474 24.28073 25.86336 44.40467 11 a > uwe3d 23.23332 23.65073 27.60330 23.96620 29.53911 40.41175 11 a > > ``` > > Now, for input data of type `integer`: > > > ``` > Unit: milliseconds > expr min lq mean median uq max neval cld > d.b 591.71859 596.31904 607.51452 601.24232 617.13886 636.51405 11 e > Balter 284.08896 297.06170 374.42691 303.14888 465.27859 488.19606 11 d > PoGibas 151.75851 155.28304 174.31369 159.18364 163.50864 329.00412 11 c > Rich 67.79770 71.22311 78.38562 77.46642 84.56777 96.55540 11 b > Frank 166.60802 170.34078 192.19833 180.09257 182.43584 350.86681 11 c > user20650 19.79204 20.06220 21.95963 20.18624 20.42393 30.13135 11 a > uwe1i 27.54680 27.83169 32.36917 28.08939 37.82286 45.21722 11 ab > uwe1d 22.60162 22.89350 25.94329 23.10419 23.74173 47.39435 11 a > uwe2i 27.05104 27.57607 27.80843 27.68122 28.02048 28.88193 11 a > uwe2d 22.83384 22.93522 23.22148 23.12231 23.41210 24.18633 11 a > uwe3i 25.17371 26.44427 29.34889 26.68290 27.08276 47.71379 11 a > uwe3d 21.68712 21.83060 26.16276 22.37659 28.40750 43.33989 11 a > > ``` > > For both `integer` and `double` input values, the approach by *user20650* is the fastest. Next are my algebraic approaches. Third is `Rich`s solution but three times slower than the second. The type of input data has the strongest impact on `d.b`'s solution and to a lesser extent on *Balter*'s. The other solutions seem to be rather invariant. Interestingly, there seems to be no remarkable difference from using `integer` or `double` constants in my algebraic solutions.
There's a lot of ways to do this, some more efficient depending on how many conditions you have. But a basic way is: ``` data$New_Column <- with(data,ifelse(foo == 0 & bar == 0, 0, ifelse(foo == 1 & bar == 0, 1, ifelse(foo == 0 & bar == 1, 2, NA)))) # foo bar New_Column #1 0 1 2 #2 1 0 1 #3 0 0 0 #4 0 0 0 #5 1 1 NA #6 0 0 0 #7 0 1 2 #8 0 0 0 #9 1 0 1 #10 1 1 NA #11 1 0 1 ```
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~15~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ========================================================================================================================================== ``` Au…b #âŽ7×bûÏ ``` -2 bytes thanks to *@maxb*. [Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//0F14oCmYiAjw6LFvTfDl2LDu8OP//8) Outputs as a list, where the single-char notes are with a trailing space. **Explanation:** ```python Au # Push the lowercase alphabet, and uppercase it …b # # Push string "b #" â # Take the cartesian product of both strings to create all possible pairs: # ["Ab","A ","A#","Bb","B ","B#",...,"Zb","Z ","Z#"] Ž7× # Push compressed integer 1999 b # Convert it to a binary string "11111001111" û # Palindromize it to "111110011111110011111" Ï # Only leave the notes in the list at the truthy values (1), (the trailing # items beyond the length of this binary string are also discarded) # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž7×` is `1999`. `Ž7×` could alternatively be `₄·<` (1000, double, decrease by 1) for the same byte-count.
[Canvas](https://github.com/dzaima/Canvas), 23 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ======================================================================================================================= ``` Z7m{#+¹¹b+]{“╷!↕„2┬²@?P ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNBJXVGRjE3JXVGRjREJXVGRjVCJTIzJXVGRjBCJUI5JUI5YiV1RkYwQiV1RkYzRCV1RkY1QiV1MjAxQyV1MjU3NyUyMSV1MjE5NSV1MjAxRSV1RkYxMiV1MjUyQyVCMiV1RkYyMCV1RkYxRiV1RkYzMA__,v=8) [22 bytes](https://dzaima.github.io/Canvas/?u=JXUyNTc3JTIxJXUyMTk1JXUyMDFFJXVGRjNBJXVGRjE3JXVGRjREJXVGRjVCJTIzJXVGRjBCJUI5JUI5YiV1RkYwQiV1RkYzRCV1RkY1QiV1RkYxQiV1RkYxMiV1RkY0RSV1MjUxNCV1RkYwQSV1RkYzMA__,v=8) with extra newlines in the output
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[Jelly](https://github.com/DennisMitchell/jelly), 18?\* 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ========================================================================================================================== ``` ØAḣ7µp⁾b#Żs6ḣ€4ẎḊ;W€ ``` A monadic Link returning a list of lists of characters. \* If a mixed list of (a) lists of characters and (b) characters is acceptable remove the trailing `W€` for 18. **[Try it online!](https://tio.run/##y0rNyan8///wDMeHOxabH9pa8KhxX5Ly0d3FZkD@o6Y1Jg939T3c0WUdDmT/P7QoCyito/AfAA "Jelly – Try It Online")** ### How? ``` ØAḣ7µp⁾b#Żs6ḣ€4ẎḊ;W€ - Link: no argument ØA - list of characters [A-Z] ḣ7 - head to 7 "ABCDEFG" µ - new monadic link (call that X) ⁾b# - list of characters "b#" p - Cartesian product ["Ab","A#","Bb","B#","Cb","C#","Db","D#","Eb","E#","Fb","F#","Gb","G#"] Ż - prepend a zero [0,"Ab","A#","Bb","B#","Cb","C#","Db","D#","Eb","E#","Fb","F#","Gb","G#"] s6 - split into sixes [[0,"Ab","A#","Bb","B#","Cb"],["C#","Db","D#","Eb","E#","Fb"],["F#","Gb","G#"]] ḣ€4 - head each to 4 [[0,"Ab","A#","Bb"],["C#","Db","D#","Eb"],["F#","Gb","G#"]] Ẏ - tighten [0,"Ab","A#","Bb","C#","Db","D#","Eb","F#","Gb","G#"] Ḋ - dequeue ["Ab","A#","Bb","C#","Db","D#","Eb","F#","Gb","G#"] W€ - wrap each (of X) ["A","B","C","D","E","F","G"] ; - concatenate ["Ab","A#","Bb","C#","Db","D#","Eb","F#","Gb","G#","A","B","C","D","E","F","G"] ```
Brainfuck, 214 Bytes ==================== ``` >>>>++++++++[<++++<++++<++++++++++++<++++++++>>>>-]<<+++<++<+.>.>>.<<<.>>>.<<<.>>.>.<<<+.>.>>.<<<.>>>.<<<+.>>>.<<<.>>.>.<<<+.>.>>.<<<.>>>.<<<.>>.>.<<<+.>.>>.<<<.>>>.<<<+.>>>.<<<.>>.>.<<<+.>.>>.<<<.>>>.<<<.>>.>.<<<+ ``` [Try it Online!](https://tio.run/##SypKzMxLK03O/v/fDgi0oSDaBkQiCBiAc0CKdWNtbCBiNtp6dnp2dno2NjZACkbrgRmYUtpEqKGa9v//AQ)
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[Brachylog](https://github.com/JCumin/Brachylog), 36 bytes ========================================================== ``` "#b"ẹ,Ẹ↺;Ṇh₇ᵗ↔{∋ᵐc}ᶠ⟨h₅ct₁₄⟩⟨h₁₂ct₅⟩ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X0k5Senhrp06D3fteNS2y/rhzraMR03tD7dOf9Q2pfpRR/fDrROSax9uW/Bo/gqgRGtyyaOmxkdNLY/mr4SIADlNIMFWoMj///@jAA "Brachylog – Try It Online") I'm currently in the process of brute-forcing the powerset index that would let me get rid of `⟨h₅ct₁₄⟩⟨h₁₂ct₅⟩` (and by extension `↺`, since the output doesn't need to be in the same order as the example output), but it's taking quite a while... maybe I should put a minute aside to actually work out what order sublists are generated in, and compute the index that way...
[Perl 5](https://www.perl.org/), ~~47~~ 41 bytes ================================================ ```perl say for'AbA#DbD#GbG#BbEbC#F#'=~/../g,A..G ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhLb9I3THJUdklyUXZPcld2SnJNclZ2U1Z3bZOX09PP13HUU/P/f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[R](https://www.r-project.org/), 50 bytes ========================================= ```r cat("Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G#") ``` [Try it online!](https://tio.run/##BcHBDcAgDATBXrhPkLYJg8F14HSA0r8zc6ve8z3NEsPESAaTKTxxXKxksdkikiDUetUP "R – Try It Online") Boring answer. [R](https://www.r-project.org/), 60 bytes ========================================= ```r cat(outer(LETTERS[1:7],c("#","","b"),paste0)[-c(2,5,17,20)]) ``` [Try it online!](https://tio.run/##K/r/PzmxRCO/tCS1SMPHNSTENSg42tDKPFYnWUNJWUlHCYiSlDR1ChKLS1INNKN1kzWMdEx1DM11jAw0YzX//wcA "R – Try It Online")
[Bash 5](https://www.gnu.org/software/bash/), 42 bytes ====================================================== ``` x=`echo {A..G}{b,,#}`;echo ${x//[BE]#???/} ``` Output: ``` Ab A A# Bb B C C# Db D D# Eb E F F# Gb G G# ```
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[Malbolge](https://github.com/TryItOnline/malbolge), ~~482~~ ~~370~~ 353 bytes ============================================================================== R1: Removed commas inbetween (as not required by the challenge) R2: Shave off a few bytes ``` ('<;_#!=6Z|{8xUwvt,PrqonKmk)"FhCUTdb?`+<;:[Z7YtVU2T|/g-O+i(gJrHc#EC~B{@zZxw:tt'r5Qo"!l/K-hUfe?bP``_Lo~[}|X2VCTR3Q+N`_^9+7Hji3ffdAc~w|u;]\wpon4VUSSQ.PONcb(JI^]#DCYX|@?>=<:u9NMRKo32MFj.C,Ae)>'<%:^"!~5:3WxwwuRts0q(Lnml)"Fhgfe"y?a`_zyxq7YXWlUj0RgfkjMb(JI^c\[Z~BAV?T=Rv987Mq44310FEi-,G@)>b&%#"8=6Z{{yyw/Sut1*)('Km$k(!Efe{zyx>`uz]r8ZXnm3TTih.PkNchg`&HFF[DY}Az ``` [Try it online!](https://tio.run/##HdCLdoEAAIDhZylDlnsscgnRDLmkqNxSKpfSWIlKr95sL/Cd//zGVpdMXVPCEIpXK5sIUPsQfK90Z52blRxfL@a5b5wSILknWGYn4SJcrWALAeWtGZtn/IyWGsEHSOtdu3KkQwQtr@EKdwezrPi1ODFBQM/0U3tWVXBpLIqbgRksnj6XnxEMjUzgobhZl2G0ezwgqrpryoHj25XV0vk2z4UZO51O0uPRUJag3td6FWkTPOc38HqtitnlIUX3TSRPkcc0kWwqiXq8GsXWIBAUMWR@dxybtn6yF2hwNvS/dk1VwAe@FTfu435BeW6us8csramnI/Wvy8uFELSaM5yp0bdyCaUuhQKSy5KdQyr52UjUpVg0ApZeZzzv8XAyU9vKvSegeN94O0FAR1W8l1sXbXd1LQnc2UAY5rBPj09Dea@JsS5JLtr8s@mG4S8 "Malbolge – Try It Online")
[JavaScript (Node.js)](https://nodejs.org), 84 bytes ==================================================== ```javascript _=>[...'ABCDEFG'].map((n,i)=>`${i%3!=2?n+'b,':''}${n}${i%3!=1?`,${n}#`:''}`).join`,` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i5aT09P3dHJ2cXVzV09Vi83sUBDI08nU9PWLkGlOlPVWNHWyD5PWz1JR91KXb1WpTqvFipsaJ@gA@IqJ4AkEjT1svIz8xJ0Ev4n5@cV5@ek6uXkp2ukaWhqWv8HAA "JavaScript (Node.js) – Try It Online") Just returning the string (as shown below) would be shorter by 36 bytes, but where's the fun in that? ```js _=>'Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G#' ```
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[Keg](https://github.com/JonoCode9374/Keg), 43 bytes ---------------------------------------------------- The string, compressed. ``` AbAA\#BbBCC\#DbDD\#EbEFF\#GbGG\#(:H<[ $]')' ``` [TIO](https://tio.run/##y05N///fMcnRMUbZKcnJ2TlG2SXJxSVG2TXJ1c0tRtk9yd09RlnDysMmWkElVl1T/f9/AA)
C, 57 bytes =========== Trivial version 57 bytes in C (gcc) ```c #include <stdio.h> f(){puts("Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G#");} int main() { f(); } ``` [Try it Online!](https://tio.run/##HcyxDsIgGEXhnacg/RdIrsYdY0JLy3MIVCVR2rTg0vTZsfFM33T86el9pZj8u4SRX9cc4nR@3epDyG0ueRWNdtDQhNahRYeOYBwMDKF36DFgIFgHC0uNVHuNKfPPPSYuvlMMkm2MHx0/9ccy5rIkflFsrz8)
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[R](https://www.r-project.org/), 50 bytes ========================================= ```r cat("Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G#") ``` [Try it online!](https://tio.run/##BcHBDcAgDATBXrhPkLYJg8F14HSA0r8zc6ve8z3NEsPESAaTKTxxXKxksdkikiDUetUP "R – Try It Online") Boring answer. [R](https://www.r-project.org/), 60 bytes ========================================= ```r cat(outer(LETTERS[1:7],c("#","","b"),paste0)[-c(2,5,17,20)]) ``` [Try it online!](https://tio.run/##K/r/PzmxRCO/tCS1SMPHNSTENSg42tDKPFYnWUNJWUlHCYiSlDR1ChKLS1INNKN1kzWMdEx1DM11jAw0YzX//wcA "R – Try It Online")
[APL (Dyalog Unicode)](https://www.dyalog.com/), 45 bytes ========================================================= ```apl 2↓(,¨⎕A)⎕R', &'⊢'AbAA#BbBCC#DbDD#EbEFF#GbGG#' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3@hR22QNnUMrHvVNddQEEkHqOgpq6o@6Fqk7Jjk6KjslOTk7K7skubgouya5urkpuye5uyur/0971DbhUW8fUIOn/6Ou5kPrjR@1TQTygoOcgWSIh2fw/zQA "APL (Dyalog Unicode) – Try It Online") Simple `⎕R`eplace operation, prepending `,` to each element in the string that matches each letter in the `⎕A`lphabet, then dropping the first 2 characters, which are `,`.
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[PHP](https://php.net/), 65 bytes ================================= Makes the list with a loop. Items are separated by `_` with a trailing separator. ```php for(;$l=ABCDEFG[$i++];)echo$l._.[$a="$l#_",$a.$b=$l.b_,$b][$i%3]; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVcmwdnZxdXN3co1UytbVjrTVTkzPyVXL04vWiVRJtlVRylOOVdFQS9VSSbIGiSfE6KkmxQKWqxrHW//8DAA "PHP – Try It Online") --- [PHP](https://php.net/), 43 bytes ================================= PHP outputs anything as is, when not inside `<?php` and `?>` tags. ```html Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G# ``` [Try it online!](https://tio.run/##BcGxAQAgCASxYb69JVCEPb6ydP8Gk3ffTJggxDKLzRZpkhTHHIoSbZrWzAc "PHP – Try It Online")
[Perl 5](https://www.perl.org/), ~~47~~ 41 bytes ================================================ ```perl say for'AbA#DbD#GbG#BbEbC#F#'=~/../g,A..G ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhLb9I3THJUdklyUXZPcld2SnJNclZ2U1Z3bZOX09PP13HUU/P/f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[brainfuck](https://github.com/TryItOnline/brainfuck), 106 bytes ================================================================ ``` +++[[-<+>>++<]>]<<[-<->]++<<++<,+<-<[->+>+<<]<+[>>>>>+>-[<.<<<.>.[<]]>[>]<+[---<.<.<.[<]]>[>]<++<.<<.<<<-] ``` [Try it online!](https://tio.run/##RYpBCoBADAMfFLMvCPlI6UEFQQQPgu9f25MpOcw027Oe9/Hu15wAIijYgNIpFdFZpOoCsYzh4hTCHZihIWl4hDId7h/JsnW/Q896yZzzAw "brainfuck – Try It Online") Outputs each note separated by carriage returns.
[Keg](https://github.com/JonoCode9374/Keg), 43 bytes ---------------------------------------------------- The string, compressed. ``` AbAA\#BbBCC\#DbDD\#EbEFF\#GbGG\#(:H<[ $]')' ``` [TIO](https://tio.run/##y05N///fMcnRMUbZKcnJ2TlG2SXJxSVG2TXJ1c0tRtk9yd09RlnDysMmWkElVl1T/f9/AA)
190,013
This task is simple: Write a program or function that outputs the list of all musical notes (using English note names) from A♭ to G♯. All notes without a name consisting of a single letter (i.e. black notes on a musical keyboard) should have their name printed twice, once as the sharp of a note, once as the flat of one. Sharp or flat notes that can be described with a single letter, like B♯ (C) or F♭ (E) should not be outputted. Here is an example of the output: ``` Ab, A, A#, Bb, B, C, C#, Db, D, D#, Eb, E, F, F#, Gb, G, G# ``` Specifications ============== * The program or function must not take any input. * The notes may be printed in any order, and in any list output permitted by our [standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) * The sharp and flat Unicode symbols (♯/♭) may be substituted with `b` and `#` * As always, [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the smallest program, in bytes, wins.
2019/08/14
[ "https://codegolf.stackexchange.com/questions/190013", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/77338/" ]
[Python 3](https://docs.python.org/3/), 50 bytes ================================================ ```python print(*map(''.join,zip(3*'ADGBCEF',7*' '+5*'#b'))) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys3sUBDXV0vKz8zT6cqs0DDWEvd0cXdydnVTV3HXEtdQV3bVEtdOUldU1Pz/38A "Python 3 – Try It Online") Python 2: [48 bytes](https://tio.run/##K6gsycjPM/r/v6AoM69EITexQENdXS8rPzNPpyqzQMNYS93Rxd3J2dVNXcdcS11BXdtUS105SV1T8/9/AA "Python 2 – Try It Online") This code can be adjusted as to include B# and Cb, at the cost of no additional bytes. This can be achieved by replacing `5` with `6`. --- Additionally, it is (finally) shorter than just outputting the plain string: [Python 3](https://docs.python.org/3/), 51 bytes ================================================ ```python exit('Ab A A# Bb B C C# Db D D# Eb E F F# Gb G G#') ``` [Try it online!](https://tio.run/##BcGxDYAwDADBVV5yEaiZwIkT72EJCRqgSAHTm7vnm8d9bZn7e86laKCoUINKowkWGCb0oDMYggeOS1kzfw "Python 3 – Try It Online") Python 2: [50 bytes](https://tio.run/##BcGxDcAgDADBVV5yQZ8NDAbv4SppAEU0md6529@517wy9/vMUzRQVKhBpdEECwwTetAZDMEDx6Vk/g "Python 2 – Try It Online")
[R](https://www.r-project.org/), 50 bytes ========================================= ```r cat("Ab,A,A#,Bb,B,C,C#,Db,D,D#,Eb,E,F,F#,Gb,G,G#") ``` [Try it online!](https://tio.run/##BcHBDcAgDATBXrhPkLYJg8F14HSA0r8zc6ve8z3NEsPESAaTKTxxXKxksdkikiDUetUP "R – Try It Online") Boring answer. [R](https://www.r-project.org/), 60 bytes ========================================= ```r cat(outer(LETTERS[1:7],c("#","","b"),paste0)[-c(2,5,17,20)]) ``` [Try it online!](https://tio.run/##K/r/PzmxRCO/tCS1SMPHNSTENSg42tDKPFYnWUNJWUlHCYiSlDR1ChKLS1INNKN1kzWMdEx1DM11jAw0YzX//wcA "R – Try It Online")
36,911,204
I am using Xcode 7.2 and I have created a swift framework, I can import the framework without error but cannon access the class files of my framework.[![enter image description here](https://i.stack.imgur.com/qJdKd.png)](https://i.stack.imgur.com/qJdKd.png) In the DropDown class file set as public [![enter image description here](https://i.stack.imgur.com/4M4gr.png)](https://i.stack.imgur.com/4M4gr.png)
2016/04/28
[ "https://Stackoverflow.com/questions/36911204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3702516/" ]
You should call Alamofire Request Function in `viewDidLoad` function. and you should `reload table data` when you got response from completion block(from where you print the data). You can reload tableview like, ``` self.tableView.reloadData() ``` hope this will help :)
First create a global bool variable with false ``` override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "CellDetailSegue" && boolVar { if let indexPaths = self.dateCollectionView.indexPathsForSelectedItems() { let subViewController = segue.destinationViewController as! SubViewConroller } } ``` call prepare segue with segue name and boolVar true from almofire block.
36,911,204
I am using Xcode 7.2 and I have created a swift framework, I can import the framework without error but cannon access the class files of my framework.[![enter image description here](https://i.stack.imgur.com/qJdKd.png)](https://i.stack.imgur.com/qJdKd.png) In the DropDown class file set as public [![enter image description here](https://i.stack.imgur.com/4M4gr.png)](https://i.stack.imgur.com/4M4gr.png)
2016/04/28
[ "https://Stackoverflow.com/questions/36911204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3702516/" ]
The first thing I noticed is that you are doing 3 asynchronous requests, not one. You could use a completion handler but which one? I think you have 2 options. 1. Nest the network calls so that the completion of one starts the next one. The downside to this approach is that they will run sequentially and if you add more, you have to continue nesting. An approach like this might be OK if you are only doing 2 calls but beyond that it will get more and more difficult. 2. Use a semaphore to wait until all the data is loaded from all the remote calls. Use the completion handler to signal the semaphore. If you are going to use this approach, then it must be done on a background thread because use of a semaphore will block the thread and you don't want that happening on the main thread. These three calls will all happen simultaneously. And the functions will return even though AlamoFire has not completed. ``` self.dataRequest(self.availablePeriods401) self.dataRequest(self.availablePeriods403) self.dataRequest(self.availablePeriods405) ``` These will execute, whether AlamoFire has completed or not. ``` print(self.availablePeriods401.count) print(self.availablePeriods403.count) print(self.availablePeriods405.count) ``` Using semaphores would look something like this: ``` override func viewWillAppear(animated: Bool) { // maybe show a "Please Wait" dialog? loadMyData() { (success) in // hide the "Please Wait" dialog. // populate data on screen } } func loadMyData(completion: MyCompletionHandler) { // Do this in an operation queue so that we are not // blocking the main thread. let queue = NSOperationQueue() queue.addOperationWithBlock { let semaphore = dispatch_semaphore_create(0) Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar1"]).responseJSON { // This block fires after the results come back // do something dispatch_semaphore_signal(semaphore); } Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar2"]).responseJSON { // This block fires after the results come back // do something dispatch_semaphore_signal(semaphore); } Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar3"]).responseJSON { // This block fires after the results come back // do something dispatch_semaphore_signal(semaphore); } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) completion(true) } } ``` [Apple Docs - Grand Central Dispatch](https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html "Grand Central Dispatch") [How to use semaphores](http://www.javabrown.com/blog/question/when-and-how-to-dispatch_semaphore_t/) The question I have for you is what are you going to do if some, bit not all of the web calls fail?
First create a global bool variable with false ``` override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "CellDetailSegue" && boolVar { if let indexPaths = self.dateCollectionView.indexPathsForSelectedItems() { let subViewController = segue.destinationViewController as! SubViewConroller } } ``` call prepare segue with segue name and boolVar true from almofire block.
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
According to `phpurple` [requirements](http://phurple.php.belsky.info/ch01.html): ``` Please let me know, if you've successfully compiled on earlier versions. Actually the extension is being developed on the php v5.2.6 with the option to be upcomming php v5.3 compatible. ``` The authors will need to update their source. However, since you have the source you could update it yourself because you noted that the project is *CLOSED*. You could also fork the code and create your own gitHub project with php 5.3 support. Good luck.
You can check the new sources shortly posted on <https://github.com/weltling/phurple>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
What you are seeing is PHP's shifty interface (ahem, hold your down votes, I said **s h i f t y**). By that, I mean function prototypes are subject to change from version to version. Take this meta example: ``` int foo_call_bar(const char *foobar, size_t len); ``` And in a later version of something, the function calculates the length dynamically, thus eliminating the second variable in the prototype: ``` int foo_call_bar(const char *foobar); ``` Some projects strive to always maintain backwards compatibility to alleviate this headache, which could be accomplished with pre-processor directives that prototype the new implementation with the `len` variable, but just don't do anything with it. If PHP did that, the code base would succumb to even more madness. Unfortunately, you'll have to modify phpurple to present the correct arguments to the correct PHP functions, and ensure that they are of the appropriate *type*. That would be a bit of an undertaking, but probably wouldn't be as difficult as it seems. The Linux kernel's VFS interface is the same way, and I'm often tasked with porting older experimental file systems to work on modern kernels.
Well, the new URL seems to be a persistent repo with fixes to PHP-5.3 and above. Maybe that should be mentioned, but that won't help with checking it out anyway. For me it worked fine, so I would say it is worth a try.
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
Well, the new URL seems to be a persistent repo with fixes to PHP-5.3 and above. Maybe that should be mentioned, but that won't help with checking it out anyway. For me it worked fine, so I would say it is worth a try.
You can check the new sources shortly posted on <https://github.com/weltling/phurple>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
According to `phpurple` [requirements](http://phurple.php.belsky.info/ch01.html): ``` Please let me know, if you've successfully compiled on earlier versions. Actually the extension is being developed on the php v5.2.6 with the option to be upcomming php v5.3 compatible. ``` The authors will need to update their source. However, since you have the source you could update it yourself because you noted that the project is *CLOSED*. You could also fork the code and create your own gitHub project with php 5.3 support. Good luck.
look at that man <http://sourceforge.net/news/?group_id=235197&id=296063>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
According to `phpurple` [requirements](http://phurple.php.belsky.info/ch01.html): ``` Please let me know, if you've successfully compiled on earlier versions. Actually the extension is being developed on the php v5.2.6 with the option to be upcomming php v5.3 compatible. ``` The authors will need to update their source. However, since you have the source you could update it yourself because you noted that the project is *CLOSED*. You could also fork the code and create your own gitHub project with php 5.3 support. Good luck.
Well, the new URL seems to be a persistent repo with fixes to PHP-5.3 and above. Maybe that should be mentioned, but that won't help with checking it out anyway. For me it worked fine, so I would say it is worth a try.
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
According to `phpurple` [requirements](http://phurple.php.belsky.info/ch01.html): ``` Please let me know, if you've successfully compiled on earlier versions. Actually the extension is being developed on the php v5.2.6 with the option to be upcomming php v5.3 compatible. ``` The authors will need to update their source. However, since you have the source you could update it yourself because you noted that the project is *CLOSED*. You could also fork the code and create your own gitHub project with php 5.3 support. Good luck.
A little late, but here is the latest library that works with PHP 5.3: The new project page is: <http://sourceforge.net/projects/phurple> The blog post: <http://belski.net/archives/23-Phurple-per-se-PHPurple.html> I have ran into a problem after I have complied it and added the extension to PHP.ini configuration: ``` PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/phurple.so' - /usr/lib/php/modules/phurple.so: undefined symbol: ZVAL_ADDREF in Unknown on line 0 ``` To fix this, change the line containing ZVAL\_ADDREF in client.c from ``` ZVAL_ADDREF(PHURPLE_G(phurple_client_obj)); ``` to ``` Z_ADDREF_P(PHURPLE_G(phurple_client_obj)); ```
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
What you are seeing is PHP's shifty interface (ahem, hold your down votes, I said **s h i f t y**). By that, I mean function prototypes are subject to change from version to version. Take this meta example: ``` int foo_call_bar(const char *foobar, size_t len); ``` And in a later version of something, the function calculates the length dynamically, thus eliminating the second variable in the prototype: ``` int foo_call_bar(const char *foobar); ``` Some projects strive to always maintain backwards compatibility to alleviate this headache, which could be accomplished with pre-processor directives that prototype the new implementation with the `len` variable, but just don't do anything with it. If PHP did that, the code base would succumb to even more madness. Unfortunately, you'll have to modify phpurple to present the correct arguments to the correct PHP functions, and ensure that they are of the appropriate *type*. That would be a bit of an undertaking, but probably wouldn't be as difficult as it seems. The Linux kernel's VFS interface is the same way, and I'm often tasked with porting older experimental file systems to work on modern kernels.
You can check the new sources shortly posted on <https://github.com/weltling/phurple>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
look at that man <http://sourceforge.net/news/?group_id=235197&id=296063>
You can check the new sources shortly posted on <https://github.com/weltling/phurple>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
What you are seeing is PHP's shifty interface (ahem, hold your down votes, I said **s h i f t y**). By that, I mean function prototypes are subject to change from version to version. Take this meta example: ``` int foo_call_bar(const char *foobar, size_t len); ``` And in a later version of something, the function calculates the length dynamically, thus eliminating the second variable in the prototype: ``` int foo_call_bar(const char *foobar); ``` Some projects strive to always maintain backwards compatibility to alleviate this headache, which could be accomplished with pre-processor directives that prototype the new implementation with the `len` variable, but just don't do anything with it. If PHP did that, the code base would succumb to even more madness. Unfortunately, you'll have to modify phpurple to present the correct arguments to the correct PHP functions, and ensure that they are of the appropriate *type*. That would be a bit of an undertaking, but probably wouldn't be as difficult as it seems. The Linux kernel's VFS interface is the same way, and I'm often tasked with porting older experimental file systems to work on modern kernels.
look at that man <http://sourceforge.net/news/?group_id=235197&id=296063>
4,775,117
I wan to cut a string in around 300 characters and add "..." at the end if it was above that number of characters. I know it can't be very hard but I don't want to cut a word in half so I wanted to know how do I do it so it doesn't end up like: "And the bird suddenl..." Thanks
2011/01/23
[ "https://Stackoverflow.com/questions/4775117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535967/" ]
What you are seeing is PHP's shifty interface (ahem, hold your down votes, I said **s h i f t y**). By that, I mean function prototypes are subject to change from version to version. Take this meta example: ``` int foo_call_bar(const char *foobar, size_t len); ``` And in a later version of something, the function calculates the length dynamically, thus eliminating the second variable in the prototype: ``` int foo_call_bar(const char *foobar); ``` Some projects strive to always maintain backwards compatibility to alleviate this headache, which could be accomplished with pre-processor directives that prototype the new implementation with the `len` variable, but just don't do anything with it. If PHP did that, the code base would succumb to even more madness. Unfortunately, you'll have to modify phpurple to present the correct arguments to the correct PHP functions, and ensure that they are of the appropriate *type*. That would be a bit of an undertaking, but probably wouldn't be as difficult as it seems. The Linux kernel's VFS interface is the same way, and I'm often tasked with porting older experimental file systems to work on modern kernels.
A little late, but here is the latest library that works with PHP 5.3: The new project page is: <http://sourceforge.net/projects/phurple> The blog post: <http://belski.net/archives/23-Phurple-per-se-PHPurple.html> I have ran into a problem after I have complied it and added the extension to PHP.ini configuration: ``` PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/modules/phurple.so' - /usr/lib/php/modules/phurple.so: undefined symbol: ZVAL_ADDREF in Unknown on line 0 ``` To fix this, change the line containing ZVAL\_ADDREF in client.c from ``` ZVAL_ADDREF(PHURPLE_G(phurple_client_obj)); ``` to ``` Z_ADDREF_P(PHURPLE_G(phurple_client_obj)); ```
59,401,565
I have created MySQL data model to store content along with its custom attributes/field. Below is a simplified version of it. One for storing content: ``` CREATE TABLE `cms_content` ( `id` int(11) NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `content_type_id` int(6) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ALTER TABLE `cms_content` ADD PRIMARY KEY (`id`), ADD KEY `content_type_id` (`content_type_id`); ``` The second one for content type (e.g. article, movie, person): ``` CREATE TABLE `cms_content_type` ( `id` int(6) NOT NULL, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ALTER TABLE `cms_content_type` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `key` (`name`); ``` Custom fields: ``` CREATE TABLE `cms_custom_field` ( `id` int(11) NOT NULL, `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `content_type_id` int(6) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ALTER TABLE `cms_custom_field` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `name` (`name`,`content_type_id`), ADD KEY `name_2` (`name`); ``` And finally one for connecting custom fields and the data: ``` CREATE TABLE `cms_content_data` ( `id` int(11) NOT NULL, `custom_field_id` int(11) NOT NULL, `content_id` int(11) NOT NULL, `value` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `value_content_id` int(11) DEFAULT NULL, `value_taxonomy_value_id` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ALTER TABLE `cms_content_data` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `key` (`value`,`content_id`,`custom_field_id`) USING BTREE, ADD KEY `content_id` (`content_id`), ADD KEY `custom_field_id` (`custom_field_id`), ADD KEY `value` (`value`), ADD KEY `value_content_id` (`value_content_id`), ADD KEY `value_taxonomy_value_id` (`value_taxonomy_value_id`), ADD KEY `custom_field_id_2` (`custom_field_id`,`content_id`); ``` **The challenge** I need to create a query that fetched content of a certain type with all of its custom fields. NB! One trick here is that there can be multiple `content_data` values for one custom field. *E.g. a movie has a field `genre` which can have multiple rows in `content_data`.* **The non-working query** I was able to dynamically generate the following query: ``` SELECT `content`.`id` AS `_content_id`, `content`.`title` AS `_content_title`, `content_data_0`.`value_taxonomy_value_id` AS `genres`, `content_data_1`.`value_content_id` AS `production_company`, `content_data_2`.`value` AS `date_released`, `content_data_3`.`value` AS `runtime`, `content_data_4`.`value` AS `tagline`, `content_data_5`.`value` AS `imdb_rating`, `content_data_6`.`value` AS `rt_rating`, `content_data_7`.`value` AS `imdb_id`, `content_data_8`.`value` AS `trailer_url`, `content_data_9`.`value` AS `api_id`, `content_data_10`.`value_taxonomy_value_id` AS `rating`, `content_data_11`.`value` AS `revenue`, `content_data_12`.`value` AS `poster_original_path`, `content_data_13`.`value` AS `rt_rating_users`, `content_data_14`.`value` AS `rt_url`, `content_data_15`.`value` AS `rt_consensus`, `content_data_16`.`value` AS `mc_rating`, `content_data_17`.`value` AS `year`, `content_data_18`.`value` AS `budget`, `content_data_19`.`value_taxonomy_value_id` AS `original_language`, `content_data_20`.`value_taxonomy_value_id` AS `production_countries`, `content_data_21`.`value` AS `original_title` FROM `cms_content` AS `content` INNER JOIN cms_content_type ON cms_content_type.id = content.content_type_id INNER JOIN `cms_content_data` AS `content_data_0` ON `content_data_0`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_1` ON `content_data_1`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_2` ON `content_data_2`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_3` ON `content_data_3`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_4` ON `content_data_4`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_5` ON `content_data_5`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_6` ON `content_data_6`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_7` ON `content_data_7`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_8` ON `content_data_8`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_9` ON `content_data_9`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_10` ON `content_data_10`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_11` ON `content_data_11`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_12` ON `content_data_12`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_13` ON `content_data_13`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_14` ON `content_data_14`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_15` ON `content_data_15`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_16` ON `content_data_16`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_17` ON `content_data_17`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_18` ON `content_data_18`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_19` ON `content_data_19`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_20` ON `content_data_20`.`content_id` = `content`.`id` INNER JOIN `cms_content_data` AS `content_data_21` ON `content_data_21`.`content_id` = `content`.`id` INNER JOIN `cms_content_type` AS `content_type` ON `content_type`.`id` = `content`.`content_type_id` WHERE `content_type`.`name` = 'movie' AND `content_data_0`.`custom_field_id` = 141 AND `content_data_1`.`custom_field_id` = 143 AND `content_data_2`.`custom_field_id` = 144 AND `content_data_3`.`custom_field_id` = 146 AND `content_data_4`.`custom_field_id` = 148 AND `content_data_5`.`custom_field_id` = 154 AND `content_data_6`.`custom_field_id` = 155 AND `content_data_7`.`custom_field_id` = 156 AND `content_data_8`.`custom_field_id` = 158 AND `content_data_9`.`custom_field_id` = 159 AND `content_data_10`.`custom_field_id` = 162 AND `content_data_11`.`custom_field_id` = 163 AND `content_data_12`.`custom_field_id` = 164 AND `content_data_13`.`custom_field_id` = 174 AND `content_data_14`.`custom_field_id` = 175 AND `content_data_15`.`custom_field_id` = 176 AND `content_data_16`.`custom_field_id` = 177 AND `content_data_17`.`custom_field_id` = 185 AND `content_data_18`.`custom_field_id` = 184 AND `content_data_19`.`custom_field_id` = 186 AND `content_data_20`.`custom_field_id` = 187 AND `content_data_21`.`custom_field_id` = 188 DESC LIMIT 100 ``` The problems here: 1. Wrong return. Apparently, since there can be multiple values for every `content_data` MySQL combines them in all sorts of way and I end up with one `movie` with various combinations of custom fields. 2. The query is super slow (probably because of many joins as well as combinations of field values) **The question** Is there any way in MySQL (plus some PHP backend magic, of course) to return all the required data in one single query? Considering the current data model. As for multiple rows, having values in comma-separated field value would work for me (unless there is a better way). Or is this data model simply very flawed and I need to change it somehow? Thanks in advance!
2019/12/18
[ "https://Stackoverflow.com/questions/59401565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2363857/" ]
I guess your enterprise app is from a public client/ native app right? Assign users and groups to a native app is meaningless. Because native app doesn't act as a service principal to ask for a token. It doesn't have a client secret. You won't get the app role from a token asked by a native app. So the “users and groups” option is unavailable in this case.
This happens when your Application Registration (which is bound to your Enterprise App) has the following setting to `Yes`. Simply change the switch to `No`. [![enter image description here](https://i.stack.imgur.com/3rZ5H.png)](https://i.stack.imgur.com/3rZ5H.png)
68,974,902
I'm coming from a JS background. In JS I could write something as follows: ```js let x = [[1, 0], [2, 1], [3, 2], [4, 3]] x.forEach(([n, i]) => console.log()) ``` So I was trying to convert to Scala, and I found a bunch of ways to do it. But I don't understand how the `match` and `case` statement are disappearing. ```scala val x = Array(1, 2, 3, 4).zipWithIndex // does what I expect x.foreach((a) => { println(a) }) // uses match x.foreach((a) => { a match { case (n, i) => println(s"$n $i") } }) // gets rid of redundant variable name x.foreach({ _ match { case (n, i) => println(s"$n $i") } }) // gets rid of unnecesary scope x.foreach(_ match { case (n, i) => println(s"$n $i") }) ``` Up to here, it makes sense. The below code I found online when looking how to loop with index. ```scala // where did `match` go? x.foreach({ case (n, i) => println(s"$n $i") }) // and now `case` is gone too? x.foreach((n, i) => println(s"$n $i")) ``` What is going on here? I would call it destructuring coming from JS, but this *seems* like a hidden/implicit `match`/`case` statement. Are there rules around that? How do I know if there should be an implicit `match`/`case` statement?
2021/08/29
[ "https://Stackoverflow.com/questions/68974902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14238358/" ]
> > > ```scala > // where did `match` go? > x.foreach({ > case (n, i) => println(s"$n $i") > }) > > ``` > > This is a *Pattern Matching Anonymous Function*, also sometimes called a *Partial Function Literal*. See [Scala Language Specification 8.5 *Pattern Matching Anonymous Functions*](https://scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html#pattern-matching-anonymous-functions) for all the gory details. Simply put, the expression ```scala { case p1 => e1 case p2 => e2 // … case pn => en } ``` is equivalent to ```scala (x1: S1, x2: S2, /* … */, xn: Sn) => (x1, x2, /* … */, xn) match { case p1 => e1 case p2 => e2 // … case pn => en } ``` provided that the result type is SAM-convertible to `FunctionN[S1, S2, /* … */, Sn, R]`, or as a special case `PartialFunction1[S1, R]` (which is where the name *Partial Function Literal* comes from.) > > > ```scala > // and now `case` is gone too? > x.foreach((n, i) => println(s"$n $i")) > > ``` > > This is a new feature of Scala 3. For a very long time, the Scala Designers wanted to unify *Tuples* and *Argument Lists*. In other words, they wanted to make it so that methods in Scala only ever take one argument, and that argument is a tuple. Unfortunately, it turned out that a) this massively breaks backwards-compatibility and b) massively breaks platform interoperability. Now, Scala 3 was an opportunity to ignore problem a), but you cannot ignore problem b) since one of the major design goals of Scala is to have seamless, tight, good, performant integration with the underlying host platform (e.g. .NET in the case of the now-abandoned Scala.NET, the ECMASCript / HTML5 / DOM / WebAPI platform in the case of Scala.js, the native Operating System in the case of Scala-native, or the Java platform (JRE, JDK, JVM, J2SE, J2EE, Java, Kotlin, Clojure, etc.) in the case of Scala-JVM). However, the Scala designers managed to find a compromise, where arguments and tuples are not the same thing, but parameters can be easily converted to tuples and tuples can be easily converted to arguments. This is called [*Parameter Untupling*](https://docs.scala-lang.org/scala3/reference/other-new-features/parameter-untupling-spec.html), and it basically means that a function of type `FunctionN[S1, S2, /* … */, Sn, R]` can be automatically converted to a function of type `Function1[(S1, S2, /* … */, Sn), R]` which is syntactic sugar for `Function1[TupleN[S1, S2, /* … */, Sn], R]`. Simply put, ```scala (p1: S1, p2: S2, /* … */, pn: Sn) => e: R ``` can automatically be converted to ```scala (x: (S1, S2, /* … */, Sn)) => { val p1: S1 = x._1 val p2: S2 = x._2 // … val pn: Sn = x._n e } ``` --- Note: unfortunately, there is no comprehensive specification of Scala 3 yet. There is a partial [Language Reference](https://docs.scala-lang.org/scala3/reference/overview.html), which however only describes differences to Scala 2. So, you typically have to bounce back and forth between the SLS and the Scala 3 docs.
About `match` keyword: ``` // where did `match` go? x.foreach({ case (n, i) => println(s"$n $i") }) ``` This is the language specification, you can ignore match keyword in anonymous functions: <https://scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html#pattern-matching-anonymous-functions>
25,489,181
So I am currently doing some work with Multi-Threading in Java and I'm pretty stuck on a, most likely, simple thing. I currently have a JButton that, when pressed invokes the method as follows: ``` private void clickTest() throws InterruptedException{ statOrganizer.incrementHappiness(); Thread t = new Thread(new Happiness(workspaceHappy)); t.start(); } ``` and then takes around 10-30 seconds to complete. During this time however, it is still possible to re-click the JButton so that it messes with how the information is displayed. What I want to do is during the time this particular thread is "alive", disable the button so that it is no longer possible to click it(and thus activate this thread once it's already going). Once the thread is finished, I want to re-enable the button again. The button code just looks like this ``` button.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 1) { try { clickTest(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); ```
2014/08/25
[ "https://Stackoverflow.com/questions/25489181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262422/" ]
Disable the button right before starting the thread. In the thread, at the end, post an event that would re-enable the button (using invokeLater). You may also need a cancel option, but that's a separate question.
The nice solution for this is to use a [glass pane](http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html#glasspane) to capture all events and stopping them from propagating to any of your UI elements on the panel under the glass pane. Of course while you only have one or two, you can call `setEnabled(false)` on them manually but glass panes give you more flexibility, you'll never have to worry about adding a new element to your UI and forgetting to disable it during background processing. Probably an overkill for one button though. Another, unrelated thing you should consider is the use of [`Executor`s](http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html) instead of launching threads for background tasks. It results in cleaner and more scalable code.
25,489,181
So I am currently doing some work with Multi-Threading in Java and I'm pretty stuck on a, most likely, simple thing. I currently have a JButton that, when pressed invokes the method as follows: ``` private void clickTest() throws InterruptedException{ statOrganizer.incrementHappiness(); Thread t = new Thread(new Happiness(workspaceHappy)); t.start(); } ``` and then takes around 10-30 seconds to complete. During this time however, it is still possible to re-click the JButton so that it messes with how the information is displayed. What I want to do is during the time this particular thread is "alive", disable the button so that it is no longer possible to click it(and thus activate this thread once it's already going). Once the thread is finished, I want to re-enable the button again. The button code just looks like this ``` button.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 1) { try { clickTest(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); ```
2014/08/25
[ "https://Stackoverflow.com/questions/25489181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262422/" ]
Disable the button right before starting the thread. In the thread, at the end, post an event that would re-enable the button (using invokeLater). You may also need a cancel option, but that's a separate question.
Try the following: ``` button.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 1) { try { clickTest(); button.setEnabled(false);//this assume 'button' is final } catch (InterruptedException e) { e.printStackTrace(); } } } }); ``` Then, modify the `run` method of your `Happiness` class: ``` public void run() { //your processing code here ... button.setEnabled(true); //reference to button can be passed in constructor of Happiness // or access using getter, ... This really depend on your implementation. } ```
24,831,438
These are my main class ``` public class Customer { public Customer() { Products = new HashSet<Product>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<Product> Products { get; set; } } public class Product { public int Id { get; set; } public int CustomerId { get; set; } public string ProductName { get; set; } public Customer Customer { get; set; } } ``` These are my view models ``` public class ProductVM { public string ProductName { get; set; } } public class CustomerVM { public string Name { get; set; } public ICollection<ProductVM> Products { get; set; } } ``` How can I populate the properties of `CustomerVM`? Something like this I have tried: ``` var tmp = _db.Customers.Select(c => new CustomerVM { Name = c.Name, Products = ????? // I don't know how to populate here } ``` Really new in `asp.net mvc` and `linq` still making my way up.
2014/07/18
[ "https://Stackoverflow.com/questions/24831438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214293/" ]
This means that for any complete object type with a fundamental alignment, it should be possible to convert the pointer returned to a pointer to that object type, respecting the alignment requirement of that object type. In practice, since alignments are powers of two, this means that an allocation function is required to return a pointer aligned to `alignof(std::max_align_t)`. There is no separate definition of "suitable alignment"; in this paragraph as elsewhere "suitably" just means that there is a requirement which the program is required to satisfy for the rest of the paragraph to hold.
Alignment is defined by the OS and platform. Usually it is the size of the largest basic type (a pointer or `double`), but it could be more. For instance, on Windows, x86 is 8 byte and x64 is 16 byte.
24,831,438
These are my main class ``` public class Customer { public Customer() { Products = new HashSet<Product>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<Product> Products { get; set; } } public class Product { public int Id { get; set; } public int CustomerId { get; set; } public string ProductName { get; set; } public Customer Customer { get; set; } } ``` These are my view models ``` public class ProductVM { public string ProductName { get; set; } } public class CustomerVM { public string Name { get; set; } public ICollection<ProductVM> Products { get; set; } } ``` How can I populate the properties of `CustomerVM`? Something like this I have tried: ``` var tmp = _db.Customers.Select(c => new CustomerVM { Name = c.Name, Products = ????? // I don't know how to populate here } ``` Really new in `asp.net mvc` and `linq` still making my way up.
2014/07/18
[ "https://Stackoverflow.com/questions/24831438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214293/" ]
This means that for any complete object type with a fundamental alignment, it should be possible to convert the pointer returned to a pointer to that object type, respecting the alignment requirement of that object type. In practice, since alignments are powers of two, this means that an allocation function is required to return a pointer aligned to `alignof(std::max_align_t)`. There is no separate definition of "suitable alignment"; in this paragraph as elsewhere "suitably" just means that there is a requirement which the program is required to satisfy for the rest of the paragraph to hold.
§3.11/1 says, > > Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on the addresses at which an > object of that type may be allocated. > > > So if a pointer is "suitably aligned" it means that the address represented by the pointer satisfies these restrictions. What exactly this means for the numerical value of the address is implementation-defined.
13,030,486
Can somebody advise whether there's a good built-in way (= AppleScript command) to pull out statistics for a DB: I need to count the number of occurrences of a string in a particular field over all records. E.g. for a record that has * *Name* * *Phone* * *Town* the script would return how many records exist with identical towns.
2012/10/23
[ "https://Stackoverflow.com/questions/13030486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089245/" ]
Step 1 - Create a relationship. - File > Manage Database > Define Database - Relationships tab - Duplicate your table occurance and name it (I used `related_towns`) - Drag a relationship between the two from town to town - Click OK. ![This is what your relationships tab should look like](https://i.stack.imgur.com/5sZLX.png) Step 2 - Create a calculated field that counts the instances of the related (duplicative) town name. * File > Manage Database > Define Database * Fields Tab * Type in the name of your new field (I used `number_of_related_towns`) at the bottom of the screen * Select "Calculation" from the field type list * Count the times that the town appears in your relationship with this calcuation: ![This is what your calculation field should look like](https://i.stack.imgur.com/8VJ11.png) Be sure that "Evaluate this calculation in the context of" is set to the name of your base table (what your layout is based on). Replace `related_towns` with whatever you named your new table occurance. Step 3 - Write a script to display your data. * Scripts > Manage Scripts * New button (bottom left) * Rebuild the screenshot below. I added comments, which hopefully explain? ![enter image description here](https://i.stack.imgur.com/vjYmj.png) Let me know if you have any questions.
I would do this in FileMaker. It is built for exactly this. Do you know how to do it in FM?
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
You could use [`join`](http://perldoc.perl.org/functions/join.html) and modify the last element to include an `and`: ``` my @list = 1 .. 5; $list[-1] = "and $list[-1]" if $#list; print join ', ', @list; ```
Just in the spirit of TIMTOWTDI (though, frankly, @perreal's answer is better as far as readability): ``` sub commas { my $last_index = $#_; my @with_commas = map { (($_==$last_index) ? "and " : "") . $_[$_] } 0 .. $last_index; print join("," @with_commas) } ``` This is somewhat similar to Alan's answer (more convoluted/complicated), but the benefit compared to that is that it would work if you need to add "and " to any OTHER element than the last one; Alan's only works when you know the exact offset (e.g. last element)
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
``` sub format_list { return "" if !@_; my $last = pop(@_); return $last if !@_; return join(', ', @_) . " and " . $last; } print format_list(@list), "\n"; ``` This also handles lists with only one element, unlike most of the other answers.
You could use [`join`](http://perldoc.perl.org/functions/join.html) and modify the last element to include an `and`: ``` my @list = 1 .. 5; $list[-1] = "and $list[-1]" if $#list; print join ', ', @list; ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
You could use [`join`](http://perldoc.perl.org/functions/join.html) and modify the last element to include an `and`: ``` my @list = 1 .. 5; $list[-1] = "and $list[-1]" if $#list; print join ', ', @list; ```
Small hint ``` for( 1 .. 10 ) { print ; $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and '); } ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
``` #!/usr/bin/perl use warnings; use strict; sub commas { return "" if @_ == 0; return $_[0] if @_ == 1; my $last = pop @_; my $rest = join (", ", @_); return $rest.", and ".$last; } my @a = (1,2,3,4,5); print commas(@a), "\n"; ```
Small hint ``` for( 1 .. 10 ) { print ; $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and '); } ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
Add the commas then add the "and ": ``` use v5.10; my $string = join ', ', 1 .. 5; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; say $string; ``` So, work that in as the case when you have more than two elements: ``` use v5.10; my @array = 1..5; my $string = do { if( @array == 1 ) { @array[0]; } elsif( @array == 2 ) { join ' and ', @array } elsif( @array > 2 ) { my $string = join ', ', @array; my $commas = $string =~ tr/,//; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; $string; } }; say $string; ```
Small hint ``` for( 1 .. 10 ) { print ; $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and '); } ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
There is a CPAN module for this, [Lingua::Conjunction](https://metacpan.org/module/Lingua%3a%3aConjunction). I use it myself, and recommend it over rolling your own solution. The usage syntax is very simple: ``` conjunction(@list); ```
Just in the spirit of TIMTOWTDI (though, frankly, @perreal's answer is better as far as readability): ``` sub commas { my $last_index = $#_; my @with_commas = map { (($_==$last_index) ? "and " : "") . $_[$_] } 0 .. $last_index; print join("," @with_commas) } ``` This is somewhat similar to Alan's answer (more convoluted/complicated), but the benefit compared to that is that it would work if you need to add "and " to any OTHER element than the last one; Alan's only works when you know the exact offset (e.g. last element)
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
``` sub format_list { return "" if !@_; my $last = pop(@_); return $last if !@_; return join(', ', @_) . " and " . $last; } print format_list(@list), "\n"; ``` This also handles lists with only one element, unlike most of the other answers.
Small hint ``` for( 1 .. 10 ) { print ; $_ == 10 ? print '' : ($_ != 9 ? print ', ' : print ' and '); } ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
There is a CPAN module for this, [Lingua::Conjunction](https://metacpan.org/module/Lingua%3a%3aConjunction). I use it myself, and recommend it over rolling your own solution. The usage syntax is very simple: ``` conjunction(@list); ```
Add the commas then add the "and ": ``` use v5.10; my $string = join ', ', 1 .. 5; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; say $string; ``` So, work that in as the case when you have more than two elements: ``` use v5.10; my @array = 1..5; my $string = do { if( @array == 1 ) { @array[0]; } elsif( @array == 2 ) { join ' and ', @array } elsif( @array > 2 ) { my $string = join ', ', @array; my $commas = $string =~ tr/,//; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; $string; } }; say $string; ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
``` sub format_list { return "" if !@_; my $last = pop(@_); return $last if !@_; return join(', ', @_) . " and " . $last; } print format_list(@list), "\n"; ``` This also handles lists with only one element, unlike most of the other answers.
There is a CPAN module for this, [Lingua::Conjunction](https://metacpan.org/module/Lingua%3a%3aConjunction). I use it myself, and recommend it over rolling your own solution. The usage syntax is very simple: ``` conjunction(@list); ```
12,201,472
I want to create a subroutine that adds commas to elements and adds an "and" before the last element, e.g., so that "12345" becomes "1, 2, 3, 4, and 5". I know how to add the commas, but the problem is the result I get is "1, 2, 3, 4, and 5," and I don't know how to get rid of the last comma. ``` sub commas { my @with_commas; foreach (@_) { push (@with_commas, ($_, ", ")); #up to here it's fine } splice @with_commas, -2, 1, ("and ", $_[-1]); @with_commas; } ``` As you can probably tell, I'm trying to delete the last element in the new array (@with\_commas), since it has the comma appended, and add in the last element in the old array (@\_, passed to the sub routine from the main program, with no added comma). When I run this, the result is, e.g., "1, 2, 3, 4, and 5," -- with the comma at the end. Where is that comma coming from? Only @with\_commas was supposed to get the commas. Any help is appreciated.
2012/08/30
[ "https://Stackoverflow.com/questions/12201472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1572378/" ]
``` sub format_list { return "" if !@_; my $last = pop(@_); return $last if !@_; return join(', ', @_) . " and " . $last; } print format_list(@list), "\n"; ``` This also handles lists with only one element, unlike most of the other answers.
Add the commas then add the "and ": ``` use v5.10; my $string = join ', ', 1 .. 5; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; say $string; ``` So, work that in as the case when you have more than two elements: ``` use v5.10; my @array = 1..5; my $string = do { if( @array == 1 ) { @array[0]; } elsif( @array == 2 ) { join ' and ', @array } elsif( @array > 2 ) { my $string = join ', ', @array; my $commas = $string =~ tr/,//; substr $string, rindex( $string, ', ' ) + 2, 0, 'and ' ; $string; } }; say $string; ```
4,209,875
* A Graph DB that can handle around 100k-1M nodes * We need nodes that can have different types and attributes * We need edges (associations between nodes) that also can have different types and attributes * Transactional support (all or nothing commits to DB) * History of changes to elements (add/remove element, add/remove edge, add/remove/modification of attribute) + time-span that during the element existed (could either be supported directly by Graph DB or we created layer on top) Bonus points: * Support for some smart graph query language that can be used find nodes + To be used for reporting and queries in program + SPARQL might be a good if they support. Too complicated query language? * Support for inheritance between node and edge types (to enable query graph for a more generic element type and then also get the inherited element types) * Replication and failover to secondary DB, or backup to a central DB
2010/11/17
[ "https://Stackoverflow.com/questions/4209875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300314/" ]
[Neo4j](http://neo4j.org/) supports everything that you need, but it is not free for commercial projects;
Not sure if it fullfills all your requirements but IntelliDimension has a commercial product that sits on top of Microsoft SQL Server and supports SPARQL. They also provide a SDK for .Net. <http://www.intellidimension.com>
1,897,064
Prove that if $\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$, then $ABC$ is right-angled. I only found that $\sin^2{A} + \sin^2{B} + \sin^2{C} = 2$, but I have no idea what to do next. Thank you in advance for your answers!
2016/08/19
[ "https://math.stackexchange.com/questions/1897064", "https://math.stackexchange.com", "https://math.stackexchange.com/users/215665/" ]
$$\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$$ Use $\cos^2{A} =\frac{1+\cos2A}2$. Then $$\cos2A+\cos2B+\cos2C=-1$$ Use $\cos2A+\cos2B+\cos2C=-1-4\cos A\cos B\cos C$ Then $$-1-4\cos A\cos B\cos C=-1$$ $$4\cos A\cos B\cos C=0$$ Then $\angle A$ or $\angle B$ or $\angle C$ is $\frac{\pi}{2}$
HINT: $$F=\cos^2A+\cos^2B+\cos^2C=\cos^2A-\sin^2B+\cos^2C+1$$ Now using [Prove that $\cos (A + B)\cos (A - B) = {\cos ^2}A - {\sin ^2}B$](https://math.stackexchange.com/questions/345703/prove-that-cos-a-b-cos-a-b-cos-2a-sin-2b), $$F=\cos(A+B)\cos(A-B)+\cos^2C+1$$ Now as $\cos(A+B)=\cos(\pi-C)=-\cos C,$ $$F=-\cos C\cos(A-B)+\cos C\{-\cos(A+B)\}=1-\cos C(2\cos A\cos B)$$
1,897,064
Prove that if $\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$, then $ABC$ is right-angled. I only found that $\sin^2{A} + \sin^2{B} + \sin^2{C} = 2$, but I have no idea what to do next. Thank you in advance for your answers!
2016/08/19
[ "https://math.stackexchange.com/questions/1897064", "https://math.stackexchange.com", "https://math.stackexchange.com/users/215665/" ]
$$\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$$ Use $\cos^2{A} =\frac{1+\cos2A}2$. Then $$\cos2A+\cos2B+\cos2C=-1$$ Use $\cos2A+\cos2B+\cos2C=-1-4\cos A\cos B\cos C$ Then $$-1-4\cos A\cos B\cos C=-1$$ $$4\cos A\cos B\cos C=0$$ Then $\angle A$ or $\angle B$ or $\angle C$ is $\frac{\pi}{2}$
By $½$-angle relations, $cos²(A)+cos²(B)+cos² (C) = 1 + ½{cos(2A)+cos(2B)} + cos²(C)$ $= 1 + cos(A+B)cos(A−B) + cos²(C) = 1 – cos (C)cos(A−B) + cos²(C),$ using $A+B=π−C$ $= 1 + cos(C){cos(C) −cos(A−B)} = 1 − 2cos (C)sin(½(C−A+B))sin(½(C+A−B))$ $= 1 – 2cos(C)sin(½π−A)sin( ½π−B) = 1 – 2cos(A)cos(B)cos(C)$ $∴ cos²(A)+cos²(B)+cos²(C) = 1 → cos(A)cos (B)cos(C) = 0 → A,B or C = ½π$
1,897,064
Prove that if $\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$, then $ABC$ is right-angled. I only found that $\sin^2{A} + \sin^2{B} + \sin^2{C} = 2$, but I have no idea what to do next. Thank you in advance for your answers!
2016/08/19
[ "https://math.stackexchange.com/questions/1897064", "https://math.stackexchange.com", "https://math.stackexchange.com/users/215665/" ]
$$\cos^2{A} + \cos^2{B} + \cos^2{C} = 1$$ Use $\cos^2{A} =\frac{1+\cos2A}2$. Then $$\cos2A+\cos2B+\cos2C=-1$$ Use $\cos2A+\cos2B+\cos2C=-1-4\cos A\cos B\cos C$ Then $$-1-4\cos A\cos B\cos C=-1$$ $$4\cos A\cos B\cos C=0$$ Then $\angle A$ or $\angle B$ or $\angle C$ is $\frac{\pi}{2}$
As you found that $\sin^2{A} + \sin^2{B} + \sin^2{C} = 2$ note that $\sin^2 \theta + \cos^2 \theta =1$ Then $1-\cos^2 A + 1- \cos^2 B + 1 - \cos^2 C = 2$ $ 3 -(\cos^2 A + \cos^2 B + \cos^2 C)= 2$ $3 - 2 = \cos^2 A + \cos^2 B + \cos^2 C$ $\cos^2 A + \cos^2 B + \cos^2 C =1$
261,222
There is issue in saving lightning components. Lightning components which has controller(which is referring User's fields). Error message are stating like - There is no such column "Email" on User entity; where as the running user is System administrator. Let us know, if someone found root cause, or work around for the same. --- Update: Added sample code to reproduce the same Sample component: SampleComponent.cmp ``` <aura:component controller="SampleClass"> Hello World </aura:component> ``` SampleClass ``` public class SampleClass { public SampleClass(){ User u = [select id, email, mobilephone from User where id=: UserInfo.getUserId()]; System.debug('Email: ' + u.email); } } ``` **Error message** > > Failed to save SampleComponent.cmp: Invalid definition for null:SampleClass: select id, email, mobilephone from User where ^ ERROR at Row:1:Column:12 No such column 'email' on entity 'User'. If you are attempting to use a custom field, be sure to append the '\_\_c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.: Source > > >
2019/05/06
[ "https://salesforce.stackexchange.com/questions/261222", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/25920/" ]
I also experienced this same issue in one my of custom lightning component. Where it was throwing the error message - There is no such column "ContactId" on User entity; After struggling the whole day I got a solution for this. **It is just to recompile APEX Classes.** **Steps to fix it:** 1. Login to Salesforce org 2. Go to setup. 3. Enter "Apex Classes" in the quick search. And then click "Apex Classes". 4. You will see "Compile all classes" link there, just go and press it. 5. Once it completes, go to the component and make the changes and save it. Now it should not show any error.
You need to recompile classes then it will work. When ever it doesn't save I compile all classes and i was able to save it. I suspect it might be due to summer 19 release patches.
30,788,175
I am working on improving my coding/ development skills and am new to using Ant. My goal is to be able to compile programs more complicated than "Hello World" from the command line. The program I am trying to compile and run uses libraries at that stored in an API, and I think I have included the correct path in my build.xml file, the code will compile and jar (when I use ant compile and ant jar commands), but when I run it I get an run time error. Here is my Ant build file: ``` <project name="Main" basedir="." default="main"> <property name="src.dir" value="src"/> <property name="build.dir" value="build"/> <property name="classes.dir" value="${build.dir}/classes"/> <property name="jar.dir" value="lib"/> <property name="main-class" value="myProject.Main"/> <target name="clean"> <delete dir="${classes.dir}"/> </target> <target name="compile" depends="clean"> <mkdir dir="${classes.dir}"/> <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false"> <classpath> <path location="${jar.dir}/dropbox-core-sdk-1.7.7.jar"/> <path location="${jar.dir}/jackson-core-2.2.4.jar"/> </classpath> </javac> </target> <target name="jar" depends="compile"> <mkdir dir="${jar.dir}"/> <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}"> <manifest> <attribute name="Main-Class" value="${main-class}"/> </manifest> </jar> </target> <target name="run" depends="jar"> <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/> </target> <target name="clean-build" depends="clean,jar"/> <target name="main" depends="clean,run"/> ``` this generates the following errors: ``` Buildfile: /Users/Phil/Documents/Java workspace/DropBoxProgram/build.xml clean: [delete] Deleting directory /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes compile: [mkdir] Created dir: /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes [javac] Compiling 7 source files to /Users/Phil/Documents/Java workspace/DropBoxProgram/build/classes jar: [jar] Building jar: /Users/Phil/Documents/Java workspace/DropBoxProgram/lib/Main.jar run: [java] Error: A JNI error has occurred, please check your installation and try again [java] Exception in thread "main" java.lang.NoClassDefFoundError: com/dropbox/core/DbxException [java] at java.lang.Class.getDeclaredMethods0(Native Method) [java] at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) [java] at java.lang.Class.privateGetMethodRecursive(Class.java:3048) [java] at java.lang.Class.getMethod0(Class.java:3018) [java] at java.lang.Class.getMethod(Class.java:1784) [java] at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544) [java] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526) [java] Caused by: java.lang.ClassNotFoundException: com.dropbox.core.DbxException [java] at java.net.URLClassLoader.findClass(URLClassLoader.java:381) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:424) [java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:357) [java] ... 7 more [java] Java Result: 1 BUILD SUCCESSFUL Total time: 1 second ``` I really appreciate any help!
2015/06/11
[ "https://Stackoverflow.com/questions/30788175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4972109/" ]
I had the same error. Turns out that Eclipse was using a symlink in the Eclipse setup for Ant Home (external ant installation). I solved it by changing Eclipse's Ant Home to a definitive location. In Eclipse `Window`->`Preferences` then `Ant`->`Runtime` then click on the `Ant Home...` button on the right and choose the correct Ant install directory.
You compiled with the classpath set to the `dropbox-core-sdk-1.7.7.jar` jar, but you didn't *run* the code with that classpath. You need to do the same for the `java` task, otherwise the JVM won't find the third-party classes. ``` <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"> <classpath> <path location="${jar.dir}/dropbox-core-sdk-1.7.7.jar"/> <path location="${jar.dir}/jackson-core-2.2.4.jar"/> </classpath> </java> ```
29,293,464
I am working on a Javascript object exercise. My output is not what I expected. Please take a look at my code and give some advise. Here is the code: ``` function myFunction(name) { this.name = name; this.models = new Array(); this.add = function (brand){ this.models = brand; }; } var c = new myFunction ("pc"); c.add("HP"); c.add("DELL"); console.log(c.models); ``` The output is `"DELL"` My expected output is `["HP","DELL"]` Thank you so much for your help!
2015/03/27
[ "https://Stackoverflow.com/questions/29293464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3222088/" ]
Change the add function. You want to push the brand into the model. Not set the model to it. ``` this.add = function (brand){ this.models.push(brand); }; ```
To add something to an array, you should use the `.push()` method. Change your code to: ``` function myFunction(name) { this.name = name; this.models = new Array(); this.add = function (brand){ this.models.push(brand); }; } ``` P.S. It is customary to name such constructor type of functions starting with a capital letter.
50,054,890
I've been trying to change the font color of the status bar using Xamarin (where the Battery, Signal and Clock is)... Can somebody advice me how to do this? Thank you
2018/04/27
[ "https://Stackoverflow.com/questions/50054890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562775/" ]
I'm not sure what API level your trying to target, but if you can use API 23 specific stuff, you can add the following to your AppTheme styles.xml: ``` <item name="android:statusBarColor">@color/colorPrimaryDark</item> <item name="android:windowLightStatusBar">true</item> ``` when android:windowLightStatusBar is set to true, status bar text color will be able to be seen when the status bar color is white, and vice-versa when android:windowLightStatusBar is set to false, status bar text color will be designed to be seen when the status bar color is dark. Example: ``` <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!-- Status bar stuff. --> <item name="android:statusBarColor">@color/colorPrimaryDark</item> <item name="android:windowLightStatusBar">true</item> </style> ```
You can change it by changing "colorPrimaryDark" attiribute of "color.xml" file where under android native project.
50,054,890
I've been trying to change the font color of the status bar using Xamarin (where the Battery, Signal and Clock is)... Can somebody advice me how to do this? Thank you
2018/04/27
[ "https://Stackoverflow.com/questions/50054890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562775/" ]
``` if (Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M) { var activity = Activity; //your activity ref.. var needWhite = true; //your goal // Fetch the current flags. var flags = activity.Window.DecorView.SystemUiVisibility; // Update the SystemUiVisibility dependening on whether we want a Light or Dark theme. if (needWhite) { activity.Window.DecorView.SystemUiVisibility = flags | (StatusBarVisibility)SystemUiFlags.LightNavigationBar; } else { activity.Window.DecorView.SystemUiVisibility = flags ^ (StatusBarVisibility)SystemUiFlags.LightNavigationBar; } } ```
You can change it by changing "colorPrimaryDark" attiribute of "color.xml" file where under android native project.
50,054,890
I've been trying to change the font color of the status bar using Xamarin (where the Battery, Signal and Clock is)... Can somebody advice me how to do this? Thank you
2018/04/27
[ "https://Stackoverflow.com/questions/50054890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3562775/" ]
I'm not sure what API level your trying to target, but if you can use API 23 specific stuff, you can add the following to your AppTheme styles.xml: ``` <item name="android:statusBarColor">@color/colorPrimaryDark</item> <item name="android:windowLightStatusBar">true</item> ``` when android:windowLightStatusBar is set to true, status bar text color will be able to be seen when the status bar color is white, and vice-versa when android:windowLightStatusBar is set to false, status bar text color will be designed to be seen when the status bar color is dark. Example: ``` <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!-- Status bar stuff. --> <item name="android:statusBarColor">@color/colorPrimaryDark</item> <item name="android:windowLightStatusBar">true</item> </style> ```
``` if (Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M) { var activity = Activity; //your activity ref.. var needWhite = true; //your goal // Fetch the current flags. var flags = activity.Window.DecorView.SystemUiVisibility; // Update the SystemUiVisibility dependening on whether we want a Light or Dark theme. if (needWhite) { activity.Window.DecorView.SystemUiVisibility = flags | (StatusBarVisibility)SystemUiFlags.LightNavigationBar; } else { activity.Window.DecorView.SystemUiVisibility = flags ^ (StatusBarVisibility)SystemUiFlags.LightNavigationBar; } } ```
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
calc.awk: ``` BEGIN { FS="}{"; # split lines by '}{' e=0; # set variable 'e' to 0 g=0; # set variable 'g' to 0 } /Einleitung/ { e=$3; } # 'Einleitung' matches, extract the page /Grundlagen/ { g=$3;} # 'Grundlagen' matches, extract the page END { print g-e; # print difference } ``` you can call it via: ``` $> awk -f calc.awk < in.txt ``` it will print `8`. you could store that number in a bash-variable like this: ``` $> nr=`awk -f calc.awk < in.txt` ``` if you need it more tight you could also rewrite `calc.awk` to be not a separate file but a one-line: ``` $> nr=`awk 'BEGIN{FS="}{";g=0;e=0}/Einleitung/{e=$3;}/Grundlagen/{g=$3;}END{print g-e;}' < in.txt` ```
``` $ DIFFERENCE=$(( $( cat FILENAME | grep Grundlagen | head -n1 | cut -c26-27 ) - $( cat FILENAME | grep Einleitung | head -n1 | cut -c26-27 ) )) $ echo $DIFFERENCE 8 ``` This requires that the lines always look exactly like this (i.e. no different headline), because of the `cut`.
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
~~I do not know if Mac OS X has awk. If it does, this should work:~~ This should work: ``` DIFFERENZ=$(awk 'BEGIN { FS="[{}]+" } { if ($4=="Einleitung") EINLEITUNG=$5 if ($4=="Grundlagen") GRUNDLAGEN=$5 } END { print GRUNDLAGEN-EINLEITUNG }' textfile) ``` How it works: * `FS="[{}]+"` sets the field separator to any combination of curly brackets. * `$4` refers to the third filed on the line (separated by curly brackets). * `DIFFERENZ=$(...)` evaluates the command `...` and stores the ouput in `DIFFERENZ`.
``` $ DIFFERENCE=$(( $( cat FILENAME | grep Grundlagen | head -n1 | cut -c26-27 ) - $( cat FILENAME | grep Einleitung | head -n1 | cut -c26-27 ) )) $ echo $DIFFERENCE 8 ``` This requires that the lines always look exactly like this (i.e. no different headline), because of the `cut`.
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
Pure bash 4.x, and shows the differences for every chapter: ``` unset page_last title_last page_cur title_cur re='\{chapter\}\{\{[[:digit:]]+\}([^}]+)\}\{([[:digit:]]+)\}' while read -r line; do if [[ $line =~ $re ]]; then title_cur=${BASH_REMATCH[1]} page_cur=${BASH_REMATCH[2]} diff=$((page_cur-page_last)) echo "${diff} pages between \"${title_last}\" and \"${title_cur}\"" title_last=$title_cur page_last=$page_cur fi done < "$myfile" ```
``` $ DIFFERENCE=$(( $( cat FILENAME | grep Grundlagen | head -n1 | cut -c26-27 ) - $( cat FILENAME | grep Einleitung | head -n1 | cut -c26-27 ) )) $ echo $DIFFERENCE 8 ``` This requires that the lines always look exactly like this (i.e. no different headline), because of the `cut`.
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
~~I do not know if Mac OS X has awk. If it does, this should work:~~ This should work: ``` DIFFERENZ=$(awk 'BEGIN { FS="[{}]+" } { if ($4=="Einleitung") EINLEITUNG=$5 if ($4=="Grundlagen") GRUNDLAGEN=$5 } END { print GRUNDLAGEN-EINLEITUNG }' textfile) ``` How it works: * `FS="[{}]+"` sets the field separator to any combination of curly brackets. * `$4` refers to the third filed on the line (separated by curly brackets). * `DIFFERENZ=$(...)` evaluates the command `...` and stores the ouput in `DIFFERENZ`.
calc.awk: ``` BEGIN { FS="}{"; # split lines by '}{' e=0; # set variable 'e' to 0 g=0; # set variable 'g' to 0 } /Einleitung/ { e=$3; } # 'Einleitung' matches, extract the page /Grundlagen/ { g=$3;} # 'Grundlagen' matches, extract the page END { print g-e; # print difference } ``` you can call it via: ``` $> awk -f calc.awk < in.txt ``` it will print `8`. you could store that number in a bash-variable like this: ``` $> nr=`awk -f calc.awk < in.txt` ``` if you need it more tight you could also rewrite `calc.awk` to be not a separate file but a one-line: ``` $> nr=`awk 'BEGIN{FS="}{";g=0;e=0}/Einleitung/{e=$3;}/Grundlagen/{g=$3;}END{print g-e;}' < in.txt` ```
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
calc.awk: ``` BEGIN { FS="}{"; # split lines by '}{' e=0; # set variable 'e' to 0 g=0; # set variable 'g' to 0 } /Einleitung/ { e=$3; } # 'Einleitung' matches, extract the page /Grundlagen/ { g=$3;} # 'Grundlagen' matches, extract the page END { print g-e; # print difference } ``` you can call it via: ``` $> awk -f calc.awk < in.txt ``` it will print `8`. you could store that number in a bash-variable like this: ``` $> nr=`awk -f calc.awk < in.txt` ``` if you need it more tight you could also rewrite `calc.awk` to be not a separate file but a one-line: ``` $> nr=`awk 'BEGIN{FS="}{";g=0;e=0}/Einleitung/{e=$3;}/Grundlagen/{g=$3;}END{print g-e;}' < in.txt` ```
Pure bash 4.x, and shows the differences for every chapter: ``` unset page_last title_last page_cur title_cur re='\{chapter\}\{\{[[:digit:]]+\}([^}]+)\}\{([[:digit:]]+)\}' while read -r line; do if [[ $line =~ $re ]]; then title_cur=${BASH_REMATCH[1]} page_cur=${BASH_REMATCH[2]} diff=$((page_cur-page_last)) echo "${diff} pages between \"${title_last}\" and \"${title_cur}\"" title_last=$title_cur page_last=$page_cur fi done < "$myfile" ```
367,132
I have a text file which contains (among others) the following lines: ``` {chapter}{{1}Einleitung}{27}{chapter.1} {chapter}{{2}Grundlagen}{35}{chapter.2} ``` How can I * get the 2 lines from this text file (they will always contain `}Einleitung` resp. `}Grundlagen}` and * extract the 2 page numbers (in this case 27 and 35), * calculate the difference `35-27 = 8` and * save the difference (`8`) of the two numbers in a variable Perhaps with a bash script in Mac OS X?
2011/12/12
[ "https://superuser.com/questions/367132", "https://superuser.com", "https://superuser.com/users/92184/" ]
~~I do not know if Mac OS X has awk. If it does, this should work:~~ This should work: ``` DIFFERENZ=$(awk 'BEGIN { FS="[{}]+" } { if ($4=="Einleitung") EINLEITUNG=$5 if ($4=="Grundlagen") GRUNDLAGEN=$5 } END { print GRUNDLAGEN-EINLEITUNG }' textfile) ``` How it works: * `FS="[{}]+"` sets the field separator to any combination of curly brackets. * `$4` refers to the third filed on the line (separated by curly brackets). * `DIFFERENZ=$(...)` evaluates the command `...` and stores the ouput in `DIFFERENZ`.
Pure bash 4.x, and shows the differences for every chapter: ``` unset page_last title_last page_cur title_cur re='\{chapter\}\{\{[[:digit:]]+\}([^}]+)\}\{([[:digit:]]+)\}' while read -r line; do if [[ $line =~ $re ]]; then title_cur=${BASH_REMATCH[1]} page_cur=${BASH_REMATCH[2]} diff=$((page_cur-page_last)) echo "${diff} pages between \"${title_last}\" and \"${title_cur}\"" title_last=$title_cur page_last=$page_cur fi done < "$myfile" ```
66,559,622
I want to update some data from the DB, so I added this Controller method: ``` public function updateAnswer(Answer $anss) { $validate_data = Validator::make(request()->all(),[ 'answer' => 'required' ])->validated(); $answer = Answer::findOrFail($anss); $answer->update($validate_data); return back(); } ``` Now the problem is I get this error: ``` Method Illuminate\Database\Eloquent\Collection::update does not exist. ``` So how to solve this issue?
2021/03/10
[ "https://Stackoverflow.com/questions/66559622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You are already resolving `$anss` using [route-model binding](https://laravel.com/docs/8.x/routing#route-model-binding). ``` public function updateAnswer(Answer $anss) ``` You are trying to call `findOrFail` with a model as an argument, which since `Model` implements `Arrayable` will return a `Collection`, thus breaking the update call. See `Illuminate\Database\Eloquent\Builder` findOrFail -> find -> findMany -> `return $this->whereKey($ids)->get($columns);`. Try: ``` public function updateAnswer(Answer $anss) { $validate_data = Validator::make(request()->all(),[ 'answer' => 'required' ])->validated(); $anss->update($validate_data); return back(); } ```
`$anss` is already an Answer object so you do not need to query it from the database. ``` $anss->answer = $validate_data['answer']; $anss->save(); ``` or ``` Answer::where('id', $anss->id) ->update($validate_data); ```
4,592,363
I am developing an RSS-reader-type application. I am toying with the possibility of using a normal TableView application but showing the articles as a film-strip. I am mainly thinking for an iPad application (but possible it works on the smaller iPhone as well). The idea is to have the cells passing/scrolling across the screen using swipe touches (but horizontal, and not vertical as with the normal TableView). They will be some-kind of miniatures of the full article, and when tapped (or with multi-touch zoom to have better control) can be enlarged to read. Then can then just be be moved on as soon as the user has seen enough of it. Does anybody know if there is an easy way of accomplishing something like that?
2011/01/04
[ "https://Stackoverflow.com/questions/4592363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542664/" ]
The most obvious solution that springs to mind would be to use a UIScrollView, as this will provide the inertial effects, etc. for free - all you'd have to do it populate it with the relevant sub-views. (UITableView's actually use a UIScrollView.) For more information and sample code, see Apple's [UIScrollView docs](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIScrollView_Class/Reference/UIScrollView.html).
If you want horizontal scrolling, take a look at Jeremy Tregunna’s [JScrollingRow](http://codaset.com/jer/jscrollingrow). It’s open source under a public domain licence.
504,060
If a body goes to the deep space then what is the temperature of that body? At that point of space is colder than the body, then the body also maintain temperature if not then what will be happen?
2019/09/21
[ "https://physics.stackexchange.com/questions/504060", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/242992/" ]
There is a geometric picture of the electromagnetic field in terms of "warps and curves," as you put it. This picture is in precise analogy to that general relativity, although it involves different mathematical objects with different physical interpretations. In general relativity, the "warps and curves" in spacetime are described mathematically by what is called the curvature tensor of spacetime. With the curvature tensor, we can determine the gravitational force on particles. Einstein's equations tell us that the curvature tensor is related to the distribution of matter and energy in spacetime. In electromagnetism, we can relate electric and magnetic forces to a curvature tensor in a similar way. However, the curvature tensor in the case of electromagnetism is a fundamentally different object both mathematically and physically. It does not describe the curvature of spacetime. Instead, it describes the curvature of a kind of "internal" space that is attached to the points of spacetime. (Mathematically, this "internal" space is a called a [fiber bundle](https://en.wikipedia.org/wiki/Fiber_bundle). Physically, the study of such spaces is called [gauge theory](https://en.wikipedia.org/wiki/Gauge_theory).) Just like Einstein's equations relate the curvature of spacetime to the presence of energy and matter, Maxwell's equations relate the electromagnetic curvature to the presence of electromagnetic charges and currents.
You cannot explain electric and magnetic fields as curved spacetime. Gravity is different. Gravity affects everything - electrons, protons, neutrons, and so on. Even light from a distant start is bent by the sun's gravity as it passes close to the surface. Gravity is a distortion of times and distances. Clocks run a little slower near the Sun. The distance to the center of the Sun is a little farther than you would expect from measuring the circumference. Anything in the region near Sun is affected by these distortions. An object like the Earth follows what seems to be a straight line, but is actually a curve. The result is an attraction toward the Sun. An electric field from an proton in the nucleus of an atom will attract an electron. It will repel a proton. A neutron or light will not feel a force at all. You can't explain an electric field as a distortion of space and time that makes things follow a curved path if some things do and others don't.
10,789,410
I am making a website in Joomla. And on my front page I have some images, which are links. I want these images a's to get a slightly green effect, like opacity + green and stil have the original images below. Is this possible to do with only css? I can get the opacity to work, but not the green color. Hope some one can help me. [Here is my site. it is the the small images under "Referencer" and "Nyheder"](http://martinehlers.dk)
2012/05/28
[ "https://Stackoverflow.com/questions/10789410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089353/" ]
This is doable with CSS. The main trick is that the links currently aren't surrounding the img block because their display type is inline. Assuming the following HTML: ``` <a href="#" class="greenish"><img src="..." /></a> ``` This is the CSS you need: ``` a.greenish { background: green; display: inline-block; } a.greenish img { opacity: 0.5; } ``` Adjust green and opacity to taste, obviously. See this [lovely jsfiddle](http://jsfiddle.net/UKXmy/3/) for an example. Note that this includes addition CSS in case you only want it to turn green when hovered.
You won't be able to do what you want with pure CSS easily. There is no "overlay" in CSS. You can manipulate the background color/opacity, but the image would always be on top of that so it would not achieve the effect you want. What you will need to do is to make the image the background of the A, then change the background do a similar image with the effect already applied. The images are small so you could easily make them sprites with the over look all in the same image. I did exactly this on the social icons at the top of my company website - <http://www.bnrbranding.com/>
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
you can that ``` #include <iostream> template<typename T> struct Facility { template<T head,T ... list> struct List { static void print() { std::cout<<"\"" << head; ((std::cout << " " << list), ...); std::cout<<"\""; } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ``` the fold expression `((std::cout << " " << list), ...)` will expands to `((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)`
In general, you use recursion for tasks like this. You have to define what happens when there are 2 or more and 1 elements in the list and recursively fall back to those definitions: ``` template <int ...> struct List; template <int First, int Second, int ... More> struct List { static void print() { std::cout << First << " "; List<Second, More ...>::print(); } }; template <int Last> struct List { static void print() { std::cout << Last; } }; ```
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
In general, you use recursion for tasks like this. You have to define what happens when there are 2 or more and 1 elements in the list and recursively fall back to those definitions: ``` template <int ...> struct List; template <int First, int Second, int ... More> struct List { static void print() { std::cout << First << " "; List<Second, More ...>::print(); } }; template <int Last> struct List { static void print() { std::cout << Last; } }; ```
You can reuse `print()` to achieve this behaviour. Afterall you are doing a `fold` operation which is by definition resursive. [Live Demo](https://wandbox.org/permlink/qLg7dneQhB2nrRLR) ``` template<T head,T ... rest_of_pack> struct List<head , rest_of_pack...> { static void print_() { std::cout<<head<<" "; List<rest_of_pack...>::print(); } }; ``` If you want to process many elements this way you might run into problems with template depth (gcc for instance has a limit of `900`). Lucky for you you can use the `-ftemplate-depth=` option to tweak this behaviour. You can compile with `-ftemplate-depth=100000` and make it work. Note that compilation time will skyrocket (most likely) or in thhe worst case you run out of memory.
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
In general, you use recursion for tasks like this. You have to define what happens when there are 2 or more and 1 elements in the list and recursively fall back to those definitions: ``` template <int ...> struct List; template <int First, int Second, int ... More> struct List { static void print() { std::cout << First << " "; List<Second, More ...>::print(); } }; template <int Last> struct List { static void print() { std::cout << Last; } }; ```
Not perfectly aligned with the question but I think may be useful putting here a solution based on fold expressions that generates a string from string-like arguments that should minimize dynamic memory allocations: ```cpp #include <iostream> #include <concepts> // std::convertible_to #include <string> #include <string_view> using namespace std::literals; template<std::convertible_to<std::string_view>... Args> [[nodiscard]] std::string mystrconcat(Args&&... args) { std::string s; const std::size_t totsiz = sizeof...(args) + (std::size(args) + ...); s.reserve(totsiz); ((s+=args, s+=' '), ...); if(!s.empty()) s.resize(s.size()-1); // Get rid of the trailing delimiter? return s; } int main() { std::cout << '\"' << mystrconcat("aa"s,"bb"sv,"ccc") << '\"' << '\n'; } ```
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
you can that ``` #include <iostream> template<typename T> struct Facility { template<T head,T ... list> struct List { static void print() { std::cout<<"\"" << head; ((std::cout << " " << list), ...); std::cout<<"\""; } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ``` the fold expression `((std::cout << " " << list), ...)` will expands to `((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)`
You can reuse `print()` to achieve this behaviour. Afterall you are doing a `fold` operation which is by definition resursive. [Live Demo](https://wandbox.org/permlink/qLg7dneQhB2nrRLR) ``` template<T head,T ... rest_of_pack> struct List<head , rest_of_pack...> { static void print_() { std::cout<<head<<" "; List<rest_of_pack...>::print(); } }; ``` If you want to process many elements this way you might run into problems with template depth (gcc for instance has a limit of `900`). Lucky for you you can use the `-ftemplate-depth=` option to tweak this behaviour. You can compile with `-ftemplate-depth=100000` and make it work. Note that compilation time will skyrocket (most likely) or in thhe worst case you run out of memory.
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
you can that ``` #include <iostream> template<typename T> struct Facility { template<T head,T ... list> struct List { static void print() { std::cout<<"\"" << head; ((std::cout << " " << list), ...); std::cout<<"\""; } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ``` the fold expression `((std::cout << " " << list), ...)` will expands to `((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)`
If you need space only between numbers (and not after the last or before the first too), you might do: ``` template <std::size_t... Is> void print_seq(std::index_sequence<Is...>) { const char* sep = ""; (((std::cout << sep << Is), sep = " "), ...); } ``` [Demo](http://coliru.stacked-crooked.com/a/0ed85128df8518dc) (It is similar to my ["runtime version"](https://stackoverflow.com/a/35373017/2684539)) for regular containers with for-loop.
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
you can that ``` #include <iostream> template<typename T> struct Facility { template<T head,T ... list> struct List { static void print() { std::cout<<"\"" << head; ((std::cout << " " << list), ...); std::cout<<"\""; } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ``` the fold expression `((std::cout << " " << list), ...)` will expands to `((std::cout << " " << list1), (std::cout << " " << list2), (std::cout << " " << list3)...)`
Not perfectly aligned with the question but I think may be useful putting here a solution based on fold expressions that generates a string from string-like arguments that should minimize dynamic memory allocations: ```cpp #include <iostream> #include <concepts> // std::convertible_to #include <string> #include <string_view> using namespace std::literals; template<std::convertible_to<std::string_view>... Args> [[nodiscard]] std::string mystrconcat(Args&&... args) { std::string s; const std::size_t totsiz = sizeof...(args) + (std::size(args) + ...); s.reserve(totsiz); ((s+=args, s+=' '), ...); if(!s.empty()) s.resize(s.size()-1); // Get rid of the trailing delimiter? return s; } int main() { std::cout << '\"' << mystrconcat("aa"s,"bb"sv,"ccc") << '\"' << '\n'; } ```
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
If you need space only between numbers (and not after the last or before the first too), you might do: ``` template <std::size_t... Is> void print_seq(std::index_sequence<Is...>) { const char* sep = ""; (((std::cout << sep << Is), sep = " "), ...); } ``` [Demo](http://coliru.stacked-crooked.com/a/0ed85128df8518dc) (It is similar to my ["runtime version"](https://stackoverflow.com/a/35373017/2684539)) for regular containers with for-loop.
You can reuse `print()` to achieve this behaviour. Afterall you are doing a `fold` operation which is by definition resursive. [Live Demo](https://wandbox.org/permlink/qLg7dneQhB2nrRLR) ``` template<T head,T ... rest_of_pack> struct List<head , rest_of_pack...> { static void print_() { std::cout<<head<<" "; List<rest_of_pack...>::print(); } }; ``` If you want to process many elements this way you might run into problems with template depth (gcc for instance has a limit of `900`). Lucky for you you can use the `-ftemplate-depth=` option to tweak this behaviour. You can compile with `-ftemplate-depth=100000` and make it work. Note that compilation time will skyrocket (most likely) or in thhe worst case you run out of memory.
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
You can reuse `print()` to achieve this behaviour. Afterall you are doing a `fold` operation which is by definition resursive. [Live Demo](https://wandbox.org/permlink/qLg7dneQhB2nrRLR) ``` template<T head,T ... rest_of_pack> struct List<head , rest_of_pack...> { static void print_() { std::cout<<head<<" "; List<rest_of_pack...>::print(); } }; ``` If you want to process many elements this way you might run into problems with template depth (gcc for instance has a limit of `900`). Lucky for you you can use the `-ftemplate-depth=` option to tweak this behaviour. You can compile with `-ftemplate-depth=100000` and make it work. Note that compilation time will skyrocket (most likely) or in thhe worst case you run out of memory.
Not perfectly aligned with the question but I think may be useful putting here a solution based on fold expressions that generates a string from string-like arguments that should minimize dynamic memory allocations: ```cpp #include <iostream> #include <concepts> // std::convertible_to #include <string> #include <string_view> using namespace std::literals; template<std::convertible_to<std::string_view>... Args> [[nodiscard]] std::string mystrconcat(Args&&... args) { std::string s; const std::size_t totsiz = sizeof...(args) + (std::size(args) + ...); s.reserve(totsiz); ((s+=args, s+=' '), ...); if(!s.empty()) s.resize(s.size()-1); // Get rid of the trailing delimiter? return s; } int main() { std::cout << '\"' << mystrconcat("aa"s,"bb"sv,"ccc") << '\"' << '\n'; } ```
51,281,811
I am using a fold expression to print elements in a variadic pack, but how do I get a space in between each element? Currently the output is "1 234", the desired output is "1 2 3 4" ``` template<typename T, typename Comp = std::less<T> > struct Facility { template<T ... list> struct List { static void print() { } }; template<T head,T ... list> struct List<head,list...> { static void print() { std::cout<<"\""<<head<<" "; (std::cout<<...<<list); } }; }; template<int ... intlist> using IntList = typename Facility<int>::List<intlist...>; int main() { using List1 = IntList<1,2,3,4>; List1::print(); } ```
2018/07/11
[ "https://Stackoverflow.com/questions/51281811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9917671/" ]
If you need space only between numbers (and not after the last or before the first too), you might do: ``` template <std::size_t... Is> void print_seq(std::index_sequence<Is...>) { const char* sep = ""; (((std::cout << sep << Is), sep = " "), ...); } ``` [Demo](http://coliru.stacked-crooked.com/a/0ed85128df8518dc) (It is similar to my ["runtime version"](https://stackoverflow.com/a/35373017/2684539)) for regular containers with for-loop.
Not perfectly aligned with the question but I think may be useful putting here a solution based on fold expressions that generates a string from string-like arguments that should minimize dynamic memory allocations: ```cpp #include <iostream> #include <concepts> // std::convertible_to #include <string> #include <string_view> using namespace std::literals; template<std::convertible_to<std::string_view>... Args> [[nodiscard]] std::string mystrconcat(Args&&... args) { std::string s; const std::size_t totsiz = sizeof...(args) + (std::size(args) + ...); s.reserve(totsiz); ((s+=args, s+=' '), ...); if(!s.empty()) s.resize(s.size()-1); // Get rid of the trailing delimiter? return s; } int main() { std::cout << '\"' << mystrconcat("aa"s,"bb"sv,"ccc") << '\"' << '\n'; } ```
26,970,250
I'm trying to get my head around the following sql problem: I have an `ACTIONS` table that contains the following: ``` ------------------------------------ | ACTIONS | |----------------------------------| | ID | | GROUP_ID | | TABLENAME | | FEATURE_ID | ------------------------------------ ``` And a bunch of tables that look like this: ``` ------------------------------------ | GRASS or SAND or ... | |----------------------------------| | FEATURE_ID | | POSITION | |+(more columns depending on table)| ------------------------------------ ``` Now the `ACTIONS`.`TABLENAME` points to a certain table (for example: `GRASS` or `SAND` or `...`) **All** these tables have a column called `position` I would now like to query all actions from the `ACTIONS` table with their respective `POSITION` values. How can i tell the query to go and look for the position values in their correct tables? Thank you for pointing me in the right direction! Max
2014/11/17
[ "https://Stackoverflow.com/questions/26970250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3425703/" ]
The `fwrite` function writes a *chunk of memory* to a file and your chunk of memory in this case is an integer in *binary* form. For example, the decimal integer `314,159` (`4CB2F16`) in 32-bit big-endian format would be stored in memory as the hex digits: ```none +----+----+----+----+ | 00 | 04 | CB | 2F | +----+----+----+----+ ``` So writing that memory block to a file will generally not result in anything readable by a human, unless you have an unusual number like `1348565002` or `175661392` (depending on the endian-ness). In order to write your integer in human-readable format, you just use `fprintf`, *very* similar to the way you used it to print to standard output: ``` fprintf (fp, "%d\t", j); printf ("%d\t", j ) ; ```
Your problem lies with the fact that *you have used* the **fwrite** function instead of the **fprintf** function. The fwrite function is a function commonly used to write binary data into a file. The data which we read in a file is generally ASCII. ASCII text uses 1 byte (8 bits or 8 0/1 places to fill) to represent each character. Now when you put binary data into a file you are placing 1's or 0's one by one into the file. Now when you opened the file each of the 1's and 0's got converted into their corresponding ASCII value. To use the fprintf function, it is exactly similar to the printf function: `fprintf(fp,"%d",j);` If you wish for more info: <http://www.c4learn.com/c-programming/c-reference/fwrite-function/> <http://www.c4learn.com/c-programming/c-reference/fprintf-function/>
27,027,447
So for my responsive site, when in the mobile-scale, I have an "Email Us" button that the user can tap to open up the email client. Originally this was a simple mailto:, but I've since changed it, but as I wanted to keep the changes to an absolute minimum, I decided upon the following method: Replace the `"mailto:example@email.com` with a link to `redirect.php` in my site directory. All that is in `redirect.php` is this: ``` <?php header('Location: mailto:example@email.com'); exit(); ?> ``` And it behaves totally fine! That was the only spot where the email address was present in the HTML or JS, so I felt like it would be overkill to do a complete encryption of the email. So my question is this: Is this enough to effectively keep spam-bots out? If no, what extra steps are necessary? Obviously you can't 100% stop them from happening, but I figured as the actual address is only on the server-side, that would significantly reduce the risk. Right?
2014/11/19
[ "https://Stackoverflow.com/questions/27027447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352022/" ]
Yes, the java access modifier's define a classes boundaries and to some extent a package's boundaries but a module is larger than a single class or package. You may want to see <http://www.slideshare.net/bjhargrave/why-osgi> which explains the progression of encapsulation through classes and onto modules.
I thought about it a little bit, and realized that there are certain privacy restrictions that OSGI's export mechanism can impose that plain old Java access modifiers cannot. See the diagrams below. ![enter image description here](https://i.stack.imgur.com/ncqoP.png) ![enter image description here](https://i.stack.imgur.com/iIZH1.png) Notice how in Plain Old Java, a public class is visible (indicated by a green arrow) to all classes no matter what. In OSGI, a public class is visible to all classes (including classes in another bundle) ONLY if it is part of an exported package. Note:The "protected classes" in the diagram are really just classes without any modifier (since there is no "protected" modifier for classes, just for fields and methods) Edit: I'm adding this relevant quote from here: <http://njbartlett.name/files/osgibook_preview_20091217.pdf> > > "A public class is visible to every class in every other package; a default access > class is only available to other classes within the same package. > There is something missing here. The above access modifiers relate to visibility > across packages, but the unit of deployment in Java is not a package, it is a > JAR file. Most JAR files offering non-trivial APIs contain more than one > package (HttpClient has eight), and generally the classes within the JAR need > to have access to the classes in other packages of the same JAR. Unfortunately > that means we must make most of our classes public, because that is the only > access modifier which makes classes visible across package boundaries. > As a consequence, all those classes declared public are accessible to clients > outside the JAR as well. Therefore the whole JAR is effectively public API, > even the parts that we would prefer to keep hidden. This is another symptom > of the lack of any runtime representation for JAR files." > > >
27,027,447
So for my responsive site, when in the mobile-scale, I have an "Email Us" button that the user can tap to open up the email client. Originally this was a simple mailto:, but I've since changed it, but as I wanted to keep the changes to an absolute minimum, I decided upon the following method: Replace the `"mailto:example@email.com` with a link to `redirect.php` in my site directory. All that is in `redirect.php` is this: ``` <?php header('Location: mailto:example@email.com'); exit(); ?> ``` And it behaves totally fine! That was the only spot where the email address was present in the HTML or JS, so I felt like it would be overkill to do a complete encryption of the email. So my question is this: Is this enough to effectively keep spam-bots out? If no, what extra steps are necessary? Obviously you can't 100% stop them from happening, but I figured as the actual address is only on the server-side, that would significantly reduce the risk. Right?
2014/11/19
[ "https://Stackoverflow.com/questions/27027447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352022/" ]
**Short answer** In a modularized system it is very important to separate API from implementation where only API is exported. You cannot do that based on class modifiers. Other very important part of OSGi is the versioning of packages. You have to assign version only to those packages that are exported. **Long answer** A more prcise answer to this question is available at the following wiki post that was written by Neil Bartlett: <http://wiki.osgi.org/wiki/Export_Only_APIs> **Similar question** Why do we need object-orientation when functions are already available in structured languages? Are not the functions used to separate logical units of an algorithm?
I thought about it a little bit, and realized that there are certain privacy restrictions that OSGI's export mechanism can impose that plain old Java access modifiers cannot. See the diagrams below. ![enter image description here](https://i.stack.imgur.com/ncqoP.png) ![enter image description here](https://i.stack.imgur.com/iIZH1.png) Notice how in Plain Old Java, a public class is visible (indicated by a green arrow) to all classes no matter what. In OSGI, a public class is visible to all classes (including classes in another bundle) ONLY if it is part of an exported package. Note:The "protected classes" in the diagram are really just classes without any modifier (since there is no "protected" modifier for classes, just for fields and methods) Edit: I'm adding this relevant quote from here: <http://njbartlett.name/files/osgibook_preview_20091217.pdf> > > "A public class is visible to every class in every other package; a default access > class is only available to other classes within the same package. > There is something missing here. The above access modifiers relate to visibility > across packages, but the unit of deployment in Java is not a package, it is a > JAR file. Most JAR files offering non-trivial APIs contain more than one > package (HttpClient has eight), and generally the classes within the JAR need > to have access to the classes in other packages of the same JAR. Unfortunately > that means we must make most of our classes public, because that is the only > access modifier which makes classes visible across package boundaries. > As a consequence, all those classes declared public are accessible to clients > outside the JAR as well. Therefore the whole JAR is effectively public API, > even the parts that we would prefer to keep hidden. This is another symptom > of the lack of any runtime representation for JAR files." > > >
21,260,272
I need a Set object type in my code. But in some browsers such object type [already exists](http://msdn.microsoft.com/en-us/library/ie/dn251547%28v=vs.94%29.aspx) and my class and standard are compatible by members. How I can declare my class only if it not exists in browser script host ? For example: ``` if (typeof Set === 'undefined' ) { function Set() { // object initialization code ... } } ``` It's not works because internal Set function object is not global.
2014/01/21
[ "https://Stackoverflow.com/questions/21260272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987850/" ]
The most robust way is probably to use this: ``` if (!("Set" in window)) { window.Set = function () { ... } } ``` In the chance that `window.Set` is defined, but its value is `undefined`, this will correctly see that it has been defined, unlike checking the value, or using `typeof`. If you need to run in a situation where `window` is not the global object, you can insert this line at the very top of your script: ``` var global = this; ``` Then you can use `global` instead of `window`.
Something like this should work. ``` if (window.Set === undefined) { window.Set = MySet; } ```
21,260,272
I need a Set object type in my code. But in some browsers such object type [already exists](http://msdn.microsoft.com/en-us/library/ie/dn251547%28v=vs.94%29.aspx) and my class and standard are compatible by members. How I can declare my class only if it not exists in browser script host ? For example: ``` if (typeof Set === 'undefined' ) { function Set() { // object initialization code ... } } ``` It's not works because internal Set function object is not global.
2014/01/21
[ "https://Stackoverflow.com/questions/21260272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987850/" ]
The most robust way is probably to use this: ``` if (!("Set" in window)) { window.Set = function () { ... } } ``` In the chance that `window.Set` is defined, but its value is `undefined`, this will correctly see that it has been defined, unlike checking the value, or using `typeof`. If you need to run in a situation where `window` is not the global object, you can insert this line at the very top of your script: ``` var global = this; ``` Then you can use `global` instead of `window`.
Simply use [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) to determine whether it is `undefined`: ``` if (typeof window.Set === 'undefined') ... ```
21,260,272
I need a Set object type in my code. But in some browsers such object type [already exists](http://msdn.microsoft.com/en-us/library/ie/dn251547%28v=vs.94%29.aspx) and my class and standard are compatible by members. How I can declare my class only if it not exists in browser script host ? For example: ``` if (typeof Set === 'undefined' ) { function Set() { // object initialization code ... } } ``` It's not works because internal Set function object is not global.
2014/01/21
[ "https://Stackoverflow.com/questions/21260272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/987850/" ]
The most robust way is probably to use this: ``` if (!("Set" in window)) { window.Set = function () { ... } } ``` In the chance that `window.Set` is defined, but its value is `undefined`, this will correctly see that it has been defined, unlike checking the value, or using `typeof`. If you need to run in a situation where `window` is not the global object, you can insert this line at the very top of your script: ``` var global = this; ``` Then you can use `global` instead of `window`.
A simple truthiness test will suffice: ``` if (!window.Set) { window.Set = ... ```
47,975,191
I've been reading on compiler optimizations vs CPU optimizations, and `volatile` vs memory barriers. One thing which isn't clear to me is that my current understanding is that CPU optimizations and compiler optimizations are orthogonal. I.e. can occur independently of each other. However, the article [volatile considered harmful](https://www.kernel.org/doc/html/v4.12/process/volatile-considered-harmful.html) makes the point that `volatile` should not be used. Linus's [post](http://yarchive.net/comp/linux/memory_barriers.html) makes similar claims. The main reasoning, IIUC, is that marking a variable as `volatile` disables *all* compiler optimizations when accessing that variable (i.e. even if they are not harmful), while still not providing protection against memory reorderings. Essentially, the main point is that it's not the *data* that should be handled with care, but rather a particular *access pattern* needs to be handled with care. Now, the [volatile considered harmful](https://www.kernel.org/doc/html/v4.12/process/volatile-considered-harmful.html) article gives the following example of a busy loop waiting for a flag: ``` while (my_variable != what_i_want) {} ``` and makes the point that the compiler can optimize the access to `my_variable` so that it only occurs once and not in a loop. The solution, so the article claims, is the following: ``` while (my_variable != what_i_want) cpu_relax(); ``` It is said that `cpu_relax` acts as a **compiler barrier** (earlier versions of the article said that it's a **memory barrier**). I have several gaps here: 1) Is the implication that gcc has special knowledge of the `cpu_relax` call, and that it translates to a hint to both the compiler *and* the CPU? 2) Is the same true for other instructions such as `smb_mb()` and the likes? 3) How does that work, given that `cpu_relax` is essentially defined as a C macro? If I manually expand `cpu_relax` will gcc still respect it as a compiler barrier? How can I know which calls are respected by gcc? 4) What is the scope of `cpu_relax` as far as gcc is concerned? In other words, what's the scope of reads that cannot be optimized by gcc when it sees the `cpu_relax` instruction? From the CPU's perspective, the scope is wide (memory barriers place a mark in the read or write buffer). I would guess gcc uses a smaller scope - perhaps the C scope?
2017/12/26
[ "https://Stackoverflow.com/questions/47975191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5154090/" ]
1. Yes, gcc has special knowledge of the semantics of `cpu_relax` or whatever it expands to, and must translate it to something for which the hardware will respect the semantics too. 2. Yes, any kind of memory fencing primitive needs special respect by the compiler and hardware. 3. Look at what the macro expands to, e.g. compile with "gcc -E" and examine the output. You'll have to read the compiler documentation to find out the semantics of the primitives. 4. The scope of a memory fence is as wide as the scope the compiler might move a load or store across. A non-optimizing compiler that never moves loads or stores across a subroutine call might not need to pay much attention to a memory fence that is represented as a subroutine call. An optimizing compiler that does interprocedural optimization across translation units would need to track a memory fence across a much bigger scope.
There are a number subtle questions related to cpu and smp concurrency in your questions which will require you to look at the kernel code. Here are some quick ideas to get you started on the research specifically for the x86 architecture. The idea is that you are trying to perform a concurrency operation where your kernel task (see kernel source sched.h for struct task\_struct) is in a tight loop comparing my\_variable with a local variable until it is changed by another kernel task (or change asynchronously by a hardware device!) This is a common pattern in the kernel. 1. The kernel has been ported to a number of architectures and each has a specific set of machine instructions to handle concurrency. For x86, cpu\_relax maps to the PAUSE machine instruction. It allows an x86 CPU to more efficiently run a spinlock so that the lock variable update is more readily visible by the spinning CPU. GCC will execute the function/macro just like any other function. If cpu\_relax is removed from the loop then gcc CAN consider the loop as non-functional and remove it. Look at the Intel X86 Software Manuals for the PAUSE instruction. 2. smp\_mb is an x86 memory fence instruction that flushes the memory cache. One CPU can change my\_variable in its cache but it will not be visible to other CPUs. smp\_mb provides on-demand cache coherency. Look at the Intel X86 Software Manuals for MFENCE/LFENCE instructions. Note that smp\_mb() flushes the CPU cache so it CAN be an expensive operation. Current Intel CPUs have huge caches (~6MB). 3. If you expand cpu\_relax on an x86, it will show **asm volatile("rep; nop" ::: "memory")**. This is NOT a compiler barrier but code that GCC will not optimize out. See the barrier macro, which is **asm volatile("": : : "memory")** for the GCC hint. 4. I'm not clear what you mean by "scope of cpu\_relax". Some possible ideas: It's the PAUSE machine instruction, similar to ADD or MOV. PAUSE will affect only the current CPU. PAUSE allows for more efficient cache coherency between CPUs. I just looked at the PAUSE instruction a little more - an additional property is it prevents the CPU from doing out-of-order memory speculation when leaving a tight loop/spinlock. I'm not clear what THAT means but I suppose it could briefly indicate a false value in a variable? Still a lot of questions....
64,085,488
I am trying to show results that I get from a SQL table, it is this: [![enter image description here](https://i.stack.imgur.com/HLtWC.png)](https://i.stack.imgur.com/HLtWC.png) what I want to do is show results 3 by 3, like this: [![enter image description here](https://i.stack.imgur.com/EGeWV.png)](https://i.stack.imgur.com/EGeWV.png) I mean a table for every 3 results that the "assigned\_bank" field matches, and if there are 4 results with the same number in "assigned\_bank", I also show it in that same table, that is; one table for each different "assigned\_bank" id. I've been trying most of the day and the closest thing I've come to is this: [![enter image description here](https://i.stack.imgur.com/yUCct.png)](https://i.stack.imgur.com/yUCct.png) This is my last code: ```html <?php $tables = sizeof($search) / 3; for ($i = 0; $i < $tables; $i++) { ?> <table class="table customers"> <thead class="thead-blue"> <tr> <th scope="col-xs-2">Name</th> <th scope="col-xs-2">Lastname</th> <th scope="col-xs-2">Bank ID</th> </tr> </thead> <tbody> <?php foreach ($search as $item){ echo '<tr align="left">'; echo '<td class="col-xs-2">' . $item["p_name"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["p_lastname"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["assigned_bank"] . '</td>' . "\r\n"; echo '</tr>'; } ?> </tbody> </table> <?php echo "\r\n"; } ?> ``` Thank you very much for any possible help or comments and thank you for taking the time to respond.
2020/09/27
[ "https://Stackoverflow.com/questions/64085488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441762/" ]
in `onChange` you need to call like this ``` onChange={(e) => { setValue(e.target.value); props.handleSliderChange(e.target.value); }} ``` since value is not updated instantly when you call `setValue(e.target.value);` , `value` will have previous value that you are passing in `props.handleSliderChang(value)` to know how `setState` works see this [answer](https://stackoverflow.com/a/41446620/7784354)
The issue is on the `onClick` callback of `FlightRange` `input`, see comments on code below ``` onChange = {(e) => { setValue(e.target.value); // this is async // therefore, the value you are passing here is not the same as e.target.value but simply the value before setting the state props.handleSliderChange(value); }} ``` So to fix this just refactor `props.handleSliderChange` argument to `e.target.value` ``` onChange = {(e) => { setValue(e.target.value); props.handleSliderChange(e.target.value); }} ```
64,085,488
I am trying to show results that I get from a SQL table, it is this: [![enter image description here](https://i.stack.imgur.com/HLtWC.png)](https://i.stack.imgur.com/HLtWC.png) what I want to do is show results 3 by 3, like this: [![enter image description here](https://i.stack.imgur.com/EGeWV.png)](https://i.stack.imgur.com/EGeWV.png) I mean a table for every 3 results that the "assigned\_bank" field matches, and if there are 4 results with the same number in "assigned\_bank", I also show it in that same table, that is; one table for each different "assigned\_bank" id. I've been trying most of the day and the closest thing I've come to is this: [![enter image description here](https://i.stack.imgur.com/yUCct.png)](https://i.stack.imgur.com/yUCct.png) This is my last code: ```html <?php $tables = sizeof($search) / 3; for ($i = 0; $i < $tables; $i++) { ?> <table class="table customers"> <thead class="thead-blue"> <tr> <th scope="col-xs-2">Name</th> <th scope="col-xs-2">Lastname</th> <th scope="col-xs-2">Bank ID</th> </tr> </thead> <tbody> <?php foreach ($search as $item){ echo '<tr align="left">'; echo '<td class="col-xs-2">' . $item["p_name"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["p_lastname"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["assigned_bank"] . '</td>' . "\r\n"; echo '</tr>'; } ?> </tbody> </table> <?php echo "\r\n"; } ?> ``` Thank you very much for any possible help or comments and thank you for taking the time to respond.
2020/09/27
[ "https://Stackoverflow.com/questions/64085488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441762/" ]
in `onChange` you need to call like this ``` onChange={(e) => { setValue(e.target.value); props.handleSliderChange(e.target.value); }} ``` since value is not updated instantly when you call `setValue(e.target.value);` , `value` will have previous value that you are passing in `props.handleSliderChang(value)` to know how `setState` works see this [answer](https://stackoverflow.com/a/41446620/7784354)
It because the child is having it's own life cycle since you are using `useState` in child. so whatever props you pass to your child, the child's state won't affected. plus you are passing incorrect value in `onChange` **Solution:** just use the props value directly on child (do not store in state): ``` export const FlightRange = (props) => { const { value, handleSliderChange } = props; return ( <> <input type='range' min={1000} max={50000} step="500" value={value} onChange={(e) => { handleSliderChange(e.target.value); }} /> <span>{value}</span> </> ); }; ```
64,085,488
I am trying to show results that I get from a SQL table, it is this: [![enter image description here](https://i.stack.imgur.com/HLtWC.png)](https://i.stack.imgur.com/HLtWC.png) what I want to do is show results 3 by 3, like this: [![enter image description here](https://i.stack.imgur.com/EGeWV.png)](https://i.stack.imgur.com/EGeWV.png) I mean a table for every 3 results that the "assigned\_bank" field matches, and if there are 4 results with the same number in "assigned\_bank", I also show it in that same table, that is; one table for each different "assigned\_bank" id. I've been trying most of the day and the closest thing I've come to is this: [![enter image description here](https://i.stack.imgur.com/yUCct.png)](https://i.stack.imgur.com/yUCct.png) This is my last code: ```html <?php $tables = sizeof($search) / 3; for ($i = 0; $i < $tables; $i++) { ?> <table class="table customers"> <thead class="thead-blue"> <tr> <th scope="col-xs-2">Name</th> <th scope="col-xs-2">Lastname</th> <th scope="col-xs-2">Bank ID</th> </tr> </thead> <tbody> <?php foreach ($search as $item){ echo '<tr align="left">'; echo '<td class="col-xs-2">' . $item["p_name"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["p_lastname"] . '</td>' . "\r\n"; echo '<td class="col-xs-2">' . $item["assigned_bank"] . '</td>' . "\r\n"; echo '</tr>'; } ?> </tbody> </table> <?php echo "\r\n"; } ?> ``` Thank you very much for any possible help or comments and thank you for taking the time to respond.
2020/09/27
[ "https://Stackoverflow.com/questions/64085488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6441762/" ]
The issue is on the `onClick` callback of `FlightRange` `input`, see comments on code below ``` onChange = {(e) => { setValue(e.target.value); // this is async // therefore, the value you are passing here is not the same as e.target.value but simply the value before setting the state props.handleSliderChange(value); }} ``` So to fix this just refactor `props.handleSliderChange` argument to `e.target.value` ``` onChange = {(e) => { setValue(e.target.value); props.handleSliderChange(e.target.value); }} ```
It because the child is having it's own life cycle since you are using `useState` in child. so whatever props you pass to your child, the child's state won't affected. plus you are passing incorrect value in `onChange` **Solution:** just use the props value directly on child (do not store in state): ``` export const FlightRange = (props) => { const { value, handleSliderChange } = props; return ( <> <input type='range' min={1000} max={50000} step="500" value={value} onChange={(e) => { handleSliderChange(e.target.value); }} /> <span>{value}</span> </> ); }; ```
3,815,606
The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$. So here's my attempt. First I find the normal vector: $\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$ And then I find its magnitude: $\frac{\sqrt{57}}{14\sqrt{2}}$ And then I take a half to it because 1/2 base times height for triangle area. But this isn't right. What am I doing wrong? Thank you in advance.
2020/09/05
[ "https://math.stackexchange.com/questions/3815606", "https://math.stackexchange.com", "https://math.stackexchange.com/users/752703/" ]
The points $P,Q,R$ are easily seen to be $P=(4,0,0),Q=(0,4,0),R=(0,0,7)$. By the symmetry in the $x-$ and $y-$coordinates, this is an isosceles triangle with base $PQ$ and height $TR$, where $T$ is the mid-point of $PQ$. Can you take it from there?
The process you're going through doesn't find the area of the correct triangle. Finding the x-, y-, and z-intercepts is actually quite simple, as they are the solutions to the equation of the plane with two of the three variables equal to $0$. $x/4+0/4+0/7=1$ implies the x-intercept is $(4,0,0)$. Similarly, the y- and z-intercepts are $(0,4,0)$ and $(0,0,7)$, respectively. Now you could use find $\overrightarrow{PQ}$ and $\overrightarrow{PR}$ and take half the magnitude of their cross product to find the area of the triangle.
3,815,606
The plane $/4+/4+/7=1$ intersects the $-$ , $ -$ , and $-$ axes in points $, , $. Find the area of the triangle $Δ$. So here's my attempt. First I find the normal vector: $\left\langle\frac{1}{4}+\frac{1}{4}+\frac{1}{7}\right\rangle$ And then I find its magnitude: $\frac{\sqrt{57}}{14\sqrt{2}}$ And then I take a half to it because 1/2 base times height for triangle area. But this isn't right. What am I doing wrong? Thank you in advance.
2020/09/05
[ "https://math.stackexchange.com/questions/3815606", "https://math.stackexchange.com", "https://math.stackexchange.com/users/752703/" ]
Points of intersection are $$P=(4,0,0)\quad Q=(0,4,0)\quad R=(0,0,7)\quad$$ then we can find the base and hight and then the area. Otherwise we can use [cross product](https://en.wikipedia.org/wiki/Triangle#Using_vectors) $$S=\frac12 \left|\vec{RP}\times \vec{RQ}\right|$$
The process you're going through doesn't find the area of the correct triangle. Finding the x-, y-, and z-intercepts is actually quite simple, as they are the solutions to the equation of the plane with two of the three variables equal to $0$. $x/4+0/4+0/7=1$ implies the x-intercept is $(4,0,0)$. Similarly, the y- and z-intercepts are $(0,4,0)$ and $(0,0,7)$, respectively. Now you could use find $\overrightarrow{PQ}$ and $\overrightarrow{PR}$ and take half the magnitude of their cross product to find the area of the triangle.