qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
1,079
This question has raised a debate within my organization with multiple points of view. Several Project Managers think that they are completely different things aiming for different results whereas other colleagues believe that both methodologies could be combined. I would be interested in understanding what makes PRINCE2 and SCRUM compatible and what makes them opponents. What are your thoughts?
2011/03/15
[ "https://pm.stackexchange.com/questions/1079", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/643/" ]
Absolutely! Prince 2 is on project level, as Scrum can be done on 'managing product delivery' level within PRINCE2. > > The Scrum process is all about > delivery. Fast and effective delivery > is key. Within PRINCE2 the delivery process is a black box. PRINCE2 is all about managing the project’s process. > > > ![enter image description here](https://i.stack.imgur.com/GnFo7.jpg) > > This makes Scrum a natural fit to the > PRINCE2 ‘Managing Product Delivery’ > process. This also makes PRINCE2 the > project management wrapper around > Scrum. I think this is a great > combination. > > > Here is more info on this: [whitebook](http://www.borselaer.org/index.php/2010/03/whitebook-prince2-combined-with-scrum/)
Probably, but I think it leads to idea-fall and Scrum factories. Project idea's and requirements come from people with the least knowledge, but are committed to on a project road-map. The Scrum team here is just an iterative factory. Instead of giving teams high-level [objectives](http://leanperformance.com/en/okr/what-is-okr/) and letting them learn and coming up with innovate solutions, what I think being Agile and Lean is all about. Although unrelated to Prince2. See [this video](https://www.youtube.com/watch?v=9dccd8lihpQ) of Marty Cagan about idea-fall, only the build steps are iterative. Not the product design, which often leads to failed products. [![enter image description here](https://i.stack.imgur.com/7NdQc.png)](https://i.stack.imgur.com/7NdQc.png) I like his idea of doing [Dual-track Scrum](http://svpg.com/dual-track-scrum/) to facilating the discovery and delivery process.
21,330,682
``` private void windowClosing(java.awt.event.WindowEvent evt) { int confirmed = JOptionPane.showConfirmDialog(null, "Exit Program?","EXIT",JOptionPane.YES_NO_OPTION); if(confirmed == JOptionPane.YES_OPTION) { dispose(); } } ``` I want to close program by pressing Close Window Button with confirmation...But when I choose "No" to back to my Jframe, it still helps me to exit the program???
2014/01/24
[ "https://Stackoverflow.com/questions/21330682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2126116/" ]
From what i understand you want something like this ``` addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { int confirmed = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the program?", "Exit Program Message Box", JOptionPane.YES_NO_OPTION); if (confirmed == JOptionPane.YES_OPTION) { dispose(); } } }); ``` If you want to use it on some button do similiar function to button. Put listener on it and do same. But I'm not sure if I get your question right. But If you want to use button use **ActionListener** and **action performed** method. check question - [Java - Message when closing JFrame Window](https://stackoverflow.com/questions/13419947/java-message-when-closing-jframe-window)
```java JFrame frame = new JFrame(); // ... frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { int resp = JOptionPane.showConfirmDialog(frame, "Are you sure you want to exit?", "Exit?", JOptionPane.YES_NO_OPTION); if (resp == JOptionPane.YES_OPTION) { frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } else { frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } } }); ```
1,279,604
**I've read a number of related questions that aren't quite my question...** * [Windows 10 Getting Windows Ready Message](https://superuser.com/questions/1189160/windows-10-getting-windows-ready-message) **Q:** ...how can I get computer to stop showing me this screen? **[ie. User simply does not want to wait 45mins for OS update installs]** * [Windows 10 64 bit stuck at getting ready](https://superuser.com/questions/951822/windows-10-64-bit-stuck-at-getting-ready/1279601#1279601) **Q:** [From a new OS install] But after reboot, the system stuck at the "Getting Ready" screen forever. **[ie. This user has never been able to log into the OS after install**] * [How can I disable the "Getting Windows Ready" message when Windows shuts down?](https://superuser.com/questions/1164313/how-can-i-disable-the-getting-windows-ready-message-when-windows-shuts-down) **Q:** User is looking for a way to bypass "Getting Windows ready" screen on shut down / restart presumably because they will reload its state directly from a software called "Deep Freeze" instead. **[ie. User wants to bypass OS procedure that is working as intended]** My Windows 10 64bit OS was recently 'refresh' *(That's "Windows" for the 'Programs' folder is deleted, registry is recreated, and windows is reinstalled without deleting any other files on the machine)*. After the 'refresh', I've been able to log in and use the PC for a number of days. Then once I was assumably stuck on the blue screen with the dots moving in a circle, etc: ``` Getting Windows ready Don't turn off your computer ``` It was stuck for a number of hours, but I eventually restarted the machine and it booted normally and I was able to use again for the last week. Some time within the week I remember investigating my windows update, I noticed that I had an update that was getting stuck and wouldn't complete normally. I don't recall if I had been able to reboot the PC after that point. Last night I rebooted the machine, and this time it has been stuck on the screen mentioned above for over 8-10+ hrs, **so I suspect that the PC is now in an erroneous state.** I've now attempted to restart the machine a number of times including into safe mode *(by forcing it into 'automatic repair' by hard booting the machine 3 times during the boot process)* and it always comes back to the blue screen mentioned above. **How do I recover my machine from this state?** *(Ideally least intrusive without a format/reinstall, etc)*
2017/12/23
[ "https://superuser.com/questions/1279604", "https://superuser.com", "https://superuser.com/users/855680/" ]
Got it! From another 'licensed' Windows 10 PC... **Boot Windows 10 Installer from a USB:** * Download this tool: [Create Windows 10 installation media](https://www.microsoft.com/en-us/software-download/windows10?tduid=(cc5cbdef235355eda514ae4a295d7886)(259740)(2542549)(UUwpUdUnU50931YYw)(dwp)) * Install the tool to a USB stick/drive * Reboot the machine and smash F8 or F12 to get the machine to boot from the USB * When you get to the screen that says "Install Windows 10" there will be a link in the lower left hand corner that says "Repair" **<- click that!** * ***Look here for some screenshots:*** [5. Use a Windows 10 installation drive and the Command Prompt](https://www.digitalcitizen.life/4-ways-boot-safe-mode-windows-10) *(There are a number of tools you can use here, but **System Restore** was the only that worked for me.)* ![**Screenshots of recovery options from USB Intaller**](https://i.stack.imgur.com/28rwo.png) **Recovery options *that worked for me*:** * **Restore back far enough to where the system was stable;** I had to do it twice to stop the blue screen issue. First time I just stepped one restore point back. The second time I went back as far as possible, which was a "Critical Windows 10 Update" right after my 'refresh' * [DrMoishe Pippik](https://superuser.com/questions/1279604/windows-10-64-bit-stuck-getting-windows-ready-after-possibly-failed-softwa/1279682#answer-1279678) **suggests doing another 'refresh'**, which likely would have worked as well. Because I just did one of those, I know that a restore point was definitely faster and retained most of my installed apps. --- **Other tools you can try from the USB Installer that DIDN'T work for me...** * Startup Repair * Startup Settings *(for safe mode)* --- **Bonuses:** **Here's a strategy to "BLOCK" automated updates to Windows 10 Home Editions:** * [HOW TO STOP AUTO UPDATES IN WINDOWS 10](https://www.bouncegeek.com/stop-auto-updates-in-windows-10-5248736148/) **Here's how to reset Windows Update if it gets into an erroneous state:** * Clear the contents of the [Software Distribution folder](http://www.thewindowsclub.com/software-distribution-folder-in-windows), [reset the Catroot2 folder](http://www.thewindowsclub.com/catroot-catroot2-folder-reset-windows) and then run Windows Update again. Reference: [How to install Windows 10 from USB with UEFI support](https://www.windowscentral.com/how-create-windows-10-usb-bootable-media-uefi-support)
Even though you wish to avoid reinstallation, that is probably the safest option, since it appears the refresh process was stuck or interrupted more than once. This ensures that *all* needed system files are in place. It may well be **faster** to do the full reinstallation than trying to refresh Windows from the active HDD. Download the [latest Windows ISO and installation media creation tool](https://www.microsoft.com/en-us/software-download/windows10), create a USB instllation and [perform a reinstallation whilst keeping data files](http://www.intowindows.com/how-to-reinstall-windows-10-without-losing-data/).
4,781,500
I am using Ubuntu. I install newer version of python. But all my installed libraries such as imdbPy, NumPy, Cython etc. can run in previous version of python whose version number is 2.6.6. When I import Cython in 2.6.6, tt works, but I try same thing in 2.7.0+ version of python ``` import cython ``` occurs an error as following: ``` import cython ImportError: No module named cython ``` What I need is to change default version of python which is used in bash. I think, I can handle it by modifying bash profile file. I also want to move all of these libs to appropriate place so that new version of python can reach them permanently.
2011/01/24
[ "https://Stackoverflow.com/questions/4781500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286714/" ]
Don't mess with your system installs - the package manager should be responsible for that. Make sure that when you install from source, you do it in a separate directory. I install things in my home directory. I like jhbuild so this is what I use to maintain different versions of python side by side: <https://thomas.apestaart.org/thomas/trac/browser/jhbuild/python> Running make from that checkout will build python 2.3-2.7 and create scripts to go into their environment: ``` [thomas@level ~]$ py-2.4 Entering interactive py shell /bin/bash [py-2.4] [thomas@level ~]$ python Python 2.4.5 (#1, Dec 16 2010, 18:51:06) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ```
You need to reinstall all the libraries for the new version. I'd recommend that you first download pip and install it. After that you can install most packages with `/path/to/Python27/bin/pip install <packagename>`, for example ``` /opt/python27/bin/pip install Cython ```
28,429,071
My camera app preview is too dark in low light. If I open my google camera it will increase brightness inside the preview so that our face is visible to take photos. But my preview is completely dark. I have handled the brightness and lightsensor. My Lightsensor works when is some light. I need to make preview is visible. Let me what should I have to handle? ``` public void initialBrightness() { try { brightnessMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE); } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); brightnessModeAuto = true; } Settings.System.putInt(this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 95); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = 100; getWindow().setAttributes(lp); } ``` I'm calling this method in onCreate method before camera preview class is called.
2015/02/10
[ "https://Stackoverflow.com/questions/28429071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4239092/" ]
To solve the problem you have to **unlock autoExposureCompensation** and **set to the MAX value**: ``` Camera.Parameters params = mCamera.getParameters(); params.setExposureCompensation(params.getMaxExposureCompensation()); if(params.isAutoExposureLockSupported()) { params.setAutoExposureLock(false); } mCamera.setParameters(params); ``` According to [Android Develop > Reference > Camera.Parameters](http://developer.android.com/reference/android/hardware/Camera.Parameters.html#setAutoExposureLock(boolean)) > > Changing the white balance mode with setWhiteBalance(String) will release the auto-white balance lock if it is set. > > > Exposure compensation, AE lock, and AWB lock can be used to capture an exposure-bracketed burst of images, for example. Auto-white balance state, including the lock state, will not be maintained after camera release() is called. > > > Locking auto-white balance after open() but before the first call to startPreview() will not allow the auto-white balance routine to run at all, and may result in severely incorrect color in captured images. > > > So be careful and use the mentioned code **after** the first call to startPreview()
By reading the open source code of Android Camera app here: <https://android.googlesource.com/platform/packages/apps/Camera.git/+/lollipop-release> It initialize the camera this way: ``` // Reset preview frame rate to the maximum because it may be lowered by // video camera application. List<Integer> frameRates = parameters.getSupportedPreviewFrameRates(); if (frameRates != null) { Integer max = Collections.max(frameRates); parameters.setPreviewFrameRate(max); } ``` And it works well in Android Nexus 5, lollipop.
14,512,392
I am having trouble getting some text to be next to an image. I have it working on one site: <http://puckpros.edkatzman.com/> but not on another: <http://petra.edkatzman.com/> and I can't see the difference. Can another pair of eyes help? Here is the jsfiddle: <http://jsfiddle.net/tangobango/rK2mG/> HTML: ``` <div id="primary" class="content-area"> <div id="content" class="site-content" role="main"> <div id="front-page"> <div id="owner-photo "> <img src="http://petra.edkatzman.com/wp-content/uploads/2013/01/Ed-headshot-small.jpg" alt="Ed Katzman" > </div> <div id="owner-description "> <h1><span class="drop-cap">Hi! </span>My name is Michael Jennings, the owner and master craftsman of Petra Stoneworks. I have over 25 years experience working with a wide range of both valuable and everyday stone pieces.</h1> <h3>We specialize in the expert repair of stone objects and the creation of original pieces. Have a look at the portfolio of our work and contact us with any questions or to start a discussion of how we might help you.</h3> </div> </div> </div><!-- #content .site-content --> </div><!-- #primary .content-area --> ``` CSS: ``` #front-page { background-color:#ffffff; padding-left: 10px; padding-right: 10px; padding-bottom: 10px; padding-top:10px; overflow: hidden; } #owner-photo { width:246px; height:246px; float:left; } ```
2013/01/24
[ "https://Stackoverflow.com/questions/14512392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1873217/" ]
The reason you can't use `geom_tile()` (or the more appropriate `geom_raster()` is because these two `geoms` rely on your tiles being evenly spaced, which they are not. You will need to coerce your data to points, and resample these to an evenly spaced raster which you can then plot with `geom_raster()`. You will have to accept that you will need to resample your original data slightly in order to plot this as you wish. You should also read up on `raster:::projection` and `rgdal:::spTransform` for more information on map projections. ``` require( RCurl ) require( raster ) require( sp ) require( ggplot2 ) tmp <- getURL("https://gist.github.com/geophtwombly/4635980/raw/f657dcdfab7b951c7b8b921b3a109c7df1697eb8/test.csv") testdf <- read.csv(textConnection(tmp)) spdf <- SpatialPointsDataFrame( data.frame( x = testdf$y , y = testdf$x ) , data = data.frame( z = testdf$z ) ) # Plotting the points reveals the unevenly spaced nature of the points spplot(spdf) ``` ![enter image description here](https://i.stack.imgur.com/jNJtb.png) ``` # You can see the uneven nature of the data even better here via the moire pattern plot(spdf) ``` ![enter image description here](https://i.stack.imgur.com/xWpTG.png) ``` # Make an evenly spaced raster, the same extent as original data e <- extent( spdf ) # Determine ratio between x and y dimensions ratio <- ( e@xmax - e@xmin ) / ( e@ymax - e@ymin ) # Create template raster to sample to r <- raster( nrows = 56 , ncols = floor( 56 * ratio ) , ext = extent(spdf) ) rf <- rasterize( spdf , r , field = "z" , fun = mean ) # Attributes of our new raster (# cells quite close to original data) rf class : RasterLayer dimensions : 56, 135, 7560 (nrow, ncol, ncell) resolution : 0.424932, 0.4248191 (x, y) extent : -124.5008, -67.13498, 25.21298, 49.00285 (xmin, xmax, ymin, ymax) # We can then plot this using `geom_tile()` or `geom_raster()` rdf <- data.frame( rasterToPoints( rf ) ) ggplot( NULL ) + geom_raster( data = rdf , aes( x , y , fill = layer ) ) ``` ![enter image description here](https://i.stack.imgur.com/gDTXj.png) ``` # And as the OP asked for geom_tile, this would be... ggplot( NULL ) + geom_tile( data = rdf , aes( x , y , fill = layer ) , colour = "white" ) ``` ![enter image description here](https://i.stack.imgur.com/2dMzj.png) Of course I should add that this data is quite meaningless. What you really must do is take the SpatialPointsDataFrame, assign the correct projection information to it, and then transform to latlong coordinates via spTransform and then rasterzie the transformed points. Really you need to have more information about your raster data. What you have here is a close approximation, but ultimately it is not a true reflection of the data.
answer: data is plotted but is just very small. --- [From here:](http://svitsrv25.epfl.ch/R-doc/library/ggplot2/html/geom_tile.html) ``` "Tile plot as densely as possible, assuming that every tile is the same size. ``` Consider this plot ``` ggplot(data = testdf[1:2,], aes(x,y,fill = z)) + geom_tile() ``` ![enter image description here](https://i.stack.imgur.com/6UUD1.png) There are two tiles in the plot above. `geom_tile` is trying to make the plot as dense as possible considering that every tile is the same size. Here we can make two tiles this big without overlapping. making enough space for 4 tiles. Have a go at the following plots and see what the resulting plots tell you: ``` df1 <- data.frame(x=c(1:3),y=(1:3)) # df1 # x y #1 1 1 #2 2 2 #3 3 3 ggplot(data = df1[1,], aes(x,y)) + geom_tile() ggplot(data = df1[1:2,], aes(x,y)) + geom_tile() ggplot(data = df1[1:3,], aes(x,y)) + geom_tile() ``` compare to this example: ``` df2 <- data.frame(x=c(1:3),y=c(1,20,300)) df2 # x y #1 1 1 #2 2 20 #3 3 300 ggplot(data = df2[1,], aes(x,y)) + geom_tile() ggplot(data = df2[1:2,], aes(x,y)) + geom_tile() ggplot(data = df2[1:3,], aes(x,y)) + geom_tile() ``` Note that for the first two plots are same for `df1` and `df2` but the third plot for `df2` is different. This is because the biggest we can make the tiles is between (`x[1],y[1])` and (`x[2],y[2])`. Any more and they would overlap which leaves lots of space between these two tiles and the last 3rd tile at `y=300`. There is also a `width` parameter in `geom_tile` although I am not sure how sensible this is here. are you sure you dont fancy another option with such sparse data ? (Your full data is still plotted: see `ggplot(data = testdf, aes(x,y)) + geom_tile(width=1000)`
11,541,446
I am new to XML and I was hoping someone could point me in the right direction on this. So an order comes in from our partner company, B2B turns it into XML and gives it back to us. It would more then likely just end up in a folder somewhere on our server or maybe the mailbox. We need to render each individual XML into a nice looking packing slip. The packing slips would be identical except for the fact that the logo would need to be changed depending on what store it came from. Any ideas?
2012/07/18
[ "https://Stackoverflow.com/questions/11541446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1521975/" ]
The difference is that when you put it on the prototype, *all* instances of `Person` share the same code for `getName` -- you can change `getName` on *all* instances of `Person` by assigning something else: ``` Person.prototype.getName = function() { return 'Mr Jones' }; ``` Also, since they share the same code, it's less memory intensive: You only have one copy of the `getName` function, instead of one copy per instance. Another difference is that you can later set the `Person` as the prototype of another class, let's say `Man`, and it will inherit the properties/methods. **Update:** Here is a good post explaining other properties of prototypes: <https://stackoverflow.com/a/1534286/295262>
In class-based words the difference between declaring a function via `prototype` and `this` would be something like this: **prototype:** the function of the instance would look like this: ``` somefunc = function(){super()/*call the function of the super-class*/}; ``` **this:** the function of the instance would look like this: ``` somefunc = function(){/* Do same stuff as in the prototype func declared */}; ``` Now changing the function on the prototype will have no effect on the instance.
71,312,050
I have a ListBody which has a `Text` element and then a `String` which is returned by an API. Such as.. ``` Destination: $destination Destination: London ``` However, if it is longer is spills over as such ``` Destination: London Paddington Station ``` How is best to ensure that if the text is long enough to require a new line it is indented with the beginning on the `String` (i.e. The 'L' in 'London' is in-line) ``` Destination: London Paddington Station ``` ``` ListBody( children: <Widget>[ RichText ( text: TextSpan( children: <TextSpan> [ TextSpan(text: "\t\tDestination ", style: TextStyle( fontSize: 18 , fontWeight: FontWeight.w400, color: Color(0xff2F2F2F), fontFamily: 'DMSans' ) ), TextSpan(text: "$destination", style: TextStyle( fontSize: 18 , fontWeight: FontWeight.w600, color: Colors.black, fontFamily: 'DMSans' ) ), ``` Thank you
2022/03/01
[ "https://Stackoverflow.com/questions/71312050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15425619/" ]
`select distinct SupervisorENO from EMPLOYEE` will also return NULL, any any value when compared to NULL will not actually return True or False, it will return *unknown*, so to speak. You can read more about that [here for example](https://www.xaprb.com/blog/2006/05/18/why-null-never-compares-false-to-anything-in-sql/). So in order to fix your query, you need to exclude NULLs: ``` select Ename from employee where Eno not in (select distinct SupervisorENO from employee where supervisoreno is not null); ``` [Here's a working demo on dbfiddle](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7b2df272391c3a93517f0d52e17a1568)
You can simply query ``` select Ename from employee where SupervisorEno is not null; ``` which will return those who have a supervisor, ie. are not themselves a supervisor. ``` select Ename from employee where SupervisorEno is null; ``` Will return the supervisors. It is better to avoid sub-queries when not strictly needed.
177,558
Something like this is on my mind: I put one or a few strings in, and the algorithm shows me a matching regex. Is there an "*easy*" way to do this, or does something like this already exist? ***Edit 1***: Yes, I'm trying to find a way to generate regex. ***Edit 2***: Regulazy is not what I am looking for. The common use for the code I want is to find a correct RegEx; for example, article numbers: * I put in *123456*, the regex should be `\d{6}` * I put in *nb-123456*, the regex should be `\w{2}-\d{6}`
2008/10/07
[ "https://Stackoverflow.com/questions/177558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25730/" ]
How about the following (matches every string)? .\*
Look at [txt2re](http://txt2re.com). This site holds a form that takes a sample string and generates a regex pattern that can match the given string. Then it generates the corresponding script for the following languages: Perl, PHP, Python, Java, Javascript, ColdFusion, C, C++ Ruby, VB, VBScript, J#.net, C#.net, C++.net, VB.net
52,458,939
I have a small Android app which uses AdMob. It has been working fine for a while. Recently, I tried to add some new features, and at the same time to upgrade all used libraries to most recent version. But I have a problem with AdMobs. I did put `implementation 'com.google.android.gms:play-services-ads:15.0.1'` into app build.gradle, `maven { url "https://maven.google.com" }` into project build.gradle, add changes to manfest file(ass suggested by [Google developers site](https://developers.google.com/admob/android/quick-start)), did couple of Clean/Build and Invalidate Caches/Restart, checked SDK manager for Google Play services, all with no result, AndroidStudio can't resolve com.google.android.gms.ads.MobileAds and other AdMobs classes. For all statments like `import com.google.android.gms.ads.MobileAds;` AndroidStudio marks as unsolvable e.g "Cannot resolve symbol 'MobileAds' ". What is more confusing, the app can be built and deployed, Gradle says no errors, the app works fine and the ads are displayed as wanted. But, there are some warnings in the Logcat such as: * 'W/Ads: #004 The webview is destroyed. Ignoring action.', * ...the Google Mobile Ads SDK will not integrate with Firebase (though I don't want to integrate it with Firebase) etc. Therefore, I cannot publish the upgraded app without being sure it functions the way I expect. My working environment is Linux/Fedora27, AndroidStudio 3.1.4, and as virtual device I use Genymotion 2.12.2.
2018/09/22
[ "https://Stackoverflow.com/questions/52458939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5316307/" ]
I think I've solved it. Somehow I figured it is ItelliJ Idea issue, so I've searched around, found some similar topics that have given me a clue. And it worked. There is a hidden folder below project folder called `.idea`. And `libraries` folder below. Full of .xml files gradle made through build process. And I deleted them all!. Restarted Android Studio and everything went well. So, go to ``` <Project>/.idea/libraries ``` and delete all it's content. I believe that some gradle versions incompatibilites caused the trouble. Clean and/or Invalidate Cache are not sufficient, so brutal delete is the solution.
If you use Android Studio. press shift key twice. then search "cache" and run "Invalidate Caches / Restart..."
7,016,937
After successfully installing the ruby-0ci8 gem and the oracle\_enhanced adapter gem I get the following error when I try to fire up my rails project server: ``` => Booting WEBrick => Rails 3.0.3 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server Exiting /Library/Ruby/Gems/1.8/gems/activerecord-oracle_enhanced-adapter-1.3.2/lib/active_record/connection_adapters/oracle_enhanced_oci_connection.rb:7: ERROR: ActiveRecord oracle_enhanced adapter could not load ruby-oci8 library. Please install ruby-oci8 gem. (LoadError) ``` Both the enhanded adapter and ruby-oci8 gem show up in my gem list. Both are present in my Gemfile. Why can't the adapter find the oci8 library? Some specs on setup I'm running: * Mac Snow Leopard (10.6.8) * Ruby 1.8.7 (2009-06-12 patchlevel 174) [i686-darwin10.8.0] * Rails 3.0.3 * ruby-oci8 (2.0.4) [gem] * activerecord-oracle\_enhanced-adapter (1.3.2) [gem] I've looked at this post: [Rails 3.0.3 - Oracle\_enhanced doesn't work](https://stackoverflow.com/questions/4561979/rails-3-0-3-oracle-enhanced-doesnt-work). But it's not helping. Anyone else run into this? ============================== Answer ------ I got it figured out. In the end i had an incorrect file structure in /usr/local/oracle/instantclient\_10\_2/ where I had stored the files for my oracle instant client. That is what was causing all the issues. Basically I had nested a second instantclient\_10\_2 directory inside the first and I had my .bash\_profile looking in the first directory and not the one below it.
2011/08/10
[ "https://Stackoverflow.com/questions/7016937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222468/" ]
Run `sudo apt-get install libaio1`
This issue is noted on the gems list of [platform specific issues](http://ruby-oci8.rubyforge.org/en/PlatformSpecificIssue.html). Your most likely solution is to follow the guide provided on how to set up the [Oracle Instant Client](http://blog.rayapps.com/2009/09/06/how-to-setup-ruby-and-oracle-instant-client-on-snow-leopard/).
28,311,030
I have a script to trigger a job on Jenkins remotely using a token. Here is my script: ``` JENKINS_URL='http://jenkins.myserver.com/jenkins' JOB_NAME='job/utilities/job/my_job' JOB_TOKEN='my_token' curl "${JENKINS_URL}/${JOB_NAME}/buildWithParameters?token=${JOB_TOKEN}" ``` **After I run it, I get following response:** ``` * Hostname was NOT found in DNS cache * Trying 10.5.187.225... * Connected to jenkins.myserver.com (10.5.187.225) port 80 (#0) > GET /jenkins/job/utilities/job/my_job/buildWithParameters?token=my_token HTTP/1.1 > User-Agent: curl/7.37.1 > Host: jenkins.myserver.com > Accept: */* > < HTTP/1.1 201 Created * Server nginx/1.6.2 is not blacklisted < Server: nginx/1.6.2 < Date: Tue, 03 Feb 2015 23:40:47 GMT < Content-Length: 0 < Location: http://jenkins.myserver.com/jenkins/queue/item/91/ < Connection: keep-alive < Cache-Control: private < Expires: Wed, 31 Dec 1969 16:00:00 PST < * Connection #0 to host jenkins.myserver.com left intact ``` I noticed that it returns the queue url in the header: <http://jenkins.myserver.com/jenkins/queue/item/91>. But I don't know how I should use this return url. 1) I am wondering if anyone knows how I can check the status for the job that I just created? 2) Since the above response does not return the job #, I can't really use this api call: ``` curl http://jenkins.myserver.com/jenkins/job/utilities/job/my_job/8/api/json ``` to check for status. So where can I get the job name and job number after I get the location url from the above response? Thanks
2015/02/03
[ "https://Stackoverflow.com/questions/28311030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1881450/" ]
I solved this problem using polling of the Jenkins server. When a job is started remotely the return headers has the job queue URL. Using this one can make more API calls to get status. Steps: * start the job * parse return 'Location' header * poll the queue looking for job to start + job queue entry will have an 'executable' entry in its json or xml with job number once it starts * poll the job status waiting for a result I used python and the Requests module to do this ``` #!/usr/bin/python import requests import re import sys import json import time # secs for polling Jenkins API # QUEUE_POLL_INTERVAL = 2 JOB_POLL_INTERVAL = 20 OVERALL_TIMEOUT = 3600 # 1 hour # job specifics: should be passed in auth_token = 'buildmaster:173223588624f980c3AAA68d4d8efe0c' jenkins_uri = '192.168.115.187:8080' job_name = 'rf_systest' build_token = 'rf_systest_auth_token' # start the build # start_build_url = 'http://{}@{}/job/{}/build?token={}'.format( auth_token, jenkins_uri, job_name, build_token) r = requests.post(start_build_url) # from return headers get job queue location # m = re.match(r"http.+(queue.+)\/", r.headers['Location']) if not m: # To Do: handle error print "Job starte request did not have queue location" sys.exit(1) # poll the queue looking for job to start # queue_id = m.group(1) job_info_url = 'http://{}@{}/{}/api/json'.format(auth_token, jenkins_uri, queue_id) elasped_time = 0 print '{} Job {} added to queue: {}'.format(time.ctime(), job_name, job_info_url) while True: l = requests.get(job_info_url) jqe = l.json() task = jqe['task']['name'] try: job_id = jqe['executable']['number'] break except: #print "no job ID yet for build: {}".format(task) time.sleep(QUEUE_POLL_INTERVAL) elasped_time += QUEUE_POLL_INTERVAL if (elasped_time % (QUEUE_POLL_INTERVAL * 10)) == 0: print "{}: Job {} not started yet from {}".format(time.ctime(), job_name, queue_id) # poll job status waiting for a result # job_url = 'http://{}@{}/job/{}/{}/api/json'.format(auth_token, jenkins_uri, job_name, job_id) start_epoch = int(time.time()) while True: print "{}: Job started URL: {}".format(time.ctime(), job_url) j = requests.get(job_url) jje = j.json() result = jje['result'] if result == 'SUCCESS': # Do success steps print "{}: Job: {} Status: {}".format(time.ctime(), job_name, result) break elif result == 'FAILURE': # Do failure steps print "{}: Job: {} Status: {}".format(time.ctime(), job_name, result) break elif result == 'ABORTED': # Do aborted steps print "{}: Job: {} Status: {}".format(time.ctime(), job_name, result) break else: print "{}: Job: {} Status: {}. Polling again in {} secs".format( time.ctime(), job_name, result, JOB_POLL_INTERVAL) cur_epoch = int(time.time()) if (cur_epoch - start_epoch) > OVERALL_TIMEOUT: print "{}: No status before timeout of {} secs".format(OVERALL_TIMEOUT) sys.exit(1) time.sleep(JOB_POLL_INTERVAL) ``` Output: ``` Tue Jan 30 16:24:08 2018: Job rf_systest added to queue: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/queue/item/164/api/json Tue Jan 30 16:24:39 2018: Job rf_systest not started yet from queue/item/164 Tue Jan 30 16:25:00 2018: Job started URL: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/job/rf_systest/79/api/json Tue Jan 30 16:25:01 2018: Job: rf_systest Status: None. Polling again in 20 secs Tue Jan 30 16:25:21 2018: Job started URL: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/job/rf_systest/79/api/json Tue Jan 30 16:25:21 2018: Job: rf_systest Status: None. Polling again in 20 secs Tue Jan 30 16:25:41 2018: Job started URL: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/job/rf_systest/79/api/json Tue Jan 30 16:25:41 2018: Job: rf_systest Status: None. Polling again in 20 secs Tue Jan 30 16:26:01 2018: Job started URL: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/job/rf_systest/79/api/json Tue Jan 30 16:26:01 2018: Job: rf_systest Status: None. Polling again in 20 secs Tue Jan 30 16:26:21 2018: Job started URL: http://buildmaster:173223588624f980c344668d4d8efe0c@192.168.115.187:8080/job/rf_systest/79/api/json Tue Jan 30 16:26:21 2018: Job: rf_systest Status: SUCCESS ``` JSON from a Jenkins queue once its job has started: ``` { "_class": "hudson.model.Queue$LeftItem", "actions": [ { "_class": "hudson.model.CauseAction", "causes": [ { "_class": "hudson.model.Cause$RemoteCause", "addr": "10.20.30.60", "note": null, "shortDescription": "Started by remote host 10.20.30.60" } ] } ], "blocked": false, "buildable": false, "cancelled": false, "executable": { "_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun", "number": 45, "url": "http://192.168.115.187:8080/job/rf_systest/45/" }, "id": 95, "inQueueSince": 1517342648136, "params": "", "stuck": false, "task": { "_class": "org.jenkinsci.plugins.workflow.job.WorkflowJob", "color": "blue_anime", "name": "rf_systest", "url": "http://192.168.115.187:8080/job/rf_systest/" }, "url": "queue/item/95/", "why": null } ```
I had similar problem to get state with rest api only. this was my solution (it is a **weak and not stable** solution!): ```sh #Ex. http://jenkins.com/job/test JOB_URL="${JENKINS_URL}/job/${JOB_NAME}" #here you can ask for next build job number function getNextBuildNr(){ curl --silent ${JOB_URL}/api/json | grep -Po '"nextBuildNumber":\K\d+' } # this will request the Status of job function getBuildState(){ buildNr=$1 curl --silent ${JOB_URL}/${buildNr}/api/json | grep -Po '"result":\s*"\K\w+' } #this will wait for your Job state, by polling Jenkins every second function waitForJob() { buildNr=$1 state="" while [ "${state}" == "" ] do sleep 1 state=$(getBuildState ${buildNr}) echo -n '.' done echo -e "\n" } #now you can run and build BUILD_NR=$(getNextBuildNr) # input here your code/function to trigger the job waitForJob ${BUILD_NR} BUILD_STATE=$(getBuildState ${BUILD_NR}) echo "$BUILD_STATE" ```
2,321,118
I am using setInterval and the jQuery load function to periodically update an image tag. ``` var refresh_days = setInterval(function() { $('#box_name').load("dynamic.php");}, 1000 ); ``` This works, but there is a slight delay before the new image is fully loaded, during which nothing is shown. Is there a way I can wait until the new image is loaded completely, and then display it, so that the image changes instantaneously from the user's perspective? My target browser is Chrome and I do not need this to be compatible with IE. Thanks,
2010/02/23
[ "https://Stackoverflow.com/questions/2321118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84398/" ]
You could load the image into an invisible `<img>` tag, and use the "load" event to update the visible one. ``` $('#hiddenImage').attr('src', newImageUrl).load(function() { $('#realImage').attr('src', newImageUrl); }); ``` That way you know it's in the cache, so the update to the visible image should be pretty quick. If you're reloading a whole chunk of stuff, then you're going to have problems because the "load" action will update the page and *then* the browser will start the HTTP transaction to satisfy the implicit "GET" request in the `<img>` tag. What you could do, therefore, is: 1. Load the whole blob into a hidden `<div>` 2. Have a live() handler waiting for the "load" event from the image tag in the hidden div; 3. React to the "load" event by moving the DOM subtree from the hidden div out to the place you really want it.
I'm thinking `.load` may be causing problems for you since you're actually reloading the entire HTML structure within that section of your HTML code. Instead of using `.load`, I'd try using the `jQuery.ajax()` method. Attach a method to the `success` option which takes the returned image and swaps it in over the old one. This way, you're just using CSS to swap out the image rather than manipulating the DOM. Look at <http://docs.jquery.com/Ajax/jQuery.ajax#options> for more info.
72,868,708
Supposing i have 3 tables in the below picture that joined together. how can i access 'Email' field in 'Users' table in my query on 'UserReferralJoins' table ? can any one help me? ``` var referalId = await _dbContext.UserReferrals.Where(x => x.UserId == CurrentUserId).Select(x => x.UserReferralId).FirstOrDefaultAsync(); var list = await _dbContext.UserReferralJoins .Where(i => i.UserReferralId == referalId) .Select(x => new { Id = x.UserReferralJoinId, UserEmail = ??? x.JoinDate }).ToListAsync(cancellationToken); ``` [![enter image description here](https://i.stack.imgur.com/fIagi.jpg)](https://i.stack.imgur.com/fIagi.jpg)
2022/07/05
[ "https://Stackoverflow.com/questions/72868708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8315431/" ]
Replace any combination of spaces and commas with a single underscore: ``` sed -E 's/[, ]+/_/g' ``` See [live demo](https://ideone.com/0dbddF). --- To rename files using this regex on *any* \*nix OS (macos doesn't ship with `rename`): ``` for f in *.txt; do mv $f $(echo "$f" | sed -E 's/[, ]+/_/g'); done ``` If your \*nix has the `rename` command (`brew install rename` if you're macos): ``` rename 's/[, ]+/_/g' *.txt ```
One line solution here: ```bash find *.txt | sed -E 'p;s/[, ]+/_/g' | tr '\n' '\0' | xargs -0 -n2 mv ``` This is a very useful command template for batch renaming files: ```bash find ... | sed 'p;s/...' | tr '\n' '\0' | xargs -0 -n2 mv ```
41,637,697
I'm using awscli (S3 Api) to operate some requests with my softlayer objectstorage. I can retrieve the buckets list, create or delete bucket. When i try to copy a sample file to a specific bucket, i'm getting an error : `aws --endpoint-url=https://s3-api.us-geo.objectstorage.softlayer.net s3 cp test.txt s3://my_test_bucket/files` I'm getting the following error (tested with both sdk apis, python boto3 api and wascli) `upload failed: ./test.txt to s3://my_test_bucket/test.txt An error occurred (SignatureDoesNotMatch) when calling the PutObject operation: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.`
2017/01/13
[ "https://Stackoverflow.com/questions/41637697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4904189/" ]
That's odd - you appear to be using the correct syntax. How are you passing your credentials? The easiest way would be in a `~/.aws/credentials` file that contains: ``` [default] aws_access_key_id = {Access Key ID} aws_secret_access_key = {Secret Access Key} ``` If you are getting the same error across different tools/libraries this is likely the issue. If you have your credentials set up correctly and are still getting the signature issue we'll need to probably do a deeper dive to figure out what's going on, because it appears you aren't doing anything incorrect.
The reason why you got the error may be the signature version is different. IBM Cloud Object Storage using signature version 2 but the default version is 4. <http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html> I'm not sure how to set the signature version by curl and python. In SDK for Java, you need to set like this, otherwise you got the error. ``` AWSCredentialsProvider provider = loadCredentialProvider(); ClientConfiguration config = new ClientConfiguration(); config.withSignerOverride("S3SignerType"); // second arg region not needed EndpointConfiguration endpointConfiguration = new EndpointConfiguration(us-geo.objectstorage.softlayer.net, ""); AmazonS3 cos = AmazonS3ClientBuilder.standard() .withCredentials(provider) .withClientConfiguration(config) .withEndpointConfiguration(endpointConfiguration) .build(); ```
1,027,938
One of the questions in my topology homework starts with: Suppose $G$ is a graph and $L \subset G$ is an embedded circle. I have looked around and found lots of definitions for an 'embedding' but am still a bit confused as to what embedded means. Going by what I have seen for definitions of embedding, does it mean that there exists a homeomorphism from $G$ onto $L$?
2014/11/18
[ "https://math.stackexchange.com/questions/1027938", "https://math.stackexchange.com", "https://math.stackexchange.com/users/136586/" ]
The course [Measure Theory](http://www.essex.ac.uk/maths/people/fremlin/mt.htm) by D.H.Fremlin includes TeX source. [Topology Course](http://at.yorku.ca/i/a/a/b/23.htm) by Aisling McCluskey and Brian McMaster in HTML. Diverse [lecture notes](http://www.maths.tcd.ie/~houghton/231/07-08/notes.php) by Conor Houghton. [Cryptography homework](http://www.cs.princeton.edu/courses/archive/spr10/cos433/) by Boaz Barak. [Digital Image Processing](http://eeweb.poly.edu/~onur/lectures/lectures.html). [Abstract Algebra handouts and Number Theory lecture notes](http://math.bard.edu/belk/math332s09/).
Many of the courses in MIT's OCW have such notes: <http://ocw.mit.edu/courses/find-by-department/>
4,950,531
I'm creating a login form with Codeigniter, and I have a controller that collects the inputs from the form, then I want to check to make sure what the user entered is in the database, so I'm collecting those values in the post and want to send them to the model for the database connection. Then if the results are in the database I want to send something back to the controller with a yes or no and then I can go from there. I'm kind of stuck, but this is what I have so far: The controller: ``` function do_login() { $login = $this->input->post('Login'); $pwd = md5($this->input->post('Passwd')); } ``` The Model: ``` function check_login() { $sql = $this->db->query("SELECT * FROM members WHERE loin = '?' AND password = '?'", array(//POST stuff goes in here)); return $sql->result(); } ``` I'm not sure how to pass the data to the model, and then back to the controller. Any help would be great! Thanks!
2011/02/09
[ "https://Stackoverflow.com/questions/4950531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348092/" ]
In any MVC form POST is sending to controller (in action property in form) and controller (as the name is decribed) controls what will happend, in your case should ask database for verification via model, get response, decide what to do, and use view to display results... so in your controller: ``` function do_login() { $login = $this->input->post('Login'); $pwd = md5($this->input->post('Passwd')); $results = $this->...your_model_name...->chek_login( parameters as login and password would help ) // base on results: has records or has not - do something // maybe display view } ```
I would add 2 parameters to `check_login` and make it boolean: ``` function check_login($user, $password) { $sql = $this->db->query("SELECT * FROM members WHERE loin = '?' AND password = '?'", array($user, $password)); if (...) return TRUE; else return FALSE; } ``` Make it boolean lets the full login checking inside the controller, so that if there are more tests to do, the developper who uses the model doesn't have to know them, so it avoids errors. For instance if you want to check that there is only one row in the database, and an internal variable to know whether login is allowed or not (just an example). Would all developer read the documentation about that variable that has to be checked before validating the login? Would that documentation be written?
7,209,361
I am looking for a simple way to collaborate between a team of programmers developing with C# ASP.NET using Visual Studio 2010. I currently use TFS at my other job, and its easy enough so I can download the current files and check them out or check them in etc. Is there a free tool out there that provides the same functionality or are there easy methods out there to have a team of developers work on the same set of code easily without having to buy TFS?
2011/08/26
[ "https://Stackoverflow.com/questions/7209361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372519/" ]
I believe the closest to TFS, and the one I use at work is Subversion: <http://subversion.apache.org/> There is also a Windows Explorer plugin called TortoiseSVN: <http://tortoisesvn.tigris.org/> And a VS plugin, though last time I tried this it was nowhere near as usable as TortoiseSVN (though this was a few years ago): <http://ankhsvn.open.collab.net/>
[Collabnet](http://www.open.collab.net/) (makers of [Subversion](http://www.open.collab.net/products/subversion/)) have a neat plugin for Visual Studio called [AnkhSVN](http://ankhsvn.open.collab.net/), so it will feel similar to TFS. If you and your other developers want an integration environment that links with Subversion (I strongly recommend you have this if you don't already), you can use any CI tool: [CruiseControl.NET](http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET), [Team City](http://www.jetbrains.com/teamcity/), [Jenkins](http://jenkins-ci.org/content/jenkins), or [BuildMaster](http://inedo.com/buildmaster) (of which I am a developer).
31,612,406
I have a list of teasers looking like this: ``` <ul> <li> <a href="#"> <article> <h1>Title of Video</h1> <img src="thumbnail.jpg"> <p>Something about the video</p> </article> </a> </li> <li> <a href="#"> <article> <h1>Title of Video</h1> <img src="thumbnail.jpg"> <p>Something about the video</p> </article> </a> </li> <li> <a href="#"> <article> <h1>Title of Video</h1> <img src="thumbnail.jpg"> <p>Something about the video</p> </article> </a> </li> </ul> ``` Should I use `<figure>` and `<figcaption>` instead of `<article>`? It is my understanding that I should only use these tags if the text directly describes what is seen in the picture and not in the case depicted above. But maybe I'm wrong ...
2015/07/24
[ "https://Stackoverflow.com/questions/31612406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388026/" ]
Here is the idea, to use special template class `map_unpacker`, it not suppose to be completed in any sense, just to show the idea: ``` #include <tuple> #include <string> #include <iostream> #include <unordered_map> #include <tuple> #include <algorithm> template<typename T1, typename T2> struct map_unpacker { typedef typename std::unordered_map<T1,T2> convert_map; typedef typename convert_map::const_iterator convert_iterator; typedef typename convert_map::value_type pair; struct iterator : convert_iterator { iterator( const map_unpacker &u, convert_iterator it ) : unpack( u ), convert_iterator( it ) {} pair operator*() { auto &&p = convert_iterator::operator*(); unpack.ref1 = p.first; unpack.ref2 = p.second; return p; } const map_unpacker &unpack; }; map_unpacker( const std::unordered_map<T1,T2> &m, T1 &r1, T2 &r2 ) : map( m ), ref1( r1 ), ref2( r2 ) {} iterator begin() const { return iterator( *this, map.begin() ); } iterator end() const { return iterator( *this, map.end() ); } private: const std::unordered_map<T1,T2> &map; T1 &ref1; T2 &ref2; }; int main() { std::unordered_map<int,std::string> map {{5,"five"},{1,"one"},{-7,"minus seven"}}; int x; std::string s; for( auto &&v : map_unpacker<int,std::string>( map, x, s ) ) { std::cout << "x==" << x << " s==" << s << std::endl; } } ```
You can change your for loop as follows: ``` for(const auto& ele: map) std::cout<< ele.first<<"->"<<ele.second<<"\n"; ``` **EDIT** ``` for(const auto& x : map) { std::tie(y,s)=x; std::cout << y << "->" << s << "\n"; } ```
65,864
I have a fragment shader, when I've carefully managed to remove most branching decisions, as I have found out through research here that they are bad. But I have one function that I just can't work out how to do it without them. The function takes in a HSV vector, and 'expands' it. By that I mean any Value (V of HSV) from `0.0` to `0.5` gets expanded to `0.0` to `1.0`. Any Value from `0.5` to `1.0` gets de-saturated, so that it becomes more white. At `V=1.0` any input colour is white. Here is my working function. Can anyone help me de-'if' it? ``` //expand doubles the level up to 0.5=> 1.0 //for over 0.5 then the saturation is reduced from where it is now (V=0.5) to 0.0 (v=1.0) vec3 expand() { vec3 expanded; float newSaturation; float newValue; //HSV = rgb2hsv(inputColor); if (HSV.z < 0.5) { //x = Hue,y = Sat,z = Val ,w= bugger all newValue = HSV.z * 2.0; //double value 0.0 to 0.5 => 0.0 to 1.0 //no need to touch saturation newSaturation = HSV.y; } else { newValue = 1.0; //value is max //need to de-saturate proportional to level over 0.5 : (1.0 - ((v - 0.5) * 2)) * s newSaturation = (1.0 - ((HSV.z - 0.5) * 2.0)) * HSV.y; } expanded = hsv2rgb(vec3(HSV.x, newSaturation, newValue)); return expanded; } ```
2013/11/14
[ "https://gamedev.stackexchange.com/questions/65864", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/39022/" ]
You can do it easily with a couple of saturates: ``` newValue = saturate(HSV.z * 2.0); //double value 0.0 to 0.5 => 0.0 to 1.0 newSaturation = (1.0 - (saturate(HSV.z - 0.5) * 2.0)) * HSV.y; ``` The first line is relatively simple to understand. Saturate will clamp the result to the 0-1 range so values bigger than 0.5 will end up as 1.0 which is exactly what you get in the second half of the conditional. You can also see that for the case of `HSV.z < 0.5` the expression `(1.0 - (saturate(HSV.z - 0.5) * 2.0))` will always end up as 1.0, which won't change HSV.y when multiplied by it.
**For PC and console GPUs, branches aren't bad; they can often improve performance.** Typically, for a simple branch like this, the hardware will just run both sides for each pixel and then pick the result. Unless your shader is ALU bound (most are texture-bound), you will see absolutely zero performance from removing branches. For a more complex/longer branch, or a branch which samples textures, the compiler may choose to use a dynamic branch. The way GPUs work is that they run many (as many as 32-64) shader cores at once, running the same instruction on different data. This group is called a "Warp" (NVIDIA) or "Wavefront" (AMD). If *any* of the fragments in a wavefront want to take that path, then every single fragment in that wavefront takes the branch. So if one pixel out of those 64 needs the then part, and the other 63 need the else part, both sides will still be executed. Same thing happens with (non-unrolled) loops. If most pixels want to execute a loop 3 times, but there's one that needs to execute it 8 times, the hardware will execute the loop 8 times for every single pixel in that wavefront. The best practice for PC/console applications is simply to write the shaders clearly and let the compiler and user-mode driver optimize it. Then, you can use a profiler (such as [GPUPerfStudio](http://developer.amd.com/tools-and-sdks/graphics-development/gpu-perfstudio-2/)) to help find out what needs to be optimized. Sometimes this will include removing branches, but in certain cases it could be better to add them, especially if you have large clumps of pixels where much of the shader is unused (for example, smooth shadows -- most pixels are either entirely shadowed or entirely un-shadowed, so you only want to do complex smoothing at the shadow edges). Mobile GPUs work very differently, so if you're designing your game for phones or tablets, you might want to look into best practices for those things.
9,887,919
I'm going to upload my vimrc to githug. But some settings is not general(e.g. on slower machine I dont use cursorcolumn) So I don't want to put all my settings in one file. How to do this? Is there something like 'source' in bash?
2012/03/27
[ "https://Stackoverflow.com/questions/9887919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590083/" ]
I think the simpliest way is to exucute a `String.split(",")` and count the size of array. So the instruction willl look like this : ``` String s = "1234,56,789"; int numberofComma = s.split(",").length; ``` Regards, Éric
``` public class OccurenceOfChar { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter any word"); String s=br.readLine(); char ch[]=s.toCharArray(); Map map=new HashMap(); for(int i=0;i<ch.length;i++) { int count=0; for(int j=0;j<ch.length;j++) { if(ch[i]==ch[j]) count++; } map.put(ch[i], count); } Iterator it=map.entrySet().iterator(); while(it.hasNext()) { Map.Entry pairs=(Map.Entry)it.next(); System.out.println("count of "+pairs.getKey() + " = " + pairs.getValue()); } } } ```
66,615,409
I am working on some rest apis which are being developed in spring boot and data jpa. The database which is an oracle backed is *supposed to be modified out side of the jpa*. The problem I am having is the change made to the database out side the jpa is not propagating to the entities. I tired doing below but none worked for me. Clearing all cache ``` for (String name : cacheManager.getCacheNames()) { System.out.println(name); cacheManager.getCache(name).clear(); } ``` Clearing session cache ``` Session session = entityManager.unwrap(Session.class); session.clear(); ``` Refreshing entity from the entity manager ``` entityManager.refresh(entity); ``` Evicting entity manager cache ``` Cache cache = entityManager.getEntityManagerFactory().getCache(); cache.evictAll(); ``` Disabling cache in properties ``` spring.cache.type=NONE spring.jpa.properties.hibernate.cache.use_second_level_cache=false ``` Adding cachable false to entities ``` @Cacheable(false) ``` I tried literally everything and looking on all the possible solution from the google search and so. I may be making some mistake but coming from the django and python experience I thought it would be simple to disable caching or anything that prevents loading entities from the database directly but seems like its not so simple. Honestly have spent 2 night solving this but nothing worked for me. Any help would be much appreciated. Thank you.
2021/03/13
[ "https://Stackoverflow.com/questions/66615409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450410/" ]
Variable `int a` is not a field but, as you said, variable and immediately after the constructor will finish it's not accessible anymore and definitely not by `obj.a` You should move it's definition outside the constructor (so basically create **field** `a`) if you wish to use it this way [What is the difference between field, variable, attribute, and property in Java POJOs?](https://stackoverflow.com/questions/10115588/what-is-the-difference-between-field-variable-attribute-and-property-in-java)
It'a just a member variables, which doesn't belong to obj, u should declare a as local variables: ```java public class Test{ public int a = 5; public Test() { } } ```
65,224,876
If I generate *n* random numbers in the interval [0,1] then the mean will be around 0.5 and they will be uniformly distributed. How could an algorithm/formula look like if I want to get *n* random numbers still in the interval [0,1], however, e.g. with a mean of 0.6. They should still be distributed as uniformly as possible, however numbers bigger than > 0.5 a bit more frequently. So far I have only found solutions, which would assume a different distribution, e.g. with a normal distribution it would be quite easy to have numbers around the desired mean, but then numbers which are much larger or much smaller will be much less frequent and I'd like to avoid that. The programming language does not really matter. I am currently trying to do that with R however.
2020/12/09
[ "https://Stackoverflow.com/questions/65224876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522992/" ]
This is more of a statistics question: you don't want a uniform distribution, but rather a different distribution that is similar but different from the uniform. Just with your explanations, there are different distributions that could correspond to what you ask, for example you could make a density function with a smooth slope between 0 and 1. Or you could have a "bump" around 0.6. You should check out [the beta distribution](https://en.wikipedia.org/wiki/Beta_distribution), which has properties similar to what you want. It has two shape parameters, that can make the distribution more bumpy if you want. And you can repametrize it\* to input the desired mean. ```r x <- 0:200/100 - .5 plot(x, dunif(x), type="l", main = "Uniform") ``` ![](https://i.imgur.com/TGAzQpB.png) ```r plot(x, dbeta(x,1.1,1), type = "l", main = "Beta 1.1; 1") ``` ![](https://i.imgur.com/Irb0MbH.png) ```r plot(x, dbeta(x,1.3,1.1), type = "l", main = "Beta 1.3; 1.1") ``` ![](https://i.imgur.com/4ItAZST.png) Created on 2020-12-09 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0) * Reparametrization: as per the linked Wikipedia article, we have these relationships: α = μν, β = (1 − μ)ν Where μ is the mean, and ν a sample size parameter. So, if you want a given μ=0.06 you just need to choose a value of ν and that gives you the `shape1` and `shape2` parameters to feed in `rbeta()`.
You could do this by taking your sample first, then finding the number which, when the sample is raised to this power, gives it the desired mean. You can find this number using `optimize` and wrap it all in a handy function: ```r runif_skew <- function(n, mean) { y <- runif(n) o <- optimize(function(x) sapply(x, function(a) (mean(y^a) - mean)^2), c(-10, 10)) return(y^o$minimum) } ``` So testing, we get: ``` set.seed(1234) samp <- runif_skew(100, mean = 0.6) samp #> [1] 0.30960945 0.77430422 0.76552230 0.77502862 0.92241558 0.78630999 #> [7] 0.08116296 0.45539329 0.80322229 0.69863075 0.82094332 0.72083812 #> [13] 0.50599764 0.95795377 0.51517442 0.90868101 0.50935602 0.49043546 #> [19] 0.40456114 0.45505040 0.53784057 0.52495782 0.37103194 0.17624617 #> [25] 0.44066837 0.89294028 0.70697395 0.95303388 0.90519278 0.18954096 #> [31] 0.65484658 0.48881344 0.52680572 0.69352738 0.39794079 0.86223518 #> [37] 0.42123912 0.48243924 0.99575933 0.89101011 0.72677936 0.79033774 #> [43] 0.53343892 0.77398195 0.54978076 0.68960374 0.81035543 0.67690563 #> [49] 0.46727665 0.86577235 0.24520062 0.53146373 0.83594108 0.69148941 #> [55] 0.36335672 0.69103666 0.68362817 0.85703730 0.39023824 0.91515557 #> [61] 0.92467723 0.18062297 0.53836223 0.09909591 0.46218794 0.82914424 #> [67] 0.52998881 0.69444152 0.20229817 0.73470110 0.32085460 0.94070430 #> [73] 0.10245695 0.87648793 0.27287373 0.70224102 0.59704639 0.23844073 #> [79] 0.54152334 0.80478925 0.95961235 0.66699780 0.34984342 0.72033505 #> [85] 0.41547888 0.94396313 0.60141737 0.53255866 0.37226639 0.94260574 #> [91] 0.38017938 0.94500732 0.33838968 0.33502176 0.29703296 0.69667413 #> [97] 0.52262060 0.14178325 0.53142748 0.85143495 hist(samp) ``` ![](https://i.imgur.com/vF6ip8l.png) Note that the domain of the sample stays within (0, 1). And our mean is exactly right: ```r mean(samp) #> [1] 0.6 ``` Created on 2020-12-09 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)
50,993,321
We currently prepare a release for QA by merging from Dev as follows using GitHub and manually doing the following: * go to the repository * request a pull on the repo (click Pull Request) * set up merge of Dev into QA (select QA on the left, Dev on the right) * add a comment "Merging Dev into QA" and click Create Pull Request * I'm the only one working on it, so never any conflicts * create the pull request (click Merge Pull Request) * confirm the pull request (click Confirm Merge) Is there a way to do this in `git` or `hub`, including the record of the pull request, so it can be scripted?
2018/06/22
[ "https://Stackoverflow.com/questions/50993321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476792/" ]
If you want to do this with `hub` like you suggested, you can simply: * Make a file `pull_request_template.md` with content `Merging Dev into QA`. If you'd like, you can add more lines to the file, and the first line will act as the title, the rest will be the body. * `hub pull-request -F pull_request_template.md -b Dev -h QA | hub merge` to both open a PR and merge it Note, since `hub` is meant to be a drop-in replacement for `git`, you should run the command from the context of your repo's local directory. For more info on these commands, see their docs: [`hub`](https://hub.github.com/hub.1.html), [`pull-request`](https://hub.github.com/hub-pull-request.1.html), and [`hub-merge`](https://hub.github.com/hub-merge.1.html).
I am not sure about "including the record of the pull request"(because it's a ul version of the merge) but I have my own script to release hope helps you: ``` git checkout dev ``` to switch dev branch ``` git fetch https://gitlab.com/xx/xx.git ``` fetch changes on upstream of the master branch ``` git commit -a -m "changes" ``` commit your local changes: ``` git pull https://gitlab.com/xx/xx.git ``` get pull request from upstream ``` git checkout master ``` now switch to master branch ``` git merge --no-commit --no-ff dev ``` if you want to do a review before merge use above comment if not remove parameters ``` git push origin master ``` push your changes to the master branch ``` git reset --merge ``` If you wish to back those changes, just reset that merge. Edit: You can wite blow command as a bash or shell script
41,118
In several 4th edition books, I have seen traps and diseases, such as Deathsong (Book of Vile Darkness p33) or a magic crossbow turret. Is there a way for a character to learn how to create and use them? Or is it only for the Dungeon Master's use?
2014/06/18
[ "https://rpg.stackexchange.com/questions/41118", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/4566/" ]
Unfortunately, "real" traps violate 4e's action economy. However, for your specific example, the crossbow turret, it is possible. The Artificer has the power: [Animate Arbalester](http://www.wizards.com/dndinsider/compendium/power.aspx?id=7664) which animates a crossbow she's holding so it can make attacks as a minor action. For prepared traps in a stronghold or diseases, or any narrative device which is used outside of combat, use a skill challenge and narrate the consequences. If they're trying to defend their base or set up an ambush, encourage them. For in combat things, allow the players to refluff their powers, such that to the narrative, they *are* doing these things, and to the mechanics they are performing their normal class powers.
**Technically, No** I don't think there's a way you can do this with only the rules-as-written, but that's because I can't find the required elements, not because there's anything in the rules to prevent it. **Added Content** That being said, I think you can add this into your game through creating new content without adding or modifying any rules. By that, I mean creating new items and martial practices and/or rituals. By 'crossbow turret' I originally thought of something you would hand fire, which is more of a weapon, but maybe you meant something that fires on its own, which is more of a trap. **Trap Example** This is tough. I think rituals and/or martial practices are about the only way you can pull this off using just the mechanics available. These are extremely open-ended mechanics which can do just about whatever you want them to. The idea is to encapsulate longer, more complex actions that wouldn't make sense in combat. Combat actions are mostly represented by powers. I would think creating a magic turret would be a ritual, rather than a martial practice. There is a martial practice, Forge Weapon, that lets you create a magical weapon, but it's just a base magic weapon +X, rather than one with the kind of special properties it would need to fire on its own. Here's a possible ritual: > > Conjure Crossbow Turret > > > Level: 12 > > Component Cost: 1,000 gp, plus a Crossbow as a focus > > Market Price: 3,200 gp > > Category: Creation > > Key Skill: Arcana > > Time: 10 minutes > > Duration: 1 hour > > > You magically animate a crossbow in an adjacent empty square. The crossbow will aim and fire magical bolts at your opponents. The crossbow is not consumed as part of the ritual, and no ammunition is needed. > > > On your turn, you may command the crossbow to fire as a minor action. It performs a ranged basic attack on the nearest enemy in range using your statistics as if you were firing it normally. > > > The maximum number of shots it can fire is determined by your Arcana roll. The crossbow falls to the ground in its space once it has fired its maximum number of shots, or when the duration ends, whichever occurs first. > > > ``` Arcana Check Result Maximum Number of Shots 19 or lower 2 20-29 3 30-39 4 40+ 5 ``` This is pretty powerful, as most rituals don't help you directly in combat, and certainly don't deal damage. You will have to be careful about how it is used, and might need to re-balance it at some point. The Arcana check table could be modified, you could require a Standard action to fire, or you could prevent them from applying a proficiency bonus, just to name a few possible tweaks. **Weapon Example** Here's a possible way your characters could make a 'magic crossbow turret', by which I mean something along the lines of a light machine gun with a bipod. Create a new Superior Ranged Two-Handed Weapon: > > Weapon: Crossbow Turret > > Prof: +2 > > Damage: 2d8 > > Range: 30/60 > > Price: 75gp > > Weight: 25lbs > > Group: Crossbow > > Properties: Load Minor, Special > > > Crossbow Turret: This weapon cannot be fired unless it is set up, and cannot be moved unless it is taken down. Setting up and taking down are minor actions. > > > Allow your characters to create this weapon with the martial practice 'Master Artisan', or a magical version with the martial practice 'Forge Weapon'. **Disease Example** I don't have the Book of Vile Darkness, so I'm not sure what Deathsong does. The closest things I can think of which are not powers would be the Assassin (Executioner)'s poisons from Heroes of Shadow, or perhaps alchemical items which can be made by characters with the Alchemist feat from the Eberron Player's Guide. For either of these, you would simply need to create a new poison or a new alchemical item.
15,112,458
I have never used Flash before but have been given an FLA file which I would like to convert to an AVI file and upload to Youtube. When the file is opened in Adobe Flash CS6, only 1 frame appears in the timeline. I have discovered that one of the layers on the timeline is a movieclip. If I go to library in the right pane, and double click this item it opens up in the timeline as 360 frames long and made up of many layers and folders. Is there a way I can export this as an AVI file? I have attempted right clicking on it and selecting "Convert to Compiled Clip" but this doesn't seem to give any AVI options. I have also tried going to File > Export > Export Movie and selecting AVI, however the exported movie only comes out as 1 frame/second long. Thanks in advance for your help.
2013/02/27
[ "https://Stackoverflow.com/questions/15112458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1554699/" ]
You haven't initialized `carBootSaleList` in your code anywhere. You can either instantiate it in the method or with the declaration. ``` CarBootSaleList carBootSaleList = new CarBootSaleList(); ```
You have not initialized carBootSaleList. ``` CarBootSaleList carBootSaleList = new carBootSaleList(); ```
10,948,594
i'm trying to join a few tables together with following code ``` var result = (from n in db.tbl_NAWs join s in db.Status on n.Status equals s.StatusID join a in db.tbl_Afdelings on n.Afdeling equals a.ID_Afdeling join l in db.Locaties on n.Locatie equals l.LocatieID select new NAW_Dto() { ClassNR = n.ClassNr, Status = s.Beschrijving, Client = n.Aanspreekvorm, Locatie = l.Naam, Afdeling = a.Afdeling, KamerNr = n.Kamernummer }).ToList(); ``` But it keeps on returning empty, any ideas ?
2012/06/08
[ "https://Stackoverflow.com/questions/10948594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1063968/" ]
**Problem 1 :** Different applications use different scales for HSV. For example gimp uses `H = 0-360, S = 0-100 and V = 0-100`. But OpenCV uses `H: 0-179, S: 0-255, V: 0-255`. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie `(5,50,50) - (15,255,255)`. **Problem 2:** And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows: ``` cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV) ``` Now run it. I got an output as follows: ![enter image description here](https://i.stack.imgur.com/WqLw3.jpg) Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid. **EDIT:** As **Karl Philip** told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new `cv2` module, so users can compare the easiness and flexibility of new `cv2` module. ``` import cv2 import numpy as np img = cv2.imread('sof.jpg') ORANGE_MIN = np.array([5, 50, 50],np.uint8) ORANGE_MAX = np.array([15, 255, 255],np.uint8) hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX) cv2.imwrite('output2.jpg', frame_threshed) ``` It gives the same result as above. But code is much more simpler.
Here's a simple HSV color thresholder script to determine the lower/upper color ranges using trackbars for any image on the disk. Simply change the image path in `cv2.imread()`. Example to isolate orange: [![enter image description here](https://i.stack.imgur.com/SKIkW.jpg)](https://i.stack.imgur.com/SKIkW.jpg) ``` import cv2 import numpy as np def nothing(x): pass # Load image image = cv2.imread('1.jpg') # Create a window cv2.namedWindow('image') # Create trackbars for color change # Hue is from 0-179 for Opencv cv2.createTrackbar('HMin', 'image', 0, 179, nothing) cv2.createTrackbar('SMin', 'image', 0, 255, nothing) cv2.createTrackbar('VMin', 'image', 0, 255, nothing) cv2.createTrackbar('HMax', 'image', 0, 179, nothing) cv2.createTrackbar('SMax', 'image', 0, 255, nothing) cv2.createTrackbar('VMax', 'image', 0, 255, nothing) # Set default value for Max HSV trackbars cv2.setTrackbarPos('HMax', 'image', 179) cv2.setTrackbarPos('SMax', 'image', 255) cv2.setTrackbarPos('VMax', 'image', 255) # Initialize HSV min/max values hMin = sMin = vMin = hMax = sMax = vMax = 0 phMin = psMin = pvMin = phMax = psMax = pvMax = 0 while(1): # Get current positions of all trackbars hMin = cv2.getTrackbarPos('HMin', 'image') sMin = cv2.getTrackbarPos('SMin', 'image') vMin = cv2.getTrackbarPos('VMin', 'image') hMax = cv2.getTrackbarPos('HMax', 'image') sMax = cv2.getTrackbarPos('SMax', 'image') vMax = cv2.getTrackbarPos('VMax', 'image') # Set minimum and maximum HSV values to display lower = np.array([hMin, sMin, vMin]) upper = np.array([hMax, sMax, vMax]) # Convert to HSV format and color threshold hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, lower, upper) result = cv2.bitwise_and(image, image, mask=mask) # Print if there is a change in HSV value if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ): print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax)) phMin = hMin psMin = sMin pvMin = vMin phMax = hMax psMax = sMax pvMax = vMax # Display result image cv2.imshow('image', result) if cv2.waitKey(10) & 0xFF == ord('q'): break cv2.destroyAllWindows() ``` --- HSV lower/upper color threshold ranges ``` (hMin = 0 , sMin = 164, vMin = 0), (hMax = 179 , sMax = 255, vMax = 255) ``` Once you have determined your `lower` and `upper` HSV color ranges, you can segment your desired colors like this: ``` import numpy as np import cv2 image = cv2.imread('1.png') hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) lower = np.array([0, 164, 0]) upper = np.array([179, 255, 255]) mask = cv2.inRange(hsv, lower, upper) result = cv2.bitwise_and(image, image, mask=mask) cv2.imshow('result', result) cv2.waitKey() ```
8,819,229
I'm converting af Crystal report to a MS report. My expression in the Crystal report was like this: ``` =IIF(Fields!foo.Value Is Nothing and Fields!bar.Value Is Nothing, 0, IIF(Fields!foo.Value Is Not Nothing and Fields!bar.Value Is Nothing, Fields!foo.Value, IIF(Fields!foo.Value Is Nothing and Fields!bar.Value Is Not Nothing, Fields!bar.Value * -1, IIF(Fields!foo.Value Is Not Nothing and Fields!bar.Value Is Not Nothing, Fields!foo.Value, 0 )))) ``` The `Not` does not work here, even thought the text is blue. Can I use `Not` or something like `!`or do I have to go crazy with `IsNothing()`
2012/01/11
[ "https://Stackoverflow.com/questions/8819229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306028/" ]
You should be able to simplify your expression to: ``` IIF(Not Fields!foo.Value Is Nothing, Fields!foo.Value, IIF(Not Fields!bar.Value Is Nothing, Fields!bar.Value * -1, 0)) ``` EDIT: To return foo.Value - bar.Value when neither is null, try: ``` = IIF(Not Fields!foo.Value Is Nothing, Fields!foo.Value, 0) - IIF(Not Fields!bar.Value Is Nothing, Fields!bar.Value, 0) ```
Try this: ``` =IIF((Fields!foo.Value.Equals(System.DBNull.Value)), "YES", "NO") =IIF((Fields!foo.Value is System.DBNull.Value), "YES", "NO") ```
44,815,139
I am trying to push an app to Heroku using the CLI. When I enter the command `git add .` in the terminal, I keep getting this error: ``` /Users/me/.config/git/ignore': Permission denied '/Users/me/.config/git/attributes': Permission denied ``` Can anyone help?
2017/06/29
[ "https://Stackoverflow.com/questions/44815139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8128359/" ]
Here's how I solved it: 1. In Terminal `cd` to the User director with `cd ~`. 2. Change the directory permissions with `sudo chmod 755 .config` 3. Enter your login password.
sudo chmod -R 777 /path/to/dir worked for me.
11,635,402
I've been stuck for a while now. I have searched a lot and I can't find the easiest way to test entity classes or JPA operations against a postgres database. I've found how to using Spring, Mockito and other things, but I can't find the simplest way using pure Java. I have the following JUnit test: ``` public class ModelConverterTest { private static EntityManagerFactory emf; private static EntityManager em; public ModelConverterTest() { } @BeforeClass public static void setUpClass() throws Exception { emf = Persistence.createEntityManagerFactory("PU"); em = emf.createEntityManager(); // Retrieve an application managed entity manager } @AfterClass public static void tearDownClass() throws Exception { em.close(); emf.close(); //close at application end } @Before public void setUp() { ... } @After public void tearDown() { } /** * Test of SIMModelToModel method, of class ModelConverter. */ @Test public void testSIMModelToModel() { System.out.println("SIMModelToModel"); SIMModel simModel = new PESMModel(); simModel.addState(testState); Model expResult = null; Model result = ModelConverter.SIMModelToModel(em, simModel); assertTrue(expResult!=null); // TODO review the generated test code and remove the default call to fail. //fail("The test case is a prototype."); } } ``` and when running it, I get the following error: ``` java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/PersistenceContextType at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:787) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:447) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2442) at java.lang.Class.getDeclaredMethods(Class.java:1808) at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:104) at sun.reflect.annotation.AnnotationType$1.run(AnnotationType.java:101) at java.security.AccessController.doPrivileged(Native Method) at sun.reflect.annotation.AnnotationType.<init>(AnnotationType.java:100) at sun.reflect.annotation.AnnotationType.getInstance(AnnotationType.java:84) at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:221) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:88) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:70) at java.lang.reflect.Field.declaredAnnotations(Field.java:1033) at java.lang.reflect.Field.getDeclaredAnnotations(Field.java:1026) at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:196) at org.junit.runners.model.FrameworkField.getAnnotations(FrameworkField.java:26) at org.junit.runners.model.TestClass.addToAnnotationLists(TestClass.java:52) at org.junit.runners.model.TestClass.<init>(TestClass.java:45) at org.junit.runners.ParentRunner.<init>(ParentRunner.java:73) at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55) at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57) at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29) at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57) at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24) at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110) at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175) at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68) ``` My persistence.xml file is: ``` <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="PU" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>jdbc/modelsystemdb</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties/> </persistence-unit> </persistence> ``` What should I do to make the test run?
2012/07/24
[ "https://Stackoverflow.com/questions/11635402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1238957/" ]
Quoting [Trouble With Crippled Java EE 6 APIs in Maven Repository And The Solution](http://www.adam-bien.com/roller/abien/entry/trouble_with_crippled_java_ee) by Adam Bien: > > Instead of using > > > ``` <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> ``` > > You should use alternative (geronimo, jboss etc.) dependencies: > > > ``` <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-ejb_3.1_spec</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-jpa_2.0_spec</artifactId> <version>1.0</version> <scope>provided</scope> </dependency> ```
In my case under Run Configurations/ClassPath on the the project, click Edit and check "Only include exported entries" that did the trick.
2,458,621
Consider I have an array of elements out of which I want to create a new 'iterable' which on every *next* applies a custom 'transformation'. What's the proper way of doing it under python 2.x? For people familiar with Java, the equivalent is Iterables#transform from google's collections framework. Ok as for a dummy example (coming from Java) ``` Iterable<Foo> foos = Iterables.transform(strings, new Function<String, Foo>() { public Foo apply(String string) { return new Foo(string); } }); //use foos below ```
2010/03/16
[ "https://Stackoverflow.com/questions/2458621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3887/" ]
A generator expression: ``` (foobar(x) for x in S) ```
Or by using `map()`: ``` def foo(x): return x**x for y in map(foo,S): bar(y) # for simple functions, lambda's are applicable as well for y in map(lambda x: x**x,S): bar(y) ```
73,067
When learning grammar in school, I was taught that any verb after the word "to" should be in present tense and no participles. i.e. To play instead of to playing, or to sleep instead of to sleeping etc. So, which sentence is correct? > > Looking forward to **see** you. > > > or > > Looking forward to **seeing** you. > > >
2015/11/11
[ "https://ell.stackexchange.com/questions/73067", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/26277/" ]
There's two different things going on here, both of which use the word *to*, which is probably what's confusing you. The rule your teacher taught you applies to infinitives, in the context of sentences where there are two verbs, like > > I like to run. > > > The verb following *to* is in the present tense, as is expected. In this case, *to* is known as a "particle," which is basically a word that doesn't fit into nice grammatical categories, but has some meaning. > > I like to running. > > > Is not correct. However, what's happening here is that *to* is a preposition connected to the adverb *forward*, which is modifying *looking*. You *look forward* to nouns. These sentences are all acceptable: > > I look forward to my wedding. > > > I'm looking forward to the weekend. > > > I was looking forward to this weekend, but I got sick. > > > So in this case, you have to use a gerund, the noun form of a verb following *forward to*. In English, the gerund is identical to the present progressive, so you get sentences like > > I look forward to seeing you. > > > I look forward to meeting you. > > > I'm looking forward to dogsledding this winter. > > > Each of these sentences are acceptable, and use a gerund (verbal noun). You can't use other forms of the verb after the preposition *to*, you can't say: > > I'm looking forward to see you. > > > I'm looking forward to saw you. > > >
"to" belongs to two different word classes. It can be a preposition + noun/pronoun as in "to someone/to something". And it can be the infinitive particle as in "to be, to have, to do". So it is no good learning "to look forward to" because the learner does not know what follows, a noun or an infinitive. The proper way is to learn "to look forward to sth (something). Then it is clear that a noun or gerund must follow and not an infinitive.
421,633
I have a project comprised of about 20 small `.sh` files. I name these "small" because generally, no file has more than 20 lines of code. I took a modular approach because thus I'm loyal to the [Unix philosophy](https://en.wikipedia.org/wiki/Unix_philosophy) and it's easier for me to maintain the project. **In the start of each `.sh` file, I put `#!/bin/bash`.** Simply put, I understand script declarations have two purposes: 1. They help the user recall what shell is needed to execute the file (say, after some years without using the file). 2. They ensure that the script runs only with a certain shell (Bash in that case) to prevent unexpected behavior in case another shell was used. --- When a project starts to grow from say 5 files to 20 files or from 20 files to 50 files (not this case but just to demonstrate) we have 20 lines or 50 **lines** of script declarations. I admit, even though it might be funny to some, it feels a bit redundant for me to use 20 or 50 instead say just **1 per project** (maybe in the **main file** of the project). Is there a way to avoid this alleged redundancy of 20 or 50 or a much greater number of lines of script declarations by using some "global" script declaration, in some main file?
2018/02/03
[ "https://unix.stackexchange.com/questions/421633", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/273994/" ]
Even though your project may now be solely consisting of 50 Bash scripts, it will sooner or later start accumulating scripts written in other languages such as Perl or Python (for the benefits that these scripting languages have that Bash does not have). Without a proper `#!`-line in each script, it would be *extremely difficult* to use the various scripts without also knowing what interpreter to use. It doesn't matter if every single script is executed *from other scripts*, this only moves the difficulty from the end users to the developers. Neither of these two groups of people should need to know what language a script was written in to be able to use it. Shell scripts executed without a `#!`-line and without an explicit interpreter are executed in different ways depending on what shell invokes them (see e.g. the question [Which shell interpreter runs a script with no shebang?](https://unix.stackexchange.com/questions/373223/which-shell-interpreter-runs-a-script-with-no-shebang) and especially [Stéphane's answer](https://unix.stackexchange.com/a/373294/116858)), which is not what you want in a production environment (you want consistent behaviour, and possibly even portability). Scripts executed with an explicit interpreter will be run by that interpreter regardless of what the `#!`-line says. This will cause problems further down the line if you decide to re-implement, say, a Bash script in Python or any other language. You should spend those extra keystrokes and always add a `#!`-line to each and every script. --- In some environments, there are multi-paragraph boilerplate legal texts in each script in each project. Be very happy that it's only a `#!`-line that feels "redundant" in your project.
> > Is there a way to avoid this alleged redundancy of 20 or 50 or a much greater number of lines of script declarations by using some "global" script declaration, in some main file? > > > There is - it is called portability or POSIX compliance. Strive to always write scripts in portable, shell-neutral way, source them only from a script that uses `#!/bin/sh` or when you use `/bin/sh` interactively (or at very least a POSIX-compliant shell such as `ksh`). However, portable scripts don't save you from: * needing to use features of one of the shells ( [ilkkachu's answer](https://unix.stackexchange.com/a/421657/85039) is an example) * needing to use scripting languages more advanced than shells (Python and Perl) * PEBKAC error: your script falls into hands of user J.Doe who runs your script not as *you* intended it, for example they run `/bin/sh` script with `csh`. --- If I may express my opinion, "avoiding redundancy" by eliminating `#!` is wrong goal. The goal should be *consistent* performance and *actually a working script* that works, and considers corner cases, follows certain general rules like [not-parsing-ls](https://mywiki.wooledge.org/ParsingLs) or [always-quoting-variables-unless-need-word-splitting](https://unix.stackexchange.com/a/68748/85039). > > They help the user recall what shell is needed to execute the file (say, after some years without using the file). > > > They're really not for user - they're for operating system to run proper interpreter. "Proper" in this case, means OS finds what is in shebang; if the code below it for wrong shell - that's author's fault. As for user memory, I don't think "user" of programs such as Microsoft Word or Google Chrome ever needed to know what language programs are written in; authors may need. Then again, scripts written portably may eliminate need to even remember which shell you used originally, because portable scripts should work in any POSIX-compliant shell. > > They ensure that the script runs only with a certain shell (Bash in that case) to prevent unexpected behavior in case another shell was used. > > > They don't. What actually prevents unexpected behavior is writing portable scripts.
42,204,375
I have 2 problems. Basic story: I have created a SIMPLE registration and login system. **Problem1:** If I try to register a new account then it says "user registration failed". At the moment it should say that because mysql can't get right information from forms. But problem is that I don't know why. Everything seems correct... **Problem2:** If I try to login with existent account then it seems that browser is only refreshing the page and nothing else... Registration with php code: ``` <?php require ('insert.php'); // If values posted, insert into the database. if (isset($_POST['username']) && isset($_POST['password'])){ $name = $_POST['name']; $email = $_POST['email']; $username = $_POST['username']; $password = $_POST['password']; // nimi refers to name, it's correct $query = "INSERT INTO `user` (nimi, email, username, password) VALUES('$name', '$email', '$username', '$password')"; //POST retrieves the data. $result = mysqli_query($connection, $query); if($result){ $smsg = "User Created Successfully."; } else { $fmsg = "User Registration Failed"; } } mysqli_close($connection); ?> <html> ... <body> ... <div> <form method="POST" class="form-horizontal" role="form"> <!-- Status, how registering went --> <?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?> <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?> <!-- Registration form starts --> <h2>Form</h2><br> <label for="Name"></label> <input name="name" type="text" id="name" maxlength="40" placeholder="Ees- ja perenimi" class="form-control" autofocus> <!-- lopp --> <label for="email"></label> <input name="email" type="email" id="email" maxlength="65" placeholder="Email" class="form-control"> <!-- lopp --> <label for="Username"></label> <input name="username" type="text" id="userName" maxlength="12" placeholder="Kasutajatunnus/kasutajanimi" class="form-control" required> <!-- lopp --> <label for="Password"></label> <input name="password" type="password" id="password" maxlength="12" placeholder="Parool" class="form-control" required> <button type="submit" class="btn btn-primary btn-block">Join</button> </form> <!-- /form --> </div> <!-- ./container --> ... </body> </html> ``` Login: ``` <?php session_start(); require ('insert.php'); //Is username and password typed? if (isset($_POST['username']) and isset($_POST['password'])){ //Making vars from inputs $username = $_POST['username']; $password = $_POST['password']; //Checking existent of values. $query = "SELECT * FROM `liikmed` WHERE username='$username' and password='$password'"; $result = mysqli_query($connection, $query) or die(mysqli_error($connection)); $count = mysqli_num_rows($result); //3.1.2 If values equal, create session. if ($count == 1){ $_SESSION['username'] = $username; } else { //If credentials doesn't match. $fmsg = "Invalid Login Credentials."; } } //if user logged in, welcome with message if (isset($_SESSION['username'])){ $username = $_SESSION['username']; echo "Hai " . $username . ""; echo "This is the Members Area"; echo "<a href='logout.php'>Logout</a>"; }else{} ?> <html> ... <body> ... <div id="bg"></div> <form method="POST" class="form-horizontal"> <h2>Login</h2><br> <label for="User"></label> <input name="username" type="text" maxlength="15" placeholder="Username" class="form-control" required autofocus> <label for="Password"></label> <input name="password" type="password" maxlength="50" placeholder="Password" class="form-control" required autofocus> <button type="submit" class="btn btn-primary btn-block">Enter</button> </form> </div> ... </body> </html> ``` And finally php database connection file (called insert.php): ``` <?php $connection=mysqli_connect("localhost","root","pw"); if (!$connection){ die("Database Connection Failed" . mysqli_error($connection)); } $select_db = mysqli_select_db($connection, 'my_database'); if (!$select_db){ die("Database Selection Failed" . mysqli_error($connection)); } ?> ```
2017/02/13
[ "https://Stackoverflow.com/questions/42204375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7099510/" ]
First of all in your login `PHP` code, you only started a `session` but you didn't tell the from where to direct to if login is successful. Add a `header` to the code. That is; ``` if ($count == 1){ $_SESSION['username'] = $username; header("Location: page.php"); //the page you want it to go to } ``` And your registration `PHP` code looks ok. Check your database table if you've misspelt anything there.
Your logic to set the $\_SESSION['username'] requires that the username and password combination exists once in your database. This might sound silly but can you confirm that this is the case (i.e. confirm that you have not created the same username and password combination). Altering the logic to be > 1 would also get around this temporarily. So your code ``` if ($count == 1){ $_SESSION['username'] = $username; } ``` should become ``` if ($count > 1){ $_SESSION['username'] = $username; } ```
38,335,046
Now that CGRectMake , CGPointMake, CGSizeMake, etc. has been removed in Swift 3.0, is there any way to automatically update all initializations like from `CGRectMake(0,0,w,h) to CGRect(x:0,y:0,width:w,height:h)`. Manual process is.. quite a pain. Not sure why Apple don't auto convert this when I convert the code to Current Swift Syntax...
2016/07/12
[ "https://Stackoverflow.com/questions/38335046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2105910/" ]
The simplest solution is probably just to redefine the functions Apple took away. Example: ``` func CGRectMake(_ x: CGFloat, _ y: CGFloat, _ width: CGFloat, _ height: CGFloat) -> CGRect { return CGRect(x: x, y: y, width: width, height: height) } ``` Put that in your module and all calls to `CGRectMake` will work again.
Short answer: don't do it. Don't let Apple boss you around. I *hate* `CGRect(x:y:width:height:)`. I've filed a bug on it. I think the initializer should be `CGRect(_:_:_:_:)`, just like `CGRectMake`. I've defined an extension on CGRect that supplies it, and plop that extension into *every single project* the instant I start. ``` extension CGRect { init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) { self.init(x:x, y:y, width:w, height:h) } } ``` That way, all I have to do is change "CGRectMake" to "CGRect" everywhere, and I'm done.
281
I've got an old SunBlade 100 workstation that I'm trying to install OpenBSD on. The first step in the process is to bring up the OpenFirmware prompt to select the boot medium, which you do by pressing `STOP`+`A`. The computer didn't have a keyboard when I bought it, but I found one that will work. However, it doesn't have a `STOP` key. Is there another way of bringing up the prompt?
2016/04/25
[ "https://retrocomputing.stackexchange.com/questions/281", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/4/" ]
I only know these a little from messing about with OpenFirmware, but I did run across [this reference that says](http://www.finnie.org/text/computers/sunblade100/): > > One glaring omission by Sun is that you cannot enter OBP from the OS > using a regular USB keyboard. You can enter OBP from the serial > console using Ctrl-Break, and Sun keyboards can do Stop-A, but there > is no way to enter OBP from a non-Sun USB keyboard. > > > Which is something I didn't know. I think this implies you are going to have to beg, borrow, or steal a keyboard. Or try to boot to the serial console. --- I do not have a SunBlade around anymore to test, but I just ran across a hint that you can get to the OBP if you push the power button twice after the first beep. Apparently, this was an alternative for this exact situation.
If you need a custom USB keyboard, this ought to be possible with any microcontroller which implementes a full USB device, so long as you can find the relevant codes to generate - that would maybe be simpler than sourcing the right hardware.
2,474,739
I'm working on a program which uses the System.Diagnostics.Debugger.Break() method to allow the user to set a breakpoint from the command-line. This has worked fine for many weeks now. However, when I was working on fixing a unit test today, I tried to use the debug switch from the command-line, and it didn't work. Here's what I've tried: * I've confirmed that the Debug() method is really being called (by putting a System.Console.WriteLine() after it) * I've confirmed that the build is still in Debug * I've done a clean build * I've restarted Product Studio A quick Google search didn't reveal anything, and the API documentation for .Net doesn't mention anything about this function not performing correctly. So... any ideas?
2010/03/19
[ "https://Stackoverflow.com/questions/2474739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1110905/" ]
I was using `Debugger.Launch()` method and it stopped working suddenly. Using ``` if (Debugger.IsAttached == false) Debugger.Launch(); ``` as suggested in [this answer](https://stackoverflow.com/a/2734204) also did not bring up the debugger. I tried resetting my Visual Studio settings and it worked!
Are you using VS 2008 SP1? I had a lot of problems around debugging in that release, and all of them were solved by this [Microsoft patch](http://support.microsoft.com/kb/957912). > > Breakpoints put in loops or in > recursive functions are not hit in all > processes at each iteration. > Frequently, some processes may pass > through many iterations of a loop, > ignoring the breakpoint, before a > process is stopped. > > > Breakpoints are hit, but they are not > visible when you debug multiple > processes in the Visual Studio > debugger. > > > There are a few other debugger-related problems also fixed.
9,243,055
I am puzzling with Amdahl's Law to determine performance gains and the serial application part and fail to figure out this one. Known is the following: ``` S(N) = Speedup factor for (N) CPU's N = Number of CPU's f = The part of the program which is executed sequential S(N) = N / ( 1 + f * ( N - 1 ) ) ``` If I have 4 CPU's and a speedup factor (performance gain) of 3x. What would *f* be? My guess: ``` S(N) = 3 (that's our performance gain using 4 CPU's) N = 4 ``` So entering these values in the formula: ``` 3 = 4 / ( 1 + f * ( 4 - 1 ) ) ``` Am I correct when I say that f = 0,11? Or do I need to set S(N) to 1 (so divide by 3)? Or am I doing something else wrong?
2012/02/11
[ "https://Stackoverflow.com/questions/9243055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204156/" ]
A classmate of mine gave the (so far working/right) answer for this. I made the following class: REMOVED TO COUNTERACT CONFUSION. This should solve it. EDIT: Ok, the previuos answer is wrong, but I found the solution. You first calculate The part that can be done parallel (it's on wikipedia but it took me a while to understand) and THEN you calculate the serial part. so the final class becomes this: ```java /** * @param s - The maximum performance profit. * @param n - The amount of processors that are usable.. * @return f - The sequential part of the program. */ public final double sequentialCalculation(final double s, final double n) { double p = 0; //the part that can be executed in parallel double f = 0; if (s <= 0) { throw new IllegalArgumentException("S > 0"); } if (n <= 0) { throw new IllegalArgumentException("N > 0"); } p = ((1 / s) - 1) / ((1 / n) - 1); f = 1 - p; return f; } ``` You are welcome.
I think you are thinking about it a little wrong if this is the equation you're supposed to be using, so let me try to explain. f is the percentage (aka, 0 <= f <= 1) of the time your program spent in the part of the code that you didn't parallelize in the single core implementation. For example, if you have a program like this: ``` // this takes 15 seconds init(); for (int i = 0; i < 10; i++) { // this takes 10 seconds, and will be split // between threads when in parallel calculate(); } // this takes 5 seconds finalize(); ``` This will run (in serial) in 15+(10\*10)+5=120 seconds. However, if implemented in parallel, there are 20 seconds of execution that can't be split amongst multiple cores. This means that even if the parallel piece is sped up so it only takes 10 seconds to perform all 10 iterations, the whole program will still take 30 seconds. This is what f helps tell us - how much of the problem can benefit from parallelization. In this example, as 20 seconds out of the total 120 must be done serially, f = 20/120 = 1/6. Using this new value of f, you can get the speed up according to Amdahl. One disclaimer - this is far from the only way of measuring speed up, and different methods have their own advantages and disadvantages.
38,893,697
I would like to write a function to return a string with html code to customize head title, description and keywords for multiple pages. I started with my `index.php` file and two auxiliary, `_head.php` and `_functions.php`. What do I have to do to implement this function? index.php: ---------- ``` <?php include "_functions.php; ?> <html> <?php echo make_head("My title", "My description", "My keywords); ?> <body> ... </body> </html> ``` \_functions.php: ---------------- ``` function make_head(title, description, keywords) { return file_get_contents("_head.php"); } ``` \_head.php ---------- ``` <head> ... <meta name="description" content="$description"> <meta name="keywords" content="$keywords"> <title>$title</title> ... </head> ```
2016/08/11
[ "https://Stackoverflow.com/questions/38893697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1195909/" ]
**\_functions.php:** ``` function make_head($title, $description, $keywords) { $head = include "_head.php"; return $head } ``` **\_head.php** ``` <head> ... <meta name="description" content="<?php echo $description; ?>" > <meta name="keywords" content="<?php echo $keywords; ?>" > <title><?php echo $title; ?></title> ... </head> ```
You can use include. In your function `make_head`, you can do something like this: ``` function make_head(title, description, keywords) { $html = include "_head.php"; return $html; } ``` When you include something, it loads it to your current state. So if you use `$title` or `$description` or `$keywords` in your `_head.php` file, they will be in the same scope and they can be used.
34,828,198
I want to use a full width div, so added container-fluid class which leaves blank space on left and right. I solved it using negative margin left and right. But the problem is the negative margin afftects bootstrap responsive nature. When I resize the left side contents are hidden and there is a horizontal scrollbar on resizing. ``` <div class="container-fluid"> <div class="row" style="background-color:gainsboro"> <div class="col-md-10"> </div> </div> </div> ```
2016/01/16
[ "https://Stackoverflow.com/questions/34828198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662214/" ]
add `overflow:hidden` to your container.
Another way to mimic <http://www.ichangemycity.com/about-us> and using Bootstraps "content centered" layout. JSFiddle here: <https://jsfiddle.net/osserpse/9L3g1ezw/4/> 1. Keep `.container` to make the text content to center on the view 2. Add a new class, `my-full-width`to `<div class="col-md-10 my-full-width>` where you want the background to span full width. As far as I know it's not possible to change/add Bootstraps `.row`or `.col-*` classes and retain control over their width and responsive behavior AND to create a background on full width of the *viewport*. (Side note: it's a best practice to scope custom classes in Bootstrap projects so is super simple to spot which classes are Bootstrap native and which are project specific; in my example I use `.my-*` **CSS:** ``` .my-full-width::after { content: ""; background-color: aliceblue; display: inline-block; position: absolute; top: 0; bottom: 0; right: -100%; left: -100%; z-index: 0 } // Add elements and classes here h1, p { position: relative; z-index: 1; //to make elements to render above the background } ```
26,380
I'm hitting the 4GB limit of FAT32 on USB drives more and more often. However, being able to unplug the device without unmounting it first is a must have for me. I've noticed exFAT recently, however I couldn't find any info on whether drives formatted with exFAT can be unplugged safely without unmounting. Can they?
2009/08/20
[ "https://superuser.com/questions/26380", "https://superuser.com", "https://superuser.com/users/7076/" ]
While it is not 100% safe to remove a FAT volume without unmounting, it is *safer* than NTFS. exFAT [has the following differences](http://www.tech-recipes.com/rx/2801/exfat_versus_fat32_versus_ntfs/) to FAT 32: * File size limit is now 16 exabytes. * Format size limits and files per directory limits are practically eliminated. * Like HPFS, exFAT uses free space bitmaps to reduce fragmentation and free space allocation/detection issues. * Like HTFS, permission systems should be able to be attached through an access control list (ACL). It is unclear if or when Vista will include this feature, however. Since caching is handled much in the same way, you should get the same unmounting behavior from exFAT as you did from FAT32.
I'd heard somewhere that on \*nix style OSes, I/O caching is done in such a way that it is much less safe to unplug a disk then on Windows. In my own experience, I have corruption issues (requiring a good `fsck`ing) semifrequently when I unplug drives in OSX. I rarely, if ever, have those issues in Windows, under both FAT32 and exFAT.
17,380,317
I developed a java desktop application where the user can manually load a file and press a button to start a simulation process. I want to automate the above two steps so that an external program can iteratively call this desktop application multiple times and run the simulation process without any human intervention every time. Any thoughts on how I can go about doing this?
2013/06/29
[ "https://Stackoverflow.com/questions/17380317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429050/" ]
ES6 added a spread operator to JavaScript. ``` function choose(choice, ...availableChoices) { return availableChoices[choice]; } choose(2, "one", "two", "three", "four"); // returns "three" ```
The nearest equivalent is the [`arguments` pseudo-array](http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/).
21,402,168
IU am experienced in Java, but new to Objective C, so this might be very stupid. Nevertheless, I have been struggling for a while now, searching for the reason why I get an expected expression error from the following code. ``` CGAffineTransform move = CGAffineTransformMakeTranslation(middleX, middleY); [shapePath applyTransform:move]; [shapePath stroke]; [shapePath fill]; ``` shapePath is a UIBezierPath, middleX and middleY are CFFloats. The error is a "parse issue", it just says "expected expression", on the first line above
2014/01/28
[ "https://Stackoverflow.com/questions/21402168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835112/" ]
Edit ==== With the extra context that you were using this inside a `switch` statement I know what is wrong. You can't declare variables inside a switch statement without enclosing the cases in curly brackets. You can read about why this is in [this answer](https://stackoverflow.com/a/5163657/608157) (in short, they don't introduce new scopes). For example, creating a variable like this gives the compiler error that you are facing: ![enter image description here](https://i.stack.imgur.com/zEATv.png) but if you add braces around the case (like below) then you can create variables within that scope ![enter image description here](https://i.stack.imgur.com/CbJJU.png) --- Original answer =============== There is no problem with the code that you have shown in that question. The following code works for me without any compiler errors: ``` UIBezierPath *shapePath = [UIBezierPath bezierPath]; CGFloat middleX = 10.0; CGFloat middleY = 10.0; CGAffineTransform move = CGAffineTransformMakeTranslation(middleX, middleY); [shapePath applyTransform:move]; [shapePath stroke]; [shapePath fill]; ``` You should look for other syntax errors in the just above what you have included in your question. For example, as [suggested in this answer](https://stackoverflow.com/a/14168319/608157), you may be missing a closing bracket (`}`) somewhere else in your code.
This code was in a switch clause. When I declared the move variable outside it, it disappeared. Don't know why though. Now it works.
28,216,144
I hope someone can help me to solve the following, probably technical, problem. I use wampserver on my desktop with windows 7, with the documentroot in the OneDrive folder. That works perfectly. Through OneDrive, I synchronize the files in the documentroot with another computer. Now I want to do the same on my tablet, running windows 8.1. I installed a new version of wamp. As installed, everything works fine. Now I want to change the directoryroot to a folder in OneDrive. So I adapted the file httpd.conf on two places: DocumentRoot "c:/wamp/www/" becomes DocumentRoot "c:/Users/Fred Simons/OneDrive/WWW/" and <Directory "c:/wamp/www/"> becomes <Directory "c:/Users/Fred Simons/OneDrive/WWW/"> After restarting the tablet, the wampserver icon is orange or red, Im am not sure. Clicking on localhost opens the browser, but it shows the message: cannot connect to the server at localhost. As already mentioned, the same construction works fine under windows 7. All files in OneDrive are available offline, so on the tablet they should be the true files and not dummies. It looks like a typo, but I do not see any. Many thanks for looking at my problem.
2015/01/29
[ "https://Stackoverflow.com/questions/28216144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2232379/" ]
Finally, I arrived at a somewhat unsatisfactory conclusion: it seems that, under Windows 8.1, folders in OneDrive cannot be used inside the WAMP root directory. My question above is an example of that. Another experiment I did was to set back the root directory to the default c:/wamp/www and the place OneDrive within this root directory. All subfolders outside OneDrive could be used, but all attempts to include a file from OneDrive failed. Under Windows 7, there is no problem in using OneDrive folders in the root directory. Hopefully, it will be possible again under Windows 10.
Try this: unckeck the `on demand` option on the `OneDrive` Settings and select directories to sync. wait some minutes.
71,386,334
This is my code: ``` const [focus1, setFocus1] = useState(false); <TextInput style={{ ...styles.input_container, borderColor: `${focus1 ? colors.darkPurple : "#b8b8b850"}`, borderWidth: `${focus1 ? 3 : 1}`, }} placeholder="Enter Username" placeholderTextColor={colors.lightGray} onFocus={() => setFocus1(true)} onBlur={() => setFocus1(false)} /> ``` The app crashes when the screen is loaded. How to change the borderWidht dynamically?
2022/03/07
[ "https://Stackoverflow.com/questions/71386334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11585967/" ]
The crash could be happening because you're giving the styles wrong. The backticks in the style are resulting in the specified values to be quoted twice. Border color would be resolved to this` ``` `"#b8b8b850"' ``` whereas it should be only quoted once. And borderwidth would be resolved into ``` `3` ``` whereas the value is supposed to be an integer and not a string. Try it like this. ``` <TextInput style={[ styles.input_container, borderColor: focus1 ? colors.darkPurple : "#b8b8b850", borderWidth: focus1 ? 3 : 1, ]} placeholder="Enter Username" placeholderTextColor={colors.lightGray} onFocus={() => setFocus1(true)} onBlur={() => setFocus1(false)} /> ```
`borderWidth` is supposed to be a number, see <https://reactnative.dev/docs/view-style-props#borderwidth> So you should write `borderWidth: focus1 ? 3 : 1`
15,224,826
I'm using Codeigniter transactions ``` $this->db->trans_start(); $this->db->query('AN SQL QUERY...'); $this->db->trans_complete(); ``` This works fine , the problem I have is that inside the `trans_start` and `trans_complete` I'm calling other functions and those functions deals with database so they contains inserts and update and some deletes ... ex: ``` $this->db->trans_start(); $this->utils->insert_function($data); $this->utils->update_function2($test); $this->db->trans_complete(); ``` Now if those functions are executed and some errors occur CodeIgniter won't do a rollback. What is the best way to deal with such issue? The only solution, I have in mind, is to return an error from those functions and inside those function add (`trans_stat` and `trans_complete`) And if it returns an error test an do `$this->db->trans_rollback` ex: ``` $this->db->trans_start(); $result = $this->utils->insert_function($data); if($result === false){ $this->db->trans_rollback(); } $this->db->trans_complete(); ``` Is there a better way of doing this? **Update 1:** As requested a sample of the external function i'm calling : ``` // insert_function contains $rec = array( 'numero' => $numero, 'transaction_id' => $id, 'debit' => $product_taxes['amount_without_taxes'], 'date' => $data['date_transaction'], ); $this->addExerciceAccountingRecords($rec); and addExerciceAccountingRecords contains function addExerciceAccountingRecords($records) { $this->db->insert('transactions_exercices', $records); } ```
2013/03/05
[ "https://Stackoverflow.com/questions/15224826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503412/" ]
What I tried was more of a trick, but it worked for me. ``` $this->db->trans_begin(); $rst1= $this->utils->insert_function($data); $rst2 = $this->utils->update_function2($test); if($this->db->trans_status() === FALSE || !isset($rst1) || !isset($rst2)){ $this->db->trans_rollback(); }else{ $this->db->trans_commit(); } ```
Try this procedure. It really work for me :) ``` $this->db->trans_start(); $this->utils->insert_function($data); $this->utils->update_function2($test); if($this->db->trans_status() === FALSE){ $this->db->trans_rollback(); }else{ $this->db->trans_complete(); } ```
26,545,307
I'am noob in sql and I have a question for you. I need to create a count in sql, I tried by no result. So I have a table: ``` Event Participant Participant count Test 123 3 Test 123 3 Test 456 1 Test 123 3 ``` I need to create a count for participant: Participant 123 have 3 participations, Participant 456 have 1 participation. Help me please. Thx so much in advance
2014/10/24
[ "https://Stackoverflow.com/questions/26545307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3348229/" ]
Problem is in assinging fillRange variable: I have updated it, check and let me know: ``` Sub why_u_no_work() Dim b As Integer Dim lastrowincurrfund As Integer Dim fundslistsym(0 To 0) As String Dim SourceRange As Range Dim fillRange As Range lastrowincurrfund = 142 b = 0 fundslistsym(b) = "DU" Set SourceRange = ThisWorkbook.Worksheets(fundslistsym(b)).Range("P1:AC1") Set fillRange = ThisWorkbook.Worksheets(fundslistsym(b)).Range("P1:AC" & lastrowincurrfund) SourceRange.AutoFill Destination:=fillRange, Type:=xlFillDefault End Sub ``` or ``` Sub why_u_no_work() Dim b As Integer Dim lastrowincurrfund As Integer Dim fundslistsym(0 To 0) As String Dim SourceRange As Range Dim fillRange As Range lastrowincurrfund = 142 b = 0 fundslistsym(b) = "DU" With ThisWorkbook.Worksheets(fundslistsym(b)) Set SourceRange = .Range("P1:AC1") Set fillRange = .Range("P1:AC" & lastrowincurrfund) SourceRange.AutoFill Destination:=fillRange, Type:=xlFillDefault End With End Sub ```
I think I have found the solution. The Range.Autofill method does not work if the sheet in which the method is going to be used is not active. So to overcome the probelm one has to just add: `ThisWorkbook.Worksheets(fundslistsym(b)).Activete and that is all... I manged to make the code run, yet I do not understand why activating the sheet is required. If anyone can help with tht please tell me. I am so eager to know why it is like that. Many thanks Artur
2,158,719
I've been asked to help with the following school problem on geometry. In the triangle $\Delta ABC$ one has $AB = 60$, $AC = 80$. Point $O$ is the centre of the circumscribed circle. Point $D$ belongs to the side $AC$. Additionally, one has $AO \perp BD$. One is asked to find $CD$. (just in case, the answer is $35$) I am really puzzled, since the information given clearly does not fix the triangle. I know how to solve the problem under the assumption that point $O$ belongs to $BD$. In this case, the solution goes as follows: Denote $\alpha = \angle OAC$, $\beta = \angle OBC$. 1. $\angle ACB = \dfrac{1}{2}\angle AOB = 45^\circ$. 2. From the sum of angles of the triangle $\triangle ABC$, one has: $$\alpha + \beta = 45^\circ$$ 3. The law of sines for the triangle $\triangle ABC$ gives: $$\dfrac{AC}{\sin(\beta + 45^\circ)}=\dfrac{AB}{\sin(45^\circ)}$$ From where one can find $\beta$: $$\beta = \arccos\left( \dfrac{2\sqrt2}{3} \right) + 45^\circ$$ 4. From the triangle $\triangle AOD$ one finds: $$CD = AC - AD = AC - \dfrac{AO}{\cos(\alpha)}= AC - \dfrac{AO}{\cos(45^\circ - \beta)}$$ Substituting the value of $\beta$ indeed gives $CD = 35$. Now, I have two questions: 1. Is it possible to get the answer without the assumption I have made (or any other one). 2. Can anyone present an easier solution? (just in case, this is one of $26$ problems in the $9$th grade quiz in Russian middle school — students are obviously limited in time and are not supposed to use Mathematica and even Stack Exchange)
2017/02/24
[ "https://math.stackexchange.com/questions/2158719", "https://math.stackexchange.com", "https://math.stackexchange.com/users/340940/" ]
Draw the line $AO$ and let $E$ be the second point of intersection of $AO$ with the circumcircle of triangle $ABC$ (the first point of intersection being $A$). Then $AE$ is the diameter of the circumcircle and therefore triangle $ABE$ is a right triangle ( $\angle \, ABE = 90^{\circ}$ ). Let $H$ be the itnersection point of $BD$ and $AO$. [![enter image description here](https://i.stack.imgur.com/cvgUV.png)](https://i.stack.imgur.com/cvgUV.png) Since by assumption $BD$ is orthogonal to $AO$, and therefore orthogonal to $AE$, segment $BD$ is an the altitude of $ABE$ through $B$. Hence triangles $AHB$ and $ABE$ are similar and thus $$\frac{AH}{AB} = \frac{AB}{AE}$$ which is equivalent to $$AH \cdot AE = AB^2 = 60^{2}$$ Triangle $AEC$ is right triangle ( $\angle \, ACE = 90^{\circ}$ ) and so is $AHD$, which means they are similar and thus $$\frac{AD}{AE}=\frac{AH}{AC} $$ which is equivalent to $$AD \cdot AC = AH \cdot AE = 60^2$$ and since $AD = AC - CD = 80 - CD$ and $AC = 80$ get the equation $$(80-CD)\cdot 80 = 60^2$$ When you solve it you get $CD = 35$.
[![enter image description here](https://i.stack.imgur.com/xgjwz.png)](https://i.stack.imgur.com/xgjwz.png) Let $G$ be the point of intersection of $AO$ and $BD.$ $AGB$ is a right triangle. Drop altitudes $OE$ and $OF$ to sides $AB$ and $AC$ respectively Since $AOB$ and $AOC$ are isosceles, these altitudes bisect their respective sides. $AFO$ is similar to $AGB$ $AF:AO = AG: AB$ $AO\cdot AG = 1800$ $AEO$ is similar to $AGD$ $AE:AO = AG: AD$ $AE\cdot AD = 1800$ $AD = 45$ $CD = 35$
68,591,567
there I'm new to C. I'm currently reading the K&R. There I got confused by a definition in it about the text streams "*A text stream is a sequence of characters divided into new lines;each line consists of 0 or more characters followed by a newline character*." And trying to knowing about this streams I was introduced to a new term namely buffer. I just know that: * A continuous flow of data (bytes or characters) in between Input and Output devices is a **STREAM** . * A temporary storage area in main memory to store the input or output data temporarily is a **BUFFER**. I don't say that I'm right, but it's my basic idea upon those terms. I want to know, what actually buffer & stream are and how these 2 things(i.e, stream & buffer) work together, in the non-abstract level of C implementation.
2021/07/30
[ "https://Stackoverflow.com/questions/68591567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14977752/" ]
You have three streams in C, `stdin`, `stdout`, and `stderr`, you can also think of files you have opened with `fopen` for example as a stream. `stdin` is generally the keyboard, `stdout` is generally your monitor, `stderr` is generally also your monitor. But they don't have to be, they are abstractions for the hardware. If for example you didn't have a keyboard but a keypad on a bank ATM for example, then `stdin` would be the keypad, if you didn't have a monitor but instead had a printer, then `stdout` would be the printer. You change what hardware they are using with calls to your operating system. You can also change their behaviour, again, through calls to your operating system, which is beyond the scope of what you're asking. So in a way, think of the buffer as the memory allocated by the operating system associated with the stream to hold the data received from the hardware component. When you type at your keyboard for example the characters you type aren't being capture directly by your IDE, they are moving from there into the buffer, then you read the buffer. That's why, for example, you have to hit enter before your code starts interacting with whatever you typed into the keyboard, because `stdin` is line buffered. Control passes from your program to the operating system until it encounters something that sends control back to your program, in a normal situation that would be the newline character. So in a way, think of it like this, the stream is the device (keyboard, monitor, or a file on your hard drive), the buffer is where the data is held while the operating system has control, and then you interact with the buffer while you are processing the data. That abstraction allows you to use all of these different things in a common manner regardless of what they are, for example: `fgets(str, sizeof(str), STREAM)` ... stream can be any input stream, be it `stdin` or a file. Taking it a step further that's why new programmers get thrown off by `scanf` for an `int` followed by an `fgets`, because `scanf` reads the `int` from the buffer but leaves the `\n` in the buffer ... then the call to `fgets` reads the `\n` that `scanf` left there and the new programmer is left wondering why they were unable to input any data. So your curiosity about streams and buffers will serve you well as you move forward in your learning about C.
Two common abstractions of I/O devices are: Streams - transfers a variable number of bytes as the device becomes ready. Block - transfers fixed-size records. A buffer is just an area of memory which holds the data being transferred.
56,435,515
How do I sort an array by the value of a key and preserve the order if the value is equal. **Array:** ``` Array ( [0] => Array ( [id] => 65 [count] => 2 ) [1] => Array ( [id] => 67 [count] => 500 ) [2] => Array ( [id] => 61 [count] => 225 ) [3] => Array ( [id] => 58 [count] => 2 ) ) ``` **Desired output:** ``` Array ( [0] => Array ( [id] => 67 [count] => 500 ) [1] => Array ( [id] => 61 [count] => 225 ) [2] => Array ( [id] => 65 [count] => 2 ) [3] => Array ( [id] => 58 [count] => 2 ) ) ``` I want to sort by the 'count' key from highest to lowest.
2019/06/03
[ "https://Stackoverflow.com/questions/56435515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2068016/" ]
**For Objective-C users** Just Use this code ``` [vc setModalPresentationStyle: UIModalPresentationFullScreen]; ``` Or if you want to add it particular in iOS 13.0 then use ``` if (@available(iOS 13.0, *)) { [vc setModalPresentationStyle: UIModalPresentationFullScreen]; } else { // Fallback on earlier versions } ```
If you have a UITabController with Screens with Embeded Navigation Controllers, you have to set the UITabController **Presentation** to FullScreen as shown in pic below [![enter image description here](https://i.stack.imgur.com/kjGa0.png)](https://i.stack.imgur.com/kjGa0.png)
16,775,115
I am trying to count total number of times that each individual column is greater than zero, grouped by the driver name. Right now I have; ``` SELECT drivername , COUNT(over_rpm) AS RPMViolations , COUNT(over_spd) AS SpdViolations , COUNT(brake_events) AS BrakeEvents FROM performxbydriverdata WHERE over_rpm > 0 OR over_spd > 0 OR brake_events > 0 GROUP BY drivername ``` This gives me all of the non-zero values but I get a display as: * Bob Smith 62 62 62 * Nathan Jones 65 65 65 * etc. I'm trying to get a count of non-zeros in each individual values.. each violation should be grouped separately.
2013/05/27
[ "https://Stackoverflow.com/questions/16775115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2117858/" ]
Use NULLIF to change zero to NULL, count ignores NULL ``` SELECT drivername, COUNT(NULLIF(over_rpm,0)) AS RPMViolations, COUNT(NULLIF(over_spd,0)) AS SpdViolations, COUNT(NULLIF(brake_events,0)) AS BrakeEvents FROM performxbydriverdata GROUP BY drivername; ``` You can probably remove the WHERE clause too with this group to improve performance OR conditions often run badly because of matching a good index Using HAVING (as per other answers) will remove any rows where all 3 aggregates are zero which may or may not be useful for you. You can add this if you want. Saying that, the WHERE implies that at least one row has non-zero values so you **don't need** both WHERE and HAVING clauses
Putting filter predicate[s] inside of a Sum() function with a case statement is a useful trick anytime you need to count items based on some predicate condition. ``` Select DriverName, Sum(case When over_rpm > 0 Then 1 Else 0 End) OverRpm, Sum(case When over_spd > 0 Then 1 Else 0 End) OverSpeed, Sum(case When brake_events > 0 Then 1 Else 0 End) BrakeEvents, etc. FROM performxbydriverdata Group By DriverName ```
30,322,885
I am just looking on a chat application which is given in the <https://github.com/nwah/peerjs-audio-chat> Actually its quite intresting to chat with just two browsers. I have some doubts regarding this peer js. I got also my free Api key from there website I just started the application with the instructions given in the github link. ``` 1. But What should i do, if i want to get Connected with another user with another API key. 2. Suppose There is someone in another computer, with another Api key, Will he'll be connected, Is there any specification if he want to run the app in same port number as given in for my app ``` Because I am not getting connected i tried many ways, Always getting error for the connection, Is there any thing else that Other user should do, if he want to connect with me...? Thanks
2015/05/19
[ "https://Stackoverflow.com/questions/30322885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3024251/" ]
You can write simply ``` for(int i = 0; i < VERTICES_NR; i++) ^^^ _vertices[i] += temp; ``` If you want to define the subscript operator then it can look like ``` Vector & operator []( int n ) { return _vertices[i]; } const Vector & operator []( int n ) const { return _vertices[i]; } ``` In this case within the class definition you can use it either like ``` operator[]( i ) ``` or ``` this->operator[]( i ) ``` or ``` ( *this )[i] ```
The overloaded operator function can be called explicitly by its name, like this: ``` operator[](i) = operator[](i) + temp; ```
5,081,502
How do you store a object with size bigger than 1 MB in memcache? Is there a way to split it up, but have the data still be accessible with the same key?
2011/02/22
[ "https://Stackoverflow.com/questions/5081502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/575944/" ]
I use the following module ("blobcache") for storing values with sizes greater than 1Mb in GAE's memcache. ``` import pickle import random from google.appengine.api import memcache MEMCACHE_MAX_ITEM_SIZE = 900 * 1024 def delete(key): chunk_keys = memcache.get(key) if chunk_keys is None: return False chunk_keys.append(key) memcache.delete_multi(chunk_keys) return True def set(key, value): pickled_value = pickle.dumps(value) # delete previous entity with the given key # in order to conserve available memcache space. delete(key) pickled_value_size = len(pickled_value) chunk_keys = [] for pos in range(0, pickled_value_size, MEMCACHE_MAX_ITEM_SIZE): # TODO: use memcache.set_multi() for speedup, but don't forget # about batch operation size limit (32Mb currently). chunk = pickled_value[pos:pos + chunk_size] # the pos is used for reliable distinction between chunk keys. # the random suffix is used as a counter-measure for distinction # between different values, which can be simultaneously written # under the same key. chunk_key = '%s%d%d' % (key, pos, random.getrandbits(31)) is_success = memcache.set(chunk_key, chunk) if not is_success: return False chunk_keys.append(chunk_key) return memcache.set(key, chunk_keys) def get(key): chunk_keys = memcache.get(key) if chunk_keys is None: return None chunks = [] for chunk_key in chunk_keys: # TODO: use memcache.get_multi() for speedup. # Don't forget about the batch operation size limit (currently 32Mb). chunk = memcache.get(chunk_key) if chunk is None: return None chunks.append(chunk) pickled_value = ''.join(chunks) try: return pickle.loads(pickled_value) except Exception: return None ```
A nice workaround is to use layer\_cache.py, a python class written and used at Khan Academy (open source). Basically it's a combination of in-memory cache (cachepy module) with memcache being used as a way of syncing the in-memory cache through instances. [find the source here](https://code.google.com/p/khanacademy/source/browse/trunk/layer_cache.py?r=857) and read Ben Kamens blog post about it [here](http://bjk5.com/post/2320616424/layer-caching-in-app-engine-with-memcache-and-cachepy).
54,813,803
The problem I have may be a fairly obvious one but im new to c# and coding in general. I have looked around online but I couldn't find anything that could help me. This is a demo code I prepared for the situation im in. ``` class Program { class Person //The class { public string jobTitle = "Cashier"; public void Greet() { Console.WriteLine("Hi, im bob."); } } public static void Main(string[] args) //Method it was instantiated in { Person Bob = new Person(); Bob.Greet(); } public static void OtherMethod() //Method I want to access it in { Bob.Greet(); Console.WriteLine(Bob.jobTitle); //"'Bob' does not exist in the current context" } } ``` This is a serious problem for me because im working on something that has alot of classes and I am forced to use temp variables to transfer the class data from Main() into the parameters of another method. Also on a side note, none of the data im trying to access is static. I can access it in Main(). I just want to know if im missing something here?
2019/02/21
[ "https://Stackoverflow.com/questions/54813803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11092295/" ]
there is no meaning of having class inside class (`Person` class in `Program` class) if you need to access `Bob` within same class check the code below ``` public class Person { public string jobTitle = "Cashier"; public void Greet() { Console.WriteLine("Hi, im bob."); } } public static class Program { private Person _bob; public static void Main(string[] args) { _bob = new Person(); _bob.Greet(); OtherMethod(); } public static void OtherMethod() { _bob.Greet(); Console.WriteLine(_bob.jobTitle); } } ```
your problem is a matter of scope and context. It's common to have these problems at first starting with programming. Pointing out why you cannot access Bob in the second method: ``` class Program { class Person //The class { public string jobTitle = "Cashier"; public void Greet() { Console.WriteLine("Hi, im bob."); } } public static void Main(string[] args) //Method it was instantiated in { // Bob is instantiated local to the main method Person Bob = new Person(); Bob.Greet(); //You didn't call OtherMethod() here } public static void OtherMethod() //Method I want to access it in { // Since Bob was not passed in as a parameter or accessible via a global var, here you dont have access to it. access it Bob.Greet(); Console.WriteLine(Bob.jobTitle); //"'Bob' does not exist in the current context" } } ``` Here, building on your example, a version that works: ``` class Program { static Person GlobalBob; // must be static because we are instantiating it inside a static method class Person { public string jobTitle = "Cashier"; public void Greet() { Console.WriteLine("Hi, im bob."); } } public static void Main(string[] args) //Method it was instantiated in { GlobalBob = new Person(); GlobalBob.Greet(); OtherMethod(); //Call your OtherMethod here otherwise it's not gonna be executed } public static void OtherMethod() //Method I want to access it in { GlobalBob.Greet(); Console.WriteLine(GlobalBob.jobTitle); //Here we have access to GlobalBob Console.ReadLine(); //Wait for you to press a key so you can read the output ! } } ``` Hope it helps!
82,713
I often see extremely beautiful and sharp portraits like these: I was wondering what makes them so sharp and beautiful: Camera quality? Lighting? Post-processing? Luck? How would I go about if I want to take a photo like one of these? [![enter image description here](https://i.stack.imgur.com/bf7tS.jpg)](https://i.stack.imgur.com/bf7tS.jpg) [![enter image description here](https://i.stack.imgur.com/EPuGx.jpg)](https://i.stack.imgur.com/EPuGx.jpg)
2016/09/10
[ "https://photo.stackexchange.com/questions/82713", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/56577/" ]
Camera quality? No. Any recent DSLR like camera can do it, even MFT. Lighting? Yes, good light is key-essential in any photography, this is no exception. Post-processing? Yes/No, post-processing of RAW files yes, but it can be done in camera as jpeg files - but that's kind of a PP as well. Luck? Nope,skills more than luck, although anything can be done by luck. Luck doesn't consistently give you great tact sharp portraits, only skills can do that. Next to light a good lens is the most important camera gear requirement, although the most important part overall is skill.
Here is one tip for sharpening without looking fake in post. Duplicate the layer in PS. Go to Filter > Other > High Pass. Set it to lightly show the edges only. Apply it and set that layer to Overlay, Use opacity to control how much you want to sharpen the image.
402,359
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
2008/12/31
[ "https://Stackoverflow.com/questions/402359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16584/" ]
In ubuntu 12.04, I have found that the only place you need to look by default is under ``` /usr/local/lib/python2.7/ ``` And simply remove the associated folder and file, if there is one!
I just uninstalled a python package, and even though I'm not *certain* I did so perfectly, I'm reasonably confident. I started by getting a list of *all* python-related files, ordered by date, on the assumption that all of the files in my package will have more or less the same timestamp, and no other files will. Luckily, I've got python installed under `/opt/Python-2.6.1`; if I had been using the Python that comes with my Linux distro, I'd have had to scour all of `/usr`, which would have taken a long time. Then I just examined that list, and noted with relief that all the stuff that I wanted to nuke consisted of one directory, `/opt/Python-2.6.1/lib/python2.6/site-packages/module-name/`, and one file, `/opt/Python-2.6.1/lib/python2.6/site-packages/module-x.x.x_blah-py2.6.egg-info`. So I just deleted those. Here's how I got the date-sorted list of files: `find "$@" -printf '%T@ ' -ls | sort -n | cut -d\ -f 2-` (I think that's got to be GNU "find", by the way; the flavor you get on OS X doesn't know about "-printf '%T@'") I use that *all* the time.
36,559,349
So i've read a handful of SO posts and some blogs, but still can't figure out why my code isn't working. My code: ``` function myFunct(d) { if (typeof d.parent.name == "undefined") { console.log("undefined") ;} else { console.log("defined") ;} } ``` `d` is an object that looks something like: ``` Object { children: Object, count: 676 } ``` I've tried using `(!d.parent.name)`, `hasOwnProperty`, `===`, and as above using `typeof`. Any suggestions? The error I recieve is `TypeError: d.parent.name is undefined` UPDATE: Ok thanks everyone for the input, and my apologies if the question was confusing. I was actually looking for `d.parent.parent` but tried to simplify the question by using `d.parent`. I think the problem is that `d.parent` is not defined so it doesn't even get to `d.parent.parent`. Sorry for not being more specific!
2016/04/11
[ "https://Stackoverflow.com/questions/36559349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3469243/" ]
If you want an undefined-safe check all the way down your object tree, you can use: ``` if( typeof( ((d || {}).parent || {}).name ) === 'undefined') { } ``` If you have the luxury of having Lodash at your disposal: ``` var d = { parent: { name: "Joe" } }; if ( typeof (_.get(d, "parent.name")) === 'undefined' ) { } ```
I believe the error is the property identifier `parent`. Are you sure your object has the property? The identifier `d` may be invalid because `parent` doesn't exists.
2,513,165
I got nabbed by the following bug *again* and would like some clarification to exactly why it is a bug. I have a simple UITableView that loads some data: ``` // myclass.h @property (nonatomic, retain) NSArray *myData // myclass.m @synthesize myData; - (void) viewDidLoad { ... myData = someDataSource // note the lack of self } - (UITableViewCell *) cellForRowAtIndexPath ... { ... cell.textLabel.text = [self.myData objectAtIndex:indexPath.row]; // EXC_BAD_ACCESS } ``` The table first loads fine, but when scrolling **up** enough that one of the cells is totally out of the view I then get the EXC\_BAD\_ACCESS error. Am I missing something in regards to @property retain. My understanding is that it releases anything that the pointer was previously pointing to before the reassignment. If I am correct then why would not using self. cause any problems? Thanks for the help. \*\*\*\* Update Why is is that in all the examples that I have checked with to the release of objects within the dealloc method without the self? ``` - (void) dealloc { [someArray release]; [someTableView release]; } ```
2010/03/25
[ "https://Stackoverflow.com/questions/2513165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26849/" ]
Bazaar's biggest strength over all other system is its flexibility. For example, developers can work in either traditional centralized mode, or they can work in the newer-style, distributed mode. Oh, and they can do it simultaneously on the same repository. Oh, and they can switch back and forth as much as they like. Bazaar also has two things which are fairly rare to version control systems: excellent documentation and available commercial support. For me, Bazaar has the most flexibility, best documentation and in general just works. Those things are far more important to me than the fact pulling a branch would be 10 seconds faster with git for example.
Bazzar work slow on large project with huge history (bzr log on file from Emacs sources take 1 minute!). And have inefficient http:// protocol (designed for local net connection, require ~5 MiB of traffic at least for any remote operation).
54,467,980
I'm working on a `RecyclerView` and I want to add a half line, picture & half line before it. However I have no idea of how to reproduce it. Can you please help me to get a similar shape? [![half line + pictogram + half line](https://i.stack.imgur.com/jaBCr.png)](https://i.stack.imgur.com/jaBCr.png)
2019/01/31
[ "https://Stackoverflow.com/questions/54467980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10088784/" ]
You didn't instantiate Workload. ``` w1 = Workload() ```
Yep, as Daniel said, you didn't instantiate Workload. Also in the **init** you are using self to initiate workload and totalchore, then, as you are not recieving it for parameter, those variables are going to nowhere.
22,950,254
I know how to count lines using grep which match certain parameters and does not match certain parameters separately. But how can we combine this functionality. For Example: ``` Name Date Value A 04-08-2014 1000 B 04-08-2014 2000 C 04-06-2014 3000 D 04-06-2014 1000 2000 04-08-2014 5000 ``` So, I am looking for command which counts number of lines which matches Date 04-08-2014 but does not have Value 2000. Note: 2000 should be part of "Value" column and dates should be in "Date" column. Any help would be highly appreciated !
2014/04/08
[ "https://Stackoverflow.com/questions/22950254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1337072/" ]
Using `awk`: ``` $ awk '$2=="04-08-2014" && $3!="2000" {count++}END{print count}' file 2 ```
> > grep "04-08-2014" file | grep -vc "2000" > > >
58,805,196
I currently have a `ul` acting as the navbar. I want it to open with the click of a button by changing its width, but it's not working. When the button is clicked nothing happens, however it should change the width and make the `ul` appear. ```js function openNav() { document.getElementByClass("nav").style.width = "250px"; } function closeNav() { document.getElementByClass("nav").style.width = "0px"; } ``` ```css .nav { list-style-type: none; margin: 0; padding: 0; width: 0; background-color: #f1f1f1; height: 100%; /* Full height */ position: fixed; /* Make it stick, even on scroll */ overflow: auto; /* Enable scrolling if the sidenav has too much content */ transition: 0.5s; } .nav li a { display: block; color: #000; padding: 8px 16px; text-decoration: none; } ``` ```html <button onclick="openNav()">Open Nav</button> <ul class="nav"> <li><a href="{% url 'sheets:list' %}" class="">Nav Element</a></li> </ul> ```
2019/11/11
[ "https://Stackoverflow.com/questions/58805196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780944/" ]
There is no such thing as `getElementByClass()`, you should use `getElementsByClassName()` instead, like in this code example: ``` function openNav() { document.getElementsByClassName("nav")[0].style.width = "250px"; } function closeNav() { document.getElementsByClassName("nav")[0].style.width = "0px"; } ```
You can make so ``` <button onclick="openNav()">Open Nav</button> <ul id='nav'> <li><a href="{% url 'sheets:list' %}" class="">Nav Element</a></li> </ul> </ul> <button onclick="openNav()">Open Nav</button> <ul id="nav"> <li><a href="{% url 'sheets:list' %}" class="">Nav Element</a></li> </ul> ``` and width will change but you cant see it so change font-size
291,403
I'm trying to do a supervised classification in ArcGIS Pro that will allow me to find Tar and Gravel rooftops in Miami. I have Landsat data but just wondering if there is imagery out there with better spatial resolution that might work better?
2018/08/01
[ "https://gis.stackexchange.com/questions/291403", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/125976/" ]
If I change the size of the layer panel, the problem goes away. Same thing in a print layout, just change the size of the right side panel and it goes back to normal.
Resizing the panels, and the entire window, did the trick for me. A tad weird, but possibly the result of the version upgrade...important for me, as I have a 30" monitor, and I need to do big maps.
14,421,259
In this loop, I am iterating through an ArrayList of type `Entity`, which contains objects of type Entity as well as objects of type Projectile, which extends Entity. I want the below code to be executed if the object is an instance of Projectile. However, the `getVelocity()` method is only in the subclass Projectile, and not in Entity. So I am unable to compile the below code. I can think of ways to work around this, such as using separate ArrayLists. However, the point was to keep all Entities within a global list rather than separate them. Is there a simple solution to this problem, or do I need to change the structure of my code? ``` for (Entity f: glo.getList()) { if (f instanceof Projectile) f.setX(f.getVelocity()/rawFPS); } ```
2013/01/20
[ "https://Stackoverflow.com/questions/14421259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562138/" ]
This seems to be a loop that updates your entities in some way every tick of your game engine. In my opinion, a cleaner solution would be: ``` class Entity { ... public void update() {} ... } class Projectile extends Entity { ... @Override public void update() { setX(velocity/rawFPS); } ... } ``` I don't know your architecture, you may or may not need to pass `rawFPS` to `update()`. (as @Naveen quite rightly pointed out, this is not very clean, so avoid it if you can). Also, if your `Entity` is abstract with no functionality on its own, consider making it an `interface` in the first place.
Seriously, Guys? instance of sucks. Every guide on Java tells you that. There's something wrong here: you are looping through a set of entities and altering the internal state of a subset (the subclass instances) using another data item: FPS. If you don't have the FPS when the Projectile is constructed, having this outer class inject it later seems kind of random. Might be cleaner to just call a set on the FPS and have the update of the positional occur then. The outer class should probably ask for just the Projectiles.
30,125,781
I have seen that titanium support CoverFlowView in titanium but it works only on ios, Can anyone have idea to achieve CoverFlow in android with titanium Thanks in advance
2015/05/08
[ "https://Stackoverflow.com/questions/30125781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4537150/" ]
`e.originalEvent.clipboardData.getData('text/plain')` works for safari, chrome, firefox and safari and chrome on an Ipad. `window.clipboardData.getData('text')` works for Internet Explorer and Edge. Note: `e.originalEvent.clipboardData.getData('text')` works for desktop browsers but not for mobile browsers. So in the end I used this ``` var clipText; if (e.originalEvent.clipboardData !== undefined){ clipText = e.originalEvent.clipboardData.getData('text/plain') } else { clipText = window.clipboardData.getData('text') } ```
``` $("element").on('paste', function (e) { if (window.clipboardData) { pastedText = window.clipboardData.getData('Text') } else if (e.clipboardData || e.originalEvent.clipboardData != undefined) { pastedText = e.originalEvent.clipboardData.getData('text/plain') } } }); ```
60,969,216
I am using Azure Cosmos DB. I have created a simple trigger in Azure Portal as follows: [![enter image description here](https://i.stack.imgur.com/ybDl7.png)](https://i.stack.imgur.com/ybDl7.png) ``` var context = getContext(); var request = context.getRequest(); // item to be created in the current operation var itemToCreate = request.getBody(); itemToCreate["address"] = "test"; // update the item that will be created request.setBody(itemToCreate); ``` Unfortunately this trigger is not being triggered when I insert new documents. I have also tried to set the "Trigger Type" to "Post". Am I missing anything?
2020/04/01
[ "https://Stackoverflow.com/questions/60969216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2695990/" ]
Firing triggers automatically in relational databases makes sense since there is schema in the database, you kind of know what to handle in a trigger logic. In NoSQL database, since there is no schema, you may end up with a large script to handle all kind of exceptions. Large script in triggers means higher bills in Cloud. Making triggers automatic can make many customers bill really high specially in IOT solutions. You can read about Azure Cosmos DB pre/post triggers in my post. <https://h-savran.blogspot.com/2020/03/create-triggers.html>
The only way according to the answers from @Guarav Mantri and @Hasan Savaran is to specify the trigger while creating the item through the API. I have managed to do it in Java Azure SDK like that: ``` RequestOptions options = new RequestOptions(); options.setPreTriggerInclude(Arrays.asList("pre")); documentClient.createDocument( collectionLink(), documentToAdd, options, true); ``` Although I am not happy with this solution because for instance the trigger will not be triggered when creating the item via Portal.
639,328
I'm a physicist attempting electronics - so please bear with me. I feel I am missing something very very obvious. ![schematic](https://i.stack.imgur.com/0jOzB.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f0jOzB.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) An op-amp with some negative feedback (as I've drawn) will attempt to keep the inverting (\$V\_{-}\$) and non-inverting (\$V\_{+}\$) at the same potential. As \$V\_{+}\$ increases, the output signal will increase with the differential gain. As the output increases, that is fed back to the inverting input, which will decrease the voltage differential until it is very close to zero (with some error dependent on the gain.) Now, a differential amplifier should amplify/will amplify the difference between the two inputs, but I don't see why. ![schematic](https://i.stack.imgur.com/2IzGg.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f2IzGg.png) Why doesn't the negative feedback force the two inputs to zero? I don't see why the same argument for the op-amp doesn't apply for the differential amplifier.
2022/10/21
[ "https://electronics.stackexchange.com/questions/639328", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/272190/" ]
The assumption (simplification) that we make that negative feedback forces the op amp's inputs to be at the same voltage is an approximation we make that is very useful when we try to analyse op amp based circuits to understand their operation/behavior. In reality there will always be small difference voltage between the inputs. In an op amp based circuit, be it an inverting amplifier, non-inverting amplifier, difference amplifier (like your second circuit) etc there are actually two gains happening simultaneously... Firstly, there is the actual gain within the op amp. This is known as the open loop gain which is equal to Vout/(V+ - V-). This is a very high value at dc (100s of thousands) but it reduces with increasing frequency. At any particular frequency, this open loop gain has a set value whatever the particular configuration of the overall circuit. The open loop gain will vary somewhat with certain variables, such as load on an amplifier or output resistance, but essentially we can consider it to be a constant at a certain frequency whatever the circuit configuration. Secondly, there is the gain of the overall circuit as set by the external resistor values. For your difference amplifier Vout = (Vin1 - Vin2) x (R1/R2) assuming R1=R4 and R2=R3. The output voltage of a circuit with negative feedback (assuming that the output isn't hitting the power rail), whatever the circuit configuration, will be forced to a value which satisfies both the open loop gain value (for the particular frequency of operation) and the overall gain of the circuit set by the external resistors, known as the closed loop gain. This situation doesn't actually occur in a perfect way. If the closed loop gain was perfectly accurate to that set by the external resistors then there would be zero difference between the op amp's inputs and the output voltage would be forced to reduce to satisfy the open loop gain. So what happens is that there is a small error in the output voltage which creates a small voltage difference between the op amp's inputs (created by negative feedback). The open loop gain is satisfied but there is a small error in the closed loop gain. This small "error" in the closed loop gain is smaller the larger the open loop gain is at any particular frequency. Precision op amps have large open loop gains. So as frequency is increased, the open loop gain gets smaller resulting in the output voltage also getting smaller and the difference voltage between the op amp's inputs getting larger. The equation which relates closed loop gain to open loop gain for a non-inverting amplifier is... Acl = Aol/(1 + B.Aol) where Acl is the closed loop gain, Aol is the open loop gain and B is the feedback fraction as set by the external resistors. The reason the open loop gain reduces with frequency is because of the compensation capacitor (usually included within the op amp) which is there to ensure stability, but that's a whole 'nother story!
The infinite open loop gain part of the ideal model for an op-amp is not very useful. The discussions around the so called requirement that the input difference must be zero is a distraction. A finite gain leads to better understanding. The equation: $$V\_{\text{out}}=A\_{\text{VOL}}V\_{\text{D}}$$ has meaning only if \$A\_{\text{VOL}}\$ is finite. ![schematic](https://i.stack.imgur.com/KQIEbm.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fKQIEbm.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) The diagram shows a zero-order approximation of an op-amp. It shows two parts: a device that subtracts the inputs and a device that amplifies the difference, plain and simple. There is no mechanism or magic that requires or makes the inputs zero. However there are some limits set by the power supplies (VCC and VEE). $$\frac{V\_{\text{CC}}}{A\_{\text{VOL}}}>V\_{\text{D}}>\frac{V\_{\text{EE}}}{A\_{\text{VOL}}}$$ Whether open loop or closed loop, the equation holds for analog operation between the limits. But there is nothing restricting \$V\_{\text{D}}\$'s range necessarily.
49,447,134
I use SQLite with PHP. With all PHP files in same folder it works. But I want files in different folders: testCreate.php (1st folder): ``` <?php class mySqlite extends SQLite3{ function __construct(){ $this->open('test.db'); } } $db = new mySqlite(); $db->exec("CREATE TABLE IF NOT EXISTS `test` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL);" ); ?> ``` testAPI.php (1st folder): ``` <?php require_once('testCreate.php'); function insert($name){ global $db; $stmt = $db->exec("INSERT INTO `test`(`name`) VALUES ('$name')"); if($stmt){ return true; }else{ return false; } } function select(){ global $db; if($stmt = $db->prepare('SELECT id,name FROM test ORDER BY `id` DESC ')) { $result = $stmt->execute(); $names=array(); while($arr=$result->fetchArray(SQLITE3_ASSOC)) { $names[]=$arr; } return $names; } } ?> ``` insert.php (2nd folder): ``` <?php if(isset($_POST['new_menu']) && !empty($_POST['new_menu'])){ require_once('../incDB/testAPI.php'); $qry = insert($_POST['new_menu']); if($qry) echo 'ok'; else echo 'no'; } ?> <form method='post'> <input type="text" name="new_menu"> <button type="submit">ADD</button> </form> ``` select.php (3rd folder): ``` <?php require_once('../incDB/testAPI.php'); $rows = select(); ?> <table> <thead> <td style="border: solid 1px #000">id</td> <td style="border: solid 1px #000">name</td> </thead> <?php foreach($rows as $row){ ?> <tr> <td style="border: dashed 1px #000"><?php echo $row['id']; ?></td> <td style="border: dashed 1px #000"><?php echo $row['name']; ?></td> </tr> <?php } ?> </table> ``` When I run insert.php or select.php I found the database in 2nd folder. I want insert and select data to/from database in 1st folder. I changed testAPI.php : ``` <?php //require_once('testCreate.php'); class mySqlite extends SQLite3{ function __construct(){ $this->open('test.db'); } } $db = new mySqlite('../incDB/test.db'); $db->exec("CREATE TABLE IF NOT EXISTS `test` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL);" ); function insert($name){ global $db; $stmt = $db->exec("INSERT INTO `test`(`name`) VALUES ('$name')"); if($stmt){ return true; }else{ return false; } } function select(){ global $db; if($stmt = $db->prepare('SELECT id,name FROM test ORDER BY `id` DESC ')) { $result = $stmt->execute(); $names=array(); while($arr=$result->fetchArray(SQLITE3_ASSOC)) { $names[]=$arr; } return $names; } } ?> ``` Still same problem.
2018/03/23
[ "https://Stackoverflow.com/questions/49447134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450367/" ]
You are getting `NULL` values because you are filtering your sums on the column expression and not on your `WHERE`. The both `NULL` records are those where `is_internal` isn't 1, so both `CASE` won't match it's `WHEN` and return default of `NULL`, instead of calculating the `SUM()`. Try filtering your "not internal" records on your `WHERE` like the following: ``` --... WHERE date >= 43179 AND m2.is_internal = 1 GROUP BY floor(date), m1.is_internal, m2.is_internal ``` You can then remove the additional condition from your `CASE`. Also I find a `SUM(CASE...)` easier to read. ``` SUM(CASE WHEN m1.is_internal = 1 THEN CAST([size] AS BIGINT) END) AS internal_volume, SUM(CASE WHEN m1.is_internal = 0 THEN CAST([size] AS BIGINT) END) AS external_volume_in ``` In general terms, if you want to filter results of a query by their column's value (if they are complex expressions and you don't want to repeat them in the `WHERE` or the `HAVING`), you should try to move them to a subquery or CTE and filtering afterwards: ``` ;WITH Results AS ( SELECT CASE WHEN (m1.is_internal = 1 AND m2.is_internal = 1) THEN SUM(CAST([size] AS BIGINT)) END AS internal_volume, CASE WHEN (m1.is_internal = 0 AND m2.is_internal = 1) THEN SUM(CAST([size] AS BIGINT)) END AS external_volume_in FROM messagesgal msg LEFT JOIN messages_addresses m1 ΟΝ msg.originator = m1.address LEFT JOIN messages_addresses m2 ΟΝ msg.recipient = m2.address WHERE date >= 43179 GROUP BY floor(date), m1.is_internal, m2.is_internal ) SELECT R.* FROM Results AS R WHERE R.internal_volume IS NOT NULL OR R.external_volume_in IS NOT NULL ```
Try this: ``` case when m2.is_internal = 1 then case m1.is_internal when 1 then 'internal volume' when 0 then 'external volume in' end end [type], case when m2.is_internal = 1 then case m1.is_internal when 1 then SUM(CAST([size] AS BIGINT)) when 0 then SUM(CAST([size] AS BIGINT)) end end [value] ``` Then you could wrap it in outer query, where you would select values, where `[value] is not null`.
16,848,931
I just want to find some fastest set bits count function in the php. For example, 0010101 => 3, 00011110 => 4 I saw there is good Algorithm that can be implemented in c++. [How to count the number of set bits in a 32-bit integer?](https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer) Is there any php built-in function or fastest user-defined function?
2013/05/31
[ "https://Stackoverflow.com/questions/16848931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1761178/" ]
You can try to apply a mask with a binary AND, and use shift to test bit one by one, using a loop that will iterate 32 times. ``` function getBitCount($value) { $count = 0; while($value) { $count += ($value & 1); $value = $value >> 1; } return $count; } ``` You can also easily put your function into PHP style ``` function NumberOfSetBits($v) { $c = $v - (($v >> 1) & 0x55555555); $c = (($c >> 2) & 0x33333333) + ($c & 0x33333333); $c = (($c >> 4) + $c) & 0x0F0F0F0F; $c = (($c >> 8) + $c) & 0x00FF00FF; $c = (($c >> 16) + $c) & 0x0000FFFF; return $c; } ```
I could figure out a few ways to but not sure which one would be the fastest : * use substr\_count() * replace all none '1' characters by '' and then use strlen() * use preg\_match\_all() PS : if you start with a integer these examples would involve using decbin() first.
62,524,021
I want to ask you a quick question as a followup to my earlier question: [React - syntax confusion to clarify](https://stackoverflow.com/questions/62522496/react-syntax-confusion-to-clarify) code for TodoItem: ``` import React from 'react' export const TodoItem = (props) => { console.log(props) console.log(props.todo.completed) return ( <div className="todo-item"> <input type="checkbox" checked={props.todo.completed} /> <p>{props.todo.text} </p> <p>Completed: {props.todo.completed} ? 'Yes' : 'No' </p> </div> ) } export default TodoItem; ``` last field in props is 'props.todo.completed' thats a boolean. I am trying to decode it to yes/no based on if its true or false, but I cant seem to get the syntax right :( I tried enclosing in backticks, {} but nothing seems to work .. when i code : Completed: {props.todo.completed} ? 'Yes' : 'No' shows up: Completed: ? 'Yes' : 'No' when i code: Completed: `{props.todo.completed} ? 'Yes' : 'No'` (adding backticks) backticks show up: Completed: `? 'Yes' : 'No'` when i code: Completed:{ `{props.todo.completed} ? 'Yes' : 'No'`} shows up: Completed:{props.todo.completed} ? 'Yes' : 'No' As you can see, i am struggling to get some basic concepts right in my head, and need your help.
2020/06/22
[ "https://Stackoverflow.com/questions/62524021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6943311/" ]
Hi you can write it like this ``` return ( <div className="todo-item"> <input type="checkbox" checked={props.todo.completed} /> <p>{props.todo.text} </p> <p>Completed: {props.todo.completed ? 'Yes' : 'No'}</p> </div> ) ```
Any javascript expression you want to evaluate in `JSX` have to be wrapped inside the curly braces`{}`. In your case, you want to evaluate a ternary expression so the whole expression has to wrapped inside the curly braces. For example, ```js <p>Completed: { props.todo.completed ? 'Yes' : 'No' }</p> ```
40,738,026
I'm trying to communicate from a web page to an extension and vice versa. To do so, I looked at the Mozilla documentation here : <https://developer.mozilla.org/fr/Add-ons/WebExtensions/Content_scripts#Communicating_with_the_web_page> And it has a simple example, but I can't make it work. On the web page script, I have this : ``` // page-script.js var messenger = document.getElementById("from-page-script"); messenger.addEventListener("click", messageContentScript); function messageContentScript() { window.postMessage({ direction: "from-page-script", message: "Message from the page" }, "*"); ``` On the content scripts page in the extension : ``` // content-script.js window.addEventListener("message", function(event) { if (event.source == window && event.data.direction && event.data.direction == "from-page-script") { alert("Content script received message: \"" + event.data.message + "\""); } }); ``` I installed the extension (as a temporary one, I uploaded my xpi file), then I used the "Debugging" method of API WebExtensions, and put a breakpoint into the listener, but whenever I call the PostMessage, the extension never seems to receive the event, the breakpoint is never triggered. Is it possible to communicate this way between a web page and an extension ? Or is there another one ?
2016/11/22
[ "https://Stackoverflow.com/questions/40738026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969881/" ]
The problem was in the manifest of my extension. I declared my content script as a background script. So, instead of writing this : ``` "background": { "scripts": ["myscript.js"], "persistent": true }, ``` You have to declare the script like this : ``` "content_scripts": [ { "matches": ["<all_urls>"], "js": ["myscript.js"] } ] ```
I was experiencing similar issues and the problem for me is I was calling the ``` window.postMessage ``` function from within an iframe. After I changed this to ``` top.window.postMessage ``` it started working.
2,158,750
![enter image description here](https://i.stack.imgur.com/oNXwn.jpg) I've tried all the possible side splitter and angle bisector theorem stuff and I still can't come up with the correct answer. I even tried some law of cosine and sine stuff, but nothing. Any help would be gladly appreciated. Thanks.
2017/02/24
[ "https://math.stackexchange.com/questions/2158750", "https://math.stackexchange.com", "https://math.stackexchange.com/users/418637/" ]
Observe triangles $ADE$ and $ABC$ are similar. Since $BC || DE$ and $BF$ is an angle bisector of $\angle \, A$ $$\angle \,DBF = \angle \, CBF = \angle \, DFB$$ so triangles $BDF$ is isosceles with $BD = DF$. Analogously $CE=EF$. Hence the perimeter $P\_{ADE}$ of triangle $ADE$ is $$P\_{ADE} = AD+DF+AE+EF = AD+DB + AE+EC = AB + AC = 26 + 34 = 60$$ The perimeter $P\_{ABC}$ of $ABC$ is $$P\_{ABC} = AB + BC+AC = 26+4=+54 = 100$$ By the similarity of $ADE$ and $ABC$ $$\frac{DE}{BC} = \frac{P\_{ADE}}{P\_{ABC}} = \frac{60}{100} = \frac{3}{5}$$ Since $BC = 40$ $$DE = \frac{3}{5} \, 40 = 24$$
You can do this with the [angle bisector theorem](https://en.wikipedia.org/wiki/Angle_bisector_theorem) used twice. First observe that $AF$ bisects $\angle BAC$, (because [angle bisectors are concurrent](https://www.algebra.com/algebra/homework/Triangles/Angle-bisectors-of-a-triangle-are-concurrent.lesson)) so continue $AF$ to meet $BC$ at point $G$. Then $G$ divides $BC$ in the ratio 26:34 so $BG = \frac {40}{60} 26 =\frac {52}{3}$ Then $BF$ divides $AG$ in the ratio $26:\frac{52}3 = 3:2$ giving $AF:AG$ as $3:5$. Thus through similarity of $\triangle ABC$ and $\triangle ADE$ the ratio between $DE$ and $BC$ is also $3:5$ i.e. $\fbox{$DE=24$}$
54,499,686
I am trying to get the token value from the following URL `http://localhost:3000/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8`. I have a get request that checks if the token is valid and redirects the user to a reset password screen. I also have a post request but when I console `req.params.token`, it outputs `:token` instead of `e3b40d3e3550b35bc916a361d8487aefa30147c8`. I am wondering if the form action is correct but don't know how to get the token value from it. **Reset Password Get Request** ``` router.get('/reset/:token', (req, res) => { console.log(req.params.token) // e3b40d3e3550b35bc916a361d8487aefa30147c8 User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, (err, user) => { if (!user) { req.flash('error_msg', 'The password reset token is invalid or has expired.') return res.redirect('/users/forgot') } res.render('reset') }) }) ``` **reset.ejs** ``` <% include ./partials/messages %> <form action="/users/reset/:token" method="POST"> <div class="form-group"> <label for="password">Password</label> <input type="password" id="password" name="password" class="form-control" placeholder="Please enter a password." value="<%= typeof password != 'undefined' ? password : '' %>" /> </div> <button type="submit" class="btn btn-primary btn-block">Register</button> </form> ``` **Reset Password Post Request** ``` router.post('/reset/:token', (req, res) => { console.log(req.params.token) // :token User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, (err, user) => { if (!user) { req.flash('error_msg', 'The password reset token is invalid or has expired.') return res.redirect('/users/forgot') } user.password = req.body.password; user.resetPasswordToken = undefined; user.resetPasswordExpires = undefined; user.save(function (err) { req.flash('success_msg', 'Working.') return res.redirect('/users/login') }) }) }) ```
2019/02/03
[ "https://Stackoverflow.com/questions/54499686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In your form in your HTML, you have this: ``` <form action="/users/reset/:token" method="POST"> ``` That's going to make the actual URL that gets requested when the form is posted be: ``` /users/reset/:token ``` There's no code doing any substitution for the `:token` here. That's just getting sent directly to the server as the URL. So, when you then have: ``` router.post('/reset/:token', (req, res) => { console.log(req.url); // "/user/reset/:token" console.log(req.params.token); // ":token" }); ``` What `req.params.token` is showing you is whatever is in the URL that's after `/users/reset`. In your case, that is the literal string `":token"`. For `req.params.token` to actually have to token in it, you would have to insert the actual token into the URL so your form tag looks like this: ``` <form action="/users/reset/e3b40d3e3550b35bc916a361d8487aefa30147c8" method="POST"> ``` Or, you will have to get access to the token some other way such as from the express session, from a cookie, from a field in the form, etc...
To get a URL parameter's value ``` app.get('/reset/:token', function(req, res) { res.send("token is " + req.params.token); }); ``` To get a query parameter ?token=Adhgd5645 ``` app.get('/reset/?token=Adhgd5645', function(req, res) { res.send("token is " + req.query.token); }); ```
45,497,684
From C++11 standard (15.1.p4): > > The memory for the exception object is allocated in an unspecified > way, except as noted in 3.7.4.1 > > > What if allocation fails -- will it throw `std::bad_alloc` instead? Call `std::terminate`? Unspecified?
2017/08/04
[ "https://Stackoverflow.com/questions/45497684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6427477/" ]
Current answer already describes what GCC does. I have checked MSVC behavior - it allocates exception on the stack, so allocation does not depend on the heap. This makes stack overflow is possible (exception object can be big), but stack overflow handling is not covered by standard C++. I used this short program to examine what happens during exception throw: ``` #include <iostream> class A { public: A() { std::cout << "A::A() at " << static_cast<void *>(this) << std::endl; } A(const A &) { std::cout << "A::A(const A &) at " << static_cast<void *>(this) << std::endl; } A(A &&) { std::cout << "A::A(A &&) at " << static_cast<void *>(this) << std::endl; } ~A() { std::cout << "A::~A() at " << static_cast<void *>(this) << std::endl; } A &operator=(const A &) = delete; A &operator=(A &&) = delete; }; int main() { try { try { try { A a; throw a; } catch (const A &ex) { throw; } } catch (const A &ex) { throw; } } catch (const A &ex) { } } ``` When build with GCC output clearly shows that exception thrown is being allocated far from stack: ``` A::A() at 0x22cad7 A::A(A &&) at 0x600020510 A::~A() at 0x22cad7 A::~A() at 0x600020510 ``` When build with MSVC output shows that exception is allocated nearby on the stack: ``` A::A() at 000000000018F4E4 A::A(A &&) at 000000000018F624 A::~A() at 000000000018F4E4 A::~A() at 000000000018F624 ``` Additional examination with debugger shows that catch handlers and destructors are executed on the top of the stack, so stack consumption grows with each catch block starting with the first throw and until `std::uncaught_exceptions()` becomes 0. Such behavior means that correct out of memory handling requires you to prove there is enough stack space for the program to execute exception handlers and all destructors on the way. To prove the same with GCC it seems that you will need to prove there no more than four nested exceptions and exceptions have size less than 1KiB (this includes header). Additionally if some thread has more than four nested exceptions, you also need to prove there is no deadlock caused by emergency buffer allocation.
Actualy it is specified that if allocation for the exception object fails, `bad_alloc` should be thrown and implementation could also call the new handler. This is what is actualy specified in the c++ standard section (§3.7.4.1) you site [[basic.stc.dynamic.allocation]](http://eel.is/c++draft/basic.stc.dynamic.allocation#3): > > An allocation function that fails to allocate storage can invoke the currently installed new-handler function > (21.6.3.3), if any. [ > Note: > A program-supplied allocation function can obtain the address of the currently > installed > new\_handler > using the > std::get\_new\_handler > function (21.6.3.4). > — end note > ] If an allocation > function that has a non-throwing exception specification (18.4) fails to allocate storage, it shall return a null > pointer. Any other allocation function that fails to allocate storage shall indicate failure only by throwing an > exception (18.1) of a type that would match a handler (18.3) of type > std::bad\_alloc > (21.6.3.1). > > > Then this recalled in [[except.terminate]](http://eel.is/c++draft/except.terminate#1.1) > > In some situations exception handling must be abandoned for less subtle error handling techniques. [ > Note: > These situations are: > — > (1.1) > when the exception handling mechanism, **after completing the initialization of the exception object** but > before activation of a handler for the exception (18.1)\* > > > So the itanium ABI does not follow the c++ standard specification, since it can block or call `terminate` if the program fails to allocate memory for the exception object.
5,389,200
Consider a Java String Field named `x`. What will be the initial value of `x` when an object is created for the class x; I know that for `int` variables, the default value is assigned as `0`, as the instances are being created. But what becomes of `String`?
2011/03/22
[ "https://Stackoverflow.com/questions/5389200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569497/" ]
That depends. Is it just a variable (in a method)? Or a class-member? If it's just a variable you'll get an error that no value has been set when trying to read from it without first assinging it a value. If it's a class-member it will be initialized to null by the VM.
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
15,652,653
I need to constantly read from my database every 1 second to get the latest values. Here is my code: ``` <?php // connect to the "tests" database $conn = new mysqli('localhost', 'root','','Test'); // check connection if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // SELECT sql query $sql = "SELECT * FROM `Value`"; // perform the query and store the result $result = $conn->query($sql); if (!$result) print 'Error!'; // if the $result contains at least one row if ($result->num_rows > 0) { // output data of each row from $result while($row = $result->fetch_assoc()) { $output=$row; print_r($output); } } else { print '0 results'; } $conn->close(); ?> ``` My HTML code refreshes every 1 second as follows: ``` function reload (){ setInterval(getData,1000); } function getData() { $.get('test.php', function(data) { var output = data; document.getElementById("output").innerHTML = "Info: " + output; }); } .... <body onload="reload();"> <p id="output"></p> </body> ``` Everything works fine but after around 5-10 mins the MYSQL server crashes. I'm assuming it is being overloaded. My thoughts are that I keep running the php script every time which connects each second. Am I doing this incorrectly? Anyone have any suggestions on a better implementation?
2013/03/27
[ "https://Stackoverflow.com/questions/15652653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769870/" ]
I think you are looking for something to have the database "unclosed" when the script has ended. In mysqli you can prepend the hostname by adding p: to use a so called persistant database connection ``` // connect to the "tests" database $conn = new mysqli('p:localhost', 'root','','Test'); ``` Read more about persistant connections here: <http://php.net/manual/en/features.persistent-connections.php>
You might try having it not start the next request until 1 second after the last one finishes by calling `setTimeout()` in the callback like so: ``` function getData() { $.get('test.php', function(data) { var output = data; document.getElementById("output").innerHTML = "Info: " + output; setTimeout(getData, 1000); }); } .... <body onload="getData();"> ``` This is generally a better approach than using `setInterval()`, cuz you may end up having two concurrent connections and request `A` may start before request `B`, but may end *after* `B`, because something happened and it took more than a second to finish the request. This could cause some weird behavior. This may also fix your issue, because maybe it fails because it ends up having several concurrent connections open from the same IP, etc.
1,223,566
I've got a single statement running on a ASP.NET page that takes a long time (by long I mean 100ms, which is too long if I want this page to be lightning fast) , and I don't care when it executes as long as executes. What is the best (and hopefully easiest) way to accomplish this?
2009/08/03
[ "https://Stackoverflow.com/questions/1223566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
If it's 100ms, then don't bother. Your users can't detect a 100ms delay. --- **Edit:** some explanations. If I remember correctly, 100 milliseconds (1/10 second) is near the minimum amount of time that a human can perceive. So, for the purpose of discussion, let me grant that this 100ms can be perceived by the users of the OP's site, and that it is worthwhile to improve performance by 100ms. I assumed from the start that the OP had correctly identified this "long-running" task as a potential source of a 100ms improvement. So, why did I suggest he ignore it? Dealing with multiple threads properly is not easy, and is a source of bugs that are difficult to track down. Adding threads to a problem is usually not a solution, but is rather a source of other problems you simply don't find right away (\*). I had the opportunity once to learn this the hard way, with a bug that could only be reproduced on the fastest eight-cpu system available at the time, and then only by pounding on the thing relentlessly, while simulating a degree of network failure that would have caused the network administrators to be lined up and shot, if it had happened in real life. The bug turned out to be in the Unix OS kernel handling of signals, and was a matter of the arrangement of a handful of instructions. Granted I've never seen anything that bad since then, I've still seen many developers tripped up by multithreading bugs. This question, seemed to be, on the one hand, asking for an "easy way out" via threading, and on the other hand, the benefit was only 100ms. Since it did not appear that the OP already had a well-tested threading infrastructure, it seemed to me that it made better sense to ignore the 100ms, or perhaps to pick up performance some other way. --- (\*) Of course, there are many circumstances where an algorithm can profitably be made parallel and executed by multiple threads, running on multiple cores. But it does not sound like the OP has such a case.
``` // This is the delegate to use to execute the process asynchronously public delegate void ExecuteBackgroundDelegate(); // [STAThread] static void Main(string[] args) { MyProcess proc = new MyProcess(); // create an instance of our execution delegate ExecuteBackgroundDelegate asynchExec = new ExecuteBackgroundDelegate(proc.Execute); // execute this asynchronously asynchExec.BeginInvoke(null, null); } ```
5,049,171
``` string dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" + app_id + "&redirect_uri=" + Server.UrlEncode(my_url) + "&scope=" + permission; ClientScript.RegisterClientScriptBlock(typeof(Page), "key", "window.open('"+dialog_url+"','_parent','');"); ``` I use this code for popup permission dialog. When user click allow facebook redirect user to my app in the popup. I need to send code from popup window to parent window then close popup when user click allow.
2011/02/19
[ "https://Stackoverflow.com/questions/5049171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360094/" ]
Tell me if this is what you are looking for... Parent Window: ``` <html> <head> <script language="Javascript"> function showFBWindow(){ url = "allowfbchild.html" newwindow=window.open(url,'name','height=200,width=150'); if (window.focus) {newwindow.focus()} } </script> </head> <body> <input type="button" OnClick="showFBWindow()" value="Open FB" /> </body> </html> ``` Child Window(allowfbchild.html) : ``` <html> <head> <script language="Javascript"> function redirectToFB(){ window.opener.location.href="http://wwww.facebook.com"; self.close(); } </script> </head> <body> Allow the user to view FB <br/>Are you sure? <input type="button" value="Ok" OnClick="redirectToFB()" /> </body> </html> ```
This is your parent window: ``` <script language="javascript"> function open_a_window() { var w = 200; var h = 200; var left = Number((screen.width/2)-(w/2)); var tops = Number((screen.height/2)-(h/2)); window.open("window_to_close.html", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left); return false; } // opener: window.onmessage = function (e) { if (e.data === 'location') { window.location.replace('https://www.google.com'); } }; </script> <input type="button" onclick="return open_a_window();" value="Open New Window/Tab" /> ``` This is your child window: ``` <!DOCTYPE html> <html> <body onload="quitBox('quit');"> <h1>The window closer:</h1> <input type="button" onclick="return quitBox('quit');" value="Close This Window/Tab" /> <script language="javascript"> function quitBox(cmd) { if (cmd=='quit') { window.opener.postMessage('location', '*'); window.open(location, '_self').close(); } return false; } </script> </body> </html> ```
3,904,486
Is there any way to copy data cells from excel and paste into jqgird or opensource grids so that is saves to database.
2010/10/11
[ "https://Stackoverflow.com/questions/3904486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274632/" ]
A complete working example using [*Nev Stokes*' given link](https://stackoverflow.com/questions/3904482/match-url-pattern-in-php-using-a-regular-expression/3904514#3904514): ``` public function clickableUrls($html){ return $result = preg_replace( '%\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))%s', '<a href="$1">$1</a>', $html ); } ```
I looked around and didn't see any that were exactly what I needed. I found [this one](http://regexlib.com/REDetails.aspx?regexp_id=1121) that was close, so I modified it as follows: ``` ^((([hH][tT][tT][pP][sS]?)\:\/\/)?([\w\\-]+(\[\w\.\&%\$\-]+)*)?((([^\s\(\)\<\>\\\"\.\ [\]\,;:]+)(\.[^\s\(\)\<\>\\\"\.\[\]\,;:]+)*(\.[a-zA-Z]{2,4}))|((([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])))(\b\:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b)?((\/[^\/][\w\.\,\?\'\\\/\+&%\$#\=~_\-]*)*[^\.\,\?\"\'\(\)\[\]!;<>{}\s\x7F-\xFF])?)$ ``` Check it out on [debuggex](https://www.debuggex.com/?re=%5E(((%5BhH%5D%5BtT%5D%5BtT%5D%5BpP%5D%5BsS%5D%3F)://)%3F(%5B%5Cw-%5D%2B(%5B%5Cw.%26%25$-%5D%2B)*)%3F(((%5B%5E%5Cs()%3C%3E%22.%5B%5D,;:%5D%2B)(.%5B%5E%5Cs()%3C%3E%22.%5B%5D,;:%5D%2B)*(.%5Ba-zA-Z%5D%7B2,4%7D))%7C(((%5B01%5D%3F%5Cd%7B1,2%7D%7C2%5B0-4%5D%5Cd%7C25%5B0-5%5D).)%7B3%7D(%5B01%5D%3F%5Cd%7B1,2%7D%7C2%5B0-4%5D%5Cd%7C25%5B0-5%5D)))(%5Cb:(6553%5B0-5%5D%7C655%5B0-2%5D%5Cd%7C65%5B0-4%5D%5Cd%7B2%7D%7C6%5B0-4%5D%5Cd%7B3%7D%7C%5B1-5%5D%5Cd%7B4%7D%7C%5B1-9%5D%5Cd%7B0,3%7D%7C0)%5Cb)%3F((/%5B%5E/%5D%5B%5Cw.,%3F%27/%2B%26%25$%23%3D%7E_-%5D*)*%5B%5E.,%3F%22%27()%5B%5D!;%3C%3E%7B%7D%5Cs%5Cx7F-%5CxFF%5D)%3F)$).
13,148,429
I have the following `DataFrame` (`df`): ``` import numpy as np import pandas as pd df = pd.DataFrame(np.random.rand(10, 5)) ``` I add more column(s) by assignment: ``` df['mean'] = df.mean(1) ``` How can I move the column `mean` to the front, i.e. set it as first column leaving the order of the other columns untouched?
2012/10/30
[ "https://Stackoverflow.com/questions/13148429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1772165/" ]
I liked [Shoresh's answer](https://stackoverflow.com/a/46166838/9075180) to use set functionality to remove columns when you don't know the location, however this didn't work for my purpose as I need to keep the original column order (which has arbitrary column labels). I got this to work though by using [IndexedSet](http://boltons.readthedocs.io/en/latest/setutils.html#) from the boltons package. I also needed to re-add multiple column labels, so for a more general case I used the following code: ``` from boltons.setutils import IndexedSet cols = list(IndexedSet(df.columns.tolist()) - set(['mean', 'std'])) cols[0:0] =['mean', 'std'] df = df[cols] ``` Hope this is useful to anyone searching this thread for a general solution.
Similar to the top answer, there is an alternative using deque() and its rotate() method. The rotate method takes the last element in the list and inserts it to the beginning: ``` from collections import deque columns = deque(df.columns.tolist()) columns.rotate() df = df[columns] ```
560,968
As the title asks (Windows 7). (How) can I change the time until the screensaver kicks in from the command line? Is it even possible? Normally I am happy with a 5 minute setting, but occasionally I want to make it longer. I would like the two lengths bound to hot-keys (I know how to do that). I guess I could record two macros and use those, but I just wondered if there are any command line options (including registry updates) that I can use to tell Windows to start the screen saver after X minutes of inactivity. (please note, I do not want to start the screen saver immediately; I want to change the length of time Windows will wait before starting it) Thanks in advance. --- [Answer] I finally used a variation on the answer from @Gjordis - but all credit goes to him. I didn't see why we needed 3 operations : add, delete then rename and reduced that to two. Since I want to bind to a hotkey, I need to execute two comamnds in one. Normally, one can separate the commands with a semicolon and issue them on one line (e.g `dir c:;dir d:`). That gave errors with the `reg` command, so in the end I have two batch files. The contens are identitcal, only the duration changes. On strange thing - the value is correctly written to the registry, but Control Panel/Personalize/Screen saver does not alwys update its GUI. However, I tested and the screen saver does behave as expected. ``` @echo off reg delete "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOut /f reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d 180 /f ``` If this helps you, please upvote the question ;-)
2013/03/05
[ "https://superuser.com/questions/560968", "https://superuser.com", "https://superuser.com/users/36006/" ]
``` reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d 600 /f ``` The value 600 is in seconds, = 10minutes Interestingly, as pointed, this works only the first time. On next change, you need to make a new key like so : ``` reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOutTemp /t REG_SZ /d 300 /f ``` Then delete the old one ``` reg delete "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOut /t REG_SZ /d 600 /f ``` Then copy the new one to the right name ``` reg copy "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOutTemp "HKEY_CURRENT_USER\Control Panel\Desktop" /v ScreenSaveTimeOut ``` Hopy this works, and you do not destory your computer, but since you did not have this registry value, i don't think deleting it can be that horrible. REG documentation here: <http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/reg.mspx?mfr=true>
In fact, this approach (via registry) doesn't work *until reboot*. Only way to do that *without* PC reboot is to use an API: <https://www.pcreview.co.uk/threads/utility-to-temporarily-change-the-screensaver.2321339/#post-7442568> but APIs can't be used from a command line, i.e. VB script. Here is the reason: <http://forums.codeguru.com/showthread.php?31534-VBScript-and-API&p=86696#post86696> It could be done by calling utility **SetScrTimeout.exe** (from the first link), but unfortunatelly, this small utility doesn't exist on internet anymore.
109,450
I am trying to deploy a contract using [Deterministic Deployment Proxy](https://github.com/Zoltu/deterministic-deployment-proxy) to a deterministic address. Since all the network has the deployer proxy deployed to it at address `0x7A0D94F55792C434d74a40883C6ed8545E406D12`. In order to deploy a `MY_CONTRACT` I want to change `to` address from `null` to `proxy_address` on the outbound contract deployment transaction using hardhat, ethers or other helper tools? That is how to overrides the `to` field of a contract deployment transaction?
2021/09/06
[ "https://ethereum.stackexchange.com/questions/109450", "https://ethereum.stackexchange.com", "https://ethereum.stackexchange.com/users/58288/" ]
When the `block.timestamp` is called from a `view` function, it will return the best block timestamp (the timestamp of the block at the tip of the blockchain. Only when we call it with a non-view or non/pure function (when we call a function that will actually modify the state), then, the `block.timestamp` will refer to the current block where the transaction was included (the new best block). We can see that in Remix, and also in rinkeby.etherscan.io. I deployed the following contract and we can read the `getCurrentContractTimeStamp` function multiple times, and it will change every time there is a new block added to the chain. <https://rinkeby.etherscan.io/address/0x567ca34aca62aa17922311ef87550e9f721d188e#readContract> We can write to it and the `updateTime` function will set the timestamp of the current block where the transaction was mined into. <https://rinkeby.etherscan.io/address/0x567ca34aca62aa17922311ef87550e9f721d188e#writeContract> ```js contract Contract { uint256 public time; // A view function. The `block.timestamp` will return the timestamp of the best block // (the block at the tip of the blockchain) function getCurrentContractTimeStamp() public view returns(uint256) { return block.timestamp; } // `block.timestamp` will return the timestamp of the block where this transaction is mined in. function updateTime() public { time = block.timestamp; } } ``` [![enter image description here](https://i.stack.imgur.com/gouyH.png)](https://i.stack.imgur.com/gouyH.png) [![enter image description here](https://i.stack.imgur.com/chLDZ.png)](https://i.stack.imgur.com/chLDZ.png)
What happens when we assign the block.timestamp to variable?? Will it change over time
3,425,688
This is a fairly well-documented error and the fix is easy, but does anyone know why Hadoop datanode NamespaceIDs can get screwed up so easily or how Hadoop assigns the NamespaceIDs when it starts up the datanodes? Here's the error: ``` 2010-08-06 12:12:06,900 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: java.io.IOException: Incompatible namespaceIDs in /Users/jchen/Data/Hadoop/dfs/data: namenode namespaceID = 773619367; datanode namespaceID = 2049079249 at org.apache.hadoop.hdfs.server.datanode.DataStorage.doTransition(DataStorage.java:233) at org.apache.hadoop.hdfs.server.datanode.DataStorage.recoverTransitionRead(DataStorage.java:148) at org.apache.hadoop.hdfs.server.datanode.DataNode.startDataNode(DataNode.java:298) at org.apache.hadoop.hdfs.server.datanode.DataNode.<init>(DataNode.java:216) at org.apache.hadoop.hdfs.server.datanode.DataNode.makeInstance(DataNode.java:1283) at org.apache.hadoop.hdfs.server.datanode.DataNode.instantiateDataNode(DataNode.java:1238) at org.apache.hadoop.hdfs.server.datanode.DataNode.createDataNode(DataNode.java:1246) at org.apache.hadoop.hdfs.server.datanode.DataNode.main(DataNode.java:1368) ``` This seems to even happen for single node instances.
2010/08/06
[ "https://Stackoverflow.com/questions/3425688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118843/" ]
Namenode generates new namespaceID every time you format HDFS. I think this is possibly to differentiate current version and previous version. You can always rollback to previous version if something is not proper which may not be possible if namespaceID is not unique for every formatted instance. NamespaceID also connects namenode and datanodes. Datanodes bind themselves to namenode through namespaceID
I was getting this too, and then I tried putting my configuration in `hdfs-site.xml` instead of `core-site.xml`. Seems to stop and start without that error now. [EDIT, 2010-08-13] Actually this is still happening, and it is caused **by** formatting. If you watch the VERSION files when you do a format, you'll see (at least I do) that the namenode gets assigned a new namespaceID, but the data node does not. Quick solution is to delete the VERSION for the datanode before format. [TIDE, 2010-08-13]
58,653,502
I would like to make the text WITHIN a table cell trigger an onclick function using JavaScript. I am able to make the cell itself trigger the onClick event but that is not what I want. ``` var table = document.getElementById(tableName); var row = table.insertRow(0); var cell1 = row.insertCell(0); cell1.innerHTML = "some text" //how do I make the text within the innerHTML trigger an onclick event? ```
2019/11/01
[ "https://Stackoverflow.com/questions/58653502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9681559/" ]
The actual text within a table cell cannot be bound to an event listener as such. If the text within the table cell is in another tag ( such as a paragraph, span, div or whatever ) then you can use a slight trick to test for which element triggered the event by comparing the event `target` and the event `currentTarget` properties. You can click anywhere in the cell and nothing will happen unless you click on the paragraph - at which point the `target` will no longer be the same as the `currentTarget` that was registered with the event listener. There is, as far as I am aware, no way of doing this with just the raw text within the table cell - and ultimately why would you need to do so anyway? ``` <table id='banana' border=1 cellpadding='5px' cellspacing='2px'> <!-- content to follow --> </table> <script> const nl=String.fromCharCode(10); var id='banana'; var table = document.getElementById( id ); var row = table.insertRow(0); var cell = row.insertCell(0); cell.innerHTML = 'This is some basic text'; var p=document.createElement('p'); p.innerText='This is a Paragraph within the table cell'; cell.appendChild( p ) cell.addEventListener( 'click', function(e){ if( e.target != e.currentTarget ) alert( [ 'target: '+e.target, 'currentTarget: '+e.currentTarget, 'text: '+e.target.innerText ].join( nl ) ) }); </script> ``` Following on from the comment made previously about triggering an event when a user selects text within the table cell, you can possibly try the following: ``` document.body.addEventListener('mouseup',(e)=>{ alert( 'Text has been selected? '+ window.getSelection() ) }); ``` There is, as I just discovered, a `selectionchange` event that might be of interest - [more information from MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/selectionchange_event)
use onclick for onClick event ``` cell1.onclick = function () { console.log("onclick"); }; ``` ```js var table = document.getElementById("table"); var row = table.insertRow(0); var cell1 = row.insertCell(0); cell1.innerHTML = "some text" cell1.onclick = function () { console.log("onclick"); }; ``` ```html <table id="table"> </table> ```
36,308,040
I am trying to get the bandwidth data for all the softlayer servers under my account. Thanks to `account_servers.rb` I am able to get the server id for all the servers. Now I would like to get the Bandwidth used by the servers for a particular time frame. The data that I am interested is > > <http://sldn.softlayer.com/reference/datatypes/SoftLayer_Metric_Tracking_Object_Bandwidth_Summary> > . > > > I tried to get information using `softlayer_client.service_named("Metric_Tracking_Object_Bandwidth_Summary")`. Unfortunately I am not able to get the details. I did find a java code, but I am interested in ruby code. Can someone please guide me to get the server bandwith summary? [Getting bandWidth data in SL](https://stackoverflow.com/questions/36061200/getting-bandwidth-data-in-sl)
2016/03/30
[ "https://Stackoverflow.com/questions/36308040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2004189/" ]
Please, try the following `Ruby` examples: ``` require 'rubygems' require 'softlayer_api' server_id = 11498369 # Your SoftLayer API username. SL_API_USERNAME = 'set me' # Your SoftLayer API key. SL_API_KEY = 'set me' softlayer_client = SoftLayer::Client.new(:username => SL_API_USERNAME, :api_key => SL_API_KEY) vsi_service = softlayer_client.service_named('SoftLayer_Virtual_Guest') metric_tracking_object_id = vsi_service.object_with_id(server_id).getMetricTrackingObjectId metric_service = softlayer_client.service_named('SoftLayer_Metric_Tracking_Object') service_ref = metric_service.object_with_id(metric_tracking_object_id) begin object_template = [{ 'keyName' => 'PUBLICOUT', 'summaryType' => 'sum' }] result = service_ref.getSummaryData('2016-03-29T00:00:00','2016-03-30T00:00:00',object_template,600) puts result.inspect rescue => e puts 'Error when executing the script...' $stdout.print(e.inspect) end ``` **References:** [SoftLayer\_Metric\_Tracking\_Object::getSummaryData](http://sldn.softlayer.com/reference/services/SoftLayer_Metric_Tracking_Object/getSummaryData) [SoftLayer\_Virtual\_Guest::getMetricTrackingObjectId](http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getMetricTrackingObjectId) Second example using `SoftLayer_Virtual_Gues::getBandwidthDataByDate`: ``` require 'rubygems' require 'softlayer_api' require 'pp' require 'date' # Set the server id that you wish to get Bandwidth information. server_id = 11498369 softlayer_client = SoftLayer::Client.new(:username => 'set me', :api_key => 'set me') server = SoftLayer::VirtualServer.server_with_id(server_id, :client => softlayer_client) get_bandwidth_data_by_date = server.service.getBandwidthDataByDate('2016-03-29T00:00:00','2016-03-30T00:00:00','public') pp('getBandwidthDataByDate: ', get_bandwidth_data_by_date) ``` **References:** [SoftLayer\_Virtual\_Guest::getBandwidthDataByDate](http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getBandwidthDataByDate)
Disclamer: I created my own Ruby SoftLayer client, you can check it at <http://github.com/zertico/softlayer> specially for situations like this one where you want to access some specific data (and I'm not SoftLayer staff ;) ) If you'd like to give it a try the code that solves your problem is ps: I'm considering you are manipulating a SoftLayer\_Hardware\_Server, right? ``` hardware = Softlayer::Hardware::Server.find(123) hardware.get_current_bandwidth_summary mask = 'mask[currentBandwidthSummary]' hardware = Softlayer::Hardware::Server.mask(mask).find(123) hardware.current_bandwidth_summary ``` You will access a ruby object like this one: ``` => #<Softlayer::Metric::Tracking::Object::Bandwidth::Summary:0x007ff74b683540 @allocation_amount="1234", @allocation_id=111111, @amount_out="12.34567", @average_daily_usage="1.23", @currently_over_allocation_flag=0, @id=1111111, @outbound_bandwidth_amount="123.45678", @projected_bandwidth_usage="123.45", @projected_over_allocation_flag=0> ``` Hope it can helps you, comment if you have any doubt about the client usage
33,284,509
The IBM MobileFirst Knowledge Center [states that](http://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/devref/t_setting_up_push_notification_iOS.html?lang=en) the following servers and port numbers have to be accessible for APNS push notifications to work: * `gateway.sandbox.push.apple.com:2195` * `feedback.sandbox.push.apple.com:2196` * `gateway.push.apple.com:2195` * `feedback.push.apple.com:2196` However, I have seen references in Apple documentation to the endpoint `1-courier.push.apple.com:5223` (for example, Apple's troubleshooting documentation [here](https://developer.apple.com/library/ios/technotes/tn2265/_index.html#//apple_ref/doc/uid/DTS40010376-CH1-TNTAG31)). Is this server and port required to be accessible by the MFP server (through a firewall) also? What is it used for?
2015/10/22
[ "https://Stackoverflow.com/questions/33284509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27641/" ]
I am not clear on what is it for, but unlike the Knowledge Center - the tutorial does mention that the MobileFirst Server instance requires that address to be available for it: <https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/notifications/push-notifications-overview/push-notifications-in-hybrid-applications/#setupiOS> Have you tried with and without it and observed any differences?
5223 is required only if the devices are connected over WiFi. "To reach the feedback service, you will need to allow inbound and outbound TCP packets over port 2196. Devices and computers connecting to the push service over Wi-Fi will need to allow inbound and outbound TCP packets over port 5223"
14,507
Other than Biggs telling the commanding officer that Luke the "best bush pilot in the outer rim", what other qualifications did he have to lead the fighter group that took out the Death Star? Both Biggs and Wedge had been in the rebel alliance longer and I'd assume seasoned pilots, at least more so than Luke. Was there a reason that Biggs or Wedge didn't lead the last group? Up until that battle, I don't remember reading or seeing anything about Luke being in combat. I wouldn't think you'd want someone that green leading an assault as important as that one was.
2012/04/08
[ "https://scifi.stackexchange.com/questions/14507", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/4953/" ]
By the time the "shot heard round the Empire" occurred, Luke's entire squadron was shot down minus Biggs, who had retreated out to counter Vader's TIE squad. Luke was the only one left to take the shot. He didn't lead the squad at all, he just outlasted most of them.
Because Luke is incorporated into the rebel army with a high starting rank in recognition of his having rescued Princess Leia. Remember that Han is also offered a commission, although he refuses.
9,087,116
I have an old 2.1.1 Ruby on Rails application, with the system upgraded to use Ruby 1.8.7. It originally used 1.8.5 or so. I want to upgrade it to Ruby 1.9.x for performance reasons, and possibly to a newer Ruby on Rails as well. I cannot find any easy chart of compatibility between different Ruby versions and Ruby on Rails versions. Will 2.1.1 work with Ruby 1.9.x? If not, how far do I need to upgrade it first, and what kind of issues am I likely to encounter? My application does complicated things to database layer, but the rest is fairly straightforward.
2012/01/31
[ "https://Stackoverflow.com/questions/9087116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52751/" ]
This is an old question, but the fact that rails is tested against a version of ruby is a good indication that it should work on that version of ruby. Since 9th April 2019, stable branches of Rails use Buildkite for automated testing, and the list of tested ruby versions, by rails branch, is: Rails 6.1 * `>= 2.5.0` Rails 6.0 * `>= 2.5.0` Rails 5.2 * `>= 2.2.2` * `< 2.7` (see <https://github.com/rails/rails/issues/38426>) Rails 5.1 * `>= 2.2.2` Rails 5.0 * `>= 2.2.2` Rails 4.2 * `>= 1.9.3` Rails 4.1 * `>= 1.9.3` Prior to 9th April 2019, stable branches of Rails since 3.0 use travis-ci for automated testing, and the list of tested ruby versions, by rails branch, is: Rails 3.0 * 1.8.7 * 1.9.2 * 1.9.3 Rails 3.1 * 1.8.7 * 1.9.2 * 1.9.3 Rails 3.2 * 1.8.7 * 1.9.2 * 1.9.3 * 2.0.0 * 2.1.8 * 2.2.6 * 2.3.3 Rails 4.0 * 1.9.3 * 2.0.0 * 2.1 * 2.2 Rails 4.1 * 1.9.3 * 2.0.0 * 2.1 * 2.2.4 * 2.3.0 Rails 4.2 * 1.9.3 * 2.0.0-p648 * 2.1.10 * 2.2.10 * 2.3.8 * 2.4.5 Rails 5.0 * 2.2.10 * 2.3.8 * 2.4.5 Rails 5.1 * 2.2.10 * 2.3.7 * 2.4.4 * 2.5.1 Rails 5.2 * 2.2.10 * 2.3.7 * 2.4.4 * 2.5.1 Rails 6.0 * 2.5.3 * 2.6.0 (From <https://www.hmallett.co.uk/2018/08/ruby-and-ruby-on-rails-version-compatibility/>)
The Rails Guide on Upgrading Ruby on Rails has a section on [Ruby versions](http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#ruby-versions). This is probably the best source as it is controlled by the Rails core team. As of August, 2016, the Rails Guide reads: > > ### 1.3 Ruby Versions > > > Rails generally stays close to the latest released Ruby version when it's released: > > > * Rails 5 requires Ruby 2.2.2 or newer. > * Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer. > * Rails 3.2.x is the last branch to support Ruby 1.8.7. > * Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible. > > >
556,480
I have yearned to use 24-bit colors in the terminal for applications such as Vim. However, xterm is limited to no more than 256 colors, which I have currently been using. I just recently learned that the Konsole terminal actually supports this True Color, but unfortunately I cannot find the correct environment to use these colors. I have only been able to set "konsole-256color" so far. How can I set Konsole to use True Color for Vim and whatnot, is this possible, or are these colors not standard in the Konsole implementation (I was inspired to use this for the new Vim powerline Python implementation)?
2013/02/24
[ "https://superuser.com/questions/556480", "https://superuser.com", "https://superuser.com/users/162554/" ]
Konsole, gnome-terminal (and all vte-based GTK+ 3 terminals since vte 0.35.1), qterminal and st (from suckless) support true colors on Linux, and iTerm2 support it on Mac. Unfortunately there's no termcap/terminfo support for this feature at the moment, and hence there's no correct value for $TERM either. Nor do the screen libraries ncurses and slang support the feature, and it seems they require ABI-incompatible change to get this fixed. The best you can do for now is set TERM=xterm-256color (or similar) and have the escape sequences hardcoded in applications (assuming the app does its own terminal handling, rather than relying on ncurses). I'm afraid it's going to take years to get this feature properly supported at all levels of the stack.
Got to Profile -> Environment and add: COLORTERM=truecolor This is what some application will check for. See e.g. <http://lists.jedsoft.org/lists/slang-users/2016/0000014.html>
48,961,825
I have an F5 bigip.conf text file in which I want to change the route domain from 701 to 703 for all lines showing "10.166.201." The route domain is represented by %701 ``` 10.166.201.10%701 10.166.201.15%701 10.166.201.117%701 ``` I am able to do this with bash but the problem is that the "else printf" command (I've also tried echo), which is supposed to print out all other lines, incorrectly parses things like "\r\n" and leaves them as "rn" ``` #!/bin/bash while read line do if [[ $line = *"10.166.201"* ]]; then printf '%s\n' "$line" | sed -e 's/701/703/' else printf '%s\n' "$line" fi done < bigip.conf > bigip.conf_updated ``` Is there a way to stop printf and echo from modifying the "\r\n"? Is there a better way to do this in sed/awk? Thanks.
2018/02/24
[ "https://Stackoverflow.com/questions/48961825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1776732/" ]
Your iPhone does not have the same *device pixel ratio* as your PC. The canvas will not render at the same resolution as it is displayed, and then can appear blurry. You have to set a css size to your canvas, then, set this size times `window.devicePixelRatio` as the size of the canvas. Finally scale your canvas coordinate system by a factor `window.devicePixelRatio` to have a pixel perfect rendering. (this article can help for further explanation <https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio>) > > A canvas can appear too blurry on retina screens. Use > window.devicePixelRatio to determine how much extra pixel density > should be added to allow for a sharper image. > > > > ``` > var canvas = document.getElementById('canvas'); > var ctx = canvas.getContext('2d'); > > // Set display size (css pixels). > var size = 200; > canvas.style.width = size + "px"; > canvas.style.height = size + "px"; > > // Set actual size in memory (scaled to account for extra pixel density). > var scale = window.devicePixelRatio; // <--- Change to 1 on retina screens to see blurry canvas. > canvas.width = size * scale; > canvas.height = size * scale; > > // Normalize coordinate system to use css pixels. > ctx.scale(scale, scale); > > ``` > >
how about this? ```js var c=document.getElementById("canvas"); var ctx=c.getContext("2d"); ctx.strokeStyle = "red"; ctx.beginPath(); ctx.moveTo(50,50); ctx.lineWidth = 10; ctx.lineTo(50,100); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.arc(50, 50, 5, 0, 2 * Math.PI, false); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath(); ``` ```html <div style="position: absolute; margin-left: 25%;display: table; align-self: center; width: 100%;"> <canvas id="canvas"></canvas> </div> ```
8,152,731
I have a program that renames files or folders to lower case names. I have written this code: ``` private void Replace(string FolderLocation, string lastText, string NewText) { if (lastText == "") { lastText = " "; } if (NewText == "") { NewText = " "; } DirectoryInfo i = new DirectoryInfo(FolderLocation); string NewName = ""; if (checkBox2.Checked) { if (i.Parent.FullName[i.Parent.FullName.Length - 1].ToString() != "\\") //For parents like E:/ { NewName = i.Parent.FullName + "\\" + i.Name.Replace(lastText, NewText); } else { NewName = i.Parent.FullName + i.Name.Replace(lastText, NewText); } NewName = NewName.ToLower(); if (NewName != i.FullName) { i.MoveTo(NewName); } foreach (DirectoryInfo sd in i.GetDirectories()) { Replace(sd.FullName, lastText, NewText); } } if (checkBox1.Checked) { foreach (FileInfo fi in i.GetFiles()) { NewName = fi.Directory + "\\" + fi.Name.Replace(lastText, NewText); NewName = NewName.ToLower(); if (NewName != fi.FullName) { fi.MoveTo(NewName); } } } } ``` But I get the following exception: > > "Source and destination path must be different." > > > How can I solve this issue?
2011/11/16
[ "https://Stackoverflow.com/questions/8152731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1003464/" ]
Although Windows Filesystems store names case-senstivie they behave case-insensitive on name comparison thus your renaming operation won't work... IF you really need/want to do that you will need to first rename temporarily the file/directory to something different and unique, then rename it "back" to the "lower case name" you want. For reference see <http://msdn.microsoft.com/en-us/library/ee681827%28v=vs.85%29.aspx> and <http://support.microsoft.com/kb/100108/en-us> . IF you need NTFS to be case-sensitive you can set the dword `ObCaseInsensitive` under `HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\kernel\` to 0 (NOT RECOMMENDED!). IF you are dealing with NFS then see <http://technet.microsoft.com/en-us/library/cc783185%28WS.10%29.aspx> .
Unfortunately this is a windows issue as it is case insensitive as Oded mentions in the comments. What you would have to do is to rename the folder twice. By moving the folder to a new temporary name then back to the lowercase of the original name.
69,526
How do you set the value of a file field when using the entity\_metadata\_wrapper? I've tried doing this in code: ``` $file = new stdClass(); $file->uid = 1; $file->uri = $file_path; $file->filename = basename($file_path); $file->filemime = file_get_mimetype($file_path); $file->filesize = filesize($file_path); $file->status = FILE_STATUS_PERMANENT; $file->display = '1'; file_save($file); // I also tried: $file = file_save($file); $node = array( 'type' => 'news_item', 'uid' => 1, 'status' => 1, 'comment' => 0, 'promote' => 0, 'language' => 'en', ); $entity = entity_create('node', $node); $ewrapper = entity_metadata_wrapper('node', $entity); $ewrapper->field_document->set((array) $file); // I also tried: $ewrapper->field_document->set($file); $ewrapper->save(true); entity_save('node', $entity); ``` But I get this exception: ``` EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of C:\wamp\www\drupal\sites\all\modules\entity\includes\entity.wrapper.inc). ``` Any help is very mych appreciated.
2013/04/10
[ "https://drupal.stackexchange.com/questions/69526", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/11807/" ]
Well I just found out a **simpler and less ugly looking way to set image**. ``` $image_file = A FILE OBJECT; //Lot of choices here : new stdClass(), file_load, etc $wrapper->FIELD_NAME->file->set($image_file); ``` Just as taxonomy or node/entity reference, the file field name point on a loaded object, thats how I find out. --- :: EDIT a posteriori :: Here how I would have do it with OP question. ``` // Get the file $file = file_save_data(file_get_contents('/my_local_path/img1.jpg'), 'public://remote_name.jpg'); // Wrap' it like one of your French girls $wrapper = entity_metadata_wrapper('node', $node); // And set the photo $wrapper->field_photo->file->set($file); // And save the node $wrapper->save(); ```
You have two ways to do it: ``` // By loading the file object in any way $file_obj = file_load($fid); $w_containing_node->field_attachment_content->file->set( $file_obj ); // By passing an array with the fid $w_containing_node->field_attachment_content->set( array('fid' => $fid) ); ``` Here is the source of the information: <https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers#example-value-set-save>
1,468,912
I have 3 different types of data: images, videos, and audio clips. Each one has an associated GPS point, so I have a base class as such: ``` public abstract class Data { public Latitude { get; set; } public Longitude { get; set; } } ``` This is so I can plot everything on a map without worrying about what kind of data it is. However, I've been reading that POCO is not supposed be derived from anything except the base `object` class in C#. Is this true?
2009/09/23
[ "https://Stackoverflow.com/questions/1468912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135318/" ]
Where did you read that? How would you build an object hierarchy if you were not allowed to derive from classes other than `System.Object`? (It goes without saying that `System.Object` will always be at the top of your class hierarchy in .NET)
While you can use inheritance, I'm not sure data of type Latitude, and Longitude are allowed in plain old CLR/C# objects.
25,390
Is there a way ,or some steps which ensure any custom module/code written in Magento is adhering to all standard/best practices, without it breaking Magento in any case i.e upgrades,extension conflicts etc.
2014/06/28
[ "https://magento.stackexchange.com/questions/25390", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/7909/" ]
You can see the error in browser (if that's what you want to do) by renaming errors/local.xml.sample to errors/local.xml . The exceptions with traces will be shown in browser then.
*it seems this is for a different version of Magento as I do not have var/report* Missing var/report indicates that something is wrong with the file permissions in the var/ directory tree. You will not be able to view the files or find the folder because Magento is being prevented from creating it in the first place and therefore has no place to create the error stack trace file.
5,035,763
I am using `flowLayoutPanel` to have relative location controls. I would like to change the location of control inside the `flowLayoutPanel`. when I say location, I dont mean control1 before control2 or something like that - I mean that if I got 2 controls, lets say `label` and `comboBox` - the `comboBox`'s height is 21, the `label`'s height is 13 and the `flowLayoutPanel`'s height is 21 also. I want to put the `label` in the vertical middle of the `flowLayoutPanel` - ((21-13)/2) from top. I dont want something specific for vertical middle I want general solution.
2011/02/17
[ "https://Stackoverflow.com/questions/5035763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519002/" ]
You could also set the top margin of the label to (containerHeight-labelHeight)/2
The flow layout is not going to help: it just arranges all controls in a list, adjusting their position to fit in the panel. You can create subgroups by putting controls in a table within the flow layout, or just use a table for maximum control.
58,540,655
How can i convert the below string to JSON using python? ``` str1 = "{'a':'1', 'b':'2'}" ```
2019/10/24
[ "https://Stackoverflow.com/questions/58540655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11889950/" ]
The string in OP's question is not JSON because the keys and values are enclosed by single-quotes. The function `ast.literal_eval` can be used to parse this string into a Python dictionary. ``` import ast str1 = "{'a':'1', 'b':'2'}" d = ast.literal_eval(str1) d["a"] # output is "1" ``` Other answers like <https://stackoverflow.com/a/58540688/5666087> and <https://stackoverflow.com/a/58540879/5666087> were able to use the `json` library because they changed `str1` from `"{'a':'1', 'b':'2'}"` to `'{"a":"1", "b":"2"}'`. The former is invalid JSON, whereas the latter is valid JSON.
``` import json str1 = '{"a":"1", "b":"2"}' jsonData = json.loads(str1) print(jsonData["a"]) ``` Reference : [LINK](http://docs.python.org/3/library/json.html)
47,043,063
So, I have two lists: ``` x =[170 169 168 167 166 165 183 201 219 237 255 274 293 312 331 350] y =[201,168] ``` I want to write a conditional `if` statement that is true only if all the contents of `y` are in `x`. How do I do this? E.g. -- `assert(y[0] in x)` and `assert(y[a] in x)` both give `True`, but `assert(y in x)` gives `False`. Similarly, `assert( any(y) in x )` raises an error as well.
2017/10/31
[ "https://Stackoverflow.com/questions/47043063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7250309/" ]
[Sets](https://docs.python.org/3.6/library/stdtypes.html#set-types-set-frozenset) are better for this: ``` set(y) <= set(x) ``` Note that this relies on your list contents being immutable, as mutable (or, more specifically, *unhashable*) objects cannot be members of sets. As in this case, lists of integers are fine.
If you insist on having them be lists, you can use the `all()` function: ``` all(item in x for item in y) ```
27,306,246
I have a program but I dont know specifically what my mistake is or how to fix it: The question is: Write a program that asks the user to enter a series of numbers separated by commas. The program should calculate and display the sum of all the numbers. For example, if I enter 4,5,6,7, the sum displayed should be 22. This is what I have so far: ``` import java.util.Scanner; public class SumAll { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String userNumber; String sum = null; //get numbers from user and store System.out.println("Enter numbers seperated by coma's: "); userNumber = keyboard.nextLine(); String[] tokens = userNumber.split("[, ]"); for (int i = 0; i < tokens.length; i++) { sum = tokens.length[i++]; //showing me error here. Its written array required but int //found. } System.out.println("Sum is: " + sum); } } ``` Thank you very much for the help.
2014/12/04
[ "https://Stackoverflow.com/questions/27306246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Sum should be an int ``` int sum = 0; ``` Your for loop should be ``` for (int i = 0; i < tokens.length; i++) { sum += Integer.parseInt(tokens[i]); } ```
I know I am more than 2 years late but I started learning Java not too long ago and would like to share my solution. :) I used the StringTokenizer class. I hope this helps someone out there in 2017 and onward. ``` import java.util.Scanner; import java.util.StringTokenizer; public class SumOfNumbersInString { public static void main(String[] args) { // Create a Scanner object Scanner keyboard = new Scanner(System.in); // Get user input System.out.print("Enter a series of numbers seperated by commas\n> "); String input = keyboard.nextLine(); // Display sum by calling the getSum method System.out.println("SUM: " + getSum(input)); } /** * * @param input with the format --> (#,#,#,#) * @return sum of numbers in the input */ public static int getSum(String input) { // Declare and initialize the sum accumulator variable int sum = 0; // Create a StringTokenizer object // The string to be tokenized is passed as 1st parameter // The "," that separates tokens/numbers is the 2nd parameter StringTokenizer stringTokenizer = new StringTokenizer(input, ","); // The hasMoreTokens method of the StringTokenizer class returns true if there are more tokens left in the string // Otherwise, it returns false while (stringTokenizer.hasMoreTokens()) { // While the string has another token (number), parse the number to an integer and add its value to sum sum += Integer.parseInt(stringTokenizer.nextToken()); } // Return sum's value to the method call return sum; } } ``` OUTPUT ``` Enter a series of numbers seperated by commas > 4,5,6,7 SUM: 22 ```
26,426
What's the practical difference between Google Drive and Dropbox? What features does one offer that the other doesn't? Specifically, how well does sharing and permissions work in Google Drive (Dropbox is fairly straightfoward)?
2012/05/04
[ "https://webapps.stackexchange.com/questions/26426", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/5784/" ]
One could sit and write all the features here, but you could also just google around as there are hundreds of post on this right now. [The one from The Verge](http://www.theverge.com/2012/4/24/2954960/google-drive-dropbox-skydrive-sugarsync-cloud-storage-competition) has a more elaborated answer.
I want to point out here that I wish Google Drive gave users the option to open files in Docs or via a native app like Pages. The lack of this option is why I use [Insync](http://Insynchq.com). Insync syncs all Google Docs as .DOC files so I can open them in Pages if necessary. It's rarely necessary, but it's nice to have the option.
1,688
I want to design a table to store friendship relationship in my web project It should satisfy at least the following 4 conditions: > > who send the add-friend request e.g.(if A TO B then this column will be A) > > > who receive the add-friend request e.g.(if A TO B then this column will be B) > > > current status e.g.(0 denotes rejected whereas 1 denotes accepted or 2 denotes unprocessed > > > our friend relationship is bilateral > > > **If any of you are experienced with this , any suggestion is welcomed** *my current design (I think bad right now) is like this* **these are the columns** ``` frienshipId fromUserId toUserId status requestTime ```
2011/03/11
[ "https://dba.stackexchange.com/questions/1688", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/1168/" ]
I'd create a table a lot like the one that you have. I'm using SQL Server data types and syntax, you may need to tweak depending on your platform. ``` CREATE TABLE FriendStatus (FriendStatusId BIGINT PRIMARY KEY IDENTITY(1,1), FromUserId BIGINT, ToUserId BIGINT, StatusId TINYINT, SentTime DATETIME2, ResponseTime DATETIME2); ``` Indexing of the table will be critical as the table grows to the tens and hundreds of millions.
What makes you think your current design is bad? Here is a create table for Oracle: ``` CREATE TABLE IVR.FRIEND ( FRIENDID NUMBER(7) NOT NULL , FROMUSERID NUMBER(7) NOT NULL , TOUSERID NUMBER(7) NOT NULL , STATUSID NUMBER(2) NOT NULL , REQUESTED DATE NOT NULL , CONSTRAINT FRIEND_PK PRIMARY KEY (FRIENDID) ENABLE ); CREATE SEQUENCE FRIENDIDSEQ; ``` If the database is Oracle you might want to consider an indexed virtual column that will limit the data to entries needed for particular queries. For example, you could have a virtual column called AcceptedFromUserId that uses the function DECODE(StatusId,1,FromUserId,NULL). The index would only contain AcceptedUserIds and would therefore be smaller than an index for all UserIds. If you regularly clean out rejected requests an indexed virtual column on PendingToUserId might be more useful. An alternative if you had partitioning would be to partition the table on the StatusId. If you don't need multiple friend requests between the same users at the same time you could abandon the FriendId using FromUserId, ToUserId, and StatusId as your primary key. In this case you should also consider making the table an Index Organized Table.
36,560,589
A vampire number is defined here <https://en.wikipedia.org/wiki/Vampire_number>. A number V is a vampire number if: * It can be expressed as X\*Y such that X and Y have N/2 digits each where N is the number of digits in V * Both X & Y should not have trailing zeros * X & Y together should have the same digits as V I came up with a solution, ``` strV = sort(toString(V)) for factor <- pow(10, N/2) to sqrt(V) if factor divides V X <- factor Y <- V/factor if X and Y have trailing zeros continue checkStr = sort(toString(X) + toString(Y)) if checkStr equals strV return true ``` Another possible solution is to permute the string represented by V and split it into half and check if its a vampire number. Which one is the best way to do so?
2016/04/11
[ "https://Stackoverflow.com/questions/36560589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2650894/" ]
In pseudocode: ``` if digitcount is odd return false if digitcount is 2 return false for A = each permutation of length digitcount/2 selected from all the digits, for B = each permutation of the remaining digits, if either A or B starts with a zero, continue if both A and B end in a zero, continue if A*B == the number, return true ``` There are a number of optimizations that could still be performed here, mostly in terms of ensuring that each possible pair of factors is tried only once. In other words, how to best check for repeating digits when selecting permutations? But that's the gist of the algorithm I would use. P.S.: You're not looking for primes, so why use a primality test? You just care about whether these are *vampire* numbers; there are only a very few possible factors. No need to check all the numbers up to sqrt(number).
Here are some suggestions: 1. First a simple improvement: if the number of digits is < 4 or odd return false (or if v is negative too). 2. You don't need to sort `v`, it is enough to count how many times each digit occurs O(n). 3. You don't have to check each number, only the combinations that are possible with the digits. This could be done by backtracking and significantly reduces the amount of numbers that have to be checked. 4. The final sort to check if all digits were used isn't needed either, just add up the used digits of both numbers and compare with the occurences in `v`. Here is the code for a JS-like language with integers that never overflow, the `V` parameter is an integer string without leading 0s: *Edit:* As it turns out the code is not only JS-*like*, but valid JS code and it had no problem to decide that 1047527295416280 is indeed a vampire number ([jsfiddle](https://jsfiddle.net/qa6vy9e0/2/)). ``` var V, v, isVmp, digits, len; function isVampire(numberString) { V = numberString; if (V.length < 4 || V.length % 2 == 1 ) return false; v = parseInt(V); if (v < 0) return false; digits = countDigits(V); len = V.length / 2; isVmp = false; checkNumbers(); return isVmp; } function countDigits(s) { var offset = "0".charCodeAt(0); var ret = [0,0,0,0,0,0,0,0,0,0]; for (var i = 0; i < s.length; i++) ret[s.charCodeAt(i) - offset]++; return ret; } function checkNumbers(number, depth) { if (isVmp) return; if (typeof number == 'undefined') { for (var i = 1; i < 10; i++) { if (digits[i] > 0) { digits[i]--; checkNumbers(i, len - 1); digits[i]++; } } } else if (depth == 0) { if (v % number == 0) { var b = v / number; if (number % 10 != 0 || b % 10 != 0) { var d = countDigits('' + b); if (d[0] == digits[0] && d[1] == digits[1] && d[2] == digits[2] && d[3] == digits[3] && d[4] == digits[4] && d[5] == digits[5] && d[6] == digits[6] && d[7] == digits[7] && d[8] == digits[8] && d[9] == digits[9]) isVmp = true; } } } else { for (var i = 0; i < 10; i++) { if (digits[i] > 0) { digits[i]--; checkNumbers(number * 10 + i, depth - 1); digits[i]++; } } } } ```