text
stringlengths
70
452k
dataset
stringclasses
2 values
Reducing a boolean expression with nested ternary expression Consider the following boolean expression with a nested ternary expression: $$(\text{if $a < 0$ then $-a$ else $a$}) < 3$$ I can "see" that it can be reduced to: $$a > -3 \land a < 3$$ However, I can't figure out the algebraic rules I need to apply in order to arrive at the reduced expression. I got as far as: $$(\text{if $a < 0$ then $-a$ else $a$}) < 3$$ $$\text{if $a < 0$ then $-a < 3$ else $a < 3$}$$ $$\text{if $a < 0$ then $a > -3$ else $a < 3$}$$ $$(a < 0 \land a > -3) \lor (\lnot(a < 0) \land a < 3)$$ $$(a < 0 \land a > -3) \lor (a \ge 0 \land a < 3)$$ But that's where I'm stuck. I think somewhere in between I should arrive at: $$(a < 0 \lor a \ge 0) \lor (a > -3 \land a < 3)$$ Or maybe: $$(a < 0 \lor a \ge 0) \land (a > -3 \land a < 3)$$ Because then the term $(a < 0 \lor a \ge 0)$ would cancel out. So I tried my way backwards from there, but I still no luck. I feel like I'm missing something quite simple. You are almost there: From: $$(a < 0 \land a > -3) \lor (a \ge 0 \land a < 3)$$ Distribute (FOIL, basically): $$(a < 0 \lor a \ge 0) \land (a < 0 \lor a < 3) \land (a > -3 \lor a < 3) \land (a > -3 \lor a \ge 0)$$ Now, as you say, $(a < 0 \lor a \ge 0)$ is a mathetical truth, and so can be ignored: $$ (a < 0 \lor a < 3) \land (a > -3 \lor a < 3) \land (a > -3 \lor a \ge 0)$$ Also, since $a < 0$ implies $a<3$, the term $(a < 0 \lor a < 3)$ reduces to the weakest claim, i.e. to $a < 3$. Likewise, $(a > -3 \lor a \ge 0)$ reduces to $a > -3$: $$ a < 3 \land (a > -3 \lor a < 3) \land a > -3 $$ Finally, if $a < 3$ and $a > -3$, then certainly $(a > -3 \lor a < 3)$, so that middle term can be completely removed, leaving you with: $$ a < 3 \land a > -3 $$ Now, note that this transformation was not a purely logical transformation, but that is because the equivalence between your original statement and the statement $ a < 3 \land a > -3 $ is indeed 'merely' a mathematical equivalence, and not a logical one. For, example, $(a < 0 \lor a \ge 0)$ is a mathematical truth, and not a logical one. Thanks for the detailed explanation! Your point about logical vs mathematical truth seems interesting. Do you have some pointers where I could read up on that? @GoodNightNerdPride No pointers, really. Just remember that in logic, only the purely logical operators, like $\land$, $\lor$, $\neg$, or $\forall$ have a fixed meaning. A mathematical relationship, like $<$, however, is in the eyes of logic 'just some 2-place relationship'. And even the constant $0$ is 'just some object from some domain' \begin{equation} (a < 0 \land a > -3) \lor (a \ge 0 \land a < 3) \\ (a < 0 \lor a \ge 0) \land (a < 0 \lor a < 3) \land (a > -3 \lor a \ge 0) \land (a > -3 \lor a < 3) \\ 1 \land (a < 3) \land (a > -3) \land 1 \\ (a < 3) \land (a > -3) \end{equation} @Bram28 $a > -3 \vee a < 3$ is indeed true of all real numbers. @FabioSomenzi Wow, brain fart! :P
common-pile/stackexchange_filtered
"The C compiler "/usr/bin/cc" is not able to compile a simple test program." I installed Cygwin64 and everything is fine in Toolchains 1, even the C Compiler is ticked. But I get these errors whenever I create a new project and 'Run' and 'Debug' buttons are grayed-out from the get go; Error:The C compiler "/usr/bin/cc" is not able to compile a simple test program. It fails with the following output: Change Dir: /cygdrive/c/Users/J/.CLion2016.2/system/cmake/generated/untitled132-5df26809/5df26809/__default__/CMakeFiles/CMakeTmp Run Build Command:"/usr/bin/make.exe" "cmTC_7ca0a/fast" C:/cygwin64/bin/make.exe: error while loading shared libraries: cygguile-17.dll: cannot open shared object file: No such file or directory CMake will not be able to correctly generate this project. Error:Configuration Debug The C compiler "/usr/bin/cc" is not able to compile a simple test program. It fails with the following output: Change Dir: /cygdrive/c/Users/J/.CLion2016.2/system/cmake/generated/untitled132-5df26809/5df26809/Debug/CMakeFiles/CMakeTmp Run Build Command:"/usr/bin/make.exe" "cmTC_7db24/fast" C:/cygwin64/bin/make.exe: error while loading shared libraries: cygguile-17.dll: cannot open shared object file: No such file or directory CMake will not be able to correctly generate this project. Error:Configuration Release The C compiler "/usr/bin/cc" is not able to compile a simple test program. It fails with the following output: Change Dir: /cygdrive/c/Users/J/.CLion2016.2/system/cmake/generated/untitled132-5df26809/5df26809/Release/CMakeFiles/CMakeTmp Run Build Command:"/usr/bin/make.exe" "cmTC_fe477/fast" C:/cygwin64/bin/make.exe: error while loading shared libraries: cygguile-17.dll: cannot open shared object file: No such file or directory CMake will not be able to correctly generate this project. Error:Configuration RelWithDebInfo The C compiler "/usr/bin/cc" is not able to compile a simple test program. It fails with the following output: Change Dir: /cygdrive/c/Users/J/.CLion2016.2/system/cmake/generated/untitled132-5df26809/5df26809/RelWithDebInfo/CMakeFiles/CMakeTmp Run Build Command:"/usr/bin/make.exe" "cmTC_c2ddb/fast" C:/cygwin64/bin/make.exe: error while loading shared libraries: cygguile-17.dll: cannot open shared object file: No such file or directory CMake will not be able to correctly generate this project. Error:Configuration MinSizeRel The C compiler "/usr/bin/cc" is not able to compile a simple test program. It fails with the following output: Change Dir: /cygdrive/c/Users/J/.CLion2016.2/system/cmake/generated/untitled132-5df26809/5df26809/MinSizeRel/CMakeFiles/CMakeTmp Run Build Command:"/usr/bin/make.exe" "cmTC_827b4/fast" C:/cygwin64/bin/make.exe: error while loading shared libraries: cygguile-17.dll: cannot open shared object file: No such file or directory CMake will not be able to correctly generate this project. I think cygguile-17.dll isn't in your windows path environment variable. where can I have it? Its probably: C:/cygwin64/bin Take a look in explorer. Then make sure that you have that in your windows environment variable PATH. I don't have it. Is it something downloadable from cygwin? I don't have in my entire system. So where to get it? I think you want to update cygwin. I actually downloaded all devel category from cygwin. What can I miss? cygguile-17.dll belongs to libguile17 package. Reistall it. Use https://cygwin.com/packages/ for this type of search
common-pile/stackexchange_filtered
Permission issue on sysfs access from android application ( .java source code ) Android application in java having permission issues when accessing sysfs entry. try{ FileOutputStream fos = new FileOutputStream("/sys/class/shift_reg/shift_reg/value"); byte mybyte = 1; fos.write(mybyte); fos.close(); } catch ( Exception e) { Log.d(TAG, "Failed in writing to Shift Register"); <------- I am always getting this exception. } 1) Have tried putting 'setenforce 0'. Does't work. Even though enforce level is permissive. 2) Do I have to access using JNI way: ( android-app -> jni -> driver ) 3) I have set file permission as 0777 for the sysfs node file. Dmesg Error message: [ 417.176302] type=1400 audit(418.589:63): avc: denied { write } for pid=3164 comm="com.android.cam" name="value" dev="sysfs" ino=9749 scontext=u:r:untrusted_app:s0 tcontext=u:object_r:sysfs:s0 tclass=file permissive=1 ps -Z u:r:untrusted_app:s0 u0_a67 4360 333 com.android.cam Following are some of the options I came across. 1. Direct access from the application [ Android Application(.java) -> jni -> driver ] Do I need to implement jni. [Doubt] Will the jni solution will not have same permission issue as only java application. [Ans]This won’t work. 2. Signing my application as 'platform_app'. Currently it shows as 'untrusted_app' [Ans] Platform app is still in app domain. This won’t work. 3. Using any existing android hardware API. Would it possible to reuse something from existing ones( modifying something from existing ones ) 1) android.hardware 2) android.hardware.input [Ans] Yes. Probably easiest way but be careful not to conflict with other modules that use the HAL you are modifying. 4. Adding a new custom system service I believe there are 2 options of adding a system service 1) Adding inside the System Server 2) Adding outside of the System Server [Ans] Yes. One of proper solutions. 5. Will developing the app using NDK help with permissions [Ans] An app is still in app domain. You will not get permissions. Note: System service implementations github: https://github.com/opersys/opersys-hal-hw
common-pile/stackexchange_filtered
stm32 NVIC_EnableIRQ() bare metal equivalent? I'm using the blue pill, and trying to figure out interrupts. I have an interrupt handler: void __attribute__ ((interrupt ("TIM4_IRQHandler"))) myhandler() { puts("hi"); TIM4->EGR |= TIM_EGR_UG; // send an update even to reset timer and apply settings TIM4->SR &= ~0x01; // clear UIF TIM4->DIER |= 0x01; // UIE } I set up the timer: RCC_APB1ENR |= RCC_APB1ENR_TIM4EN; TIM4->PSC=7999; TIM4->ARR=1000; TIM4->EGR |= TIM_EGR_UG; // send an update even to reset timer and apply settings TIM4->EGR |= (TIM_EGR_TG | TIM_EGR_UG); TIM4->DIER |= 0x01; // UIE enable interrupt TIM4->CR1 |= TIM_CR1_CEN; My timer doesn't seem to activate. I don't think I've actually enabled it though. Have I?? I see in lots of example code commands like: NVIC_EnableIRQ(USART1_IRQn); What is actually going in NVIC_EnableIRQ()? I've googled around, but I can't find actual bare-metal code that's doing something similar to mine. I seem to be missing a crucial step. Update 2020-09-23 Thanks to the respondents to this question. The trick is to set the bit for the interrupt number in an NVIC_ISER register. As I pointed out below, this doesn't seem to be mentioned in the STM32F101xx reference manual, so I probably would never have been able to figure this out on my own; not that I have any real skill in reading datasheets. Anyway, oh joy, I managed to get interrupts working! You can see the code here: https://github.com/blippy/rpi/tree/master/stm32/bare/04-timer-interrupt Details related to Cortex core are generally mentioned in the "Programming Manual", not in the "Reference Manual". Found description of the NVIC registers here: https://booksite.elsevier.com/9780124080829/downloads/APP-06.pdf NVIC->ISER[1] |= (1 << (EXTI15_10_IRQn - 32)); // EXTI15_10_IRQn is 40, so ISER[1] and bit position 8 Even if you go bare metal, you might still want to use the CMSIS header files that provide declarations and inline version of very basic ARM Cortex elements such NVIC_EnableIRQ. You can find NVIC_EnableIRQ at https://github.com/ARM-software/CMSIS_5/blob/develop/CMSIS/Core/Include/core_cm3.h#L1508 It's defined as: #define NVIC_EnableIRQ __NVIC_EnableIRQ __STATIC_INLINE void __NVIC_EnableIRQ(IRQn_Type IRQn) { if ((int32_t)(IRQn) >= 0) { __COMPILER_BARRIER(); NVIC->ISER[(((uint32_t)IRQn) >> 5UL)] = (uint32_t)(1UL << (((uint32_t)IRQn) & 0x1FUL)); __COMPILER_BARRIER(); } } If you want to, you can ignore __COMPILER_BARRIER(). Previous versions didn't use it. The definition is applicable to Cortex M-3 chips. It's different for other Cortex versions. With the libraries is still considered bare metal. Without operating system, but anyway, good that you have a desire to learn at this level. Someone has to write the libraries for others. I was going to do a full example here, (it really takes very little code to do this), but will take from my code for this board that uses timer1. You obviously need the ARM documentation (technical reference manual for the cortex-m3 and the architectural reference manual for armv7-m) and the data sheet and reference manual for this st part (no need for programmers manual from either company). You have provided next to no information related to making the part work. You should never dive right into a interrupt, they are advanced topics and you should poll your way as far as possible before finally enabling the interrupt into the core. I prefer to get a uart working then use that to watch the timer registers when the roll over, count, etc. Then see/confirm the status register fired, learn/confirm how to clear it (sometimes it is just a clear on read). Then enable it into the NVIC and by polling see the NVIC sees it, and that you can clear it. You didn't show your vector table this is key to getting your interrupt handler working. Much less the core booting. 08000000 <_start>: 8000000: 20005000 8000004: 080000b9 8000008: 080000bf 800000c: 080000bf ... 80000a0: 080000bf 80000a4: 080000d1 80000a8: 080000bf ... 080000b8 <reset>: 80000b8: f000 f818 bl 80000ec <notmain> 80000bc: e7ff b.n 80000be <hang> ... 080000be <hang>: 80000be: e7fe b.n 80000be <hang> ... 080000d0 <tim1_handler>: The first word loads the stack pointer, the rest are vectors, the address to the handler orred with one (I'll let you look that up). In this case the st reference manual shows that interrupt 25 is TIM1_UP at address 0x000000A4. Which mirrors to 0x080000A4, and that is where the handler is in my binary, if yours is not then two things, one you can use VTOR to find an aligned space, sometimes sram or some other flash space that you build for this and point there, but your vector table handler must have the proper pointer or your interrupt handler won't run. volatile unsigned int counter; void tim1_handler ( void ) { counter++; PUT32(TIM1_SR,0); } volatile isn't necessarily the right way to share a variable between interrupt handler and foreground task, it happens to work for me with this compiler/code, you can do the research and even better, examine the compiler output (disassemble the binary) to confirm this isn't a problem. ra=GET32(RCC_APB2ENR); ra|=1<<11; //TIM1 PUT32(RCC_APB2ENR,ra); ... counter=0; PUT32(TIM1_CR1,0x00001); PUT32(TIM1_DIER,0x00001); PUT32(NVIC_ISER0,0x02000000); for(rc=0;rc<10;) { if(counter>=1221) { counter=0; toggle_led(); rc++; } } PUT32(TIM1_CR1,0x00000); PUT32(TIM1_DIER,0x00000); A minimal init and runtime for tim1. Notice that the NVIC_ISER0 is bit 25 that is set to enable interrupt 25 through. Well before trying this code, I polled the timer status register to see how it works, compare with docs, clear the interrupt per the docs. Then with that knowledge confirmed with the NVIC_ICPR0,1,2 registers that it was interrupt 25. As well as there being no other gates between the peripheral and the NVIC as some chips from some vendors may have. Then released it through to the core with NVIC_ISER0. If you don't take these baby steps and perhaps you have already, it only makes the task much worse and take longer (yes, sometimes you get lucky). TIM4 looks to be interrupt 30, offset/address 0x000000B8, in the vector table. NVIC_ISER0 (0xE000E100) covers the first 32 interrupts so 30 would be in that register. If you disassemble the code you are generating with the library then we can see what is going on, and or look it up in the library source code (as someone already did for you). And then of course your timer 4 code needs to properly init the timer and cause the interrupt to fire, which I didn't check. There are examples, you need to just keep looking. The minimum is vector in the table set the bit in the interrupt set enable register enable the interrupt to leave the peripheral fire the interrupt Not necessarily in that order. Aha! OK, that gave me enough clues to make it work. I can't see NVIC_ISER0 in the datasheets, so I'm a little confused. Nevertheless, it seems that the address is 0xE000E100 - which I got from googling around. I just need to set the bit with the interrupt number I'm trying to set. I will update my original question. Many thanks.
common-pile/stackexchange_filtered
Why do we have a tag Arduino and Raspberry Pi if we have special SE sites for that? We have SE sites specialized on Arduino and Raspberry Pi. Why should we have these tags here?Why not to migrate all questions about Arduino and Raspberry Pi there? You can get an answer more faster there. Or maybe these tags on SO for special questions about programming? Questions for those devices can still be valid on Stack Overflow even with those sites in operation. In general it is possible for a question to be valid on multiple sites but it is discouraged from cross posting the question on multiple sites. Related: Can we please move all vim questions to vi.stackexchange.com? The number of eyes that see things posted on SO is orders of magnitude higher than the eyes that would see questions on either one of those sites. And, I suspect, the people asking the questions are fortunate to have found SO and don't have a clue about the other sites. "You can get an answer more faster there." - hmm, I don't think so. You may get a really dedicated answer a little quicker, maybe. The really hard to write kind, I can see how on a dedicated site you have a higher chance of a topic expert to write a really comprehensive answer if you are lucky enough that those experts want to make the dedicated site a big success and thus patrol it regularly. "New contributor"...? Pretty sure I've seen you before. Same nick, same avatar, etc...? @yivi I recreated my profile as I got blocked from asking questions. Deletion and recreation generally doesn't lift the ban; you're still going to encounter difficulties while posting. They might be slightly looser than they were, but they're still there. @fbueckert Well, I'll try to do my best not to get blocked again. There are two very distinct reasons for this. Stack Overflow existed well before either of those network sites did. Those who actually do programming work on an Arduino or Raspberry Pi are perfectly comfortable asking their questions here, and we're perfectly comfortable with answering them. A programming question involving either Arduino or Raspberry Pi here is not off-topic. We welcome programming questions. What we don't discuss here is the hardware aspect of working with these boards. Migrating these questions wouldn't do any good, since we don't migrate questions older than 60 days anywhere at all (it is technically a hurdle to do it - only employees could and they generally don't), and there's no guarantee that the questions we're migrating would actually get the attention they need to begin with. Best to leave 'em here. Just because there are SE-sites that specialize on them doesn't mean that they should be migrated since they are single-board microcontrollers that can be programmed and programming related questions are definitly suitable for SO. From the help center: What topics can I ask about here? Stack Overflow is for professional and enthusiast programmers, people who write code because they love it. We feel the best Stack Overflow questions have a bit of source code in them, but if your question generally covers… a specific programming problem, or a software algorithm, or software tools commonly used by programmers; and is a practical, answerable problem that is unique to software development
common-pile/stackexchange_filtered
Eclipse doesn't resolve forward references of scala I want to construct Fibonacci sequence using this scala specific expression: val fibs: Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 } but the eclipse compiler complains regarding forward references: Forward reference extends over definition of value fibs With this issue I can't run main method in eclipse. How should I resolve that? edit I've tried to declare it in worksheet, main, method and in REPL. The last one works perfectly. That is a limitation of the worksheet. If you put this in a separate class or method it should work. [edit] fibs needs to be a field. If it's a local val, it needs the lazy modifier. This should work: def foo { lazy val fibs: Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 } } or class C { val fibs: Stream[Int] = 0 #:: 1 #:: fibs.zip(fibs.tail).map { n => n._1 + n._2 } } I take it back. It only works if fibs is a field, not a local val.
common-pile/stackexchange_filtered
To which AWS service are mapped these two endpoint URI? I had in my hands these last days two URI belonging to AWS, I am not able to guess which AWS service would generate such URI: cognito-idp.eu-west-1.amazonaws.com quicksilver.elasticbeanstalk.com dig quicksilver.elasticbeanstalk.com responds with NXDOMAIN so I guess the sysadmin who had a host.example.com CNAME pointing to quicksilver.elasticbeanstalk.com was just a mistake or he had other reasons to do that. Because the correct URI structure for elastic beanstalk would be: quicksilver.us-west-1.elasticbeanstalk.com There is no way to skip the region part in the URI. For the first URI, It is a live server: https://cognito-idp.eu-west-1.amazonaws.com Which AWS service did generate that URI? I looked at https://docs.aws.amazon.com/general/latest/gr/rande.html but I am not able to find it. Update: I still need the answer for the something.elasticbeanstalk.com , I keep seeing URLs with that structure, what I would expect would be: something.us-west-1.elasticbeanstalk.com, can somebody tell something about it please ? quicksilver.elasticbeanstalk.com is from AWS Elastic Beanstalk: https://aws.amazon.com/elasticbeanstalk/ cognito-idp.eu-west-1.amazon.com is from AWS Cognito: https://aws.amazon.com/cognito/ Thanks, but for the elasticbeanstalk are you sure? I don't see how to create an elastic beanstalk without the region, notice: quicksilver.elasticbeanstalk.com , it does not have the region in the URI!! If it had then that would be easy. Do you know how to create elasticbeanstalk services without URI? This behavior changed in 2016 when region became part of the domain for new environments https://aws.amazon.com/about-aws/whats-new/2016/01/aws-elastic-beanstalk-adds-support-for-amazon-route-53-aliasing/
common-pile/stackexchange_filtered
'Zend_Http_Client_Exception' with message 'Passed adapter is not a HTTP connection adapter This is making my crazy. I really hate to post questions but "here goes". I was able to upload a video using the Zend Gdata API for You Tube. "One video"... Ever since I have received this error: Fatal error: Uncaught exception 'Zend_Http_Client_Exception' with message 'Passed adapter is not a HTTP connection adapter' in ../pathtoapp/Zend/Http/Client.php:926 Stack trace: #0 ../pathtoapp/Zend/library/Zend/Gdata/HttpClient.php(275): Zend_Http_Client->setAdapter(Object(__PHP_Incomplete_Class)) #1 ../pathtoapp/Zend/library/Zend/Gdata/App.php(692): Zend_Gdata_HttpClient->setAdapter(Object(__PHP_Incomplete_Class)) #2 ../pathtoapp/Zend/library/Zend/Gdata.php(219): Zend_Gdata_App->performHttpRequest('POST', 'http://uploads....', Array, Object(Zend_Gdata_MediaMimeStream), 'multipart/relat...', NULL) #3 ../pathtoapp/Zend/library/Zend/Gdata/App.php(910): Zend_Gdata->performHttpRequest('POST', 'http://uploads....', Array, Object(Zend_Gdata_MediaMimeStream), 'multipart/relat...') #4 /home/spotya/public_html/devblogpost/php/Zend/library/Zend/Gdata/App.php(985): Zend_Gdata_App-> in ../pathtoapp/Zend/library/Zend/Http/Client.php on line 926 Similar posts I found have solved the issue, but their solutions have not worked for me. My Code: error_reporting(E_ALL); require_once('Zend/Loader.php'); require_once('../../includes/defines.php'); Zend_Loader::loadClass('Zend_Gdata_HttpClient'); $client = new Zend_Gdata_HttpClient(); $developerKey = ''; $applicationID = ''; $clientID = ''; $sql = "SELECT * FROM `you_tube_credentials` WHERE `user_id` = '1'"; $auth = $db->FetchAssoc($db->Query($sql)); if($auth['id'] == '') // If Auth Key not stored in DB get one { $authenticationURL= 'https://www.google.com/accounts/ClientLogin'; Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $httpClient = Zend_Gdata_ClientLogin::getHttpClient( $username = '', $password = '', $service = 'youtube', $client = null, $source = 'My Videos', // a short string identifying your application $loginToken = null, $loginCaptcha = null, $authenticationURL ); $httpClient_ser = serialize($httpClient); $sql = "INSERT INTO `you_tube_credentials` (`user_id`,`user_name`,`password`,`application`,`developer_key`,`http_client`) VALUES (1,'social@spotya.com','XXXXXXX','Spotya Videos','".$db->Escape($developerKey)."','".$db->Escape($httpClient_ser)."')"; $db->Query($sql); header('location: youtube.php'); } else { $httpClient = unserialize($auth['http_client']); } $sql = "SELECT * FROM `video_cue` WHERE `posted` < 4 AND `post_datetime` < '".date('Y-m-d H:i:m')."'"; $result = $db->Query($sql); while($row = $db->FetchAssoc($result)) { $transactionid = time(); Zend_Loader::loadClass('Zend_Gdata_YouTube'); $yt = new Zend_Gdata_YouTube($httpClient,"Spotya Videos",$clientID,$developerKey); // create a new VideoEntry object $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry(); // create a new Zend_Gdata_App_MediaFileSource object $filesource = $yt->newMediaFileSource(realpath('/pathtovideo/video_auto_upload/'.$row['file_name'])); //$filesource = $yt->newMediaFileSource(realpath('Wildlife.mp4')); $filesource->setContentType('video/mp4'); // set slug header $filesource->setSlug($row['file_name']); // add the filesource to the video entry $myVideoEntry->setMediaSource($filesource); $myVideoEntry->setVideoTitle($row['title']); $myVideoEntry->setVideoDescription($row['description']); // The category must be a valid YouTube category! $myVideoEntry->setVideoCategory('Education'); // Set keywords. Please note that this must be a comma-separated string // and that individual keywords cannot contain whitespace $myVideoEntry->SetVideoTags($row['tags']); // upload URI for the currently authenticated user $uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads'; // try to upload the video, catching a Zend_Gdata_App_HttpException, // if available, or just a regular Zend_Gdata_App_Exception otherwise $sql = "INSERT INTO `video_post_log` (`transactionid`,`sent`,`status`) VALUES ('".$transactionid."', '".$db->Escape(serialize($myVideoEntry))."', 'Initialized')"; $db->Query($sql); try { $result = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry'); } catch (Zend_Gdata_App_HttpException $httpException) { $result = $httpException->getRawResponseBody(); } catch (Zend_Gdata_App_Exception $e) { $result = $e->getMessage(); } if(is_array($result) == true || is_object($result) == true) { if(strpos($result,'xml') === false) { $result = serialize($result); } } $sql = "UPDATE `video_post_log` SET `result`= '".$db->Escape($result)."',`status` = 'Complete' WHERE `transactionid` = '".$transactionid."'"; $db->Query($sql); $sql = "UPDATE `video_cue` SET `posted`=`posted`+1 WHERE `file_name` = '".$row['file_name']."'"; $db->Query($sql); } I noticed this in the stack trace: Zend_Gdata_HttpClient->setAdapter(Object(__PHP_Incomplete_Class)) Notice how it says it is passing a __PHP_Incomplete_Class object to setAdapter. My guess is that when you pull the object from the database and unserialize it, the class that you are unserializing is not loaded, which is why it becomes a __PHP_Incomplete_Class object. Try adding this code before you attempt to unserialize the HTTP client from the database: else { Zend_Loader_Autoloader::autoload('Zend_Gdata_HttpClient'); $httpClient = unserialize($auth['http_client']); } By preloading the class, when you call unserialize, it should come out as a Zend_Gdata_HttpClient instead of the incomplete class. In case that doesn't work, try to also load Zend_Http_Client since that is what Zend_Gdata_HttpClient extends from. EDIT: Also try using the newer autoloader; replace: require_once('Zend/Loader.php'); Zend_Loader::loadClass('Zend_Gdata_HttpClient'); with: require_once 'Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); // this sets up the ZF autoloader Zend_Loader_Autoloader::autoload('Zend_Gdata_HttpClient'); Hmmm... Zend_Loader_Autoloader not found error, but clearly Zend_Loader_Autoloader is in Zend/Loader.php. Are you using Zend_Application or Zend Framework standalone and just picking the component you need? Well, a reference to it within the deprecated registerAutoLoad anyways. I'll search around and see if I can find anyone else with this error. Not sure actually. I don't have "any" experience with Zend. I am using Zend's Gdata version 1.11.12. And whatever flavor is contained within. I just made an edit, looks like you are using just the Gdata stuff standalone I couldn't find Autoloader.php located anywhere in the Zend library folder. So I downloaded the latest minimal version of the Zend framework. I copied the necessary folder to my library directory. Now Its.. well I can at least communicate with the server, and its returning an XML error. "validation code too short". Thanks for your help, it really saved my skin. I think I can take it from here. FYI for anyone who get 'validation too short'. You Tube requires 'Title','Description','Tags'. I was testing using tags, "this,is,a,test". "a" was too short to be considered a keyword. Upload is working now.
common-pile/stackexchange_filtered
How to write good docstrings for decorators in Python? I have a problem with writing good and informative docstrings for decorators in Python. Let's say I have a following decorator: def require_login(view): """ Decorator for limiting access to a view for authenticated users only. :param view: view function to decorate :return: ??? """ @wraps(view) def wrapper(...): ... return wrapper What should be described in :return:? "Decorated view"? It seems not very informative to for me, to be honest. What is the best way to describe a decorator without writing obvious things in documentation? And how to document a decorator with arguments such us: def require_permission(permission_name): def decorator(view): @wraps(view) @require_login def wrapper(...): ... return wrapper return decorator If you know any good way to document decorators in Python, I would also appreciate all of your advices. Is it really necessary to describe the return value of a decorator? It is a good question. Do you suggest to simply omit the return part? Yeah, doesn't seem like there's any point to it.
common-pile/stackexchange_filtered
jQuery UI Sortable - IE6 & IE7 z-index issue I'm trying to use jQuery UI's sortable but when dragging from one container to another, the item is appearing BEHIND the container. JSFiddle: http://jsfiddle.net/7LrLE/8/ I've uploaded a screen: Here's my code: <ul class="droppable grid-9"> <li>aaaaaaaa</li> <li>bbbbbbbbbbbbbbbb</li> <li>ccccccccccccccc</li> </ul> <ul class="droppable grid-9"> <li>xxxxxxxxxxx</li> <li>yyyyyyyyyyyy</li> <li>zzzzzzzzzzzzzz</li> </ul> And here's my jQuery code: $('.droppable').sortable({ appendTo: 'body' axis: 'y', connectWith: '.droppable', zIndex: 5 }).disableSelection(); Any help is greatly appreciated! FIXED I was able to fix the issue using the following jQuery code: $('.droppable').sortable({ axis: 'y', connectWith: '.droppable', over: function() { $(this).css('z-index', '1'); }, start: function() { $(this).css('z-index','2'); } }).disableSelection(); A JS Bin test case showing the problem would be very helpful. I think you would need to dynamically decrement the zIndex property so that the element above has a higher zIndex than the one below hoping there is a better way. dtan: how would you go about doing that? you would get the number (effectively becoming the length) of elements you have to affect, loop through that many number of times and then decrement from a set zIndex
common-pile/stackexchange_filtered
Is the term 'String' too jargony to use in a user interface? Having worked as a software developer for a long time, I'm out of touch sometimes with whether a word would be considered jargon. I am adding something to a user interface where a name is given, and a type. The type would be one of Number, Date, or 'String'. I'm just not sure if 'string' in the technical sense is a term that is in common usage, or if it is still considered jargon. 'Text' sounds mildly inappropriate to use, because that implies a length (to me at least), whereas this would be something short. So, is there a better word I can use? Google Forms uses Text to refer to a short string and Paragraph Text to refer to a longer text. Can you not detect the type automatically based on the supplied text? @Graham - It's more about validation or presentation. This is an administrative interface for displaying additional fields to a user, so if 'Date' is shown as the type, a date chooser would be used when prompting the user. If number, then we'd validate that an actual number is input, etc. Should this be migrated to http://ux.stackexchange.com/ ? @Marcin: I would have voted to migrate, but the answers here are fine. Definitely too jargony as you say. A string for everyday people is still a filament made up fibrous material, not a chain of somethings. Go for text, characters/letters, words/phrase or whatever vocabulary is used for describing this to kids in schools. P.S: You should take that programming hat off every now and then ;) Depends a lot on what you expect the user to enter, for me; I'd sooner use sentence, snippet, summary or description. A max. length guide to the right or bottom of the field to further guide the user could even be added as an optional extra. It would also be good to know the user base of the application. Are they developers of some sort? BTW, nice avatar. FOR THE HORDE! Only on Stackexchange can this question be asked in an English Language context and get 38 upvotes. Relevant MSO post. String is probably still a bit "jargony" for many. Call it Text instead. Exactly! Expresses the same information in a less esoteric task domain. +1 and to the OP's thought that "Text" implies length is generally only true for people working with relational databases. For normal people, "Text" doesn't imply any length, short or long. Users are more familiar with "Text Box" than string, and those are often single line inputs. I'm not going to change my first sentence there, but on reflection I think it implies that at some point in the future, string may no longer be considered 'jargony'. Which I neither expect nor would wish to see happen. In reality the word is, and will remain, "jargon". Trivia (from Crockford on JavaScript, part 2) because I just have to share. This supports the idea that string should stay jargon, in my opinion. "Now, string. Ever wonder why we call them strings? ... Nobody knows. As far as I can tell, the first use of string to mean a data type in a programming language which is a sequence of characters was the ALGOL 60 report ... But they didn't explain in the report why they called it string, and there doesn't appear to be a good reason for it." http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2 @Davy8, a text does, though, I think. I wouldn't call someone's name a text, but I would call the Gettysburg Address a text. @Davy8: True. "Text" in your example is a data type. In that case, I hope the UI designer would use an appropriate label for a control that captures the value of a strongly-typed Text column. In that case, I hope the application is capable of adequately handling 2GB of input value, especially in distributed or Web applications. =S @msh210: Remember this is in a context where the user has other choices called Date and Number. He's no more likely to think of the Gettysburg Address than he is to think Date = someone you take for a romantic night out, and Number = the haunting melody you smooch to later. Ooh! This is my field of expertise. =) Never use "string" to describe a series of characters, in any user interface element. The exception to this rule, is when the user is expected to be a developer (programmer, analyst, power user, etc.). If any, the user interface should use jargon with which the user is expected to be familiar. When using jargon in the user interface, it should not be so cryptic that a novice user is unable to easily interpret the meaning. Describe what the string represents. The data type that must be provided should be enforced by the input capturing mechanism (text box, etc.), and/or inferred by the description. Use a date chooser for dates and a text box for names. Date choosers are important; because a date may be entered in various formats -- the date chooser returns a predefined format. If you are having trouble doing so, the user interface must be re-evaluated. For example: First Name (implies alpha characters) Password (implies alphanumeric and common punctuation characters) Message (implies alphanumeric and common punctuation characters) Birth date (implies date format) Hours worked (implies integral data) The reason why "Number, Date, or 'String'" sounds correct, is because the meaning of string is contextual to anyone familiar with its correlation to "a series of characters." For everyone else in the world (likely 99.7% or so of world population), it means "a long piece of fiber". Side note: Proper, modern software architecture, particularly MVP, MVC, and MVVM, accommodate interchangeable user interfaces. Using these architectures would allow the same application to have both a "technical" and "non-technical" interface. This is very useful, because the logic and data remain the same, and only a new user interface needs be built. Therefore, an application program could contain both expert and novice interfaces. This could be as simple as displaying definitions of jargon to novice users, and not to experts. +1 for the exception to the rule, though I'd expand it to include analysts, power-users, and others that have strong technical backgrounds but might not be programmers. @FrustratedWithFormsDesigner, I changed it to "developers", which includes all you listed. Thank you for the notice. Actually, the analysts I was referring to were Business Analysts, most of whom don't know how to program but are familiar with the technical jargon that programmers use. And many power users aren't programmers at all. ;) We did some informal research on precisely this for the ConML modelling language, which is aimed at non experts in information technologies. We wanted a "string" data type but we didn't want to sound too techie. Our conclusion was to use Text as a data type name, and from our experience at teaching and using ConML, it is well received and understood. 'Text' sounds mildly inappropriate to use, because that implies a length (to me at least), Text is the standard for this kind of data, String will probably make no sense to someone without a programming background. I'm a native English speaker and have never heard that saying Text implies a length. A text does, though, I think. I wouldn't call someone's name a text, but I would call the Gettysburg Address a text. "Alphanumeric data"? Still kinda jargon-y, but more intelligible without context. This is not the best answer, but in my opinion it doesn't deserve a negative score. I think alphanumeric data should indeed be clearer to a layperson than string. Especially nowadays, with people being asked to provide passwords for everything, it is quite common to encounter the term alphanumeric, and it's not hard for people who have some sense of English but not computers to figure this one out. When using terms for non-programmers, one must try to see how the word will be interpreted by them. I once had a GUI which on which I had used the word "check sum" for a check-sum calculated from an order number (to catch entry errors.) I had clerks telling me that the software complained the check sum was wrong, but they had double-checked the amount on the customer's check (e.g. the check's "SUM"), and it was correct! String is a bad choice because it doesn't mean the same thing you thing it does. To a non-programmer, string is a shoe strings or twine. "Text" would be a good choice. Text indicates a alphanumeric data, and has no intrinsic implication of length. You said you thought that the word implies length, so a modifier may help be more specific. "Short Text", as a two-word answer, is a much better choice than "String." Does it have to be a single word? How about any string of characters or any sequence of characters? I think that'd do. My impression — nothing more — is that bare string is pretty jargony. Or just characters. Just remember that string only makes sense to us as we're used to thinking about it as an array (or string) of chars. Unless this screen's audience is technical or at least considered a super user, I think 'text' is going to be most meaningful to the most people even if it's not 100% accurate. To your point (and perhaps where you're having trouble coming to like 'text'), the word 'text' in my/our field, implies a different data structure, in that it's usually a LOB. But I say this to perhaps put a name to your hesitation w/ the word 'text' An extremely anti-jargony option is Any Characters, and seems not to imply length. It's better than String, however, I doubt it's better than Text.
common-pile/stackexchange_filtered
Why does the author mean by "The $(p+1)/2$ numbers to $x^2$, for $0\leq x\leq (p-1)/2$, ..." I couldn't get the proof for the given theorem. How is the $(p+1)/2$ numbering to $x^2$, how is the following relation valid?? It's saying "The collection of this-many numbers, each of the form $x^2$ for an $x$ in this range, are incongruent ...". Here, "this-many" is $(p+1)/2$, which counts the values in the range $0, 1, 2, \ldots, (p-1)/2$. The $\frac{p+1}{2}$ numbers $0^2,1^2,2^2, \ldots, (\frac{p-1}{2})^2$. First: Counting the (square) numbers including zero, we find that there are $1+\frac{p-1}{2}=\frac{p+1}{2}$ of them. Second: $x_1^2-x_2^2=(x_1-x_2)(x_1+x_2)$, so if $p\mid x_1^2-x_2^2$ then $p\mid x_1-x_2$ or $p\mid x_1+x_2$. Since $0 \leq x_1, x_2 \leq \frac{p-1}{2}$, from $p\mid x_1-x_2$ it follows that $x_1=x_2$. Also, $x_1+x_2 \leq p-1$, so if $p\mid x_1+x_2$ then $x_1=x_2=0$. Therefore, for $x_1, x_2$ in the give range, from $x_1^2 \equiv x_2^2 \pmod{p}$ it follows that $x_1 = x_2$.
common-pile/stackexchange_filtered
Problems using location poller (cwac-locpoll) android I am currently developing an application which gets the users location from time to time and stores it, later on it sends it over the network. I have been testing out the location poller but have had some issues, it seems that in some android models the location updates are not received for some time. The service does run, but only returns the last known location. Below some data that I have received to show what I mean: +----------+------------------+--------------------+--------------+--------------+ | Accuracy | Date registered | Date from position | Lat | Lng | +----------+------------------+--------------------+--------------+--------------+ | 8.3 | 16/08/2013 14:23 | 16/08/2013 14:23 | -2.361.446 | -4.665.134 | | 45 | 16/08/2013 14:28 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:32 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:36 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:40 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:44 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:48 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:52 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 14:56 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:00 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:04 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:08 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:12 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:16 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:20 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | | 45 | 16/08/2013 15:24 | 16/08/2013 02:26 | -235.644.403 | -465.143.039 | +----------+------------------+--------------------+--------------+--------------+ Any ideas? Use adb shell dumpsys alarm to confirm that your alarms are configured properly. I also ran into issues using the CWAC poller, and ended up using material from this popular SO post with my own timers/broadcast receivers to control the frequency. The MyLocation code, and this tutorial were what finally worked for me. Good luck!
common-pile/stackexchange_filtered
Cannot install lighttpd on Ubuntu 18.04 LTS I'm using Ubuntu 18.04 LTS. I can't find out what's causing this error. I tried to google but couldn't find the solution. Please help. sudo apt install lighttpd -y Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: spawn-fcgi Suggested packages: rrdtool php5-cgi lighttpd-doc The following NEW packages will be installed: lighttpd spawn-fcgi 0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded. Need to get 291 kB of archives. After this operation, 1,027 kB of additional disk space will be used. Get:1 http://archive.ubuntu.com/ubuntu bionic/universe amd64 lighttpd amd64 1.4.45-1ubuntu3 [276 kB] Get:2 http://archive.ubuntu.com/ubuntu bionic/universe amd64 spawn-fcgi amd64 1.6.4-2 [14.9 kB] Fetched 291 kB in 8s (35.0 kB/s) Selecting previously unselected package lighttpd. (Reading database ... 358529 files and directories currently installed.) Preparing to unpack .../lighttpd_1.4.45-1ubuntu3_amd64.deb ... Unpacking lighttpd (1.4.45-1ubuntu3) ... Selecting previously unselected package spawn-fcgi. Preparing to unpack .../spawn-fcgi_1.6.4-2_amd64.deb ... Unpacking spawn-fcgi (1.6.4-2) ... Processing triggers for ufw (0.35-5) ... Processing triggers for ureadahead (0.100.0-20) ... Setting up spawn-fcgi (1.6.4-2) ... Setting up lighttpd (1.4.45-1ubuntu3) ... Job for lighttpd.service failed because the control process exited with error code. See "systemctl status lighttpd.service" and "journalctl -xe" for details. invoke-rc.d: initscript lighttpd, action "start" failed. ● lighttpd.service - Lighttpd Daemon Loaded: loaded (/lib/systemd/system/lighttpd.service; enabled; vendor preset: enabled) Active: activating (auto-restart) (Result: exit-code) since Sun 2018-06-17 13:28:45 IST; 9ms ago Process: 25574 ExecStartPre=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf (code=exited, status=127) Processing triggers for systemd (237-3ubuntu10) ... Processing triggers for man-db (2.8.3-2) ... lighttpd is not starting systemctl status lighttpd.service ● lighttpd.service - Lighttpd Daemon Loaded: loaded (/lib/systemd/system/lighttpd.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2018-06-17 13:28:47 IST; 1min 53s ago Process: 25986 ExecStartPre=/usr/sbin/lighttpd -tt -f /etc/lighttpd/lighttpd.conf (code=exited, status=127) Jun 17 13:28:47 surjit systemd[1]: lighttpd.service: Service hold-off time over, scheduling restart. Jun 17 13:28:47 surjit systemd[1]: lighttpd.service: Scheduled restart job, restart counter is at 7. Jun 17 13:28:47 surjit systemd[1]: Stopped Lighttpd Daemon. Jun 17 13:28:47 surjit systemd[1]: lighttpd.service: Start request repeated too quickly. Jun 17 13:28:47 surjit systemd[1]: lighttpd.service: Failed with result 'exit-code'. Jun 17 13:28:47 surjit systemd[1]: Failed to start Lighttpd Daemon. Check for errors with journalctl -u lighttpdlighttpd and in /var/log/lighttpd/error.log . On clean Ubuntu 18.04 LTS I can't reproduce the error. You should check that lighttpd is only one HTTP server (have exclusive access to port HTTP/80 ). Please add output of sudo netstat -p -l | grep http to the question. I have Apache web server installed.. that's why I stopped the server before installing lighttpd. And also there's no log file.. may lighttpd is not configured properly. See my answer here: https://askubuntu.com/questions/1072840/failed-to-start-lighttpd-daemon-on-boot/1113413#1113413
common-pile/stackexchange_filtered
inconsistent bad mask error in packet tracer i was assigning: <IP_ADDRESS> <IP_ADDRESS> to 3560 switch which shouldn't throw an error of bad mask given that it is in the usable range: Address: <IP_ADDRESS> 01010011.10101110.00010000.10100 000 Netmask: <IP_ADDRESS> = 29 11111111.11111111.11111111.11111 000 Wildcard: <IP_ADDRESS> 00000000.00000000.00000000.00000 111 => Network: <IP_ADDRESS>/29 01010011.10101110.00010000.10100 000 (Class A) Broadcast: <IP_ADDRESS> 01010011.10101110.00010000.10100 111 HostMin: <IP_ADDRESS> 01010011.10101110.00010000.10100 001 HostMax: <IP_ADDRESS> 01010011.10101110.00010000.10100 110 Hosts/Net: 6 so i am just wondering what was causing the error? because it ended up letting me put the mask in after i trying a couple of times. thanks for taking the time to read my post any help is appreciated The mask you were trying to use really is a bad mask. You were trying to use <IP_ADDRESS>. You simply had a typographical error that you eventually corrected. It happens, and it is a big reason to have a peer review of your work before putting it into production. i think i might be blind but i cant see where i made the typographical error In the third octet, you have two hundred twenty-five, not two hundred fifty-five.
common-pile/stackexchange_filtered
how to make append changes to an arraylist I made this code, I am wondering what am I missing since when i return the list the new change i made to the position of j does not work! static ArrayList<Integer> SmallChange(ArrayList<Integer> list, int j){ int change = CS2004.UI(-5, 5); // this just makes a random int between -5 and 5. int newnum = change += list.get(j); if (newnum > list.size()){ newnum = list.size(); } else if (newnum < 0){ newnum = 0; } System.out.println(list); return list; } You need to put newnum back to the list. list.set(j, newnum). interesting so this re adds it to the list based on the position of j? Yup. See: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#set(int,%20E) Thanks, you've soled my question btw :) You could just read the documentation here to find out... You need to replace the old value of j with newnum by calling list.set(j, newnum) before you return the list at the end. Even better, return a copy of the list instead of modifying the original list. Although in this case the modification to the list is trivial, it is is usually best to not modify parameters passed into a method. That is, keep your method without "side-effects" - instead of modifying the list passed in, you return a new list in this case. Ex: List<Integer> copiedList = new ArrayList<Integer>(list); copiedList.set(j, newnum); return copiedList; To modify the list with the new number you would need to add the new calculated number back to the list at position J you can do this with the set command. Your code should look something like the following static ArrayList<Integer> SmallChange(ArrayList<Integer> list, int j){ int change = CS2004.UI(-5, 5); // this just makes a random int between -5 and 5. int newnum = change += list.get(j); if (newnum > list.size()){ newnum = list.size(); } else if (newnum < 0){ newnum = 0; } list.set(j, newnum); System.out.println(list); return list; } This will set index J to either 0, the list size, or the calculated value depending on which of your logic statements get executed
common-pile/stackexchange_filtered
Which Recycler Adapter method is called when recycler wants to recycler an adapter I am aware that a recycler adapter and listview basically recycles adapters that can fit a given screen giving the user the illusion of multiple items, my main reason for this question is because I have an app that loads a great deal of images in a recycler using Picasso but I noticed Picasso is not doing the job as expected, my app uses roughly 10mb on the emulator and about 4mb on real devices, this is really good for an app that displays images but I want to go further, I want to be recycling bitmaps myself in the method that is called when an adapter leaves the screen, that is, since views are recycled there has to be a method that removes data out of an adapter and refills it with new data to make that illusion a reality, I looked at the recycler adapter documentation and I noted 2 methods the onDetachedFromRecyclerView and onViewDetachedFromWindow both of which cannot be overridden, anyone have an idea on how I can approach my problem? solved it, I had to override onViewRecycled and the previous 2 methods are overridenable except I did not know how to, I know do. @Override public void onViewRecycled(MyViewHolder holder) { super.onViewRecycled(holder); //destory anything here } Can you give an example code snippet of what you did inside this method?
common-pile/stackexchange_filtered
Is polynomial ring a lattice? My prof says it's not. But I can't find a polynomial pair of $f,g$ such that $max(f,g)$ or $min(f,g)$ is not in $R[x]$. Define uniform order: $f\leq g$,if for all $x, f\leq g $. How are you defining the underlying order? What is "uniform order"? Consider $f=-g$ where $f$ takes at least negative value and at least one positive value. Edit: You can also take this comment as a hint. you mean this makes a non differentiable function hence not a polynomial? No,thing like that.Let $f(x)=x$,for all $x$and $g=-f$.What is $\max(f,g)$? Note that the ordering you give forms a lattice over the set of functions continuous in an interval, so the problem must be that a supremum isn't a polynomial. As git suggests in a comment above, you can take $f(x) = x, g(x) = - x$. I claim that not only is there no supremum of these two functions, but in fact there is no polynomial greater than both of them under your ordering. Can you see why?
common-pile/stackexchange_filtered
10.9 CoreBluetooth RetrivePeriperals Im developing an app on OSX that uses CoreBluetooth. I have encountered a problem on OSX Mavericks that i cant seem to get around. (All of this works perfectly on OSX 10.8). First lets go through the flow of the application This flow is fairly established and has been used used successfully in iOS apps and works on 10.8. So on Mavericks, the first run completes successfully. It scans, finds and connects to the device correctly. It also saves out the UUID of the device to a .plist file along with other properties. Upon relaunch of the app, it attempts to go down the left hand column of the flow which is where the problems seem to occur. So the first issue i noticed was that my call to self.central retrievePeripherals: never calls my delegate callback of -(void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals . It simply never gets the callback on Mavericks. My next thought was "oh they have a new API for fetching peripherals on Mavericks and the old one is deprecated, lets try that". So i added in my calls to NSArray *identifiers = [self.central retrievePeripheralsWithIdentifiers:@[uuid]]; and i get caught in a sempahore wait trap. Upon closer debugging of what was going on it turned out that sometimes my CBCentralManager gets into a state of CBCentralManagerStateUnknown and never updates the state to a newer one. The next thing i tried was to fire up Activity Monitor and kill the blued process. Finally, my delegate callback for -(void)centralManagerDidUpdateState:(CBCentralManager *)central was called with the correct CBCentralManagerStatePoweredOn so i performed retrievePeripheralsWithIdentifiers again and received an empty array. So all of these problems seem to be linked to blued in some way. Does anyone have more insight into this process to elude as to what is going on? My main question is. Why does this work the first time through the app but not the second? Upon quitting the app after the initial scan and connection it seems i can no longer use the system bluetooth for anything without resetting blued (which even then doesn't retrieve peripherals). Is there some sort of shutdown sequence i need to do on the CBCentralManager to keep blued from going AWOL? Any advice would be greatly apprecciated! While this is obviously a very old thread, I stumbled upon the same issue today and decided to post a fix for posterity. I was trying to hack together a simple app based on the HeartRateMonitor example provided by Apple. Unfortunately, it does not work on 10.9 if autoConnect is set to TRUE, what's worse, it brings blued down on its knees. In 10.9, a call to the (deprecated) retrievePeripherals freezes blued without a chance to restore. CBCentralManager goes into CBCentralManagerStateUnknown, Bluetooth cannot be turned on/off using OS functions etc. The only solution that I found is to killall -9 blued. However, the synchronous retrievePeripheralsWithIdentifiers worked well for me (on 10.9.4). Here's the relevant excerpt from the modified HeartRateMonitor code: /* Retreive already known devices */ if(autoConnect) { NSArray *peripherals = [manager retrievePeripheralsWithIdentifiers:[NSArray arrayWithObject:(id)aPeripheral.identifier]]; NSLog(@"Retrieved peripheral: %lu - %@", [peripherals count], peripherals); [self stopScan]; /* If there are any known devices, automatically connect to it.*/ if([peripherals count] >=1) { [indicatorButton setHidden:FALSE]; [progressIndicator setHidden:FALSE]; [progressIndicator startAnimation:self]; peripheral = [peripherals objectAtIndex:0]; [peripheral retain]; [connectButton setTitle:@"Cancel"]; [manager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]]; } } Should have updated this, it looks like 10.9.3 fixed the issue i was seeing and the new method works as you show above.
common-pile/stackexchange_filtered
how can i configure the service provider in wso2is for different tenants of version 5.2.0 As per the documentation, enabling the SAAS Application, allows the Service provider to all tenants is not working.Even Though we have created the service provider per each tenant. when login by using wso2is authentication page it is saying authentication fails. I have seen the log file of WSO2IS it says service provider has to be registered. But,we have tested the same service provider application name by using the soap webservice by giving the same credentials it is giving the response. Thanks In advance, In what tenant you created the service provider? Is it in super tenant or in a tenant you created later. Thank you for reply pulasthi,In the super tenant we have created the service provider and the tenant created later we have service provider and for the service provider we have enabled the SASS. @pulasthi7 same issue here, when using getServiceProviders() WS with different tenant doesn't yield the SP app name in the Soap response, even after configuring the super.tenant SP app as SaaS. Solution is, Verify the ClientId/ClientSecret is associated with the Application/SP. If Using SoapWS, for OAuthServices then use the super-user credentials(~assuming the clientID/clientSecret belongs to superUser). If using HTTP-Post:Binding, replace the secToken, respective to each user(~this is for validation in SAMLsoo/SAMLAssertion). Hope it helps..! ,Yes it has clarified ,Thanku
common-pile/stackexchange_filtered
PHP: execute command as synchronous process and read stderr I have a PHP class that must launch a Java main as a separate process. The execution must be synchronous and after its end I must read the stderr to handle and log potential errors. I see that the most popular techniques to run separate processes from PHP are exec() and proc_open(). However, I do not understand which I should use and how. Exec(), being synchronous and very easy to use, should be the best choice for me. However, from what I see here on StackOverflow: PHP StdErr after Exec(), it seems that the only way to get the stderr is to explicitly create a file for it. It does not seem to me like an elegant solution. On turn, proc_open seems a really powerful tool, and it does allow direct, separate access to stdin, stdout and stderr. For what I need to do, the code should be something like this: $proc = proc_open($cmd,[2 => ['pipe','w']],$pipes); $stderr = stream_get_contents($pipes[2]); fclose($pipes[2]); proc_close($proc); $error = var_dump($stderr) The problem is proc_open is asynchronous, so if I get it right, I can not be sure that when I run stream_get_contents I will get any relevant message (errors might occur later!). What should I do? stream_get_contents() will wait for EOF on the pipe, which will happen when the program ends. So that makes it synchronous. That's essentially what happens inside exec(), except it's doing it with stdout rather than stderr. You can't have an assignment after return, since return exits from the function. Did you look at the second answer in the question you linked to? It shows how to get stderr using exec() with output redirection in the command line. Hi Barmar, thanks for your great advices. I thought that stream_get_contents() would just take a snapshot of the stderr stream (I also read the documentation but it does not mention EOF; I guess PHP docs are quite... concise). This definitely solves my issue! if you write an answer with it, I can mark it as the solution for my problem. As for the answer in the exec question, I did read it, but creating a new file with posix_mkfifo() just for redirecting stderr whenever I call a process seems a bit meh, doesn't it? I would avoid that unless it is absolutely necessary :) The documentation says it reads the remainder of a stream. The remainder is everything until the stream ends, which is EOF. (As for the return, yeah, that's a copy-paste error ahah) Why do I need to write an answer when your code will work as written? You don't need to create a new file with mkfifo. Use the solution with command 2>&1 >/dev/null You only need the FIFO if you want to be able to get both stdout and stderr separately.
common-pile/stackexchange_filtered
Reading data of floppies from a ZX Spectrum Swift Disc Back in the day when we had a Sixword Ltd. Swift Disc floppy-drive we were ahead of the game on our speccy, allowing us to use 3.5inch floppy disks. See: https://www.worthpoint.com/worthopedia/swift-disc-interface-zx-spectrum-540379389 http://www.crashonline.org.uk/44/swiftdisk.htm https://spectrumcomputing.co.uk/index.php?cat=96&id=1000412 https://hardware.speccy.org/hardware/Swift_Disc-Sixword-i.html I see the full hardware spec and even the rom is available online at the hardware.speccy.org link above which is pretty amazing. Does anyone have an idea what disk format was used (it was a snapshot of the entire memory) and how our old floppies might be digitalized for the modern retro world. Possibly we could convert them to FDI format? Motivation: It would be kind of nice to try and upload our never released game "Galactic Patrol" like we did with StarBlade. Apologies for making the enemy waves too evil there! Could have done with some more playtesting but we were both still in school. This ran in 'full' co our using the rapid screen switch scheme my brother devised which is mentioned here in crash. It might be worth getting the disks to someone with a device like a Greaseweazle. It will generate a raw image of the magnetic flux patterns on the disk that can be reassembled into a filesystem later. Information on the SwiftDisk is thin on the ground, but it does seem to use a standard DSDD 3½" drive so recovery may not be too complex. Good luck! As an emulator author, I will wager that if you can get a flux-level capture then I — or someone else like me — can emulate the Swift or otherwise parse the disk image sufficiently to extract the data, given that the ROM is available. That is, if there isn’t already an emulator such that it just works. The quoted 32us bit length plus the size of the company strongly implies a standard MFM encoding, so you might even just be able to do a sector dump using a regular PC drive, or even a USB drive, and capture everything. Talking of the greaseweazle and similar are there any available to buy anywhere ready assembled? I could probably cobble it together myself but given enough time but I have a knack of messing up with hardware. Also there's an element of yak shaving. This is my swift disc, up and running in 2022 :-) https://youtu.be/kMOO6KIVf3c I can send you a blank floppy image, which will enable you to see the disk format. Would that help answer your question? @BruceAdams There are some official vendors for the Greaseweazle linked on the GitHub repo's wiki. I recently bought a Greaseweazle V4 and, of the listed sources, AmigaKit had the lowest total price for a Canadian buyer. Also, note that the client tools for the FluxEngine are now capable of driving Greaseweazle hardware and seem more novice-friendly. I couldn't find technical information or an existing emulator but via your links I found this high-resolution image of the interface's board. From there I notice the following things: the disk controller is a WD1770, that's the big one on the left; the two large chips on the right both half underneath the edge connector are an 8kb RAM and an EPROM; and everything else that's visible is 74-series logic. It's a safe bet based on the architecture of the Spectrum that the interrupt button switches in the on-board ROM and triggers an NMI. The ROM images linked are 32kb and 16kb in size but the former just seems to be 16kb data copied twice you can also adduce that the EPROM is 16kb, in which case there might be some guesswork in figuring out when and where that 8kb of RAM appears. I found old mentions in comp.sys.sinclair that the Microdrive emulation added to a later version was partly hardware based, but seems to have come with a board revision. So an emulator author would probably start with the older EPROM in the hope that the extra hardware wasn't yet present. Otherwise, the good news is that the disk controller is an extremely standard part that just does vanilla IBM encoding, and based on the advertised floppy capacity of "thirteen 48kb games per disk", you can assume the physical format of the data on disk is MFM (i.e. regular PC 'double density'). So: you might be able to image your disk using a plain USB disk drive (unless you find one that supports high density floppies only) as MFM is essentially the only thing they support — but they're often restricted to 512-byte sectors with fixed numbering so this isn't guaranteed. Might be worth a try before looking around for a less-common solution though. This MSX-related page gives a guide for Linux and macOS though the Windows section is empty. Some slight more research might be necessary there. Failing that, look into solutions that can image floppies for a machine like the Amstrad CPC, as those should handle different sector sizes and addressing, and the common CPC-related file formats can retain all that information. If you have an old enough PC to have a pre-USB floppy-disk controller and drive and an OS like DOS that gives software unfettered access to the controller then that should do the trick. Or low-level disk controllers now exist for exactly this problem, such as the Greaseweazle mentioned by scruss, the Kryoflux and others. Starting from a working Spectrum emulator it then shouldn't be too much of a trek to get the Swift disc interface added and to read your floppy. What software should write to a WD1770 is very well-known so you could isolate those addresses fairly easily, and pretty much the first thing the NMI routine will need to do is backup the current display so you'd likely be able to figure out the RAM question without too much dilemma. At that point it might well be as easy as just plugging in your disk image. A lot of the time when these slightly more obscure interfaces don't get emulated it's just because no test data is available; it's very possible that you'd be able to get an existing author interested just by having a disk image. Otherwise a Spectrum emulator is easy to knock up so someone like me who has the generally correct sort of code kicking about should be able to help. Alternatively, since my search wasn't especially thorough, you might find that the thing already is emulated — in which case please let me know so that I can change 90% of this answer. Thanks for a very helpful answer. What about reading the disks with an Amiga? I haven't booted it up in a long while but last time I did it was working very well. I recall reading that PCs couldn't read amiga disks because the amiga controller could do things the PC disk controllers couldn't. From what you say this sounds incorrect so its a mere matter of software. If there is a usb connectable floppy drive that would work with a modern linux or windows PC though it would make life easier. An Amiga disk controller could definitely read all the information on a disk based on the controller in use; I don't know the first thing about imaging formats on an Amiga though so I can't help with what software you'd use to do the reading or what form you'd end up with. Certainly if there is a tool for capturing to a file format like Amstrad CPC DSK then you could just use that. See also https://retrocomputing.stackexchange.com/questions/1634/can-i-image-amiga-floppy-disks-on-a-modern-computer It might be worth mentioning that it's double-sided 80-track double-density. Early US 3.5" drives were single-sided. 40-track 3.5" drives existed, even if they were common only in Japan. (In Japan we refer to double-sided 40-track double-density as "2D" and double-sided 80-track double-density as "2DD," and the same wide vs. narrow head issue arose as with 5.25" double-density drives vs. HD drives in double-density mode in the rest of the world. You'll see the latter label on diskettes even though 2D and 2DD are the exact same media.) Looks like it uses WD1770 I am not familiar with it but first check if WD1770 is compatible with IBM format. If yes then you can read the discs directly on PC ... If not you need HW capable of reading the disc. So in case of PC compatible you just image it using direct sector access in C++ (or any other language or utility) instead of file format. After you obtain the binary image of the floppy (one way or the other) there are two options: emulate FDC so you need to have some emulator capable of emulating your FDC interface or add such functionality to some open source code one. In your last link are ROM images and also circuit (but that one is unreadable) so it might be possible to emulate this by reversing the circuitry... I done this before for my emulator and D40/D80 FDC based on WD2797. However this is easily doable only for emulators that runs on MC (machine cycle) timing resolution (like mine) otherwise the FDC must be only hacked by hooking up to the HW and SW condition bypassing Z80 code and injecting FDC code/operations instead (that is how most emulators do it however this is not 100% compatible and custom loaders and stuff might not work) which no one without deep knowledge on the targeted FDC workings can do. extract files or you bypass the FDC completely and extract the non compressed files from the image into format readable by emulators like *.tap. In case you share some images (best with description what files and how long are in it) I would be happy to try to create a win32 converter that would do this for you. as the files are just snapshots this might be your best option. Ideally if you have also access to the HW you could create a specific memory pattern and save it to floppy so the inffering of filesystem is easier ... for example fill the 128K (RAM part) with 32 bit addresses (incremental value) so we can get the sectors together in correct order and then match it to FAT if its used... The WD1770 was super popular; it’s also used with the +D/DISCiple interface and the SAM Coupé, the Acorn Electron, BBC and Archimedes, the MSX, the Oric, the Atari ST and probably a lot more that aren’t springing to mind right now. Also it has a really great datasheet — all logic is just provided accurately in a flow chart. I recall the hardware died (which is one reason why we never attempted upload) but I think we still have it somehwere. What format are your original disks. I have backed up my original Swift Disk Microdrive emulator and Copy disks supplied by Sixword to floppy image, then written them to new floppies (retaining the original Swift Disk format) using Sam disk with the simple command Samdisk name.dsk a: on my Windows 2000 Pentium 2 with in built floppy disk drive. I can use the image to write to new floppy disks that work in the Swift Disc drive, exactly the same as the original disk. I would have to work out the commands, but in theory I could also convert these floppy disk images into the many other formats Samdisk supports too. If it's a question of extracting original files out into a form a Windows 10 PC could read, I have a program that allows you to do this from Atari ST floppy disk images. So in theory I could convert the Swift Disc image into an Atari.st image then extract the files onto a Windows PC. I'm not "technical" but do have the necessary hardware and have used these tools for specific reasons for sometime. I did this originally to write Opus Discovery .OPD floppy images to real floppies to run on my Opus Discoverys floppy drive interface for my Spectrum 48k. I have no idea of the format. That was part of the question. I do not have any images as files. We have the old floppies somewhere. They need to be imaged by appropriate hardware If they can still be read after all these years. Bruce if you have the original disks, and they are readable I simply nead to use my set up with Samdisk to write them to an image, as described in my comment.
common-pile/stackexchange_filtered
Nginx set header for cert used with mTLS We have NGINX running on an EC2 instance behind an Application Load Balancer. We have configured our ALB to use mTLS with Passthrough (new feature on an ALB since Nov. 2023). Based upon the AWS documentation, the client cert will be passed through to NGINX on the header X-Amzn-Mtls-Clientcert. We have verified this as well. Since the certificate is the X-Amzn-Mtls-Clientcert header, how do we configure NGINX to use that header to establish the mTLS connection? Our current NGINX server config: server { error_log /var/log/nginx/error.log debug; listen 443 ssl; server_name ~abc.com; ssl_certificate /etc/ssl/certs/nginx.crt; ssl_certificate_key /etc/ssl/private/nginx.key; ssl_verify_client on; ssl_client_certificate /etc/ssl/client_certs/publicapi.crt; ssl_verify_depth 1; location /mtls-statuscheck { access_log /var/log/nginx/access-mtls.log main; return 200 "$ssl_client_verify - $http_Content_Type $http_User_Agent $http_X_Amzn_Mtls_Clientcert"; add_header Content-Type text/plain; } } It seems like there should be two solutions (but I am new to NGINX): Configure NGINX to look at the X-Amzn-Mtls-Clientcert header for the client cert to establish the mTLS connection; or Add "something" to set the header that NGINX currently looks at for the client cert to the value of the X-Amzn-Mtls-Clientcert header We have tried setting a header "ssl-client-cert" to the value of X-Amzn-Mtls-Clientcert in the server block, but that did not work.
common-pile/stackexchange_filtered
Render React JS server side using .net I did the comments tutorial on http://reactjs.net/getting-started/tutorial.html and got it to render server side using .net mvc. I have an existing mvc app where I rewrote a page in react. I'm trying to render it server side using .net but I get an error when it tries to render server side. Exception Details: React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function at React.createClass.render (Script Document [8]:80:39) -> var answerNodes = this.props.data.map(function(answer){ at ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (Script Document [2]:7395:34) Here's the code: In my MVC view: @Html.React("TopicAnswers", new { initialAnswers = Model, url = Url.Action("TopicAnswers", new { id = ViewBag.TopicID }), }) My TopicAnswers.jsx file: var TopicAnswers = React.createClass({ getInitialState: function(){ alert('inside getInitialState: ' + this.props.initialAnswers); return {answers: this.props.initialAnswers}; } My ReactConfig.cs file: ReactSiteConfiguration.Configuration .AddScript("~/Scripts/internal/eusVote/TopicAnswers.jsx"); QUESTION: Why is it having a problem rendering the react file server side? I got this error message trying to render React jsx file server side using .net: "React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function" My problem was that in the JSX file, I still had ComponentWillMount which called the loadAnswersFromServer. This is what you need if you are rendering client side. But once you adjust your code to render server side, you need to comment out/remove the ComponentWillMount so that it doesn't try to run the loadAnswersFromServer function on the server side. With MVC, the data should be passed from the controller to the view and referenced in the @Html.Render("Comment", new { initialData = Model }) for the initial load. Also, don't forget to comment out/remove the React.render( ... ) line from the JSX file. alert is available only in browser window context. When rendering it on a server you can not call any functions that are browser related. If you are calling them, then you need to shim them so they are not failing on a server. Thanks Tomas. I edited my OP to show the error message I was getting before I tried to put in the Alert. It seems that my react file "TopicAnswers.jsx" is not being read via the @Html.React in my MVC view.
common-pile/stackexchange_filtered
Importing Group Audience data I have a site using OG7 and created groups to let users to access to some content as per the user membership and concent-type membership as well. Each user has to belong to a group and I can select that group(s) for him/her in the corresponding Group-Audience list box when adding or editing user information. I have also created content-types which should be attached to a group via Group-Visibility and Group-Audience Fields. When creating content, let's say an Event, I just select in the group-audience list the group I want that event to stick to and also I choose private as the group visibility choice. Now, the problem is that I need to import a huge number or nodes of different content types, say Events, and each one has to be associated to a group. Currently I just import the content-type data using feeds modules (feeds-import) using a CSV file and once in Drupal I do the group associations by hand. I cannot find a way to import the content-type along with group association while importing the data, also I don't know how to do it directly in the database, I tried but it didnt work. Anyone of you know how to import group-audiences? anyone knows which tables are affected when associating a group to a content-type? Thanks in advance for your time in assisting me. If you want to import a lot of different content types you might want to check the Migrate Module out It supports Organic Groups. Migrate Documentation // Maybe this can help you some of the way Migrate Classes: Location CCK to Address Field Migrate Extras This might also give you a clue on how to do it. I know its Migrate OG
common-pile/stackexchange_filtered
Setting Itemsource for ControlTemplate I have created an AutocompleteBox and it works completely fine outside a ControlTemplate. When I place it within a Control template, the autocompletebox is no longer populated with any items. <ControlTemplate x:Key="EditAppointmentTemplate" TargetType="telerik:SchedulerDialog"> <Grid Margin="6"> <Grid.ColumnDefinitions> <ColumnDefinition Width="97" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="Participants" Margin="6 0" VerticalAlignment="Center" HorizontalAlignment="Left" /> <telerik:RadAutoCompleteBox Margin="6 0" Grid.Column="1" ItemsSource="{Binding Atts}" SelectedItems="{Binding SelectedAttendees,Mode=TwoWay}" DisplayMemberPath="DisplayName" TextSearchPath="Search" Style="{StaticResource MultiAutoBox}" WatermarkContent="Search ..." MinHeight="55" VerticalContentAlignment="Top" Padding="5"> </telerik:RadAutoCompleteBox> </Grid> </ControlTemplate> <Style x:Key="EditAppointmentDialogStyle" TargetType="telerik:SchedulerDialog"> .... <Setter Property="Template" Value="{StaticResource EditAppointmentTemplate}" /> .... <Style x:Key="EditAppointmentDialogStyle"/> <telerik:RadScheduleView x:Name="scheduleview" .... EditAppointmentDialogStyle="{StaticResource EditAppointmentDialogStyle}" .... <telerik:RadScheduleView x:Name="scheduleview"/> I'm thinking I have to set the ItemsSource to target a relative ancestor I tried the following and the itemsource isn't populating still. ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:SchedulerDialog}}, Path=Atts}" Control templates should be entirely self contained, as such your control should expose a dependency property (call it SuggestionsSource for example) to which the auto-complete box binds via a TemplateBinding. Where you use the dialog control you then bind said property to your DataContext property. In your dialogue class (if you want to extend the functionality of an existing control you will need a sub-class to introduce properties, here MySchedulerDialog) public static readonly DependencyProperty SuggestionsSourceProperty = DependencyProperty.Register("SuggestionsSource", typeof(IList), typeof(MySchedulerDialog), new UIPropertyMetadata(null)); public IList SuggestionsSource { get { return (IList)GetValue(SuggestionsSourceProperty); } set { SetValue(SuggestionsSourceProperty, value); } } In control template XAML: <telerik:RadAutoCompleteBox Margin="6 0" Grid.Column="1" ItemsSource="{TemplateBinding SuggestionsSource}" ...> Where you use the control: <local:MySchedulerDialog SuggestionsSource="{Bindings Atts}" .../> Could you possibly give me a snippet or PseudoCode so I can have a more indepth understand what you are referring to? @Master: You really should read up on control authoring on MSDN, added example anyway...
common-pile/stackexchange_filtered
`object' is undefined due to async function that fetched data in useEffect hook in reactjs I am fetching an object from api using axios.get("url"). The object fetched successfully (in Animal state) but there is a component level state (imageState) which requires updation using setState with fetched data. Code:Component: import React,{useEffect, useState} from 'react' import axios from 'axios' const AnimalDetail = ({match}) => { const [Animal ,setAnimal ] = useState({}) const Id = parseInt(match.params.id) const [imageState, setImageState] = useState (""); useEffect(()=>{ const fetchAnimal = async () => { const {data} = await axios.get(`/api/animals/${Id}`) setAnimal(data) } fetchAnimal() // setImageState(Animal.image[0]) // need to access first index of image object },[]) useEffect(()=>{ setImageState(Object.values(Animal.image)[0]) // error cant convert undefined to object } return ( <> <h2>imageState </h2> //undefined <h2>{typeof(Animal.image)}</h2> //gives object </> ) } export default AnimalDetail Backend Api : {"id":2, "image":["/image.jpg","/image2.jpg"], "price":60000, "breed":"", "isAvailable":true, "weight":110, } How can i fetch the data and update the component level state periodically(after fetching)? Can you console.log(data) and edit your post to tell me what you get? It looks like you declare imageState a second time after your useEffect. This is not the main problem, but you will need to delete that line eventually. Is there a compelling reason not to do setImageState(data.image[0]) inside fetchAnimal? @samuei yes there is no problem is doing that too. The real problem still here with me is the typeof(Animal.image) that gives object but when i just console.log(Animal.image) then i get Array ["img1",''img2"]. I actually need to map these images into divs. typeof returns "object" for arrays, so that's expected. @MichaelHoobler I assigned {data} to component state(Animal) and when i console.log(Animal) i get an object in console like this Object { id: 1, image: (1) […], breed: "", isAvailable: true, weight: 100, … }. You can try following, maybe this can help you. Removed the second useEffect and updated the image state in the first useEffect. And also I can see, you have declared const [imageState, setImageState] = useState (""); twice. You can remove the second one. Also, make sure you handle the API error in useEffect otherwise this may break the application on API failure. import React, { useEffect, useState } from 'react'; import axios from 'axios'; const AnimalDetail = ({ match }) => { const [Animal, setAnimal] = useState({}); const Id = parseInt(match.params.id); const [imageState, setImageState] = useState(''); useEffect(() => { const fetchAnimal = async () => { const { data } = await axios.get(`/api/animals/${Id}`); setAnimal(data); setImageState(data.image[0]); }; if (Id) { fetchAnimal(); } }, [Id]); return ( <> <h2>imageState </h2> //undefined <h2>{typeof Animal.image}</h2> //gives object </> ); }; export default AnimalDetail; your code has some error in the second useEffect. you can use this one : useEffect(() => { if (Animal) setImageState(Object.values(Animal.image)[0]); // error cant convert undefined to object }, [Animal]); this is because the Animal should have value first. and you are defining imageState two times in your code! the first one is enough.
common-pile/stackexchange_filtered
Erratic behavior of train_test_split() in scikit-learn Python 3.5 (anaconda install) SciKit 0.17.1 I just can't understand why train_test_split() has been giving me what I consider unreliable splits of a list of training cases. Here's an example. My list trnImgPaths has 3 classes, each one with 67 images (total 201 images): ['/Caltech101/ferry/image_0001.jpg', ... thru ... '/Caltech101/ferry/image_0067.jpg', '/Caltech101/laptop/image_0001.jpg', ... thru ... '/Caltech101/laptop/image_0067.jpg', '/Caltech101/airplane/image_0001.jpg', ... thru ... '/Caltech101/airplane/image_0067.jpg'] My list of targets trnImgTargets perfectly matches this both in length and also the classes themselves align perfectly with trnImgPaths. In[148]: len(trnImgPaths) Out[148]: 201 In[149]: len(trnImgTargets) Out[149]: 201 If I run: [trnImgs, testImgs, trnTargets, testTargets] = \ train_test_split(trnImgPaths, trnImgTargets, test_size=141, train_size=60, random_state=42) or [trnImgs, testImgs, trnTargets, testTargets] = \ train_test_split(trnImgPaths, trnImgTargets, test_size=0.7, train_size=0.3, random_state=42) or [trnImgs, testImgs, trnTargets, testTargets] = \ train_test_split(trnImgPaths, trnImgTargets, test_size=0.7, train_size=0.3) Although I end up getting: In[150]: len(trnImgs) Out[150]: 60 In[151]: len(testImgs) Out[151]: 141 In[152]: len(trnTargets) Out[152]: 60 In[153]: len(testTargets) Out[153]: 141 I never get a perfect split of 20 - 20 - 20 for the training set. I can tell because both by manual checking and doing a sanity check by confusion matrix. Here are the results for each experiment above, respectively: [[19 0 0] [ 0 21 0] [ 0 0 20]] [[19 0 0] [ 0 21 0] [ 0 0 20]] [[16 0 0] [ 0 22 0] [ 0 0 22]] I expected the split to be perfectly balanced. Any thoughts why this is happening? It even appears it may be misclassifying a few cases a priori, because there will never be n=22 training cases for a given class. In short: this is expected behaviour. Random splitting does not guarantee "balanced" splits. This is what stratified splitting is for (also implemented in sklearn). interesting... it's too bad I didn't find this "feature" in the docs, nor what kind of tolerance they implemented for the unequal selection of cases when random splitting -- train_test_split also has a stratified argument -- could that be used to lock in the n of cases? yes, you can also pass a specific values to stratify argument. For random splitting there is no "tolerance" - this is literaly random split, whatever is generated by random numbers generator - is used. Based on @lejlot comments, the way I managed to lock in the number of cases was using a new feature for train_test_split on SKLearn 0.17. There is now an argument called stratify, which I'm using as follow (this will force the split to follow the number of labels in your label list): [trnImgs, testImgs, trnTargets, testTargets] = \ train_test_split(trnImgPaths, trnImgTargets, test_size=0.7, train_size=0.3, stratify=trnImgTargets) Now, every time I run the script I get: [[20 0 0] [ 0 20 0] [ 0 0 20]]
common-pile/stackexchange_filtered
How to modify HttpServletRequest body in java? I would like to modify the request body before it reaches to Http Servlet and gets processed.The JSON Payload of the Request body is like following and I would like to get rid of the "PayamtChqmanViewObject" (Detail) part. { "ChqAccCode": "1", "ChqAmt": 1, "ChqBankCompCode": "TEST", "ChqBchName": "TEST", "ChqBchPost": "Y", "ChqPostDate":"2020-08-14", "ChqCompCode": "TEST", "ChqDate": "2020-04-21", "ChqDeptCode": "0", "ChqDesc": "TEST", "ChqDraftCode": "M", "ChqJobCode": null, "ChqJointVenName": null, "ChqNum": 123, "ChqPayeeAddr1": "Rome", "ChqPayeeAddr2": "1", "ChqPayeeAddr3": "Rome", "ChqPayeeCountry": "Italy", "ChqPayeeName1": "A1", "ChqPayeeName2": null, "ChqPayeePostalCode": "85695", "ChqPayeeRegCode": "IT", "ChqRecCode": "O", "ChqSeqNum": "1", "ChqVenCode": "ZZ", "ChqVouCode": null, "PayamtChqmanViewObj":[ { "PaCompCode": "ZZ", "PaChqCompCode": "ZZ", "PaVenCode": "ACME", "PaChqNum": 123, "PaPayCurrAmt": 1, "PaAmt": 1, "PaVouInvCode": "INV001", "PaDiscAmt": 0, "PaChqSeqNum": "1" } ] } I am able to get the Request Body with using following method, however I am not sure how to delete the detail part of the JSON and pass the processed request body to HTTP Servlet. public static String getBody(HttpServletRequest request) throws IOException { String body = null; StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream inputStream = request.getInputStream(); if (inputStream != null) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); char[] charBuffer = new char[128]; int bytesRead = -1; while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { stringBuilder.append(charBuffer, 0, bytesRead); } } else { stringBuilder.append(""); } } catch (IOException ex) { throw ex; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException ex) { throw ex; } } } body = stringBuilder.toString(); System.out.println("BODY IS:" + body); return body; } Thank you very much for the help! Why do you need to delete that part? It is needed for a certain business case. @obayral - your approach is completely wrong. The Servlet specification already has a robust mechanism for exactly what you're trying to accomplish. Please review Bogdan's response below. Please post back if you have questions; please be sure to "Upvote" and "Accept " his reply. @paulsm4 could you tell me why my approach is completely wrong? I have accepted the answer also. You can't change the request, but you could wrap it. See the following question for more details: Why do we wrap HttpServletRequest ? The api provides an HttpServletRequestWrapper but what do we gain from wrapping the request? You will need to put a servlet filter in front of your servlet to make the wrapping work. As for how to remove that part from the content, you could do it with plain old string manipulations from what the String class offers, or with something like StringUtils, or you could parse the JSON with a library of your choice, remove that property, then write it back as a string. Thanks for the answer! It gave me a better insight. I do have 2 follow up questions though. 1) I can't change the request, but can't I wrap the request into a form that I want? 2) I can do a classical parsing and String manipulations(this was my 1st approach also), however how can I pass this String to HttpRequest to be processed by the Servlet? Thanks. that's exactly what I'm saying in the answer. You wrap the original request into your own version with the help of HttpServletRequestWrapper. In your version you change what you want different and let everything else go through to the original request object you wrapped. 2) You will probably need to implement the getInputStream method in your wrapper to return an InputStream constructed from your String (maybe some other methods from the wrapper too, depending on what else you need). You then send the wrapper request to your servlet in the chain, not the original request.
common-pile/stackexchange_filtered
group two columns from DB in perl I am writing a script which needs grouping and I can't do them in the SQL. I get my results as ArrayReference. My query to the DB returns something like this. 1234 TIN 32364 TIN 34367 BOX 87484 TIN 45674 BOX 45476 TIN 4575 BOX I want them to be grouped like : These are the list of BOX: 4575,45674,34367. These are the list of TIN: 1234,32364,87484,45476. Any suggestions please? Use a group by in your query .... else you will have run through all the rows returned, search for BOX and TIN and store them in separate array accordingly Group by could be used only if you use aggregate function in your query. And I cant do any aggregate function in my columns. I have given just the two of them as example. I am having more than 10 types to search for. And the code look convoluted with too many if conditions.Correct me if I am wrong on Group by in SQL . Thanks @SipraMoon - Nonsense, of course you can do some aggregation in your database. That's one of the things that an RDBMS was built for! If you insist on not using the database for this, then the following code will do the basic grouping. # Assume data is in @rows my %group; push @{ $group{$_->[1]} }, $_->[0] for @rows; while (my ($key, $items) = each %group) { print "These are the list of $key: ". join(',', @$items) .".\n"; } So exactly what does your array reference look like? Is it an array of arrays like this: @myArray = [ [ 1234, TIN, ] [ 32364, TIN, ] 34367, BOX, ] ] Or an array of hashes: = [ { NUMBER => 1234, TYPE => TIN, } ] Or is each row a single return of some form of fetch? There are five different ways to return data from a database using the DBI interface: fetchrow_arrayref fetchrow_array fetchrow_hashref fetchall_arrayref fetchall_hashref Assuming you used fetchall_arrayref, here's a sample program that will do what you want: use strict; use warnings; use feature qw(say switch); use Data::Dumper; my $fetchedSqlData = [ [ qw(1234 tin) ], [ qw(3434 box) ], [ qw(4341 tin) ], [ qw(2343 box) ], ]; my @tinList; my @boxList; foreach my $row (@{$fetchedSqlData}) { if ($row->[1] eq "tin") { push @tinList => $row->[0]; } else { push @boxList => $row->[0]; } } say "These are the list of BOX: " . join ", " => @boxList; say "These are the list of TIN: " . join ", " => @tinList; A better way would be to have a single hash based upon the value in column 2 and each hash would be a reference to an array: my %typeHash; foreach my $row (@{$fetchedSqlData}) { $typeHash{$row->[1]} = [] if not exist $typeHash{$row->[1]}; push @{$typeHash{$row->[1]}} => $row->[0]; } This is a bit more confusing, but would be more flexible incase you added a type "CRATE" to your list. Printing out the data from this would be: foreach my $type (sort keys %typeHash) { say "These are the list of $type: " . join ", " => $typeHash{$type}->[0]; } BTW, I didn't test this hash of arrays, so expect coding errors. And, yes, I know I don't have to do $typeHash{$row->[1]) = [] if not exists $typeHash{$row->[1]}, but I like doing this because it makes sure I'm storing the right type of data in the hash element. To thoroughly test this, I would have to build a database, and do a DBI fetchall_arrayref to verify exactly how the data is returned. I'm basing this off my erratic memory on how DBI worked when I last used it and the documentation. There might be a way of doing this with map, but I generally haven't found map to be any more efficient than a simple loop.
common-pile/stackexchange_filtered
If $|f(z)| \geq |g(z)|$ for $z \in D$ and $E = \{ z \in D : |f(z)| =|g(z)| \}$ has a limit point, then $E=D$. This is my problem: Let $D := \{ z \in \mathbb{C} : |z| <1 \}$. Let $f$ and $g$ be analytic functions on $D$. Suppose $|f(z)| \geq |g(z)|$ for all $z \in D$. Define $E = \{ z \in D : |f(z)| =|g(z)| \}$. Show that if $E$ has a limit point in $D$, then $E=D$. This looks like it should be related to the identity theorem for analytic functions, but I can't seem to get it to work out. Going for a proof by contradiction, I assume that $E \;$ has a limit point in $D\;$ and that $E \neq D\;$. Then there is a sequence $z_n$ of points in $E$ which converges to a limit point $z_0$ in $D$. By continuity, $z_0 \in E$; that is, $f(z) = re^{i\theta}$ and $g(z) = re^{i\phi}$ for some $r$, $\theta$, and $\phi$. And here I stop. Any advice on how to proceed? Thanks. I think that you can use the maximum modulus principle to get what you want. Suppose first that $f$ has no zeros in the unit disk $D$. Then that means that $\dfrac{g(z)}{f(z)}$ is analytic in $D$. Then your condition that $|f(z)| \geq |g(z)|$ for every $z \in D$ translates to $$\left | \frac{g(z)}{f(z)} \right | \leq 1 \quad \text{for every $z \in D$}$$ Then since $E$ has a limit point in $D$, there is a sequence of points $z_n \in E$ such that $z_n \to a$ for some $a \in D$ and since for every $z_n \in E$ we have $\left | \dfrac{g(z_n)}{f(z_n)} \right | = 1$ then by continuity also $$\left | \frac{g(z_n)}{f(z_n)} \right | \to \left | \frac{g(a)}{f(a)} \right | $$ so $\left | \dfrac{g(a)}{f(a)} \right | = 1$. Thus we have that $$\left | \frac{g(z)}{f(z)} \right | \leq \left | \frac{g(a)}{f(a)} \right | \quad \text{for every $z \in D$}$$ so by the maximum modulus principle we conclude that $g/f$ is constant, say $g/f = c$ and $|c| = 1$. Then this implies that $|f(z)| = |g(z)|$ for all $z \in D$ and this implies that $E = D$ as you wanted to show. Now, what happens if $f$ has zeros in $D$? In this case you can use the inequality $|f(z)| \geq |g(z)|$ to conclude that if $f$ has a zero of order $n$ at $a \in D$, then $a$ is also a zero of $g$ of order $m$ and actually $m \geq n$. This implies that the quotient $g/f$ has removable singularities at the zeros of $f$ and then we can redefine the function at those points and again we would have $g/f$ analytic in $D$ and the previous argument applies. I have to admit that I'm not entirely convinced by this argument since I'm not really using the full hypothesis that $E$ has a limit point in $D$. For the maximum modulus principle I only need $E$ to be non empty. If someone spots a mistake I would appreciate it if you can point it out please. Thanks. Well, if you replace the assumption "E has a limit point in $D$" by "$E$ is not empty", then the statement is false : consider $f(z)=z$ and $g(z)=0$ for all $z$, for example. I think the issue here is that you have to rule out the case where $g$ is zero, for example by showing that there exists $z \in E$ with $f(z) \neq 0$. @Malik Thank you very much for pointing that out, you're absolutely right. I guess that now some things have to be modified. I'll try to see if I can fix the argument. You're welcome! The argument can probably be fixed by something like that : Set $F:= { z \in D : f(z)=0 }$. If $F=D$, then $f$ is identically zero and so is $g$, and the conclusion follows. If not, then $F$ has no accumulation point in $D$. Take a sequence of distinct points $z_n$ in $E$ with $z_n \rightarrow z_0 \in E$. Since $F$ has no accumulation point, for all $n$ sufficiently large we have that $z_n \notin F$. Then $|f(z_0)| = |g(z_0)|$ with $f(z_0) \neq 0$, and now you can apply the maximum modulus principle to conclude that $g/f$ has a maximum at $z_0$...
common-pile/stackexchange_filtered
best practice when order of calls in class are important? I have one class with two important functions: public class Foo { //plenty of properties here void DoSomeThing(){/*code to calculate results*/} void SaveSomething(){/* code to save the results in DB*/} } SaveSomething() uses the results calculated in DoSomeThing(). the problem is that we must not to call SaveSomething() before DoSomeThing() or if that happens the results are not true results. I mean order of calls are important, this is a problem in maintaining the code.(when new one is added to team). is there any way to manage this? I think of 3 methods as below throwing exception in SaveSomething() if it called before DoSomeThing() having a bool that are set in DoSomeThing() and SaveSomething() code changes to: bool resultsAreCalculated = false; void SaveSomething(){ if (!resultsAreCalculated) { DoSomeThing(); // the resultsAreCalculated = true; is set in DoSomeThing(); // can we throw some exception? } /* code to save the results in DB*/ } implementing it Fluent like : Foo x = new Foo(); x.DoSomeThing().SaveSomething(); in this case, it is important to guarantee that this is not happens: x.SaveSomething().DoSomeThing(); right now, i use the second method. is there any better way or is that enough? This isn't really code review, since it's not complete. You might want to post this on Stack Overflow, since it's a design question. @S.Lott yes, it is, but i think it is not to be complete code here. I post complete code, as a new question, mentioning 2 or 3 of answers here & then it feels more code review. BTW, this question is relevant to link. after 1.5 years of first launch when all team members are new(in this project, not in programming!). Code Review is for complete code. After all design decisions. That's what "review" means -- it means after all the work is done to create it. A design question goes on Stack Overflow. This isn't code, this is pseudocode for a design. It does not belong on Code Review. If you read Code Review FAQ, you'll see it clearly stated that Best Practice questions like this are off-topic. One option to help avoid user error is to make it clear by passing a variable. By doing this, it raises a flag for the user that they need to get the results (i.e. DoSomething()) before calling SaveSomething(...). results = DoSomething(); // returns the results to be saved SaveSomething(results); Confused a bit with this answer, since there is no way to upvote only second part of it. +1 anyway Edit: Removed 1st part. You're right - it's more of a tangent than a directly answering the question. Good call. Ideally methods that need to follow a certain order in execution denote, or imply the need to implement, a workflow of some sort. There are a couple of design patterns that support enforcing workflow-like linear execution order, such as the Template Method Pattern, or Strategy. To Take the Template Method approach, your Foo class will have an abstract base that defines the order of executing Do() and Save(), something like: public abstract class FooBase { protected abstract void DoSomeThing(); protected abstract void SaveSomething(); public void DoAndSave() { //Enforce Execution order DoSomeThing(); SaveSomething(); } } public class Foo : FooBase { protected override void DoSomeThing() { /*code to calculate results*/ } protected override void SaveSomething() { /* code to save the results in DB*/ } } This way You class consumers will only have access to DoAndSave() and they will not infract the order of execution you intended. There are another patterns that deals with workflow / state transition type of situations. You can refer to Chain of Command, and State Patterns. In response to your comment: This follows the same Template idea, you add another step in your template, imagine you want to validate the results before saving, you can extend your template to become: public abstract class FooBase { protected abstract void DoSomeThing(); protected abstract void SaveSomething(); protected abstract bool AreValidResults(); public void DoAndSave() { //Enforce Execution order DoSomeThing(); if (AreValidResults()) SaveSomething(); } } And of course for a more elaborate workflow I referred you to the state pattern at the end of my original answer, you can have a more granular control over the transition condition from one state to another. what if the mid results are needed by another part? for example if DoSomeThing() results are to be shown to user and then if they agree(click some where) then SaveSomething() happens? Please see my edited answer.. the comment section could not accomodate a lengthy reply. Just note that this would be just as vague for the maintainers of the DoAndSave() method. In this case, note the importance of the comment @Anas Karkoukli added. The comment becomes what will ensure the code is not broken by the maintainers. How about this? interface Result { void Save(); SomeData GetData(); } class Foo { Result DoSomething() { /* ... */ } } Usage: myFoo.DoSomething().Save(); //or something like: var result = myFoo.DoSomething(); if (result.GetData().Importance > threshold) result.Save(); From an outside perspective, this makes a lot of sense. A Result is produced and provides means of being saved, if desired, while the implementation is completely opaque. I don't have to worry about passing this back to the right Foo instance. In fact I can pass the result to objects, that don't even know the Foo instance that created it (in fact the creator should pass on all necessary information for saving to the result upon creation). The result may have a method to tell me, whether it has been saved already, if that is needed. And so on. This is basically just application of the SRP, although primarily on the interface rather than the implementation. Foo's interface provides means to produce results, Result abstracts means to manipulate results. Steve McConnel's excellent book Code Complete spends a whole chapter discussing this question. It's Chapter 14 in the second edition. If the order of statements is important, then it is very good practice to enforce that ordering with data. So rather than calculateResults(); saveResults(); (storing the results in instance variables) write Results r = calculateResults(); saveResults(r); It is then much harder to try to save the results before they are calculated. There is a clear indication of which the expected order is. yes, and then the Results are usable in someway, for example : UpdateUI(r); I like Anas Karkoukli's answer, but another alternative is a state machine. public class Foo { private enum State { AwaitingDo, AwaitingValidate, AwaitingSave, Saved } private State mState = State.AwaitingDo; private void Do() { // Do something mState = State.AwaitingValidate; } private void Validate() { // Do something mState = State.AwaitingSave; } private void Save() { // Do something mState = State.Saved; } public void MoveToNextState() { switch (mState) { case State.AwaitingDo: Do(); break; case State.AwaitingValidation: Validate(); break; case State.AwaitingSave: Save(); break; case State.Saved: throw new Exception("Nothing more to do."); break; } } } It's a bit slap-dash, but you get the idea. The problem with Anas' answer is that all of the functions are executed as a single step, which means you can't get to the intermediate stages of the object. A state machine forces developers to follow the workflow, but each at each stage of the workflow they can examine the properties of the object before moving on to the next. Expanding upon Levinaris' answer (+1 if I had the rep), you could alternatively have a Save() method on the results object returned from the DoSomthing() method. So you would get something like this: var obj = new Foo(); // Get results var results = obj.DoSomething(); // Check validity, and user acceptance if(this.AreValidResults(results) && this.UserAcceptsResults(results)) { // Save the results results.Save(); } else { // Ditch the results results.Dispose(); } Obviously this approach would require that the returned results object is either a generic type that handles the saving/disposing of results, but also contains the generic results; or it would need to be some form of base class that specific result types could inherit. Do and Save methods are not seems like an ordered pair to me. You need to order them only because you don't return the state of the calculation from the Do method. If you write Do method as a method that return the results to the client code, then you can rewrite Save, so it would receive the results as a parameter. Benefits: You don't need to order methods anymore, because Save method doesn't care how the client got the parameter. It just receives it at that's it. You can unit test Do method more easily, because methods become less coupled. You can move your Save method to another class, if you ever need to write a complex save logic or implement a repository pattern.
common-pile/stackexchange_filtered
How to sort by meridian (AM and PM) in C? I have an issue trying to make my program sort by AM and PM. It's part of the requirements for my assignment or I would've done it as 24 hour format. This is my code so far #include <stdio.h> struct date { int month; int day; int year; int hour; int min; int meridian; }; typedef enum {undergraduate, graduate, post_doc } StudentLevel; struct student { char name[20]; long int banner_id; struct date date_of_enrollment; struct date time_of_enrollment; StudentLevel level; }data[5]; int lessThan(struct student S1 , struct student S2) { struct date A = S1.date_of_enrollment; struct date B = S2.date_of_enrollment; struct date C = S1.time_of_enrollment; struct date D = S2.time_of_enrollment; if (A.year < B.year) return 1; else if (A.year == B.year && A.month < B.month) return 1; else if (A.year == B.year && A.month == B.month && A.day < B.day) return 1; else if (A.year == B.year && A.month == B.month && A.day == B.day && C.hour < D.hour) return 1; else if (A.year == B.year && A.month == B.month && A.day == B.day && C.hour == D.hour && C.min < D.min) return 1; else if (A.year == B.year && A.month == B.month && A.day == B.day && C.hour == D.hour && C.min == D.min & C.meridian < D.meridian) return 1; else return 0; } int sort(struct student *data) { int i, j; struct student x; for (i = 0; i < 5; i++){ for (j = 0; j < 5; j++){ if (lessThan(data[i], data[j])){ x = data[j]; data[j] = data[i]; data[i] = x; } } } return 0; } int main () { int i; printf ("Enter Name, Banner ID, the date of Enrollment (Month Day Year), the time of enrollemtn (Hour Min Meridian(am or pm) and Student Level(0=Undergraduate, 1=graduate, or 2=Post Doc): \n"); for (i=0;i<2;i++) scanf ("%s %ld %d %d %d %d %d %d %d",data[i].name,&data[i].banner_id, &data[i].date_of_enrollment.month,&data[i].date_of_enrollment.day, &data[i].date_of_enrollment.year, &data[i].time_of_enrollment.hour, &data[i].time_of_enrollment.min, &data[i].time_of_enrollment.meridian, &data[i].level); printf ("You entered : \n"); sort(data); for (i=0;i<2;i++) printf("%s %ld %d %d %d %d %d %d %d \n",data[i].name, data[i].banner_id,data[i].date_of_enrollment.month,data[i].date_of_enrollment.day,data[i].date_of_enrollment.year,data[i].time_of_enrollment.hour, data[i].time_of_enrollment.min, data[i].time_of_enrollment.meridian,data[i].level); return 0; } The program just doesn't seem to want to sort by meridian. I also don't know how to tell it how to do it though so it's entirely my fault. Any tips would be greatly appreciated. Why use it at all, just use 24H time notation, and convert to 12H when displaying. Or even easier, use ISO8601 dates, they sort alphabetically. It's part of the requirements for my assignment sadly. It's a stupid requirement, because it is Bad Design. But, that won't help you. It is quite simple though. You are missing one & in your last comparison: C.min == D.min & C.meridian < D.meridian should be C.min == D.min && C.meridian < D.meridian How is meridien stored? I was planning on doing it as a enum as i did with under, grad, and post doc. That's what I'm working on at the moment. Feel as it'd make it easier. Yet it is an int. You should use 0 for AM and 1 for PM. Thank you so much! Let me work on it a bit more and I will report back. Thank you for time, Bart! I have a question, it took forever to print out the correct answer. I thought it didn't work. Any way to fix that? Got it to work. Thank you! Oh and I realized that i had a \n at the end of scanf which caused the problem.
common-pile/stackexchange_filtered
Maximizing an integral over a convex region Let $C$ denote a compact, convex region in the plane containing the origin with unit area, and let $f$ be a probability distribution on $C$. Let $f^\ast$ denote the distribution that maximizes the quantity $$\mathcal{G}(f):=\iint_C a\sqrt{f(x)} + b\|x\|f(x)~dx $$ where $a$ and $b$ are given constants. I'm interested in bounding $\mathcal{G}(f^\ast)$ from above. Clearly, we know that $\mathcal{G}(f^\ast)\leq a + b\max_{x\in C} \|x\|$ because we have $\iint_C \sqrt{f(x)}\leq 1~dx$ and $\iint_C \|x\|f(x)~dx\leq \max_{x\in C} \|x\|$. Are there any tighter upper bounds for this expression? You should be able to solve for $f^*$ directly. Let $f(x)=g(x)^2$, then you have the following stationarity condition: $a + 2(b||x|| -\mu) g(x)=0$, where $\mu$ is a Lagrange multiplier. So you just have to solve for the $\mu$ that gives $\int_C g(x)^2=1$.
common-pile/stackexchange_filtered
Image in Widget not appearing on device but working fine on Emulator. How to fix? I made a widget which reads an image from internal storage and displays it in an ImageView. It is working fine on the emulator (Android 2.3.3. API Level 10) but when I run it on my device (Droid Razr Android 2.3.6), it does not display the image. The widget is there on the screen but its just blank. Other parts of the widget are working fine like the Configuration Activity etc. Only the image is not appearing. What could be wrong ? Thanks for your help! What you probably want to do is share any relevant code and/or research into the problem you've already done. That way folks will have a better idea of what's going on in your code. I found out where I was going wrong. Anyways, will keep in mind to post some code in the future. In that case, add an answer to your own question so folks will know how you solved it. Okay I fixed it. In my Storage class through which I store and read images from internal memory, there is a function that takes the fileName as a parameter. Now this fileName was to be used when making the final call to store it. Instead, I had written "fileName". So there was only one file in the storage named fileName. This led to problems when reading from the storage using the actual fileName. I have two suggestions of what could be wrong: Your file may not be where specified on your device You may not have read permission for the file; try issuing chmod a+r yourfile in an adb shell I changed the method by which it displays the image. Using RemoteView, I setup the ImageView bitmap from the Configuration Activity instead of widget reading the image from storage. Still same problem. Works on emulator but not on device.
common-pile/stackexchange_filtered
Sparse consolidation Algorithm in Congos TM1 How do the sparse consolidation algorithm helps to improve the Cognos TM1 performance? what is sparse consolidation algorithm? I found a concise description here: Cognos TM1 Rules – how do they really work? During consolidations, TM1 uses a sparse consolidation algorithm to skip over cells that contain zero or are empty. This algorithm speeds up consolidation calculations in cubes that are highly sparse. A comprehensive post on TM1 rules and consolidation: Skipcheck Feeders in TM1 It gives step by step process on how rules and consolidation works in TM1 and how skipcheck and feeders are used to improve the calculation speed.
common-pile/stackexchange_filtered
Running python cgi script Interpreter results differ to browser I was having difficulty converting a program I made to a cgi script. I suspected it was to do with os.walk so I made a smaller test script to test this. (I noticed the single \ before the D in the variable loc and tried changing that to a double \ still no change) Produces no errors cant tell why it doesn't run the for loop with os.walk in the browser. I tried adding some data into s and run for loop printing of contents of it and that worked fine, but trying to do it on os.walk I can't seem to get it to work. I can't find anything relating to the issue on google or stackoverflow. Below is the code: import cgi,cgitb,os loc = "C:\\Users\\wen\Desktop\\sample data\\old py stuff\\" cgitb.enable(display=1,logdir=loc) s = [] print("Content-type:text/html\r\n\r\n") print("<html>") print("<body>") print("<p>"+loc+"</p>") for r,ds,fs in os.walk(loc): print("<p>omgwtf</p>") for f in fs: s.append(f) for i in s: print("<p>"+i+"</p>") print("</body>") print("</html>") Took a screenshot, the output in interpreter on the left and browser on right i.imgur.com/136y1Yq.jpg webserver is running iis7 I'm pretty sure I've solved the problem, I needed to give the folders permissions for 'Authenticated users'.
common-pile/stackexchange_filtered
Google analytics in android and campaigns sources in play store I've got a question regarding google analytics in Android and campaigns. I've read all tutorials regarding implementing GA in Android application and I think that I managed to do this correctly, since "something" is showing in GA panels (i.e. that application was downloaded, how many times etc.). But I've got problem with gathering campaigns info (or with checking if this was implemented properly). After implemented what is written HERE and tested in a way that was described HERE everything were looking good. However, when I put application to play store (but as an alpha version) and I tried to used link generated with helper tool for url with campaigns nothing happens (in GA it shows that application was downloaded but with "none" campaign). So my question will be: Is this happening because this is an alpha and url is not handling this well or because I've done something wrong, since GA and campaigns should work with alpha version too. At the end I only want to add, that in my case I want only tracking sources from which my app were downloaded.
common-pile/stackexchange_filtered
Custom Post Types database persistance. Why not? My background is .NET/C#/Laravel e.t.c I am beginning to like very much WP and i started educating myself on using WordPress as a development framework. I tried something very simple. Create an entity and have a basic CRUD on this entity and then show it up in my frontend. Nothing tricky right? So after reading i found out that one way to do this is to create the entity (aka Custom Post Type) , create custom fields (aka my entity properties) and let WP backend do the CRUD. Then i could use various techniques to show the data in the frontend. To my great surprise i found out that the CPT are not persisted in any wp table, and that when i disable my plugin i loos ethe CPT but i do NOT loose the underlying data!! Imagine my surprise , due to the fact that i am used in having absolute db integrity. And i wonder , why was it decided that CPTs are working in this way? I don't understand the problem. If a plugin that register a CPT is disabled, then that content type won't exist anymore, it's fine. I think it is not good idea to delete the data on plugin deactivation but it could be fine to delete it when the plugin is removed. Most plugins do nothing and leave the data on database but you can choose to delete it, it is totally up to you. Anyway, if you develop a plugin for the public, you should notice to the users that data will be lost if they remove the plugin or make it optional. Imaging users loosing data just because they click on a button. What db integrity is lost? Per your own statements, the data persists in the database, unless intentionally removed by the plugin that created it. @s_ha_dum You can remove the CPT and leave custom taxonomy data for thsi CPT to exist in db. In my eyes things like these seem strange. I am just trying to understand and "feel" the WP way...dont get me wrong... I don't think there is definitive answer (there might be old discussion buried in some ticket), but I can offer some historical perspective. WordPress didn't start with Custom Post Types. They were relatively late addition. While they were modeled after native post types, those still remain kind of special case. So the concept of such split was kind of already in place — post data was stored in database and logic governing it was stored in runtime code, before CPTs even existed. In addition WP hooks system and plugin activation/deactivation favor runtime code approach as well. Implementing activation/deactivation in plugins is kind of clunky and most plugins simply don't bother with those routines. For a long time themes didn't even have a way to run activation/deactivation logic without some creative hacks. Additionally post registrations contain localized strings and WP localization workflow works by extracting strings from source code. Storing those in database would require having two different workflows for compiling list of localized strings. As well as hugely complicate their changes on updates. In a nutshell — the implementation is simply consistent with WP history and typical practices. Things are clearer..i am navigating probably in the line that decides if you need WP for your needs or not. Ultimately if one want to have a simple /moderate CRUD operation where he turns too? CPTs with Custom taxonomies and custom fileds, or he does go the way of custom tables? Custom tables are considered kind of last resort in WP. People use them, but not until they are really sure they need them. So if someone needs to make a simple CRUD and display operation what he does? Take Gravity forms to interact with CPT? I mean that eventaully i am feeling like WP has a very very distinct line that says dotn use me from this point on..A line that many people seem to ignore and try to hack wp to do what they need. Yeah, plugins/frameworks are basic approaches to it.
common-pile/stackexchange_filtered
Code style of method chaining within Zend this has previously been asked here (http://framework.zend.com/issues/browse/ZF-11135) with no response from Zend so really it has to come down to popular or majority decision. The reason I am asking is because the company that I work for are increasing in size and having a standard style is obviously a sensible approach. One example that is ignored from the example linked above is multiple methods per line, I.e $this->setAction()->setMethod()->etc() ->etc()->andSoForth(); Which assists in the compliance of line length. So whats your personal opinion? Method chaining can get a little hard to follow on long lines, but if you add a return before each method call then it is perfectly readable and saves repetitively typing the class variable. Regarding the question asked at http://framework.zend.com/issues/browse/ZF-11135 - the first and second code examples are identical - should they be showing a difference? Thanks for the response. Please accept my apologies I actually posted the wrong link :) The first example is method chaining on multiple lines and the second example if ensuring that each method call is always returned to the next line.
common-pile/stackexchange_filtered
Finding the law of X - Y when X and Y are not independent I have the following joint density: $$ f_{X,Y}(x,y) =\frac{2}{(1+x)^3} (0<y<x) $$ I want to find the density of X - Y. Now, I found that $f_X(x) = \frac{1}{x} (0<x<\infty)$ and $ f_Y(y) = \mathbb{1} (0,x)$, so X and Y are not independent. I want to use the following formula that gives me the density function of Z = X + Y: $$ f_Z(z) = \int f_{X,Y}(x,z-x)dx $$ However I am not sure how should I change it to get the density of X - Y. I tried using $x - z$ instead of $z-x$ but it does not work. Any hint? No need to write down marginal densities. $P(X-Y\leq t) =\int _0^{\infty} \int _y ^{y+t} \frac 2 {(1+x)^{3}} dx dy=1-\frac 1 {1+t}$ for $t \geq 0$ and $0$ for $t <0$. Hence the density of $X-Y$ is $\frac 1 {(1+t)^{2}}, 0<t<\infty$. [ To get the limits for integration note that When $t >0$, $x-y < t$ and $0 <y<x$ are equivalent to $y<x<y+t$ and $ x >0$ I see. Can I say that X - Y and Y are not independent even though they have the same law because X and Y are not independent?
common-pile/stackexchange_filtered
WebRTC screen sharing quality in Chrome I'm using the following RecordRTC demo for recording a video of the user's desktop. When using Firefox, the produced video has correct resolution (in my case, it's 2880x1800). But when using Chrome, the produced video's resolution is only 50% of the original one, meaning 1440x900. Is there any limitation for video resolution on Chrome, when using screen sharing? Thanks! There are limitation in the Codec that are used by WebRTC, Chrome uses different codecs than Firefox. You have VP8, VP9 and h264. Also the whole implementation of WebRTC is made by the browsers themselves, so default settings will differ. Is there anything I can do to make use the original resolution? I've used all of the codecs you mentioned, and they all generate a smaller resolution. You can set the resolution right? I have no experience with desktop capturing,but with camera you can do it.
common-pile/stackexchange_filtered
Compile error "already defined" It looks like this: error LNK2005: "unsigned long __cdecl GetModuleBase(void *, class std::basic_string<char,struct std::char_traits<char>, class std::allocator<char> > &)" (?GetModuleBase@@YAKPAXAAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined And code i have recently added: #include "Windows.h" #include <TlHelp32.h> #include <psapi.h> #include <string> #pragma comment(lib, "psapi") //#pragma comment(lib, "TlHelp32") i could not find where this lib located using namespace std; DWORD GetModuleBase(HANDLE hProc, string &sModuleName) { HMODULE *hModules; char szBuf[50]; DWORD cModules; DWORD dwBase = -1; //------ EnumProcessModules(hProc, hModules, 0, &cModules); hModules = new HMODULE[cModules/sizeof(HMODULE)]; if(EnumProcessModules(hProc, hModules, cModules/sizeof(HMODULE), &cModules)) { for(int i = 0; i < cModules/sizeof(HMODULE); i++) { if(GetModuleBaseName(hProc, hModules[i], szBuf, sizeof(szBuf))) { if(sModuleName.compare(szBuf) == 0) { dwBase = (DWORD)hModules[i]; break; } } } } delete[] hModules; return dwBase; } I dont understand what is this, maybe i am using wrong code? Or TlHelp32.lib is needed, but VS says it cannot find such static library. Are your headers guarded with #ifndef macro? of course not pragma. That's a link error, not a compiler error. It suggests that you have two functions called GetModuleBase with the same signature. Perhaps you are linking the same code twice? GetModuleBase function is defined more than once in the project. Maybe it is defined in two different .cpp files, or in h-file which is included to different .cpp files. There is a GetModuleBase function in the namespace Microsoft::WRL. Your code includes the Microsoft's function (in another part of the project, it's internal), so during link phase it raises an error. Change the name of the function or use a namespace. I wondered about this but in a C++ program it should be possible to have two different functions with the same name as long as the signatures are different. Thanks, but i've solved my problem (i am sorry) it was include error (i put the function code to header without declaration, probably this was the problem). @john: you're right, but as the error says, there is something wrong during the link phase (C++ compiler says all ok). Then as Loryan55 has explained, the declaration was missing. Your GetModuleBase() function is defined twice and the linker is having trouble resolving the conflict. Do a search for "GetModuleBase" and you will find it. Ideally you will declare the function prototype once in a header like so: DWORD GetModuleBase(HANDLE hProc, string &sModuleName); Use header guards or at least this preprocessor directive at the top of your header file: #pragma once Then define GetModuleBase() once in a .cpp file, in this .cpp file you need to include the header file. Remove any additional declarations or definitions for this function and your problem should be solved. Anytime you have this problem the fast solution is to CTRL-F to open the find prompt and search for the function name, you will quickly identify the conflict with this method.
common-pile/stackexchange_filtered
plugin:vite:import-analysis Failed to resolve import "../components/x.vue" from "src\router\index.js". Does the file exist? In my Vue JS application, I have the following js inside src/routes index.js import { createRouter, createWebHistory } from "vue-router"; import Dashboard from '../views/Dashboard.vue'; import Customers from '../views/Customers.vue'; import Login from '../views/Login.vue'; import Register from '../views/Register.vue'; import DefaultLayout from '../components/DefaultLayout.vue'; import AuthLayout from '../components/AuthtLayout.vue'; import store from "../store"; const routes = [ { path : '/', redirect : '/dashboard', component : DefaultLayout, meta : { requiresAuth : true }, children : [ {path : '/dashboard', name : 'Dashboard', component : Dashboard}, {path : '/customers', name : 'Customers', component : Customers} ] }, { path : '/auth', redirect : '/login', name : 'Auth', component : AuthLayout, children:[ { path : '/login', name : 'Login', component : Login, }, { path : '/register', name : 'Register', component : Register, }, ], }, ]; const router = createRouter({ history : createWebHistory(), routes }) router.beforeEach((to, from, next) => { if(to.meta.requiresAuth && !store.state.user.token){ next({name : 'Login'}) } else if (store.state.user.token && ( to.name === 'Login' || to.name === 'Register' ) ) { next({ name : 'Dashboard' }); } else{ next () } }) export default router; And I have the following Login.vue inside src/views. <template> <div> <img class="mx-auto h-12 w-auto" src="https://tailwindui.com/img/logos/workflow-mark-indigo-600.svg" alt="Workflow" /> <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900"> Sign in to your account </h2> <p class="mt-2 text-center text-sm text-gray-600"> Or {{ ' ' }} <a href="#" class="font-medium text-indigo-600 hover:text-indigo-500"> start your 14-day free trial </a> </p> </div> <form class="mt-8 space-y-6" action="#" method="POST"> <input type="hidden" name="remember" value="true" /> <div class="rounded-md shadow-sm -space-y-px"> <div> <label for="email-address" class="sr-only">Email address</label> <input id="email-address" name="email" type="email" autocomplete="email" required="" class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Email address" /> </div> <div> <label for="password" class="sr-only">Password</label> <input id="password" name="password" type="password" autocomplete="current-password" required="" class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Password" /> </div> </div> <div class="flex items-center justify-between"> <div class="flex items-center"> <input id="remember-me" name="remember-me" type="checkbox" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded" /> <label for="remember-me" class="ml-2 block text-sm text-gray-900"> Remember me </label> </div> <div class="text-sm"> <a href="#" class="font-medium text-indigo-600 hover:text-indigo-500"> Forgot your password? </a> </div> </div> <div> <button type="submit" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"> <span class="absolute left-0 inset-y-0 flex items-center pl-3"> <LockClosedIcon class="h-5 w-5 text-indigo-500 group-hover:text-indigo-400" aria-hidden="true" /> </span> Sign in </button> </div> </form> </template> <script> import { LockClosedIcon } from '@heroicons/vue/solid' export default { components: { LockClosedIcon, }, } </script> Then I have a component called, AuthLayout.vue inside src/components <template> <div class="min-h-full flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8"> <div class="max-w-md w-full space-y-8"> <div> <router-view></router-view> </div> </div> </template> <script> import { LockClosedIcon } from '@heroicons/vue/solid' export default { components: { LockClosedIcon, }, } </script> Every time I tried to run my application, it kept giving me the following errors. [plugin:vite:import-analysis] Failed to resolve import "../components/AuthtLayout.vue" from "src\router\index.js". Does the file exist? When I comment import AuthLayout from '../components/AuthtLayout.vue'; from the index.js application runs fine. But every time I try to enable it, it gives me an error. I'm using tailwind CSS and Vue 3 seems you have typo in authtLayout.vue with extra t [plugin:vite:import-analysis] Failed to resolve import "../components/AuthtLayout.vue" from "src\router\index.js". Does the file exist? You have a typo in AuthtLayout.vue (extra T). Change to AuthLayout.vue might help For me, Webstorm imported without the .vue extension that triggered the error. dropping the comment in case someone faces the same issue.
common-pile/stackexchange_filtered
Turning MapsForge project into a navigation app using Graphhopper I am trying to make a basic navigation app from my MapsForge project. It seems there is no MapsForge library for Navigation. I found out that it could be done with Graphhopper but I couldn't find any Jar files of it either. Is there any Graphhopper libraries that i can add to my project or is there any other way including Graphhopper to my project? Use maven or gradle via the snippet provided at https://graphhopper.com/#community or see the sample application in the repo
common-pile/stackexchange_filtered
When does malloc not call mmap? I'm studying operating systems at university and one of my tasks was find situation when malloc() doesn't cause mmap() system call. I used strace linux utility to trace system calls, but in my situation I saw mmap() syscalls every time when malloc() was used. Is malloc() always call mmap() or not? Thanks Note that you can simply get and read the source code of whatever memory allocator your system uses (or a custom one like jemalloc or tcmalloc). It is very instructive. Or you can look at informal documentation malloc() usually calls a user-space sub-allocator for performance reasons. A syscall for more space can be made if the sub-allocator runs out. I'd bet $0.02 that the malloc() shipped with Microsoft compilers does not call mmap() at all :-) ...or virtualAlloc(), or similar API :) This is defined neither by C, C++ nor the POSIX standard. Is malloc() always call mmap() or not? Not necessarly. This depends on the malloc implementation, configuration and the size of the allocation and possibly other factors. If using glibc: Tunable: glibc.malloc.mmap_threshold This tunable supersedes the MALLOC_MMAP_THRESHOLD_ environment variable and is identical in features. When this tunable is set, all chunks larger than this value in bytes are allocated outside the normal heap, using the mmap system call. This way it is guaranteed that the memory for these chunks can be returned to the system on free. Note that requests smaller than this threshold might still be allocated via mmap. If this tunable is not set, the default value is set to ‘131072’ bytes and the threshold is adjusted dynamically to suit the allocation patterns of the program. If the tunable is set, the dynamic adjustment is disabled and the value is set as static. If not using glibc, then consult the documentation or source of the implementation that you use. I saw mmap() syscalls every time when malloc() was used. This statement is similar in spirit to saying "There's no way to get to work today" - it only makes sense when lots of context is known. You'd have to disclose the exact benchmark you were using, glibc version, distro, etc. I'm pretty sure that if you're allocating lots of small objects (e.g. 16-32 bytes), you will not be seeing mmap() on every call. Syscalls are performance hogs when compared to "limited" operations on data structures, so malloc() would perform very poorly if it really always invoked mmap(), no matter the circumstances. Sure, if you were always calling it like malloc(1024), then yes, it may end up mmap()-ing often. And you'd also want to see what sort of mmap() arguments were passed. So, all I see here is that your benchmark somehow is skewed against you :)
common-pile/stackexchange_filtered
popen returns error when executing python script containing logging I have 2 python scripts where 1 is using subprocess to execute the other, see below: main.py import subprocess command = ['python', 'logging_test.py'] proc1 = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc1.communicate() print('Output returned from command: {}'.format(out)) print('Error returned from command: {}'.format(err)) logging_test.py import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('log') logger.info('hello') When running main.py I get this as the output: Output returned from command: Error returned from command: INFO:log:hello I would expect for the log message to be returned by stdout, not stderr... Does anyone know why it is getting returned as an error? Standard error is for diagnostics as well as error messages. basicConfig, among other things, provides a StreamHandler for the root logger. By default, a new StreamHandler writes to standard error. Ahhh okay, thanks! setting stream=sys.stdout in basicConfig or StreamHandler resolves this for me.
common-pile/stackexchange_filtered
How can you remove a field from a word document? I'm working on a project where the user can insert data into a document using fields, document properties and variables. The user also needs to be able to remove the data from the document. So far, I've managed to remove the document property and variable, but I'm not sure how I would go about removing the field (that's already inserted into the document). Note that I need to compare the field to a string, and if it matches; delete it from the doc. I'm assuming you're using .NET Interop with Word. In that case, I believe you're looking for Field.Delete. This is of course also assuming you know how to get the field you're looking for, which would usually be enumerating through _Document.Fields (or a more finite range if you know one) until you get the right one. Thank you kindly for your response. I'm currently enumerating through all the document fields, but how do I read the field information? For example: {DOCPROPERTY MyField /Mergeformat/} How would I be able to get the "MyField" programmatically? I cannot find the right property in my field to compare it to. @Kevin van Zanten - Is Field.Code.Text what you're looking for? Yes, that's exactly what I needed, thank you to you as well sir! @Kevin van Zanten - Sure thing. Interop can be a bit annoying (and the documentation is rather trial-and-error-ish at times). Sometimes it's just worth setting a breakpoint and playing around with intellisense in the immediate window until you find what you're looking for. The Field has a Delete method. See the documentation for Field.Delete. So I think something like this would work: foreach(Field f in ActiveDocument.Fields) { f.Select(); if(f.Type == TypeYouWantToDelete) { d.Delete(); } }
common-pile/stackexchange_filtered
Static analysis for a specification document (boston housing authority) I want to do a static analysis for a bunch of specification documents. the specification documents are the Boston Housing Authority - "intake and screening", "leased housing" , and "Inspections" (http://www.bostonhousing.org/detpages/deptinfo128.html). I know I am suppose to inspect the documents; but the requirements look perfectly stated and specified, so I don't know what else I should do. Please how should I go about it?
common-pile/stackexchange_filtered
How to remove what are apparently control characters in notepad++? I have some entries in notepad++ ive never seen before. I have highlighted squares on many lines with SGCI SSA PU1 PU2 MW and SPA within which if copy/pasted here all translate to/become `` I'm looking for a way to remove these from the entries. Google indicates they are "control characters" but there are far too many for me to try and remove manually. tried [\x00-\x09\x0B-\x0C\x0E-\x1F] but apparently it did not/does not cover the offending characters. here is an example of some lines just in case my original post wasn't clear enough. Here is the file itself. https://www.dropbox.com/s/lymgnxy9p0atp8x/TrophyID.txt?dl=0 Is it possible for you to share the file or part of it for others to have a look? Because replacing them the way @Toto proposed should have worked. Yes, im afraid it's due to user error somehow. he's helped me several times and is always spot on. I added a link to the file to the OP. @klepp0906 Please do not link to a direct file download, instead pasting the file's contents onto PasteBin, then linking to it. (Linking to a direct file download is an unnecessary security risk for any trying to help.) notepad++ has a menu entry for encoding which lets you change to UTF-8. The answers are well-meaning but ultimately not that useful. @JW0914 roger that! @ThomasDickey yea i noticed that and it was already on UTF-8 by default. Unless that was the incorrect choice. It could have been copied from some (program) which didn't identify the encoding properly, and sent doubly-encoded data. It's hard to say, from the limited sample. but codes in 0x80 to 0x9f range are more likely from UTF-8 than valid printable characters. All these characters are UTF8 Ctrl+H Find what: [\x{0080}-\x{0099}] or [\x00-\x09\x0B-\x0C\x0E-\x1F] Replace with: LEAVE EMPTY or whatever you want CHECK Wrap around CHECK Regular expression Replace all Explanation: [ # character class \x{0080} # from character http://www.fileformat.info/info/unicode/char/0080/index.htm - # upto \x{0099} # character http://www.fileformat.info/info/unicode/char/0099/index.htm ] # end character class [ # character class \x00-\x09 # hex 00 to 09 \x0B-\x0C # hex 0B to 0C \x0E-\x1F # hex 0E to 1F ] # end character class You can adapt the range to fit exactly your needs. Screenshot (before): I've taken some lines from your example file. Screenshot (after): Here I've used XXX as replacement to see where the replacement has been done. this did the trick, perhaps i should have provided more information in the OP from the get-go. Once again, thank you for your time and help! @klepp0906: You're welcome, glad it helps. @Toto Great answer, but its layout/presentation is discombobulated. Second example worked for me. But this did not get rid of "DEL" control characters. SGCI or 'Single Graphic Character Introducer' (U+0099) and PU2, or rather 'Private Use Two' (U+0092) are part of the 'Latin-1-supplement' block which goes from [\x80-\xFF]. Here you can see all the characters in this block. So to remove both SGCI and PU2 you need to find: [\x99\x92] Replace by nothing. I've extented to more characters, there are also STS, CCH and some other. thank you for the reference. I'll slowly pick up this gnarly regex stuff. that reference in comparison to your expression and toto's affords me the ability to manipulate what is kept and what is omitted in the future. filed away! I flagged his as the answer as it evidently came in first but both work perfectly. It is possible that "Show All Characters" and/or "Show White Space and TAB" are enabled. Disable them by going to View -> Show Symbol, then selecting them. unfortunately they were not, thank you though. I'll know to look here if I get any related funny-business in the future. Ctrl+H Find what: [\x00-\x09\x0B-\x0C\x0E-\x1F] Replace with: LEAVE EMPTY CHECK Wrap around CHECK Regular expression Replace all Explanation: [ # character class \x00-\x09 # hexa 00 to 09 \x0B-\x0C # hexa 0B to 0C \x0E-\x1F # hexa 0E to 1F ] # end character class Screenshot (before): Screenshot (after): unfortunately this did not work. 0 occurrences were replaced. unsure if relevant - but your before screenshot shows none of the highlighted strings/characters that are giving me trouble. I assumed the regex blanket/covered them all - evidently not the case. Please let me know if anymore information will help! I edited my OP with a few images. @Toto Why did you post a second answer that's the same as the first? Different regex values doesn't equal a new answer.
common-pile/stackexchange_filtered
On Windows 11 INTL layout automatially appears every x weeks (randomly) This INTL layout appears suddently from nowhere: And it is not reflected in settings, only my normal layout: So to remove it, I have to add it first using "Add a keyboard" (this costs me a lot of time and concentration because there is no search field in dropdown used to select layout options): and then remove, and it disappears for some time So obviously it is bug. Question how to fix it? PS: Why it is so important: US INTL is especially annoying for me as a Software Developer because it does not allow to enter single quote characters so I never would like to see it On the next day after removal INTL appeared again, I executed Get-WinUserLanguageList immidiately once I saw INTL in taskbar again: PS C:\Users\ivan> Get-WinUserLanguageList LanguageTag : en-US Autonym : English (United States) EnglishName : English LocalizedName : English (United States) ScriptName : Latin InputMethodTips : {0409:00000409} Spellchecking : True Handwriting : False Then, as always I have to go to "Add a keyboard" select "United States International" in Options -> Keyboards to remove it. Now WinUserLanguageList is: LanguageTag : en-US Autonym : English (United States) EnglishName : English LocalizedName : English (United States) ScriptName : Latin InputMethodTips : {0409:00000409, 0409:00020409} Spellchecking : True Handwriting : False And after that once I removed it from Keyboards LanguageTag : en-US Autonym : English (United States) EnglishName : English LocalizedName : English (United States) ScriptName : Latin InputMethodTips : {0409:00000409} Spellchecking : True Handwriting : False So when I see fake INTL keyboard in taskbar, in fact Get-WinUserLanguageList does not show 0409:00020409 Here is My Windows version: PS C:\Users\ivan> [System.Environment]::OSVersion.Version Major Minor Build Revision ----- ----- ----- -------- 10 0 22000 0 From specs: Edition Windows 11 Pro Version 21H2 Installed on ‎12/‎6/‎2021 OS build 22000.438 Experience Windows Feature Experience Pack 1000.22000.438.0 Can you provide us the output of Get-WinUserLanguageList by editing your question? We also need the Windows 11 version of this window Actually, International does allow single quotes, but you do have to follow each ' keystroke with spacebar [which I'm sure would also be annoying if you weren't expecting it] @Ramhound thanks, added, today issue was reproduced again I am wondering if this is a setting that is being pushed from e.g. a Microsoft account based on settings used on another device. (cloud-based roaming profile)
common-pile/stackexchange_filtered
After Image drag and drop make AJAX save to save image and its class I have a page where i am dragging image from one div and dropping it into another div. After drop event user has to click the save button for saving the data in database by making a get request .But after the button is clicked page is refreshed and that image is again in the previous div. so what i can do to make a AJAX call so that image and its class is saved after drop event ? javascript $(function() { adFitsApp.set_app_cookie("{{ adftoken }}", "{{ adfdy }}"); $('#sortable1 img').css("cursor", "pointer"); $( "#sortable1 div" ).sortable({ connectWith: "div", stop: function( event, ui ) { if($('#sortable2').find('img').length==6) { $('#btn-start').html("<a id='btn-start' href='/dashboard/redeem/{{ pk }}' >Redeem Coupon</a>"); } } }); $( "#sortable2" ).sortable({ connectWith: "div", change: function( event, ui ) { var theID = ui.item.attr('id'); ui.item.addClass(theID + '-style'); } }); $('#sortable2').find('img').length }); after every drop event save the images to db by ajax and then load the second div with saved images in db Or you may use cookies. Ajax Sorry but I have no knowledge of ajax can you please give a demo how I can do that Ajax is basically just a way to send requests in JS (JQuery) Using it is really simple: $("element").on("event", function() { $.ajax({ url: "your_url", data: {your: "data"}, success: function(data) { //success }, error: function(data) { //error } }); }); Code For you, I'd try this: <div class="control-group"> <a id="btn-start" href="/dashboard/save" data-pk="{{ pk }}" class="btn btn-primary btn-embossed">Save</a> </div> $("#btn-start").on("click", function() { $.ajax({ url: $(this).attr("href"), data: {pk: $(this).data("pk")}, success: function(data) { //success here }, error: function(data) { //error here } }); });
common-pile/stackexchange_filtered
Windows telnet different local echo behavior When I connect to a web server using telnet on port 80, I need to enable local echo to see what I type. However, when I connect to a POP3 server (port 110) the local echo seems to be enabled by default. Why is that? What is the difference? This may be more of a superuser question.
common-pile/stackexchange_filtered
illegal access to loading collection error I'm getting the error Illegal access to loading collection when I'm trying to get a list of variants belonging to a certain product. The NHibernate mapping is as below <list name="Variants" lazy="false" cascade="save-update" inverse="false" table="PluginProduct_ProductVariant"> <key column="ProductId" /> <index column="Ordinal" /> <one-to-many class="Plugin.Product.Business.Entities.Variant, Plugin.Product" /> </list> I already tried chancing the laziness and inverse properties as suggested in other topics on this site, but they didn't do the trick. I'm using NHibernate in combination with ASP.NET MVC and and I'm trying to loop through a collection of variant in my view. The view is calling the following method public ActionResult ShowProduct() { var id = new Guid(PluginData.PageParameters["Id"]); var variant = _variantService.GetVariantById(id); var product = variant.Product; return PluginView("ShowProduct.ascx", product); } The above code runs without any problems. But when I debug just before returning the view I see that the list of variants which the product contains is empty. When I open more detailed debug information it's showing me the collection error. In the view of my web application I'm trying to do the following <% foreach (var variant in Model.Variants) {%> kleur: <%= variant.Color %> van: <%= variant.FromPrice %> voor: <%= variant.Price %> <%} %> Okay, very stupid, but I finally got the problem solved. The index column Ordinal in the database wasn't getting the correct values so it was always NULL. This caused the error because NHibernate couldn't find an index column to create the list on. Cost me a lot of time unfortunately, but glad I got it solved! Got the problem solved! I ran into an other problem adding a product with a variant so i changed this intelligence in my controller. Then i ran into a problem with the mapping so i changes the mapping as below and it all worked! <list name="Variants" lazy="false" cascade="all" inverse="false"> <key column="ProductId" /> <index column="Ordinal" /> <one-to-many class="Plugin.Product.Business.Entities.Variant, Plugin.Product" /> </list> inverse="true" is the most commonly used, because it means that the other endpoint is the one that has the key in one to many associations (the many side has a foreign key to the one side). I got this problem and it wasn't a mapping problem but actually a data problem. We received way too much data in our collections, but we got this exception anyway instead of something more useful. I expected my collection to contain 10-15 records but it had some 4 million records. it could also be a case of a cross product (see https://www.tutorialspoint.com/sql/sql-cartesian-joins.htm) which you may or may not have wanted. The many to one property isn´t mapped corretly in the other map class, so it will not bring results to relate it to. Basically I deleted the line: map.PropertyRef("Codigo"); And it has worked normally. ManyToOne(x => x.Menu, map => { map.Column("COD_MENU"); //map.PropertyRef("Codigo"); map.NotNullable(true); map.Cascade(Cascade.None); });
common-pile/stackexchange_filtered
SpriteKit and C file ( not objective_C file ) How do you call Spritekit functions/variables inside a C file ( .h .c ) ? not objective_C file ( .h .m ) Thank you for your help Import your C header file in the bridging file, and call your C code in .swift file as you are doing with Obj-C code. @Whirlwind I think he is looking to go the other way, using spritekit inside C @Knight0fDragon Oh, you are right. I wonder what is the purpose of doing something like that... Perhaps OP does not know that Objective C is a strict superset of C (Basically C with object oriented programming) To OP: I am not sure if you can import objective C libraries into C, I tried looking for an answer for you, and all I found was this https://stackoverflow.com/questions/8127124/xcode-importing-objective-c-files-into-a-c-file which basically says no I added tags, and upvoted your question (unlike the other two slackers here).
common-pile/stackexchange_filtered
Labour-saving vs. Labour-augmenting technical change I've read a number of posts on the above topic but none refers to published empirical papers. Google searches have been hopeless. Does anyone know of any paper on empirical derivation of technical change indices? A lot of papers use these terms interchangibly, there is a clear difference between them (labour-saving technical change stems from bias in technical chnage). Using some historical data, I am trying to establish if technical change has been labour-saving or labour-augmenting. However, I've yet to read an empirical paper on the topic. On an outset, they seem like the same thing. Seems like it would be impossible to identify a difference. @EconJohn Yes, but they appear to have different defining properties and I want to identify the difference empirically. Responses to this earlier post shed some light on the difference: https://economics.stackexchange.com/questions/18079/labour-saving-vs-labour-augmenting-what-is-the-difference I think a more fundamental question what data is necessary to estimate elasticity of substitution. do you have such data? Yes, I do have aggregate data on factors of produciton and output. what can be done using these to identify the difference? I think you would need data on human capital to properly Identify labor saving and labor augmenting. This is because we have to separate the specific impacts of labor and capital on the production process. I think, I have data on human capital, how would I proceed from there onwards? Are you aware of any empirical strategy to identify the differences using these variables? Thanks. What do you think? Productivity is a residual (poor prospects for useful literature). 2) The answer is both labour-saving and also labour augmenting. If the same amount can be produced with less hours of labour, additional labour may be available for other activities, including new ones. (creative destruction). 3) Human capital data is generally in the form of years of education, or thresholds of education (e.g., high school completion, college completion, MA completion) or years of industry experience, and does not include things like specific training taken to be able to effectively use new technologies. This is how I'd approach the problem. Please point out any issues on this method as it is based on my own approach (I have no textbook to reference this to). Based on the information you have, you would run a regression of log output on log-labor, log-capital and log-human capital. This would give you a model like this. $$\ln(Y)=\beta_0+\beta_1\ln(L)+\beta_2\ln(K)+\beta_3\ln(H)+\mu$$ in terms of a more "economic looking" equation, we take the expectation of this equation and take $e$ and raise it to the power of both sides giving us our production function. $$\mathbb{E}[\ln(Y)]=\mathbb{E[}\beta_0+\beta_1\ln(L)+\beta_2\ln(K)+\beta_3\ln(H)+\mu]$$ $$\ln(Y)=\beta_0+\beta_1\ln(L)+\beta_2\ln(K)+\beta_3\ln(H)$$ Recall that we view $\beta_0$s the co-efficient on omitted variable $\ln(A)$ as the rate of technological change1,2 $$\exp\{\ln(Y)\}=\exp\{\beta_0+\beta_1\ln(L)+\beta_2\ln(K)+\beta_3\ln(H)\}$$ $$Y=A^{\beta_0}L^{\beta_1}K^{\beta_2}H^{\beta_3}$$ Using this form you can more comfortably calculate elasticity of subsitution between $L$ and $K$. If your elasticity of substitution is greater than or equal to 1 you have a labor saving process, however if elasticity of substitution is less than 1, we either have a process which is either a Human capital augmented process of TFP augmented process 3. Hope this helps 1. https://en.wikipedia.org/wiki/Solow_residual#Regression_analysis_and_the_Solow_residual 2. the actual "quantity" of $A$ can be calculated by $$A=\left(\frac{Y}{L^{\beta_1}K^{\beta_2}H^{\beta_3}}\right)^{\frac{1}{\beta_0}}$$ 3. this is of course assuming that either $\beta_3>0$ and/or $\beta_0>0$. Thanks @EconJohn, not sure if a Cobb-Douglass type function can be used to differentiate between forms of technical change. This is because technical change is assumed to be Hicks neutral in C-B type functions. CES functions may be approriate for this empirical exercise, but I may hve to deal with non-linearities in the parameters. @london, can you send me the source for your view on hicks neutrality of the cobb-douglas function? @EconJon, note that your model is based on the Hicks neutrality assumption of $A$. Also, isn't the substitution elasticity between $K$ and $L$ is $1$ in Cobb-Douglass? @london Ah I see. I don't think that case universally though I am open to being wrong. Elasticity of substitution is 1 in cobb-douglas. You need to estimate a CES or translog. @user928172 I know, but using a "generalized" cobb douglas can get you similar results.
common-pile/stackexchange_filtered
Finding family of functions for which $\Delta h = 0$ I have a function $h(x, y) = g(r)$, with $x = r \cos \theta$ and $y = r \sin \theta$. I was able to find a formula for $\Delta h$: $$\Delta h = \frac{\partial^2 g}{\partial r^2} + \frac{1}{r} \frac{\partial g}{\partial r} + \frac{1}{r^2} \frac{\partial^2 g}{\partial \theta^2}$$ I need to prove that the family of functions for which $\Delta h = 0$ is only $h = c \log (r) + d$ where $c, d$ are constants. We just started doing Calc 3 in this class so I don't really know what tools I can use from here. Assume $g(r,\theta) = R(r) \Theta (\theta)$ and apply it in $\Delta h = 0$. Ummm, what you want to prove is not quite true. It is true for the special case of $\partial_\theta g=0$. But if $g$ is allowed to vary in $\theta$, nope. So I would first assume $\partial_\theta g=0$. Then demonstrate that your solution actually solves the "radial" part of the equation. Then, since that part is a second order linear equation, it can have only two independent solutions. You have two independent solutions ($c\log(r)$ and $d$), so they have to be the ones. My bad, I mistyped. Above in the packet it says that $h(x,y) = g(r, \theta)$, but for this exercise it only wants $h(x,y) = g(r)$. Thanks for your answer - I'm reading through it now. Okay, so I've read through it and it makes sense. Funny that it uses tools from ODE since this course is taken before ODE. Anyhow, +1.
common-pile/stackexchange_filtered
How can I solve "Unreachable code" error in my kotlin project? SplashActivity.kt @AndroidEntryPoint @SuppressLint("CustomSplashScreen") class SplashActivity : ComponentActivity() { private val viewModel: SplashScreenViewModel by viewModels() private val tokenManager = TokenManager(this) val activity = this private val errMsg = "Bir hata ile karşılaşıldı." private fun navigateToMain(isTokenExist: Boolean) { val intent = Intent(this@SplashActivity, MainActivity::class.java) intent.putExtra("isTokenExist", isTokenExist) startActivity(intent) finish() } override fun onCreate(savedInstanceState: Bundle?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { val splashScreen = installSplashScreen() splashScreen.setKeepOnScreenCondition { true } } super.onCreate(savedInstanceState) if (viewModel.state.value.error) { Toast.makeText(this@SplashActivity, errMsg, Toast.LENGTH_LONG).show() } lifecycleScope.launch(Dispatchers.IO) { tokenManager.getRefreshToken().collect { refreshToken -> if (refreshToken != null) { if (viewModel.state.value.error) { delay(2000) activity.navigateToMain(false) } viewModel.state.collect { activity.navigateToMain(!it.error) } activity.viewModel.refreshAccessToken(refreshToken) //unreachable code warning } else { delay(2000) activity.navigateToMain(false) } } } } } SplashScreenViewModel.kt @HiltViewModel class SplashScreenViewModel @Inject constructor( private val tokenManager: TokenManager ) : ViewModel() { private val _state = MutableStateFlow(SplashScreenState()) val state: StateFlow<SplashScreenState> = _state.asStateFlow() fun refreshAccessToken(refreshToken: String) { viewModelScope.launch { try { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY val okHttpClient = OkHttpClient .Builder() .addInterceptor(loggingInterceptor) //.authenticator(AuthAuthenticator(tokenManager)) .build() val retrofit = Retrofit.Builder() .baseUrl(Constants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() val service = retrofit.create(RegisterService::class.java) val response = service.refreshToken(model = RefreshToken(refreshToken)) if (response.isSuccessful && response.body() != null) { val newAccessToken = response.body()?.access_token val newRefreshToken = response.body()?.refresh_token if (newAccessToken != null && newRefreshToken != null) { tokenManager.saveAccessToken(newAccessToken) tokenManager.saveRefreshToken(newRefreshToken) } } _state.update { it.copy( completed = true ) } } catch (e: Exception) { _state.update { it.copy( error = true, completed = true ) } } } } } data class SplashScreenState( val error: Boolean = false, var completed:Boolean = false ) TokenManager.kt class TokenManager(private val context: Context) { companion object { private val ACCESS_TOKEN = stringPreferencesKey("access_token") private val REFRESH_TOKEN = stringPreferencesKey("refresh_token") private val EXPIRATION_TIME = longPreferencesKey("expiration_time") } fun getAccessToken(): Flow<String?> { return context.dataStore.data.map { preferences -> preferences[ACCESS_TOKEN] } } suspend fun saveAccessToken(token: String) { context.dataStore.edit { preferences -> preferences[ACCESS_TOKEN] = token val expirationTime = System.currentTimeMillis() preferences[EXPIRATION_TIME] = expirationTime + 86400 * 1000 } } fun getAccessTokenExpirationTime(): Flow<Long?> { return context.dataStore.data.map { preferences -> preferences[EXPIRATION_TIME] } } suspend fun deleteAccessToken() { context.dataStore.edit { preferences -> preferences.remove(ACCESS_TOKEN) } } fun getRefreshToken(): Flow<String?> { return context.dataStore.data.map { preferences -> preferences[REFRESH_TOKEN] } } suspend fun saveRefreshToken(token: String) { context.dataStore.edit { preferences -> preferences[REFRESH_TOKEN] = token val expirationTime = System.currentTimeMillis() preferences[EXPIRATION_TIME] = expirationTime + 86400 * 1000 } } suspend fun deleteRefreshToken() { context.dataStore.edit { preferences -> preferences.remove(REFRESH_TOKEN) } } I'm getting an Unreachable code warning. I shared my splash activity and viewodel codes above. I think that the codes I made are correct, but there is a part that I do not like, why android studio gives this warning. viewModel.state.collect { activity.navigateToMain(!it.error) } activity.viewModel.refreshAccessToken(refreshToken) // --> Unreachable code warning In this line of code will activity.navigateToMain(!it.error) not work when there is a change in state anyway? so there is no change in the first time, then it will not work and the following code will work so activity.viewModel.refreshAccessToken(refreshToken) right ? If this is the case, the logic is correct, but if navigateToMain works, then it is normal to give an Unreachable code warning at the first time because after navigating, it goes to the mainActivity and this terminates the splashActivity, then the activity.viewModel.refreshAccessToken(refreshToken) line does not work. Is it right what I did? or is there an error? I'm not sure so I wanted to ask can you help? A StateFlow never completes, so when you call collect on state, none of the code below the collect call will ever be reached, because collect will never return. Edit: The way you have your StateFlow set up, it will have a complete == true value when you are ready to navigate. So the quick and easy fix for your code is to replace viewModel.state.collect { activity.navigateToMain(!it.error) } with val refreshResult = viewModel.state.first { it.completed } activity.navigateToMain(!refreshResult.error) The first function suspends until a value is emitted that means the criteria in the lambda, and then it returns that value. Also, have this if (viewModel.state.value.error) { block where you navigate away from the screen, but then allow the rest of your logic to continue. You either need to call return @launch inside this if block or wrap the code below it in an else block. You also need to remove (Dispatchers.IO) after your launch call. There is no blocking code in your coroutine that would require it, and you need to be on Main to navigate between activities. Optional: This is how I would design the ViewModel class to avoid the possibility of redundantly restarting the fetch if the Fragment is recreated and calls refreshAccessToken() again. class SplashScreenViewModel @Inject constructor( private val tokenManager: TokenManager ) : ViewModel() { private val _state = MutableStateFlow(SplashScreenState()) val state: StateFlow<SplashScreenState> = _state.asStateFlow() private val refreshJob: Job? = null fun refreshAccessToken(refreshToken: String) { if (refreshJob != null) { return } refreshJob = viewModelScope.launch { // your original code // After all code from your original coroutine, if you want to // support ability to call this function again to do another refresh: refreshJob = null } } //... } can you share example code ? I would have to see your TokenManager class. But it's not trivial to redesign the whole thing, especially without knowing everything your app needs to do and how it should behave. I shared my token manager you can see Actually, as I look at it closer, I think using a Flow to hold the results of the token refresh is OK. You do need to preserve the ongoing work in case the fragment is recreated while waiting for results, so a hot flow is needed (you could use Deferred, but we probably want to have the ability to refresh again). I updated with some recommendations.
common-pile/stackexchange_filtered
Getting json on Ajax response callback I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part. One thing I have read in the help is that if you return json data, the callback function will fill that json data in the second parameter. So in my php file that gets called I have: header('Content-type: application/json'); if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true) echo json_encode(array('lastid' => $acs_ajch_sql->msgid)); else echo json_encode(array('error' => $response)); On the ajax request I have: onSuccess: function (response,json) { alert(response.responseText); alert(json); } The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null. Anyone know how I can make this work? This is the correct syntax for retrieving JSON with Prototype onSuccess: function(response){ var json = response.responseText.evalJSON(); } Thanks! But I did read somewhere about that second parameter thing :P Thanks Jose. Yeah, http://www.prototypejs.org/learn/introduction-to-ajax it says that second param is json, crap, wont work for me - onSuccess: function(transport, json){ alert(json ? Object.inspect(json) : "no JSON object"); } There is a property of Response: Response.responseJSON which is filled with a JSON objects only if the backend returns Content-Type: application/json, i.e. if you do something like this in your backend code: $this->output->set_content_type('application/json'); $this->output->set_output(json_encode($answer)); //this is within a Codeigniter controller in this case Response.responseJSON != undefined which you can check on the receiving end, in your onSuccess(t) handler: onSuccess:function(t) { if (t.responseJSON != undefined) { // backend sent some JSON content (maybe with error messages?) } else { // backend sent some text/html, let's say content for my target DIV } } I am not really answering the question about the second parameter of the handler, but if it does exist, for sure Prototype will only provide it in case of proper content type of the response. This comes from Prototype official : Evaluating a JavaScript response Sometimes the application is designed to send JavaScript code as a response. If the content type of the response matches the MIME type of JavaScript then this is true and Prototype will automatically eval() returned code. You don't need to handle the response explicitly if you don't need to. Alternatively, if the response holds a X-JSON header, its content will be parsed, saved as an object and sent to the callbacks as the second argument: new Ajax.Request('/some_url', { method:'get', onSuccess: function(transport, json){ alert(json ? Object.inspect(json) : "no JSON object"); } }); Use this functionality when you want to fetch non-trivial data with Ajax but want to avoid the overhead of parsing XML responses. JSON is much faster (and lighter) than XML. You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget: //fetches comments from the server CommentWidget.prototype.getComments = function() { var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id; this.asyncRequest('GET', commentURL, null); } //initiates an XHR request CommentWidget.prototype.asyncRequest = function(method, uri, form) { var o = createXhrObject() if(!o) { return null; } o.open(method, uri, true); o.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); var self = this; o.onreadystatechange = function () {self.callback(o)}; if (form) { o.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); o.send(makePostData(form)); } else { o.send(''); } } //after a comment is posted, this rewrites the comments on the page CommentWidget.prototype.callback = function(o) { if (o.readyState != 4) { return } //turns the JSON string into a JavaScript object. var response_obj = eval('(' + o.responseText + ')'); this.comments = response_obj.comments; this.refresh() } I open-sourced this code here http://www.trailbehind.com/comment_widget Cool. Thanks for this. I just used prototype because I do some more stuff with it, like using delay, update and some other small things.
common-pile/stackexchange_filtered
Error when trying to install RVM on my VPS I'm working on deploying my first rails app to my mediatemple(dv) and i'm first trying to install RVM using this command: bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer) and I get the following error: curl: (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed More details here: http://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). The default bundle is named curl-ca-bundle.crt; you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. Could not download 'https://github.com/wayneeseguin/rvm/tarball/stable'. Make sure your certificates are up to date as described above. To continue in insecure mode run 'echo insecure >> ~/.curlrc'. It looks like I should be able to specify -k/--insecure to skip the certificate check, but how can I do that? I'm kind of a linux rookie. You can put "-k" after the "curl" and before the "-s". Did you read the error message properly ? The last line in that message has the solution. echo insecure >> ~/.curlrc Run the above in your shell and rerun the RVM installer.
common-pile/stackexchange_filtered
where to find good review resources? I am taking my certification test for secondary mathematics next month and I am extremely overwhelmed by the amount of stuff i need to brush up on. http://www.mttc.nesinc.com/PDFs/MI_field022_SG.pdf that is the review guide containing information on everything we will be tested on. Does anyone have suggestions for places I can go to easily look up everything from unit conversions to differentials.. Any resource with good information is helpful. Also and recommendations for things i need to remember to brush up on. It's been over a year since I took calc 3 and a lot longer since I took anything else. currently im trying to brush up on the properties of fields rings groups and vector spaces
common-pile/stackexchange_filtered
Extract First Name Middle Name and Last Name Using VBA I Have come close to finding the solution but not completely. I want to separate the first, middle (if it exists) and last names in separate name field. The data & current results: Data FName LName Doe,John John Doe Doe,John A John A Doe Doe,John Art, Jr John Art, Jr Doe The Code: First_Name: Mid([Client Name],InStr([Client Name],",")+1) Last_Name: Left([Client Name],InStr([Client Name],",")-1) As you can see, I am not focused on the middle name right now, but would like to capture that as well in a MName for the middle name/initial. I have found many options on the web getting close to this but none which accomplishes the task of having the data look like: Data FName MName LName Doe,John John Doe Doe,John A John A Doe Doe,John Art, Jr John Art Doe Jr Doe,John A, Jr John A Doe JR Thanks edited: added mName initalization try this Option Explicit Sub names() Dim namesRng As Range, cell As Range Dim arr As Variant Dim fName As String, mName As String, lName As String Set namesRng = ActiveSheet.Range("A2:A10") '<== here set the actual range of "Data", header excluded For Each cell In namesRng.SpecialCells(xlCellTypeConstants, xlTextValues) arr = Split(cell.value, ",") lName = Trim(arr(0)) If UBound(arr) = 2 Then lName = lName & " " & Trim(arr(2)) arr = Split(Trim(arr(1))) fName = Trim(arr(0)) mName="" If UBound(arr) = 1 Then mName = Trim(arr(1)) cell.Offset(, 1).Resize(, 3) = Array(fName, mName, lName) Next cell End Sub This worked very well for me - thank you! I added a "currentRow = cell.Row" variable so that I could plug the parsed names into a separate column as Range("AA" & currentRow).Value = fname, etc. Replace commas with spaces and replace resulting double spaces with single spaces. Then start splitting the string out based on spaces. Assumptions: There will ALWAYS be at least a first and last name, an IF like the ones in my code will get around this if there is potential for just a first name. There will only ever be ONE suffix to a surname (ie jr) Sub FixNames() Dim MyString As String, FirstName As String, MiddlePart As String, Surname As String, X As Long For X = 2 To Range("A" & Rows.Count).End(xlUp).Row FirstName = "": MiddlePart = "": Surname = "" MyString = Replace(Replace(Range("A" & X).text, ",", " "), " ", " ") FirstName = Split(Replace(MyString, ",", " "), " ")(1) Surname = Split(Replace(MyString, ",", " "), " ")(0) If Len(MyString) - Len(Replace(MyString, " ", "")) >= 2 Then MiddlePart = Split(Replace(MyString, ",", " "), " ")(2) If Len(MyString) - Len(Replace(MyString, " ", "")) > 2 Then Surname = Surname & " " & Split(Replace(MyString, ",", " "), " ")(3) Range("B" & X).Formula = FirstName Range("C" & X).Formula = MiddlePart Range("D" & X).Formula = Surname Next End Sub Option Explicit Sub names() Dim name As String Dim first_name As String Dim mid_name As String Dim last_name As String name = "AA,BB,CC" first_name = Left(name, InStr(name, ",") - 1) mid_name = Mid(name, InStr(name, ",") + 1, InStrRev(name, ",") - InStr(name, ",") - 1) last_name = Right(name, Len(name) - InStrRev(name, ",")) MsgBox first_name & Chr(10) & mid_name & Chr(10) & last_name End Sub
common-pile/stackexchange_filtered
Importing large number of images into Python to convert to Numpy array I am attempting to import a large number of images and convert them into an array to do similarity comparisons between images based on colors at each pixel and shapes contained within the pictures. I'm having trouble importing the data, the following code works for small numbers of images (10-20) but fails for larger ones (my total goal is to import 10,000 for this project). from PIL import Image import os,os.path imgs=[] path="Documents/data/img" os.listdir(path) valid_images =[".png"] for f in os.listdir(path): ext= os.path.splitext(f)[1] if ext.lower() not in valid_images: continue imgs.append(Image.open(os.path.join(path,f))) When I execute this I receive the following message OSError: [Errno 24] Too many open files: 'Documents/data/img\81395.png' Is there a way to edit how many files can be open simultaneously? Or possibly a more efficient way to convert these tables to arrays as I go and "close" the image? I'm very new to this sort of analysis so any tips or pointers are appreciated. Don't store PIL.Image objects and just convert them into numpy arrays instead. For that you need to change the line where you append image to a list to this: ''' imgs.append(np.asarray(Image.open(os.path.join(path,f)))) ''' Thanks, that is super helpful! I'm a little confused at what the output structure is. It looks like a list of tuples, am I to interpret these as the RGB values for a particular pixel? If so how do I relate it back to which pixel the value is associated with? These are RGB values for each layer of an image. Grayscale would have a single layer so e.g. an array of shape 100x100 would represent a grayscale image of 100x100 pixels and RGB image would be an array of shape 100x100x3. And so this is what you're seing there in that list. I suggest looking up some tutorials on image manipulation in python using arrays. Something like this for example: https://scipy-lectures.org/advanced/image_processing/
common-pile/stackexchange_filtered
It will displays blank in Session.getEffectiveUser().getEmail(); I am having an issue with App Script. So, I am currently finding a way in Google Sheet that if a user opens the Sheet, there will a pop-up UI that will display the Email they currently logged in. I tried this: function onOpen() { var userEmail = Session.getEffectiveUser().getEmail(); var ui = SpreadsheetApp.getUi(); ui.alert('User Email', 'The current user\'s email is: ' + userEmail, ui.ButtonSet.OK); } But this will work only to the owner of the Google Sheet and the App Script. I shared a link to another email and when the UI won't display the email or return NULL. And when I give permissions of the App Script to that email, it's still won't work. The only time that this code will work on another email is that I will manually run the code. Is there something I missed? Tried ChatGBT btw but still nothing. Google Workspace Domain Users: Scripts have broader access to user data, including email addresses, within the same Google Workspace domain. For standard Gmail accounts, Google's privacy policies are stricter, often leading the Session.getActiveUser().getEmail() method to return an empty string.
common-pile/stackexchange_filtered
Time zone missing from time series I am in the process of merging two data frames based on date-time, and seem to have run into a snag. The time column in 1 of 2 of the DF's has a timezone stamp: #Example "2012-09-28 08:15:00 MDT" And the other DF time column does not #Example 2 "2012-09-28 08:15:00" In my program both of these are POSIXct objects, formatted exactly the same ,besides the timezone stamp. When trying to merge based on the Time columns, NA's appear, b/c they are not recognizing each other. I have narrowed the problem down to the DF missing the Tz. Something strange is going on. When I have the Data for the datetime Column outside the data frame it reads as such #Code used to make these values NewTime<-as.POSIXct(TimeDis$datetime, format="%Y-%m-%d %H:%M") >NewTime [1] "2017-08-16 00:00:00 MDT" "2017-08-16 00:15:00 MDT" [3] "2017-08-16 00:30:00 MDT" "2017-08-16 00:45:00 MDT" Now when I put this into a data frame with data, the "MDT" does not show up Discharge_Time<-data.frame(NewTime,DischargeFin) > Discharge_Time NewTime DischargeFin 1 2017-08-16 00:00:00 990525.2 2 2017-08-16 00:15:00 990525.2 3 2017-08-16 00:30:00 1000719.2 4 2017-08-16 00:45:00 1000719.2 Even stranger if I call, >Discharge_Time[1,1] "2017-08-16 MDT" I get the MDT back but now no time.... I have no idea what is going on, but am hoping to find a way for the MDT and all the rest to stick around in that data frame so I can successfully merge it with the other DF, which isn't missing anything Research Done: How to change a time zone in a data frame? Changing time zones with POSIXct time series, R Looking at attributes(x) for Time1 and Time2, I see that neither has a tz; and that your code runs fine with no NAs visible in DATA.... Ah, totally missed that when I added the POSIXct line, it added a MDT to both data.frames. I will delete that as it is not accurate Ok. Feel free to reorganize your question in the way that makes the most sense for the question to be understood; it's not necessary to add trailing EDITs and such. Folks can see the edit history and you can apologize to earlier answerers for changing it on them in comments if appropriate. Roger that, thanks @Frank I have done more digging and narrowed down the problem and hopefully made my question more clear. I apologize for any confusion. So after many attempts to recreate this error I found it to a culprit of the na.locf function of the package zoo. After padding my data on the interval '15 min' with the pad function from padr, I wanted to replace those N/A values with the previous value in the column. This works well except for the fact it gets rid of the TZ in the date-time. And this is where the problem came from. An example is shown below library(padr) library(zoo) #Dates Missing 8:30 for padding Dates<-c("2017-08-18 08:00","2017-08-18 08:15","2017-08-18 08:45", "2017-08-18 09:00") #Example Data Data<-c(1,2,3,4) #Df Df<-data.frame(Dates, Data) #Change to POSIXct Df$Dates<-as.POSIXct(Df$Dates, format="%Y-%m-%d %H:%M") #We can see now the Dates have been assigned a Timezone >Dates [1] "2017-08-18 08:00:00 MDT" "2017-08-18 08:15:00 MDT" [3] "2017-08-18 08:45:00 MDT" "2017-08-18 09:00:00 MDT" #Now we Pad Df<-pad(Df, interval='15 min') #TZ is still intact (So it's not padr) >Df[1,1] [1] "2017-08-18 08:00:00 MDT" #Here is where the problem lies, in the na.locf function from zoo library(zoo) FixDf<-na.locf(Df, option="locf") #replaces N/A with previous value FixDf[1,1] [1] "2017-08-18 08:00:00" #NO TIMEZONE! It is not supposed to that. Could you make a reproducible example and share it as an issue here? You might have found a bug in pad. @Edwin I have truly found the issue, it lies in the na.locf function from the package zoo, I have placed the example in my answer Try library(lubridate) Df1<-data.frame(Time1 = as_datetime(Time1),Data1) Df2<-data.frame(Time1 = as_datetime(Time2),Data2) DATA<-merge(x = Df1, y = Df2, by = "Time1", all.x = TRUE) DATA Time1 Data1 Data2 1 2012-09-28 06:15:00 1 5 2 2012-09-28 06:30:00 2 6 3 2012-09-28 06:45:00 3 7 In your version, your time get's converted to factors, which are not equal across dataframes. For instance, str(Df1$Time1) Factor w/ 3 levels "2012-09-28 08:15:00 MDT",..: 1 2 3 str(Df2$Time1) Factor w/ 3 levels "2012-09-28 08:15:00",..: 1 2 3 shows you that your factor levels are different, which is why the merge does not work. Thanks for the response. Yes I realize that they are factors in the example, but in the actual program the date-time is a POSIXct object, so they are formatted mainly the same way as your example, just including %H:%M as well. I would like to convert them just using as.Date(), but the objects must be padded first to check for missing data. So my only option is to keep them in POSIXct, although that should work well if I can get rid of the timestamp This answer is correct given the code in the example - if the actual program is different, we'd need to see it (or a relevant excerpt) I have narrowed the question down, and made it more clear what the problem is, sorry about that.
common-pile/stackexchange_filtered
view render - backbone.js How do I make this result in backbone.js result wanted <p><h3>fgfdgdfg</h3></p> var TodoView = Backbone.View.extend({ el:'p', render: function () { $('body').append(this.$el.html("<h3>fgfdgdfg</h3>")); } }); var todoView = new TodoView(); todoView.render(); Use tagName instead of el. Edited to fix bad html, thanks @muistooshort. Just removed the <p> altogether. var TodoView = Backbone.View.extend({ tagName:'h3', render: function () { $('body').append(this.$el.html("fgfdgdfg")); } }); var todoView = new TodoView(); todoView.render(); You set el if there is an existing DOM element you want the view to use. Setting tagName tells Backbone to generate an 'h3' element for the view's root. You could do this, also (I prefer this way; avoid setting 'el'): var TodoView = Backbone.View.extend({ tagName:'h3', render: function () { this.$el.html("fgfdgdfg"); return this; } }); // view is more reusable now, since it doesn't have the 'body' part in render. // So, another instance could be rendered and added to the page somewhere else. var todoView = new TodoView(); $('body').append(todoView.render().el); var todoView2 = new TodoView(); $('body').append(todoView2.render().el); If your html already had the 'h3' element you wanted to use for the view, you could do this: // assuming this html on the page already: // <body><h3></h3></body> var TodoView = Backbone.View.extend({ // setting 'el' tells backbone to use the existing <h3>. // You probably would want to use an id rather than 'h3' though. el:'h3', render: function () { this.$el.html("fgfdgdfg"); return this; } }); var todoView = new TodoView(); todoView.render(); Sort of. El is DOM element, which is basically acting like a wrapper for your rendered content. By default, its a DIV, but you can change its type using tagName as Paul has pointed out. Whether or not this works depends on the browser, <p><h3>X</h3></p> is not valid HTML so some browsers will correct it to <p></p><h3>X</h3><p></p> (or similar) behind your back. You probably can't because <p><h3>fgfdgdfg</h3></p> is not valid HTML and the browser will often attempt to correct invalid HTML. From the fine <p> specification: Permitted contents Phrasing content And phrasing content is: phrasing content Consists of phrasing elements intermixed with normal character data. Normal character data is, more or less, just plain text without markup so <h3> won't be in there. Phrasing elements are simple things like <a>, <b>, <img>, ... and there is no <h3> in there either. You'll have to fix your HTML if you want consistent results. Then, once you have valid HTML in mind, Paul's advice should get things finished.
common-pile/stackexchange_filtered
Add/remove row in a table I have the following jquery code to add and remove a row in a table. I have multiple tables on one page. Each row in each table has these two classes: .row-add and .row-delete Now when I click on '.row-add'to add a new row, all the tables are affected, meaning that row is added to all of the tables on the same page. What should I do to make it only apply to its own table when clicked? Jquery: $(document).ready(function () { $('.row-delete').click(function () { $(this).closest("tr").remove(); }); $('.row-add').click(function () { $(this).closest("tr").clone(true).appendTo(".table-comparison"); }); }); Html: <div id="tab-1" class="tab-section"> <div class="container flat rounded-sm bspace"> <table cellspacing="0" class="display table-comparison"> <thead> <tr> <th><span>Effective Date</span></th> <th><span>Price</span></th> </tr> </thead> <tbody> <tr> <td><input class="effective-date" type="text" value="01/01/2013"> - <input class="effective-date" type="text" value="06/05/2015"> <span class="row-add"></span> <span class="row-delete"></span> </td> <td> $<input class="price" value="50"> / <select> <option>Second</option> <option>Minute</option> <option>Hour</option> <option>Day</option> <option>Week</option> <option>Biweek</option> </select> / <select> <option>Day</option> <option>Week</option> <option>Biweek</option> <option>Month</option> <option>Quarter</option> <option>Year</option> </select> <span class="row-add"></span> <span class="row-delete"></span> </td> </tr> <tr class="price-present"> <td><input class="effective-date" type="text" value="07/01/2013"> - <span class="effective-date">Present</span> <span class="row-add"></span> <span class="row-delete"></span> </td> <td> $<input class="price" value="40"> / <select> <option>Second</option> <option>Minute</option> <option>Hour</option> <option>Day</option> <option>Week</option> <option>Biweek</option> </select> / <select> <option>Day</option> <option>Week</option> <option>Biweek</option> <option>Month</option> <option>Quarter</option> <option>Year</option> </select> <span class="row-add"></span> <span class="row-delete"></span> </td> </tr> <tr> <td><input class="effective-date" type="text" value="01/01/2011"> - <input class="effective-date" type="text" value="06/30/2012"> <span class="row-add"></span> <span class="row-delete"></span> </td> <td> $<input class="price" value="30"> / <select> <option>Second</option> <option>Minute</option> <option>Hour</option> <option>Day</option> <option>Week</option> <option>Biweek</option> </select> / <select> <option>Day</option> <option>Week</option> <option>Biweek</option> <option>Month</option> <option>Quarter</option> <option>Year</option> </select> <span class="row-add"></span> <span class="row-delete"></span> </td> </tr> </tbody> </table> </div> </div> try to be specific ... closest("tr") you are selecting all trs. try giving an ID, or class and select that id using jquery. The problem is that your jQuery selector is on class attribute, if you want to refer to a single table, you have to go by id. In this case I think the best approach is, if you generate programmatically the html code, to add to every table an auto generated id and to add to every clickable row the following code: onclick="addrow(table_id)" where table_id is the autogenerated id of the table. Then: function addrow(table) {$(table).closest("tr").clone(true).appendTo(".table-comparison");} Just be warned that also .table-comparison should be avoided switching to id, but I don't know the details of your code! Hope this helps! EDIT: still better, if you don't generate code, is the bind function, like $("p").bind("click", function(event){ This way you can access ex-post who has sent the event. In your case you I think you could write: $(".row-delete").bind("click", function (event) { event.target.closest("tr").remove(); }); $(".row-add").bind("click", function (event) { event.target.closest("tr").clone(true).appendTo(".table-comparison"); }); Source: JQuery Doc I copied the html here as well. Can you re-write the jquery part? If you use the bind function it's not necessary: the parameter to the anonymous function passed to bind is the launching event, so you can access it with e.target. What you obtain is THE row that launched the event. From there you can take the table and so on. Added code but I still have to resolve the table-comparison part.
common-pile/stackexchange_filtered
Google play android market publish and save buttons have no effect The 'android developer console' publish and save buttons don't do anything In the android developer console at play.google.com/apps/publish, I login and click the "APK Files" tab and upload my updated APK. I have done this successfully 15 times before. I press the save button, literally nothing happens. No error, no message, no page refresh, nada. When I press the "Un-publish" button, nothing happens. I've triple checked my program, it is working perfectly. I've tried other browsers, restarted eclipse, the smartphone, computer, it's all fine. Something is wrong with Android market console. The android APK save button doesn't work. OK I figured out my problem.. I'm 100% certain it's a bug in the android developer console / Android market console. Basically what happened is the exchange rate in Zimbabwe, Quatar and Togo and a few other places changed their exchange rates due to inflation or whatever, and when I uploaded my new APK, google needed me to review and change the prices for these countries. So to fix here is what I have to do: Go to play.google.com/apps/publish Login, click your program in the android app listings, click "Upload APK tab". Upload your APK. Click the save and publish buttons, which are completely ineffective. Click the greyed out tab: "Product Details". Scroll 3/4 the way down to the exchange rate section, there is a red box around some countries. Enter in a price for those countries, fix any other red items. Click on the checkmarks at the bottom to re-validate the stuff you've validated before. Go back to the upload APK tab. Click Save. The save produces the expected result "save completed". Recommendation for the Google: Pushing the save button should produce a popup: "You need to review some currency exchange problems in the program details". My saviour :). I would also note that even on the 'Product Details' tab there should be an error message at the top of the screen. Poor stuff, Google! I want that hour of my life back! If you uploaded a new app version and can't save it, I think there is an error on the "Product details" tab. Since Google Play added some new countries a few days ago, if your app is a paid one, you first have to set prices for these new countries before you can save your app. I think it's not a real bug. There is just an error message missing on the APK tab. There is a real bug, but I'm not sure what it is. I had the same problem. Closing the browser tab and reopening it fixed the problem for me, showing that there was no real issue with my app settings.
common-pile/stackexchange_filtered
Filter one list depending on selection in another list let's say I have one list with my company's departments and one list with all employees. My list of employees has a lookup field to select the department. Now I want to have one page with a list of all departments and below a list with all the employees. If I select one department in the list I'd like my employee list to only show employees from this department. How can this be done? Thanks in advance You can simply achieve this by using webpart connections. Let's say you already have a webpart page with the two webparts, one below the other, and there is a lookup column in the employees list to the department list, as you said in your question. You just have to edit your web part page and select from the webpart dropdown menu Connections-> Send Row of Data To -> Employees. A little wizzard will open. There you select "Connection Type: Get Filter Values From" and click "Configure". On the next step select "Provider Field Name: Title" or whatever is the name of the field on which you want to filter on. In this case I suppose it's the Title of the Departments list. Below select "Cosnumer Field Name: Department" or whatever is the name of the lookup field in your Employees list pointing to the Departments list. Then click Finish. Click Save or Stop Editing to save the page. Don't forget to publish it, if you have version control activated. Now a new column appeared on the Departments list. It will allow you to select a department and it will filter automatically all employees below. The only disadvantage is, that OOTB, as far as I know at least, it cannot show all data, it is always applying filtering on the first row from the upper list. I hope it was you were looking for. :) Thank you Norbert. That was exactly what I wanted to do. You could also use the jQuery library (by Marc Anderson) to implement the connected look up fields, see example I agree with Falak, you'd want to use something like Marc Anderson's SPServices library, but I'd recommend using the cascading dropdown function. My mistake.. After re-reading the question, it looks like you just want to display the employees. If you wanted to select them, you would use something like the cascading dropdowns.
common-pile/stackexchange_filtered
Run NUXT without server How can I run a static NUXT project without a server? That's what I did: I created a new project (without any line of code) with VUETIFY I ran the command npn run generate I went to dist/index.html The project opens but no link is clicked I added the line in nuxt.config.js route: { base: '/ProjectName/' }, I ran generate again The links are still not clicked, And if there is a clicked link it points to drive c I think you are asking, how you can host the project through some service like apache? No. My goal is to put NUXT within webview. webview, is a concept in android, right? yes. is like browser. Isn't it correct, that we need to have a URL to display the same in webview? is correct. and I want via URL of file Try to switch to hash mode in your router! (https://v2.nuxt.com/docs/configuration-glossary/configuration-router/#mode) In your nuxt.config.js it should look like this: // Target: https://go.nuxtjs.dev/config-target target: 'static', ssr: false, // Disable Server Side rendering router: { mode: 'hash', // switch from history mode, that requires a server to fake filesystem calls, to totally client based approach where all urls prefixed with #. base: './', // change to './' if you want to test it locally }, Now you should be able to use "npm run generate" and just open the index.html file in your "dist" directory.
common-pile/stackexchange_filtered
how do i make my contact form work? The code below acts strange when I click the button on my website. First it opens a new page where the form is again displayed but without any css or js. Then when I refill all the info and click send, it says its submitted but it wont actually sent the email. I have tried to modify the code I am still new to php. Code below displays and functions the contact form. <?php $action=$_REQUEST['action']; if ($action=="") { ?> <form action="" method="POST" enctype="multipart/form-data"> <input type="hidden" name="action" value="submit"> Your name:<br> <input name="name" type="text" value="" size="30"/><br> Your email:<br> <input name="email" type="text" value="" size="30"/><br> Your message:<br> <textarea name="message" rows="7" cols="30"></textarea><br> <input type="submit" value="Send email"/> </form> <?php } else /* send the submitted data */ { $name=$_REQUEST['name']; $email=$_REQUEST['email']; $message=$_REQUEST['message']; if (($name=="")||($email=="")||($message=="")) { echo "All fields are required, please fill <a href=\"\">the form</a> again."; } else{ $from="From: $name<$email>\r\nReturn-path: $email"; $subject="Personal Plate inquiry from website"; <EMAIL_ADDRESS>$subject, $message, $from); echo "Email sent!"; } } ?> Is this running on an actual webserver somewhere or on a private system in your LAN? @DuaneLortie its on an actual website There are some mistakes on your code: use $_POST instead of $_REQUEST. You can try this way: <?php if(isset($_POST['submit'])){ $name=$_POST['name']; $email=$_POST['email']; $message=$_POST['message']; if (($name =="")||($email=="")||($message=="")) { echo "All fields are required, please fill <a href=\"\">the form</a> again."; } else{ $from="From: $name<$email>\r\nReturn-path: $email"; $subject="Personal Plate inquiry from website"; <EMAIL_ADDRESS>$subject, $message, $from); echo "Email sent!"; } } ?> <form action="" method="POST" enctype="multipart/form-data"> <input type="hidden" name="action" value="submit"> Your name:<br> <input name="name" type="text" value="" size="30"/><br> Your email:<br> <input name="email" type="text" value="" size="30"/><br> Your message:<br> <textarea name="message" rows="7" cols="30"></textarea><br> <input type="submit" name="submit" value="Send email"/> </form> $_REQUEST contains data of $_POST. http://php.net/manual/en/reserved.variables.request.php @AndrejLudinovskov, It is but don't forget, $_REQUEST is a different variable than $_GET and $_POST @RuhulAmin i get a jist of the work behind those, but my code still doesnt work. do you think i have a problem with the server? you have IMAP module installed for php? @M.I. i dont thinks so. its on a hosted webpage
common-pile/stackexchange_filtered
How to unbold a section of a \boldmath or \boldsymbol? I have some locally defined commands such as \newcommand{\cosx}[1]{\color{blue}\boldsymbol \cos^{#1} x} and I would like to be able to unbold some part of it. Is there a more elegant way to achieve this than by repeating the commands as in: \newcommand{\cosx}[1]{{\color{blue}\boldsymbol \cos}^{#1} {\color{blue}\boldsymbol x}} e.g. some way of wrapping the section to be formatted normally? I saw this question, but I believe that issue is actually more complicated as it feeds a bolded symbol into a new command; moreover, the solutions presented are beyond my ability to generalize to other situations (i.e. my question could be generalized to 'how to exempt a section in math mode from formatting (bold, colour, font etc)?'). thanks, but this wouldn't work for the colours or fonts, & does not appear to work for the bold, either... \boldsymbol takes an argument so in your example it only applies to \cos how can you unbold only part of that? the first command has the \boldsymbol apply to everything i.e. \cos^{#1} x; the 2nd is a hacked version showing the effect I was trying to achieve. I think you want (not sure why) \documentclass{article} \usepackage{amsmath} \usepackage{bm} \usepackage{xcolor} \DeclareMathOperator{\bcos}{\textcolor{blue}{\mathbf{cos}}} \newcommand{\bx}{\textcolor{blue}{\bm{x}}} \begin{document} $\bcos^2\bx$ \end{document} If you really want the \cosx macro, add \newcommand{\cosx}[1]{\bcos^{#1}\bx} This achieves the desired effect (I am a teacher & do extensive colour-coding in my notes to help students follow steps and see the most important info), but seems to me a variation on what I posted. Is there nothing like $\bm{\cos x \cdot \normalmath{\sin x} \cdot \cos x} = \cos^{\bm{2}}x \cdot \sin x where everything inside \normalmath{ } would be rendered in default font-style? & is there any reason to use \DeclareMathOperator{} over \newcommand for the blue / bold cos(x)? Would be interested to learn more if you can point me in the right direction. Thank you kindly for all your help! @RaxAdaam The main reason is that as an operator, the symbol gets the right spacing. thank you - that is enormously helpful to know & stands to simplify a lot of the local commands I've implemented.
common-pile/stackexchange_filtered
Vue Router beforeEnter vs beforeEach I am trying to redirect non-logged in user from all pages to /login. I tried beforeEach() but it doesn't fire when user enter site with direct url like /home, /event. Per-Route Guard beforeEnter() works perfectly since it fires once the user lands on that particular page. However, it requires me to add beforeEnter() on every routes. I am looking for a way to duplicate that beforeEnter() on almost every page on the router (even on dynamic pages) which non-logged in user will be redirected to /login. This one works when user enter with direct url /home. routes: [ { path: '/home', name: 'home', beforeEnter(to, from, next){ if ( to.name !== 'login' && !this.isloggedin ){ next({ path: 'login', replace: true }) } else { next() } } }, ... ] This one only works after user entered the site and route changed vm.$router.beforeEach((to, from, next)=>{ if ( to.name !== 'login' && !this.isloggedin ){ next({ path: 'login', replace: true }) } else { next(); } }) Thanks in advance. It looks like this beforeEach is being defined inside an initialized component, which means the first routing has already occured. Define it in the router module with your routes instead: const router = new VueRouter({ ... }) router.beforeEach((to, from, next)=>{ if ( to.name !== 'login' && !this.isloggedin ){ next({ path: 'login', replace: true }) } else { next(); } }) Hopefully you are using Vuex and can import the store for store.state.isloggedin. If not using Vuex yet, this illustrates why it is useful for global state. For a global and neat solution, you can control the router behavior in the App.vue using the router.beforeResolve(async (to, from, next) => {});. beforeResolve is better than beforeEach, as beforeResolve will not load the component of the accessed path URL unless you fire manually the next function. This is very helpful as you'll not render any interafce unless you check the authentication status of the user and then call next(). Example: router.beforeResolve(async (to, from, next) => { // Check if the user is authenticated. let isUserAuthenticated = await apiRequestCustomFunction(); // Redirect user to the login page if not authenticated. if (!isUserAuthenticated) { location.replace("https://example.com/signin"); return false; } // When next() is called, the router will load the component corresponding // to the URL path. next(); }); TIP: You can display a loader while you check if the user is authenticated or not and then take an action (redirect to sign in page or load the app normally). How would you display that loader you mention? what are the use cases for beforeEach though? I was always using beforeEach and only now noticed that there is beforeResolve hook, so trying to understand the both better now. This explanation is wrong. Not only is beforeResolve not better than beforeEach (they are both useful), it comes after it, not before. And both require next. Can you explain what's the wrong? My point is that beforeResolve allows you to prevent the load of the component before it is loaded based on some conditions, in case for e.g. a component must be accessed by authorized users.
common-pile/stackexchange_filtered
changing time format in pandas I have a dataframe with a column datetime that looks like this 2020-05-03T14:51:31.23625 (I assume %Y-%m-%dT%H:%M:%S) I would like to change it to dd/mm/yyyy hh:mm:ss format. I found this post and I tried something similar (code below) but it works ony for the first row of the dataframe. Could someone help me to find the mistake? Thanks! df['time']=pd.DataFrame({'time':pd.to_datetime(df['time'])}) df['new'] = df['time'].dt.strftime("%d/%m/%Y %H:%M:%S") [![enter image description here][2]][2] two things: (1) I don't see why you need the first line, try pd.to_datetime(df['time']).dt... directly. And (2), provide an example of your data (before) and the (after) result; that will help us understand exactly what you're going through. Try via split() and to_datetime() method: df['datetime']=pd.to_datetime(df['datetime'].str.split('.').str[0],errors='coerce') I think I'm confused by the use of 'time':['2020-05-03T14:51:31.23625','2020-05-03T14:51:31.23625'] in the first line. Is python taking this as format example? well that was a sample dataframe that I created...since you didn't provide your dataframe so I created a sample dataframe for demonstration purpose!! @CpF Updated my answer to make you more clear...kindly have a look :)
common-pile/stackexchange_filtered
How to read a file from a jar file? I have a file in a JAR file. It's 1.txt, for example. How can I access it? My source code is: Double result=0.0; File file = new File("1.txt")); //how get this file from a jar file BufferedReader input = new BufferedReader(new FileReader(file)); String line; while ((line = input.readLine()) != null) { if(me==Integer.parseInt(line.split(":")[0])){ result= parseDouble(line.split(":")[1]); } } input.close(); return result; see http://stackoverflow.com/questions/16842306 possible duplicate of How do I read a resource file from a Java jar file? possible duplicate of How to a read file from jar in Java? You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream(), like so: ... InputStream in = getClass().getResourceAsStream("/1.txt"); BufferedReader input = new BufferedReader(new InputStreamReader(in)); ... Assuming the calling class is inside the jar file of course. Otherwise he can just unzip it a read it using the classes in java.util.jar (or even more basic, as a plain old zip file using java.util.zip). If your jar is on the classpath: InputStream is = YourClass.class.getResourceAsStream("1.txt"); If it is not on the classpath, then you can access it via: URL url = new URL("jar:file:/absolute/location/of/yourJar.jar!/1.txt"); InputStream is = url.openStream(); Also make sure to include that exclamation point after the jar. It's not optional. Is there a way to test this? (using jUnit, testNG, Spock, ...). I tried it, but the files was never found during the Tests. Thanks for your answer. This part "url.openStream();" was what I needed. A Jar file is a zip file..... So to read a jar file, try ZipFile file = new ZipFile("whatever.jar"); if (file != null) { ZipEntries entries = file.entries(); //get entries from the zip file... if (entries != null) { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); //use the entry to see if it's the file '1.txt' //Read from the byte using file.getInputStream(entry) } } } Hope this helps. The other answers are correct, I just gave another alternative. Something similar to this answer is what you need. You need to pull the file out of the archive in that special way. BufferedReader input = new BufferedReader(new InputStreamReader( this.getClass().getClassLoader().getResourceAsStream("1.txt"))); BufferedReader doesn't except InputStream argument private String loadResourceFileIntoString(String path) { //path = "/resources/html/custom.css" for example BufferedReader buffer = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path))); return buffer.lines().collect(Collectors.joining(System.getProperty("line.separator"))); } This worked for me to copy an txt file from jar file to another txt file public static void copyTextMethod() throws Exception{ String inputPath = "path/to/.jar"; String outputPath = "Desktop/CopyText.txt"; File resStreamOut = new File(outputPath); int readBytes; JarFile file = new JarFile(inputPath); FileWriter fw = new FileWriter(resStreamOut); try{ Enumeration<JarEntry> entries = file.entries(); while (entries.hasMoreElements()){ JarEntry entry = entries.nextElement(); if (entry.getName().equals("readMe/tempReadme.txt")) { System.out.println(entry +" : Entry"); InputStream is = file.getInputStream(entry); BufferedWriter output = new BufferedWriter(fw); while ((readBytes = is.read()) != -1) { output.write((char) readBytes); } System.out.println(outputPath); output.close(); } } } catch(Exception er){ er.printStackTrace(); } } } I have run into this same issue several times before. I was hoping in JDK 7 that someone would write a classpath filesystem, but alas not yet. Spring has the Resource class which allows you to load classpath resources quite nicely. The answers have been very good, but I thought I could add to the discussion with showing an example that works with files and directories that are classpath resources. I wrote a little prototype to solve this very problem. The prototype does not handle every edge case, but it does handle looking for resources in directories that are in the jar files. I have used Stack Overflow for quite sometime. This is the first time that I remember answering a question so forgive me if I go to long (it is my nature). package com.foo; import java.io.File; import java.io.FileReader; import java.io.InputStreamReader; import java.io.Reader; import java.net.URI; import java.net.URL; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Prototype resource reader. * This prototype is devoid of error checking. * * * I have two prototype jar files that I have setup. * <pre> * <dependency> * <groupId>invoke</groupId> * <artifactId>invoke</artifactId> * <version>1.0-SNAPSHOT</version> * </dependency> * * <dependency> * <groupId>node</groupId> * <artifactId>node</artifactId> * <version>1.0-SNAPSHOT</version> * </dependency> * </pre> * The jar files each have a file under /org/node/ called resource.txt. * <br /> * This is just a prototype of what a handler would look like with classpath:// * I also have a resource.foo.txt in my local resources for this project. * <br /> */ public class ClasspathReader { public static void main(String[] args) throws Exception { /* This project includes two jar files that each have a resource located in /org/node/ called resource.txt. */ /* Name space is just a device I am using to see if a file in a dir starts with a name space. Think of namespace like a file extension but it is the start of the file not the end. */ String namespace = "resource"; //someResource is classpath. String someResource = args.length > 0 ? args[0] : //"classpath:///org/node/resource.txt"; It works with files "classpath:///org/node/"; //It also works with directories URI someResourceURI = URI.create(someResource); System.out.println("URI of resource = " + someResourceURI); someResource = someResourceURI.getPath(); System.out.println("PATH of resource =" + someResource); boolean isDir = !someResource.endsWith(".txt"); /** Classpath resource can never really start with a starting slash. * Logically they do, but in reality you have to strip it. * This is a known behavior of classpath resources. * It works with a slash unless the resource is in a jar file. * Bottom line, by stripping it, it always works. */ if (someResource.startsWith("/")) { someResource = someResource.substring(1); } /* Use the ClassLoader to lookup all resources that have this name. Look for all resources that match the location we are looking for. */ Enumeration resources = null; /* Check the context classloader first. Always use this if available. */ try { resources = Thread.currentThread().getContextClassLoader().getResources(someResource); } catch (Exception ex) { ex.printStackTrace(); } if (resources == null || !resources.hasMoreElements()) { resources = ClasspathReader.class.getClassLoader().getResources(someResource); } //Now iterate over the URLs of the resources from the classpath while (resources.hasMoreElements()) { URL resource = resources.nextElement(); /* if the resource is a file, it just means that we can use normal mechanism to scan the directory. */ if (resource.getProtocol().equals("file")) { //if it is a file then we can handle it the normal way. handleFile(resource, namespace); continue; } System.out.println("Resource " + resource); /* Split up the string that looks like this: jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/ into this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar and this /org/node/ */ String[] split = resource.toString().split(":"); String[] split2 = split[2].split("!"); String zipFileName = split2[0]; String sresource = split2[1]; System.out.printf("After split zip file name = %s," + " \nresource in zip %s \n", zipFileName, sresource); /* Open up the zip file. */ ZipFile zipFile = new ZipFile(zipFileName); /* Iterate through the entries. */ Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); /* If it is a directory, then skip it. */ if (entry.isDirectory()) { continue; } String entryName = entry.getName(); System.out.printf("zip entry name %s \n", entryName); /* If it does not start with our someResource String then it is not our resource so continue. */ if (!entryName.startsWith(someResource)) { continue; } /* the fileName part from the entry name. * where /foo/bar/foo/bee/bar.txt, bar.txt is the file */ String fileName = entryName.substring(entryName.lastIndexOf("/") + 1); System.out.printf("fileName %s \n", fileName); /* See if the file starts with our namespace and ends with our extension. */ if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) { /* If you found the file, print out the contents fo the file to System.out.*/ try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) { StringBuilder builder = new StringBuilder(); int ch = 0; while ((ch = reader.read()) != -1) { builder.append((char) ch); } System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder); } catch (Exception ex) { ex.printStackTrace(); } } //use the entry to see if it's the file '1.txt' //Read from the byte using file.getInputStream(entry) } } } /** * The file was on the file system not a zip file, * this is here for completeness for this example. * otherwise. * * @param resource * @param namespace * @throws Exception */ private static void handleFile(URL resource, String namespace) throws Exception { System.out.println("Handle this resource as a file " + resource); URI uri = resource.toURI(); File file = new File(uri.getPath()); if (file.isDirectory()) { for (File childFile : file.listFiles()) { if (childFile.isDirectory()) { continue; } String fileName = childFile.getName(); if (fileName.startsWith(namespace) && fileName.endsWith("txt")) { try (FileReader reader = new FileReader(childFile)) { StringBuilder builder = new StringBuilder(); int ch = 0; while ((ch = reader.read()) != -1) { builder.append((char) ch); } System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder); } catch (Exception ex) { ex.printStackTrace(); } } } } else { String fileName = file.getName(); if (fileName.startsWith(namespace) && fileName.endsWith("txt")) { try (FileReader reader = new FileReader(file)) { StringBuilder builder = new StringBuilder(); int ch = 0; while ((ch = reader.read()) != -1) { builder.append((char) ch); } System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder); } catch (Exception ex) { ex.printStackTrace(); } } } } } You can see a fuller example here with the sample output.
common-pile/stackexchange_filtered
Trying to create a randomly generated test I have already created a GUI for this assignment and now need to figure out how to execute each option. I need to create a test that can use Math.random() to generate equations that end in a whole number, the user can choose from easy, medium, or hard, with each option using a different number range. The user can also choose from addition, subtraction, multiplication, or division, and can choose multiple for one test. I am trying to write code that will store each value into an array of values for each equation (aVal1 being the first value for an addition equation and aVal2 being the second) But when I try to run the program and print out what aVal[0] has calculated into, it returns as 0. It seems like the program is not reading my equation like I want it to. Here is my code: import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class MathQuiz extends JFrame implements ActionListener { private JLabel questionNmbr = new JLabel ("Select # of questions:"); private JTextField questionTxt = new JTextField(8); private JLabel questionTypes = new JLabel ("Select wanted question types:"); private JCheckBox addition = new JCheckBox("+"); private JCheckBox subtraction = new JCheckBox("-"); private JCheckBox multiplication = new JCheckBox("x"); private JCheckBox division = new JCheckBox("÷"); private JLabel difficulty = new JLabel ("Choose difficulty:"); private JRadioButton easy = new JRadioButton("Easy"); private JRadioButton medium = new JRadioButton("Medium"); private JRadioButton hard = new JRadioButton("Hard"); private JButton submit = new JButton("Submit"); //whether or not each is chosen private int aNmbr = 0; private int sNmbr = 0; private int mNmbr = 0; private int dNmbr = 0; //how many questions each operation will have private int aQs = 0; private int sQs = 0; private int mQs = 0; private int dQs = 0; public MathQuiz() { //grouping radio btns ButtonGroup level = new ButtonGroup(); level.add(easy); level.add(medium); level.add(hard); easy.addActionListener(this); medium.addActionListener(this); hard.addActionListener(this); submit.addActionListener(this); setTitle("Quiz"); setSize(400, 400); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(questionNmbr); add(questionTxt); add(questionTypes); add(addition); add(subtraction); add(multiplication); add(division); add(difficulty); add(easy); add(medium); add(hard); add(submit); setVisible(true); } public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); Object obj2 = e.getSource(); //prints out the test if (obj == submit) { int QNmbr = Integer.parseInt(questionTxt.getText()); int[] aVal1 = new int[Integer.parseInt(questionTxt.getText())]; int[] aVal2 = new int[Integer.parseInt(questionTxt.getText())]; try { Integer.parseInt(questionTxt.getText()); } catch (NumberFormatException f) { JOptionPane.showMessageDialog(this, "Please enter a number"); } if (obj == addition) { aNmbr = 1; } if (obj == subtraction) { sNmbr = 1; } if (obj == multiplication) { mNmbr = 1; } if (obj == division) { dNmbr = 1; } //if easy is chosen if (obj == easy) { if(obj2 == addition) { for(int i = 0; i < 2; i++){ aVal1[i] = (int) (Math.random() * 11); System.out.print(aVal1[0]); } for(int j = 0; j < Integer.parseInt(questionTxt.getText()); j++){ aVal2[j] = (int) (Math.random() * 11); } } /*if(obj2 == subtraction) { while (i < (Integer.parseInt(questionTxt.getText())) / (aNmbr + sNmbr + mNmbr + dNmbr)) { aVal1[i] = (int) (Math.random() * 11); i++; } while (j < Integer.parseInt(questionTxt.getText())) { aVal2[j] = (int) (Math.random() * 11); j++; } } if(obj2 == multiplication) { while (i < (Integer.parseInt(questionTxt.getText())) / (aNmbr + sNmbr + mNmbr + dNmbr)) { aVal1[i] = (int) (Math.random() * 11); i++; } while (j < Integer.parseInt(questionTxt.getText())) { aVal2[j] = (int) (Math.random() * 11); j++; } } if(obj2 == division) { while (i < (Integer.parseInt(questionTxt.getText())) / (aNmbr + sNmbr + mNmbr + dNmbr)) { aVal1[i] = (int) (Math.random() * 11); i++; } while (j < Integer.parseInt(questionTxt.getText())) { aVal2[j] = (int) (Math.random() * 11); j++; } } */ } if (obj == medium) { } if (obj == hard) { } System.out.println(aVal1[0]); } } } Integer.parseInt(questionTxt.getText()); the result of this call isn't been assigned to anything, but since you're doing to before hand (and assigning it to QNmbr I question it's value It's not possible for if (obj == submit) { AND if (obj == addition) { (or any of the other evaluations to obj) to be true at the same time. Instead, you need to be looking at the actual component states That's what it was I needed to use .isSelected() instead of (obj == addition). My Math.random() is printing the right integers now, thank you! Let's just break this down for a second... Object obj = e.getSource(); Object obj2 = e.getSource(); //prints out the test if (obj == submit) { //... if (obj == addition) {...} if (obj == subtraction) {...} if (obj == multiplication) {...} if (obj == division) {...} //if easy is chosen if (obj == easy) { if (obj2 == addition) {...} } if (obj == medium) {...} if (obj == hard) {...} System.out.println(aVal1[0]); if obj is equal to submit, it's impossible for obj to be equal to addition or any other object. If obj is equal to addition (or any other object), there's no way to enter the if (obj == submit) { block any way, so the whole thing makes no sense. Also obj and obj2 are the same thing, so, more confusion. Also, this makes no sense... int QNmbr = Integer.parseInt(questionTxt.getText()); try { Integer.parseInt(questionTxt.getText()); } catch (NumberFormatException f) { JOptionPane.showMessageDialog(this, "Please enter a number"); } The exception will already have been trigged when doing int QNmbr = Integer.parseInt(questionTxt.getText());. So, if you want to trap this, the whole block of logic must be trapped in the try-catch block, not just the conversion ... I mean, what do you do after the catch - how do you know an exception has occurred? Instead, you need to look at the components themselves and make decisions based on there states, for example... public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); //prints out the test if (obj == submit) { int QNmbr = Integer.parseInt(questionTxt.getText()); int[] aVal1 = new int[Integer.parseInt(questionTxt.getText())]; int[] aVal2 = new int[Integer.parseInt(questionTxt.getText())]; aNmbr += addition.isSelected() ? 1 : 0; aNmbr += subtraction.isSelected() ? 1 : 0; aNmbr += multiplication.isSelected() ? 1 : 0; aNmbr += division.isSelected() ? 1 : 0; if (easy.isSelected()) { if (addition.isSelected()) { for (int i = 0; i < QNmbr; i++) { aVal1[i] = (int) (Math.random() * 11); aVal2[i] = (int) (Math.random() * 11); System.out.print(aVal1[0]); } } } else if (medium.isSelected()) { } else if (hard.isSelected()) { } System.out.println(aVal1[0]); } } I'd also recommend taking a look at: How to Use Formatted Text Fields and How to Use Spinners for controlling user input (ie numbers only) How to Use Combo Boxes as an alternative for when you want to limit the choice a user can make (to one option, obviously)
common-pile/stackexchange_filtered
How to current location in Android using google Maps? I'm trying to get the user's Location by showing that he is in which area with Particular location in google maps with the help of Android API while surfing in internet I came to know that getLocationManger() is used to view the Location but it shows only by Latitude,Longitude. If someone have any idea about this please help me friends. http://stackoverflow.com/questions/22931103/get-current-location-gmaps/22931253#22931253 ok Sir let me try this and know for you But sir i'd tried androidhive tutorials to get current location by it does not show the map and we can't view where and which location we are it is actually a button is clicked a toastmessage appears as lat,longtitude. yes now you get the lat and long values...just store them in two double values(gps.getlatiue(),gps.getlongitude) and place them in your google map. ok sir i'll go on with this can you please guide me if futher any doubts. ok.but it is very easy.I guess you will implement it by yourself.if any problem arises then inform me. Let us continue this discussion in chat. You can get the user's current location in terms of latitude and longitude and simply make an Implicit Intent to launch map with these values. To get current location: LocationManager locationManager = (LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { //Toast.makeText(getApplicationContext(),"Entered onLocationChanged",Toast.LENGTH_SHORT).show(); Log.d("LIFECYCLE","Entered onLocationChanged"); lat = location.getLatitude(); lon = location.getLongitude(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener); To show on google map: Intent intent = null,chooser = null; intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("geo:"+lat+","+lon)); chooser = Intent.createChooser(intent,"Launch Maps"); startActivity(chooser); /* creating chooser because: If this is not done, your app may crash when run on the emulator because the emulator may not have an activity installed which can handle the intent.*/ Make sure you have the needed permissions in your Manifest file. And if u find this useful, click the tick and also upvote ;) Try this one LocationManager lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); Location net_loc = null; lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); you can get the current location from net_loc. ok Sir let me try this and know for you actually i'm new to android if ok Sir let me try this and know for you actually i'm new to android if futher any doubts about this can you please guide me. sure @Manoj don't worry. sir i'd tried with the above code give by you but it shows me anything no issues can give some explained code to go ahead. should i set any thing for net_location If you want to get the location from network provider. you can also use net_loc =lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); `LocationManager lm; Location location; lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); }`
common-pile/stackexchange_filtered
Which type of argument passes a value to a procedure from the calling environment Which type of argument passes a value to a procedure from the calling environment 1.IN 2.IN OUT 3.OUT 4.OUT IN If more than one answer is possible than give the answer. check updated answer check my updated answer and accept it if it answers your query. I think you are asking for mysql stored procedure parameters modes not arguments as you mentioned wrongly in you question. Parameters are the variables in method definition; arguments is the data which you pass to the functions or methods and parameters mode specify the context of the parameter. Following are the mysql stored procedure parameters mode. IN – It is the default mode. When you define an IN parameter in a stored procedure, the calling program has to pass an argument to the stored procedure OUT – the value of an OUT parameter can be changed inside the stored procedure and its new value is passed back to the calling program. INOUT – an INOUT parameter is the combination of IN and OUT parameters. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the new value back to the calling program. Source: mysqltutorial EXAMPLE : To view only specific policy record from Policy table. delimiter ## create procedure view_policy(IN pid) begin select * from Policy where policy_id=pid; end## delimiter ; UPDATE According to mysql 5.7 reference manual there is nothing called as "OUT IN"
common-pile/stackexchange_filtered
Mysql Login issues I have very strange issues I have developed yetiforce crm in local system and migrated to globehost sever . the mysql version is 5.6 in local and hosting server but my login does not work in hosting server what could be the possible reason. Regards Do you expect a list of all 4913 reasons for your login not working? Just enter it in google and read every result, one of it might be it. Or you could narrow it down and add the error messages you get and describe in more detail what you did to migrate (e.g. if you moved both the application and the database to the hosting server or just the db and expect the app to work on a local client with a remote server; what values in your config you changed; ...) if you want more details let me know, I am not looking for harping suggestion As I said: to narrow your problem down, you would need to add the error messages you get and describe in more detail what you did to migrate (e.g. if you moved both the application and the database to the hosting server or just the db and expect the app to work on a local client with a remote server; what values in your config you changed; ...). Please also add if you can login at all (with the mysql client) with these credentials, and from where (from server, from your local pc, both). Also add if you want to login as the "root"-user (otherwise, the specific username does not matter). my local system has php5 and mysql 5.6, the server too has the same configuration. first I thought the problem is with the password so went and reset the password via command line inside mysql-DB, still same error occurred. what is challenging is I don't see any error in logfiles. if I restored the data base from the hosted database on some other local system it works and I am able to login into the application. I don't think you are doing it intentionally, but you answered exactly zero of my questions (if I assume that at least your app will show some kind of error message when trying to connect) - just to give you an impression how hard it can be to answer questions with few details. The more details you add, the more likely it is that the required information is in there. So to start again: Can you connect to the server db a) from a mysql client on the server b) from a local mysql client? Also (and probably the main issue): do you run your app on your local pc or did you move it to the server too? I got the solutions, it had to do with the permission of the files, the directory should be 755 and files had to be 644, some of the files had different permission which was causing the problems
common-pile/stackexchange_filtered
Mechanism of ring opening of amine combined with formylation What is the mechanism for this reaction? The tertiary amine is converted into an amide and the ring gains a double bond. I can't figure out how the C-O double bond would be formed. Oh, that's the easy part, but can you figure out what happens earlier? That's more interesting part. Find the nucleophile. Find the electrophile. Combine. Hint. The amide is a formyl amide. Where does the H attached to the carbonyl come from? Can chloroform react with sodium hydroxide? This reaction is very similar to Reimer-Tiemann reaction which also consists of the reagent $CHCl_{3}$ + $NaOH$. The mechanism of that reaction is believed to have dichlorocarbene intermediate too. A good point to remember is that the dichlorocarbene intermediate is often used to form cyclopropane or carbonyl groups. This is the mechanism for the reimer tiemann reaction. We can see the similarity in the this reaction and the one you have mentioned previously. Mm, that's better. Although the arrows still suggest an intramolecular proton transfer which I don't like... @orthocresol I am not sure if I should discuss this here, but I will be honest, I am a 12th grade student and hence couldn't understand the terms you used earlier. I don't understand what correction there should be here. Can you please elaborate in simple terms, or can we discuss it in chat? To deprotonate a X–H bond, the base (let's say B) needs to come from the opposite side of the hydrogen, i.e. X–H···B. That's essentially like an SN2 reaction, and the reason is the same: you need to get to the σ* orbital. This makes an intramolecular deprotonation essentially impossible, because that lone pair that is supposedly doing the deprotonation can't reach the σ* orbital. More likely that the negative charge picks up a proton from somewhere else, and the proton on the ring is lost some other way. Apart from that nitpick, your mechanism is fine, though; your edit fixed the other things I pointed out. But I'd still ask you to type out your text, instead of attaching a picture of written text. It's easier for everybody else to read, and can be searched for. I will grant that that the σ* orbital seems very difficult align. I just thought that the aromaticity would drive it to be essentially SN1 type acid base reaction. I guess the arrows seem to direct people into thinking this is SN2( in which case should I just get rid of them and add equilibrium arrows?) I will update this answer to text format once my major exams get over (because I don't mainly know how to do TeX and draw custom images.) That being said thanks for your inputs. Yes it’s the arrows that are the issue. Removing them is fine.
common-pile/stackexchange_filtered
Ignore case in prettyfaces pattern if you defined a url mapping as follows: @URLMapping(id = "myPage", pattern = "/myPage", viewId = "/faces/pages/myPage.xhtml") if you tried to enter the url as: http:localhost:8080/myPage this will work fine, but if you changed the case to: http:localhost:8080/mypage or http:localhost:8080/MYPAGE it won't work, it won't find the page, so is there's a way to ignore the case in the pattern, or such thing is not supported in PrettyFaces yet, if not supported, then please suggest a workaround. Something like this is currently not directly supported with PrettyFaces. But you could achieve something like this with a simple workaround: Change your mapping to a completely lowercase URL: @URLMapping(id = "myPage", pattern = "/mypage", viewId = "/faces/pages/myPage.xhtml") And then add a rewrite rule that performs the lowercase transformation: <rewrite match="(?i)/mypage" toCase="lowercase" redirect="chain" /> I think this should work fine. You could also try to build a more general pattern so that you don't have to repeat the rewrite rule for every mapping.
common-pile/stackexchange_filtered
Angular2 importing component methods into another component I have a home component which needs to call LoginComponent method isLoggedIn() to check if the user is logged in as follows in @CanActivate The home component should activate only if the user is logged in and authenticated HomeComponent.ts import {Component, OnInit} from 'angular2/core'; import {AboutComponent} from "../about/AboutComponent"; import {ROUTER_DIRECTIVES} from "angular2/router"; import {LoginComponent} from '../login/LoginComponent' @Component({ selector: 'home', /* template: ` <div> <div class="input"> <label for="Name">Name</label> <input type="text" id="name" #name> </div> <button (click)="onGetAll(name.value)">GET Request </button> <p>Response: {{response}}</p> </div> <a [routerLink]="['../About']">link to About component</a> `,*/ templateUrl: '../app/templates/dashboard.html', styleUrls: ['../app/assets/light-bootstrap-dashboard.css','../app/assets/demo.css','../app/assets/pe-icon-7-stroke. css','../app/assets/bootstrap.min.css'], directives : [ROUTER_DIRECTIVES] }) @CanActivate(() => LoginComponent.loggedIn()) //<-- This is not working export class HomeComponent implements OnInit { response: string; constructor() {} ngOnInit() {} onGetAll(name: string){ console.log("Button clicked.. more code goes here " + name); } } LoginCompoent.ts import {Component} from 'angular2/core'; import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {AuthHttp,AuthConfig, tokenNotExpired, AUTH_PROVIDERS} from 'angular2-jwt'; import {HomeComponent} from '../home/HomeComponent' import {AboutComponent} from '../about/AboutComponent' import {AuthService} from '../../services/AuthService' declare var Auth0Lock; @Component({ selector: 'protected', template: '<router-outlet></router-outlet>', directives: [ROUTER_DIRECTIVES], providers: [AUTH_PROVIDERS,AuthService] }) export class LoginComponent { constructor(private auth: AuthService) { this.auth.login(); } login() { this.auth.login(); } logout() { this.auth.logout(); } loggedIn() { return tokenNotExpired(); } } Add AuthService as provider in parent Component of Login and Home component. Usually App component. Remove it from Login. Now inject it in both home and login component and check whatever you need. Only one copy will be created for Auth Service since you provided it only once loggedIn method is not a static method hence it will not be called, Having said that, ideally, to check whether the user logged-in state you should call a service. The service should tell if the user is logged-in and also it should have a static method on the service. Yes, I have a service AuthService. it's imported into LoginComponent Can you make loggedin a static method and try? and what is tokennotexpired method which is returned is it some method coming from auth0? Thanks it worked. tokenexpired() is a boolean coming from Auth0.
common-pile/stackexchange_filtered
How do I get the closest date to today with an ISO date format? I have a function that's to read an array of objects and find: if customerAuthorizedTime is null if customerAuthorizedTime **is**null`, then find the one with the closest date to today, the current day. My attempt: My attempt to filter out all objects to find all the customerAuthorizedTime is null and then find the closest date const filteredData = data.filter((a: MemberAppointment) => a.customerAuthorizedTime === null) const filteredAppointment = // use .sort() or .find() to find closest date? I stop short because I'm unsure of how to find ISO dates that are closest to the current day. My second attempt: I wanted to try to perform a more direct approach with .find(): const currentDate = new Date().toISOString() const filteredAppointment = data.find((a: MemberAppointment) => a.customerAuthorizedTime === null && // date is closest to today's date) But the problem remains that I'm not sure how to find the closest date to today's date in ISO format. Is there a way to also satisfy this condition with moment.js? My dataset: const data = [ { 'appointmentId': 403749, 'masterAppointmentId': 403749, 'memberPartyRoleId': 1262903, 'description': 'Training (30 minutes)', 'startTime': '2019-06-09T22:00:00-04:00', 'mustCancelBy': '2019-06-09T22:00:00-04:00', 'activityTransactionId': 19726389, 'customerAuthorizedTime': '2019-06-09T00:33:02-04:00', }, { 'appointmentId': 403750, 'masterAppointmentId': 403750, 'memberPartyRoleId': 1262903, 'description': 'Training (30 minutes)', 'startTime': '2019-06-09T21:00:00-04:00', 'mustCancelBy': '2019-06-09T21:00:00-04:00', 'activityTransactionId': 19726390, 'customerAuthorizedTime': null, }, { 'appointmentId': 403748, 'masterAppointmentId': 403748, 'memberPartyRoleId': 1262903, 'description': 'Training (30 minutes)', 'startTime': '2019-06-09T20:00:00-04:00', 'mustCancelBy': '2019-06-09T20:00:00-04:00', 'activityTransactionId': 19726388, 'customerAuthorizedTime': null, }, { 'appointmentId': 403747, 'masterAppointmentId': 403747, 'memberPartyRoleId': 1262903, 'description': 'Training (30 minutes)', 'startTime': '2019-06-09T19:00:00-04:00', 'mustCancelBy': '2019-06-09T19:00:00-04:00', 'activityTransactionId': 19726387, 'customerAuthorizedTime': '2019-06-09T00:13:18-04:00', }] it would cost you O(N) but you can always run through the data array, use the moment().diff(date, 'days') function and keep the smallest absolute value. you could always just get the now date (new Date().toISOString()) and then find the absolute diff and keep it. I think that would be the simplest solution. Do you only care about the future? so you can also remove past dates from the search method and cut down the search just realized new Date().getTime(); returns the utc timestamp. much easier to compare to that. so same thing. just convert all dates into timestamp and find the smallest absolute or positive dff. still O(N) Traversing all appointments and calculating the closest datetime (in future) to today. If there is no items(array is empty) or all items have customerAuthorizedTime == null - func's result will be current datetime. function dateOfClosestApointmentToToday(items) { let now = (new Date()).getTime(); let found = null; items.filter(function(itm) { if (!!itm.customerAuthorizedTime) { let t = (new Date(itm.customerAuthorizedTime)).getTime(); if (!found || t > now && t < found) { found = t; } } }); return (new Date(!!found? found: now)).toISOString(); } // // get closest datetime // let closest = dateOfClosestApointmentToToday(data);
common-pile/stackexchange_filtered
Fitting a convex polygon into another polygon I am searching for an algorithm where I can check whether a convex polygon (shape 1) fits into another polygon (shape 2). My first research brought me to "Packing irregular shapes". This is in my opinion a little bit overkill. I only have one container and one object. Shape 1 is normally a convex polygon. Shape 2 can be convex, or concave. My application: I have 3D laser scanner to measure logs, which gives me shape 2. I also have different cutting profiles from which I consider the convex hull, giving shape 1. Now I want to check whether a cutting profile fits into my laser profile. You could just try brute force and see if it's fast and accurate enough. E.g. three nested loops for rotation, x translation and y translation. You want to know the path and rotations (if there exists one) that you have to describe with shape 1, so that its vertices will cut out shape 2 (without cutting away too much)? Have you asked this question on other Stack Exchange sites? Like https://math.stackexchange.com/ I think you are looking for a graph-theory algorithm of some sort.. and as a side-note they're pretty complex.. your other option is to apply triangulation and work with graphics-processing algorithm Can shapes be rotated? (With logs, orientation can indeed be important.) Coming to mind: (smallest) circle cc containing shape_1: compare areas for a measure of "compactness". Similarly, find (largest) circle ic fitting into shape_2 - encountering a circle larger than cc you're done (including orientation). If not, find the largest diameter length of shape_1 (and the (sum of) max. distance(s) to both sides of it) for one restricting measure, or the smallest rectangle to contain shape_1. A related, if not encouraging read: Cutting stock. Motivation. If you would ask whether a disk B of certain radius can fit into a polygon P then there is a standard method in computational geometry: Check whether the maximum inscribed circle has a radius not smaller; see this stackoverflow answer: The above algorithm to compute the maximum inscribed circle is quite "simple": Compute the so-called Generalized Voronoi Diagram and take the Voronoi node with largest clearance radius. (This is only motivation, just keep reading for a minute.) In your case your Shape 2 is not a ball; well, not a Euclidean ball, to be precise. But, actually, your Shape 2, as a convex polygon B, could define a convex distance function and compute the Voronoi diagram under this polyhedral distance function. But this is more theoretical background and maybe not something you want to implementation for production code. Those Voronoi diagrams are strongly related to computing offset curves, e.g., for tool-path planing in NC-machining. See this blog article for some discussions and the following figure: A ball B of radius r fits into the shape P if and only if there is an offset curve at distance r. (You actually get the set of all valid centers, namely those within the offset curve at radius r.) And those offset curves can be mathematically described as a Minkowski difference, as outlined in the blog article. Minkowski-difference. So now we can come back to your original problem. Does a convex polygon B fit within a polygon P? It does if and only if the Minkowski difference (P-B) is a non-empty set; any center out of (P-B) works as an example. A few more details based on the figure above: Let us denote by -B = {-v : v in B} the shape B after point reflection. (Choose the origin anywhere you like; I denoted it by the little cross with 'o' for origin.) Now think of -B as the shape of a pen (blue) and you move your pen (actually the cross) along the boundary of P. You get the gray area. (This is the Minkowski sum of the boundary of P with -B.) Remove the gray area from P and you get the Minkowski difference P-B. Choose any point within P-B and place a copy of B there; it will fit within P. I placed a few copies (orange) for you. Implementation. You can construct the gray area by considering each segment s of P individually and slide -B along it. More precisely, you place a copy of -B on each endpoint of s and find the tangents of the two copies of -B that form the boundary of the gray area: Take the per-segment solutions and compute the union over all segments of P. Then subtract this union from P. Take a look at Clipper for an open source library that can do that for you. What you get is not only the boolean answer whether B fits into P, but the set of all valid center for B in form of an set of polygons. Maybe this is interesting for your application, too. If you allow for rotations of B as well then the problem gets significantly more complex, I think. Maybe you can work with some discretization of rotational angles. Maybe you find some solution in the field of robot-motion planning resp. related to the piano mover's problem in computational geometry. Thank you very much for the visual explanation of the Minkowski sum/difference (I still do not know which is which, or even if they are different things), but your choice of shape and non-centered origin point for the polygon B helped a lot. I was trying to understand why my collision detection code for two rects was failing when I did not use their center as the origin. Now I finally understood why: I was not "reflecting". Your image would be a more than welcome addition to the (IMO) severely visually lacking wikipedia article on the Minkowski sum. Thanks! Perquisites : you should have all vertex coordinate of both (PolygonA,PolygonB) convex polygons. Step1: Put all the points of both convex polygon in one set . Step2: Find the convex polygon using grahamscan with new set of points. Step3: Now you have Big convex polygon which will contain both convex polygons . That means you have vertex of the newly create polygon let's call it PolygonC. Step4: Now check if polygonC and PolygonA are same with same set of vertex points if yes that means PolygonA contains PolygonB If above condition is not true repeat same check with PolygonB if Above condition is not true for any of Polygon then no polygon is fitting into another polygon . Graham Scan
common-pile/stackexchange_filtered
Unusal behavior with python list comprehension I have found this and this, but as far as I can understand, I believe that I am not duplicating those questions. While tinkering around to write the shortest code I can write to find the powerset of a set, I came across this behavior: lst = [1,2,3] powerset = set([()]) [powerset.update([subset + tuple([x]) for subset in powerset]) for x in lst] print 'powerset:', sorted(powerset, key = lambda x: len(x)) > powerset: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] What puzzles me further is that powerset is updated even when the list that results from the list comprehension is something quite different. lst = [1,2,3] powerset = set([()]) holy_ghost = [powerset.update([subset + tuple([x]) for subset in powerset]) for x in lst] print 'holy_ghost:', holy_ghost print 'powerset:',sorted(powerset, key = lambda x: len(x)) print type(powerset),', len:', len(powerset) > holy_ghost: [None, None, None] > powerset: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] > <type 'set'> , len: 8 Here is the nested-loop version of the list comprehension, which needs a "dummy" variable to avoid a "Set changed size during iteration" runtime error. lst2 = [1,2,3] powerset2 = set([()]) for x in lst2: dummy = set(powerset2) for subset in powerset2: dummy.update([subset + tuple([x])]) powerset2 = dummy print sorted(powerset2, key = lambda x: len(x)) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] Question: In python 2.7, is this an intended and acceptable use for list comprehension style code that is safe to use? I am not a programmer so I will be grateful if you pitch it at my level (beginner + / intermediate –) :) Thanks. You are using the list comp only for the side effects. Don't do that. The equivalent without is for x in lst: powerset.update([subset + tuple([x]) for subset in powerset]) (no temp vars needed). The powerset.update() call returns None which is why you see your [None, None, None] result. somevar.update (works for sets and dicts) works in-place: it updates somevar, but it does not return any value; which in Python means, it returns None. Thus, you're updating powerset inside a list comprehension, but as it returns None for each update, your final list comprehension contains just Nones. Depending on what final result you want, you can use this behaviour, or rewrite your list comprehension to contain whatever you want.
common-pile/stackexchange_filtered
Transferring nmap report to excel after running a scan using zenmap (nmap), I ended up with a lot of host reports. Now i have to translate those reports to excel file, so it's easier to read. In the excel file I need to see host ip and open ports. It's my first time doing a job like that, therefore, a step by step guide would be highly appreciated. Officially, you can get reports of nmap in XML format refer this link. However, to get it in excel format you might need third-party libraries. Refer this video for a guide on how to use a popular python library available for this purpose. You can download the library from here.
common-pile/stackexchange_filtered
Homogeneous quadratic parts of polynomials in Unbalanced Oil and Vinegar In the book Multivariate Public Key Cryptography, the author describes the polynomials in the cryptographic system Unbalanced Oil and Vinegar in the following way: Define $V=\{1,\dots,v\}$ and $O=\{v+1,\dots,n\}$. The central map is $\mathcal{F}=(f^{(1)},\dots, f^{(o)})$ where the polynomials $f^{(i)}$ are of the form: $$f^{(i)} = \sum_{j,k\in V} \alpha^{(i)}_{j,k}x_jx_k + \sum_{j\in V,k\in O}\beta^{(i)}_{j,k}x_jx_k + \sum_{j\in V\cup O}\gamma^{(i)}_j x_j + \delta^{(i)}\quad (i=1,\dots,o).$$ The author then makes the following claim: The homogeneous part of the polynomials $f^{(i)}$ can be rewritten as $$\hat{f}^{(i)}(\mathbf{x}) = \mathbf{x}^T\cdot F^{(i)}\cdot \mathbf{x}$$ with $$F^{(i)} = \begin{pmatrix}\star_{v\times v} & \star_{v\times o}\\ \star_{o\times v} & 0_{o\times o}\end{pmatrix}$$ where $\star$ means non-zero elements. My question is then: Is the last part of the matrix full of zeros because there is no term in the $f^{(i)}$ of the form $\sum_{j,k\in O}\text{[something]}$? Yes, that's right. In fact we may write $f^{(i)}(\mathbf{x})=\mathbf{x}^T F^{(i)}\mathbf{x}+(\mathbf{y}^{(i)})^T\mathbf{x}+\delta^{(i)}$ where $$ F^{(i)}=\begin{bmatrix} A^{(i)} & B^{(i)} \\ 0 & 0 \end{bmatrix} $$ and $A^{(i)}=[\alpha_{jk}^{(i)}]$, $B^{(i)}=[\beta_{jk}^{(i)}]$, $\mathbf{y}^{(i)}=[\gamma_j^{(i)}]$. It's possible to write the corner blocks $B$ and $0$ differently and get the same result, for example with $\frac{1}{2}B$ and $\frac{1}{2}B^T$ (resp.). If the corner blocks are $C$ and $D$ (resp.), the only constraint is that $C+D^T=B$ to get the same quadratic form. To understand why this is all true, set $|V|=2,|O|=2$ and write everything out explicitly.
common-pile/stackexchange_filtered
PERSON 1 Our population genetics model is completely stuck. The likelihood function for this migration pattern takes forever to compute, even with just fifty individuals. PERSON 2 What if we skip calculating the likelihood entirely? I've been reading about methods that generate samples from the posterior without ever touching that computational nightmare. PERSON 1 How can you get the posterior without the likelihood? Bayes' theorem literally requires it - posterior equals likelihood times prior over evidence. PERSON 2 Think about it differently. Instead of computing exact probabilities, we simulate datasets using different parameter values, then keep only the simulations that produce data similar to what we observed. PERSON 1 So you're saying we generate fake datasets, compare them to our real data, and if they match closely enough, we accept those parameters as plausible? PERSON 2 Exactly. If we simulate migration rates of 0.05 and get synthetic population data that looks nothing like our observations, we reject that rate. But if 0.12 produces data resembling ours, we keep it. PERSON 1 That makes sense for avoiding the likelihood calculation, but how do we define "similar enough"? Our real dataset has specific allele frequencies and geographic clustering patterns. PERSON 2 We need summary statistics - maybe average heterozygosity, pairwise genetic distances, or isolation-by-distance correlations. If the simulated and observed summaries are within some tolerance, we accept the parameters. PERSON 1 But doesn't that approximation introduce error? We're throwing away information by reducing the full dataset to just a few summary numbers. PERSON 2 Definitely, but consider the alternative. Exact inference might be mathematically pure, but if it takes weeks to run or crashes our computers, we get zero answers instead of approximate ones. PERSON 1 True. And we could validate our approximation by checking if different summary statistics give consistent parameter estimates, or by tightening the tolerance to see if results stabilize. PERSON 2 Plus, for complex evolutionary models with multiple populations, gene flow, and selection, approximate methods might be our only realistic option. The computational complexity grows exponentially with model size. PERSON 1 Right, so we trade some precision for actually being able to solve the problem. Better
sci-datasets/scilogues
why text alignment of formula field and labels changed in print? I use visual studio 2013 and crystal report 13-0-10. alignment of formula field and labels are correct in preview mode, but when I print crystal report file alignment of them change from center to lefttoright. How can I have them center alignment? Best Regards Have you found the solution ؟ Make sure that the settings of the report as the paper you would like to print on, e.g. A4 Size paper>> open the report >> select crystal report menu>> Design >> Page setup>> in the printer option area check the option (No Printer optimize for screen display) then from page option select (A4 (210x297mm)) and try. Or you can check you text object alignment left center or right and your paragraph radio buttons left-to-right or right-to-left.
common-pile/stackexchange_filtered
How to know drive letter from a batch file is launched? I would like to create a DOS/Windows batch file that copy files from a source to the letter drive from which this batch is launched. So, if i run the batch file from G:\ i would like it copy from the source to G:\MyDir. Elsewhere, if i run it from F:\ it must copy to F:\MyDir. How to write this in Windows Batch? I answer myself: i've to use %CD%.
common-pile/stackexchange_filtered
How to hide keyboard in android I wants to hide keyboard of device. I have try this code but its not working for me, Please Suggest me some other codes. InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } I have also try for manifest file but its also not working InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); EditText myEditText = (EditText) findViewById(R.id.myEditText); // Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } use this code using inputmanager and hideSoftInputFromWindow When this code in root view's onTouch, it should work. If you want to hide keyboard when activity opened, you can add android:windowSoftInputMode="stateHidden" to AndroidManifest.xml You can simply add LinearLayout(with visibility gone/invisible) or any layout,that has no child. And redirect the focus to it when activity starts. ;)
common-pile/stackexchange_filtered
Try-with-resources - Does it automatically close the connection? Java I've been working on a SQL utility and I am trying to set the parameters inside a prepared statement in multiple functions. To lessen the code, I have a function that returns a prepared statement where all the params are set. My question is: Does the connection reference in the configureStatement() get closed using the try with resources in the query()? If not how can the code be refactored to close the PreparedStatement and the Connection every time? public void query(String queryString, List<String> queryParams, Consumer<ResultSet> sqlConsumer) { try (PreparedStatement preparedStatement = this.configureStatement(queryString, queryParams)) { sqlConsumer.accept(preparedStatement.executeQuery()); } catch(SQLException exception) { exception.printStackTrace(); } } private PreparedStatement configureStatement(String query, List<String> queryParams) throws SQLException { PreparedStatement preparedStatement = this.getConnection().prepareStatement(query); for (int i = 0; i < queryParams.size(); ++i) preparedStatement.setString(i, queryParams.get(i)); return preparedStatement; } Is the question if the connection gets closed with try-with-resources on the PreparedStatement or do you want to ask a different question about restructuring your code which closes the connection after running a query? Please [edit] your post to make it clear what single question you want to ask. @Progman Yes, that's my basic question. I have edited it to make it a little more clear. Which database system and which JDBC client/version/library are you using? Mysql with HikariCP so com.mysql.jdbc.Driver This doesn't seem to be a question about try-with-resources, but about the close method of PreparedStatement. No, the try with resources does not close the Connection that is used inside the PreparedStatement. Only the PreparedStatement and its ResultSet are closed. When a Statement object is closed, its current ResultSet object, if one exists, is also closed. It is possible to reuse a connection to execute many PreparedStatements. Each of which is closed after usage. When the connection is no longer needed it can be closed as well. You could perhaps check it like this: public void query(String queryString, List<String> queryParams, Consumer<ResultSet> sqlConsumer) { Connection connection; try (PreparedStatement preparedStatement = this.configureStatement(queryString, queryParams)) { connection=preparedStatement.getConnection(); sqlConsumer.accept(preparedStatement.executeQuery()); } catch(SQLException exception) { exception.printStackTrace(); } if(connection!=null){ System.out.println("Is Connection closed:"+connection.isClosed()); } } private PreparedStatement configureStatement(String query, List<String> queryParams) throws SQLException { PreparedStatement preparedStatement = this.getConnection().prepareStatement(query); for (int i = 0; i < queryParams.size(); ++i) preparedStatement.setString(i, queryParams.get(i)); return preparedStatement; } A refactoring that closes connections by using the try-with-resources with multiple statements: public void query(String queryString, List<String> queryParams, Consumer<ResultSet> sqlConsumer) { try ( Connection connection=this.getConnection(); PreparedStatement preparedStatement = this.configureStatement(connection, queryString, queryParams);) { sqlConsumer.accept(preparedStatement.executeQuery()); } catch(SQLException exception) { exception.printStackTrace(); } if(connection!=null){ connection.close(); } } private PreparedStatement configureStatement( Connection connection,String query, List<String> queryParams) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(query); for (int i = 0; i < queryParams.size(); ++i) preparedStatement.setString(i, queryParams.get(i)); return preparedStatement; } That's what I figured. Any ideas on how I could refactor to make this happen? I want to have a query() and execute() function where both takes that param list. I don't want to copy-paste the for loop code in both functions. I'd rather have a method that does it automatically. But the connection needs to be closed after it completes. I guess I could close the connection manually in each function but that looks a little messy. Sure I will update the example, but perhaps you can also update the question to reflect that need. So it is easier for future readers to understand the question/answer. This is what I was looking for. Another way I just thought of was closing the connection manually in the consumer itself. Think I'll use this instead though. Thank you. You are welcome, closing the connection manually is also possible. But you can leverage the try-with-resources to ensure both the connection and the prepared statement are closed. Q: What makes you think returning an object from one of your own methods won't allow the object to be "closed" in a Java try with resources? From the Java documentation: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource. The key issue: the object returned from your method must implement java.lang.AutoCloseable. In your case, it does: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html Interface PreparedStatement All Superinterfaces: AutoCloseable, Statement, Wrapper I know that the PreparedStatement returned from that function will be closed. However, the connection that is referenced inside the configureStatement function needs to be closed as well. To my knowledge, closing the statement with a try-resource did not close the connection too. I guess they do though. Your code clearly shows both the connection and your method that creates the prepared statement are in the same try/resource block. Hence both are closed when the block exits. It sounded like your question was just asking about the "configureStatement()" method - hence my reply. No, of course closing a prepared statement doesn't necessarily close the connection. Why would you even think that???
common-pile/stackexchange_filtered
Generate a Uniform Spherical Distribution using rejection methods in Python I've been trying to generate a uniform spherical distribution in Python using uniform random sampling. For some reason my presumed spherical distribution looks more like an ovoid than like a sphere. I am using the fact that a sphere is defined: x^2 + y^2 + z^2 = R^2 and assuming R = 1 I get that the condition that the points should satisfy to be inside the sphere is: x^2 + y^2 + z^2 <= 1. For some reason this does not work. I have a perfect circular distribution from a top view (projection in the xy plane), but there is clearly a elliptical geometry in the planes xz and yz. import numpy as np import numpy.random as rand import matplotlib.pyplot as plt N = 10000 def sample_cube(number_of_trials): """ This function receives an integer and returns a uniform sample of points in a square. The return object is a list of lists, which consists of three entries, each is a list of the copordinates of a point in the space. """ cube = rand.uniform(low = -1, high = 1, size = (number_of_trials, 3)) x_cube = cube[:,0] y_cube = cube[:,1] z_cube = cube[:,2] return [x_cube, y_cube, z_cube] def sample_sphere(cube): """ This function takes a list on the form [x_cube, y_cube, z_cube] and then sample an spherical distribution of points. """ in_sphere = np.where(np.sqrt(cube[0]**2 + cube[1]**2 + cube[2]**2) <= 1) return in_sphere """ Main Code """ cube = sample_cube(N) sphere = sample_sphere(cube) print(sphere[0]) print(cube) print(cube[0][sphere[0]]) x_in_sphere = cube[0][sphere[0]] y_in_sphere = cube[1][sphere[0]] z_in_sphere = cube[2][sphere[0]] fig = plt.figure() ax = plt.axes(projection = "3d") ax.scatter(x_in_sphere, y_in_sphere, z_in_sphere, s = 1, color = "black") plt.show() plt.clf I was simply trying to get a uniform sphere. There should be something wrong with the approach, but I can not spot the mistake. The "squares in the background grid are not square, they're rectangular even though the ranges are the same for vertical and horizontal axes. It looks like a scaling problem in the plotting, not a problem with generating the data. Your third plot looks like it's properly scaled, the squares are square. Thank you. It was a silly mistake after all hahaha. Your min and max values seem to be almost the same for your xyz axes print(min(x_in_sphere), max(x_in_sphere)) print(min(y_in_sphere), max(y_in_sphere)) print(min(z_in_sphere), max(z_in_sphere)) -0.9799174154721233 0.9854060288509665 -0.9960657675761417 0.9877950419993617 -0.9945133729449587 0.9934754901005494 This means your axes of your plot dont have the same scale. To rescale them you can use the code from this Stackoverflow Question: matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y- smth like: import numpy as np import numpy.random as rand import matplotlib.pyplot as plt N = 10000 def sample_cube(number_of_trials): """ This function receives an integer and returns a uniform sample of points in a square. The return object is a list of lists, which consists of three entries, each is a list of the copordinates of a point in the space. """ cube = rand.uniform(low = -1, high = 1, size = (number_of_trials, 3)) x_cube = cube[:,0] y_cube = cube[:,1] z_cube = cube[:,2] return [x_cube, y_cube, z_cube] def sample_sphere(cube): """ This function takes a list on the form [x_cube, y_cube, z_cube] and then sample an spherical distribution of points. """ in_sphere = np.where(np.sqrt(cube[0]**2 + cube[1]**2 + cube[2]**2) <= 1) return in_sphere """ Main Code """ cube = sample_cube(N) sphere = sample_sphere(cube) print(sphere[0]) print(cube) print(cube[0][sphere[0]]) x_in_sphere = cube[0][sphere[0]] y_in_sphere = cube[1][sphere[0]] z_in_sphere = cube[2][sphere[0]] fig = plt.figure() ax = plt.axes(projection = "3d") ax.scatter(x_in_sphere, y_in_sphere, z_in_sphere, s = 1, color = "black") ax.set_aspect('equal') print(min(x_in_sphere), max(x_in_sphere)) print(min(y_in_sphere), max(y_in_sphere)) print(min(z_in_sphere), max(z_in_sphere)) x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() x_range = abs(x_limits[1] - x_limits[0]) x_middle = np.mean(x_limits) y_range = abs(y_limits[1] - y_limits[0]) y_middle = np.mean(y_limits) z_range = abs(z_limits[1] - z_limits[0]) z_middle = np.mean(z_limits) # The plot bounding box is a sphere in the sense of the infinity # norm, hence I call half the max range the plot radius. plot_radius = 0.5 * max([x_range, y_range, z_range]) ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius]) ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius]) ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) plt.show() Perfect, thank you, I just added ax.set_aspect('equal') and it worked perfectly fine. :)
common-pile/stackexchange_filtered
Fight for your life! Try figure out what the answer is by looking at the image below. The answer is nine letters long. The answer is Colosseum because V = Vertical H = Horizontal U = Up D = Down L = Left R = Right Now act out these moves clockwise with the only legal knight moves in chess on the board (starting from bottom left with the instruction "V"); You get "Colosseum" backwards: That was fast, well done!
common-pile/stackexchange_filtered
What is the right amount of money supply? As Bitcoin limits the money supply and the total amount of coins in circulation, whereas central banks have a degree of freedom to influence the money supply, I came to wonder what perspectives and constraints exist to determine the right amount of money supply. Could one definition be "The right amount of money supply incentivizes economic activity without causing excessive inflation"? Welcome to Economics:SE. Thank you for your question; please consider revising it to be more in line with our community expectations. Like many other stacks, we expect questions to provide evidence of prior research. That helps us to understand the question, and avoids our repeating work you've already done. Our help center, and other stacks provide additional resources to assist with revisions. In addition, this seems to be too broad. Per rules in our help center questions should not be too broad, please consider narrowing it down to one topic, or break it down into multiple economics.se questions (but also please keep in mind the reminder in the previous comment) The right amount is typically thought to be that which keeps average prices under control (many central banks use a target of about 2% inflation) or which keep exchange rates stable (consider Sweden or Hong Kong) or which lead to full employment (but not overfull). But the connection between money supply and these other indicators seems weaker than it was previously thought to be or at least more indirect, so instead it is more usual today to use interest rates for these purposes. Some might say Bitcoin has empirically failed to provide stability of price or exchange value.
common-pile/stackexchange_filtered
Interesting SQL Sorting Issue It's crunch time, deadline for my most recent contract is coming in two days and almost everything is complete and working fine (knock on wood) except for one issue. In one of my stored procedures, I'm needing to return a result set as follows. group_id name -------- -------- A101 Craig A102 Craig Z101 Craig Z102 Craig A101 Jim A102 Jim Z101 Jim Z102 Jim B101 Andy B102 Andy Z101 Andy Z102 Andy The names need to be sorted by the first character of the group id and also include the Z101/Z102 entries. By sorting strictly by the group id, I get a result set as follows: group_id name -------- -------- A101 Craig A102 Craig A101 Jim A102 Jim B101 Andy B102 Andy Z101 Andy Z102 Andy Z101 Craig Z102 Craig Z101 Jim Z102 Jim I really can't think of a solution that doesn't involve me making a cursor and bloating the stored procedure up more than it already is. I'm sure a great mind out there has an elegant solution and I'm eager to see what the community can come up with. Thanks a ton in advance. Edit: Let me expand :) I'm sorry, it's late and I'm coffee addled. The above result set is a special case for a special type of data entry. Being transparent, we're making an election based website and these are going to be candidates sorted by office, name, and then district. Most offices have multiple districts in them except for district positions like magistrate/coroner, which will have only one. The Z comes in as the "district" for absentee machine and absentee paper votes. The non-magistrate positions can be sorted by name first, as they are all grouped together. However, the existing system lists all magistrates in a huge clump of information, when they should be sorted by individual districts. This is where the issue lies. To protect my pride, I want to add that I had no control over the normalization of the database. It was given to me by the client. Here's the order clause of my stored procedure, if it helps: ORDER BY candidate.party, candidate.ballot_name, CASE WHEN candidate.district_type = 'MAG' THEN LEFT(votecount.precinct_id, 1) END, candidate.last_name, candidate.first_name, precinct.name Edit 2: Here's where I currently stand (1:43 A.M.) - I'm using a suggestion below to create a conditional inner join as follows: IF candidate.district_type = 'MAG' BEGIN ( SELECT candidate.id AS candidate_id, candidate.last_name, LEFT(votecount.precinct_id, 1) AS district, votecount.precinct_id FROM candidate INNER JOIN votecount ON votecount.candidate_id = candidate.id GROUP BY name ) mag_order INNER JOIN mag_order ON mag_order.candidate_id = candidate.id END and then I'll sort it by mag_order.district, candidate.precinct_id, candidate.last_name. For some reason I'm getting a SQL error when aliasing the ( SELECT ) as mag_order. Anyone see anything wrong with the code? I can't for the life of me. Sorry this is a bit tangential. Hi, I don't understand the requirement. If you want to sort by the first character of group_id, is the output not correct? Where did the combination of Z101 and Craig come from, or... where did it go in the second table there? Can you please post some sample complete input, the output you want, and the output you actually get, since I suspect you're only posting parts of the data and cutting it off. I'm going to take a crack at rewording your criteria, please post a comment (or update your question): You want to order by the first character of the group_id, which means A comes before B comes before C, etc. And then for A, you want to order by the name, which means Andy would come before Craig (except that Andy doesn't have any A's). However, once you've decided that you're onto Craig, you also want all his Z's. I think ORDER BY name, group_id is all you need, but it depends on if it matters more that the Craig/etc grouping as at the top. @OMG Ponies Actually if you look carefully it is more complicated than that @Lasse V. Karlsen Yeah, essentially I need it to order strictly by group_id's first character and include Z as an arbitrary group_id at the end of that result. It's convoluted =-/ What is the source data please? I suspect you don't actually have a "z" group, no? Sorry, I'll rephrase that. It would be easier to generate the Z grouping on the fly... Well, the data is coming from a table that tracks vote counts, so the Z grouping is actually in the database and needs to be tracked separately than the districts. I think the route I'll go after messing around with it is switching Z101/Z102 to [district_id]AB1/[district_id]AB2. This won't screw with anything and everything will display as expected then. It'd take far less time than what I've already put into trying to sort this junk. I'd still be interested in a solution for future reference though. This is a hell of a problem. SELECT g1.group_id, g1.name FROM groups g1 INNER JOIN ( SELECT MIN(group_id), name FROM groups GROUP BY name ) g2 on g1.name = g2.name ORDER BY g2.group_id, g1.name, g1.group_id This solution is very close. The only issue with it is that what I'm talking about above is a special case in a large set of returned data. About 20% of returned data needs to be handled in the way I'm asking, where the other 80% is a simple [order by name, group_id]. I'm going to play around with your solution a bit and try to make it fit. Thanks a ton. @rofly, the sorted set you have has Craig, Jim, Andy. I'm not sure how this jives with 80% by "name, group_id". Perhaps a larger dataset sample and expected result is needed (along with test data ddl/inserts). SELECT groupId, name FROM table ORDER BY getFirstGroupId(name), name, groupId Then your getFirstGroupId() function would return the first groupId for that name SELECT MIN(groupId) FROM groupTable WHERE name = @name ORDER BY name DESC, SUBSTR(group_id,1), group_id
common-pile/stackexchange_filtered
How to make a legend is horizontally Please tell us how to make a horizontal legend. And here are the results: But I want this: I have the following code: <script type="text/javascript"> //$(function () { function getJson() { var result = []; $.ajax({ url: "WebService1.asmx/GetJson3", success: function (data) { $.each(data, function (key, value) { item = { "company": value.BusinessUnitName, "revenue": value.QTY_Case, "expenses": value.QTY_Case_Target, "cos": value.QTY_Case_LY } result.push(item); }); }, async: false, }); $("#columnChart").igDataChart({ width: "280px", height: "200px", dataSource: result, legend: { element: "columnLegend" }, title: "title", subtitle: "subtitle", axes: [{ name: "xAxis", type: "categoryX", //label: "company", labelTopMargin: 5, gap: 0.4, overlap: 0.0, }, { name: "yAxis", type: "numericY", maximumValue: 250000, interval: 50, minimumValue: 0, formatLabel: function (val) { var bVal = (val / 10000), rounded = Math.round(bVal * 100) / 100; return rounded + "M"; } }], series: [{ name: "series1", title: "revenue", type: "column", isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "revenue" }, { name: "series2", title: "expenses", type: "column", isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "expenses" }, { name: "series3", title: "cos", type: "column", isTransitionInEnabled: true, xAxis: "xAxis", yAxis: "yAxis", valueMemberPath: "cos" }, ] }); } $(function () { getJson(); }); </script> I hope to be guided. Thank You, Best regard I'm not sure what the HTML output looks like, but you might be able to set the three elements (revenue, expenses, cos) to each have a display of inline-block in CSS. Since you have the CSS tag on here. https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=igDataChart+horizontal+legend the first result is someone else asking the same question, to which they got an answer Thanks to Sam and Andrew Bone It was very good advice. I just added some code As they guide you. It's success. Best regard The question is answered in the link provided by Andrew Bone. I will post the answer here as well so it's visible. Make the table rows belonging to the legend to be displayed as inline-block. #columnLegend tr { display: inline-block; } Another suggestion I have based on the code that you've provided is to not make the $.ajax call sync. Just initialize the igDataChart inside the success callback. $.ajax({ url: "WebService1.asmx/GetJson3", success: function (data) { $.each(data, function (key, value) { item = { "company": value.BusinessUnitName, "revenue": value.QTY_Case, "expenses": value.QTY_Case_Target, "cos": value.QTY_Case_LY } result.push(item); initChart(); }); } }); hello Konstantin Dinev, Thanks for advice. I added code: #columnLegend tr {display: inline-block;}. Where
common-pile/stackexchange_filtered
Superfluid + Super conductivity in a bose condensate so my question is this can we theoretically and empirically find a BOSE condensate, with SUPERFLUID properties but which is also a SUPERCONDUCTING device ? A Bose-Einstein condenstate (BEC) is a purely non-interacting effect, and as such it is not technically a superfluid. However, since the superfluid critical velocity $v_c$ goes as the interaction strength $g$, a BEC, having $g = 0$, would have $v_c = 0$. So even if you do want to call it a superfluid, it's kind of a boring superfluid. A superconductor is essentially the same as a superfluid but for a charged fluid, so that is composed of particles (elementary or not) that have an electrical charge.
common-pile/stackexchange_filtered
Download excel file using memory stream in C# I have to return file by creating excel workbook from memory stream. I have used Interop, closed.xml, spire.xls but not founding a way to achieve the same. var stream=clsUploadHelper.GetAttachmentFileStream(string.Empty, Filename); Workbook book=new Workbook(); book.worksheet.Add(stream); stream.Position = 0; string xmlString = "attachment;filename=" + Filename; return File(stream, xmlString, Filename); I am new in that, Please help if possible. Thanks in advance. @Jazb Actually already byte written to the file that are coming for the download and using that byte/stream we just need to return an excel file @all anyone please help Tell us what framework you're using. You didn't specify, but it looks like you're building a Web UI. may be late to the party, but I ran into this issue today and was able to write this POC in order to return an XLSX file in a .NET Core Web API using Spire.XLS [HttpPost] public async Task<FileResult> Post() { try { var workbook = new Workbook(); var sheet = workbook.Worksheets[0]; sheet.InsertRow(1); sheet.Rows[0].Columns[0].Value = "testing..."; await using var stream = new MemoryStream(); workbook.SaveToStream(stream, Spire.Xls.FileFormat.Version2016); const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Response.ContentType = contentType; HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); var fileContentResult = new FileContentResult(stream.ToArray(), contentType) { FileDownloadName = $"test.xlsx" }; return fileContentResult; } catch (Exception e) { Console.WriteLine(e); return null; } }
common-pile/stackexchange_filtered
Replicating SAS DO loop in Oracle PL/SQL I'm trying to replicate a DO loop from SAS into Oracle PL/SQL. Basically, this DO loop iterates over the table and creates multiple rows for a single employee. I'm not extremely familiar with loops in PL/SQL so any help is appreciated. I can't think of any way to recreate this except for creating numerous tables then combining them. I'll explain more on my thoughts at the end; for now, please see an example of the data and what the SAS DO loop is doing. HIST_EMPLOYEE Table: +----------+----------+--------+ | EMPLOYEE | START_YR | END_YR | +----------+----------+--------+ | JOHN | 2013 | 2014 | | WILL | 2012 | 2016 | | MARK | 2012 | 2012 | +----------+----------+--------+ DO loop in SAS: DATA HIST_EMPLOYEE_NEW; SET HIST_EMPLOYEE; DO YR = START_YR TO END_YR; OUTPUT; END; RUN; Output: +----------+----------+--------+------+ | EMPLOYEE | START_YR | END_YR | YR | +----------+----------+--------+------+ | JOHN | 2013 | 2014 | 2013 | | JOHN | 2013 | 2014 | 2014 | | WILL | 2012 | 2016 | 2012 | | WILL | 2012 | 2016 | 2013 | | WILL | 2012 | 2016 | 2014 | | WILL | 2012 | 2016 | 2015 | | WILL | 2012 | 2016 | 2016 | | MARK | 2012 | 2012 | 2012 | +----------+----------+--------+------+ The way I'd solve this (which is not efficient in any way) is to create tables filtered on END_YR < START_YR + i where i is from 0 to 10, then create the YR column then combine all tables. I can discuss this further, but I already feel like this is the bad way of doing things. Here's one way. The "with" clause is called a Common Table Expression (CTE) and just sets up the test data with a unique id for each entry. The query uses a CONNECT BY which can be thought of as a looping mechanism for each row returned. It comes along with a variable called "level" which is incremented once for each iteration (it starts at 1). To define how many times to "loop" for each row is the expression (end_yr-start_yr+1). For JOHN we'll need to loop 2 times as we need 2 rows, WILL 5 rows, etc. The "PRIOR ID" clauses help to handle the multiple rows for each original row. with hist_employee(id, employee, start_yr, end_yr) as ( select 1, 'JOHN', 2013, 2014 from dual union all select 2, 'WILL', 2012, 2016 from dual union all select 3, 'MARK', 2012, 2012 from dual ) select employee, start_yr, end_yr, (start_yr + (level-1)) as YR from hist_employee connect by level <= end_yr-start_yr+1 and prior id = id and prior sys_guid() is not null order by id; EMPLOYEE START_YR END_YR YR -------- ---------- ---------- ---------- JOHN 2013 2014 2013 JOHN 2013 2014 2014 WILL 2012 2016 2012 WILL 2012 2016 2013 WILL 2012 2016 2014 WILL 2012 2016 2015 WILL 2012 2016 2016 MARK 2012 2012 2012 8 rows selected. Great idea! Instead of making my own unique id for each entry (since the table was longer than my example), I used rowid which made it so that the entire 'with' clause was unnecessary Yeah, you wouldn't use the WITH, that was just to set up the example. Glad this helped you. Try to use a real primary key from your data though if you can. Just make a table with one value of YR ranging from some minimum to maximum and join on that. So something like: with years as ( select 2012 + rownum - 1 as YR from dual connect by rownum < (2016 - 2012) ) select a.*,b.YR from HIST_EMPLOYEE a inner join years b on a.start_yr <= b.yr and b.yr <= a.end_yr ; Just change the lower (2012) and upper (2016) limits to change the number of years you want to generate. See this question: How to populate calendar table in Oracle?
common-pile/stackexchange_filtered