qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
49,320,384
Is there a way in Laravel to do some check on associating? For example I've `Home` and `Owner`, I would like on `associate` check if `Home` as already an `Owner`, and in that case I must execute some code... Some suggestions?
2018/03/16
[ "https://Stackoverflow.com/questions/49320384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1663720/" ]
You should use `event.stopPropagation();` who prevents the event from beeing trigger with the children elements. There is the doc : <https://api.jquery.com/event.stoppropagation/>
5,516,743
I'm trying to setup a 2-column layout where the left area is fixed and the main content is fluid. I've seen several answers on here, which tend to work. However, there is some odd behavior when I use a "jsTree" in my "left" area and jQuery UI tabs in the main/content area. **html** ``` <div id="main"> <div id="left"> <div id="tree"> </div> </div> <div id="right"> <ul> <li><a href="#a">A</a></li> <li><a href="#b">B</a></li> <li><a href="#c">C</a></li> </ul> <div id="a"> <h3>A is here</h3> </div> <div id="b"> <h3>B is here</h3> </div> <div id="c"> <h3>C is here</h3> </div> </div> </div> ``` **css** ``` #left { float: left; width: 200px; overflow: auto; } #right { margin: 0 0 0 200px; } ``` **javascript** ``` $(document).ready(function() { $('#right').tabs(); $('#tree').jstree({ "plugins" : [ "json_data", "themes"], "json_data" : { "data" : [ { "data" : "A node", "children" : [ "Child 1", "Child 2" ] }, { "attr" : { "id" : "li.node.id" }, "data" : { "title" : "Long format demo", "attr" : { "href" : "#" } } } ] }, }); }); ``` The problem I'm having is, as I expand the tree (on the left) the tabs on the right start getting funky. The area containing the tabs (the element I believe) grows vertically. Take a look here for this example: <http://jsfiddle.net/codecraig/gBUw2/>
2011/04/01
[ "https://Stackoverflow.com/questions/5516743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70535/" ]
Josiah has it right but a better solution is to change the nature of the clear-fix technique. The `.ui-helper-clearfix` does this: ``` .ui-helper-clearfix::after { clear: both; content: '.'; display: block; height: 0px; visibility: hidden; } ``` And the problem is the `clear:both`. You can get the desired clearing without losing the full-width block display with this: ``` #right .ui-helper-clearfix { clear: none; overflow: hidden; } ``` That replaces the `clear:both` *clear-fix* with an `overflow:hidden` *clear-fix*. <http://jsfiddle.net/ambiguous/BkWWW/>
61,367,678
Consider following code snippet: ``` enum class Bar { A }; void foo(Bar) {} struct Baz { void foo() { foo(Bar::A); } }; ``` It fails to compile, the message from gcc 9.2 is: ``` :12:19: error: no matching function for call to 'Baz::foo(Bar)' 12 | foo(Bar::A); | ``` I don't suspect it is a bug since clang 10 also fails. I have two questions regarding this situation: 1. Where does standard define bahaviour for such overloads? 2. What are the possible reasons that compiler behaviour is specified that way? [live example](https://godbolt.org/z/LcnL9-)
2020/04/22
[ "https://Stackoverflow.com/questions/61367678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3414900/" ]
According to the rule of unqualified name lookup, from the standard, [[basic.lookup.unqual]/1](https://timsong-cpp.github.io/cppwp/basic.lookup.unqual#1), (emphasis mine) > > In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaration in the order listed in each of the respective categories; **name lookup ends as soon as a declaration is found for the name**. > > > That means the name `foo` is found at the class scope (i.e. the `Baz::foo` itself), then name lookup stops; the global one won't be found and considered for the overload resolution which happens later. About your 2nd question, functions can't be overloaded through different scopes; which might cause unnecessary confusion and complexity. Consider the following code: ``` struct Baz { void foo(int i) { } void foo() { foo('A'); } }; ``` You know `'A'` would be converted to `int` then passed to `foo(int)`, that's fine. If functions are allowed to be overloaded through scopes, if someday a `foo(char)` is added in global scope by someone or library, behavior of the code would change, that's quite confusing especially when you don't know about the adding of the global one.
16,077,321
My question has already been asked here in the following link. [Spring: Why do we autowire the interface and not the implemented class?](https://stackoverflow.com/questions/12899372/spring-why-do-we-autowire-the-interface-and-not-the-implemented-class/12899432#12899432) What I want to know if we use `@Qualifier` to inject a bean than what is the purpose of autowiring an interface ?? Why not we auto-wire the same implementation class ?? By autowiring an interface we want to take advantage of run-time polymorphism but that's not achieved if we follow the approach of `@Qualifier`. Please suggest me a standard way. Following is the simple code if I do it without spring. I wonder how spring will inject the PrepaidPaymentService instance and PostPaidPaymentService instance?? ``` public interface PaymentService{ public void processPayment(); } public class PrepaidPaymentService implements PaymentService{ public void processPayment(){ System.out.println("Its Prepaid Payment Service"); } } public class PostPaidPaymentService implements PaymentService{ public void processPayment(){ System.out.println("Its Postpaid Payment Service"); } } public class Test { public PaymentService service; public static void main(String[] args) { Test test = new Test(); int i = 1; if(i ==1 ){ test.setService(new PrepaidPaymentService()); test.service.processPayment(); } i = 2; if(i == 2){ test.setService(new PostPaidPaymentService()); test.service.processPayment(); } } public void setService(PaymentService service){ this.service = service; } } ```
2013/04/18
[ "https://Stackoverflow.com/questions/16077321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2067856/" ]
There is [`do`](https://rvm.io/set/do/) command in RVM. So you need to call: ``` %x{rvm 1.8.7 do /usr/bin/podcast} ``` or if `/usr/bin/` is in `$PATH` you can run only: ``` %x{rvm 1.8.7 do podcast} ```
59,147
How do I change the Device Name of my Nexus 7 2013 (not rooted)? On my Samsung Galaxy S4 hotspot, the Nexus 7 shows up as `android-xxx`, where `xxx` is some random sequence of characters. How do I change the name to something like `geffchang-nexus7`?
2013/12/17
[ "https://android.stackexchange.com/questions/59147", "https://android.stackexchange.com", "https://android.stackexchange.com/users/5342/" ]
Unless the OEM has built in the option (Samsung have for example) you cannot change the device name without [root](/questions/tagged/root "show questions tagged 'root'"). The [nexus-7](/questions/tagged/nexus-7 "show questions tagged 'nexus-7'") does not have this option. On the Samsung Galaxy S4 (for example) you can go to *Settings > More > About Device > Device Name* and you can change it directly from there. For those with root: ``` su getprop net.hostname setprop net.hostname <new_hostname> ``` Or simply download a [build.prop editor app from the play store.](https://play.google.com/store/apps/details?id=org.nathan.jf.build.prop.editor&hl=en) This requires Root also. WARNING: Any changes to this file can stop your device from working or cause unexpected behaviour, do so at **YOUR OWN RISK.** --- **To change Hotspot name:** Go to > > Wireless & Networks > Tethering & Portable hotspot. > > > ![](https://cdn3.pcadvisor.co.uk/cmsdata/features/3279408/3-Portable-hotspot-web_thumb.jpg) Then > > > > > > Tick the box next to Portable Wi-Fi hotspot > > Tap Portable Wi-Fihotspot settings and you can edit the Wi-Fi network > > name, and choose a password. > > > > > > > > > ![](https://cdn3.pcadvisor.co.uk/cmsdata/features/3279408/4-Portable-hotspot-web_thumb.jpg) Enter your name there!
12,525
I've been scouring google to see if it's possible to record gameplay audio for consoles as well as live commentary from a microphone or headset. Most of what I come across, from either forums or product FAQs say that it's possible to do one but not both. On PCs, it's easy, but on consoles you can only do one. Or so I'm told. However, I see quite a few videos on Youtube from consoles with both game audio and live commentary. So it must be possible. Can anyone tell me how how it's possible to do both on a console? I know nothing about video editing and production so I'm curious what devices and programs are needed to accomplish this. Also, is it possible to record the console audio and live commentary as two separate tracks? Thank you for your time! I appreciate any help.
2014/09/02
[ "https://avp.stackexchange.com/questions/12525", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/6425/" ]
`-preset` ========= Use the slowest preset that is fast enough that it does not drop frames. You can see if `ffmpeg` is dropping frames in the console output (if I recall correctly). Presets are: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. `-crf` ====== Use the highest `-crf` value that still provides an acceptable quality level. Range is 0-51. 0 is lossless, 18 is generally considered to be visually lossless or nearly so, 23 is default, and 51 is worst quality. Using a value of 1 will likely result in a huge file. ### Also see: * [FFmpeg H.264 Video Encoding Guide](https://trac.ffmpeg.org/wiki/Encode/H.264)
4,776,446
There a lot of C++ class libraries either open source or commercial like MFC, ATL, SmartWin++, QT. but none of them has the design and the architecture and the purity of .NET framework class library. What about the idea of implementing C++ library that is like .NET framework class library and provide the developers with a wide range of features and of course the library will be unmanaged and will wrap win32 API and COM
2011/01/23
[ "https://Stackoverflow.com/questions/4776446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/539471/" ]
Interesting question. But I believe it would be either a waste of time or not optimal to re-create the .NET BCL (base class library) for unmanaged C++. Why is that? 1. The C++ language is quite different from the .NET languages. This means that if you were to re-write the BCL for C++, you would optimally try to make the best use of C++. This would probably result in a fairly different framework design: * `IDisposable` and `Close` methods would not be necessary, since C++ offers deterministic freeing of releases and teardown of objects; something like `using` blocks, but far more generic. (The relevant C++ concepts are scopes, automatic storage, RAII, and smart pointer classes.) That is, a C++ BCL has the potential for a much more elegant design in this respect. * C++ templates are quite different from .NET generics. C++ also doesn't have delegates or events (even though you could probably mimick these). Reflection and run-time type and code generation also won't work easily with C++. Finally, C++ (before C++0x) doesn't support lambda functions. This means that the more modern additions to the BCL would probably have to look quite different in C++. 2. There are things in the BCL that have become obsolete, or if you designed the BCL today, it would turn out quite differently. Let's take `System.Reflection`. This part of the BCL was built before generics were introduced. If it was re-written from scratch today, chances are that reflection would take advantage of generics and therefore better type safety. 3. As you see, a new, C++ version of the BCL would very likely end up quite different than the .NET BCL it's based on; so you ought to wonder if it's even necessary to base such a new library on the .NET BCL at all. Do you even need to have one single framework, or is it easier in the end to develop separate libraries? One for networking, one for abstract data types, one for GUIs, one for reflection etc. * Separate libraries have the disadvantage that they possibly have no consistent API design. Therefore experience with one library doesn't help you at all learning another API. * Because of that, separate libraries can be easier to maintain. One can maintain the reflection library without having to concert each of one's actions with the GUI library maintainers, for example. * Separate libraries have the advantage that you can exchange one for the other if you find a cleaner, faster, or otherwise better replacement. 4. Even if someone wrote a C++ version of the BCL -- it would take much resources to maintain such a library in the long term, even more so when you consider that it should be platform-independent. Microsoft has this capacity and these resources. Would you, too? The lure of one great library for everything is indeed the consistency of one API, and the fact that "everyone" would use it. But I think even if you wrote such a C++ BCL, you'll find it hard to reach almost every C++ programmer and convince them to your that library.
26,857
There is a lot of track remixes online. Most of producers use separated vocals from songs. It is almost impossible that they could cut only vocal out of total track in such good quality. What is more, anywhere in the network is not available finished dry vocal version. So how is it possible that they are in possession of such good vocal version? Assume also that they have not purchased it from the artist. Please tell me HOW?? O\_O Thx
2013/10/17
[ "https://sound.stackexchange.com/questions/26857", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/6561/" ]
The generic term for split / separated tracks is "stems". If you google "vocal stems" you'll find free ones for random songs, not hits but usable. Vocal stems for popular songs are usually available (at a price) from the label or artist.
25,234,556
In vim, I could use `:%sno/[abt]//g` to remove all text of "[abt]" literally (as explained [here](http://vim.wikia.com/wiki/Simplifying_regular_expressions_using_magic_and_no-magic)). I tried the same command in `evil-mode`, but it complains it doesn't understand the `sno` command, so how can I do the same thing in `evil-mode`?
2014/08/11
[ "https://Stackoverflow.com/questions/25234556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266185/" ]
To my knowledge, `evil` does not (yet?) support the "magic/no magic" regexp options (actually, it only does a smallish subset of `ex` functionality~~, so I don't think `%` will work either~~). As @Ehvince's answer suggests, the standard Emacs way to do the replace is with `query-replace` or `query-replace-regexp`. If you'd like to stick to `evil`, just escape the square brackets with a backslash: ``` :s/\[abt\]//g ``` *NB*: backslash escapes in Emacs often bite people coming from other environments or programming languages; have a look at [the bottom of this manual node on the backslash](http://www.gnu.org/software/emacs/manual/html_node/elisp/Regexp-Special.html#Regexp-Special) for more information.
22,210
What do you call the square brackets used to target a barcode/QR scanner? I thought this would be called "reticle," but when I Google the term, all I see are circles with crosshairs. Is there a more precise term, especially in the context of a digital device/camera, or is reticle the word? ![scanner target](https://i.stack.imgur.com/vYbtD.jpg)
2012/06/07
[ "https://ux.stackexchange.com/questions/22210", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/4695/" ]
**Colloquial: *Target Area,* \*Focus Area,\* or *Focus Frame*** It looks like "[target area](http://www.google.com/imgres?hl=en&biw=1428&bih=933&tbm=isch&tbnid=3bqqeUAwteODEM%3a&imgrefurl=http://www.androidapps-home.com/quickmark-barcode-scanner-android-6963.html&docid=Nbr4x3pvKwmdGM&imgurl=http://ssl.gstatic.com/android/market/tw.com.quickmark/ss-320-1-7&w=320&h=480&ei=7G7XT6L5DOms8AGi_vyNBQ&zoom=1&iact=hc&vpx=181&vpy=175&dur=953&hovh=275&hovw=183&tx=100&ty=130&sig=106342795571774308654&page=1&tbnh=154&tbnw=104&start=0&ndsp=38&ved=1t:429,r:0,s:0,i:75)" is the most straightforward term. "Focus frame" is the best colloquial phrase from photography, given that it is often referred to as an "AF (autofocus) Frame" or "focus frame" in camera manuals and discussions. There is some reference to "focus area," which is also descriptive and easy to understand: 1. <http://qrganize.com/features.php> 2. <http://www.butkus.org/chinon/chinon/cp-9af/cp-9af.htm> 3. <http://forums.dpreview.com/forums/readflat.asp?forum=1020&message=41383138&changemode=1> 4. <http://www.sds.com/mug/9xi_vfdr.html> 5. <http://www.scoop.it/t/fuji-x-pro1/p/1758069851/do-you-read-the-manual-tip-3-focus-frame-to-center-fujifilm-digital-camera-x-pro1-owner-s-manual> 6. <http://www.scoop.it/t/fuji-x-pro1/p/1884969260/do-you-read-the-manual-tip-7-corrected-af-frame-fujifilm-digital-camera-x-pro1-owner-s-manual> 7. <http://www.sds.com/mug/700si-inf3.html> 8. <http://www.sds.com/mug/9xi_vfdr.html> **Technical: *Reticle* or *Crosshairs*** [Reticle](http://en.wikipedia.org/wiki/Reticle) (or "crosshairs") is a term originating with telescopes, microscopes, and oscilloscopes, to name a few. Because scopes are round, "reticle" generally implies a circular view with cross hairs. However, the term is technically accurate when describing focus areas in cameras (credit goes to @mawcsco for finding the reference): <http://www.reticles.com/reticles_kr900.htm>. Here's another interesting reference: <http://www.techniquip.com/manuals/DCG-200MManual_r3.pdf>. **Alternative Colloquial: *Crosshair Box*** Although I believe the above terms to be more generally understandable in reference to cameras, scanners and similar apps, the term "crosshair box" does show up colloquially as a [reference to the "pick box"](http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair%20box&x=0&y=0) in AutoDesk's product AutoCAD, for virtual cameras in gaming environments, and in one found reference to the reticle on a telescope: 1. <http://usa.autodesk.com/adsk/servlet/u/gsearch/results?siteID=123112&catID=123155&id=2088334&qt=crosshair+box&x=0&y=0> 2. <http://www.garagegames.com/community/forums/viewthread/48233> 3. <http://www.astropix.com/HTML/I_ASTROP/TRACKED/MANUAL.HTM> 4. <http://community.bistudio.com/wiki/Camera.sqs> **iOS Term: *Focus Indicator*** Apple uses a similar element called the "[focus indicator](http://developer.apple.com/library/ios/#DOCUMENTATION/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/TakingPicturesAndMovies.html)" in the camera app, however this square moves to indicate where the focus is, rather than form a fixed frame in the viewfinder. **Other Camera Terms** Cameras use "viewfinders," for the entire viewable area, "[bright line frame](http://www.butkus.org/chinon/chinon/intrafocus_35f-ma/body09.jpg)" and "[frame finder](http://www.mir.com.my/rb/photography/companies/nikon/nikkoresources/RF-Nikkor/RF-Accessories/Nikon-RF-Finders/KelSportFrame_3.jpg)" for the area inside the viewfinder.
32,710,883
When I try to debug my app in Android Studio I get a gradle error. I have now idea how I can fix it. Does anyone have any ideas or fixes for me so I can continue debugging my app. I googled it already and people are saying the cause could be that there are duplicate imports in the gradle file but I checked this and there are none. When I rebuilt gradle it is successful but when I debug I get this error. ``` Executing tasks: [:app:assembleDebug] Configuration on demand is an incubating feature. :app:preBuild :app:compileDebugNdk UP-TO-DATE :app:preDebugBuild :app:checkDebugManifest :app:preReleaseBuild :app:prepareComAndroidSupportAppcompatV72220Library UP-TO-DATE :app:prepareComAndroidSupportDesign2220Library UP-TO-DATE :app:prepareComAndroidSupportMediarouterV72200Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72100Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42221Library UP-TO-DATE :app:prepareComBalysvMaterialmenuMaterialMenu154Library UP-TO-DATE :app:prepareComFacebookAndroidFacebookAndroidSdk460Library UP-TO-DATE :app:prepareComGithubJohnkilAndroidRobototextviewRobototextview240Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServices750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAds750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAnalytics750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppinvite750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppstate750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesCast750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesDrive750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesFitness750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGames750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesIdentity750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesLocation750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMaps750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesNearby750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPanorama750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesSafetynet750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWallet750Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWearable750Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:compileDebugJava UP-TO-DATE :app:preDexDebug UP-TO-DATE :app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303) at com.android.dx.command.dexer.Main.run(Main.java:246) at com.android.dx.command.dexer.Main.main(Main.java:215) at com.android.dx.command.Main.main(Main.java:106) FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:dexDebug'. > com.android.ide.common.internal.LoggedErrorException: Failed to run command: /Users/x/Development/Android SDK/build-tools/21.1.2/dx --dex --no-optimize --output /Users/app/app/build/intermediates/dex/debug --input-list=/Users/app/app/build/intermediates/tmp/dex/debug/inputList.txt Error Code: 2 Output: UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:277) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168) at com.android.dx.merge.DexMerger.merge(DexMerger.java:189) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303) at com.android.dx.command.dexer.Main.run(Main.java:246) at com.android.dx.command.dexer.Main.main(Main.java:215) at com.android.dx.command.Main.main(Main.java:106) * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 42.045 secs ``` My build.gradle: ``` apply plugin: 'com.android.application' apply plugin: 'android-apt' def AAVersion = '3.3.2' def JacksonVersion = '2.5.2' apt { arguments { androidManifestFile variant.outputs[0].processResources.manifestFile // androidManifestFile variant.outputs[0].processResources.manifestFile // if you have multiple outputs (when using splits), you may want to have other index than 0 // you should set your package name here if you are using different application IDs resourcePackageName "com.app" // You can set optional annotation processing options here, like these commented options: // logLevel 'INFO' // logFile '/var/log/aa.log' } } android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.app" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/NOTICE' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/spring.handlers' exclude 'META-INF/spring.schemas' exclude 'META-INF/spring.tooling' } } repositories { mavenCentral() mavenLocal() maven { url 'http://repo.spring.io/milestone' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:recyclerview-v7:21.0.0' compile 'com.android.support:design:22.2.0' compile( [group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: "$JacksonVersion"], [group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: "$JacksonVersion"], [group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: "$JacksonVersion"] ) apt "org.androidannotations:androidannotations:$AAVersion" compile "org.androidannotations:androidannotations-api:$AAVersion" compile "org.springframework.android:spring-android-rest-template:2.0.0.M2" compile "com.squareup.okhttp:okhttp:2.4.0" compile "com.squareup.okhttp:okhttp-urlconnection:2.4.0" compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.readystatesoftware.systembartint:systembartint:1.0.3' compile 'com.github.johnkil.android-robototextview:robototextview:2.4.0' compile 'com.balysv.materialmenu:material-menu:1.5.4' compile 'com.j256.ormlite:ormlite-android:4.48' compile 'com.facebook.android:facebook-android-sdk:4.6.0' compile 'com.google.android.gms:play-services:7.5.0' } ```
2015/09/22
[ "https://Stackoverflow.com/questions/32710883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841903/" ]
Try this : ``` $str = '1.8 to 250'; preg_match_all('!\d+!', $str, $matches); print_r($matches); ``` From this post [Extract numbers from a string](https://stackoverflow.com/questions/6278296/extract-numbers-from-a-string)
49,761,972
Assuming I want to ensure that `myKey` in `{ myKey: '' }` only contains the strings `foo`, `bar`, `baz`, I could achieve this in two ways. ``` // with a String Literal Type type MyKeyType = 'foo' | 'bar' | 'baz'; // or with a String Enum enum MyKeyType { FOO = 'foo', BAR = 'bar', BAZ = 'baz' } ``` I wonder where the pros and cons of one over the other are, as both look the same to me (exept from the way I would access the values for e.g. a condition check). The only difference I found in the TS documentation is that Enums are real objects at runtime, what might be desirable in some cases.
2018/04/10
[ "https://Stackoverflow.com/questions/49761972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6191996/" ]
The key thing to understand is that *the values of string enums are opaque*. The intended use case for a string enum is that you don't want other code to know or care what the literal string backing `MyKeyType.FOO` is. This means that you won't be able to, say, pass the *literal string* `"bar"` to a function accepting a `MyKeyType` -- you'll have to write `MyKeyType.BAR` instead.
39,722,669
I have several text files where each line starts with a group code, and each data item is separated by pipe characters. There is a specific group that will sometimes have data, and sometimes have no data, and will therefore only have the group code and pipes. I am trying to remove these groups with no data, while keeping the ones that do have data. For example, two lines in my file would look like: ``` A01|ABC|123|XYZ| A05|123456789|| A05||| A01|DEF|456|UVW| A05|987654321|| A05||| A08|SOMEDATA| ``` I want it to look like ``` A01|ABC|123|XYZ| A05|123456789|| A01|DEF|456|UVW| A05|987654321|| A08|SOMEDATA| ``` I have tried to use findstr, as below: ``` type MYFILE.txt | findstr /v "A05|||" > MYFILE.txt ``` however this is deleting everything from the file, rather than just lines containing A05|||
2016/09/27
[ "https://Stackoverflow.com/questions/39722669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4388475/" ]
Try using another file: ``` FindStr/RV "^A05||" MyFile.txt>AnotherFile.txt ``` Then if needs be **del**ete **Myfile.txt** & **ren**ame **AnotherFile.txt MyFile.txt**
63,211
I am trying to run haproxy in front of tomcat on a Solaris x86 box, but I am getting intermittent failures. At seemingly random intervals, the request just hangs until haproxy times out the connection. I thought maybe it was my app, but I've been able to reproduce it with the tomcat manager app, and hitting tomcat directly there is no problems at all. Hitting it repeatedly with curl will cause the error within 10-15 tries ``` curl -ikL http://admin:admin@<my server>:81/manager/status ``` haproxy is running on port 81, tomcat on port 7000. haproxy returns a 504 gateway timeout to the client, and puts this into the log file: ``` Sep 7 21:39:53 localhost haproxy[16887]: xxx.xxx.xxx.xxx:65168 [07/Sep/2009:21:39:23.005] http_proxy http_proxy/tomcat7000 5/0/0/-1/30014 504 194 - - sHNN 0/0/0/0/0 0/0 "GET /manager/status HTTP/1.1" ``` Tomcat shows nothing, no error in the logs and no indication that the request ever makes it to the tomcat server. The request count is not incremented, the manager app only shows activity on one thread, serving up the manager app. Here are my haproxy and tomcat connector settings, I've been playing with both a good deal trying to chase down the issue, so they may not be ideal, but they definitely don't seem like they should cause this error. server.xml ``` <Connector port="7000" protocol="HTTP/1.1" enableLookups="false" maxKeepAliveRequests="1" connectionLinger="10" /> ``` haproxy config ``` global log loghost local0 chroot /var/haproxy listen http_proxy :81 mode http log global option httplog option httpclose clitimeout 150000 srvtimeout 30000 contimeout 3000 balance roundrobin cookie SERVERID insert server tomcat7000 127.0.0.1:7000 cookie server00 check inter 2000 ```
2009/09/08
[ "https://serverfault.com/questions/63211", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
I suspect that your Tomcat is pausing for a full garbage collection, which is why it is not responding or logging anything. See [here](http://www.infoq.com/news/2010/04/cliff_click_gc_pauses/) for more information on this problem.
64,873,395
I have data like this ``` Name valuta price Type Type2 A USD 10 Acc 1 B USD 30 Acc 2 C SGD 20 Acc 3 D SGD 05 Acc 4 A SGD 35 Acc 1 C SGD 05 Acc 3 B USD 50 Rej 2 ``` Grouping based on Name, valuta and type. (type2 always have a unique value based on name) and sum the price when have the same group condition, the last step is to order based the highest price followed by same group condition. And after process (Group & Order), the output should be like this: ``` Name valuta price Type Type2 B USD 50 Rej 2 B USD 30 Acc 2 A SGD 35 Acc 1 A USD 10 Acc 1 C SGD 25 Acc 3 D SGD 05 Acc 4 ``` I tried use cte because pipeline process design seems clear to me but the result is wrong. ``` WITH Cte_Process1 AS ( SELECT Name, valuta, SUM(price) AS price, Type, Type2 FROM table1 GROUP BY Name, valuta, price, Type, Type2 ) SELECT * FROM Cte_Process1 ORDER BY price ```
2020/11/17
[ "https://Stackoverflow.com/questions/64873395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10766911/" ]
You can do it with `MAX()` window function in the `ORDER BY` clause: ``` select Name, valuta, sum(price) price, type, type2 from tablename group by Name, valuta, type, type2 order by max(sum(price)) over (partition by Name) desc, Name, sum(price) desc ``` See the [demo](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=d5f1a11b024e3ad4af706cda9f84a8cb). Results: ``` > Name | valuta | price | type | type2 > :--- | :----- | ----: | :--- | ----: > B | USD | 50 | Rej | 2 > B | USD | 30 | Acc | 2 > A | SGD | 35 | Acc | 1 > A | USD | 10 | Acc | 1 > C | SGD | 25 | Acc | 3 > D | SGD | 5 | Acc | 4 ```
8,161
I have converted an edge loop to a curve. The edge loop itself was fairly low poly. I want the curve to look smooth so I tried to increase the resolution of it but it looks exactly the same. ![enter image description here](https://i.stack.imgur.com/Nvun0.png) Is there a way I can get the curve to be a smooth interpolation of the edge loop? **[blende file](http://www.pasteall.org/blend/28013)**
2014/03/29
[ "https://blender.stackexchange.com/questions/8161", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/1476/" ]
This is because the converted curve is a *Poly* spline. To convert it to a smoothly interpolated curve: 1. Convert it to a Bezier or NURBS spline in *3D view > Tool shelf > Curve Tools > Set Spline Type*: ![enter image description here](https://i.stack.imgur.com/nVW7N.png) 2. Then convert all the Control Vertices to *Auto* (or something besides *vector*) by pressing `A`*> Select all* `V`*> Automatic*. Now you can adjust the *Resolution* as desired to adjust the "smoothness": ![enter image description here](https://i.stack.imgur.com/0rJ43.png)
18,653,163
I have a project PROJECT\_A which contains mdf file database. In the solution of this project I added one new project - PROJECT\_B. My question is:Can I use .mdf file from PROJECT\_A in PROJECT\_B?
2013/09/06
[ "https://Stackoverflow.com/questions/18653163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281755/" ]
You can add .mdf file as a [Link Reference](http://support.microsoft.com/kb/306234) to project B Right click project B and then properties > Add Reference > Existing Item > Select the .mdf file and in the add button select `Add As Link` option.
53,924
Preface this by saying I will be launching this script whether it be applescript or bash script with Alfred.app. Sorry to be so blunt and unknowledgable but I need to run a couple lines of bash in an applescript. I think a simple bash script is capable but I do not know for sure. Here are the details (note that the commands should probably be different so if you have suggestions, please feel free to state them as they are probably correct): I want the script to 1. `rm ~/Library/Vidalia/vidalia.conf'` 2. `unzip ~/Library/Vidalia/vidalia.conf.zip'` 3. launch Vidalia.app Step below I do not believe is possible since the Vidalia.app is not scriptable and I don't want the applescript/bash script to be running until Vidalia quits... but if it's possible to implement without the script needing to stay open: 4) On quit of Vidalia.app `rm ~/Library/Vidalia/vidalia.conf` Is this possible. I can use bash or applescript whatever is easiest for you guy's & gals to help me with. If I could get the first three steps to run I would be plenty happy! Thanks for your time and sorry for my lack of knowledge. Any tips or pointers are welcome. Heck, I don't even know if those are the "proper" shell commands to use, they did the job but if they are "sound" I do not know. Thank you for your time and patience. **UPDATE - Question: How to move unzipped file into different directory?** Okay I have one last question. How would I do this same sort of action, but I wanted to keep `vidalia.conf.zip` in another directory? Say, for example, an external volume named `tor` - I moved into the mounted volume named `tor` with `pushd`, but when I go to extract the file with what I think should work `-d` I get the error that I `cannot create extraction directory` Which is good because I don't want to replace the directory, just move what get's unzipped into the pre-existing directory. Yeah, I will probably have to remove the file already there depending on what I am doing so what I have looks like this... ``` pushd ~/Library/Vidalia/ rm vidalia.conf popd pushd /Volumes/tor unzip vidalia.conf.zip -d ~/Library/Vidalia/ popd ``` I haven't quite tried this too much once I ran into the error with plain old `-d`. As I was typing this I realized that I had to be navigating directories more with `pushd` and then out with `popd`. Originally I just had lines 4 and 5 but added the top 3 to remove the `.conf` that currently is there ... if ... it is there... Which bring me to one more question… Is it harmless to tell bash to remove a file that doesn't exist? I would have no idea where to even start with `if then` statements. Lastly, can anyone recommend a good beginners intro to Bash book? I'd love to actually learn this stuff instead of just having to google and then turn around and bug you all. Thank you again for your help. You solved my earlier problem perfectly, I even learned a lot from the simple example (I think.) Cheers!
2012/06/17
[ "https://apple.stackexchange.com/questions/53924", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/24084/" ]
As @laaph mentioned, if you just want to run bash commands, use a bash script. There are, however, a few issues with your commands. Your script has to look like: ``` #!/bin/sh pushd ~/Library/Vidalia rm vidalia.conf unzip vidalia.conf.zip popd open /Applications/Vidalia.app ``` If you didn't change to the correct directory, `unzip` would unzip the file into your home directory, or wherever you launched your script from. There are ways to look for when an app quits, but in your case this seems useless, you're removing the `.conf` whenever you launch the script anyway. But if you really want that, you could simply do: ``` #!/bin/sh pushd ~/Library/Vidalia rm vidalia.conf unzip vidalia.conf.zip popd open -W /Applications/Vidalia.app pushd ~/Library/Vidalia rm vidalia.conf popd ``` (This would make the script wait until you close the app, and then it'd delete the configuration file. Again though, this is useless and redundant if you'll be only launching the app with the script.) Also, you could try a simpler solution: I assume that what you want is just to have the same vidalia.conf whenever you start the program. If that's the case, try just making the `.conf` read-only.
703,542
I've been trying to figure out this integral via use of residues: $$\int\_{-\infty}^{\infty} \displaystyle \frac{\cos{5x}}{x^4+1}dx$$ The usual semicircle contour wont work for this guy as the integrated is unbounded. My idea came from a book I was reading on contour integration, where we let $$f(z) = \displaystyle\frac{e^{(-5iz)}}{2(z^4+1)}+\displaystyle\frac{e^{(5iz)}}{2(z^4+1)}$$ And do the integral in the complex play as follows: $\gamma\_{1}= \text{The contour taken to be the top half of the circle in the counter clockwise direction}$ This contour uses the second term in $f(z)$ $\gamma\_{2}= \text{The contour taken from $-R$ to $R$ on the real axis}$ $\gamma\_{3}= \text{The contour taken to be the bottom half of the circle in the clockwise direction}$ This uses the first term in $f(z)$. In the end, the contours $\gamma\_{1}$ and $\gamma\_{3}$ are bounded and will tend to $0$ as $R$ goes to infinity, so that we're left with the two integrals that we want. My issue now is that when computing residues..everything seems to be cancelling out and I'm getting $0$. Should I take different contour? I'm really not sure what I did wrong.
2014/03/07
[ "https://math.stackexchange.com/questions/703542", "https://math.stackexchange.com", "https://math.stackexchange.com/users/17243/" ]
I've given the skeleton of my work below. Fill in any missing pieces and check your answer against mine. Using $\gamma=[-R,R]\cup Re^{i[0,\pi]}$ and the simple poles at $\frac{1+i}{\sqrt2}$ and $\frac{-1+i}{\sqrt2}$ inside $\gamma$ $$ \begin{align} \int\_{-\infty}^\infty\frac{\cos(5x)}{x^4+1}\mathrm{d}x &=\mathrm{Re}\left(\int\_\gamma\frac{e^{i5z}}{z^4+1}\mathrm{d}z\right)\\ &=\mathrm{Re}\left(2\pi i\left(\left[\frac{e^{i5z}}{4z^3}\right]\_{z=\frac{1+i}{\sqrt2}} +\left[\frac{e^{i5z}}{4z^3}\right]\_{z=\frac{-1+i}{\sqrt2}}\right)\right)\\ &=\mathrm{Re}\left(\frac{\pi}{2i}e^{-5/\sqrt2}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2} -\frac{1-i}{\sqrt2}e^{-i5/\sqrt2} \right)\right)\\ &=\pi e^{-5/\sqrt2}\mathrm{Im}\left(\frac{1+i}{\sqrt2}e^{i5/\sqrt2}\right)\\ &=\pi e^{-5/\sqrt2}\mathrm{Im}\left(e^{i(5/\sqrt2+\pi/4)}\right)\\ &=\pi e^{-5/\sqrt2}\sin\left(\frac5{\sqrt2}+\frac\pi4\right) \end{align} $$ Mathematica 8 agrees numerically, but its closed form involves complex functions and looks nothing like what I have above.
293,983
I am looking for ways to make a mobile power supply for 10 units of MG996R servo motors, each of which can draw up to around 800 mA to 1 A and operate between 4.8 V to 7.2 V. I have 12 Eneloop AA batteries (BK-3MCCA8BA), and from [Panasonic Eneloop BK-3MCC (4th gen) - where I can find maximum discharge current?](https://electronics.stackexchange.com/questions/123709/panasonic-eneloop-bk-3mcc-4th-gen-where-i-can-find-maximum-discharge-current), I gathered that each of my Eneloop AA battery can discharge up to 6 A, which means that I should be able to power up to 6 MG996R's with a 4 or 6 AA battery pack. This appears to agree with my setup where I am trying to control the 10 servo motors using the Adafruit 16-channel 12-bit PWM driver with a 1000 uF capacitor. Once I begin to control over 5 servo motors, I get jitters, which I assume is due to the insufficient current. However, I also read at [How do I determine the maximum amp output of a battery pack?](https://electronics.stackexchange.com/questions/61939/how-do-i-determine-the-maximum-amp-output-of-a-battery-pack) that I can model the batteries as a Thevenin-equivalent circuit, where the current is V\_Th/R\_Th. If I had 4 1.2 V AA batteries in series and assumed an individual internal resistance of 100 mOhms, I should be getting 4.8 V/ 0.4 ohms= 12 A. This current should be sufficient for 10 of my servo motors? However, this is not the case. What am I missing here? Also, could I put 2 packs of 6 AA battery holders in parallel to provide sufficient current?
2017/03/22
[ "https://electronics.stackexchange.com/questions/293983", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/142940/" ]
This one is really clear, surprisingly clear in fact ... downright enlightened. That additional wording that MicroChip put in ... "true ..." makes it a very safe bet that you can perform whatever routing function through that pin you wish to ease your layout. The only caveat is not to put a sensitive net through the pin, since it will add parasitics (a handful of pF) if it matters. Alternate wordings would be "DNC" for do not connect, which is a command, not a suggestion. or "Reserved" where you must fear for your life if you ever connect that pin incorrectly. I've been reading data sheets since the '70s and they have not been better or worse across time. This one is very clear. To convince yourself, put your meter on the highest resistance range to each pin in turn. Checking that it declares over-range. Make sure that you perform each measurement with both polarities of the meter. Most meters use a one-polarity source, often ramping in a triangle, so they read differently each way and a diode will fool you.
8,700,063
This is an interview question: Design a data structure to perform the following operation efficiently: `boolean isPrefix(String s1, String s2)`. I guess we can create a `multimap`, which maps prefixes to their strings. For instance, ``` strings: "aa", "ab", "abc", "ba", "ca" multimap: "a" -> ["aa", "ab", "abc"] "aa" -> ["aa"] "ab" -> ["ab", "abc"] "abc" -> ["abc"] "ba" -> ["ba"] "ca" -> ["ca"] ``` Which data structure would you propose ?
2012/01/02
[ "https://Stackoverflow.com/questions/8700063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/521070/" ]
The trie data structure would seem like an obvious answer, but the problem as stated doesn't require an advanced data structure. A simple string comparison will suffice and would be very fast. Ultimately, if you want to validate that one string is a prefix of another, you will have to compare every character at corresponding positions. No data structure eliminates the need for the character-by-character comparison. That being said, if you're *searching* for the prefix in a large body of text, there are other techniques such as [Rabin-Karp probablistic string matching](http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm).
58,710,504
Opencart generates its sitemap on the fly and this is a problem in a big catalogs over 10.000 products. So I have modified the function to generate a static sitemap in an XML file. When I access to my <http://localhost/index.php?route=extension/feed/google_sitemap> I generate a sitemap-google.xml file without problems and with a unlimited execution time. I tried to add it in a cron in the development server each 4 hours ``` 0 0,4,8,12,16,20 /usr/bin/php /path/to/index.php?route=extension/feed/google_sitemap ``` But I'm receiving a "command not found". Can I execute on cli the "?params/etc"?
2019/11/05
[ "https://Stackoverflow.com/questions/58710504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9417576/" ]
Reflection is based on the assembly’s *metadata*. What you seem to want would need to involve some kind of *source code* inspection to figure out all the concrete generic types created at runtime. Possible? Yes, the compiler does it, but not with reflection.
69,031,724
This is the code I usually write: ``` alignas(16) __m128 myBuffer[8]; ``` But maybe (since the object-array is 128\*8 bit = 128 byte) I should write: ``` alignas(128) __m128 myBuffer[8]; ``` Or, "since the first 16 byte are aligned" in the first example, the rest will be automatically aligned in memory?
2021/09/02
[ "https://Stackoverflow.com/questions/69031724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365251/" ]
128-bit SIMD data types must be aligned on 16 bytes. The compiler already knows that, so it's not needed to align `__m128` manually. See for example, [MSVC docs on `__m128`](https://learn.microsoft.com/en-us/cpp/cpp/m128?view=msvc-160): > > Variables of type `__m128` are automatically aligned on 16-byte boundaries. > > > Also, arrays are contiguous. Each array element is naturally aligned the same as the first one. There's no need to multiply the alignment for arrays. So you need not bother with `alignas` at all: ``` __m128 myBuffer[8]; ``` This will just work.
8,644,259
I need to know, in android sdk 4.0 the following line says that 'the file is not found'. But the webview loads perfectly in sdk 2.2 and 2.3 etc. ``` mWebView.loadUrl("file:///android_asset/currentLocation.html?width_="+grosswt+"&height_="+grossht); ``` Is there any other way to send query string with url in android webview?
2011/12/27
[ "https://Stackoverflow.com/questions/8644259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/761132/" ]
Yes, this is a known bug, even in ICS. Google don't feel like fixing it. <http://code.google.com/p/android/issues/detail?id=17535>
17,895,602
I'm using asp.net web service .asmx to transport json data. I have following code which seems not to be working. ``` $.ajax({ type: "POST", url: "../../App_Code/jsonWebService/getValue", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (output) { alert(output); $(config.captchaQuestion).html(output[0] + " + " + output[1] + " ="); $(config.captchaHidden).val(output[2]); } }); ``` And my code inside jsonWebService.cs of asmx file is: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Script.Services; using System.Web.Script.Serialization; /// <summary> /// Summary description for jsonWebService // </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class jsonWebService : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Array getValue() { Random getRandom = new Random(); int rand1 = getRandom.Next(0, 9); int rand2 = getRandom.Next(0, 9); int sum = rand1 + rand2; int[] jsonObject = new int[3] { rand1, rand2, sum }; return jsonObject; } } ``` And I'm getting Forbidden error 403. Thanks in advance.
2013/07/27
[ "https://Stackoverflow.com/questions/17895602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1834764/" ]
you need to convert your text into array first, because what your doing right now includes a `,` in your regexp pattern ``` $stop_ips_masks = file_get_contents('array.txt'); $stop_ips_masks = explode("," $stop_ips_masks); ``` You might also need to do a trim operation and remove the newlines as well. it would be easier if you stick to one record separator. like comma or newline. not both. If you remove the `,` from your text file then you can do ``` $stop_ips_masks = file('array.txt'); ```
18,889,688
I'm trying to test a `HttpServletRequest` and for that I have used [Mockito](http://code.google.com/p/mockito/) as follow: ``` HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); ``` now before putting the http-request in `assert` methods I just want to build a simple http header as below without starting a real server: ``` x-real-ip:127.0.0.1 host:example.com x-forwarded-for:127.0.0.1 accept-language:en-US,en;q=0.8 cookie:JSESSIONID=<session_ID> ``` can some one help how can I build such a test header? thanks.
2013/09/19
[ "https://Stackoverflow.com/questions/18889688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277740/" ]
You can just stub the calls to request.getHeaders etc. or if you can add a dependency, [Spring-test](http://mvnrepository.com/artifact/org.springframework/spring-test/3.2.0.RELEASE) has a `MockHttpServletRequest` that you could use (see [here](http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html#mock-objects-servlet)) ``` MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("x-real-ip","127.0.0.1"); ``` Or you could build your own implementation which allows you to set headers.
10,883,786
I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others? Background: I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes.
2012/06/04
[ "https://Stackoverflow.com/questions/10883786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803923/" ]
`document.ready()` callbacks are called in the order they were registered. If you register your testing callback first, it will be called first. Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other `document.ready()` callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until `document.ready()`. Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to `document.ready()` that when passed and set to `true` indicated to call that function first or you could add a new method `document.readyFirst()` that would call your function first. This would involve minor changes to the `document.ready()` processing code in jQuery.
46,619,261
I want to send a message to websocket from `java` code. This is configuration class for `websockets` ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { private WebSocketHandler handler; public WebSocketConfig(WebSocketHandler handler) { this.handler = handler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) { webSocketHandlerRegistry.addHandler(this.handler, "/ws"); } } ``` This is `websocket` handler ``` @Component public class WebSocketHandler extends TextWebSocketHandler { private static final Logger LOGGER = JavaLogUtils.getLogger(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { LOGGER.info(" Server >>>> {}", message); session.sendMessage(message); } } ``` When I send message from `html` page via `javascript` like this ``` $(function(){ var connection = new WebSocket('ws://localhost:8080/ws'); connection.onopen = function () { console.log('Connected...'); }; connection.onmessage = function(event){ console.log('>>>>> ' + event.data); var json = JSON.parse(event.data); $("#output").append("<span><strong>" + json.user + "</strong>: <em>" + json.message +"</em></span><br/>"); }; connection.onclose = function(event){ $("#output").append("<p class=\"text-uppercase\"><strong>CONNECTION: CLOSED</strong></p>"); }; $("#send").click(function(){ var message = {} message["user"] = $("#user").val(); message["message"] = $("#message").val(); connection.send(JSON.stringify(message)); }); }); ``` It works fine. But when I try to send the message from `java client` it fails ``` @SpringBootApplication @ComponentScan("com.lapots.breed.platform.cloud.boot") @EnableJpaRepositories("com.lapots.breed.platform.cloud.boot.repository") @EntityScan("com.lapots.breed.platform.cloud.boot.domain") @EnableAspectJAutoProxy @EnableJms public class JavaCloudSampleApplication { public static void main(String[] args) { SpringApplication.run(JavaCloudSampleApplication.class, args); } @Bean public CommandLineRunner welcomeSocketMessage(WebSocketHandler handler) throws URISyntaxException { return args -> { StandardWebSocketClient client = new StandardWebSocketClient(); ListenableFuture<WebSocketSession> future = client.doHandshake(handler, new WebSocketHttpHeaders(), new URI("ws://localhost:8080/ws")); WebSocketSession session = future.get(); WebSocketMessage<String> message = new TextMessage("Hello from Spring"); session.sendMessage(message); }; } } ``` and I get this error ``` java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.20.jar:2.20] at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:272) [surefire-junit4-2.20.jar:2.20] at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:236) [surefire-junit4-2.20.jar:2.20] at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.20.jar:2.20] at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:386) [surefire-booter-2.20.jar:2.20] at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:323) [surefire-booter-2.20.jar:2.20] at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:143) [surefire-booter-2.20.jar:2.20] Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:735) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:716) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:703) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:304) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120) ~[spring-boot-test-1.5.6.RELEASE.jar:1.5.6.RELEASE] at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.10.RELEASE.jar:4.3.10.RELEASE] ... 26 common frames omitted Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:1.8.0_121] at java.util.concurrent.FutureTask.get(FutureTask.java:192) ~[na:1.8.0_121] at com.lapots.breed.platform.cloud.boot.JavaCloudSampleApplication.lambda$welcomeSocketMessage$4(JavaCloudSampleApplication.java:76) ~[classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:732) ~[spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE] ... 32 common frames omitted Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:395) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16] at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:150) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE] at org.springframework.web.socket.client.standard.StandardWebSocketClient$1.call(StandardWebSocketClient.java:147) ~[spring-websocket-4.3.10.RELEASE.jar:4.3.10.RELEASE] at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_121] at java.lang.Thread.run(Thread.java:745) ~[na:1.8.0_121] Caused by: java.util.concurrent.ExecutionException: java.io.IOException: The remote computer refused the network connection. at sun.nio.ch.PendingFuture.get(PendingFuture.java:202) ~[na:1.8.0_121] at org.apache.tomcat.websocket.WsWebSocketContainer.connectToServer(WsWebSocketContainer.java:336) ~[tomcat-embed-websocket-8.5.16.jar:8.5.16] ... 4 common frames omitted Caused by: java.io.IOException: The remote computer refused the network connection. at sun.nio.ch.Iocp.translateErrorToIOException(Iocp.java:309) ~[na:1.8.0_121] at sun.nio.ch.Iocp.access$700(Iocp.java:46) ~[na:1.8.0_121] at sun.nio.ch.Iocp$EventHandlerTask.run(Iocp.java:399) ~[na:1.8.0_121] ... 1 common frames omitted [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 8.071 s <<< FAILURE! - in com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests [ERROR] contextLoads(com.lapots.breed.platform.cloud.boot.app.JavaCloudSampleApplicationTests) Time elapsed: 0 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: java.lang.IllegalStateException: Failed to execute CommandLineRunner Caused by: java.util.concurrent.ExecutionException: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed Caused by: javax.websocket.DeploymentException: The HTTP request to initiate the WebSocket connection failed Caused by: java.util.concurrent.ExecutionException: java.io.IOException: The remote computer refused the network connection. Caused by: java.io.IOException: The remote computer refused the network connection. ```
2017/10/07
[ "https://Stackoverflow.com/questions/46619261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432980/" ]
A bit late but if you're using API 21+, you can set the secondary progress tint to be transparent: ``` android:secondaryProgressTint="@android:color/transparent" ```
23,239
This question may sound rhetorical or not well posed, but I wonder what the economic viability or sustainability of certain Emirates routes is. Among its 164 destinations, Emirates is currently serving a whole host of non-major airports (airports which, according to [this list](https://en.wikipedia.org/wiki/List_of_the_world%27s_busiest_airports_by_passenger_traffic#2015_statistics), are not among the 30 busiest in the World). Among them are: * Newcastle upon Tyne (NCL) * Prague (PRG) * Bologna (BLQ) * Harare (HRE) and so forth. **My question:** on the majority of these routes, a Boeing 777 is deployed. But how economically viable could it be to fly such a high-capacity plane to destinations where the target market is not so wealthy or not big enough? In some of these instances, Emirates is the sole airline operating the Boeing 777. Also, I speculate that other airlines would probably use another, smaller aircraft to some of these destinations. I am sure Emirates does its market researches with adequate meticulousness before opening any new route, but I am still doubtful - couldn't the people living around Bologna take a train to Milan to get to Dubai, for instance, [given their close proximity](https://www.google.it/maps/dir/Bologna/Milan,+MI/@44.0344603,10.50582,6z/data=!4m14!4m13!1m5!1m1!1s0x477fd498e951c40b:0xa2e17c015ba49441!2m2!1d11.3426163!2d44.494887!1m5!1m1!1s0x4786c1493f1275e7:0x3cffcd13c6740e8d!2m2!1d9.1859243!2d45.4654219!3e3)?
2015/11/28
[ "https://aviation.stackexchange.com/questions/23239", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/11885/" ]
There are many reasons an airline may fly to a given destination and the economics of air travel are complex to say the least. I would like to fist address your question > > couldn't the people living around Bologna take a train to Milan to get > to Dubai > > > Sure they could but airlines don't only service locations because of the people that live there they may service them for the very people that don't. I fly both commercially and as a GA pilot to explore new places. I generally fly out of the Philadelphia area which is one of the busiest in the US. From there I head to plenty of tiny airstrips all over the place, none of these airstrips are in towns that are as economically prosperous or busy as Philadelphia but they see my travel because I wish to explore the area. The same goes for foreign airports, simply because a country is less economically prosperous or "busy" than another does not mean it has less to offer culturally and in fact may be a hot bed for tourism. I have personally been to both Prague and Bologna and they are great cities both with large tourist markets. I can see it being very economical to fly a wide body airliner there full of tourists and maybe only a few locals. While layovers may attract the lower budget fliers there are plenty of people who prefer a direct flight for both the convenience and time savings. You may be able to find more [stats here](https://www.iata.org/publications/economics/Pages/index.aspx).
42,309,571
I've got this fragment of automatically-generated HTML: ``` <label><input type="radio" name="question24_answer" value="A">A)&nbsp; H<sub>0</sub>&#58; p = 0.0016<br/>H<sub>1</sub>&#58; p &lt; 0.0016</label> ``` This produces the following: [![enter image description here](https://i.stack.imgur.com/bSbPx.png)](https://i.stack.imgur.com/bSbPx.png) I'd like the two lines of the label to align vertically so they look good: [![enter image description here](https://i.stack.imgur.com/uRnV8.png)](https://i.stack.imgur.com/uRnV8.png) If necessary, the `A)` can be omitted, though I'd prefer not to: [![enter image description here](https://i.stack.imgur.com/uAOQy.png)](https://i.stack.imgur.com/uAOQy.png)
2017/02/18
[ "https://Stackoverflow.com/questions/42309571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3063736/" ]
> > Any solution needs to be something that can be done automatically. > > > I believe that would rule out a pure HTML solution to which is the only tag your question has. So at the risk of ignoring the fact there's no CSS or JavaScript tag, I'll suggest JavaScript right off and a little bit of CSS. 1. `.querySelectorAll()` collects every `<br/>` that's a child of a `<label>` into a NodeList 2. `Array.prototype.map.call()`executes a function on each item of the NodeList and return a new array 3. `insertAdjacentHTML()` inserts a `<span>` after every `<br>` in the NodeList 4. This `<span>`'s width is 6.4ch; ch is a unit of measure equal to the width of a zero. 5. Use a monospaced font and make sure that `<input>` inherits font. These steps help normalize variances that fonts may cause. 6. To make it perfect, use a combination of `vertical-align` and `line-height` so the radio button is aligned properly. **SNIPPET** ```js var br = document.querySelectorAll('label br'); Array.prototype.map.call(br, function(obj) { return obj.insertAdjacentHTML('afterend', "<span class='ch'><span>") }); ``` ```css body { font: 400 16px/1.5 Consolas; } input { vertical-align: -10%; line-height: 1; font: inherit; } .ch { display:inline-block; width: 6.4ch; } ``` ```html <label><input type="radio" name="question24_answer" value="A">A)&nbsp; H<sub>0</sub>&#58; p = 0.0016<br/>H<sub>1</sub>&#58; p &lt; 0.0016</label> <br/> <label><input type="radio" name="question24_answer" value="B">B)&nbsp; H<sub>26</sub>&#58; p = 0.04096<br/>CH<sub>2</sub>&#58; p &lt; 0.096</label> <br/> <label><input type="radio" name="question24_answer" value="C">C)&nbsp; H<sub>89</sub>&#58; p = 0.00248966652<br/>H<sub>1</sub>&#58; p &lt; 0.0016</label> <br/> <label><input type="radio" name="question24_answer" value="D">D)&nbsp; H<sub>0</sub>&#58; p = 0.1<br/>H<sub>652</sub>&#58; p &lt; 0.0016</label> ```
65,027,547
I'm using using this data to fill a FlatList, each item contains a LinearGradient ``` const DATA = [ { id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba', title: 'First Item', firstColor: "#f472a7", secondColor: "#d84351" }, { id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63', title: 'Second Item', firstColor: "#50be71", secondColor: "#50be71" }, { id: '58694a0f-3da1-471f-bd96-145571e29d72', title: 'Third Item', firstColor: "#e2bd4f", secondColor: "#e49074" } ]; ``` I added two properties called "firstColor" and "secondColor", to fill the LinearGradient colors, but I'm having some issues doing that. I'm receiving this error: ``` TypeError: undefined is not an object (evaluating '_ref3.secondColor') ``` Code: ``` const Item = ({ title }, { firstColor }, { secondColor }) => ( <LinearGradient colors={[{firstColor}, {secondColor} ]} style={styles.item} > <Text style={styles.title}>{title}</Text> </LinearGradient> ); const renderItem = ({ item }) => ( <Item title={item.title} /> ); ... <SafeAreaView style={styles.container}> <FlatList data={DATA} renderItem={renderItem} keyExtractor={item => item.id} /> </SafeAreaView> ```
2020/11/26
[ "https://Stackoverflow.com/questions/65027547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6596416/" ]
Since Python 3.7, keys in dict are ordered. ------------------------------------------- You can use enumerate in order to keep track of the position of the element in the dict while iterating over it. Then, you use the `i` as an index on each row of the 2d list, convert each value to int and do a sum of the result. ```py List2d = [['1', '55', '32', '667' ], ['43', '76', '55', '100'], ['23', '70', '15', '300']] dictionary = {'New York':0, "London": 0, "Tokyo": 0, "Toronto": 0 } for i, city in enumerate(dictionary.keys()): dictionary[city] = sum(int(row[i]) for row in List2d) print(dictionary) # {'New York': 67, 'London': 201, 'Tokyo': 102, 'Toronto': 1067} ```
65,462,499
I am trying to use grep with the `pwd` command. So, if i enter `pwd`, it shows me something like: ``` /home/hrq/my-project/ ``` But, for purposes of a script i am making, i need to use it with grep, so it only prints what is after `hrq/`, so i need to hide my home folder always (the `/home/hrq/`) excerpt, and show only what is onwards (like, in this case, only `my-project`). Is it possible? I tried something like `pwd | grep -ov 'home'`, since i saw that the "-v" flag would be equivalent to the NOT operator, and combine it with the "-o" only matching flag. But it didn't work.
2020/12/27
[ "https://Stackoverflow.com/questions/65462499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10113447/" ]
Given: ``` $ pwd /home/foo/tmp $ echo "$PWD" /home/foo/tmp ``` Depending on what it is you really want to do, either of these is probably what you really should be using rather than trying to use grep: ``` $ basename "$PWD" tmp $ echo "${PWD#/home/foo/}" tmp ```
1,842,608
I'm using Python to write a regular expression for replacing parts of the string with a XML node. The source string looks like: ``` Hello REPLACE(str1) this is to replace REPLACE(str2) this is to replace ``` And the result string should be like: ``` Hello <replace name="str1"> this is to replace </replace> <replace name="str2"> this is to replace </replace> ``` Can anyone help me?
2009/12/03
[ "https://Stackoverflow.com/questions/1842608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150324/" ]
What makes your problem a little bit tricky is that you want to match inside of a multiline string. You need to use the `re.MULTILINE` flag to make that work. Then, you need to match some groups inside your source string, and use those groups in the final output. Here is code that works to solve your problem: ``` import re s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$" pat = re.compile(s_pat, re.MULTILINE) s_input = """\ Hello REPLACE(str1) this is to replace REPLACE(str2) this is to replace""" def mksub(m): return '<replace name="%s">%s</replace>' % m.groups() s_output = re.sub(pat, mksub, s_input) ``` The only tricky part is the regular expression pattern. Let's look at it in detail. `^` matches the start of a string. With `re.MULTILINE`, this matches the start of a line within a multiline string; in other words, it matches right after a newline in the string. `\s*` matches optional whitespace. `REPLACE` matches the literal string "REPLACE". `\(` matches the literal string "(". `(` begins a "match group". `[^)]` means "match any character but a ")". `+` means "match one or more of the preceding pattern. `)` closes a "match group". `\)` matches the literal string ")" `(.*)` is another match group containing ".\*". `$` matches the end of a string. With `re.MULTILINE`, this matches the end of a line within a multiline string; in other words, it matches a newline character in the string. `.` matches any character, and `*` means to match zero or more of the preceding pattern. Thus `.*` matches anything, up to the end of the line. So, our pattern has two "match groups". When you run `re.sub()` it will make a "match object" which will be passed to `mksub()`. The match object has a method, `.groups()`, that returns the matched substrings as a tuple, and that gets substituted in to make the replacement text. EDIT: You actually don't need to use a replacement function. You can put the special string `\1` inside the replacement text, and it will be replaced by the contents of match group 1. (Match groups count from 1; the special match group 0 corresponds the the entire string matched by the pattern.) The only tricky part of the `\1` string is that `\` is special in strings. In a normal string, to get a `\`, you need to put two backslashes in a row, like so: `"\\1"` But you can use a Python "raw string" to conveniently write the replacement pattern. Doing so you get this: import re ``` s_pat = "^\s*REPLACE\(([^)]+)\)(.*)$" pat = re.compile(s_pat, re.MULTILINE) s_repl = r'<replace name="\1">\2</replace>' s_input = """\ Hello REPLACE(str1) this is to replace REPLACE(str2) this is to replace""" s_output = re.sub(pat, s_repl, s_input) ```
117,371
I'm an intern in an industrial company in Brazil and it happens that I'm using excel a lot. I just started playing with VBA couple of days ago, and I'm amused of how many things it can do for me! I don't have a strong programming background, so I'm learning by doing. The code is working fine and it takes less than 15 seconds from start to finish. I'm not that concerned with the time, but if it could be improved that'd be great. My main goal is to keep the code simple and efficient. I'll be leaving the company in the next months and I'd like it to be easy to maintain and use. What I'm asking is a better way to write readable code, with performance as a secondary concern. My code delete 4 sheets of content in my current workbook, and then copies the updated data from 4 other closed workbooks. Then it closes everything. The data is about the daily production and their names are in Portuguese, sorry about that. ``` Sub CopiarBase() ' ' Atalho do teclado: Ctrl+q ' ' Variables Dim MyCurrentWB As Workbook Dim BMalharia As Worksheet Dim BBeneficiamento As Worksheet Dim BEmbalagem As Worksheet Dim BDikla As Worksheet Set MyCurrentWB = ThisWorkbook Set BMalharia = MyCurrentWB.Worksheets("B-Malharia") Set BBeneficiamento = MyCurrentWB.Worksheets("B-Beneficiamento") Set BEmbalagem = MyCurrentWB.Worksheets("B-Embalagem") Set BDikla = MyCurrentWB.Worksheets("B-Dikla") 'Clean all the cells - Workbook 1 Dim Malharia_rng As Range Set Malharia_rng = BMalharia.Range("A2:CN" & BMalharia.Cells(Rows.Count, 1).End(xlUp).Row) Malharia_rng.ClearContents Dim Ben_rng As Range Set Ben_rng = BBeneficiamento.Range("A2:CY" & BBeneficiamento.Cells(Rows.Count, 1).End(xlUp).Row) Ben_rng.ClearContents Dim Emb_rng As Range Set Emb_rng = BEmbalagem.Range("A2:CT" & BEmbalagem.Cells(Rows.Count, 1).End(xlUp).Row) Emb_rng.ClearContents Dim Dikla_rng As Range Set Dikla_rng = BDikla.Range("A2:AV" & BDikla.Cells(Rows.Count, 1).End(xlUp).Row) Dikla_rng.ClearContents 'Copy from Malharia Workbook Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Malharia Base.xls" LastRowMB = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Cells(Rows.Count, 1).End(xlUp).Row Dim Malha_base As Range Set Malha_base = Workbooks("Malharia Base.xls").Worksheets("Malharia Base").Range("A2:CN" & LastRowMB) MyCurrentWB.Worksheets("B-Malharia").Range("A2:CN" & LastRowMB).Value = Malha_base.Value Workbooks("Malharia Base.xls").Close 'Copy from Beneficiamento Workbook Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Beneficiamento Base.xls" LastRowBB = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Cells(Rows.Count, 1).End(xlUp).Row Dim Ben_base As Range Set Ben_base = Workbooks("Beneficiamento Base.xls").Worksheets("Beneficiamento Base").Range("A2:CY" & LastRowBB) MyCurrentWB.Worksheets("B-Beneficiamento").Range("A2:CY" & LastRowBB).Value = Ben_base.Value Workbooks("Beneficiamento Base.xls").Close 'Copy from Embalagem Workbook Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Embalagem Base.xls" LastRowEB = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Cells(Rows.Count, 1).End(xlUp).Row Dim Emb_base As Range Set Emb_base = Workbooks("Embalagem Base.xls").Worksheets("Embalagem Base").Range("A2:CT" & LastRowEB) MyCurrentWB.Worksheets("B-Embalagem").Range("A2:CT" & LastRowEB).Value = Emb_base.Value Workbooks("Embalagem Base.xls").Close 'Copy from Dikla Workbook Workbooks.Open "C:\Users\marco.henrique\Desktop\Bases\Diklatex Base.xls" LastRowDB = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Cells(Rows.Count, 1).End(xlUp).Row Dim Dikla_base As Range Set Dikla_base = Workbooks("Diklatex Base.xls").Worksheets("Diklatex Base").Range("A2:AV" & LastRowDB) MyCurrentWB.Worksheets("B-Dikla").Range("A2:AV" & LastRowDB).Value = Dikla_base.Value Workbooks("Diklatex Base.xls").Close End Sub ```
2016/01/20
[ "https://codereview.stackexchange.com/questions/117371", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/95263/" ]
An idea for you: Right now, your code is assuming all sorts of things about worksheets in **other** workbooks including, but not limited to: * The names of the other workbooks' worksheets * The location of the data within those sheets If any of those workbooks change you'll have to go through every macro that interacts with them and change all the details. This is a huge source of errors and data corruption. Instead, each of your (other) workbooks should have an internal Macro to export sheet data. That way, if something in your other workbooks changes, you can change the code there, and every other workbook that needs the data won't need to be re-written. As an example, this is some code from my last VBA project with example usage: --- From any other workbook that wants the data: -------------------------------------------- ``` Sub test() Dim wbTarget as Workbook Set wbTarget = [Workbook Ref] Dim targetCodeName As String wbTarget.GetSubsheetCodeNames newClientCodename:=targetCodeName Dim arr As Variant arr = wbTarget.GetDataArrayFromSheetByCodename(targetCodeName) End Sub ``` --- **In the workbook containing the data:** ---------------------------------------- ``` Option Explicit Public Const ADVISER_HEADER As String = "Adviser" Public Sub GetSubsheetCodeNames( _ Optional ByRef newClientCodename As String _ , Optional ByRef existingClientCodename As String _ , Optional ByRef otherInitialCodename As String _ , Optional ByRef groupSchemesCodename As String _ , Optional ByRef clientWithdrawalsCodename As String) newClientCodename = wsNewClient.CodeName existingClientCodename = wsExistingClient.CodeName otherInitialCodename = wsOtherInitial.CodeName groupSchemesCodename = wsGroupSchemes.CodeName clientWithdrawalsCodename = wsClientWithdrawals.CodeName End Sub Public Function GetDataArrayFromSheetByCodename(ByVal wsCodename As String) As Variant '/ returns the dataArray, or an error if could not find worksheet Dim dataArray As Variant dataArray = Array() Dim wsWasFound As Boolean Dim wsTarget As Worksheet, ws As Worksheet wsWasFound = False For Each ws In ThisWorkbook.Worksheets If ws.CodeName = wsCodename Then Set wsTarget = ws wsWasFound = True Exit For End If Next ws Dim topLeftCellText As String topLeftCellText = GetWsTopLeftCellText(wsTarget) Dim tableRange As Range If wsWasFound Then dataArray = GetWsDataArray(ThisWorkbook, wsTarget, topLeftCellText, useCurrentRegion:=False) GetDataArrayFromSheetByCodename = dataArray Else GetDataArrayFromSheetByCodename = CVErr(2042) '/ #N/A error End If End Function Private Function GetWsTopLeftCellText(ByRef ws As Worksheet) As String Dim topLeftCellText As String Select Case ws.CodeName Case Is = "wsNewClient" topLeftCellText = ADVISER_HEADER Case Is = "wsExistingClient" topLeftCellText = ADVISER_HEADER Case Is = "wsOtherInitial" topLeftCellText = ADVISER_HEADER Case Is = "wsGroupSchemes" topLeftCellText = ADVISER_HEADER Case Is = "wsClientWithdrawals" topLeftCellText = ADVISER_HEADER Case Else '/ TODO: Add Error handling Stop End Select GetWsTopLeftCellText = topLeftCellText End Function ``` --- ``` Public Function GetWsDataArray(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _ , Optional ByVal searchStartRow As Long = 1, Optional ByVal searchStartColumn As Long = 1 _ , Optional ByVal searchEndRow As Long = 10, Optional ByVal searchEndColumn As Long = 10) As Variant '/ 10x10 is arbitrary search range that should cover almost all typical worksheets Dim dataArray As Variant dataArray = Array() dataArray = GetWsDataRange(wbTarget, wsTarget, topLeftCellText, useCurrentRegion, searchStartRow, searchStartColumn, searchEndRow, searchEndColumn) GetWsDataArray = dataArray End Function Public Function GetWsDataRange(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _ , ByVal searchStartRow As Long, ByVal searchStartColumn As Long _ , ByVal searchEndRow As Long, ByVal searchEndColumn As Long) As Range Dim wbSource As Workbook, wsSource As Worksheet Set wbSource = ActiveWorkbook Set wsSource = ActiveSheet wbTarget.Activate wsTarget.Activate ShowAllWsCells wsTarget Dim topLeftCell As Range, searchRange As Range, dataRange As Range Set searchRange = wsTarget.Range(Cells(searchStartRow, searchStartColumn), Cells(searchEndRow, searchEndColumn)) Set topLeftCell = CellContainingStringInRange(searchRange, topLeftCellText) Dim lastRow As Long, lastCol As Long If useCurrentRegion Then Set dataRange = topLeftCell.CurrentRegion Else lastRow = Cells(Rows.Count, topLeftCell.Column).End(xlUp).Row lastCol = Cells(topLeftCell.Row, Columns.Count).End(xlToLeft).Column Set dataRange = wsTarget.Range(topLeftCell, Cells(lastRow, lastCol)) End If Set GetWsDataRange = dataRange wbSource.Activate wsSource.Activate End Function Public Function CellContainingStringInRange(ByRef rngSearch As Range, ByVal strSearch As String) As Range Dim errorMessage As String Set CellContainingStringInRange = rngSearch.Find(strSearch, LookIn:=xlValues) If CellContainingStringInRange Is Nothing _ Then errorMessage = "Couldn't find cell """ & strSearch & """ in " & rngSearch.Worksheet.name PrintErrorMessage errorMessage, stopExecution:=True End If End Function Public Sub ShowAllWsCells(ByRef ws As Worksheet) ws.Rows.Hidden = False ws.Columns.Hidden = False ws.AutoFilterMode = False End Sub ``` --- As you can see, the workbook containing the data knows all sorts of information about how to locate the data that the other workbooks **do not need to know**. If it changes, you only have to change the information **in the workbook that changed**. Any other workbook that wants the data can just ask for it, **and let the target handle the details**. Also, --- Codenames --------- Codenames are big and clever. Every worksheet and workbook has a "name" that the user can see and change. `MyCurrentWB.Worksheets("B-Dikla")` is referencing a sheet name. A Codename on the other hand is a secret name that can **only** be set/changed in the IDE. [![enter image description here](https://i.stack.imgur.com/6u86p.png)](https://i.stack.imgur.com/6u86p.png) the name in brackets is the "name". The name not in brackets is the "codename". It is set in the properties window. [![enter image description here](https://i.stack.imgur.com/KqNBN.png)](https://i.stack.imgur.com/KqNBN.png) If you give a sheet a codename (E.G. "wsBDikla") then the user can change the name as much as they like, all you have to do is use `wsBDikla.ClearContents` in your code and it will keep running.
23,081,395
I am facing issue to start my tomcat server in netbeans. I am getting error when I click on start button ``` "Starting of tomact failed, check whether the /Application/NetBeans/apache-tomcat-7.0.52/bin/catalina/sh and related scripts are executable." ``` For more details please check screenshot ![enter image description here](https://i.stack.imgur.com/VWgsX.png)
2014/04/15
[ "https://Stackoverflow.com/questions/23081395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1331568/" ]
You should run from the command line / shell if you can though I realize you want to run from Netbeans in this case. Also make sure that all your `.sh` scripts are executable (do a `chmod`) because otherwise they cannot be called. Lastly, make sure you have the right permissions to run the scripts. Once you are beyond these checks, you'll possibly get other error messages e.g. your `JAVA_HOME` or your `CATALINA_HOME` are not set. These will be easy to fix. ### EDIT To run Tomcat from the terminal, * go to your Tomcat folder (either `TOMCAT_HOME` or `TOMCAT_HOME/bin`). * Make sure all `.sh` scripts are executable (`chmod a+x *.sh`) * run `startup.sh`: .`/startup.sh` or `bin/startup.sh` (depending on whether you are inside `TOMCAT_HOME` or inside `TOMCAT_HOME/bin`)
21,339,759
I have an situation where I need to save a hibernate object, but I am not sure whether an ID would be assigned by calling app (using special logic with in a range - unique) or not. If the ID is not assigned, I need hibernate to generate an ID higher than the possible ID range which the app would input (i know the range). Else should go with what using app inputs. I am working on MySQL - checking to see if I can custom generator like below ``` public class MyDOIdGenerator extends IdentityGenerator{ @Override public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { if ((((MyDO) obj).getId()) == null) { Serializable id = super.generate(session, obj) ; return id; } else { return ((MyDO) obj).getId(); } } } ``` But my problem is, I dont know how the super.generate would behave in a clustered environment. Would it maintain the ID synchronization across servers? How do I specify the number to start from? (Because I need to exclude the app using id range when having hibernate generate it) Please help Thanks
2014/01/24
[ "https://Stackoverflow.com/questions/21339759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233126/" ]
Actually you will still need to do some stuff with your Models in your controller. Use Repository Pattern do to so, which is pretty similar of querying your models in your controller, but being less verbose: ``` public function serve($company) { return View::make('layouts.singlereview')->withReview(with(new Review)->getCompanyData($company)); } ``` And put the whole logic in your repository: ``` class Review extends Eloquent { public function getCompanyData($company) { return static::select('head', 'body', 'logo', 'name') ->where('company', '=', $company) ->firstOrFail(); } } ```
84,249
When Finn and Rose Tico were in the jail cell where they met the thief, why was the thief even there, if he could just easily escape with basically no effort?
2017/12/27
[ "https://movies.stackexchange.com/questions/84249", "https://movies.stackexchange.com", "https://movies.stackexchange.com/users/60426/" ]
He got himself arrested so the police would stop bothering him. =============================================================== Taken from p. 65 of *The Last Jedi Visual Dictionary*: > > Already known to local authorities, **DJ purposely arranges his own arrest** for a petty crime. The jail is the only place he can grab some sleep with the assurance that he won't be pestered by the Canto Bight Police Department. > > >
26,236,662
How can I create a script that checks if a process is running, and when it is not running executes a line of codes? And let the script check every minute? I was thinking of something like this: ``` #! /bin/bash case "$(pidof Program.exe | wc -w)" in 0) echo "Restarting Program: $(date)" >> /var/log/ProgramLog.txt (mono-runtime Program.exe -option1 yes -option2 no -option3 6; 1) & ;; 1) # all ok ;; *) echo "Removed double Program: $(date)" >> /var/log/ProgramLog.txt kill $(pidof Program.exe | awk '{print $1}') ;; esac ``` 0: If no process is found execute the code 1: If process is found do nothing \*: If there is more than 1 process found stop the last one there are 2 codes to execute: mono-runtime Program.exe -option1 yes -option2 no -option3 6 and behind the semicolon: 1 Is this a correct way to do that?: (mono-runtime Program.exe -option1 yes -option2 no -option3 6; 1) &
2014/10/07
[ "https://Stackoverflow.com/questions/26236662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3572440/" ]
The monit (small software) will do all this job for you: Please look here: ``` https://mmonit.com/monit/documentation/ ```
12,664
I am using a Microsoft template for adding Training and Courses for people to register for. Everything is working fine, but I want to add a field to the Courses list. I want to add a field to indicate what type of staff this course is for, eg HR, Health & Safety, Admin, etc. So I have searched all over for answers to this, the documentation on SharePoint is shocking, and I did the following: * Settings > Create Column on the Courses page. * Entered all necessary details * On DispForm, EditForm and NewForm (.aspx) added `@fStaffType, Staff Type;` to `DataFields` section. (`Staff Type` is the name of the field`) * On DispForm added a new row to display the data: ``` <tr> <td width="190px" valign="top" class="ms-formlabel"> <H3 class="ms-standardheader"> <nobr>Staff Type</nobr> </H3> </td> <td width="400px" valign="top" class="ms-formbody"> <xsl:value-of select="@fStaffType"/> </td> </tr> ``` * On EditForm and NewForm added a new row to edit/enter data: ``` <tr> <td width="190px" valign="top" class="ms-formlabel"> <H3 class="ms-standardheader"> <nobr>Staff Type</nobr> </H3> </td> <td width="400px" valign="top" class="ms-formbody"> <SharePoint:FormField runat="server" id="ff12{$Pos}" ControlMode="New" FieldName="fStaffType" __designer:bind="{ddwrt:DataBind('i',concat('ff12',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@fStaffType')}"/> <SharePoint:FieldDescription runat="server" id="ff12description{$Pos}" FieldName="fStaffType" ControlMode="New"/> </td> </tr> ``` On EditForm and NewForm I get the error: > > Error Rendering Control - > ff12description\_1 > > > An unhandled exception has occured. > Object reference not set to an > instance of an object. > > > If I comment out the description it will show the first `td` (Field Name) but the second `td` is just empty. Any help would be greatly appreciated! EDIT: A related problem, don't know if I should create a new question or not. But Marc D Anderson answered below and I was able to add and display a new field. However, I can add a new Course perfectly but if I edit one, and change the Staff Type field, a new Course will be created at the current day and time. But if other fields are edited they edit correctly. Any ideas?
2011/05/13
[ "https://sharepoint.stackexchange.com/questions/12664", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/3393/" ]
Many of the ["Fabulous 40" templates](http://technet.microsoft.com/en-us/windowsserver/sharepoint/bb407286.aspx) have customized forms. (You'll probably debate the fabulous part of the name at this point.) It looks like you are doing roughly the right things in the forms, but it's a little hard to tell where it's going south on you. When you created the new column, did you give it a name of "fStaffType"? If not, that's the issue. If you named it "Staff Type", then the internal name (or StaticName) for the column is "Staff\_x0020\_Type". (The space in the name will be encoded.) EDIT: You can find the StaticName for a column by going into list settings and editing that column. The StaticName will be at the end of the URL as a Query String parameter. Depending on which characters you have used, it may bedouble encoded, like Staff%5Fx0020%5FType. You don't need to add the column DisplayName and StaticName to the DiataFields section -- it doesn't really serve any obvious purpose, frankly. You'll just need to make sure that the column name in the SharePoint:FormField and SharePoint:FieldDescription matches the StaticName for the column name you've added. The trailing "\_1" in the error is part of the unique name that SharePoint gives each instance of that column in the page (you could be allowing edits to multiple items in the same form) by appending the value of the $Pos variable.
787,992
Let $G$ be a reductive group and $B$ a Borel subgroup. The Bruhat decomposition allows us to write (where $W$ is the Weyl group): $$ G/B = \coprod\_{w\in W} BwB$$ Why is this form the same as looking at the $G$-orbit decomposition ($G$ acting diagonally): $$ (G/B)^2 = \coprod\_{w\in W} G\cdot (eB,wB)$$ I believe this generalizes. If $P\_1,...,P\_n$ are parabolic subgroups, then looking at the orbits of the diagonal $G$ action on $G/P\_1\times ... \times G/P\_n$ is the same as the orbit structure of the $P\_1$ action on $G/P\_2 \times ... \times G/P\_n$.
2014/05/09
[ "https://math.stackexchange.com/questions/787992", "https://math.stackexchange.com", "https://math.stackexchange.com/users/130769/" ]
So, suppose $$G/B = \coprod\_{w \in W} B w B.$$ Then, pick $(gB, hB) \in (G/B)^{2}.$ We can find $w$ such that $g^{-1}h \in BwB$. Say $g^{-1}hB = bwB$. Then, $b^{-1}g^{-1}h \in wB$ and hence, $$(gB, hB) = gb(eB, b^{-1}g^{-1}hB) = gb(eB, wB).$$ Hence, $(G/B)^{2} \subseteq \coprod\_{w \in W} G\cdot (eB, wB)$, and the reverse inclusion is obvious. Now, suppose $$(G/B)^{2} \subseteq \coprod\_{w \in W} G \cdot (eB, wB).$$ Pick $gB \in G/B$. Then, for some $w \in W$, and $g \in G$, $$(eB, gB) = (g'B, g'wB)$$ and hence $g' \in B$ and hence $gB \in BwB.$ Hence, $G/B \subseteq \coprod\_{w \in W} BwB$ and the reverse inclusion is trivial.
60,231,231
I'm trying to make a regex to identify a comment. It has to start with // and end with a new line or a \*) pattern.
2020/02/14
[ "https://Stackoverflow.com/questions/60231231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12899942/" ]
Set `closeOnSelect` to `false` ``` <ng-select [items]="items" bindLabel="name" bindValue="id" [multiple]="true" [closeOnSelect]="false" placeholder="Select categories" [(ngModel)]="selectedCategories"> </ng-select> ```
14,888,843
I have my two log files in my django root dir called `apache.error.log` and `django.log`. In my `app/static` folder I have the HTML file `mylog.html`. Now I want to view those log files inside that HTML page. Is this possible? I want to view the last 20 lines of both files. basically something like `tail -f`, but inside the browser so that I can have my one tab always open for debugging.
2013/02/15
[ "https://Stackoverflow.com/questions/14888843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024264/" ]
If you're using Class Based Views: ``` class LogTemplateView(TemplateView): template_name = "mylog.html" apache_log_file = "apache.error.log" django_log_file = "django.log" def get_context_data(self, **kwargs): """ This has been overriden to give the template access to the log files. i.e. {{ apache_log_file }} and {{ django_log_file }} """ context = super(LogTemplateView, self).get_context_data(**kwargs) context["apache_log_file"] = self.tail(open(self.apache_log_file, "r"), 20) context["django_log_file"] = self.tail(open(self.django_log_file, "r"), 20) return context # Credit: Armin Ronacher - http://stackoverflow.com/a/692616/1428653 def tail(f, n, offset=None): """Reads a n lines from f with an offset of offset lines. The return value is a tuple in the form ``(lines, has_more)`` where `has_more` is an indicator that is `True` if there are more lines in the file. """ avg_line_length = 74 to_read = n + (offset or 0) while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None], \ len(lines) > to_read or pos > 0 avg_line_length *= 1.3 ```
62,116,031
I have a `SerialPort` object. I have put an event handler on this to monitor disposal, exceptions and received data events: ``` mySp.DataReceived += sp_DataReceived; mySp.ErrorReceived += sp_ErrorReceived; mySp.Disposed += sp_Disposed; ``` After a few minutes I stop receiving data, but I have good reason to believe this is not an issue with the sender of the serial messages. I've had issues in this app before with GC disposing things I needed (`Threading.Timer` objects), so I want to make sure this `SerialPort` is not being disposed. I attached a `Disposed` handler, but I've just read GC would not invoke `Dispose` - so how can I tell if it's GC or an issue elsewhere?
2020/05/31
[ "https://Stackoverflow.com/questions/62116031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12683473/" ]
With the GC we can never say if it is or when it is collected - only if it **CAN** be collected. The rule is "the GC can collect everything that does not have a chain of strong references to a application root." If you got that, the GC will not touch it. If you do not have it the GC may touch it - eventually. Running the GC is expensive. While it collects, all other threads *must pause*. Accordingly the Framework is lazy at running it. If it only runs once - on application closure - that is the ideal case. Before that only some rare scenarios can get it into action: * The danger of a OOM Exception. Before those happen, the GC will have collected everything it can. * Manually calling it * various optimsiations. Like trying to collect everything you created inside the function you just finished. * any alternate GC strategy, like the one optimized for servers As for your problem: **As long as you keep a strong reference to something, it can not be collected**. If you got a strong reference, the GC has to assume you are working on it and it is not supposed to remove it. It may still do other background stuff with it (like moving it around in memory), but those changes are usually invisible for you. The only way to cause a memory leak with a GC like this, is to forgetting to remove all strong references to something. Mostly it is people forgetting to remove it from a Collection. Event handlers by design do not count as "a unbroken chain of strong references". GUI Automatics already have a strong reference chain to everything that is displayed (and the stuff that is only hidden, not undisplayed). I think you are doing some wierd way of multitasking like this: * you create a instance * you register events * you do not keep a strong reference This will not work. You need to use a proper way of multitasking - ideally using some blocking or polling code - to process them. That would also allow you to get Exceptions out of the SerialPorts.
40,889,351
Can you please advise how i can implement this sql query: ``` select * from products where (category, category2, category3) in (2, 138, 136, 125) ``` Error: ``` #1241 - Operand should contain 3 column(s) ```
2016/11/30
[ "https://Stackoverflow.com/questions/40889351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7230953/" ]
1) input variable : continuous / output variable : categorical C4.5 algorithm solve this situation. [C4.5](https://en.wikipedia.org/wiki/C4.5_algorithm) In order to handle continuous attributes, C4.5 creates a threshold and then splits the list into those whose attribute value is above the threshold and those that are less than or equal to it. 2) input variable : continuous / output variable : continuous CART(classification and regression trees) algorithm solves this situation. [CART](https://en.wikipedia.org/wiki/Decision_tree_learning) Case 2 is the regression problem. You should enumerate the attribute `j`, and enumerate the values `s` in that attribute, and then splits the list into those whose attribute value is above the threshold and those that are less than or equal to it. Then you get two areas [![enter image description here](https://i.stack.imgur.com/oecME.png)](https://i.stack.imgur.com/oecME.png) Find the best attribute `j` and the best split value `s`, which [![enter image description here](https://i.stack.imgur.com/PIAH0.png)](https://i.stack.imgur.com/PIAH0.png) `c_1` and `c_2` and be solved as follows: [![enter image description here](https://i.stack.imgur.com/CBCGj.png)](https://i.stack.imgur.com/CBCGj.png) Then when do regression, [![enter image description here](https://i.stack.imgur.com/y19cp.png)](https://i.stack.imgur.com/y19cp.png) where [![enter image description here](https://i.stack.imgur.com/sga1c.png)](https://i.stack.imgur.com/sga1c.png)
49,819,295
In Xamarin.Android, to load an image using FFImageLoading, a ImageViewAsync must be used instead of a standard ImageView. I couldn't find what I can use if I wanna load my image into an ImageButton. Didn't find an "ImageButtonAsync".
2018/04/13
[ "https://Stackoverflow.com/questions/49819295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Dont know if this is relevant or not. I gave my svg a tap gesture to get it working like a button. first reference the FFImageLoading.Svg.Forms in your xaml ``` namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms" ``` second add the svgImage with a tap gesture ``` <ffimageloadingsvg:SvgCachedImage Source="YourImageSource" > <ffimageloadingsvg:SvgCachedImage.GestureRecognizers> <TapGestureRecognizer NumberOfTapsRequired="1" Command="{Binding YourCommand}"/> </ffimageloadingsvg:SvgCachedImage.GestureRecognizers> </ffimageloadingsvg:SvgCachedImage> ``` You will call this in the constructor of your ViewModel to initialize the command ``` YourCommand= new DelegateCommand(async () => await ExecuteYourCommandAsync()); ``` Create the properties that bind to the xaml file ``` public ICommand YourCommand { get => yourCommand; set => SetProperty(ref yourCommand, value); } private ICommand yourCommand; ``` The await ExecuteYourCommandAsync is a method that you create. and in there you will put your logic of what you actually want the tap gesture to do. You can also pass through object with the command. let met know if this makes sense
3,347,504
I have the following **HashMap**: ``` HashMap<String,Object> fileObj = new HashMap<String,Object>(); ArrayList<String> cols = new ArrayList<String>(); cols.add("a"); cols.add("b"); cols.add("c"); fileObj.put("mylist",cols); ``` I write it to a file as follows: ``` File file = new File("temp"); FileOutputStream f = new FileOutputStream(file); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(fileObj); s.flush(); ``` Now I want to read this file back to a HashMap where the Object is an ArrayList. If i simply do: ``` File file = new File("temp"); FileInputStream f = new FileInputStream(file); ObjectInputStream s = new ObjectInputStream(f); fileObj = (HashMap<String,Object>)s.readObject(); s.close(); ``` This does not give me the object in the format that I saved it in. It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place. //How can I read the same object back into a HashMap ? OK So based on Cem's note: This is what seems to be the correct explanation: **ObjectOutputStream serializes the objects (HashMap in this case) in whatever format that ObjectInputStream will understand to deserialize and does so generically for any Serializable object. If you want it to serialize in the format that you desire you should write your own serializer/deserializer.** *In my case: I simply iterate through each of those elements in the HashMap when I read the Object back from the file and get the data and do whatever I want with it. (it enters the loop only at the point where there is data).* Thanks,
2010/07/27
[ "https://Stackoverflow.com/questions/3347504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403828/" ]
You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you. ``` public static void main(String... args) throws IOException, ClassNotFoundException { HashMap<String, Object> fileObj = new HashMap<String, Object>(); ArrayList<String> cols = new ArrayList<String>(); cols.add("a"); cols.add("b"); cols.add("c"); fileObj.put("mylist", cols); { File file = new File("temp"); FileOutputStream f = new FileOutputStream(file); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(fileObj); s.close(); } File file = new File("temp"); FileInputStream f = new FileInputStream(file); ObjectInputStream s = new ObjectInputStream(f); HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject(); s.close(); Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode()); Assert.assertEquals(fileObj.toString(), fileObj2.toString()); Assert.assertTrue(fileObj.equals(fileObj2)); } ```
14,996,632
There are some `C#` console applications that started by **Windows scheduler**. How can I gather work progress from any of them (using internal data available only in concrete console application)? In other words, I want to show some data from running console application on my asp.net webforms website. How can i do this?
2013/02/21
[ "https://Stackoverflow.com/questions/14996632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083527/" ]
Host a http server inside the console app that the website can communicate with. I already kind of do this using self host signal r inside a tray application and it works a treat. <https://github.com/SignalR/SignalR/wiki/Self-host>
25,409,822
In my package, before I perform a query on my database I check if some of the params provided are valid: ``` //check if(!$this->checkId($id)) //error //do the query $user = User::find($id); ``` What's the best way to handle this in a laravel package? Throw an error? If so, which kind? Do an app abort?
2014/08/20
[ "https://Stackoverflow.com/questions/25409822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013512/" ]
Using findOrFail() ------------------ There is a pretty good method that Laravel provides just for this case called `findOrFail()`. What you can do is use that and then catch the exception. ``` try { $user = User::findOrFail($queryParam); } catch(ModelNotFoundException $e) { // Do things that should happen here if your query parameter does not exist. } ``` If you do not wish to catch it here, you can setup a listener for this exception. You can place it anywhere you wish as long as it's being autoloaded. ``` use Illuminate\Database\Eloquent\ModelNotFoundException; App::error(function(ModelNotFoundException $e) { return Response::make('Not Found', 404); }); ``` Throwing an exception --------------------- If all you want to do is throw an error if a query param isn't available, you can throw any of the exceptions found here... <https://github.com/symfony/symfony/tree/master/src/Symfony/Component/HttpKernel/Exception> If none suit you, you can create your own and just extend `Symfony\Component\HttpKernel\Exception\HttpException` and `throw new YourCustomException($statusCode, $message);`. Just follow what they've done in the other exception classes and it should be fairly easy. Then you can modify the the "exception listener" to catch `YourCustomException`. Here is a tutorial I found... <http://fideloper.com/laravel4-error-handling>
34,726,185
Imagine I'm building a blog system where a user can upload images for a blog post. I have a problem mapping the uploaded images with user and their blog post. Here's the flow : 1. User uploaded some pictures, it's saved to the server. 2. I store the image name in the related table, means later I can retrieve images by blog's post\_id. But what if the user upload images that has the same file name?
2016/01/11
[ "https://Stackoverflow.com/questions/34726185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5485528/" ]
You can do the fading with just css transitions all you need to do is use jquery toggleClass function when the window reaches 150px. Try the following: ``` $(window).on( "scroll", function() { $('#secondNav').toggleClass('scrolled', $(this).scrollTop() > 150); }); ``` and the css ``` #secondNav.navbar-default{ background: #000; transition: background-color 0.5s ease; } #secondNav.scrolled { background: rgba(0,0,0,0.5); } ``` The transition property is what will give you the fade in and out and then you can change the background of the navbar-default to whatever you want it to be. When it reaches 150px it will toggle the scrolled class and change the background.
90,189
I tried to sync the blockchain and, though I have ample free disk space (>500 GB on my computer, the chain is ~265) I've been having a hard time. So, how can I use an SPV node to send transactions and/or view the blockchain? NOTE: don't do this if you don't have to because the blockchain needs nodes to ensure adequate distribution.
2019/09/03
[ "https://bitcoin.stackexchange.com/questions/90189", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/96148/" ]
Try Electrum. Exact details on how to install depend on Linux distribution used. Also Wasabi Wallet could be good choice, easy to setup.
324,562
``` telnet www.ietf.org 80 GET /rfc.html HTTP/1.1 Host: www.ietf.org ``` This sequence of commands starts up a telnet (i.e., TCP) connection to port 80 on IETF’s Web server, www.ietf.org. Then comes the GET command naming the path of the URL and the protocol. Try servers and URLs of your choosing. The next line is the mandatory Host header. 1. Can we use `ssh` instead of `telnet`, something like ``` ssh www.ietf.org 80 GET /rfc.html HTTP/1.1 Host: www.ietf.org ``` ? 2. What **other programs** besides `ssh` can be used in place of `telnet` in the above example to establish a connection from a local host to a remote http server, so that we can send a http request to the http server and receive a http response from it? What **kind of programs** can be used in place of `telent` in the above example? Thanks.
2016/11/19
[ "https://unix.stackexchange.com/questions/324562", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/674/" ]
To reconfigure the keyboard in Debian, run (as `root`, or using `sudo`): ``` dpkg-reconfigure keyboard-configuration ``` Link to official Debian documentation [here](https://wiki.debian.org/Keyboard). If your keys are "random" (I have been there, not fun!), try to find the characters needed to execute the command above.
72,315,325
Using react native with typescript and redux toolkit Hi I'm bothering with render a list of messages via FlatList. By ScrollView everything rendering good but I need to implement infiniti scroll. So I'm doing something like this ``` const MessagesScreen = () => { const companyId = useAppSelector(getCompanyId); const userId = useAppSelector(getUserId); const { data: messages, isLoading, refetch } = useGetMessagesQuery({ userId, companyId }); useFocusEffect(refetch); return ( <FlatList data={messages} renderItem={() => { <Messages messages={messages} />; }} /> ); }; ``` In `return()` I'm trying to render FlatList with component Messages which is down here: ``` const Messages = ({ messages }: { messages: Message[] }) => { const navigation = useNavigation<RootStackScreenProps<'DrawerNavigator'>['navigation']>(); const { colors } = useTheme(); return ( <View style={styles.container}> {messages.map(message => { const createdAt = message.created_at; const isRead = message.read; const icon = isRead ? 'email-open-outline' : 'email-outline'; const onClick = () => { navigation.navigate('Message', { messageId: message.id }); }; return ( <TouchableOpacity key={message.id} onPress={onClick}> <View style={[styles.message, { borderBottomColor: colors.separator }]} > <View style={styles.iconPart}> <Icon name={icon} type="material-community" style={ isRead ? { color: colors.separator } : { color: colors.inputFocus } } size={24} ></Icon> </View> <View style={styles.bodyPart}> <Text numberOfLines={1} style={[isRead ? styles.readSubject : styles.unReadSubject]} > {message.subject} </Text> <Text numberOfLines={1} style={[isRead ? styles.readBody : styles.unReadBody]} > {message.body} </Text> </View> <View style={styles.datePart}> <Text style={{ color: colors.shadow }}> {dayjs(createdAt).fromNow()} </Text> </View> </View> </TouchableOpacity> ); })} </View> ); }; ``` Actually behaviour is just rendering white screen with error ``` Possible Unhandled Promise Rejection (id: 17): Error: Objects are not valid as a React child (found: object with keys {id, msg_type, created_at, subject, body, author, company_id, read}). If you meant to render a collection of children, use an array instead. ```
2022/05/20
[ "https://Stackoverflow.com/questions/72315325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15032294/" ]
there is problem with your call back function: **you are not returning Messages component** **1:Remove curly braces** ```js return ( <FlatList data={messages} renderItem={() => <Messages messages={messages}/> } /> ); ``` **2:Add return statement** ```js return ( <FlatList data={messages} renderItem={() => { return <Messages messages={messages} />; }} /> ); ```
33,576,572
[![Vector plot made in Python](https://i.stack.imgur.com/y4Odp.png)](https://i.stack.imgur.com/y4Odp.png) I am solving a lid-driven cavity flow problem. For creating the figure, I chose Python because it was the only language I know that has such a feature. For the figure, I have to plot streamlines and vector arrows. See the figure. Here is the line of code in question: `plt.quiver(x, y, u, v, color='black', headwidth=1, scale = 10, headlength=4)` My problem is the size of the black vector arrows, not the blue streamlines. I would like to have larger vector arrows with less arrow density. Is there anyway I can do this in Python? I have not seen this elsewhere.
2015/11/06
[ "https://Stackoverflow.com/questions/33576572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Based on the [answer provided here](https://stackoverflow.com/a/25343170/5067311), you can prune your input arrays into `quiver` by using strides, as in `x[::2,::2]` etc. to use only every second element of the arrays. To spare some writing, you can define a `slice` to do the bulk of the notation for you: ``` skip = (slice(None, None, 2), slice(None, None, 2)) plt.quiver(x[skip], y[skip], u[skip], v[skip], color='black', headwidth=1, scale=10, headlength=4) ``` This will use every second data point. Obviously, for a different factor for rarification, change the integers in the definition of `skip`. The automatic arrow scaling of `plt.quiver` should do most of the job for you, you just have to find a satisfactory input point density.
64,632,871
hello everyone I have two dataframes and I'd like to join information from one df to another one in a specific way. I'm gonna explain better. Here is my first df where i'd like to add 6 columns (general col named col1, col2 and so on..): ``` res1 res4 aa1234 1 AAAAAA 1 4 IVGG 2 AAAAAA 8 11 RPRQ 3 AAAAAA 10 13 RQFP 4 AAAAAA 12 15 FPFL 5 AAAAAA 20 23 NQGR 6 AAAAAA 32 35 HARF ``` here is the 2nd df: ``` res1 dist 1 3.711846 1 3.698985 2 4.180874 2 3.112819 3 3.559737 3 3.722107 4 3.842375 4 3.914970 5 3.361647 5 2.982788 6 3.245118 6 3.224230 7 3.538315 7 3.602273 8 3.185184 8 2.771583 9 4.276871 9 3.157737 10 3.933783 10 2.956738 ``` Considering "res1" I'd like to add to the 1st df in my new 6 columns the first 6th values contained in "dist" of second df corresponding to res1 = 1. After, in the 1st df I have res1 = 8, so I'd like to add in the new 6 columns the 6 values from res1 = 8 contained in "dist" of 2nd df. I'd like to obtain something like this ``` res1 res4 aa1234 col1 col2 col3 col4 col5 col6 1 4 IVGG 3.71 3.79 4.18 3.11 3.55 3.72 8 11 RPRQ 3.18 2.77 4.27 3.15 3.93 2.95 10 13 RQFP 12 15 FPFL 20 23 NQGR 32 35 HARF ``` Please consider that I have to do it on a large dataset and for 1000 and more files... thanks!
2020/11/01
[ "https://Stackoverflow.com/questions/64632871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14467368/" ]
All of this is not necessary. You can simply try to convert the input to a `float`. If it throws an error, it means that the input is not a valid number. You can catch this error using a `try-except` block and print `Invalid`: ``` while True: num1 = input("Enter First Number: ") try: num1 = float(num1) break except ValueError: print("Invalid") ``` Output: ``` Enter First Number: >? 1` Invalid Enter First Number: >? 1-0-0 Invalid Enter First Number: >? 100 ```
25,963,818
I have an issue that relates to threading, cleaning up unmanaged resources and shutting down my app. In the main UI thread I have a method that creates a new instance of class Worker. In Worker's constructor I start a new thread that has a while(Scanning) loop that updates some controls in my UI using Invoke() continuously (until Scanning bool is set to false). In the UI thread I raise the event FormClosing() whenever the application is closing down (through X button or Application.Exit() etc.). In FormClosing() I set Scanning to false and do some cleanup of unmanaged resources (that can only be done after the worker thread is done, because it uses those resources. The problem is that when I close the app down the MainForm apparently gets instantly disposed, so the app crashes at the Invoke (because it is trying to make a delegate run from UI thread, but that thread is disposed). In an attempt to make the worker finish before the UI closes I tried to create a method StopWorker() in the worker class where I put Scanning = false, and then Thread.Join. As you can imagine the Join caused a deadlock as it makes the UI thread sleep but the Invoke needs the UI thread to move on. In summary I need to cleanup unmanaged resources in FormClosing. I need the worker thread to be done before I do that though, as it uses these resources. The worker thread cannot finish (it uses Invoke) if the MainForm is disposed, therefore creating a tricky situation.
2014/09/21
[ "https://Stackoverflow.com/questions/25963818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4059350/" ]
Based on Hans Passant's answer [here](https://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event/1732361#1732361), I created the below solution. It seems to be working very well. In UI class/thread: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { var button = sender as Button; if (button != null && string.Equals(button.Name, @"CloseButton")) { //FormClosing event raised by a user-created button action } else { //FormClosing event raised by program or the X in top right corner //Do cleanup work (stop threads and clean up unmanaged resources) if (_bw.Scanning) { _bw.Scanning = false; ClosePending = true; e.Cancel = true; return; } //Code to clean up unmanaged resources goes here (dummy code below) ApplicationLogger.Get.Log("Doing final cleanup work and exiting application..."); MemoryHandler.Get.Dispose(); ApplicationLogger.Get.Dispose(); } } ``` My worker thread is in another class that has a public bool property called Scanning. It also has this while loop (notice the line at the bottom): ``` private void Worker() { while (Scanning) { Thread.Sleep(50); _sendBackValue[0] = "lbOne"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbTwo"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); _sendBackValue[0] = "lbThree"; _sendBackValue[1] = "blaBla"; _synch.Invoke(_valueDelegate, _sendBackValue); } MainForm.Get.Invoke((Action)(() => MainForm.Get.StopScanning())); } ``` Finally, back in the UI class/thread I have this method: ``` public void StopScanning() { if (!ClosePending) return; ApplicationLogger.Get.Log("Worker thread is closing the application..."); Close(); } ```
41,881
I would like to use the title color of my `beamer` presentation (some kind of blue) to write some inline text with the same color. Therefore I want to know the color definition. Is there a command for using the same color as the title? My preamble definitions are: ``` \mode<presentation> { \usetheme{Warsaw} } \usecolortheme{crane} ``` **EDIT:** ``` \documentclass{beamer} \usepackage{caption} \mode<presentation> { \usetheme{Warsaw} } \usecolortheme{crane} \begin{document} \begin{frame}{\bf This is the title's color I want to ``copy''} \begin{itemize} \item I want to use the ``blue'' color from the title for the caption of the table. \end{itemize} \vspace{1.5\baselineskip} \begin{table} \begin{tabular}{c|c} table1 & trial \\ \hline \hline 1 & 2 \\ 3 & 4 \end{tabular} \caption*{My table} \end{table} \end{frame} \end{document} ```
2012/01/22
[ "https://tex.stackexchange.com/questions/41881", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10529/" ]
You can copy the color from the frame title this way: ``` \caption*{\usebeamercolor[fg]{frametitle}{My table}} ```
57,239,371
I want to disable caching or restrict the cache to 24 hours. My ApolloClient runs exclusively on the Server side. My environment: * apollo-boost 0.4.3 * graphql 14.1.1 * apollo-link-batch-http - 1.2.12 Right now, that's how I configure my `ApolloClient`. ``` new ApolloClient({ ssrMode: true, cache: new InMemoryCache(), link: WithApollo.BatchLink(), credentials: 'same-origin', }); ``` [The closest thing I saw in docs is `FetchOptions`](https://www.apollographql.com/docs/react/essentials/get-started/#configuration-options) ... But it doesn't specify what options i can actually pass to achieve my need for disabling or restricting the cache.
2019/07/28
[ "https://Stackoverflow.com/questions/57239371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631086/" ]
This is where `pandas` library comes with real power and conciseness: with [`pandas.read_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html)/[`pandas.Dataframe.to_csv`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html) one-liner: ``` import pandas as pd pd.read_csv('input.csv', sep=',').to_csv('output.csv', sep=';', index=False) ``` The final `output.csv` contents: ``` DCA.P/C.05820;5707119001793;P/C STEELSERIES SURFACE QcK MINI;5,4;Yes DCA.P/C.05821;5707119001779;P/C STEELSERIES SURFACE QcK;7,2;No DCA.P/C.05823;5707119001762;P/C STEELSERIES SURFACE QcK+;11,9;No ```
11,415,365
I am fairly new to webworks. I am trying to get the camera api to work and I keep getting the error: Error in supported: TypeError: 'undefined' is not an object (evaluating 'blackberry.media.camera') The page I am trying to use is on a hosted server. The code is as follows: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" id="viewport" content="height=device-height,width=device-width,user-scalable=no" /> <script language="javascript" type="text/JavaScript" > function takePicture() { try { blackberry.media.camera.takePicture(successCB, closedCB, errorCB); } catch(e) { alert("Error in supported: " + e); } } function successCB(filePath) { document.getElementById("path").innerHTML = filePath; //alert("Succeed: " + filePath); } function closedCB() { // alert("Camera closed event"); } function errorCB(e) { alert("Error occured: " + e); } </script> <title>Camera Test Widget</title> </head> <body > <p>Test the Camera by pressing the button below</p> <b><a href="#" onclick="takePicture();">Take a Picture</a></b> <div id="path"></div> </body> </html> ``` And my config.xml file is as follows: ``` <?xml version="1.0" encoding="UTF-8"?> <widget xmlns="http://www.w3.org/ns/widgets" xmlns:rim="http://www.blackberry.com/ns/widgets" version="1.0.0.0" rim:header="WebWorks Sample"> <access uri="http://www.flyloops.net/" subdomains="true"> <feature id="blackberry.app.event" required="true" version="1.0.0.0"/> <feature id="blackberry.media.camera" /> </access> <name>Flyloops.net</name> <description>This is a sample application.</description> <content src="index.html"/> </widget> ``` The page is hosted at: <http://www.flyloops.net/mobile/bb/camera.html> I have been tearing my hair out for the past 3 hours...any help would be greatly appreciated.
2012/07/10
[ "https://Stackoverflow.com/questions/11415365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1515055/" ]
If using PlayBook, make sure to have the correct element(s) defined <https://developer.blackberry.com/html5/apis/blackberry.media.camera.html> otherwise, if you are trying to access the blackberry.media.camera API *from* a remote website, then you need to white list that correctly in config.xml like this: ``` <access uri="http://www.flyloops.net/" subdomains="true"> <feature id="blackberry.media.camera" /> </access> ```
61,160,922
I want to be able to import SVG files from the file system, layer them, change their fill colors, and then export them as a single vector file.
2020/04/11
[ "https://Stackoverflow.com/questions/61160922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7214070/" ]
The solution to this problem was simply to import the SVG data as a string, swap out constants for various properties, and then write the new string to the file system. For example, the following svg displays an orange circle: ```html <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <circle cx="500" cy="500" r="500" fill="orange"/> </svg> ``` If you wanted to be able to dynamically change the color of the circle, you could just replace the "orange" text with a placeholder name, such as "{FILL\_COLOR}". Now, the SVG should look like this: ```html <svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"> <circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/> </svg> ``` In your code, you can load the file from the file system as a string and then make changes to it as needed; you could then write the result to the file system. This solution also works perfectly on frontends. Instead of loading the SVG from the file system, simply have it as a hard-coded constant. Once you make the changes to the SVG, you can use the result however you want. ```js function getCircle(color) { const svg = `<svg viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg"><circle cx="500" cy="500" r="500" fill="{FILL_COLOR}"/></svg>`; return svg.replace('{FILL_COLOR}', color); } ```
56,765,872
I am trying to achieve that C interprets my string as macro. Hey, let's suppose there is a defined macro as, ``` #define ABC 900 ``` If i define; ``` char* s[] = "ABC" ; ``` then, ``` printf("%d",s) ; ``` Is there any way the compiler understands that "ABC" as macro ABC and passes 900 integer value to printf ? ``` #include<stdio.h> #define abc 15 int main(void) { char a[] = "abc" ; printf("%d",a); return 0; } ``` When i try the above code, instead of my desired output 15 , i get 6487568 which i guess the integer equivalent of that string. Edit : those were random values , or address of strings. ( as stated below by others )
2019/06/26
[ "https://Stackoverflow.com/questions/56765872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11701071/" ]
No, what you're trying to do is double impossible. You can't access variables by name at runtime (string -> variable) because the compiled machine code knows nothing about the names in your C code, and you can't access macros from the compiler because the compiler knows nothing about macros (they're expanded by the preprocessor before the compiler even sees the code). In other words, compilation / execution happens in multiple stages: 1. C source code is preprocessed (which gets rid of directives like `#include` or `#define` and expands macros). 2. The preprocessed token stream is passed to the compiler, which converts it to machine code (a runnable program). 3. Finally the program runs. Simplified example: ``` // original C code #define FOO 42 ... int x = y + FOO; ``` After preprocessing: ``` ... int x = y + 42; ``` After compilation: ``` movl %ecx, %eax addl $42, %eax ``` There is no trace of `FOO` in step 2, and the final code knows nothing about `x` or `y`. Variable values such as strings only exist at runtime, in step 3. You can't get back to step 1 from there. If you wanted to access information about macros at runtime, you'd have to keep it explicitly in some sort of data structure, but none of this is automatic.
3,571,792
I am trying to structure a database for optimal use. But I have no idea how to make that happen. Here is what i will have A category which will have many products and a count for each on of those products For example Restaurants will be the category and the products will be the computer system, cash register and each one of these products has a count so maybe there will be 2 cash registers and 3 computer systems and so on. Another catagory might be a bar, which might or might not have the same products. Then the user has the option of choosing a 2 restarant package which might have a discount rate for getting all the products. I just need to structure the ERB if i can get some help, Thanks
2010/08/26
[ "https://Stackoverflow.com/questions/3571792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223367/" ]
PRODUCTS -------- * PRODUCT\_ID (primary key) * PRODUCT\_NAME CATEGORIES ---------- * CATEGORY\_ID (primary key) * CATEGORY\_NAME PRODUCT\_CATEGORIES\_MAP ------------------------ * PRODUCT\_ID (primary key, foreign key to `PRODUCTS`) * CATEGORY\_ID (primary key, foreign key to `CATEGORIES`) * QUANTITY This'll allow you to associate a product to more than one category, but not allow duplicates.
31,895,473
I'm trying to compile and install an open source application on Ubuntu. I can make the application, make the installer, and make the package. I don't see any error during those steps. when I issue the dpkg -i to install it if fails with the following error. dpkg: error processing archive application.deb (--install): corrupted filesystem tarfile - corrupted package archive dpkg-deb: error: subprocess paste was killed by signal (Broken pipe) I can only find references to fixing the issue when downloading files and say to issue apt-get clean and purge. I've done that and it doesn't work and it doesn't seem applicable since I'm creating the install file. When I issue dpkg -c application.deb, it shows me the contents, so the file isn't total corrupted. Any suggestions on how to get this application to install?
2015/08/08
[ "https://Stackoverflow.com/questions/31895473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/719989/" ]
Following the description on <https://github.com/Brewtarget/brewtarget> on a newly installed Ubuntu 14.04.3 gives me a .deb that installs. These are the commands I ran: ``` $ sudo apt-get install cmake git qtbase5-dev qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5webkit5-dev libqt5sql5-sqlite libqt5svg5 libqt5multimedia5-plugins doxygen $ git clone https://github.com/Brewtarget/brewtarget.git $ mkdir brewtarget-build $ cd brewtarget-build $ cmake ../brewtarget $ make $ make package $ sudo apt-get install libphonon4 libqt4-webkit phonon phonon-backend-vlc $ sudo dpkg -i brewtarget*.deb Selecting previously unselected package brewtarget_2.2.0. (Reading database ... 175209 files and directories currently installed.) Preparing to unpack brewtarget_2.2.0_x86_64.deb ... Unpacking brewtarget_2.2.0 (2.2.0-1) ... Setting up brewtarget_2.2.0 (2.2.0-1) ... $ file *.deb brewtarget_2.2.0_x86_64.deb: Debian binary package (format 2.0) ``` What version of Ubuntu are you running? It is odd that your error message says "application.deb", as I got a .deb named "brewtarget\_2.2.0\_x86\_64.deb" when following the instructions.
34,364,289
I'm trying out the new Core CLR type ASP.Net on my Mac and running in to no end of problems. I've managed to get StructureMap referenced and installed via dnu and dnu restore, but now I'm getting errors in VS Code stating that: ``` The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'. [dnx451] ``` I've done a good amount of googling but all I can find are things stating I need to add a using for System, that doesn't fix the problem. Startup.cs: ``` using System; using System.Reflection; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using StructureMap; namespace Authorization { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public IServiceProvider ConfigureServices(IServiceCollection services) { var container = new Container(); container.Configure(x => { x.Scan(scanning => { scanning.Assembly(Assembly.GetExecutingAssembly()); scanning.TheCallingAssembly(); scanning.WithDefaultConventions(); }); }); container.Populate(services); return container.GetInstance<IServiceCollection>(services); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } // Entry point for the application. public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } } ``` project.json: ``` { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "tooling": { "defaultNamespace": "Authorization" }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "StructureMap.Dnx": "0.4.0-alpha4" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel" }, "frameworks": { "dnx451": {}, "dnxcore50": {} }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } ``` Any help gratefully received! Thanks
2015/12/18
[ "https://Stackoverflow.com/questions/34364289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333417/" ]
I tried a little and can suggest you two versions to fix the problem with compilation. The first way is removing `dnxcore50` and making some changes in `Startup.cs`. To be exactly one can use the following `project.json`: ```json { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "structuremap": "4.0.1.318", "StructureMap.Dnx": "0.4.0-alpha4" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel" }, "frameworks": { "dnx451": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } ``` and the following `Startup.cs`: ```cs using System.Reflection; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using StructureMap; using StructureMap.Graph; namespace HelloWorldWebApplication { public class Startup { public IServiceCollection ConfigureServices(IServiceCollection services) { var container = new Container(); container.Configure(x => { x.Scan(scanning => { scanning.Assembly(typeof(Startup).GetTypeInfo().Assembly); scanning.TheCallingAssembly(); scanning.WithDefaultConventions(); }); }); container.Populate(services); return container.GetInstance<IServiceCollection>(); } public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async context => { await context.Response.WriteAsync("Hello World!"); }); } public static void Main(string[] args) => Microsoft.AspNet.Hosting.WebApplication.Run<Startup>(args); } } ``` Alternatively one can add back `"dnxcore50": { }` in the `"frameworks"` part, but comment the line `scanning.TheCallingAssembly();` and `using StructureMap.Graph;`
62,866,512
I am using the following CSS to centre the text on the page but it seems to be creating a large CLS (Cumulative Layout Shift), is there a more efficient way to centre the text? ``` @media only screen and (min-width: 1000px) { .page { width: 1000px; margin: 0 auto; font-size: 1.0em; line-height: 1.6em; font-family: Arial, sans-serif; word-wrap: break-word; } } @media only screen and (max-width: 999px) { .page { margin: 0 auto; font-size: 1.0em; line-height: 1.6em; font-family: Arial, sans-serif; word-wrap: break-word; } } ``` The CLS issue only occurs in the Desktop version and not the Mobile version which makes me think it is the `width` option.
2020/07/12
[ "https://Stackoverflow.com/questions/62866512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203146/" ]
It turns out the cause of Cumulative Layout Shift was caused by an image incorrectly sized with the wrong width, I said 700 when the image was actually 702. Strangely, the error was being reported in the wrong place, the error was being reported in another div rather than where the image was. If you are looking for the cause of CLS, look at the image sizings. It wasn't caused by the style width css. The Mobile version worked because I sized that correctly.
36,931,119
The following program: ``` #include <stdio.h> int main() { char s[10] = ""; fprintf(stdout, "%s", "hello"); fscanf(stdout, "%6s", s); perror(NULL); } ``` outputs `Bad file descriptor`. But section 7.21 of the [C11 draft standard](http://port70.net/~nsz/c/c11/n1570.html#7.21) doesn't seem to say anything about whether or not `stdout` is allowed to be passed to `fscanf`. Is this undefined behavior? Explicit (give standard quote) or implied (by omission)?
2016/04/29
[ "https://Stackoverflow.com/questions/36931119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6269788/" ]
The specification (ISO/IEC 9899:2011 (E), §7.21) doesn't actually mention any restrictions on input streams being passed to output functions, or output streams being passed to input functions. The only limitation in the specification is that the stream passed to `fflush` must be an output stream.
68,891,149
can anyone help me on how to remove the huge white space between the two images? Both images are in their respective divs with layer effects when hovered. I have tried changing display to inline-block and setting font-size to 0 but nothing works. I also want the two images to be at the center when adjusted. I may have incorrectly apply the mentioned efforts to different classes or divs throughout the process but I am not sure where I did wrong. Attached are the html and css along with a screenshot of how it looks like on local server. I hope the attachments are useful. Thank you. [![enter image description here](https://i.stack.imgur.com/Ei366.png)](https://i.stack.imgur.com/Ei366.png) ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; height: 100%; width: 100%; position: absolute; top: 0; left: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="#"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
2021/08/23
[ "https://Stackoverflow.com/questions/68891149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16713796/" ]
Like this? If so you just need to use `display: flex` and `align-items: flex-start` ```css *{ padding: 0; margin: 0; box-sizing: border-box; } .row { display: flex; align-items: flex-start } .campus-col{ flex-basis: 32%; border-radius: 10px; margin-bottom: 30px; position: relative; overflow: hidden; } .campus-col img{ width: 100%; display: block; } .layer{ background: transparent; position: absolute; top: 0; left: 0; right: 0; bottom: 0; transition: 0.5s; } .layer:hover{ background: rgba(226,0,0,0.7); } .layer h3{ width: 100%; font-weight: 500; color: #fff; font-size: 26px; bottom: 0; left: 50%; transform: translateX(-50%); position: absolute; opacity: 0; transition: 0.5s; text-align: center; } .layer:hover h3{ bottom: 49%; opacity: 1; ``` ```html <div class="row"> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>TEXT</h3></a> </div> </div> <div class="campus-col"> <img src="https://via.placeholder.com/150"> <div class="layer"> <a href="#"><h3>MESSENGER</h3></a> </div> </div> </div> ```
17,538,167
I have a String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nice formatting plus syntax highlight. I don't want to use a web framework or web browser for such a simple thing. How do I do this? ``` | unformattedXml formattedXml | unformattedXml := '<tag><nested>hello</nested></tag>'. formattedXml := UnknownClass new format: unformattedXml. ``` Note: My input is a String. My output is a String.
2013/07/09
[ "https://Stackoverflow.com/questions/17538167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2562583/" ]
To pretty print your xml string you can use the following ``` xmlString := '<a><b><c></c></b></a>'. xml := XMLDOMParser parseDocumentFrom: xmlString. ^ String streamContents: [:stream| xml prettyPrintOn: stream ] ``` That should give you ``` <a> <b> <c /> </b> </a> ``` I don't know what would be the best option for syntax highlighting
8,252,759
I am developing a taskmanager on Android 2.1. I want to reset date and time on clicking the reset button to current date and time. Help me with the code.. ``` public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText next = (EditText) findViewById(R.id.editText1); final Button sub = (Button) findViewById(R.id.button1); final Button res = (Button) findViewById(R.id.button2); final DatePicker dp= (DatePicker) findViewById(R.id.datePicker1); final TimePicker tp = (TimePicker) findViewById(R.id.timePicker1); res.setOnClickListener(new View.OnClickListener() { public void onClick(final View view) { next.setText(""); dp.refreshDrawableState(); } }); }} ```
2011/11/24
[ "https://Stackoverflow.com/questions/8252759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1031045/" ]
``` //get current time Time now = new Time(); now.setToNow(); //update the TimePicker tp.setHour(now.hour); tp.setMinute(now.minute); //update the DatePicker dp.updateDate(now.year, now.month, now.monthDay); ```
7,029,870
I have this code for drawpath and nothing shows up and I cant figure out why. ``` //i move the path's starting point somewhere up here to a point. //get center x and y are the centers of a picture. it works when i //do drawline and store the different starting points //but i want it to look continuous not like a lot of different //lines path.lineTo(a.getCenterX(), a.getCenterY()); path.moveTo(a.getCenterX(), a.getCenterY()); p.setStrokeWidth(50); p.setColor(Color.BLACK); canvas.drawPath(path,p); ``` ![drawpath image](https://i.stack.imgur.com/4g17b.png) thanks in advance
2011/08/11
[ "https://Stackoverflow.com/questions/7029870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/782117/" ]
i had to add this to paint in order to make it work. dunno why. ``` mPaint.setDither(true); mPaint.setColor(0xFFFFFF00); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(3); ```
346,195
So I've been looking all over the internet for a Decimal to Binary converter but all I've been able to find are Binary to Decimal converters, and Decimal to BCD circuits, does anyone have one?
2017/12/21
[ "https://electronics.stackexchange.com/questions/346195", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/172586/" ]
Yes, you'll struggle to find one. The reason for this is that there is no common reason for a BCD to binary converter. Where do the BCD digits come from that you need to convert? The purpose of the many binary to BCD converter ICs that are around are to support 7-segment displays in the pre-cheap-microcontroller era. You used to use a binary to BCD converter to break out each digit from your ADC or counter, then you would use a BCD to 7-segment driver to run each LED/LCD/VFD display to provide a human readable display of the binary measurement. As you can imagine, this was a rather common function in electronics devices, hence why the chips are readily available. Without knowing much more about the problem you are trying to solve, your best bet is to use a cheap microcontroller. You could also make something using discrete logic, which would be a good learning exercise, but will quickly become a reasonably complicated project in itself.
65,613,573
Is it possible to validate a field only when it exists? I'm going to create an application. A field(email) may / may not display on step 2, it depends on the step 1's selected option. The problem is that I can't put `email: Yup.string().Required()`, it causes that the validation run all the time even the field is not displayed.
2021/01/07
[ "https://Stackoverflow.com/questions/65613573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5400365/" ]
You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation. Something like this. ``` const initialSchema= { name: '', isEmail: false, // change this when you want to add validation email: '', phone: '', }; const validationSchema = Yup.object().shape({ name: Yup.string() .required('Enter Name') isEmail: Yup.boolean(), email: Yup.string().when('isEmail', { is: true, then: Yup.string() .required('Enter Email ID'), otherwise: Yup.string(), }), phone: Yup.string() .required('Enter Mobile No'), }); ``` Here is the [documentation reference](https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema) for same. **Update:** [Here](https://codesandbox.io/s/exciting-haze-82j4q) is the working codesandbox. I've added checkbox with `display:none;`, and added the default state values in data context.
4,098,493
I need to find remote data such as RAM usage, swap usage, number of processors, etc, using a php script from the local computer and 10 other remote computers. How can I go about it? The remote computers are all running Linux, and they can run any service that is needed of the machine. What I have in mind is that I can somehow use ssh using the PHP script. Then use top or something to find what I need. It also needs to be a single PHP file that displays all the information.
2010/11/04
[ "https://Stackoverflow.com/questions/4098493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357538/" ]
I think you will probably want to look at PHP Expect, it allows you to do something like connect to a remote host, and provide input/responses to output on the remote. <http://us3.php.net/manual/en/book.expect.php>
9,909,932
Consider following code: ``` SwingWorker<Void, Void> sworker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(5); try { for (int j = 0; j < 5; j++) { Callable<Object> worker = new MyCallableImpl(); Future<Object> future = executor.submit(worker); array[j] = future.get(); } } catch (InterruptedException e) { // some code here } catch (ExecutionException e) { // some code here } // some code here executor.shutdown(); return null; } }; sworker.execute(); ``` As I said in the title: is this a good practice to invoke ExecutorService inside doInBackground() method of SwingWorker? It works for me (JDK1.7), GUI is not blocked and multiple threads from Executor pool are running in background, but still I have some doubts...
2012/03/28
[ "https://Stackoverflow.com/questions/9909932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/699908/" ]
It is entirely dependent on your compiler and architecture. In your case it looks as if the fields are indeed being 8-byte-aligned, perhaps for performance reasons.
61,308,766
I have a requirement where i want to skip all the upcoming tasks if a "Release artifacts" task is run. Release artifact task runs only if one of the variable is set to "true" while running the pipeline. ``` parameters: release: $(release) - task: Bash@3 displayName: Release artifacts condition: and(succeeded(), eq('${{ parameters.release }}', true)) inputs: targetType: 'inline' script: | # Write your commands here # Steps to release the artifacts ( gradle release plugin) gradle release -Prelease.useAutomaticVersion=true - task: Bash@3 - task: Bash@3 ``` Is there a way to exit/truncate the pipeline with exit code 0 ? I am looking for a functionality to skip all the upcoming tasks if one of the conditions is true without having to add that check in all the tasks ? Reason : gradle release will make modification to gradle.properties which will trigger CI again.
2020/04/19
[ "https://Stackoverflow.com/questions/61308766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768610/" ]
You may have a race condition which may cause undefined behavior. In create\_serv\_and\_init\_client() you define a local variable serv. The address of this variable is passed to the thread. When create\_serv\_and\_init\_client completes serv will go out of scope, even if the thread is still using it. As a result the value of serv may no longer be correct.
17,877
I once asked a question if the sentence > > jeder muss dafür verantwortlich sein, was er gesagt hat > > > is correct and was told that it is acceptable and that the verb must go at the end of its own clause before any subordinate clause. However, I was also told by a native speaker that this sentence could also be enclosed by one, like > > Jeder muss für das, was er gesagt hat, verantwortlich sein. > > > or > > Jeder ist für das, was er gesagt hat, verantwortlich. > > > I just wonder that in the first sentence above the verb 'sein' goes to the end of the entire sentence after the subordinate clause. It really annoys me how should I correctly build the German main clause and subordinate clause and is there a rule I can follow? And Take the following sentences. > > 1. Sobald ich Zeit habe, werde ich dir helfen. > 2. Ich werde dir helfen, sobald ich Zeit habe. > 3. Ich werde dir, sobald ich Zeit habe, helfen. > > > I can understand the first two sentences well but I still get confused by the third one.
2014/11/18
[ "https://german.stackexchange.com/questions/17877", "https://german.stackexchange.com", "https://german.stackexchange.com/users/9721/" ]
Don't let the third sentence type confuse you. The subordinate clause is an insertion and the outer sentence structure is not changed by it. The normal sentences would be > > Jeder ist für das verantwortlich. > > > Ich werde dir helfen. > > > The conjugated verb is at the second position as usual. The tricky part is were to insert the subordinate clauses. In the first example right after the part that is restricted by it. In the second example I would assume it is inserted behind the object. However, there are [dependent subordinate clauses](http://canoonet.eu/services/OnlineGrammar/Satz/Komplex/Ordnung/Subordination.html) which work differently.
64,606,542
Merge 2 dataframes. I have dataframe A that has a value in a non constant timestamp: ``` creation_time value_A 2020-09-22 00:00:35 83.0 2020-09-22 00:00:43 83.0 2020-09-22 00:02:20 82.0 2020-09-22 00:03:09 77.0 2020-09-22 00:03:04 77.0 2020-09-22 00:03:44 77.0 2020-09-22 00:07:10 71.0 ... 2020-10-23 11:42:31 136.0 2020-10-23 11:42:32 136.0 2020-10-23 11:42:35 136.0 2020-10-29 11:42:31 136.0 2020-10-29 11:42:32 136.0 2020-10-29 11:42:35 136.0 ``` and dataframe B. The first column is a range. For example, from 0 to 75 on 2020-09-22 the value\_B should be 60. ``` value_A_range creation_time value_B 0 2020-09-22 00:00:00.000000 60 75 2020-09-22 00:00:00.000000 65 124 2020-09-22 00:00:00.000000 300 143 2020-09-22 00:00:00.000000 360 0 2020-10-16 12:23:25.000000 60 75 2020-10-16 12:23:25.000000 400 124 2020-10-16 12:23:25.000000 400 143 2020-10-16 12:23:25.000000 450 0 2020-10-28 15:53:31.000000 10 82 2020-10-28 15:53:31.000000 30 114 2020-10-28 15:53:31.000000 40 129 2020-10-28 15:53:31.000000 60 139 2020-10-28 15:53:31.000000 110 ``` Expected result: Get value\_B for each timestamp in dataframe A. Match on range for value\_A on the available timestamp. ``` creation_time value_A value_B 2020-09-22 00:00:35 83.0 65 2020-09-22 00:00:43 83.0 65 2020-09-22 00:02:20 82.0 65 2020-09-22 00:03:09 60.0 60 2020-09-22 00:03:04 60.0 60 2020-09-22 00:03:44 60.0 60 2020-09-22 00:07:10 129.0 300 ... 2020-10-23 11:42:31 136.0 400 2020-10-23 11:42:32 156.0 450 2020-10-23 11:42:35 136.0 400 2020-10-29 11:42:31 85.0 30 2020-10-29 11:42:32 120.0 40 2020-10-29 11:42:35 160.0 110 ``` Resources I'm trying: [range](https://stackoverflow.com/questions/44367672/best-way-to-join-merge-by-range-in-pandas) and [merge\_asof](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html)
2020/10/30
[ "https://Stackoverflow.com/questions/64606542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6587020/" ]
Tensorflow isn't in the "defaults" anaconda channel. It is on conda-forge instead. In order to add conda-forge to your channels: 1. Click on "channels" (left of where you searched for tensorflow) 2. Click on "add" 3. Paste this URL in: <https://conda.anaconda.org/conda-forge/> 4. Press enter 5. Press "Update channels" 6. Now search again, and it should be there! [conda-forge added to channels](https://i.stack.imgur.com/4g29c.png) Source: <https://conda-forge.org/docs/user/introduction.html>
3,390,403
I'm designing a website for an organization that's a state chapter of a national organization. The national organization has implemented a member login that I need to use for the state website. My website is in PHP, and it looks like the server for the national organization is using SOAP and ColdFusion. I'm a total newbie to using SOAP, so I'm probably missing a bunch of things. The national organization sent me this information: > > Fields to collect on a form > > mausername > > mapassword > > > Static variables > > componenttype Value: Chapter > > components Value: NM > > authusername Value: NMChap > > authpassword Value: USA > > authpagealias Value: Login > > > The webservice is located here: > <https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL> > > > The following fields will be returned: > Email, FirstName, LastName, LoggedIn, Phone\_Release, UserName > > > If LoggedIn returns “true,” the member has been authenticated as a member of the component. > > > This has been implemented and tested here: <http://aptadevisg.apta.org/am/aptaapps/test/NM_Chap_test_form.cfm> > > > Based on this information and reading the SOAP documentation, this is what I came up with: ``` $apta_server = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/aptamemberauthorize.cfc?WSDL'; $post_data['mausername'] = '107150'; $post_data['mapassword'] = 'barnes'; $post_data['componenttype'] = 'Chapter'; $post_data['components'] = 'NM'; $post_data['authusername'] = 'NMChap'; $post_data['authpassword'] = 'USA'; $post_data['authpagealias'] = 'Login'; $options = array('trace' => 1, 'exceptions' => 0); $options['location'] = 'https://www.apta.org/AM/APTAAPPS/ComponentAuthWebService/MemberAuth'; try { $client = new soapclient($apta_server, $options); } catch (Exception $e) { } $client->debug_flag = 1; try { $result = $client->__soapCall('MemberAuth', array($post_data)); echo '<h1>Soap Result</h1><pre>'; print_r($result); echo '</pre>'; } catch (SoapFault $fault) { echo '<h1>Soap Fault</h1><pre>'; print_r($fault); echo '</pre>'; } echo '<pre>getFunctions<br>'; print_r($client->__getFunctions()); echo '</pre>'; echo '<pre>getTypes<br>'; print_r($client->__getTypes()); echo '</pre>'; echo '<pre>getLastResponseHeaders<br>'; print_r($client->__getLastResponseHeaders()); echo '</pre>'; echo '<pre>getLastResponse<br>'; print_r($client->__getLastResponse()); echo '</pre>'; ``` When I print out the result of the \_\_soapCall(), I get a message of: "looks like we got no XML document." I really don't know what I'm doing regarding SOAP, so any help would be greatly appreciated. You can view the results of the test login attempt at: <http://rc19.info/test_login.php>
2010/08/02
[ "https://Stackoverflow.com/questions/3390403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389803/" ]
If you are interested in finding out whether a variable has been declared regardless of its value, then using the `in` operator is the safest way to go. Consider this example: ``` // global scope var theFu; // theFu has been declared, but its value is undefined typeof theFu; // "undefined" ``` But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the `in` operator for a more robust check. ``` "theFu" in window; // true "theFoo" in window; // false ``` If you are interested in knowing whether the variable hasn't been declared or has the value `undefined`, then use the `typeof` operator, which is guaranteed to return a string: ``` if (typeof myVar !== 'undefined') ``` Direct comparisons against `undefined` are troublesome as `undefined` can be overwritten. ``` window.undefined = "foo"; "foo" == undefined // true ``` As @CMS pointed out, this has been patched in ECMAScript 5th ed., and `undefined` is non-writable. `if (window.myVar)` will also include these falsy values, so it's not very robust: ``` false 0 "" NaN null undefined ``` Thanks to @CMS for pointing out that your third case - `if (myVariable)` can also throw an error in two cases. The first is when the variable hasn't been defined which throws a `ReferenceError`. ``` // abc was never declared. if (abc) { // ReferenceError: abc is not defined } ``` The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example, ``` // or it's a property that can throw an error Object.defineProperty(window, "myVariable", { get: function() { throw new Error("W00t?"); }, set: undefined }); if (myVariable) { // Error: W00t? } ```
464,802
Take a look at this here: ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{align*} \Leftrightarrow \qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow \qquad e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{align*} \end{document} ``` Is it possible to have the equivalences below each other like the equations are? ``` \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \begin{document} \begin{alignat*}{4} P'_1(t)&=-\lambda P_1(t)+\lambda P_0(t)\\ \Leftrightarrow &&\qquad P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} && (2.6)\\ \Leftrightarrow && e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \\ \end{alignat*} \end{document} ``` This almost works but i have the mention problem that the first line is pulled to the very left.
2018/12/14
[ "https://tex.stackexchange.com/questions/464802", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/173831/" ]
Like so? ``` \documentclass{article} \usepackage{amsmath} \begin{document} \begin{align} \Leftrightarrow&& P'_1(t)+\lambda P_1(t)&=\lambda e^{-\lambda t} \tag{2.6} \\ \Leftrightarrow&& e^{\lambda t}P'_1(t)+\lambda e^{\lambda t}P_1(t)&=\lambda e^{\lambda t} e^{-\lambda t}=\lambda \notag \end{align} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/82Cbm.png)](https://i.stack.imgur.com/82Cbm.png)
40,368,293
I have a stylesheet that specifies a style for `<LABEL>`. But some `<LABEL>`s are special: Currently I inline style them like this: ``` <LABEL style="text-align:right; line-height:15pt"> <div style="padding-right:20px">My Label Text</div> </LABEL> ``` I suspect there's a way to specify a CSS class, perhaps called `rightlabel`, to render the preceding using something simple like this: ``` <LABEL class="rightlabel">My Label Text</LABEL> ``` What would the correct way be to do that? I.e., is there a way to define `rightlabel` in CSS to produce the overridden `<LABEL>` **while automatically wrapping its children in a padded child container** (because the style doesn't work correctly unless that is done, and it doesn't seem proper to depend on the coder to implement two elements to get the style right)? **Amendment:** I can get most of the way there using a child selector – as shown in [this fiddle](https://jsfiddle.net/c3h9a2b9/) with this CSS: ``` .rightLabel {text-align: right} .rightLabel > * {padding-right: 20px} ``` But I can't find a way to apply the padding to the label contents without explicitly wrapping the contents in some container. I.e., the above CSS works correctly on ``` <LABEL class="rightLabel"> <div>This is what we wanted!</div> </LABEL> ``` but not on ``` <LABEL class="rightLabel">Why am I not padded?</LABEL> ``` Is it possible to apply a style to the `<LABEL>` contents without explicitly coding them inside another HTML element (child)?
2016/11/01
[ "https://Stackoverflow.com/questions/40368293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2662901/" ]
Usually, faces stores indices of each triangle in the vertices array. So the first face is a triangle consisting of vertices[0], vertices[1], vertices[2]. The second one consists of vertices[3], vertices[4], vertices[5] and so on.
5,257,198
How can I measure time that ListView/ListActivity takes for rendering its list? I have a ListActivity that takes a long time to show (on older devices it's ~3s) and I'd like to optimize that. EDIT: I already have time between Activity1 and Activity2. During this time, Activity2 is doing some stuff (initializing). Among other things, it renders its list. I want to get time this activity takes to render that list. If total time between activities is 3s, I want to know whether rendering list takes 2.9s or 0.5s....
2011/03/10
[ "https://Stackoverflow.com/questions/5257198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133648/" ]
You could simply ouput the time. For example you could use the logcat ``` final long t0 = System.currentTimeMillis(); // code to measure Log.w(TAG, "TEXT" + System.currentTimeMillis()-t0); ``` Of course you could use any other system for the ouput like a dialog or stuff. Just use what you like. EDIT: If you don't want to use a debug message in your code all the time you could do it like this: Create a class called settings: ``` public class Settings { public static final boolean DEBUG = true; // If you prefer you could do use an enum // enum debugLevel {SHOW_EVERYMESSAGE, ERRORS, IMPORTANT_MESSAGES, ...} // In your classes you would have to check that DEBUG is less or equal than // the debugLevel you want } ``` In classes where you want to use a debug message simply do this ``` import xxx.yyy.Settings class foo { final static boolean DEBUG = Settings.DEBUG; if(DEBUG){ // Debug messages } } ``` Now if you want to disable DEBUG messages you could simply set `DEBUG = false` in your Settings class. If you want to measure between two activities you could use intents and send t0 with an intent to the other activity to compute the time. Of course you could include this with `if(DEBUG){ /* code */ }` statements to spare the sending of the intent in the final release. The if statements should not increase the computation of your code too dramatically.
26,871,085
I'm trying to save the contents of an entire Wordpress site using python and without ftp / server access. In other words, I want to save a "complete copy, or closest possible" of the Wordpress site to disk and I can't download everything from ftp / server. I've found some options to iterate through the various pages that make up the site, but nothing that will "save the site as a whole."
2014/11/11
[ "https://Stackoverflow.com/questions/26871085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114926/" ]
If you really want to use Python and nothing else, you could use [wpull](http://wpull.readthedocs.org/en/master/index.html), which is a wget clone written in Python. They have an example for archiving/downloading an entire website in their docs. ``` wpull billy.blogsite.example --warc-file blogsite-billy \ --no-check-certificate \ --no-robots --user-agent "InconspiuousWebBrowser/1.0" \ --wait 0.5 --random-wait --waitretry 600 \ --page-requisites --recursive --level inf \ --span-hosts --domains blogsitecdn.example,cloudspeeder.example \ --hostnames billy.blogsite.example \ --reject-regex "/login\.php" \ --tries inf --retry-connrefused --retry-dns-error \ --delete-after --database blogsite-billy.db \ --quiet --output-file blogsite-billy.log ```
9,960,908
I'm trying to write a function that does the following: * takes an array of integers as an argument (e.g. [1,2,3,4]) * creates an array of all the possible permutations of [1,2,3,4], with each permutation having a length of 4 the function below (I found it online) does this by taking a string as an argument, and returning all the permutations of that string I could not figure out how to modify it to make it work with an array of integers, (I think this has something to do with how some of the methods work differently on strings than they do on integers, but I'm not sure...) ``` let permArr = []; let usedChars = []; function permute(input) { const chars = input.split(""); for (let i = 0; i < chars.length; i++) { const ch = chars.splice(i, 1); usedChars.push(ch); if (chars.length === 0) { permArr[permArr.length] = usedChars.join(""); } permute(chars.join("")); chars.splice(i, 0, ch); usedChars.pop(); } return permArr }; ``` Note: I'm looking to make the function return arrays of *integers*, **not** an array of *strings*. I really need the solution to be in JavaScript. I've already figured out how to do this in python
2012/04/01
[ "https://Stackoverflow.com/questions/9960908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215474/" ]
If you notice, the code actually splits the chars into an array prior to do any permutation, so you simply remove the join and split operation ```js var permArr = [], usedChars = []; function permute(input) { var i, ch; for (i = 0; i < input.length; i++) { ch = input.splice(i, 1)[0]; usedChars.push(ch); if (input.length == 0) { permArr.push(usedChars.slice()); } permute(input); input.splice(i, 0, ch); usedChars.pop(); } return permArr }; document.write(JSON.stringify(permute([5, 3, 7, 1]))); ```
11,794,136
I'm facing the problem when i am creating database in SQL server management studio 2008. it is showing error that xpstar90.dll DLL find could not load (response 126).
2012/08/03
[ "https://Stackoverflow.com/questions/11794136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556859/" ]
The error `undefined local variable or method 'params'` clearly indicates that `params` are not available in your model. Also, it's not a good idea to use params in your models. See this question [Rails How to pass params from controller to after\_save inside model](https://stackoverflow.com/questions/4725185/rails-how-to-pass-params-from-controller-to-after-save-inside-model). Further, even if you got `params` in your model, `params[:wallet]` will not be available because that wasn't submitted from the web form. ``` # No 'wallet' key here. Parameters: {"utf8"=>"✓", "authenticity_token"=>"7rgoJQwWFFbo4Wv6gHF2AzwQpCQwB+Pp/kaNRw/YW/k=", "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"} ``` **UPDATE** Creating wallet without `params` ``` has_one :wallet, :dependent => :destroy after_create do |user| user.create_wallet end ```
3,277,745
I have a layout that looks like this: ``` .-------------------.u |#content |u '-------------------'u .-------------------.u |#menu |u '-------------------'u .-------------------.u |#morecontent vu | vu | vu '-------------------'u ``` `u`'s represent the body scrollbar and `v`'s the one created from `#morecontent`'s `overflow: auto` property. I have `#menu` contain dynamic data so sometimes it takes more than one line but right now `#morecontent` is sized to fit only one. How can I make the height of `#morecontent` adjust itself so it doesn't cause the `u` scrollbar to be scrollable or "enabled". I guess when I have more than one line? I know I should be using `%`'s and I tried using `max-height` but it didn't really work the way I wanted...
2010/07/19
[ "https://Stackoverflow.com/questions/3277745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Make sure that your div uses only max-height and min-height. Do not use height. If you want its height to go forever, don't set anything.
40,181,608
I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work. My PHP page: ``` <?php $servername = "10.10.10.10"; $username = "username"; $password = "password"; $dbname = "GENERIC_TABLES"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<br> WO Number ". $row["WO_NUM"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?> ``` So, WO\_NUM column has numbers like 1, 2, 3 etc. I want to get the last one + 1 So if I do like: ``` $sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1"; ``` Then it works fine, but if I want to make it WO\_NUM + 1 then it returns nothing. Why it happens like that and is there any way to get what I want using MySQL? I don't want to get WO\_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
2016/10/21
[ "https://Stackoverflow.com/questions/40181608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6743748/" ]
As you realized, `WO_NUM+1` changes the column name in the resulting array, so use an alias `WO_NUM+1 as NEW_NUM`. However I would not bother with the sorting and limit. Consider `MAX()`: ``` SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS ```
11,340,696
How can I remove multiple "[" in HTML Tag ID attribute with Regex? For example ``` <div id="test[12][45][67]">test inline [for example]</div> ``` Change to ``` <div id="test12]45]67]">test inline [for example]</div> ```
2012/07/05
[ "https://Stackoverflow.com/questions/11340696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409400/" ]
What you could (most likely should) do is to use a PHP HTML parser, such as [PHP Simple DOM Parser](http://simplehtmldom.sourceforge.net/) to go over the HTML, extract the ID value and then replace it using something like so: ``` <?php $string = <yourID> $pattern = '/\[/g'; $replacement = ''; echo preg_replace($pattern, $replacement, $string); ?> ``` This would allow you to *safely* modify only your `id` section in a relatively simple manner.
15,865,797
I want to add elements to my array through a user input. I know this can be done very easy using a list but i have to use an array. The problem with the code is that the array.lenght will always be 1. I want the array to have the same size as the total amount of elements in it, so size of the array shouldnt be set when declaring the array. I thought that if you add an element to an array it will copy the previous values + the added value and create a new array. UPDATED WITH ANSWER ``` public static void Add(int x){ if (Item == null) // First time need to initialize your variable { Item = new int[1]; } else { Array.Resize<int>(ref Item, Item.Length + 1); } Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1 } ```
2013/04/07
[ "https://Stackoverflow.com/questions/15865797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197276/" ]
Use `List<int>` instead of an explicit array, which will dynamically size for you, and use the Add() method to add elements at the end.
58,178,675
My goal is to make a small program/macro in VBA Excel that fixes column names automatically. The way I would like to do this is having `Subs` for each individual column name `cell`. Each of these `Subs` has an `Array` of Strings, which contain the keywords that will be searched. If the cells value is exactly one of the Strings, the value will be fixed. How they will be fixed, however, depends on the column name and that is why each of these subs will need to be created separately. Now, I've created the `Sub` which calls all the individual `cell` fixing `Subs`. I've also made the `Function` that tests if the corresponding `cell` contains one of the keywords. However, I can't figure out how to properly pass information about the `Array` of searchable Strings and the corresponding `cell` to the `Sub`. I'm getting a "Run-time error '13': Type mismatch" when I try to call the FindMatch() Function. ``` Function FindMatch(textArr() As String, cell As Range) As Boolean FindMatch = False Dim testCell As Range Dim i As Integer ' Range.Find() each string in the Array. If one of the Strings is found, FindMatch is true For i = 0 To UBound(textArr) Set testCell = cell.Find(What:=textArr(i), LookIn:=xlValues, LookAt:=xlWhole) If Not testCell Is Nothing Then FindMatch = True End If Next i End Function ``` It is called from here: ``` Sub FindCr(cell As Range) Dim match As Boolean match = False Dim textArr() As String ' I get the type mismatch error here. textArr = Array("Cr", "Bag ", " Dog") match = FindMatch(textArr, cell) If match Then ' Do stuff depending on the column, for example: HighlightRange cell End If End Sub ``` And here is the main Sub that calls the individual find-and-fix Subs. It is also called from a big main loop that goes through the whole range of column name cells. ``` Public Sub fixColumnNames(cell As Range) 'Do find-and-fix functions for all possible column names FindCr cell End Sub ``` Note, I didn't want to use a ParamArray because I also need to pass the `cell` in the FindMatch() Function. I believe ParamArray is used only for when there is an undefined amount of arguments in the call. I don't want the `cell` to go in the ParamArray. I tried changing the declarations of FindMatch and Dim textArr() to `As Variant`, but it really messes up the Range.Find() function. It started matching all kinds of wrong keywords when it was given a `Variant`. Like this: ``` Function FindMatch(textArr() As Variant, cell As Range) As Boolean ``` And ``` Dim textArr() As Variant textArr = Array("Cr", "Bag ", " Dog") match = FindMatch(textArr, cell) ``` So if you have an alternative approach for passing list of Strings to a Function with other additional arguments, please teach me. Or if you know what is causing the problems, help would be appreciated.
2019/10/01
[ "https://Stackoverflow.com/questions/58178675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12130762/" ]
I'm not exactly sure why you are having issues, but this is working just fine for me. Since you were having issues with `ParamArray`, I went ahead and incorporated that into the code for demonstration purposes. ``` Sub FindCr(cell As Range) If FindMatch(cell, "Cr", "Bag ", " Dog") Then MsgBox "There was a match!" End If End Sub Function FindMatch(ByVal cell As Range, ParamArray textArr() As Variant) As Boolean Dim i As Long For i = 0 To UBound(textArr) If Not cell.Find(What:=textArr(i), LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then FindMatch = True Exit Function End If Next End Function ``` I have shortened it a bit for you for readability. You never demonstrated what you were passing for your `Cell` argument, but make sure that you are fully qualifying the range. ``` Dim Cell As Range Set Cell = Thisworkbook.Worksheets(1).Range("A1") ``` would be an example of a fully qualified range.
64,531,838
I have this string where I need to extract only one word to put into a new columns. ``` HELLO WORLD TEST SHOES1 PROJECT ``` The required string is SHOES, but it has '1' beside it. How can I extract the SHOES only? Thank you
2020/10/26
[ "https://Stackoverflow.com/questions/64531838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14122835/" ]
``` $("#franchise").change(function() { //alert( $( "#franchise" ).val() ); var f = $( "#franchise" ).val(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: 'POST', url : 'ajax/series', data : ({franchise : f}), dataType: 'JSON', success: function(response) { $("#series").html(''); $("#series").append(response); } }); }); ```
154,695
There are two worlds of more or less equivalent technological level, say a difference of only a few decades and no more than 50 years. A first contact event occurs and after the hoopla dies down trading starts. Initially, barter is the primary form of trade but this quickly becomes cumbersome. How would the two economies first establish a currency exchange and exchange rate? Some commodities are similar and occur in similar quantities, particularly minerals gold, iron etc. Other commodities are unique to one civilization or the other; plants and animals unique to each planet, unique tech developed by one and not the other. Some restrictions: * Both planets have one currency or at least a dominant currency (like the USD) * Neither planet is in a "dominant" economic or technological position. * Travel between the planets takes a few days * There is a moderate level of trust in business dealings but it is not clear how laws apply to off worlders on each planet. Ideas I've toyed with: * comparable commodity-based exchange, ie. gold standard type exchanges, but this seems archaic for technologically advanced worlds and would anyone really want to transport heavy gold out of the gravity well of a planet * some type of crypto type exchange, but this seems problematic with distance and not very conducive to trade as the price fluctuates
2019/09/07
[ "https://worldbuilding.stackexchange.com/questions/154695", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/5101/" ]
You just pass laws on each world allowing the purchase and sale of the other world’s currency, with some sensible regulation to make sure people can’t get ripped off. Then the markets will establish the exchange rate and arrange the physical transport of any currency that actually needs to be moved, just like between two countries on Earth at present.
7,349,907
I'm developing software that will utilize a config file. I don't know many syntaxes or formats of config files. Here are the two I know: (common with .conf files) ``` [section] key=value #comment ``` or (common with .ini) ``` key value ; comment ``` My interest is something versatile that's almost a language. Let's say ``` [Default] Start = 0 End = 10 Speed = 1 [Section 3-6] Speed = 2 ``` This would act as an override. However this isn't any convention that I know of. Is there a common syntax that allows for this?
2011/09/08
[ "https://Stackoverflow.com/questions/7349907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425380/" ]
As of 2015, xml is no longer the de facto standard. Here are options. [TOML](https://github.com/toml-lang/toml) ``` # This is a TOML document. title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 [servers] # tabs / spaces ok but not required [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" ``` [YAML](https://yaml.org/) ``` %YAML 1.2 --- YAML: YAML Ain't Markup Language Projects: C/C++ Libraries: - libyaml # "C" Fast YAML 1.1 - Syck # (dated) "C" YAML 1.0 - yaml-cpp # C++ YAML 1.2 implementation ``` [CSON](https://github.com/bevry/cson) ``` # Comments!!! greatDocumentaries: [ 'earthlings.com' 'forksoverknives.com' ] importantFacts: # Multi-Line Strings! Without Quote Escaping! emissions: ''' Livestock and their byproducts account for at least 32,000 million tons of carbon dioxide (CO2) per year, or 51% of all worldwide greenhouse gas emissions. ''' ``` [JSON5](http://json5.org/) and [Human JSON](http://hjson.org/) - flexible json supersets [Properties File](http://en.wikipedia.org/wiki/.properties) - used by java programs
41,629,311
I have a list of lists. Each list should have 6 elements. There are cases in which my list only contains 1 element (*Check last element of following list*): ``` [['lemonade', '/g/11bz0dg4b_', '46.6522598267', 'Lemonade', 'Beyonc\xc3\xa9', 'en'], ['blank space', '/m/012d3qyr', '153.392837524', 'Blank Space', '', 'en'], ['radiolab', '/g/11b80zm_6d', '11.685131073', 'Radiolab', '', 'en'], ['migos t shirt']] ``` Hence I can easily do this and then append: ``` l = ['migos t shirt'] l += ['','','','',''] ll.append(l) ``` Is there a better/elegant way to do this? End goal is to use my list of lists with **csv.writerows** and want my file to have a consistent number of commas in this case 6 elements.
2017/01/13
[ "https://Stackoverflow.com/questions/41629311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260826/" ]
try this ``` ll = list(map(lambda x: x if len(x)==6 else x + ['']*(6-len(x)), ll)) ``` insipred by @Mike Müller`s answer ``` ll = list(map(lambda x: x + ['']*(6-len(x)), ll)) ``` with list comprehension ``` ll2 = [x + ['']*(6-len(x)) for x in ll] ```
30,537
***In Jeremiah, which dreams is God saying to not listen to?*** > > **NKJV, Jeremiah 29:8** - For thus says the Lord of hosts, the God of Israel: Do not let your prophets and your diviners who are in your midst deceive you, nor listen to your dreams which you cause to be dreamed. > > > In Hebrew, is God saying for Israel to not listen to any of their own dreams? Or, is God talking about a specific type of dream that is caused - perhaps through substances, lucid dreaming, or even daydreaming? In Hebrew, how should Jeremiah 29:8 be translated and then interpreted? * Should `"have dreamed"` be translated in 2nd, or 3rd Person Plural? `"... you all have dreamed"` ... or, `"... they have dreamed"`? * Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream? * Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams? **Or, can the verses be validly / reasonably translated in multiple ways?**
2017/11/19
[ "https://hermeneutics.stackexchange.com/questions/30537", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/6338/" ]
> > Should "have dreamed" be translated in 2nd, or 3rd Person Plural? "... you all have dreamed" ... or, "... they have dreamed"? > > > The word is מַחְלְמִים, which is a masculine plural participle (which might be translated as "dream" in the present, or "dreamer," but certainly not "have dreamed" - on the exact translation see below), undeclined for person. However, the word אַתֶּם before מַחְלְמִים unambiguously makes it a second person plural address, that "you" are doing, and not the prophets mentioned previously. > > Is the NKJV correct to imply an active sense of either making yourself dream, or even others causing themselves to dream? > > > The word מַחְלְמִים is in the *hiph'il* form, which usually means causing someone to do something. For the translation, some ancient versions (LXX, Peshitta) ignore the different form and translate it as "dream" (as if it said חוֹלְמִים), which might be a clue to confusion as how to translate, or possibly a different text (maybe it was erased due to being interpreted as an enclitic *mem*: rearranging the consonantal text gives אשר אתמ-ם חלמים). However, according to the Masorah and the Targum, which echoes the *hiph'il* form of the Hebrew, it seems to be saying "which you cause to dream." Some possible explanations: * The explanation you propose, causing dreams through substances, is very creative, and fits the grammar, but I don't recall any mention of causing dreams through substances in the Bible * One interpretation given is that "your dreams" are the dreams of the prophets with whom Jeremiah is disputing, and they are called "your dreams" because the people listened to them, and without their encouragement they wouldn't have continued to have those dreams ([Radaq](https://en.wikipedia.org/wiki/David_Kimhi)). This interpretation is seen as well in the NIV translation "Do not listen to the dreams you encourage them to have." * I would like to propose reading מְחַלְּמִים in the *pi''el* form, by analogy to מְאַהֵב (e.g. in Hosea 2:9), which differs from the *qal* אוֹהֵב "lover" with the meaning "improper lover." Maybe מְחַלְּמִים could also mean having an *improper* dream > > Is the NASB correct to imply that Israel was no longer to listen to anyone's dreams? > > > No. Jeremiah said the exile would last 70 years (29:10), and told them to build houses, marry, and pray for the welfare of their city (29:5-7). Other prophets were making the claim that the exile would be short and they would return to their land soon (28:3). This is the claim Jeremiah was disputing, which is far from saying "no longer to listen to anyone's dreams." The dreams referred to here are those of a "חֹלֵם חֲלוֹם" ("dreamer," Deuteronomy 13:2, in apposition to "נָבִיא," prophet). He was disputing very specific prophetic dreams, just as he disputes other prophets many other times in the book. The Greek and Aramaic translations tend to translate this sort of prophet as "false prophet" (unlike the Hebrew, which never says "false prophet"), and "dreams" in this context should be understood as "false dreams" - i.e., specifically the dreams Jeremiah was disputing. He is not addressing the reliability of dreams in general.
4,672,619
Yahoo blocks emails from our website. We've written them to reverse that decision without much luck. So we block site registrations from @yahoo.com emails. Our problem is Yahoo has other email domains besides @yahoo.com. For instance @ymail.com, @rocketmail.com, @btinternet.com, and I'm sure many more. Plus international domains. So the question is, how do I check if an email domain belongs to Yahoo? I supposed I could try to find a definitive list of all Yahoo domains, but I'm sure there has to be a better way. For instance doing some kind of host lookup on the domain. Are there any suggestions to do that in PHP?
2011/01/12
[ "https://Stackoverflow.com/questions/4672619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401019/" ]
Definitive list is probably the best way to go. You don't want to have to do some kind of lookup every time someone registers for your site. But if you really don't want to use a static list, you should be able to use `getmxrr()` and see if the MX record is from yahoo.
52,335,378
I'm new to RxJS observables and I'm trying to resolve a rather simple use case. In a service, I first make a http call that returns an item (as an observable). The item contains an array of ids, some of them repeated. For each distinct id, I need to call another http service (again returns an observable), and add its return value to the original item in place of the corresponding id. These calls should happen in parallel. Finally, once every call has completed, my service should return an observable of the original item, now with its sub-items in place. To give a better idea, this is what it would look like with promises rather than observables: ``` MyService() { return HttpGetMainItem() .then(item => { var promises = _.uniq(item.subItems) .map(sid => HttpGetSubItem(sid) .then(subItem => { // add to matching item.subItems })); // wait for all promises to complete and return main item return Promise.all(promises).then(() => item); }); } ``` What would be the best way to accomplish this working with observables? EDIT: from the answers it seems I wasn't very clear. The example with promises is just for clarity, in my case the http calls are actually Angular's HttpClient.get, so they return observables- I'm looking to do everything with observables.
2018/09/14
[ "https://Stackoverflow.com/questions/52335378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463893/" ]
Here's one way you can accomplish the above with rxjs. 1. Convert the promise to an observable using `from`. 2. In the outer pipe call `switchMap` so that you can call another observable and return that as the result of the outer observable. You're switching execution contexts. 3. Inside the switchMap do the map of subItems as you did before and then use `forkJoin` to create an Observable of all the elements' promise. ForkJoin will emit an array of all the results once all promise complete. It's like `promise.all`. 4. Add the items like you were planning to do before, and return the original item. **Code** ``` from(HttpGetMainItem()).pipe( switchMap(item => forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid))) .pipe( map(results => { /* add results to matching items.subItems and */ return item; }) ) ) ); ``` I feel this looks a bit clunky, due to the need to retain the root item and the nesting it requires. You can use the selector parameter of switchMap to combine the outer and inner observable. You can use that parameter in place of the logic you had in `map()` and since both observables' results are passed you won't need any further nesting. ``` from(HttpGetMainItem()).pipe( switchMap( item => forkJoin(_.uniq(item.subItems).map(sid => HttpGetSubItem(sid))), (item, results) => { /* add results to matching items.subItems and */ return item; } ) ); ```
20,628,700
I have the following (working) XAML for a ComboBox: ``` <ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items}"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Converter={StaticResource MyEnumToStringConverter}}"/> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox> ``` I don't like this code: In order to change how my enum is represented as a string, I also have to specify the look of the ComboBox ItemTemplate. What if I want to globally change the appearance of all my ComboBoxes? Another solution is to specify the converter on the ItemSource binding: ``` <ComboBox SelectedValue="{Binding SelectedItem}" ItemsSource="{Binding Items, Converter={StaticResource MyEnumToStringConverter}}" /> ``` I don't like this either since I want the ComboBox to store my real type, not the string representation of it. What other alternatives do I have?
2013/12/17
[ "https://Stackoverflow.com/questions/20628700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/617658/" ]
It is not necessary to set the `ItemTemplate` of each ComboBox, either in a Style or not. Instead you could simply create a default DataTemplate for the enum type by setting its [DataType](http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx) property ``` <Window.Resources> <local:MyEnumStringConverter x:Key="MyEnumStringConverter"/> <DataTemplate DataType="{x:Type local:MyEnum}"> <TextBlock Text="{Binding Converter={StaticResource MyEnumStringConverter}}"/> </DataTemplate> ... </Window.Resources> ```
1,818,862
``` public AddressBookApp(){ frame = new JFrame("Address Book"); frame.setSize(500, 400); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setBackground(Color.gray); panel.setLayout(null); frame.add(panel); frame.setVisible(true); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu file = new JMenu("File"); menubar.add(file); JMenuItem insert = new JMenuItem("Import"); file.add(insert); insert.addActionListener(this); JMenuItem export = new JMenuItem("Export"); file.add(export); export.addActionListener(this); JMenuItem exit = new JMenuItem("Exit"); file.add(exit); exit.addActionListener(this); Font f = new Font("Helvetica", Font.BOLD, 10); btnadd = new JButton("Add"); btnadd.setFont(f); btnadd.setBounds(200, 250, 80, 20); panel.add(btnadd); btnprev = new JButton("Previous"); btnprev.setBounds(40, 250, 80, 20); btnprev.setFont(f); btnprev.addActionListener(this); panel.add(btnprev); btnnxt = new JButton("Next"); btnnxt.setBounds(120, 250, 80, 20); btnnxt.setFont(f); btnnxt.addActionListener(this); panel.add(btnnxt); btndel = new JButton("Delete"); btndel.setBounds(280, 250, 80, 20); btndel.setFont(f); panel.add(btndel); btnclear = new JButton("Clear"); btnclear.setBounds(360, 250, 80, 20); btnclear.setFont(f); btnclear.addActionListener(this); panel.add(btnclear); txtname = new JTextField(""); txtname.setBounds(210, 40, 160, 20); txtname.setFont(f); panel.add(txtname); txtnum = new JTextField(""); txtnum.setBounds(210, 70, 160, 20); txtnum.setFont(f); panel.add(txtnum); txtmob = new JTextField(""); txtmob.setBounds(210, 100, 160, 20); txtmob.setFont(f); panel.add(txtmob); txtadd1 = new JTextField(""); txtadd1.setBounds(210, 130, 160, 20); txtadd1.setFont(f); panel.add(txtadd1); lblname = new JLabel("Name"); lblname.setBounds(160, 40, 160, 20); lblname.setFont(f); panel.add(lblname); lblnum = new JLabel("Number"); lblnum.setBounds(160, 70, 160, 20); lblnum.setFont(f); panel.add(lblnum); lblmob = new JLabel("Mobile"); lblmob.setBounds(160, 100, 160, 20); lblmob.setFont(f); panel.add(lblmob); lbladd1 = new JLabel("Address "); lbladd1.setBounds(160, 130, 160, 20); lbladd1.setFont(f); panel.add(lbladd1); } public static void main(String[] args) { AddressBookApp ab = new AddressBookApp(); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Exit")) System.exit(0); else if (e.getActionCommand().equals("Import")) { importContacts(); } else if (e.getActionCommand().equals("Export")); { exportContacts(); } if (e.getSource() == btnnxt) { nextContact(); } else if (e.getSource() == btnprev) { prevContact(); } } public void importContacts() { try{ BufferedReader fileSize = new BufferedReader(new FileReader("../files/example.buab")); BufferedReader importContacts = new BufferedReader(new FileReader("../files/example.buab")); int i = 0; String contacts; while (( fileSize.readLine()) !=null) { details.add(importContacts.readLine()); i++; } fileSize.close(); int x = 0; int y = 0; for (x = 0, y = 0; x < details.size(); x++, y++) { if (y == 4) { y = 0; } if (y == 0) { name.add(details.get(x)); } if (y == 1) { phone.add(details.get(x)); } if (y == 2) { mobile.add(details.get(x)); } if (y == 3) { address.add(details.get(x)); } } } catch (IOException ioe) { ioe.printStackTrace(); } txtname.setText(name.get(0)); txtnum.setText(phone.get(0)); txtmob.setText(mobile.get(0)); txtadd1.setText(address.get(0)); } public void exportContacts() { FileOutputStream file; PrintStream out; try { file = new FileOutputStream("../files/example.buab", true); out = new PrintStream(file); out.println(txtname.getText()); out.println(txtnum.getText()); out.println(txtmob.getText()); out.println(txtadd1.getText()); System.err.println (""); out.close(); } catch (Exception e) { System.err.println ("Error in writing to file"); } } public void nextContact() { if(index < details.size() - 1) { index++; txtname.setText(name.get(index)); txtnum.setText(phone.get(index)); txtmob.setText(mobile.get(index)); txtadd1.setText(address.get(index)); } importContacts(); } public void prevContact() { if (index > 0) { index--; txtname.setText(name.get(index)); txtnum.setText(phone.get(index)); txtmob.setText(mobile.get(index)); txtadd1.setText(address.get(index)); } importContacts(); } ``` }
2009/11/30
[ "https://Stackoverflow.com/questions/1818862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221246/" ]
From the code I see no reason, why it should export data after pressing the next or previous button. Don't forget to close the streams after reading. Just for curiosity - I've seen a lot of partial solutions to this assignment from various new SO users - and they have in common, that the assignees *seems* to lack some basic OO knowledge. Who advised you to drop the contact details in separate lists rather then inventing a Contact class that holds all contact attributes and dropping contact objects in a single (sortable) list? Have you been forced to avoid classes or has your teacher simply left you alone, finding it out yourself? Good luck anyway :)
57,512
I plan on building a web based room booking application for meeting rooms at a company. The requirements are not set in stone and are pretty much left to me, as long as these core ones are met: 1. Users can view monthly schedule for meeting room, so see what days and times there are bookings for a particular room. 2. Users can book a meeting room 3. Users can edit,delete a booking once made. 4. Receptionists have power to cancel bookings, even though they were not the ones that made them. If I have missed any obvious ones, please point them out. So with the above in mind, I have come up with the following ERD. ![erd room booking](https://i.stack.imgur.com/xLDZs.jpg) Can you see any obvious issues with the above ERD? I have gone through the above scenarios / requirements, and I believe the above design satisfies them all, but it is possible that I am very much mistaken (has happened before). Any help and feedback would be greatly appreciated.
2014/01/24
[ "https://dba.stackexchange.com/questions/57512", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/20381/" ]
How do you know how long a room is booked for? Your model indicates when a booking starts, but when does it end? Also, your ERD shows foreign keys from `BOOKING` to `USER` and `ROOM` but these columns aren't acknowledged in your `BOOKING` table. Some other answers have interpreted that as the columns being missing. You should be explicit in your diagram to avoid confusion (or add the FK columns if you missed them!)
16,976,335
Assume we constructed a quicksort and the pivot value takes linear time. Find the recurrence for worst-case running time. My answer: T(n)= T(n-1) + T(1) + theta(n) Worst case occurs when the subarrays are completely unbalanced. There is 1 element in one subarray and (n-1) elements in the other subarray. theta(n) because it takes running time n to find the pivot. Am I doing this correctly?
2013/06/07
[ "https://Stackoverflow.com/questions/16976335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1855045/" ]
Your recurrence is mostly correct, but you don't actually have two recursive calls made. In the worst-case for quicksort, the pivot will be the largest or smallest element in the array, so you'll recur on one giant array of size n - 1. The other subarray has length 0, so no recursive calls are made. To top everything off, the total work done is Θ(n) per level, so the recurrence relation would more appropriately be > > T(n) = T(n - 1) + Θ(n) > > > This in turn then solves to Θ(n2). Hope this helps!
18,393,312
I have a simple button, and I want to use CSS to make it onhover, bring up a dropdown of a few more buttons with links, and when the button is pressed I want the button to stay at the onhover state. How can this be accomplished? For example a games button that when hovered over it drops down to buttons that have different links to games. Sorry if this is unclear. Thanks in advanced.
2013/08/23
[ "https://Stackoverflow.com/questions/18393312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2565624/" ]
When you make those two synchronized, the getter and setter themselves are thread-safe. More specifically: - When you call the setter, you are guaranteed that the value of the variable is what you set it to when the method finishes. - When you call the getter, you are guaranteed that the return value is the value of the variable when you made the call. However, making the getter and setter *themselves* thread-safe does not mean that the application *as a whole* (i.e. whatever is using this class) is thread-safe. If your thread wants to call a setter then get the same value upon invoking the getter, that involves synchronization on a different level. As far as thread-safety is concerned, a thread-safe class need not control **how** its methods are invoked (for example, it need not control which way the threads interleave their calls), but it needs to ensure that **when** they are, the methods do what they are supposed to.